source: tspsg/src/mainwindow.cpp @ 0ac9690913

0.1.3.145-beta1-symbian0.1.4.170-beta2-bb10appveyorimgbotreadme
Last change on this file since 0ac9690913 was 0ac9690913, checked in by Oleksii Serdiuk, 14 years ago

+ Toolbar state and position is now saved and restored with Main Window state and position.

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