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

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

+ Wait Cursor (a.k.a Hourglass) while application starts.
+ Open file, passed as command-line argument.

  • Renamed all resources to have lowercase names.
  • Application couldn't be built on Qt < 4.5, because it has no QTextDocumentWriter class. Made a workaround.
  • Property mode set to 100644
File size: 18.9 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        if (QCoreApplication::arguments().count() > 1) {
90                tspmodel->loadTask(QCoreApplication::arguments().at(1));
91                setWindowModified(false);
92        }
93#ifdef Q_OS_WINCE
94        taskView->resizeColumnsToContents();
95        taskView->resizeRowsToContents();
96#endif // Q_OS_WINCE
97}
98
99void MainWindow::enableSolutionActions(bool enable)
100{
101        actionFileSaveAsSolution->setEnabled(enable);
102        solutionText->setEnabled(enable);
103        if (!enable)
104                output.clear();
105}
106
107bool MainWindow::loadLanguage(QString lang)
108{
109// i18n
110bool ad = false;
111        if (lang.isEmpty()) {
112                ad = settings->value("Language","").toString().isEmpty();
113                lang = settings->value("Language",QLocale::system().name()).toString();
114        }
115static QTranslator *qtTranslator;
116        if (qtTranslator) {
117                qApp->removeTranslator(qtTranslator);
118                delete qtTranslator;
119                qtTranslator = NULL;
120        }
121        qtTranslator = new QTranslator();
122static QTranslator *translator;
123        if (translator) {
124                qApp->removeTranslator(translator);
125                delete translator;
126        }
127        translator = new QTranslator();
128        if (lang.compare("en") && !lang.startsWith("en_")) {
129                // Trying to load system Qt library translation...
130                if (qtTranslator->load("qt_" + lang,QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
131                        qApp->installTranslator(qtTranslator);
132                else
133                        // No luck. Let's try to load bundled one.
134                        if (qtTranslator->load("qt_" + lang,"i18n"))
135                                qApp->installTranslator(qtTranslator);
136                        else {
137                                delete qtTranslator;
138                                qtTranslator = NULL;
139                        }
140                // Now let's load application translation.
141                if (translator->load(lang,"i18n"))
142                        qApp->installTranslator(translator);
143                else {
144                        if (!ad)
145                                QMessageBox(QMessageBox::Warning,trUtf8("Language change"),trUtf8("Unable to load translation language."),QMessageBox::Ok,this).exec();
146                        delete translator;
147                        translator = NULL;
148                        return false;
149                }
150        }
151        return true;
152}
153
154void MainWindow::initDocStyleSheet()
155{
156QColor color = settings->value("Output/Color",DEF_FONT_COLOR).value<QColor>();
157QColor hilight;
158        if (color.value() < 192)
159                hilight.setHsv(color.hue(),color.saturation(),127 + qRound(color.value() / 2));
160        else
161                hilight.setHsv(color.hue(),color.saturation(),color.value() / 2);
162        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;}");
163        solutionText->document()->setDefaultFont(settings->value("Output/Font",QFont(DEF_FONT_FAMILY,DEF_FONT_SIZE)).value<QFont>());
164}
165
166void MainWindow::spinCitiesValueChanged(int n)
167{
168#ifdef Q_OS_WINCE
169int count = tspmodel->numCities();
170#endif // Q_OS_WINCE
171        tspmodel->setNumCities(n);
172#ifdef Q_OS_WINCE
173        if (n > count)
174                for (int k = count; k < n; k++) {
175                        taskView->resizeColumnToContents(k);
176                        taskView->resizeRowToContents(k);
177                }
178#endif // Q_OS_WINCE
179}
180
181
182void MainWindow::actionFileNewTriggered()
183{
184        if (isWindowModified()) {
185int 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();
186                if ((res == QMessageBox::Cancel) || ((res == QMessageBox::Yes) && !saveTask()))
187                        return;
188        }
189        tspmodel->clear();
190        setWindowModified(false);
191        tabWidget->setCurrentIndex(0);
192        solutionText->clear();
193        enableSolutionActions(false);
194}
195
196void MainWindow::actionFileOpenTriggered()
197{
198        if (isWindowModified()) {
199int 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();
200                if ((res == QMessageBox::Cancel) || ((res == QMessageBox::Yes) && !saveTask()))
201                        return;
202        }
203QFileDialog od(this);
204        od.setAcceptMode(QFileDialog::AcceptOpen);
205        od.setFileMode(QFileDialog::ExistingFile);
206QStringList filters(trUtf8("All Supported Formats") + " (*.tspt *.zkt)");
207        filters.append(QString(trUtf8("%1 Task Files")).arg("TSPSG") + " (*.tspt)");
208        filters.append(QString(trUtf8("%1 Task Files")).arg("ZKomModRd") + " (*.zkt)");
209        filters.append(trUtf8("All Files") + " (*)");
210        od.setNameFilters(filters);
211        if (od.exec() != QDialog::Accepted)
212                return;
213QStringList files = od.selectedFiles();
214        if (files.size() < 1)
215                return;
216        tspmodel->loadTask(files.first());
217        setWindowModified(false);
218        solutionText->clear();
219        enableSolutionActions(false);
220}
221
222void MainWindow::actionFileSaveAsTaskTriggered()
223{
224        saveTask();
225}
226
227void MainWindow::actionFileSaveAsSolutionTriggered()
228{
229static QString selectedFile;
230        if (selectedFile.isEmpty())
231                selectedFile = "solution.html";
232QFileDialog sd(this);
233        sd.setAcceptMode(QFileDialog::AcceptSave);
234QStringList filters(trUtf8("HTML Files") + " (*.html *.htm)");
235#if QT_VERSION >= 0x040500
236        filters.append(trUtf8("OpenDocument Files") + " (*.odt)");
237#endif // QT_VERSION >= 0x040500
238        filters.append(trUtf8("All Files") + " (*)");
239        sd.setNameFilters(filters);
240        sd.selectFile(selectedFile);
241        if (sd.exec() != QDialog::Accepted)
242                return;
243QStringList files = sd.selectedFiles();
244        if (files.empty())
245                return;
246        selectedFile = files.first();
247#if QT_VERSION >= 0x040500
248QTextDocumentWriter dw(selectedFile);
249        if (!(selectedFile.endsWith(".htm",Qt::CaseInsensitive) || selectedFile.endsWith(".html",Qt::CaseInsensitive) || selectedFile.endsWith(".odt",Qt::CaseInsensitive) || selectedFile.endsWith(".txt",Qt::CaseInsensitive)))
250                dw.setFormat("plaintext");
251        dw.write(solutionText->document());
252#else
253        // Qt < 4.5 has no QTextDocumentWriter class
254QFile file(selectedFile);
255        if (!file.open(QFile::WriteOnly))
256                return;
257QTextStream ts(&file);
258        ts.setCodec(QTextCodec::codecForName("UTF-8"));
259        ts << solutionText->document()->toHtml("UTF-8");
260#endif // QT_VERSION >= 0x040500
261}
262
263bool MainWindow::saveTask() {
264QFileDialog sd(this);
265        sd.setAcceptMode(QFileDialog::AcceptSave);
266QStringList filters(QString(trUtf8("%1 Task File")).arg("TSPSG") + " (*.tspt)");
267        filters.append(trUtf8("All Files") + " (*)");
268        sd.setNameFilters(filters);
269        sd.setDefaultSuffix("tspt");
270        if (sd.exec() != QDialog::Accepted)
271                return false;
272QStringList files = sd.selectedFiles();
273        if (files.size() < 1)
274                return false;
275        if (tspmodel->saveTask(files.first())) {
276                setWindowModified(false);
277                return true;
278        } else
279                return false;
280}
281
282void MainWindow::actionSettingsPreferencesTriggered()
283{
284SettingsDialog sd(this);
285        if (sd.exec() != QDialog::Accepted)
286                return;
287        if (sd.colorChanged() || sd.fontChanged()) {
288                initDocStyleSheet();
289                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)) {
290                        QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
291                        solutionText->clear();
292                        solutionText->setHtml(output.join(""));
293                        QApplication::restoreOverrideCursor();
294                }
295        }
296}
297
298#ifndef Q_OS_WINCE
299void MainWindow::actionFilePrintSetupTriggered()
300{
301QPrintDialog pd(printer,this);
302#if QT_VERSION >= 0x040500
303        // No such methods in Qt < 4.5
304        pd.setOption(QAbstractPrintDialog::PrintSelection,false);
305        pd.setOption(QAbstractPrintDialog::PrintPageRange,false);
306#endif
307        pd.exec();
308}
309#endif // Q_OS_WINCE
310
311void MainWindow::buttonRandomClicked()
312{
313        tspmodel->randomize();
314        setWindowModified(true);
315#ifdef Q_OS_WINCE
316        taskView->resizeColumnsToContents();
317        taskView->resizeRowsToContents();
318#endif // Q_OS_WINCE
319}
320
321void MainWindow::outputMatrix(tMatrix matrix, QStringList &output, int nRow, int nCol)
322{
323int n = spinCities->value();
324QString line="";
325        output.append("<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\">");
326        for (int r = 0; r < n; r++) {
327                line = "<tr>";
328                for (int c = 0; c < n; c++) {
329                        if (matrix[r][c] == INFINITY)
330                                line += "<td align=\"center\">"INFSTR"</td>";
331                        else if ((r == nRow) && (c == nCol))
332                                line += "<td align=\"center\" class=\"selected\">" + QVariant(matrix[r][c]).toString() + "</td>";
333                        else
334                                line += "<td align=\"center\">" + QVariant(matrix[r][c]).toString() + "</td>";
335                }
336                line += "</tr>";
337                output.append(line);
338        }
339        output.append("</table>");
340}
341
342void MainWindow::buttonSolveClicked()
343{
344tMatrix matrix;
345QList<double> row;
346int n = spinCities->value();
347bool ok;
348        for (int r = 0; r < n; r++) {
349                row.clear();
350                for (int c = 0; c < n; c++) {
351                        row.append(tspmodel->index(r,c).data(Qt::UserRole).toDouble(&ok));
352                        if (!ok) {
353                                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();
354                                return;
355                        }
356                }
357                matrix.append(row);
358        }
359CTSPSolver solver;
360sStep *root = solver.solve(spinCities->value(),matrix);
361        if (!root)
362                return;
363        QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
364QColor color = settings->value("Output/Color",DEF_FONT_COLOR).value<QColor>();
365        output.clear();
366        output.append("<p>" + trUtf8("Variant #%1").arg(spinVariant->value()) + "</p>");
367        output.append("<p>" + trUtf8("Task:") + "</p>");
368        outputMatrix(matrix,output);
369        output.append("<hr>");
370        output.append("<p>" + trUtf8("Solution of Variant #%1 task").arg(spinVariant->value()) + "</p>");
371sStep *step = root;
372        n = 1;
373QString path = "";
374        while (n <= spinCities->value()) {
375                if (step->prNode->prNode != NULL || (step->prNode->prNode == NULL && step->plNode->prNode == NULL)) {
376                        if (n != spinCities->value()) {
377                                output.append("<p>" + trUtf8("Step #%1").arg(n++) + "</p>");
378                                outputMatrix(step->matrix,output,step->candidate.nRow,step->candidate.nCol);
379                                if (step->alts)
380                                        output.append("<p class=\"hasalts\">" + trUtf8("This step has alternate candidates for branching.") + "</p>");
381                                output.append("<p>&nbsp;</p>");
382                        }
383                        path += QString(" (%1,%2)").arg(step->candidate.nRow + 1).arg(step->candidate.nCol + 1);
384                }
385                if (step->prNode->prNode != NULL)
386                        step = step->prNode;
387                else if (step->plNode->prNode != NULL)
388                        step = step->plNode;
389                else
390                        break;
391        }
392        output.append("<p>" + trUtf8("Optimal path:") + "</p>");
393        output.append("<p>&nbsp;&nbsp;" + path + "</p>");
394        output.append("<p>" + trUtf8("The price is <b>%1</b> units.").arg(step->price) + "</p>");
395        solutionText->setHtml(output.join(""));
396        solutionText->setDocumentTitle(trUtf8("Solution of Variant #%1 task").arg(spinVariant->value()));
397        enableSolutionActions();
398        tabWidget->setCurrentIndex(1);
399        QApplication::restoreOverrideCursor();
400}
401
402void MainWindow::actionHelpAboutTriggered()
403{
404        // TODO: Normal about window :-)
405QString about = QString::fromUtf8("TSPSG - TSP Solver and Generator\n");
406        about += QString::fromUtf8("    Version: "BUILD_VERSION"\n");
407        about += QString::fromUtf8("    Copyright (C) 2007-%1 Lёppa <contacts[at]oleksii[dot]name>\n").arg(QDate::currentDate().toString("yyyy"));
408        about += QString::fromUtf8("Target OS: %1\n").arg(OS);
409        about += "Qt library:\n";
410        about += QString::fromUtf8("    Compile time: %1\n").arg(QT_VERSION_STR);
411        about += QString::fromUtf8("    Runtime: %1\n").arg(qVersion());
412        about += QString::fromUtf8("Built on %1 at %2\n").arg(__DATE__).arg(__TIME__);
413        about += "\n";
414        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.";
415        QMessageBox(QMessageBox::Information,"About",about,QMessageBox::Ok,this).exec();
416}
417
418void MainWindow::loadLangList()
419{
420QSettings langinfo("i18n/languages.ini",QSettings::IniFormat);
421#if QT_VERSION >= 0x040500
422        // In Qt < 4.5 QSettings doesn't have method setIniCodec.
423        langinfo.setIniCodec("UTF-8");
424#endif
425QDir dir("i18n","*.qm",QDir::Name | QDir::IgnoreCase,QDir::Files);
426        if (!dir.exists())
427                return;
428QFileInfoList langs = dir.entryInfoList();
429        if (langs.size() <= 0)
430                return;
431QAction *a;
432        for (int k = 0; k < langs.size(); k++) {
433                QFileInfo lang = langs.at(k);
434                if (!lang.completeBaseName().startsWith("qt_") && lang.completeBaseName().compare("en")) {
435#if QT_VERSION >= 0x040500
436                        a = menuSettingsLanguage->addAction(langinfo.value(lang.completeBaseName() + "/NativeName",lang.completeBaseName()).toString());
437#else
438                        // We use Name if Qt < 4.5 because NativeName is in UTF-8, QSettings
439                        // reads .ini file as ASCII and there is no way to set file encoding.
440                        a = menuSettingsLanguage->addAction(langinfo.value(lang.completeBaseName() + "/Name",lang.completeBaseName()).toString());
441#endif
442                        a->setData(lang.completeBaseName());
443                        a->setCheckable(true);
444                        a->setActionGroup(groupSettingsLanguageList);
445                        if (settings->value("Language",QLocale::system().name()).toString().startsWith(lang.completeBaseName()))
446                                a->setChecked(true);
447                }
448        }
449}
450
451void MainWindow::actionSettingsLanguageAutodetectTriggered(bool checked)
452{
453        if (checked) {
454                settings->remove("Language");
455                QMessageBox(QMessageBox::Information,trUtf8("Language change"),trUtf8("Language will be autodetected on next application start."),QMessageBox::Ok,this).exec();
456        } else
457                settings->setValue("Language",groupSettingsLanguageList->checkedAction()->data().toString());
458}
459
460void MainWindow::groupSettingsLanguageListTriggered(QAction *action)
461{
462        if (actionSettingsLanguageAutodetect->isChecked()) {
463                // We have language autodetection. It needs to be disabled to change language.
464                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) {
465                        actionSettingsLanguageAutodetect->trigger();
466                } else
467                        return;
468        }
469        if (loadLanguage(action->data().toString())) {
470                settings->setValue("Language",action->data().toString());
471                retranslateUi(this);
472        }
473}
474
475void MainWindow::closeEvent(QCloseEvent *event)
476{
477        if (isWindowModified()) {
478int 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();
479                if ((res == QMessageBox::Cancel) || ((res == QMessageBox::Yes) && !saveTask())) {
480                        event->ignore();
481                        return;
482                }
483        }
484        settings->setValue("NumCities",spinCities->value());
485#ifndef Q_OS_WINCE
486        // Saving windows state
487        if (settings->value("SavePos",false).toBool()) {
488                settings->beginGroup("MainWindow");
489                settings->setValue("Maximized",isMaximized());
490                if (!isMaximized()) {
491                        settings->setValue("Size",size());
492                        settings->setValue("Position",pos());
493                }
494                settings->endGroup();
495        }
496#endif // Q_OS_WINCE
497        QMainWindow::closeEvent(event);
498}
499
500void MainWindow::dataChanged()
501{
502        setWindowModified(true);
503}
504
505void MainWindow::numCitiesChanged(int nCities)
506{
507        spinCities->setValue(nCities);
508}
Note: See TracBrowser for help on using the repository browser.