source: tspsg/src/mainwindow.cpp @ caef58b531

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

More code documentation.

  • Property mode set to 100644
File size: 22.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
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");
37        loadLanguage();
38        setupUi(this);
39#ifndef Q_OS_WINCE
40QStatusBar *statusbar = new QStatusBar(this);
41        statusbar->setObjectName("statusbar");
42        setStatusBar(statusbar);
43#endif // Q_OS_WINCE
44        initDocStyleSheet();
45        solutionText->document()->setDefaultFont(settings->value("Output/Font",QFont(DEF_FONT_FAMILY,DEF_FONT_SIZE)).value<QFont>());
46        solutionText->setTextColor(settings->value("Output/Color",DEF_FONT_COLOR).value<QColor>());
47        solutionText->setWordWrapMode(QTextOption::WordWrap);
48#ifdef Q_OS_WINCE
49        // A little hack for toolbar icons to have sane size.
50int s = qMin(QApplication::desktop()->screenGeometry().width(),QApplication::desktop()->screenGeometry().height());
51        toolBar->setIconSize(QSize(s / 10,s / 10));
52#endif
53#ifndef QT_NO_PRINTER
54        printer = new QPrinter(QPrinter::HighResolution);
55#endif // QT_NO_PRINTER
56        groupSettingsLanguageList = new QActionGroup(this);
57        actionSettingsLanguageEnglish->setData("en");
58        actionSettingsLanguageEnglish->setActionGroup(groupSettingsLanguageList);
59        loadLangList();
60        spinCities->setMaximum(MAX_NUM_CITIES);
61        actionSettingsLanguageAutodetect->setChecked(settings->value("Language","").toString().isEmpty());
62        connect(actionFileNew,SIGNAL(triggered()),this,SLOT(actionFileNewTriggered()));
63        connect(actionFileOpen,SIGNAL(triggered()),this,SLOT(actionFileOpenTriggered()));
64        connect(actionFileSave,SIGNAL(triggered()),this,SLOT(actionFileSaveTriggered()));
65        connect(actionFileSaveAsTask,SIGNAL(triggered()),this,SLOT(actionFileSaveAsTaskTriggered()));
66        connect(actionFileSaveAsSolution,SIGNAL(triggered()),this,SLOT(actionFileSaveAsSolutionTriggered()));
67        connect(actionSettingsPreferences,SIGNAL(triggered()),this,SLOT(actionSettingsPreferencesTriggered()));
68        connect(actionSettingsLanguageAutodetect,SIGNAL(triggered(bool)),this,SLOT(actionSettingsLanguageAutodetectTriggered(bool)));
69        connect(groupSettingsLanguageList,SIGNAL(triggered(QAction *)),this,SLOT(groupSettingsLanguageListTriggered(QAction *)));
70        connect(actionHelpAboutQt,SIGNAL(triggered()),qApp,SLOT(aboutQt()));
71        connect(actionHelpAbout,SIGNAL(triggered()),this,SLOT(actionHelpAboutTriggered()));
72#ifndef QT_NO_PRINTER
73        menuFile->insertAction(actionFileExit,actionFilePrintPreview);
74        menuFile->insertAction(actionFileExit,actionFilePrint);
75        menuFile->insertSeparator(actionFileExit);
76        toolBar->insertAction(actionSettingsPreferences,actionFilePrint);
77        connect(actionFilePrintPreview,SIGNAL(triggered()),this,SLOT(actionFilePrintPreviewTriggered()));
78        connect(actionFilePrint,SIGNAL(triggered()),this,SLOT(actionFilePrintTriggered()));
79#endif // QT_NO_PRINTER
80        connect(buttonSolve,SIGNAL(clicked()),this,SLOT(buttonSolveClicked()));
81        connect(buttonRandom,SIGNAL(clicked()),this,SLOT(buttonRandomClicked()));
82        connect(buttonBackToTask,SIGNAL(clicked()),this,SLOT(buttonBackToTaskClicked()));
83        connect(spinCities,SIGNAL(valueChanged(int)),this,SLOT(spinCitiesValueChanged(int)));
84        setCentralWidget(tabWidget);
85QRect rect = geometry();
86#ifndef Q_OS_WINCE
87        if (settings->value("SavePos",false).toBool()) {
88                // Loading of saved window state
89                settings->beginGroup("MainWindow");
90                resize(settings->value("Size",size()).toSize());
91                move(settings->value("Position",pos()).toPoint());
92                if (settings->value("Maximized",false).toBool())
93                        setWindowState(windowState() | Qt::WindowMaximized);
94                settings->endGroup();
95        } else {
96                // Centering main window
97                rect.moveCenter(QApplication::desktop()->availableGeometry(this).center());
98                setGeometry(rect);
99        }
100#endif // Q_OS_WINCE
101        qsrand(QDateTime().currentDateTime().toTime_t());
102        tspmodel = new CTSPModel();
103        taskView->setModel(tspmodel);
104        connect(tspmodel,SIGNAL(numCitiesChanged(int)),this,SLOT(numCitiesChanged(int)));
105        connect(tspmodel,SIGNAL(dataChanged(const QModelIndex &, const QModelIndex &)),this,SLOT(dataChanged(const QModelIndex &, const QModelIndex &)));
106        connect(tspmodel,SIGNAL(layoutChanged()),this,SLOT(dataChanged()));
107        if ((QCoreApplication::arguments().count() > 1) && (tspmodel->loadTask(QCoreApplication::arguments().at(1))))
108                setFileName(QCoreApplication::arguments().at(1));
109        else {
110                setFileName();
111                spinCities->setValue(settings->value("NumCities",DEF_NUM_CITIES).toInt());
112                spinCitiesValueChanged(spinCities->value());
113        }
114        setWindowModified(false);
115}
116
117void MainWindow::enableSolutionActions(bool enable)
118{
119        buttonSaveSolution->setEnabled(enable);
120        actionFileSaveAsSolution->setEnabled(enable);
121        solutionText->setEnabled(enable);
122        if (!enable)
123                output.clear();
124#ifndef QT_NO_PRINTER
125        actionFilePrint->setEnabled(enable);
126        actionFilePrintPreview->setEnabled(enable);
127#endif // QT_NO_PRINTER
128}
129
130bool MainWindow::loadLanguage(QString lang)
131{
132// i18n
133bool ad = false;
134        if (lang.isEmpty()) {
135                ad = settings->value("Language","").toString().isEmpty();
136                lang = settings->value("Language",QLocale::system().name()).toString();
137        }
138static QTranslator *qtTranslator; // Qt library translator
139        if (qtTranslator) {
140                qApp->removeTranslator(qtTranslator);
141                delete qtTranslator;
142                qtTranslator = NULL;
143        }
144        qtTranslator = new QTranslator();
145static QTranslator *translator; // Application translator
146        if (translator) {
147                qApp->removeTranslator(translator);
148                delete translator;
149        }
150        translator = new QTranslator();
151        if (lang.compare("en") && !lang.startsWith("en_")) {
152                // Trying to load system Qt library translation...
153                if (qtTranslator->load("qt_" + lang,QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
154                        qApp->installTranslator(qtTranslator);
155                else
156                        // No luck. Let's try to load bundled one.
157                        if (qtTranslator->load("qt_" + lang,PATH_I18N))
158                                qApp->installTranslator(qtTranslator);
159                        else {
160                                // Qt library translation unavailable
161                                delete qtTranslator;
162                                qtTranslator = NULL;
163                        }
164                // Now let's load application translation.
165                if (translator->load(lang,PATH_I18N))
166                        qApp->installTranslator(translator);
167                else {
168                        if (!ad)
169                                QMessageBox(QMessageBox::Warning,trUtf8("Language Change"),trUtf8("Unable to load translation language."),QMessageBox::Ok,this).exec();
170                        delete translator;
171                        translator = NULL;
172                        return false;
173                }
174        }
175        return true;
176}
177
178void MainWindow::initDocStyleSheet()
179{
180QColor color = settings->value("Output/Color",DEF_FONT_COLOR).value<QColor>();
181QColor hilight;
182        if (color.value() < 192)
183                hilight.setHsv(color.hue(),color.saturation(),127 + qRound(color.value() / 2));
184        else
185                hilight.setHsv(color.hue(),color.saturation(),color.value() / 2);
186        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;}");
187        solutionText->document()->setDefaultFont(settings->value("Output/Font",QFont(DEF_FONT_FAMILY,DEF_FONT_SIZE)).value<QFont>());
188}
189
190void MainWindow::setFileName(QString fileName)
191{
192        this->fileName = fileName;
193        setWindowTitle(QString("%1[*] - %2").arg(QFileInfo(fileName).completeBaseName()).arg(trUtf8("Travelling Salesman Problem")));
194}
195
196void MainWindow::spinCitiesValueChanged(int n)
197{
198int count = tspmodel->numCities();
199        tspmodel->setNumCities(n);
200        if ((n > count) && settings->value("Autosize",true).toBool())
201                for (int k = count; k < n; k++) {
202                        taskView->resizeColumnToContents(k);
203                        taskView->resizeRowToContents(k);
204                }
205}
206
207bool MainWindow::maybeSave()
208{
209        if (!isWindowModified())
210                return true;
211int res = QMessageBox(QMessageBox::Warning,trUtf8("Unsaved Changes"),trUtf8("Would you like to save changes in current task?"),QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel,this).exec();
212        if (res == QMessageBox::Save)
213                return saveTask();
214        else if (res == QMessageBox::Cancel)
215                return false;
216        else
217                return true;
218}
219
220void MainWindow::actionFileNewTriggered()
221{
222        if (!maybeSave())
223                return;
224        QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
225        tspmodel->clear();
226        setFileName();
227        setWindowModified(false);
228        tabWidget->setCurrentIndex(0);
229        solutionText->clear();
230        enableSolutionActions(false);
231        QApplication::restoreOverrideCursor();
232}
233
234void MainWindow::actionFileOpenTriggered()
235{
236        if (!maybeSave())
237                return;
238QFileDialog od(this);
239        od.setAcceptMode(QFileDialog::AcceptOpen);
240        od.setFileMode(QFileDialog::ExistingFile);
241QStringList filters(trUtf8("All Supported Formats") + " (*.tspt *.zkt)");
242        filters.append(trUtf8("%1 Task Files").arg("TSPSG") + " (*.tspt)");
243        filters.append(trUtf8("%1 Task Files").arg("ZKomModRd") + " (*.zkt)");
244        filters.append(trUtf8("All Files") + " (*)");
245        od.setNameFilters(filters);
246        if (od.exec() != QDialog::Accepted)
247                return;
248QStringList files = od.selectedFiles();
249        if (files.empty())
250                return;
251        if (!tspmodel->loadTask(files.first()))
252                return;
253        setFileName(files.first());
254        tabWidget->setCurrentIndex(0);
255        setWindowModified(false);
256        solutionText->clear();
257        enableSolutionActions(false);
258}
259
260void MainWindow::actionFileSaveTriggered()
261{
262        if ((fileName == trUtf8("Untitled") + ".tspt") || (!fileName.endsWith(".tspt",Qt::CaseInsensitive)))
263                saveTask();
264        else
265                if (tspmodel->saveTask(fileName))
266                        setWindowModified(false);
267}
268
269void MainWindow::actionFileSaveAsTaskTriggered()
270{
271        saveTask();
272}
273
274void MainWindow::actionFileSaveAsSolutionTriggered()
275{
276static QString selectedFile;
277        if (selectedFile.isEmpty())
278#ifndef QT_NO_PRINTER
279                selectedFile = "solution.pdf";
280#else
281                selectedFile = "solution.html";
282#endif // QT_NO_PRINTER
283QFileDialog sd(this);
284        sd.setAcceptMode(QFileDialog::AcceptSave);
285QStringList filters;
286#ifndef QT_NO_PRINTER
287        filters.append(trUtf8("PDF Files") + "(*.pdf)");
288#endif
289        filters.append(trUtf8("HTML Files") + " (*.html *.htm)");
290#if QT_VERSION >= 0x040500
291        filters.append(trUtf8("OpenDocument Files") + " (*.odt)");
292#endif // QT_VERSION >= 0x040500
293        filters.append(trUtf8("All Files") + " (*)");
294        sd.setNameFilters(filters);
295        sd.selectFile(selectedFile);
296        if (sd.exec() != QDialog::Accepted)
297                return;
298QStringList files = sd.selectedFiles();
299        if (files.empty())
300                return;
301        selectedFile = files.first();
302        QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
303#ifndef QT_NO_PRINTER
304        if (selectedFile.endsWith(".pdf",Qt::CaseInsensitive)) {
305QPrinter printer(QPrinter::HighResolution);
306                printer.setOutputFormat(QPrinter::PdfFormat);
307                printer.setOutputFileName(selectedFile);
308                solutionText->document()->print(&printer);
309                QApplication::restoreOverrideCursor();
310                return;
311        }
312#endif
313#if QT_VERSION >= 0x040500
314QTextDocumentWriter dw(selectedFile);
315        if (!(selectedFile.endsWith(".htm",Qt::CaseInsensitive) || selectedFile.endsWith(".html",Qt::CaseInsensitive) || selectedFile.endsWith(".odt",Qt::CaseInsensitive) || selectedFile.endsWith(".txt",Qt::CaseInsensitive)))
316                dw.setFormat("plaintext");
317        dw.write(solutionText->document());
318#else
319        // Qt < 4.5 has no QTextDocumentWriter class
320QFile file(selectedFile);
321        if (!file.open(QFile::WriteOnly)) {
322                QApplication::restoreOverrideCursor();
323                return;
324        }
325QTextStream ts(&file);
326        ts.setCodec(QTextCodec::codecForName("UTF-8"));
327        ts << solutionText->document()->toHtml("UTF-8");
328        file.close();
329#endif // QT_VERSION >= 0x040500
330        QApplication::restoreOverrideCursor();
331}
332
333bool MainWindow::saveTask() {
334QFileDialog sd(this);
335        sd.setAcceptMode(QFileDialog::AcceptSave);
336QStringList filters(trUtf8("%1 Task File").arg("TSPSG") + " (*.tspt)");
337        filters.append(trUtf8("All Files") + " (*)");
338        sd.setNameFilters(filters);
339        sd.setDefaultSuffix("tspt");
340        if (fileName.endsWith(".tspt",Qt::CaseInsensitive))
341                sd.selectFile(fileName);
342        else
343                sd.selectFile(QFileInfo(fileName).canonicalPath() + "/" + QFileInfo(fileName).completeBaseName() + ".tspt");
344        if (sd.exec() != QDialog::Accepted)
345                return false;
346QStringList files = sd.selectedFiles();
347        if (files.empty())
348                return false;
349        if (tspmodel->saveTask(files.first())) {
350                setFileName(files.first());
351                setWindowModified(false);
352                return true;
353        }
354        return false;
355}
356
357void MainWindow::actionSettingsPreferencesTriggered()
358{
359SettingsDialog sd(this);
360        if (sd.exec() != QDialog::Accepted)
361                return;
362        if (sd.colorChanged() || sd.fontChanged()) {
363                initDocStyleSheet();
364                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)) {
365                        QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
366                        solutionText->clear();
367                        solutionText->setHtml(output.join(""));
368                        QApplication::restoreOverrideCursor();
369                }
370        }
371}
372
373#ifndef QT_NO_PRINTER
374void MainWindow::printPreview(QPrinter *printer)
375{
376        solutionText->print(printer);
377}
378
379void MainWindow::actionFilePrintPreviewTriggered()
380{
381QPrintPreviewDialog ppd(printer, this);
382    connect(&ppd,SIGNAL(paintRequested(QPrinter *)),SLOT(printPreview(QPrinter *)));
383    ppd.exec();
384}
385
386void MainWindow::actionFilePrintTriggered()
387{
388QPrintDialog pd(printer,this);
389#if QT_VERSION >= 0x040500
390        // No such methods in Qt < 4.5
391        pd.setOption(QAbstractPrintDialog::PrintSelection,false);
392        pd.setOption(QAbstractPrintDialog::PrintPageRange,false);
393#endif
394        if (pd.exec() != QDialog::Accepted)
395                return;
396        QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
397        solutionText->document()->print(printer);
398        QApplication::restoreOverrideCursor();
399}
400#endif // QT_NO_PRINTER
401
402void MainWindow::buttonRandomClicked()
403{
404        QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
405        tspmodel->randomize();
406        QApplication::restoreOverrideCursor();
407}
408
409void MainWindow::buttonBackToTaskClicked()
410{
411        tabWidget->setCurrentIndex(0);
412}
413
414void MainWindow::outputMatrix(tMatrix matrix, QStringList &output, int nRow, int nCol)
415{
416int n = spinCities->value();
417QString line="";
418        output.append("<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\">");
419        for (int r = 0; r < n; r++) {
420                line = "<tr>";
421                for (int c = 0; c < n; c++) {
422                        if (matrix[r][c] == INFINITY)
423                                line += "<td align=\"center\">"INFSTR"</td>";
424                        else if ((r == nRow) && (c == nCol))
425                                line += "<td align=\"center\" class=\"selected\">" + QVariant(matrix[r][c]).toString() + "</td>";
426                        else
427                                line += "<td align=\"center\">" + QVariant(matrix[r][c]).toString() + "</td>";
428                }
429                line += "</tr>";
430                output.append(line);
431        }
432        output.append("</table>");
433}
434
435void MainWindow::buttonSolveClicked()
436{
437tMatrix matrix;
438QList<double> row;
439int n = spinCities->value();
440bool ok;
441        for (int r = 0; r < n; r++) {
442                row.clear();
443                for (int c = 0; c < n; c++) {
444                        row.append(tspmodel->index(r,c).data(Qt::UserRole).toDouble(&ok));
445                        if (!ok) {
446                                QMessageBox(QMessageBox::Critical,trUtf8("Data error"),trUtf8("Error in cell [Row %1; Column %2]: Invalid data format.").arg(r + 1).arg(c + 1),QMessageBox::Ok,this).exec();
447                                return;
448                        }
449                }
450                matrix.append(row);
451        }
452CTSPSolver solver;
453sStep *root = solver.solve(n,matrix,this);
454        if (!root)
455                return;
456        QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
457QColor color = settings->value("Output/Color",DEF_FONT_COLOR).value<QColor>();
458        output.clear();
459        output.append("<p>" + trUtf8("Variant #%1").arg(spinVariant->value()) + "</p>");
460        output.append("<p>" + trUtf8("Task:") + "</p>");
461        outputMatrix(matrix,output);
462        output.append("<hr>");
463        output.append("<p>" + trUtf8("Solution of Variant #%1 task").arg(spinVariant->value()) + "</p>");
464sStep *step = root;
465        n = 1;
466        while (n <= spinCities->value()) {
467                if (step->prNode->prNode != NULL || (step->prNode->prNode == NULL && step->plNode->prNode == NULL)) {
468                        if (n != spinCities->value()) {
469                                output.append("<p>" + trUtf8("Step #%1").arg(n++) + "</p>");
470                                outputMatrix(step->matrix,output,step->candidate.nRow,step->candidate.nCol);
471                                if (step->alts)
472                                        output.append("<p class=\"hasalts\">" + trUtf8("This step has alternate candidates for branching.") + "</p>");
473                                output.append("<p>&nbsp;</p>");
474                        }
475                }
476                if (step->prNode->prNode != NULL)
477                        step = step->prNode;
478                else if (step->plNode->prNode != NULL)
479                        step = step->plNode;
480                else
481                        break;
482        }
483        if (solver.isOptimal())
484                output.append("<p>" + trUtf8("Optimal path:") + "</p>");
485        else
486                output.append("<p>" + trUtf8("Resulting path:") + "</p>");
487        output.append("<p>&nbsp;&nbsp;" + solver.getSortedPath() + "</p>");
488        output.append("<p>" + trUtf8("The price is <b>%1</b> units.").arg(step->price) + "</p>");
489        if (!solver.isOptimal()) {
490                output.append("<p>&nbsp;</p>");
491                output.append("<p>" + trUtf8("<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>");
492        }
493        output.append("<p></p>");
494        solutionText->setHtml(output.join(""));
495        solutionText->setDocumentTitle(trUtf8("Solution of Variant #%1 task").arg(spinVariant->value()));
496
497        // Scrolling to the end of text.
498QTextCursor cursor(solutionText->textCursor());
499        cursor.movePosition(QTextCursor::End, QTextCursor::MoveAnchor);
500        solutionText->setTextCursor(cursor);
501
502        enableSolutionActions();
503        tabWidget->setCurrentIndex(1);
504        QApplication::restoreOverrideCursor();
505}
506
507void MainWindow::actionHelpAboutTriggered()
508{
509//! \todo TODO: Normal about window :-)
510QString about = QString::fromUtf8("TSPSG: TSP Solver and Generator\n");
511        about += QString::fromUtf8("    Version: "BUILD_VERSION"\n");
512        about += QString::fromUtf8("    Copyright (C) 2007-%1 Lёppa <contacts[at]oleksii[dot]name>\n").arg(QDate::currentDate().toString("yyyy"));
513        about += QString::fromUtf8("Target OS: %1\n").arg(OS);
514        about += "Qt library:\n";
515        about += QString::fromUtf8("    Compile time: %1\n").arg(QT_VERSION_STR);
516        about += QString::fromUtf8("    Runtime: %1\n").arg(qVersion());
517        about += QString::fromUtf8("Built on %1 at %2\n").arg(__DATE__).arg(__TIME__);
518        about += QString::fromUtf8(VERSIONID"\n\n");
519        about += QString::fromUtf8("Algorithm: %1\n").arg(CTSPSolver::getVersionId());
520        about += "\n";
521        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.";
522        QMessageBox(QMessageBox::Information,"About",about,QMessageBox::Ok,this).exec();
523}
524
525void MainWindow::loadLangList()
526{
527QSettings langinfo(PATH_I18N"/languages.ini",QSettings::IniFormat);
528#if QT_VERSION >= 0x040500
529        // In Qt < 4.5 QSettings doesn't have method setIniCodec.
530        langinfo.setIniCodec("UTF-8");
531#endif
532QDir dir(PATH_I18N,"*.qm",QDir::Name | QDir::IgnoreCase,QDir::Files);
533        if (!dir.exists())
534                return;
535QFileInfoList langs = dir.entryInfoList();
536        if (langs.size() <= 0)
537                return;
538QAction *a;
539        for (int k = 0; k < langs.size(); k++) {
540                QFileInfo lang = langs.at(k);
541                if (!lang.completeBaseName().startsWith("qt_") && lang.completeBaseName().compare("en")) {
542#if QT_VERSION >= 0x040500
543                        a = menuSettingsLanguage->addAction(langinfo.value(lang.completeBaseName() + "/NativeName",lang.completeBaseName()).toString());
544#else
545                        // We use Name if Qt < 4.5 because NativeName is in UTF-8, QSettings
546                        // reads .ini file as ASCII and there is no way to set file encoding.
547                        a = menuSettingsLanguage->addAction(langinfo.value(lang.completeBaseName() + "/Name",lang.completeBaseName()).toString());
548#endif
549                        a->setData(lang.completeBaseName());
550                        a->setCheckable(true);
551                        a->setActionGroup(groupSettingsLanguageList);
552                        if (settings->value("Language",QLocale::system().name()).toString().startsWith(lang.completeBaseName()))
553                                a->setChecked(true);
554                }
555        }
556}
557
558void MainWindow::actionSettingsLanguageAutodetectTriggered(bool checked)
559{
560        if (checked) {
561                settings->remove("Language");
562                QMessageBox(QMessageBox::Information,trUtf8("Language change"),trUtf8("Language will be autodetected on next application start."),QMessageBox::Ok,this).exec();
563        } else
564                settings->setValue("Language",groupSettingsLanguageList->checkedAction()->data().toString());
565}
566
567void MainWindow::groupSettingsLanguageListTriggered(QAction *action)
568{
569        if (actionSettingsLanguageAutodetect->isChecked()) {
570                // We have language autodetection. It needs to be disabled to change language.
571                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) {
572                        actionSettingsLanguageAutodetect->trigger();
573                } else
574                        return;
575        }
576bool untitled = (fileName == trUtf8("Untitled") + ".tspt");
577        if (loadLanguage(action->data().toString())) {
578                settings->setValue("Language",action->data().toString());
579                retranslateUi(this);
580                if (untitled)
581                        setFileName();
582        }
583}
584
585/*!
586 * \brief Handles Main Window close event.
587 * \param event Close event.
588 *
589 *  Checks whether or not a current task was saved and asks for saving if not.
590 *  Saves TSPSG settings.
591 */
592void MainWindow::closeEvent(QCloseEvent *event)
593{
594        if (!maybeSave()) {
595                event->ignore();
596                return;
597        }
598        settings->setValue("NumCities",spinCities->value());
599#ifndef Q_OS_WINCE
600        // Saving windows state
601        if (settings->value("SavePos",false).toBool()) {
602                settings->beginGroup("MainWindow");
603                settings->setValue("Maximized",isMaximized());
604                if (!isMaximized()) {
605                        settings->setValue("Size",size());
606                        settings->setValue("Position",pos());
607                }
608                settings->endGroup();
609        }
610#endif // Q_OS_WINCE
611        QMainWindow::closeEvent(event);
612}
613
614void MainWindow::dataChanged()
615{
616        setWindowModified(true);
617}
618
619void MainWindow::dataChanged(const QModelIndex &tl, const QModelIndex &br)
620{
621        setWindowModified(true);
622        if (settings->value("Autosize",true).toBool()) {
623                for (int k = tl.row(); k <= br.row(); k++)
624                        taskView->resizeRowToContents(k);
625                for (int k = tl.column(); k <= br.column(); k++)
626                        taskView->resizeColumnToContents(k);
627        }
628}
629
630void MainWindow::numCitiesChanged(int nCities)
631{
632        blockSignals(true);
633        spinCities->setValue(nCities);
634        blockSignals(false);
635}
Note: See TracBrowser for help on using the repository browser.