source: tspsg/src/mainwindow.cpp @ e0fcac5f2c

0.1.3.145-beta1-symbian0.1.4.170-beta2-bb10appveyorimgbotreadme
Last change on this file since e0fcac5f2c was e0fcac5f2c, checked in by Oleksii Serdiuk, 15 years ago
  • Finished documentation.
  • Sorted all functions in .cpp files according to order of their declaration in .h files.
  • Property mode set to 100644
File size: 23.1 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
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)
125{
126        if (!maybeSave()) {
127                event->ignore();
128                return;
129        }
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());
139                }
140                settings->endGroup();
141        }
142#endif // Q_OS_WINCE
143        QMainWindow::closeEvent(event);
144}
145
146/* Privates **********************************************************/
147
148void MainWindow::actionFileNewTriggered()
149{
150        if (!maybeSave())
151                return;
152        QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
153        tspmodel->clear();
154        setFileName();
155        setWindowModified(false);
156        tabWidget->setCurrentIndex(0);
157        solutionText->clear();
158        enableSolutionActions(false);
159        QApplication::restoreOverrideCursor();
160}
161
162void MainWindow::actionFileOpenTriggered()
163{
164        if (!maybeSave())
165                return;
166QFileDialog od(this);
167        od.setAcceptMode(QFileDialog::AcceptOpen);
168        od.setFileMode(QFileDialog::ExistingFile);
169QStringList filters(trUtf8("All Supported Formats") + " (*.tspt *.zkt)");
170        filters.append(trUtf8("%1 Task Files").arg("TSPSG") + " (*.tspt)");
171        filters.append(trUtf8("%1 Task Files").arg("ZKomModRd") + " (*.zkt)");
172        filters.append(trUtf8("All Files") + " (*)");
173        od.setNameFilters(filters);
174        if (od.exec() != QDialog::Accepted)
175                return;
176QStringList files = od.selectedFiles();
177        if (files.empty())
178                return;
179        if (!tspmodel->loadTask(files.first()))
180                return;
181        setFileName(files.first());
182        tabWidget->setCurrentIndex(0);
183        setWindowModified(false);
184        solutionText->clear();
185        enableSolutionActions(false);
186}
187
188void MainWindow::actionFileSaveTriggered()
189{
190        if ((fileName == trUtf8("Untitled") + ".tspt") || (!fileName.endsWith(".tspt",Qt::CaseInsensitive)))
191                saveTask();
192        else
193                if (tspmodel->saveTask(fileName))
194                        setWindowModified(false);
195}
196
197void MainWindow::actionFileSaveAsTaskTriggered()
198{
199        saveTask();
200}
201
202void MainWindow::actionFileSaveAsSolutionTriggered()
203{
204static QString selectedFile;
205        if (selectedFile.isEmpty())
206#ifndef QT_NO_PRINTER
207                selectedFile = "solution.pdf";
208#else
209                selectedFile = "solution.html";
210#endif // QT_NO_PRINTER
211QFileDialog sd(this);
212        sd.setAcceptMode(QFileDialog::AcceptSave);
213QStringList filters;
214#ifndef QT_NO_PRINTER
215        filters.append(trUtf8("PDF Files") + "(*.pdf)");
216#endif
217        filters.append(trUtf8("HTML Files") + " (*.html *.htm)");
218#if QT_VERSION >= 0x040500
219        filters.append(trUtf8("OpenDocument Files") + " (*.odt)");
220#endif // QT_VERSION >= 0x040500
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();
230        QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
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
241#if QT_VERSION >= 0x040500
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());
246#else
247        // Qt < 4.5 has no QTextDocumentWriter class
248QFile file(selectedFile);
249        if (!file.open(QFile::WriteOnly)) {
250                QApplication::restoreOverrideCursor();
251                return;
252        }
253QTextStream ts(&file);
254        ts.setCodec(QTextCodec::codecForName("UTF-8"));
255        ts << solutionText->document()->toHtml("UTF-8");
256        file.close();
257#endif // QT_VERSION >= 0x040500
258        QApplication::restoreOverrideCursor();
259}
260
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();
267}
268
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
285void MainWindow::actionSettingsPreferencesTriggered()
286{
287SettingsDialog sd(this);
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        }
299}
300
301void MainWindow::actionSettingsLanguageAutodetectTriggered(bool checked)
302{
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());
308}
309
310void MainWindow::groupSettingsLanguageListTriggered(QAction *action)
311{
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        }
326}
327
328void MainWindow::actionHelpAboutTriggered()
329{
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();
344}
345
346void MainWindow::buttonBackToTaskClicked()
347{
348        tabWidget->setCurrentIndex(0);
349}
350
351void MainWindow::buttonRandomClicked()
352{
353        QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
354        tspmodel->randomize();
355        QApplication::restoreOverrideCursor();
356}
357
358void MainWindow::buttonSolveClicked()
359{
360tMatrix matrix;
361QList<double> row;
362int n = spinCities->value();
363bool ok;
364        for (int r = 0; r < n; r++) {
365                row.clear();
366                for (int c = 0; c < n; c++) {
367                        row.append(tspmodel->index(r,c).data(Qt::UserRole).toDouble(&ok));
368                        if (!ok) {
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();
370                                return;
371                        }
372                }
373                matrix.append(row);
374        }
375CTSPSolver solver;
376sStep *root = solver.solve(n,matrix,this);
377        if (!root)
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        }
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>");
411        output.append("<p>" + trUtf8("The price is <b>%1</b> units.").arg(step->price) + "</p>");
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        }
416        output.append("<p></p>");
417        solutionText->setHtml(output.join(""));
418        solutionText->setDocumentTitle(trUtf8("Solution of Variant #%1 task").arg(spinVariant->value()));
419
420        // Scrolling to the end of text.
421QTextCursor cursor(solutionText->textCursor());
422        cursor.movePosition(QTextCursor::End, QTextCursor::MoveAnchor);
423        solutionText->setTextCursor(cursor);
424
425        enableSolutionActions();
426        tabWidget->setCurrentIndex(1);
427        QApplication::restoreOverrideCursor();
428}
429
430void MainWindow::dataChanged()
431{
432        setWindowModified(true);
433}
434
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
496void MainWindow::loadLangList()
497{
498QSettings langinfo(PATH_I18N"/languages.ini",QSettings::IniFormat);
499#if QT_VERSION >= 0x040500
500        // In Qt < 4.5 QSettings doesn't have method setIniCodec.
501        langinfo.setIniCodec("UTF-8");
502#endif
503QDir dir(PATH_I18N,"*.qm",QDir::Name | QDir::IgnoreCase,QDir::Files);
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);
512                if (!lang.completeBaseName().startsWith("qt_") && lang.completeBaseName().compare("en")) {
513#if QT_VERSION >= 0x040500
514                        a = menuSettingsLanguage->addAction(langinfo.value(lang.completeBaseName() + "/NativeName",lang.completeBaseName()).toString());
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
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
529bool MainWindow::loadLanguage(QString lang)
530{
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();
536        }
537static QTranslator *qtTranslator; // Qt library translator
538        if (qtTranslator) {
539                qApp->removeTranslator(qtTranslator);
540                delete qtTranslator;
541                qtTranslator = NULL;
542        }
543        qtTranslator = new QTranslator();
544static QTranslator *translator; // Application translator
545        if (translator) {
546                qApp->removeTranslator(translator);
547                delete translator;
548        }
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;
572                }
573        }
574        return true;
575}
576
577bool MainWindow::maybeSave()
578{
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;
588}
589
590void MainWindow::outputMatrix(tMatrix matrix, QStringList &output, int nRow, int nCol)
591{
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);
607        }
608        output.append("</table>");
609}
610
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)
636{
637        this->fileName = fileName;
638        setWindowTitle(QString("%1[*] - %2").arg(QFileInfo(fileName).completeBaseName()).arg(trUtf8("Travelling Salesman Problem")));
639}
Note: See TracBrowser for help on using the repository browser.