source: tspsg/src/mainwindow.cpp @ 899d1b8e15

0.1.3.145-beta1-symbian0.1.4.170-beta2-bb10appveyorimgbotreadme
Last change on this file since 899d1b8e15 was 899d1b8e15, checked in by Oleksii Serdiuk, 15 years ago

+ Selected application language is now saved and restored.
+ Added language selection entries to main menu.
+ On-the-fly language switching.
+ Loading corresponding Qt library language, if exists.

  • File/New? sets all table cells to zeros.
  • Translation updates to reflect recent changes.
  • Renamed language files from language names to language codes.
  • Renamed some slot to have unified signal/slot naming.
  • Printer settings are now persistant until application close.
  • Property mode set to 100644
File size: 9.6 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 <QtGui>
25#ifndef Q_OS_WINCE
26        #include <QPrintDialog>
27#endif // Q_OS_WINCE
28#include "mainwindow.h"
29
30MainWindow::MainWindow(QWidget *parent)
31        : QMainWindow(parent)
32{
33        settings = new QSettings(QSettings::IniFormat,QSettings::UserScope,"TSPSG","tspsg");
34        loadLanguage();
35        setupUi(this);
36#ifndef Q_OS_WINCE
37        printer = new QPrinter();
38#endif // Q_OS_WINCE
39        groupSettingsLanguageList = new QActionGroup(this);
40        loadLangList();
41        spinCities->setValue(settings->value("NumCities",5).toInt());
42        actionSettingsLanguageAutodetect->setChecked(settings->value("Language","").toString().isEmpty());
43        connect(actionFileNew,SIGNAL(triggered()),this,SLOT(actionFileNewTriggered()));
44        connect(actionSettingsPreferences,SIGNAL(triggered()),this,SLOT(actionSettingsPreferencesTriggered()));
45        connect(actionSettingsLanguageAutodetect,SIGNAL(triggered(bool)),this,SLOT(actionSettingsLanguageAutodetectTriggered(bool)));
46        connect(groupSettingsLanguageList,SIGNAL(triggered(QAction *)),this,SLOT(groupSettingsLanguageListTriggered(QAction *)));
47        connect(actionHelpAbout,SIGNAL(triggered()),this,SLOT(actionHelpAboutTriggered()));
48#ifndef Q_OS_WINCE
49        connect(actionFilePrintSetup,SIGNAL(triggered()),this,SLOT(actionFilePrintSetupTriggered()));
50#endif // Q_OS_WINCE
51        connect(buttonSolve,SIGNAL(clicked()),this,SLOT(buttonSolveClicked()));
52        connect(buttonRandom,SIGNAL(clicked()),this,SLOT(buttonRandomClicked()));
53        connect(spinCities,SIGNAL(valueChanged(int)),this,SLOT(spinCitiesValueChanged(int)));
54QRect rect = geometry();
55#ifdef Q_OS_WINCE
56        // HACK: Fix for all tabWidget elements becoming "unclickable" if making it central widget.
57        rect.setSize(QApplication::desktop()->availableGeometry().size());
58        rect.setHeight(rect.height() - (QApplication::desktop()->screenGeometry().height() - QApplication::desktop()->availableGeometry().height()));
59        tabWidget->resize(rect.width(),rect.height() - toolBar->size().height());
60#else
61        if (settings->value("SavePos",false).toBool()) {
62                // Loading of saved window state
63                settings->beginGroup("MainWindow");
64                resize(settings->value("Size",size()).toSize());
65                move(settings->value("Position",pos()).toPoint());
66                if (settings->value("Maximized",false).toBool())
67                        setWindowState(windowState() | Qt::WindowMaximized);
68                settings->endGroup();
69        } else {
70                // Centering main window
71                rect.moveCenter(QApplication::desktop()->availableGeometry(this).center());
72                setGeometry(rect);
73        }
74#endif // Q_OS_WINCE
75        qsrand(QDateTime().currentDateTime().toTime_t());
76        tspmodel = new CTSPModel();
77        tspmodel->setNumCities(spinCities->value());
78        taskView->setModel(tspmodel);
79#ifdef Q_OS_WINCE
80        taskView->resizeColumnsToContents();
81        taskView->resizeRowsToContents();
82#endif // Q_OS_WINCE
83}
84
85bool MainWindow::loadLanguage()
86{
87// i18n
88bool ad = settings->value("Language","").toString().isEmpty();
89QString lang = settings->value("Language",QLocale::system().name()).toString();
90static QTranslator *qtTranslator;
91        if (qtTranslator) {
92                qApp->removeTranslator(qtTranslator);
93                delete qtTranslator;
94                qtTranslator = NULL;
95        }
96        qtTranslator = new QTranslator();
97        if (lang.compare("en") && !lang.startsWith("en_")) {
98                // Trying to load system Qt library translation...
99                if (qtTranslator->load("qt_" + lang,QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
100                        qApp->installTranslator(qtTranslator);
101                else
102                        // No luck. Let's try to load bundled one.
103                        if (qtTranslator->load("qt_" + lang,"i18n"))
104                                qApp->installTranslator(qtTranslator);
105                        else {
106                                delete qtTranslator;
107                                qtTranslator = NULL;
108                        }
109        }
110        // Now let's load application translation.
111static QTranslator *translator;
112        if (translator) {
113                qApp->removeTranslator(translator);
114                delete translator;
115        }
116        translator = new QTranslator();
117        if (lang.compare("en") && !lang.startsWith("en_")) {
118                if (translator->load(lang,"i18n"))
119                        qApp->installTranslator(translator);
120                else {
121                        if (!ad)
122                                QMessageBox(QMessageBox::Warning,trUtf8("Language change"),trUtf8("Unable to load translation language."),QMessageBox::Ok,this).exec();
123                        delete translator;
124                        translator = NULL;
125                        return false;
126                }
127        }
128        return true;
129}
130
131void MainWindow::spinCitiesValueChanged(int n)
132{
133#ifdef Q_OS_WINCE
134int count = tspmodel->numCities();
135#endif // Q_OS_WINCE
136        tspmodel->setNumCities(n);
137#ifdef Q_OS_WINCE
138        if (n > count)
139                for (int k = count; k < n; k++) {
140                        taskView->resizeColumnToContents(k);
141                        taskView->resizeRowToContents(k);
142                }
143#endif // Q_OS_WINCE
144}
145
146
147void MainWindow::actionFileNewTriggered()
148{
149        tspmodel->clear();
150}
151
152void MainWindow::actionSettingsPreferencesTriggered()
153{
154SettingsDialog sd(this);
155        sd.exec();
156}
157
158#ifndef Q_OS_WINCE
159void MainWindow::actionFilePrintSetupTriggered()
160{
161QPrintDialog pd(printer,this);
162        pd.setOption(QAbstractPrintDialog::PrintSelection,false);
163        pd.setOption(QAbstractPrintDialog::PrintPageRange,false);
164        pd.exec();
165}
166#endif // Q_OS_WINCE
167
168void MainWindow::buttonRandomClicked()
169{
170        tspmodel->randomize();
171#ifdef Q_OS_WINCE
172        taskView->resizeColumnsToContents();
173        taskView->resizeRowsToContents();
174#endif // Q_OS_WINCE
175}
176
177void MainWindow::buttonSolveClicked()
178{
179        // TODO: Task solving goes here :-)
180tMatrix matrix;
181double *row;
182int n = spinCities->value();
183bool ok;
184        for (int r = 0; r < n; r++) {
185                row = new double[n];
186                for (int c = 0; c < n; c++) {
187                        row[c] = tspmodel->index(r,c).data(Qt::UserRole).toDouble(&ok);
188                        if (!ok) {
189                                QMessageBox(QMessageBox::Critical,trUtf8("Data error"),QString(trUtf8("Error in cell [Row %1; Column %2]: Invalid data format.")).arg(r + 1).arg(c + 1),QMessageBox::Ok,this).exec();
190                                return;
191                        }
192                }
193                matrix.append(row);
194        }
195CTSPSolver solver;
196sStep *root = solver.solve(spinCities->value(),matrix);
197        if (!root)
198                QMessageBox(QMessageBox::Critical,trUtf8("Solution error"),trUtf8("There was an error while solving the task."),QMessageBox::Ok,this).exec();
199        // tabWidget->setCurrentIndex(1);
200}
201
202void MainWindow::actionHelpAboutTriggered()
203{
204        // TODO: Normal about window :-)
205QString about = QString::fromUtf8("TSPSG - TSP Solver and Generator\n\
206    Copyright (C) 2007-%1 Lёppa <contacts[at]oleksii[dot]name>\n\
207Qt library versions:\n\
208    Compile time: %2\n\
209    Runtime: %3\n\
210\n\
211TSPSG 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.").arg(QDate().toString("%Y"),QT_VERSION_STR,qVersion());
212        QMessageBox(QMessageBox::Information,"About",about,QMessageBox::Ok,this).exec();
213}
214
215void MainWindow::loadLangList()
216{
217QSettings langinfo("i18n/languages.ini",QSettings::IniFormat);
218        langinfo.setIniCodec("UTF-8");
219QDir dir("i18n","*.qm",QDir::Name | QDir::IgnoreCase,QDir::Files);
220        if (!dir.exists())
221                return;
222QFileInfoList langs = dir.entryInfoList();
223        if (langs.size() <= 0)
224                return;
225        menuSettingsLanguage->addSeparator();
226QAction *a;
227        for (int k = 0; k < langs.size(); k++) {
228                QFileInfo lang = langs.at(k);
229                if (!lang.completeBaseName().startsWith("qt_")) {
230                        a = menuSettingsLanguage->addAction(langinfo.value(lang.completeBaseName() + "/NativeName",lang.completeBaseName()).toString());
231                        a->setData(lang.completeBaseName());
232                        a->setCheckable(true);
233                        a->setActionGroup(groupSettingsLanguageList);
234                        if (settings->value("Language",QLocale::system().name()).toString().startsWith(lang.completeBaseName()))
235                                a->setChecked(true);
236                }
237        }
238}
239
240void MainWindow::actionSettingsLanguageAutodetectTriggered(bool checked)
241{
242        if (checked) {
243                settings->remove("Language");
244                QMessageBox(QMessageBox::Information,trUtf8("Language change"),trUtf8("Language will be autodetected on next application start."),QMessageBox::Ok,this).exec();
245        } else
246                settings->setValue("Language",groupSettingsLanguageList->checkedAction()->data().toString());
247}
248
249void MainWindow::groupSettingsLanguageListTriggered(QAction *action)
250{
251        if (actionSettingsLanguageAutodetect->isChecked()) {
252                // We have language autodetection. It needs to be disabled to change language.
253                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) {
254                        actionSettingsLanguageAutodetect->trigger();
255                } else
256                        return;
257        }
258        if (loadLanguage()) {
259                settings->setValue("Language",action->data().toString());
260                retranslateUi(this);
261        } else {
262        }
263}
264
265void MainWindow::closeEvent(QCloseEvent *event)
266{
267        settings->setValue("NumCities",spinCities->value());
268#ifndef Q_OS_WINCE
269        // Saving windows state
270        if (settings->value("SavePos",false).toBool()) {
271                settings->beginGroup("MainWindow");
272                settings->setValue("Maximized",isMaximized());
273                if (!isMaximized()) {
274                        settings->setValue("Size",size());
275                        settings->setValue("Position",pos());
276                }
277                settings->endGroup();
278        }
279#endif // Q_OS_WINCE
280        QMainWindow::closeEvent(event);
281}
Note: See TracBrowser for help on using the repository browser.