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

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

+ PDF format option when saving solution if platform supports printing.

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