source: tspsg/src/mainwindow.cpp @ 430bd7f7e9

0.1.3.145-beta1-symbian0.1.4.170-beta2-bb10appveyorimgbotreadme 0.1.1.42-alpha1
Last change on this file since 430bd7f7e9 was 430bd7f7e9, checked in by Oleksii Serdiuk, 15 years ago

+ Finished solving algorithm (needs thorough testing).
+ Solution can be saved to HTML or OpenDocument? format.
+ Added VERSIONINFO resource for windows builds.

  • Updated translations to have unified terminology everywhere.

NB: This will be the first public alpha build.

  • Property mode set to 100644
File size: 18.4 KB
Line 
1        /*
2 *  TSPSG: TSP Solver and Generator
3 *  Copyright (C) 2007-2009 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
26MainWindow::MainWindow(QWidget *parent)
27        : QMainWindow(parent)
28{
29        settings = new QSettings(QSettings::IniFormat,QSettings::UserScope,"TSPSG","tspsg");
30        loadLanguage();
31        setupUi(this);
32        initDocStyleSheet();
33        solutionText->document()->setDefaultFont(settings->value("Output/Font",QFont(DEF_FONT_FAMILY,DEF_FONT_SIZE)).value<QFont>());
34        solutionText->setTextColor(settings->value("Output/Color",DEF_FONT_COLOR).value<QColor>());
35        solutionText->setWordWrapMode(QTextOption::WordWrap);
36#ifdef Q_OS_WINCE
37        // A little hack for toolbar icons to have sane size.
38int s = qMin(QApplication::desktop()->screenGeometry().width(),QApplication::desktop()->screenGeometry().height());
39        toolBar->setIconSize(QSize(s / 10,s / 10));
40#endif
41#ifndef Q_OS_WINCE
42        printer = new QPrinter();
43#endif // Q_OS_WINCE
44        groupSettingsLanguageList = new QActionGroup(this);
45        actionSettingsLanguageEnglish->setData("en");
46        actionSettingsLanguageEnglish->setActionGroup(groupSettingsLanguageList);
47        loadLangList();
48        spinCities->setValue(settings->value("NumCities",5).toInt());
49        actionSettingsLanguageAutodetect->setChecked(settings->value("Language","").toString().isEmpty());
50        connect(actionFileNew,SIGNAL(triggered()),this,SLOT(actionFileNewTriggered()));
51        connect(actionFileOpen,SIGNAL(triggered()),this,SLOT(actionFileOpenTriggered()));
52        connect(actionFileSaveAsTask,SIGNAL(triggered()),this,SLOT(actionFileSaveAsTaskTriggered()));
53        connect(actionFileSaveAsSolution,SIGNAL(triggered()),this,SLOT(actionFileSaveAsSolutionTriggered()));
54        connect(actionSettingsPreferences,SIGNAL(triggered()),this,SLOT(actionSettingsPreferencesTriggered()));
55        connect(actionSettingsLanguageAutodetect,SIGNAL(triggered(bool)),this,SLOT(actionSettingsLanguageAutodetectTriggered(bool)));
56        connect(groupSettingsLanguageList,SIGNAL(triggered(QAction *)),this,SLOT(groupSettingsLanguageListTriggered(QAction *)));
57        connect(actionHelpAboutQt,SIGNAL(triggered()),qApp,SLOT(aboutQt()));
58        connect(actionHelpAbout,SIGNAL(triggered()),this,SLOT(actionHelpAboutTriggered()));
59#ifndef Q_OS_WINCE
60        connect(actionFilePrintSetup,SIGNAL(triggered()),this,SLOT(actionFilePrintSetupTriggered()));
61#endif // Q_OS_WINCE
62        connect(buttonSolve,SIGNAL(clicked()),this,SLOT(buttonSolveClicked()));
63        connect(buttonRandom,SIGNAL(clicked()),this,SLOT(buttonRandomClicked()));
64        connect(spinCities,SIGNAL(valueChanged(int)),this,SLOT(spinCitiesValueChanged(int)));
65QRect rect = geometry();
66        setCentralWidget(tabWidget);
67#ifndef Q_OS_WINCE
68        if (settings->value("SavePos",false).toBool()) {
69                // Loading of saved window state
70                settings->beginGroup("MainWindow");
71                resize(settings->value("Size",size()).toSize());
72                move(settings->value("Position",pos()).toPoint());
73                if (settings->value("Maximized",false).toBool())
74                        setWindowState(windowState() | Qt::WindowMaximized);
75                settings->endGroup();
76        } else {
77                // Centering main window
78                rect.moveCenter(QApplication::desktop()->availableGeometry(this).center());
79                setGeometry(rect);
80        }
81#endif // Q_OS_WINCE
82        qsrand(QDateTime().currentDateTime().toTime_t());
83        tspmodel = new CTSPModel();
84        tspmodel->setNumCities(spinCities->value());
85        taskView->setModel(tspmodel);
86        connect(tspmodel,SIGNAL(numCitiesChanged(int)),this,SLOT(numCitiesChanged(int)));
87        connect(tspmodel,SIGNAL(dataChanged(const QModelIndex &, const QModelIndex &)),this,SLOT(dataChanged()));
88        connect(tspmodel,SIGNAL(layoutChanged()),this,SLOT(dataChanged()));
89#ifdef Q_OS_WINCE
90        taskView->resizeColumnsToContents();
91        taskView->resizeRowsToContents();
92#endif // Q_OS_WINCE
93}
94
95void MainWindow::enableSolutionActions(bool enable)
96{
97        actionFileSaveAsSolution->setEnabled(enable);
98        solutionText->setEnabled(enable);
99        if (!enable)
100                output.clear();
101}
102
103bool MainWindow::loadLanguage(QString lang)
104{
105// i18n
106bool ad = false;
107        if (lang.isEmpty()) {
108                ad = settings->value("Language","").toString().isEmpty();
109                lang = settings->value("Language",QLocale::system().name()).toString();
110        }
111static QTranslator *qtTranslator;
112        if (qtTranslator) {
113                qApp->removeTranslator(qtTranslator);
114                delete qtTranslator;
115                qtTranslator = NULL;
116        }
117        qtTranslator = new QTranslator();
118static QTranslator *translator;
119        if (translator) {
120                qApp->removeTranslator(translator);
121                delete translator;
122        }
123        translator = new QTranslator();
124        if (lang.compare("en") && !lang.startsWith("en_")) {
125                // Trying to load system Qt library translation...
126                if (qtTranslator->load("qt_" + lang,QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
127                        qApp->installTranslator(qtTranslator);
128                else
129                        // No luck. Let's try to load bundled one.
130                        if (qtTranslator->load("qt_" + lang,"i18n"))
131                                qApp->installTranslator(qtTranslator);
132                        else {
133                                delete qtTranslator;
134                                qtTranslator = NULL;
135                        }
136                // Now let's load application translation.
137                if (translator->load(lang,"i18n"))
138                        qApp->installTranslator(translator);
139                else {
140                        if (!ad)
141                                QMessageBox(QMessageBox::Warning,trUtf8("Language change"),trUtf8("Unable to load translation language."),QMessageBox::Ok,this).exec();
142                        delete translator;
143                        translator = NULL;
144                        return false;
145                }
146        }
147        return true;
148}
149
150void MainWindow::initDocStyleSheet()
151{
152QColor color = settings->value("Output/Color",DEF_FONT_COLOR).value<QColor>();
153QColor hilight;
154        if (color.value() < 192)
155                hilight.setHsv(color.hue(),color.saturation(),127 + qRound(color.value() / 2));
156        else
157                hilight.setHsv(color.hue(),color.saturation(),color.value() / 2);
158        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;}");
159        solutionText->document()->setDefaultFont(settings->value("Output/Font",QFont(DEF_FONT_FAMILY,DEF_FONT_SIZE)).value<QFont>());
160}
161
162void MainWindow::spinCitiesValueChanged(int n)
163{
164#ifdef Q_OS_WINCE
165int count = tspmodel->numCities();
166#endif // Q_OS_WINCE
167        tspmodel->setNumCities(n);
168#ifdef Q_OS_WINCE
169        if (n > count)
170                for (int k = count; k < n; k++) {
171                        taskView->resizeColumnToContents(k);
172                        taskView->resizeRowToContents(k);
173                }
174#endif // Q_OS_WINCE
175}
176
177
178void MainWindow::actionFileNewTriggered()
179{
180        if (isWindowModified()) {
181int res = QMessageBox(QMessageBox::Warning,trUtf8("New Task"),trUtf8("Would you like to save changes in current task?"),QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel,this).exec();
182                if ((res == QMessageBox::Cancel) || ((res == QMessageBox::Yes) && !saveTask()))
183                        return;
184        }
185        tspmodel->clear();
186        setWindowModified(false);
187        tabWidget->setCurrentIndex(0);
188        solutionText->clear();
189        enableSolutionActions(false);
190}
191
192void MainWindow::actionFileOpenTriggered()
193{
194        if (isWindowModified()) {
195int res = QMessageBox(QMessageBox::Warning,trUtf8("Task Open"),trUtf8("Would you like to save changes in current task?"),QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel,this).exec();
196                if ((res == QMessageBox::Cancel) || ((res == QMessageBox::Yes) && !saveTask()))
197                        return;
198        }
199QFileDialog od(this);
200        od.setAcceptMode(QFileDialog::AcceptOpen);
201        od.setFileMode(QFileDialog::ExistingFile);
202QStringList filters(trUtf8("All Supported Formats") + " (*.tspt *.zkt)");
203        filters.append(QString(trUtf8("%1 Task Files")).arg("TSPSG") + " (*.tspt)");
204        filters.append(QString(trUtf8("%1 Task Files")).arg("ZKomModRd") + " (*.zkt)");
205        filters.append(trUtf8("All Files") + " (*)");
206        od.setNameFilters(filters);
207        if (od.exec() != QDialog::Accepted)
208                return;
209QStringList files = od.selectedFiles();
210        if (files.size() < 1)
211                return;
212        tspmodel->loadTask(files.first());
213        setWindowModified(false);
214        solutionText->clear();
215        enableSolutionActions(false);
216}
217
218void MainWindow::actionFileSaveAsTaskTriggered()
219{
220        saveTask();
221}
222
223void MainWindow::actionFileSaveAsSolutionTriggered()
224{
225static QString selectedFile;
226        if (selectedFile.isEmpty())
227                selectedFile = "solution.html";
228QFileDialog sd(this);
229        sd.setAcceptMode(QFileDialog::AcceptSave);
230QStringList filters(trUtf8("HTML Files") + " (*.html *.htm)");
231        filters.append(trUtf8("OpenDocument Files") + " (*.odt)");
232        filters.append(trUtf8("All Files") + " (*)");
233        sd.setNameFilters(filters);
234        sd.selectFile(selectedFile);
235        if (sd.exec() != QDialog::Accepted)
236                return;
237QStringList files = sd.selectedFiles();
238        if (files.empty())
239                return;
240        selectedFile = files.first();
241QTextDocumentWriter dw(selectedFile);
242        if (!(selectedFile.endsWith(".htm",Qt::CaseInsensitive) || selectedFile.endsWith(".html",Qt::CaseInsensitive) || selectedFile.endsWith(".odt",Qt::CaseInsensitive) || selectedFile.endsWith(".txt",Qt::CaseInsensitive)))
243                dw.setFormat("plaintext");
244        dw.write(solutionText->document());
245}
246
247bool MainWindow::saveTask() {
248QFileDialog sd(this);
249        sd.setAcceptMode(QFileDialog::AcceptSave);
250QStringList filters(QString(trUtf8("%1 Task File")).arg("TSPSG") + " (*.tspt)");
251        filters.append(trUtf8("All Files") + " (*)");
252        sd.setNameFilters(filters);
253        sd.setDefaultSuffix("tspt");
254        if (sd.exec() != QDialog::Accepted)
255                return false;
256QStringList files = sd.selectedFiles();
257        if (files.size() < 1)
258                return false;
259        if (tspmodel->saveTask(files.first())) {
260                setWindowModified(false);
261                return true;
262        } else
263                return false;
264}
265
266void MainWindow::actionSettingsPreferencesTriggered()
267{
268SettingsDialog sd(this);
269        if (sd.exec() != QDialog::Accepted)
270                return;
271        if (sd.colorChanged() || sd.fontChanged()) {
272                initDocStyleSheet();
273                if (!output.isEmpty() && sd.colorChanged() && (QMessageBox(QMessageBox::Question,trUtf8("Settings Changed"),trUtf8("You have changed color settings.\nDo you wish to apply them to current solution text?"),QMessageBox::Yes | QMessageBox::No,this).exec() == QMessageBox::Yes)) {
274                        QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
275                        solutionText->clear();
276                        solutionText->setHtml(output.join(""));
277                        QApplication::restoreOverrideCursor();
278                }
279        }
280}
281
282#ifndef Q_OS_WINCE
283void MainWindow::actionFilePrintSetupTriggered()
284{
285QPrintDialog pd(printer,this);
286#if QT_VERSION >= 0x040500
287        // No such methods in Qt < 4.5
288        pd.setOption(QAbstractPrintDialog::PrintSelection,false);
289        pd.setOption(QAbstractPrintDialog::PrintPageRange,false);
290#endif
291        pd.exec();
292}
293#endif // Q_OS_WINCE
294
295void MainWindow::buttonRandomClicked()
296{
297        tspmodel->randomize();
298        setWindowModified(true);
299#ifdef Q_OS_WINCE
300        taskView->resizeColumnsToContents();
301        taskView->resizeRowsToContents();
302#endif // Q_OS_WINCE
303}
304
305void MainWindow::outputMatrix(tMatrix matrix, QStringList &output, int nRow, int nCol)
306{
307int n = spinCities->value();
308QString line="";
309        output.append("<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\">");
310        for (int r = 0; r < n; r++) {
311                line = "<tr>";
312                for (int c = 0; c < n; c++) {
313                        if (matrix[r][c] == INFINITY)
314                                line += "<td align=\"center\">"INFSTR"</td>";
315                        else if ((r == nRow) && (c == nCol))
316                                line += "<td align=\"center\" class=\"selected\">" + QVariant(matrix[r][c]).toString() + "</td>";
317                        else
318                                line += "<td align=\"center\">" + QVariant(matrix[r][c]).toString() + "</td>";
319                }
320                line += "</tr>";
321                output.append(line);
322        }
323        output.append("</table>");
324}
325
326void MainWindow::buttonSolveClicked()
327{
328tMatrix matrix;
329QList<double> row;
330int n = spinCities->value();
331bool ok;
332        for (int r = 0; r < n; r++) {
333                row.clear();
334                for (int c = 0; c < n; c++) {
335                        row.append(tspmodel->index(r,c).data(Qt::UserRole).toDouble(&ok));
336                        if (!ok) {
337                                QMessageBox(QMessageBox::Critical,trUtf8("Data error"),QString(trUtf8("Error in cell [Row %1; Column %2]: Invalid data format.")).arg(r + 1).arg(c + 1),QMessageBox::Ok,this).exec();
338                                return;
339                        }
340                }
341                matrix.append(row);
342        }
343CTSPSolver solver;
344sStep *root = solver.solve(spinCities->value(),matrix);
345        if (!root)
346                return;
347        QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
348QColor color = settings->value("Output/Color",DEF_FONT_COLOR).value<QColor>();
349        output.clear();
350        output.append("<p>" + trUtf8("Variant #%1").arg(spinVariant->value()) + "</p>");
351        output.append("<p>" + trUtf8("Task:") + "</p>");
352        outputMatrix(matrix,output);
353        output.append("<hr>");
354        output.append("<p>" + trUtf8("Solution of Variant #%1 task").arg(spinVariant->value()) + "</p>");
355sStep *step = root;
356        n = 1;
357QString path = "";
358        while (n <= spinCities->value()) {
359                if (step->prNode->prNode != NULL || (step->prNode->prNode == NULL && step->plNode->prNode == NULL)) {
360                        if (n != spinCities->value()) {
361                                output.append("<p>" + trUtf8("Step #%1").arg(n++) + "</p>");
362                                outputMatrix(step->matrix,output,step->candidate.nRow,step->candidate.nCol);
363                                if (step->alts)
364                                        output.append("<p class=\"hasalts\">" + trUtf8("This step has alternate candidates for branching.") + "</p>");
365                                output.append("<p>&nbsp;</p>");
366                        }
367                        path += QString(" (%1,%2)").arg(step->candidate.nRow + 1).arg(step->candidate.nCol + 1);
368                }
369                if (step->prNode->prNode != NULL)
370                        step = step->prNode;
371                else if (step->plNode->prNode != NULL)
372                        step = step->plNode;
373                else
374                        break;
375        }
376        output.append("<p>" + trUtf8("Optimal path:") + "</p>");
377        output.append("<p>&nbsp;&nbsp;" + path + "</p>");
378        output.append("<p>" + trUtf8("The price is <b>%1</b> units.").arg(step->price) + "</p>");
379        solutionText->setHtml(output.join(""));
380        solutionText->setDocumentTitle(trUtf8("Solution of Variant #%1 task").arg(spinVariant->value()));
381        enableSolutionActions();
382        tabWidget->setCurrentIndex(1);
383        QApplication::restoreOverrideCursor();
384}
385
386void MainWindow::actionHelpAboutTriggered()
387{
388        // TODO: Normal about window :-)
389QString about = QString::fromUtf8("TSPSG - TSP Solver and Generator\n");
390        about += QString::fromUtf8("    Version: "BUILD_VERSION" ("BUILD_STATUS")\n");
391        about += QString::fromUtf8("    Copyright (C) 2007-%1 Lёppa <contacts[at]oleksii[dot]name>\n").arg(QDate::currentDate().toString("yyyy"));
392        about += QString::fromUtf8("Target OS: %1\n").arg(OS);
393        about += "Qt library:\n";
394        about += QString::fromUtf8("    Compile time: %1\n").arg(QT_VERSION_STR);
395        about += QString::fromUtf8("    Runtime: %1\n").arg(qVersion());
396        about += QString::fromUtf8("Built on %1 at %2\n").arg(__DATE__).arg(__TIME__);
397        about += "\n";
398        about += "TSPSG is licensed under the terms of the GNU General Public License. You should have received a copy of the GNU General Public License along with TSPSG.";
399        QMessageBox(QMessageBox::Information,"About",about,QMessageBox::Ok,this).exec();
400}
401
402void MainWindow::loadLangList()
403{
404QSettings langinfo("i18n/languages.ini",QSettings::IniFormat);
405#if QT_VERSION >= 0x040500
406        // In Qt < 4.5 QSettings doesn't have method setIniCodec.
407        langinfo.setIniCodec("UTF-8");
408#endif
409QDir dir("i18n","*.qm",QDir::Name | QDir::IgnoreCase,QDir::Files);
410        if (!dir.exists())
411                return;
412QFileInfoList langs = dir.entryInfoList();
413        if (langs.size() <= 0)
414                return;
415QAction *a;
416        for (int k = 0; k < langs.size(); k++) {
417                QFileInfo lang = langs.at(k);
418                if (!lang.completeBaseName().startsWith("qt_") && lang.completeBaseName().compare("en")) {
419#if QT_VERSION >= 0x040500
420                        a = menuSettingsLanguage->addAction(langinfo.value(lang.completeBaseName() + "/NativeName",lang.completeBaseName()).toString());
421#else
422                        // We use Name if Qt < 4.5 because NativeName is in UTF-8, QSettings
423                        // reads .ini file as ASCII and there is no way to set file encoding.
424                        a = menuSettingsLanguage->addAction(langinfo.value(lang.completeBaseName() + "/Name",lang.completeBaseName()).toString());
425#endif
426                        a->setData(lang.completeBaseName());
427                        a->setCheckable(true);
428                        a->setActionGroup(groupSettingsLanguageList);
429                        if (settings->value("Language",QLocale::system().name()).toString().startsWith(lang.completeBaseName()))
430                                a->setChecked(true);
431                }
432        }
433}
434
435void MainWindow::actionSettingsLanguageAutodetectTriggered(bool checked)
436{
437        if (checked) {
438                settings->remove("Language");
439                QMessageBox(QMessageBox::Information,trUtf8("Language change"),trUtf8("Language will be autodetected on next application start."),QMessageBox::Ok,this).exec();
440        } else
441                settings->setValue("Language",groupSettingsLanguageList->checkedAction()->data().toString());
442}
443
444void MainWindow::groupSettingsLanguageListTriggered(QAction *action)
445{
446        if (actionSettingsLanguageAutodetect->isChecked()) {
447                // We have language autodetection. It needs to be disabled to change language.
448                if (QMessageBox(QMessageBox::Question,trUtf8("Language change"),trUtf8("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) {
449                        actionSettingsLanguageAutodetect->trigger();
450                } else
451                        return;
452        }
453        if (loadLanguage(action->data().toString())) {
454                settings->setValue("Language",action->data().toString());
455                retranslateUi(this);
456        }
457}
458
459void MainWindow::closeEvent(QCloseEvent *event)
460{
461        if (isWindowModified()) {
462int res = QMessageBox(QMessageBox::Warning,trUtf8("Application Close"),trUtf8("Would you like to save changes in current task?"),QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel,this).exec();
463                if ((res == QMessageBox::Cancel) || ((res == QMessageBox::Yes) && !saveTask())) {
464                        event->ignore();
465                        return;
466                }
467        }
468        settings->setValue("NumCities",spinCities->value());
469#ifndef Q_OS_WINCE
470        // Saving windows state
471        if (settings->value("SavePos",false).toBool()) {
472                settings->beginGroup("MainWindow");
473                settings->setValue("Maximized",isMaximized());
474                if (!isMaximized()) {
475                        settings->setValue("Size",size());
476                        settings->setValue("Position",pos());
477                }
478                settings->endGroup();
479        }
480#endif // Q_OS_WINCE
481        QMainWindow::closeEvent(event);
482}
483
484void MainWindow::dataChanged()
485{
486        setWindowModified(true);
487}
488
489void MainWindow::numCitiesChanged(int nCities)
490{
491        spinCities->setValue(nCities);
492}
Note: See TracBrowser for help on using the repository browser.