source: tspsg/src/mainwindow.cpp @ 278bc7818f

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

+ Added Symmetric mode: in this mode the cost of travel from city 1 to city 2 and vice versa is the same.
+ Added the ability to reset all settings to their defaults: hold Shift while clicking Save button in Settings Dialog.

  • Better SIP show/hide handling under wince: no need to resize the Main Window, when it isn't active.
  • Property mode set to 100644
File size: 33.0 KB
Line 
1/*
2 *  TSPSG: TSP Solver and Generator
3 *  Copyright (C) 2007-2010 Lёppa <contacts[at]oleksii[dot]name>
4 *
5 *  $Id$
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
41        initDocStyleSheet();
42
43#ifndef QT_NO_PRINTER
44        printer = new QPrinter(QPrinter::HighResolution);
45#endif // QT_NO_PRINTER
46
47#ifdef Q_OS_WINCE
48        currentGeometry = QApplication::desktop()->availableGeometry(0);
49        // We need to react to SIP show/hide and resize the window appropriately
50        connect(QApplication::desktop(), SIGNAL(workAreaResized(int)), SLOT(desktopResized(int)));
51#endif // Q_OS_WINCE
52        connect(actionFileNew,SIGNAL(triggered()),this,SLOT(actionFileNewTriggered()));
53        connect(actionFileOpen,SIGNAL(triggered()),this,SLOT(actionFileOpenTriggered()));
54        connect(actionFileSave,SIGNAL(triggered()),this,SLOT(actionFileSaveTriggered()));
55        connect(actionFileSaveAsTask,SIGNAL(triggered()),this,SLOT(actionFileSaveAsTaskTriggered()));
56        connect(actionFileSaveAsSolution,SIGNAL(triggered()),this,SLOT(actionFileSaveAsSolutionTriggered()));
57#ifndef QT_NO_PRINTER
58        connect(actionFilePrintPreview,SIGNAL(triggered()),this,SLOT(actionFilePrintPreviewTriggered()));
59        connect(actionFilePrint,SIGNAL(triggered()),this,SLOT(actionFilePrintTriggered()));
60#endif // QT_NO_PRINTER
61        connect(actionSettingsPreferences,SIGNAL(triggered()),this,SLOT(actionSettingsPreferencesTriggered()));
62        connect(actionSettingsLanguageAutodetect,SIGNAL(triggered(bool)),this,SLOT(actionSettingsLanguageAutodetectTriggered(bool)));
63        connect(groupSettingsLanguageList,SIGNAL(triggered(QAction *)),this,SLOT(groupSettingsLanguageListTriggered(QAction *)));
64        connect(actionHelpAboutQt,SIGNAL(triggered()),qApp,SLOT(aboutQt()));
65        connect(actionHelpAbout,SIGNAL(triggered()),this,SLOT(actionHelpAboutTriggered()));
66
67        connect(buttonSolve,SIGNAL(clicked()),this,SLOT(buttonSolveClicked()));
68        connect(buttonRandom,SIGNAL(clicked()),this,SLOT(buttonRandomClicked()));
69        connect(buttonBackToTask,SIGNAL(clicked()),this,SLOT(buttonBackToTaskClicked()));
70        connect(spinCities,SIGNAL(valueChanged(int)),this,SLOT(spinCitiesValueChanged(int)));
71
72#if !defined(Q_OS_WINCE) && !defined(Q_OS_SYMBIAN)
73        // Centering main window
74QRect rect = geometry();
75        rect.moveCenter(QApplication::desktop()->availableGeometry(this).center());
76        setGeometry(rect);
77        if (settings->value("SavePos", DEF_SAVEPOS).toBool()) {
78                // Loading of saved window state
79                settings->beginGroup("MainWindow");
80                restoreGeometry(settings->value("Geometry").toByteArray());
81                restoreState(settings->value("State").toByteArray());
82                settings->endGroup();
83        }
84#else
85        setWindowState(Qt::WindowMaximized);
86#endif // Q_OS_WINCE
87
88        tspmodel = new CTSPModel(this);
89        taskView->setModel(tspmodel);
90        connect(tspmodel,SIGNAL(numCitiesChanged(int)),this,SLOT(numCitiesChanged(int)));
91        connect(tspmodel,SIGNAL(dataChanged(const QModelIndex &, const QModelIndex &)),this,SLOT(dataChanged(const QModelIndex &, const QModelIndex &)));
92        connect(tspmodel,SIGNAL(layoutChanged()),this,SLOT(dataChanged()));
93        if ((QCoreApplication::arguments().count() > 1) && (tspmodel->loadTask(QCoreApplication::arguments().at(1))))
94                setFileName(QCoreApplication::arguments().at(1));
95        else {
96                setFileName();
97                spinCities->setValue(settings->value("NumCities",DEF_NUM_CITIES).toInt());
98                spinCitiesValueChanged(spinCities->value());
99        }
100        setWindowModified(false);
101}
102
103MainWindow::~MainWindow()
104{
105#ifndef QT_NO_PRINTER
106        delete printer;
107#endif
108}
109
110/* Privates **********************************************************/
111
112void MainWindow::actionFileNewTriggered()
113{
114        if (!maybeSave())
115                return;
116        QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
117        tspmodel->clear();
118        setFileName();
119        setWindowModified(false);
120        tabWidget->setCurrentIndex(0);
121        solutionText->clear();
122        toggleSolutionActions(false);
123        QApplication::restoreOverrideCursor();
124}
125
126void MainWindow::actionFileOpenTriggered()
127{
128        if (!maybeSave())
129                return;
130
131QStringList filters(tr("All Supported Formats") + " (*.tspt *.zkt)");
132        filters.append(tr("%1 Task Files").arg("TSPSG") + " (*.tspt)");
133        filters.append(tr("%1 Task Files").arg("ZKomModRd") + " (*.zkt)");
134        filters.append(tr("All Files") + " (*)");
135
136QFileDialog::Options opts = settings->value("UseNativeDialogs", DEF_USE_NATIVE_DIALOGS).toBool() ? QFileDialog::Options() : QFileDialog::DontUseNativeDialog;
137QString file = QFileDialog::getOpenFileName(this, tr("Task Load"), QString(), filters.join(";;"), NULL, opts);
138        if (file.isEmpty() || !QFileInfo(file).isFile())
139                return;
140        if (!tspmodel->loadTask(file))
141                return;
142        setFileName(file);
143        tabWidget->setCurrentIndex(0);
144        setWindowModified(false);
145        solutionText->clear();
146        toggleSolutionActions(false);
147}
148
149void MainWindow::actionFileSaveTriggered()
150{
151        if ((fileName == tr("Untitled") + ".tspt") || (!fileName.endsWith(".tspt",Qt::CaseInsensitive)))
152                saveTask();
153        else
154                if (tspmodel->saveTask(fileName))
155                        setWindowModified(false);
156}
157
158void MainWindow::actionFileSaveAsTaskTriggered()
159{
160        saveTask();
161}
162
163void MainWindow::actionFileSaveAsSolutionTriggered()
164{
165static QString selectedFile;
166        if (selectedFile.isEmpty()) {
167                if (fileName == tr("Untitled") + ".tspt") {
168#ifndef QT_NO_PRINTER
169                        selectedFile = "solution.pdf";
170#else
171                        selectedFile = "solution.html";
172#endif // QT_NO_PRINTER
173                } else {
174#ifndef QT_NO_PRINTER
175                        selectedFile = QFileInfo(fileName).canonicalPath() + "/" + QFileInfo(fileName).completeBaseName() + ".pdf";
176#else
177                        selectedFile = QFileInfo(fileName).canonicalPath() + "/" + QFileInfo(fileName).completeBaseName() + ".html";
178#endif // QT_NO_PRINTER
179                }
180        }
181
182QStringList filters;
183#ifndef QT_NO_PRINTER
184        filters.append(tr("PDF Files") + " (*.pdf)");
185#endif
186        filters.append(tr("HTML Files") + " (*.html *.htm)");
187#if QT_VERSION >= 0x040500
188        filters.append(tr("OpenDocument Files") + " (*.odt)");
189#endif // QT_VERSION >= 0x040500
190        filters.append(tr("All Files") + " (*)");
191
192QFileDialog::Options opts = settings->value("UseNativeDialogs", DEF_USE_NATIVE_DIALOGS).toBool() ? QFileDialog::Options() : QFileDialog::DontUseNativeDialog;
193QString file = QFileDialog::getSaveFileName(this, QString(), selectedFile, filters.join(";;"), NULL, opts);
194        if (file.isEmpty())
195                return;
196        selectedFile = file;
197        QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
198#ifndef QT_NO_PRINTER
199        if (selectedFile.endsWith(".pdf",Qt::CaseInsensitive)) {
200QPrinter printer(QPrinter::HighResolution);
201                printer.setOutputFormat(QPrinter::PdfFormat);
202                printer.setOutputFileName(selectedFile);
203                solutionText->document()->print(&printer);
204                QApplication::restoreOverrideCursor();
205                return;
206        }
207#endif
208#if QT_VERSION >= 0x040500
209QTextDocumentWriter dw(selectedFile);
210        if (!(selectedFile.endsWith(".htm",Qt::CaseInsensitive) || selectedFile.endsWith(".html",Qt::CaseInsensitive) || selectedFile.endsWith(".odt",Qt::CaseInsensitive) || selectedFile.endsWith(".txt",Qt::CaseInsensitive)))
211                dw.setFormat("plaintext");
212        dw.write(solutionText->document());
213#else
214        // Qt < 4.5 has no QTextDocumentWriter class
215QFile file(selectedFile);
216        if (!file.open(QFile::WriteOnly)) {
217                QApplication::restoreOverrideCursor();
218                return;
219        }
220QTextStream ts(&file);
221        ts.setCodec(QTextCodec::codecForName("UTF-8"));
222        ts << solutionText->document()->toHtml("UTF-8");
223        file.close();
224#endif // QT_VERSION >= 0x040500
225        QApplication::restoreOverrideCursor();
226}
227
228#ifndef QT_NO_PRINTER
229void MainWindow::actionFilePrintPreviewTriggered()
230{
231QPrintPreviewDialog ppd(printer, this);
232        connect(&ppd,SIGNAL(paintRequested(QPrinter *)),SLOT(printPreview(QPrinter *)));
233        ppd.exec();
234}
235
236void MainWindow::actionFilePrintTriggered()
237{
238QPrintDialog pd(printer,this);
239#if QT_VERSION >= 0x040500
240        // No such methods in Qt < 4.5
241        pd.setOption(QAbstractPrintDialog::PrintSelection,false);
242        pd.setOption(QAbstractPrintDialog::PrintPageRange,false);
243#endif
244        if (pd.exec() != QDialog::Accepted)
245                return;
246        QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
247        solutionText->document()->print(printer);
248        QApplication::restoreOverrideCursor();
249}
250#endif // QT_NO_PRINTER
251
252void MainWindow::actionSettingsPreferencesTriggered()
253{
254SettingsDialog sd(this);
255        if (sd.exec() != QDialog::Accepted)
256                return;
257        if (sd.colorChanged() || sd.fontChanged()) {
258                initDocStyleSheet();
259                if (!output.isEmpty() && sd.colorChanged() && (QMessageBox(QMessageBox::Question,tr("Settings Changed"),tr("You have changed color settings.\nDo you wish to apply them to current solution text?"),QMessageBox::Yes | QMessageBox::No,this).exec() == QMessageBox::Yes)) {
260                        QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
261                        solutionText->clear();
262                        solutionText->setHtml(output.join(""));
263                        QApplication::restoreOverrideCursor();
264                }
265        }
266        if (sd.translucencyChanged() != 0) {
267                toggleTranclucency(sd.translucencyChanged() == 1);
268        }
269}
270
271void MainWindow::actionSettingsLanguageAutodetectTriggered(bool checked)
272{
273        if (checked) {
274                settings->remove("Language");
275                QMessageBox::information(this, tr("Language change"), tr("Language will be autodetected on next application start."));
276        } else
277                settings->setValue("Language", groupSettingsLanguageList->checkedAction()->data().toString());
278}
279
280void MainWindow::groupSettingsLanguageListTriggered(QAction *action)
281{
282        if (actionSettingsLanguageAutodetect->isChecked()) {
283                // We have language autodetection. It needs to be disabled to change language.
284                if (QMessageBox(QMessageBox::Question,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,this).exec() == QMessageBox::Yes) {
285                        actionSettingsLanguageAutodetect->trigger();
286                } else
287                        return;
288        }
289bool untitled = (fileName == tr("Untitled") + ".tspt");
290        if (loadLanguage(action->data().toString())) {
291                QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
292                settings->setValue("Language",action->data().toString());
293                retranslateUi();
294                if (untitled)
295                        setFileName();
296                QApplication::restoreOverrideCursor();
297        }
298}
299
300void MainWindow::actionHelpAboutTriggered()
301{
302//! \todo TODO: Normal about window :-)
303QString title;
304#if defined(Q_OS_WINCE) || defined(Q_OS_SYMBIAN)
305        title += QString::fromUtf8("<b>TSPSG<br>TSP Solver and Generator</b><br>");
306#else
307        title += QString::fromUtf8("<b>TSPSG: TSP Solver and Generator</b><br>");
308#endif // Q_OS_WINCE
309        title += QString::fromUtf8("Version: <b>"BUILD_VERSION"</b><br>");
310        title += QString::fromUtf8("<b>&copy; 2007-%1 Lёppa</b><br>").arg(QDate::currentDate().toString("yyyy"));
311        title += QString::fromUtf8("<b><a href=\"http://tspsg.sourceforge.net/\">http://tspsg.sf.net/</a></b><br>");
312QString about;
313        about += QString::fromUtf8("Target OS: <b>%1</b><br>").arg(OS);
314#ifndef STATIC_BUILD
315        about += "Qt library (shared):<br>";
316        about += QString::fromUtf8("&nbsp;&nbsp;&nbsp;&nbsp;Build time: <b>%1</b><br>").arg(QT_VERSION_STR);
317        about += QString::fromUtf8("&nbsp;&nbsp;&nbsp;&nbsp;Runtime: <b>%1</b><br>").arg(qVersion());
318#else
319        about += QString::fromUtf8("Qt library: <b>%1</b> (static)<br>").arg(QT_VERSION_STR);
320#endif // STATIC_BUILD
321        about += QString::fromUtf8("Built on <b>%1</b> at <b>%2</b><br>").arg(__DATE__).arg(__TIME__);
322        about += "<br>";
323        about += QString::fromUtf8("Id: <b>"VERSIONID"</b><br>");
324        about += QString::fromUtf8("Algorithm: <b>%1</b><br>").arg(CTSPSolver::getVersionId());
325        about += "<br>";
326        about += "TSPSG is free software: you can redistribute it and/or modify it<br>"
327                "under the terms of the GNU General Public License as published<br>"
328                "by the Free Software Foundation, either version 3 of the License,<br>"
329                "or (at your option) any later version.<br>"
330                "<br>"
331                "TSPSG is distributed in the hope that it will be useful, but<br>"
332                "WITHOUT ANY WARRANTY; without even the implied warranty of<br>"
333                "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the<br>"
334                "GNU General Public License for more details.<br>"
335                "<br>"
336                "You should have received a copy of the GNU General Public License<br>"
337                "along with TSPSG.  If not, see <a href=\"http://www.gnu.org/licenses/\">http://www.gnu.org/licenses/</a>.";
338
339QDialog *dlg = new QDialog(this);
340QLabel *lblIcon = new QLabel(dlg),
341        *lblTitle = new QLabel(dlg);
342QTextBrowser *txtAbout = new QTextBrowser(dlg);
343QVBoxLayout *vb = new QVBoxLayout();
344QHBoxLayout *hb = new QHBoxLayout();
345QDialogButtonBox *bb = new QDialogButtonBox(QDialogButtonBox::Ok, Qt::Horizontal, dlg);
346
347        lblIcon->setPixmap(QPixmap(":/images/tspsg.png").scaledToWidth(logicalDpiX() * 2 / 3, Qt::SmoothTransformation));
348        lblIcon->setAlignment(Qt::AlignTop);
349        lblTitle->setOpenExternalLinks(true);
350        lblTitle->setText(title);
351
352        hb->addWidget(lblIcon);
353        hb->addWidget(lblTitle);
354        hb->addStretch();
355
356//      txtAbout->setTextInteractionFlags(txtAbout->textInteractionFlags() ^ Qt::TextEditable);
357        txtAbout->setWordWrapMode(QTextOption::NoWrap);
358        txtAbout->setOpenExternalLinks(true);
359        txtAbout->setHtml(about);
360        txtAbout->moveCursor(QTextCursor::Start);
361
362        bb->button(QDialogButtonBox::Ok)->setCursor(QCursor(Qt::PointingHandCursor));
363
364        vb->addLayout(hb);
365        vb->addWidget(txtAbout);
366        vb->addWidget(bb);
367
368        dlg->setWindowFlags(Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::WindowCloseButtonHint);
369        dlg->setWindowTitle(tr("About TSPSG"));
370        dlg->setLayout(vb);
371
372        connect(bb, SIGNAL(accepted()), dlg, SLOT(accept()));
373
374        // Adding some eyecandy in Vista and 7 :-)
375        if (QtWin::isCompositionEnabled())  {
376                QtWin::enableBlurBehindWindow(dlg, true);
377        }
378
379        dlg->resize(410, 300);
380        dlg->exec();
381
382        delete dlg;
383}
384
385void MainWindow::buttonBackToTaskClicked()
386{
387        tabWidget->setCurrentIndex(0);
388}
389
390void MainWindow::buttonRandomClicked()
391{
392        QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
393        tspmodel->randomize();
394        QApplication::restoreOverrideCursor();
395}
396
397void MainWindow::buttonSolveClicked()
398{
399TMatrix matrix;
400QList<double> row;
401int n = spinCities->value();
402bool ok;
403        for (int r = 0; r < n; r++) {
404                row.clear();
405                for (int c = 0; c < n; c++) {
406                        row.append(tspmodel->index(r,c).data(Qt::UserRole).toDouble(&ok));
407                        if (!ok) {
408                                QMessageBox(QMessageBox::Critical,tr("Data error"),tr("Error in cell [Row %1; Column %2]: Invalid data format.").arg(r + 1).arg(c + 1),QMessageBox::Ok,this).exec();
409                                return;
410                        }
411                }
412                matrix.append(row);
413        }
414CTSPSolver solver;
415SStep *root = solver.solve(n,matrix,this);
416        if (!root)
417                return;
418        QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
419QColor color = settings->value("Output/Color",DEF_FONT_COLOR).value<QColor>();
420        output.clear();
421        output.append("<p>" + tr("Variant #%1").arg(spinVariant->value()) + "</p>");
422        output.append("<p>" + tr("Task:") + "</p>");
423        outputMatrix(matrix, output);
424        output.append("<hr>");
425        output.append("<p>" + tr("Solution of Variant #%1 task").arg(spinVariant->value()) + "</p>");
426SStep *step = root;
427        n = 1;
428        while (n <= spinCities->value()) {
429                if (step->prNode->prNode != NULL || ((step->prNode->prNode == NULL) && (step->plNode->prNode == NULL))) {
430                        if (n != spinCities->value()) {
431                                output.append("<p>" + tr("Step #%1").arg(n++) + "</p>");
432                                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())))) {
433                                        outputMatrix(*step, output);
434                                }
435                                output.append("<p>" + tr("Selected candidate for branching: %1.").arg(tr("(%1;%2)").arg(step->candidate.nRow + 1).arg(step->candidate.nCol + 1)) + "</p>");
436                                if (!step->alts.empty()) {
437SCandidate cand;
438QString alts;
439                                        foreach(cand, step->alts) {
440                                                if (!alts.isEmpty())
441                                                        alts += ", ";
442                                                alts += tr("(%1;%2)").arg(cand.nRow + 1).arg(cand.nCol + 1);
443                                        }
444                                        output.append("<p class=\"hasalts\">" + tr("%n alternate candidate(s) for branching: %1.","",step->alts.count()).arg(alts) + "</p>");
445                                }
446                                output.append("<p>&nbsp;</p>");
447                        }
448                }
449                if (step->prNode->prNode != NULL)
450                        step = step->prNode;
451                else if (step->plNode->prNode != NULL)
452                        step = step->plNode;
453                else
454                        break;
455        }
456        if (solver.isOptimal())
457                output.append("<p>" + tr("Optimal path:") + "</p>");
458        else
459                output.append("<p>" + tr("Resulting path:") + "</p>");
460        output.append("<p>&nbsp;&nbsp;" + solver.getSortedPath() + "</p>");
461        if (isInteger(step->price))
462                output.append("<p>" + tr("The price is <b>%n</b> unit(s).", "", qRound(step->price)) + "</p>");
463        else
464                output.append("<p>" + tr("The price is <b>%1</b> units.").arg(step->price, 0, 'f', settings->value("Task/FractionalAccuracy", DEF_FRACTIONAL_ACCURACY).toInt()) + "</p>");
465        if (!solver.isOptimal()) {
466                output.append("<p>&nbsp;</p>");
467                output.append("<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>");
468        }
469        output.append("<p></p>");
470
471        solutionText->setHtml(output.join(""));
472        solutionText->setDocumentTitle(tr("Solution of Variant #%1 task").arg(spinVariant->value()));
473
474        if (settings->value("Output/ScrollToEnd", DEF_SCROLL_TO_END).toBool()) {
475                // Scrolling to the end of text.
476                solutionText->moveCursor(QTextCursor::End);
477        }
478
479        toggleSolutionActions();
480        tabWidget->setCurrentIndex(1);
481        QApplication::restoreOverrideCursor();
482}
483
484void MainWindow::dataChanged()
485{
486        setWindowModified(true);
487}
488
489void MainWindow::dataChanged(const QModelIndex &tl, const QModelIndex &br)
490{
491        setWindowModified(true);
492        if (settings->value("Autosize", DEF_AUTOSIZE).toBool()) {
493                for (int k = tl.row(); k <= br.row(); k++)
494                        taskView->resizeRowToContents(k);
495                for (int k = tl.column(); k <= br.column(); k++)
496                        taskView->resizeColumnToContents(k);
497        }
498}
499
500#ifdef Q_OS_WINCE
501void MainWindow::changeEvent(QEvent *ev)
502{
503        if ((ev->type() == QEvent::ActivationChange) && isActiveWindow())
504                desktopResized(0);
505
506        QWidget::changeEvent(ev);
507}
508
509void MainWindow::desktopResized(int screen)
510{
511        if ((screen != 0) || !isActiveWindow())
512                return;
513
514QRect availableGeometry = QApplication::desktop()->availableGeometry(0);
515        if (currentGeometry != availableGeometry) {
516                QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
517                /*!
518                 * \hack HACK: This hack checks whether \link QDesktopWidget::availableGeometry() availableGeometry()\endlink's \c top + \c hegiht = \link QDesktopWidget::screenGeometry() screenGeometry()\endlink's \c height.
519                 *  If \c true, the window gets maximized. If we used \c setGeometry() in this case, the bottom of the
520                 *  window would end up being behind the soft buttons. Is this a bug in Qt or Windows Mobile?
521                 */
522                if ((availableGeometry.top() + availableGeometry.height()) == QApplication::desktop()->screenGeometry().height()) {
523                        setWindowState(windowState() | Qt::WindowMaximized);
524                } else {
525                        if (windowState() & Qt::WindowMaximized)
526                                setWindowState(windowState() ^ Qt::WindowMaximized);
527                        setGeometry(availableGeometry);
528                }
529                currentGeometry = availableGeometry;
530                QApplication::restoreOverrideCursor();
531        }
532}
533#endif // Q_OS_WINCE
534
535void MainWindow::numCitiesChanged(int nCities)
536{
537        blockSignals(true);
538        spinCities->setValue(nCities);
539        blockSignals(false);
540}
541
542#ifndef QT_NO_PRINTER
543void MainWindow::printPreview(QPrinter *printer)
544{
545        solutionText->print(printer);
546}
547#endif // QT_NO_PRINTER
548
549void MainWindow::spinCitiesValueChanged(int n)
550{
551        QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
552int count = tspmodel->numCities();
553        tspmodel->setNumCities(n);
554        if ((n > count) && settings->value("Autosize", DEF_AUTOSIZE).toBool())
555                for (int k = count; k < n; k++) {
556                        taskView->resizeColumnToContents(k);
557                        taskView->resizeRowToContents(k);
558                }
559        QApplication::restoreOverrideCursor();
560}
561
562void MainWindow::closeEvent(QCloseEvent *ev)
563{
564        if (!maybeSave()) {
565                ev->ignore();
566                return;
567        }
568        if (!settings->value("SettingsReset", false).toBool()) {
569                settings->setValue("NumCities", spinCities->value());
570
571                // Saving Main Window state
572                if (settings->value("SavePos", DEF_SAVEPOS).toBool()) {
573                        settings->beginGroup("MainWindow");
574#if !defined(Q_OS_WINCE) && !defined(Q_OS_SYMBIAN)
575                        settings->setValue("Geometry", saveGeometry());
576#endif // Q_OS_WINCE
577                        settings->setValue("State", saveState());
578                        settings->endGroup();
579                }
580        } else {
581                settings->remove("SettingsReset");
582        }
583
584        QMainWindow::closeEvent(ev);
585}
586
587void MainWindow::initDocStyleSheet()
588{
589QColor color = settings->value("Output/Color",DEF_FONT_COLOR).value<QColor>();
590QColor hilight;
591        if (color.value() < 192)
592                hilight.setHsv(color.hue(),color.saturation(),127 + qRound(color.value() / 2));
593        else
594                hilight.setHsv(color.hue(),color.saturation(),color.value() / 2);
595        solutionText->document()->setDefaultStyleSheet("* {color: " + color.name() +";} p {margin: 0px 10px;} table {margin: 5px;} td {padding: 1px 5px;} .hasalts {color: " + hilight.name() + ";} .selected {color: #A00000; font-weight: bold;} .alternate {color: #008000; font-weight: bold;}");
596        solutionText->document()->setDefaultFont(settings->value("Output/Font",QFont(DEF_FONT_FAMILY,DEF_FONT_SIZE)).value<QFont>());
597}
598
599void MainWindow::loadLangList()
600{
601QDir dir(PATH_I18N, "tspsg_*.qm", QDir::Name | QDir::IgnoreCase, QDir::Files);
602        if (!dir.exists())
603                return;
604QFileInfoList langs = dir.entryInfoList();
605        if (langs.size() <= 0)
606                return;
607QAction *a;
608QTranslator t;
609QString name;
610        for (int k = 0; k < langs.size(); k++) {
611                QFileInfo lang = langs.at(k);
612                if (lang.completeBaseName().compare("tspsg_en", Qt::CaseInsensitive) && t.load(lang.completeBaseName(), PATH_I18N)) {
613                        name = t.translate("--------", "LANGNAME", "Please, provide a native name of your translation language here.");
614                        a = menuSettingsLanguage->addAction(name);
615                        a->setStatusTip(QString("Set application language to %1").arg(name));
616                        a->setData(lang.completeBaseName().mid(6));
617                        a->setCheckable(true);
618                        a->setActionGroup(groupSettingsLanguageList);
619                        if (settings->value("Language", QLocale::system().name()).toString().startsWith(lang.completeBaseName().mid(6)))
620                                a->setChecked(true);
621                }
622        }
623}
624
625bool MainWindow::loadLanguage(const QString &lang)
626{
627// i18n
628bool ad = false;
629QString lng = lang;
630        if (lng.isEmpty()) {
631                ad = settings->value("Language", "").toString().isEmpty();
632                lng = settings->value("Language", QLocale::system().name()).toString();
633        }
634static QTranslator *qtTranslator; // Qt library translator
635        if (qtTranslator) {
636                qApp->removeTranslator(qtTranslator);
637                delete qtTranslator;
638                qtTranslator = NULL;
639        }
640static QTranslator *translator; // Application translator
641        if (translator) {
642                qApp->removeTranslator(translator);
643                delete translator;
644                translator = NULL;
645        }
646
647        if (lng == "en")
648                return true;
649
650        // Trying to load system Qt library translation...
651        qtTranslator = new QTranslator(this);
652        if (qtTranslator->load("qt_" + lng, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
653                qApp->installTranslator(qtTranslator);
654        else {
655                // No luck. Let's try to load a bundled one.
656                if (qtTranslator->load("qt_" + lng, PATH_I18N))
657                        qApp->installTranslator(qtTranslator);
658                else {
659                        // Qt library translation unavailable
660                        delete qtTranslator;
661                        qtTranslator = NULL;
662                }
663        }
664
665        // Now let's load application translation.
666        translator = new QTranslator(this);
667        if (translator->load("tspsg_" + lng, PATH_I18N))
668                qApp->installTranslator(translator);
669        else {
670                delete translator;
671                translator = NULL;
672                if (!ad) {
673                        settings->remove("Language");
674                        if (QApplication::overrideCursor() != 0)
675                                QApplication::restoreOverrideCursor();
676                        if (isVisible())
677                                QMessageBox::warning(this, tr("Language Change"), tr("Unable to load the translation language.\nFalling back to autodetection."));
678                        else
679                                QMessageBox::warning(NULL, tr("Language Change"), tr("Unable to load the translation language.\nFalling back to autodetection."));
680                }
681                return false;
682        }
683        return true;
684}
685
686bool MainWindow::maybeSave()
687{
688        if (!isWindowModified())
689                return true;
690int res = QMessageBox(QMessageBox::Warning,tr("Unsaved Changes"),tr("Would you like to save changes in current task?"),QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel,this).exec();
691        if (res == QMessageBox::Save)
692                return saveTask();
693        else if (res == QMessageBox::Cancel)
694                return false;
695        else
696                return true;
697}
698
699void MainWindow::outputMatrix(const TMatrix &matrix, QStringList &output)
700{
701int n = spinCities->value();
702QString line="";
703        output.append("<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\">");
704        for (int r = 0; r < n; r++) {
705                line = "<tr>";
706                for (int c = 0; c < n; c++) {
707                        if (matrix.at(r).at(c) == INFINITY)
708                                line += "<td align=\"center\">"INFSTR"</td>";
709                        else
710                                line += isInteger(matrix.at(r).at(c)) ? QString("<td align=\"center\">%1</td>").arg(matrix.at(r).at(c)) : QString("<td align=\"center\">%1</td>").arg(matrix.at(r).at(c), 0, 'f', settings->value("Task/FractionalAccuracy", DEF_FRACTIONAL_ACCURACY).toInt());
711                }
712                line += "</tr>";
713                output.append(line);
714        }
715        output.append("</table>");
716}
717
718void MainWindow::outputMatrix(const SStep &step, QStringList &output)
719{
720int n = spinCities->value();
721QString line="";
722        output.append("<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\">");
723        for (int r = 0; r < n; r++) {
724                line = "<tr>";
725                for (int c = 0; c < n; c++) {
726                        if (step.matrix.at(r).at(c) == INFINITY)
727                                line += "<td align=\"center\">"INFSTR"</td>";
728                        else if ((r == step.candidate.nRow) && (c == step.candidate.nCol))
729                                line += isInteger(step.matrix.at(r).at(c)) ? QString("<td align=\"center\" class=\"selected\">%1</td>").arg(step.matrix.at(r).at(c)) : QString("<td align=\"center\" class=\"selected\">%1</td>").arg(step.matrix.at(r).at(c), 0, 'f', settings->value("Task/FractionalAccuracy", DEF_FRACTIONAL_ACCURACY).toInt());
730                        else {
731SCandidate cand;
732                                cand.nRow = r;
733                                cand.nCol = c;
734                                if (step.alts.contains(cand))
735                                        line += isInteger(step.matrix.at(r).at(c)) ? QString("<td align=\"center\" class=\"alternate\">%1</td>").arg(step.matrix.at(r).at(c)) : QString("<td align=\"center\" class=\"alternate\">%1</td>").arg(step.matrix.at(r).at(c), 0, 'f', settings->value("Task/FractionalAccuracy", DEF_FRACTIONAL_ACCURACY).toInt());
736                                else
737                                        line += isInteger(step.matrix.at(r).at(c)) ? QString("<td align=\"center\">%1</td>").arg(step.matrix.at(r).at(c)) : QString("<td align=\"center\">%1</td>").arg(step.matrix.at(r).at(c), 0, 'f', settings->value("Task/FractionalAccuracy", DEF_FRACTIONAL_ACCURACY).toInt());
738                        }
739                }
740                line += "</tr>";
741                output.append(line);
742        }
743        output.append("</table>");
744}
745
746void MainWindow::retranslateUi(bool all)
747{
748        if (all)
749                Ui::MainWindow::retranslateUi(this);
750
751        actionSettingsLanguageEnglish->setStatusTip(tr("Set application language to %1").arg("English"));
752
753#ifndef QT_NO_PRINTER
754        actionFilePrintPreview->setText(QApplication::translate("MainWindow", "P&rint Preview...", 0, QApplication::UnicodeUTF8));
755#ifndef QT_NO_TOOLTIP
756        actionFilePrintPreview->setToolTip(QApplication::translate("MainWindow", "Preview solution results", 0, QApplication::UnicodeUTF8));
757#endif // QT_NO_TOOLTIP
758#ifndef QT_NO_STATUSTIP
759        actionFilePrintPreview->setStatusTip(QApplication::translate("MainWindow", "Preview current solution results before printing", 0, QApplication::UnicodeUTF8));
760#endif // QT_NO_STATUSTIP
761
762        actionFilePrint->setText(QApplication::translate("MainWindow", "&Print...", 0, QApplication::UnicodeUTF8));
763#ifndef QT_NO_TOOLTIP
764        actionFilePrint->setToolTip(QApplication::translate("MainWindow", "Print solution", 0, QApplication::UnicodeUTF8));
765#endif // QT_NO_TOOLTIP
766#ifndef QT_NO_STATUSTIP
767        actionFilePrint->setStatusTip(QApplication::translate("MainWindow", "Print current solution results", 0, QApplication::UnicodeUTF8));
768#endif // QT_NO_STATUSTIP
769        actionFilePrint->setShortcut(QApplication::translate("MainWindow", "Ctrl+P", 0, QApplication::UnicodeUTF8));
770#endif // QT_NO_PRINTER
771}
772
773bool MainWindow::saveTask() {
774QStringList filters(tr("%1 Task File").arg("TSPSG") + " (*.tspt)");
775        filters.append(tr("All Files") + " (*)");
776QString file;
777        if (fileName.endsWith(".tspt", Qt::CaseInsensitive))
778                file = fileName;
779        else
780                file = QFileInfo(fileName).canonicalPath() + "/" + QFileInfo(fileName).completeBaseName() + ".tspt";
781
782QFileDialog::Options opts = settings->value("UseNativeDialogs", DEF_USE_NATIVE_DIALOGS).toBool() ? QFileDialog::Options() : QFileDialog::DontUseNativeDialog;
783        file = QFileDialog::getSaveFileName(this, tr("Task Save"), file, filters.join(";;"), NULL, opts);
784
785        if (file.isEmpty())
786                return false;
787        if (tspmodel->saveTask(file)) {
788                setFileName(file);
789                setWindowModified(false);
790                return true;
791        }
792        return false;
793}
794
795void MainWindow::setFileName(const QString &fileName)
796{
797        this->fileName = fileName;
798        setWindowTitle(QString("%1[*] - %2").arg(QFileInfo(fileName).completeBaseName()).arg(tr("Travelling Salesman Problem")));
799}
800
801void MainWindow::setupUi()
802{
803        Ui::MainWindow::setupUi(this);
804
805#if QT_VERSION >= 0x040600
806        setToolButtonStyle(Qt::ToolButtonFollowStyle);
807#endif
808
809#if !defined(Q_OS_WINCE) && !defined(Q_OS_SYMBIAN)
810QStatusBar *statusbar = new QStatusBar(this);
811        statusbar->setObjectName("statusbar");
812        setStatusBar(statusbar);
813#endif // Q_OS_WINCE
814
815#ifdef Q_OS_WINCE
816        menuBar()->setDefaultAction(menuFile->menuAction());
817
818QScrollArea *scrollArea = new QScrollArea(this);
819        scrollArea->setFrameShape(QFrame::NoFrame);
820        scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
821        scrollArea->setWidgetResizable(true);
822        scrollArea->setWidget(tabWidget);
823        setCentralWidget(scrollArea);
824#endif // Q_OS_WINCE
825
826        //! \hack HACK: A little hack for toolbar icons to have a sane size.
827#ifdef Q_OS_WINCE
828        toolBar->setIconSize(QSize(logicalDpiX() / 4, logicalDpiY() / 4));
829#elif defined(Q_OS_SYMBIAN)
830        toolBar->setIconSize(QSize(logicalDpiX() / 5, logicalDpiY() / 5));
831#endif // Q_OS_WINCE
832
833        solutionText->document()->setDefaultFont(settings->value("Output/Font",QFont(DEF_FONT_FAMILY,DEF_FONT_SIZE)).value<QFont>());
834        solutionText->setTextColor(settings->value("Output/Color",DEF_FONT_COLOR).value<QColor>());
835        solutionText->setWordWrapMode(QTextOption::WordWrap);
836
837#ifndef QT_NO_PRINTER
838        actionFilePrintPreview = new QAction(this);
839        actionFilePrintPreview->setObjectName("actionFilePrintPreview");
840        actionFilePrintPreview->setEnabled(false);
841        actionFilePrintPreview->setIcon(QIcon(":/images/icons/document_preview.png"));
842
843        actionFilePrint = new QAction(this);
844        actionFilePrint->setObjectName("actionFilePrint");
845        actionFilePrint->setEnabled(false);
846        actionFilePrint->setIcon(QIcon(":/images/icons/fileprint.png"));
847
848        menuFile->insertAction(actionFileExit,actionFilePrintPreview);
849        menuFile->insertAction(actionFileExit,actionFilePrint);
850        menuFile->insertSeparator(actionFileExit);
851
852        toolBar->insertAction(actionSettingsPreferences,actionFilePrint);
853#endif // QT_NO_PRINTER
854
855        groupSettingsLanguageList = new QActionGroup(this);
856        actionSettingsLanguageEnglish->setData("en");
857        actionSettingsLanguageEnglish->setActionGroup(groupSettingsLanguageList);
858        loadLangList();
859        actionSettingsLanguageAutodetect->setChecked(settings->value("Language", "").toString().isEmpty());
860
861        spinCities->setMaximum(MAX_NUM_CITIES);
862
863        retranslateUi(false);
864
865        // Adding some eyecandy in Vista and 7 :-)
866        if (QtWin::isCompositionEnabled() && settings->value("UseTranslucency", DEF_USE_TRANSLUCENCY).toBool())  {
867                toggleTranclucency(true);
868        }
869}
870
871void MainWindow::toggleSolutionActions(bool enable)
872{
873        buttonSaveSolution->setEnabled(enable);
874        actionFileSaveAsSolution->setEnabled(enable);
875        solutionText->setEnabled(enable);
876        if (!enable)
877                output.clear();
878#ifndef QT_NO_PRINTER
879        actionFilePrint->setEnabled(enable);
880        actionFilePrintPreview->setEnabled(enable);
881#endif // QT_NO_PRINTER
882}
883
884void MainWindow::toggleTranclucency(bool enable)
885{
886        QtWin::enableBlurBehindWindow(this, enable);
887        QtWin::enableBlurBehindWindow(tabWidget, enable);
888
889        if (QtWin::enableBlurBehindWindow(tabTask, enable))
890                tabTask->setAutoFillBackground(enable);
891        if (QtWin::enableBlurBehindWindow(tabSolution, enable))
892                tabSolution->setAutoFillBackground(enable);
893}
Note: See TracBrowser for help on using the repository browser.