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

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