source: tspsg/src/mainwindow.cpp @ 2fb523720a

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

+ Created installation (INSTALLS and DEPLOYMENT) entries for *nix, windows and wince platforms in tspsg.pro file. Now qmake generates install rules in Makefile.
+ Automatic resize of columns after their content changes can be turned on/off in settings now.

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