source: tspsg-svn/trunk/src/mainwindow.cpp @ 69

Last change on this file since 69 was 69, checked in by laleppa, 15 years ago

Made MainWindow::closeEvent() private.

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