Subversion Repositories public

Rev

Rev 274 | Rev 276 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
88 andreas 1
/***************************************************************************
221 andreas 2
 *   Copyright (C) 2007 - 2009 by Andreas Theofilu                         *
119 andreas 3
 *   andreas@theosys.at                                                    *
88 andreas 4
 *                                                                         *
5
 *   This program is free software; you can redistribute it and/or modify  *
6
 *   it under the terms of the GNU General Public License as published by  *
7
 *   the Free Software Foundation version 3 of the License.                *
8
 *                                                                         *
9
 *   This program is distributed in the hope that it will be useful,       *
10
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
11
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
12
 *   GNU General Public License for more details.                          *
13
 *                                                                         *
14
 *   You should have received a copy of the GNU General Public License     *
15
 *   along with this program; if not, write to the                         *
16
 *   Free Software Foundation, Inc.,                                       *
17
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
18
 ***************************************************************************/
19
 
119 andreas 20
#include "config.h"
88 andreas 21
#include "managefile.h"
22
#include "sportwatcherwidget.h"
23
#include "settingswidget.h"
96 andreas 24
#include "progresswidget.h"
152 andreas 25
#include "wmsbase.h"
158 andreas 26
#include "coordinateswidget.h"
274 andreas 27
#include "shapewidget.h"
151 andreas 28
#include <string.h>
96 andreas 29
 
137 andreas 30
#include <iostream>
88 andreas 31
#include <kfiledialog.h>
32
#include <kmessagebox.h>
232 andreas 33
#include <KConfig>
88 andreas 34
#include <klocale.h>
232 andreas 35
#include <k3listview.h>
100 andreas 36
#include <kaboutdata.h>
232 andreas 37
#include <kaboutapplicationdialog.h>
218 andreas 38
#include <kinputdialog.h>
128 andreas 39
#include <kglobalsettings.h>
218 andreas 40
#include <kcombobox.h>
154 andreas 41
#include <qapplication.h>
88 andreas 42
#include <qstring.h>
43
#include <qdatetime.h>
109 andreas 44
#include <qtoolbutton.h>
132 andreas 45
#include <qcursor.h>
172 andreas 46
#include <qregexp.h>
232 andreas 47
#include <QMouseEvent>
246 andreas 48
#include <QRect>
49
#include <QRegion>
245 andreas 50
#include <KIcon>
151 andreas 51
 
232 andreas 52
#if defined HAVE_GDAL
158 andreas 53
   #include <gdal/ogr_spatialref.h>
54
   #include <gdal/ogrsf_frmts.h>
55
   #include <gdal/gdalwarper.h>
165 andreas 56
   #include <gdal/ogrsf_frmts.h>
157 andreas 57
#endif
58
 
218 andreas 59
#include "garmin.h"
158 andreas 60
#include "transform.h"
217 andreas 61
#include "import.h"
274 andreas 62
#include "render.h"
88 andreas 63
 
232 andreas 64
//#define DEBUG	1
151 andreas 65
 
137 andreas 66
using std::cout;
158 andreas 67
using std::cerr;
68
using std::clog;
137 andreas 69
using std::endl;
70
 
71
 
104 andreas 72
typedef struct
73
{
74
	double lon;
75
	double lat;
76
} posn_type;
77
 
245 andreas 78
sportwatcherWidget::sportwatcherWidget(QWidget *parent)
88 andreas 79
{
245 andreas 80
	ui_sportwatcherWidgetBase.setupUi(this);
232 andreas 81
 
82
#if defined HAVE_GDAL
157 andreas 83
	mFactor = 10;		// Factor to calculate square pixels
84
#endif
88 andreas 85
	mama = parent;
86
	gmn = 0;
87
	min_hr = max_hr = avg_hr = 0;
88
	min_height = max_height = 0.0;
89
	max_time = 0;
104 andreas 90
	zfactor = 0;
132 andreas 91
	mapLap = 0;
92
	mapPan = QRect(0, 0, 0, 0);
93
	stateHand = stateFlag = stateGlas = false;
94
	oldTransX = oldTransY = 0.0;
95
	lmbPressed = 0;
246 andreas 96
	DIRTY = true;
248 andreas 97
	curTab = ui_sportwatcherWidgetBase.tabView->currentIndex();
98
	tabDirt0 = tabDirt1 = tabDirt2 = tabDirt3 = true;
230 andreas 99
	kl = new KLocale(QString("kdesktop"), 0);
132 andreas 100
 
88 andreas 101
	// Load the config parameters
232 andreas 102
	KConfig cfg (QString("sportwatcher.rc"), KConfig::SimpleConfig);
103
	KConfigGroup ic (&cfg, "SportWatcher");
104
	lower1 = ic.readEntry("lower1", 0);
105
	lower2 = ic.readEntry("lower2", 0);
106
	lower3 = ic.readEntry("lower3", 0);
107
	upper1 = ic.readEntry("upper1", 0);
108
	upper2 = ic.readEntry("upper2", 0);
109
	upper3 = ic.readEntry("upper3", 0);
110
	MaxHr = ic.readEntry("maxHr", 180);
111
	restHr = ic.readEntry("restHr", 60);
112
	vo2max = ic.readEntry("vo2max", 50);
113
	weight = ic.readEntry("weight", 70);
114
	sampleTime = ic.readEntry("seconds", 15);
115
	Serial = ic.readEntry("Serial", false);
116
	Forerunner = ic.readEntry("Forerunner", false);
117
	Contour = ic.readEntry("Contour", false);
118
	Device = ic.readEntry("Device", "/dev/ttyUSB0");
119
	Data = ic.readEntry("Data", QDir::home().absolutePath() + "/.sportwatcher");
120
	HRM = ic.readEntry("HRM", QDir::home().absolutePath() + "/polar");
121
	MAP = ic.readEntry("MAP", QDir::home().absolutePath() + "/.sportwatcher/track.wms");
122
	Units = ic.readEntry("Units", 0);
123
	MapType = ic.readEntry("MapType", 7);
88 andreas 124
}
125
 
126
sportwatcherWidget::~sportwatcherWidget()
127
{
104 andreas 128
	destroy();
230 andreas 129
	delete kl;
88 andreas 130
}
131
 
100 andreas 132
void sportwatcherWidget::destroy()
133
{
134
	if (gmn)
135
	   garmin_free_data (gmn);
136
 
137
	gmn = 0;
132 andreas 138
	oldTransX = oldTransY = 0.0;
100 andreas 139
}
140
 
245 andreas 141
void sportwatcherWidget::Initialize()
142
{
143
	// Set some widget settings
144
	ui_sportwatcherWidgetBase.btHand->setIcon(KIcon("hand"));
145
	ui_sportwatcherWidgetBase.btGlas->setIcon(KIcon("glas"));
146
	ui_sportwatcherWidgetBase.btGlasMinus->setIcon(KIcon("glas_minus"));
147
	ui_sportwatcherWidgetBase.btGlasPlus->setIcon(KIcon("glas_plus"));
148
	ui_sportwatcherWidgetBase.btFlag->setIcon(KIcon("flag"));
149
	ui_sportwatcherWidgetBase.btFullscreen->setIcon(KIcon("fullscreen"));
248 andreas 150
 
151
	if (curTab != 0)
152
	{
153
	   ui_sportwatcherWidgetBase.tabView->setCurrentIndex(0);
154
	   curTab = ui_sportwatcherWidgetBase.tabView->currentIndex();
155
	}
156
 
245 andreas 157
//	btHand->setToggleButton(true);
158
//	btGlas->setToggleButton(true);
159
	// Fill the activities
160
	getActivities();
161
#if defined HAVE_GDAL
162
	// Initialize the GDAL
163
	GDALAllRegister();
164
	poDataset = 0;
165
#endif
166
}
167
 
247 andreas 168
QTreeWidgetItem *sportwatcherWidget::findElement(QTreeWidget *wdg, const QString &val)
132 andreas 169
{
247 andreas 170
QTreeWidgetItem *item, *child, *subchild;
132 andreas 171
 
246 andreas 172
	if (!wdg)
247 andreas 173
	   return 0;
246 andreas 174
 
175
	for (int a = 0; a < wdg->topLevelItemCount(); a++)
132 andreas 176
	{
246 andreas 177
	   if (!(item = wdg->topLevelItem(a)))
178
	      continue;
132 andreas 179
 
246 andreas 180
	   for (int j = 0; j < item->childCount(); j++)
181
	   {
182
	      if (!(child = item->child(j)))
183
		 continue;
184
 
185
	      if (child->data(0, Qt::UserRole).toString() == val)
247 andreas 186
		 return child;
187
 
188
	      for (int i = 0; i < child->childCount(); i++)
189
	      {
190
		 if (!(subchild = child->child(i)))
191
		    continue;
192
 
193
		 if (subchild->data(0, Qt::UserRole).toString() == val)
194
		    return subchild;
195
	      }
246 andreas 196
	   }
132 andreas 197
	}
198
 
247 andreas 199
	return 0;
132 andreas 200
}
201
 
88 andreas 202
/*
203
 * Search for a directory named .sportwatcher in the home directory of
204
 * the user and search for *.gmn files. Open the files and read the header
205
 * to find the basic data of activities. Then add the information into
206
 * the activities KListView.
207
 */
208
void sportwatcherWidget::getActivities()
209
{
210
QString path, txt;
232 andreas 211
QDir mdir, dir = QDir::home();
88 andreas 212
QStringList years, months;
247 andreas 213
QTreeWidgetItem *running, *biking, *other, *year_run, *year_bike, *year_other;
246 andreas 214
QTreeWidgetItem *el;
215
QList<QTreeWidgetItem *> item;
232 andreas 216
int i, j;
247 andreas 217
int y_run, y_bike, y_other;
88 andreas 218
RUN_NODE *rn;
219
LAP *lap;
220
 
221
	if (Data.isEmpty())
222
	{
232 andreas 223
	   path = dir.homePath();
88 andreas 224
	   path.append("/.sportwatcher");
225
	}
226
	else
227
	   path = Data;
228
 
229
	dir.setPath(path);
132 andreas 230
	dir.refresh();
88 andreas 231
 
232
	if (!dir.exists())
233
	{
234
	   dir.mkdir(path);
235
	   return;
236
	}
237
 
132 andreas 238
	destroy();
128 andreas 239
 
245 andreas 240
	if (!ui_sportwatcherWidgetBase.liActivities)
241
	{
242
	   KMessageBox::error(this, i18n("Error initializing some widgets of main window!"));
243
	   return;
244
	}
245
 
246
	ui_sportwatcherWidgetBase.liActivities->clear();
246 andreas 247
	ui_sportwatcherWidgetBase.liActivities->setSortingEnabled(false);
248
	ui_sportwatcherWidgetBase.liActivities->setColumnCount(1);
245 andreas 249
 
246 andreas 250
	running = new QTreeWidgetItem(ui_sportwatcherWidgetBase.liActivities);
251
	biking = new QTreeWidgetItem(ui_sportwatcherWidgetBase.liActivities);
252
	other = new QTreeWidgetItem(ui_sportwatcherWidgetBase.liActivities);
253
 
245 andreas 254
	if (!other || !biking || !running)
255
	{
256
	   KMessageBox::error(this, i18n("Not enough memory to initilize application!"));
257
	   return;
258
	}
259
 
246 andreas 260
	running->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
261
	biking->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
262
	other->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
128 andreas 263
 
246 andreas 264
	running->setText(0, i18n("Running"));
265
	biking->setText(0, i18n("Biking"));
266
	other->setText(0, i18n("Others"));
88 andreas 267
 
246 andreas 268
	KIcon fld(QString("history"));
269
	running->setIcon(0, fld);
270
	biking->setIcon(0, fld);
271
	other->setIcon(0, fld);
272
 
273
	running->setStatusTip(0, i18n("\"Running\" activities."));
274
	biking->setStatusTip(0, i18n("\"Biking\" activities."));
275
	other->setStatusTip(0, i18n("\"Other\" and \"Multisport\" activities."));
276
 
88 andreas 277
	dir.cd(path);
278
	dir.setFilter(QDir::Dirs | QDir::NoSymLinks);
279
	dir.setSorting(QDir::Name);
132 andreas 280
	dir.refresh();
232 andreas 281
	QFileInfoList list = dir.entryInfoList();
88 andreas 282
 
232 andreas 283
	if (!list.size())
88 andreas 284
	   return;
285
 
232 andreas 286
	for (i = 0; i < list.size(); i++)		// Years
287
	{
288
	QFileInfo fileInfo = list.at(i);
88 andreas 289
 
232 andreas 290
	   if (fileInfo.fileName() == QString(".") || fileInfo.fileName() == QString(".."))
88 andreas 291
	      continue;
292
 
232 andreas 293
	   years += fileInfo.absoluteFilePath();
88 andreas 294
	}
295
 
232 andreas 296
	for (i = 0; i < years.size(); ++i)
88 andreas 297
	{
232 andreas 298
	   if (months.size() > 0)
88 andreas 299
	      months.clear();
300
 
232 andreas 301
	   dir.setPath(years.at(i));
132 andreas 302
	   dir.refresh();
232 andreas 303
	   list = dir.entryInfoList();
88 andreas 304
 
232 andreas 305
	   if (!list.size())
88 andreas 306
	      continue;
307
 
232 andreas 308
	   for (j = 0; j < list.size(); j++)		// Months
309
	   {
310
	   QFileInfo fileInfo = list.at(j);
88 andreas 311
 
232 andreas 312
	      if (fileInfo.fileName() == QString(".") || fileInfo.fileName() == QString(".."))
88 andreas 313
		 continue;
314
 
232 andreas 315
	      months += fileInfo.absoluteFilePath();
88 andreas 316
	   }
317
 
232 andreas 318
	   for (j = 0; j < months.size(); ++j)
88 andreas 319
	   {
232 andreas 320
	      mdir.setPath(months.at(j));
321
	      mdir.cd(months.at(j));
88 andreas 322
	      mdir.setFilter(QDir::Files | QDir::NoSymLinks);
246 andreas 323
	      mdir.setSorting(QDir::Name);
232 andreas 324
	      mdir.setNameFilters(QStringList("*.gmn"));
132 andreas 325
	      mdir.refresh();
232 andreas 326
	      list = mdir.entryInfoList();
88 andreas 327
 
232 andreas 328
	      if (!list.size())
88 andreas 329
		 continue;
330
 
232 andreas 331
	      for (int a = 0; a < list.size(); a++)		// Files
332
	      {
333
	      QFileInfo fileInfo = list.at(a);
88 andreas 334
 
232 andreas 335
		 files += fileInfo.absoluteFilePath();
88 andreas 336
	      }
337
	   }
338
	}
339
 
247 andreas 340
	y_run = y_bike = y_other = 0;
341
	year_run = year_bike = year_other = 0;
88 andreas 342
	// Open every file and read its head
232 andreas 343
	for (i = 0; i < files.size(); ++i)
88 andreas 344
	{
247 andreas 345
	QTreeWidgetItem *yr, *yb, *yo;
132 andreas 346
 
246 andreas 347
	   if (findElement(ui_sportwatcherWidgetBase.liActivities, files.at(i)))
348
	      continue;
349
 
88 andreas 350
	   spw.destroy();
351
 
232 andreas 352
	   if (spw.setFileName(files.at(i).toAscii().constData()) == -1)
88 andreas 353
	      return;
354
 
355
	   if (gmn)
246 andreas 356
	   {
88 andreas 357
	      garmin_free_data (gmn);
246 andreas 358
	      gmn = 0;
359
	   }
88 andreas 360
 
246 andreas 361
	   if (!(gmn = spw.readFile()))
362
	      continue;
363
 
88 andreas 364
	   ds.destroy();
365
	   ds.garmin_print_data(gmn);
366
	   rn = ds.getRunNode();
367
 
245 andreas 368
	   if (!rn)
369
	      return;
370
 
88 andreas 371
	   lap = ds.getLap(rn->run->first_lap_index);
245 andreas 372
 
373
	   if (!lap)
374
	      return;
375
 
88 andreas 376
	   const QDateTime *qt = garmin_dtime (lap->start_time);
232 andreas 377
	   // By default set the name of the session to the date and time
378
	   // it was recorded.
379
	   QString idx = kl->formatDateTime (*qt, KLocale::ShortDate, true);
248 andreas 380
	   QString stTip = kl->formatDateTime (*qt, KLocale::LongDate, true);
88 andreas 381
 
232 andreas 382
	   // If we have a custom name for this session, set it.
217 andreas 383
	   if (strlen (rn->run->workout.name) > 1 && strlen (rn->run->workout.name) < 16 && isalpha (rn->run->workout.name[0]))
232 andreas 384
	      idx = QString (rn->run->workout.name);
217 andreas 385
 
88 andreas 386
	   switch (rn->run->sport_type)
387
	   {
388
	      case D1000_running:
247 andreas 389
		 yr = findElement(ui_sportwatcherWidgetBase.liActivities, QString("run_%1").arg(qt->date().year()));
390
 
391
		 if (!yr && qt->date().year() != y_run)
392
		 {
393
		    year_run = new QTreeWidgetItem(running, running);
394
		    y_run = qt->date().year();
395
		    year_run->setText(0, QString("%1").arg(y_run));
396
		    year_run->setData(0, Qt::UserRole, QString("run_%1").arg(y_run));
397
		    year_run->setIcon(0, KIcon(QString("today")));
398
		    year_run->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable);
399
		 }
400
		 else
401
		    year_run = yr;
402
 
403
		 el = new QTreeWidgetItem(year_run, year_run);
246 andreas 404
		 el->setText(0, idx);
405
		 el->setData(0, Qt::UserRole, files.at(i));
247 andreas 406
		 el->setIcon(0, KIcon(QString("spw-running")));
246 andreas 407
		 el->setStatusTip(0, stTip);
408
		 el->setToolTip(0, stTip);
409
		 el->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable);
88 andreas 410
	      break;
411
 
412
	      case D1000_biking:
247 andreas 413
		 yb = findElement(ui_sportwatcherWidgetBase.liActivities, QString("bike_%1").arg(qt->date().year()));
414
 
415
		 if (!yb && qt->date().year() != y_bike)
416
		 {
417
		    year_bike = new QTreeWidgetItem(biking, biking);
418
		    y_bike = qt->date().year();
419
		    year_bike->setText(0, QString("%1").arg(y_bike));
420
		    year_bike->setData(0, Qt::UserRole, QString("bike_%1").arg(y_run));
421
		    year_bike->setIcon(0, KIcon(QString("today")));
422
		    year_bike->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable);
423
		 }
424
		 else
425
		    year_bike = yb;
426
 
427
		 el = new QTreeWidgetItem(year_bike, year_bike);
246 andreas 428
		 el->setText(0, idx);
429
		 el->setData(0, Qt::UserRole, files.at(i));
430
		 el->setStatusTip(0, stTip);
431
		 el->setToolTip(0, stTip);
432
		 el->setIcon(0, KIcon(QString("bike")));
433
		 el->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable);
88 andreas 434
	      break;
435
 
436
	      case D1000_other:
247 andreas 437
	      default:
438
		 yo = findElement(ui_sportwatcherWidgetBase.liActivities, QString("other_%1").arg(qt->date().year()));
88 andreas 439
 
247 andreas 440
		 if (!yo && qt->date().year() != y_other)
441
		 {
442
		    year_other = new QTreeWidgetItem(other, other);
443
		    y_other = qt->date().year();
444
		    year_other->setText(0, QString("%1").arg(y_other));
445
		    year_other->setData(0, Qt::UserRole, QString("other_%1").arg(y_run));
446
		    year_other->setIcon(0, KIcon(QString("today")));
447
		    year_other->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable);
448
		 }
449
		 else
450
		    year_other = yo;
451
 
452
		 el = new QTreeWidgetItem(year_other, year_other);
246 andreas 453
		 el->setText(0, idx);
454
		 el->setData(0, Qt::UserRole, files.at(i));
455
		 el->setStatusTip(0, stTip);
456
		 el->setToolTip(0, stTip);
457
		 el->setIcon(0, KIcon(QString("other")));
458
		 el->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable);
88 andreas 459
	   }
460
 
461
	   delete qt;
462
	}
463
 
246 andreas 464
	ui_sportwatcherWidgetBase.liActivities->setItemExpanded(running, true);
88 andreas 465
 
247 andreas 466
	if (year_run)
467
	   ui_sportwatcherWidgetBase.liActivities->setItemExpanded(year_run, true);
468
 
88 andreas 469
	if (gmn)
470
	   garmin_free_data (gmn);
471
 
472
	gmn = 0;
473
}
474
 
475
/*$SPECIALIZATION$*/
476
void sportwatcherWidget::btFullscreenSlot()
477
{
132 andreas 478
	oldTransX = oldTransY = 0.0;
479
	mapPan.setCoords(0, 0, 0, 0);
246 andreas 480
	DIRTY = true;
104 andreas 481
	showTrack(0);
246 andreas 482
	DIRTY = false;
88 andreas 483
}
484
 
485
void sportwatcherWidget::btGlasMinusSlot()
486
{
132 andreas 487
bool sh = stateHand;
488
 
489
	stateHand = false;
246 andreas 490
	DIRTY = true;
104 andreas 491
	showTrack(zfactor - 1000);
246 andreas 492
	DIRTY = false;
132 andreas 493
	stateHand = sh;
88 andreas 494
}
495
 
496
void sportwatcherWidget::btGlasPlusSlot()
497
{
132 andreas 498
bool sh = stateHand;
499
 
500
	stateHand = false;
246 andreas 501
	DIRTY = true;
104 andreas 502
	showTrack(zfactor + 1000);
246 andreas 503
	DIRTY = false;
132 andreas 504
	stateHand = sh;
88 andreas 505
}
506
 
507
void sportwatcherWidget::btHandSlot()
508
{
132 andreas 509
QCursor cs;
510
 
511
	if (stateGlas)
512
	{
513
	   stateGlas = false;
245 andreas 514
	   ui_sportwatcherWidgetBase.btGlas->toggle();
132 andreas 515
	}
516
 
517
	stateHand = (stateHand) ? false : true;
518
 
519
	if (stateHand)
232 andreas 520
	   cs.setShape(Qt::PointingHandCursor);
132 andreas 521
	else
232 andreas 522
	   cs.setShape(Qt::ArrowCursor);
132 andreas 523
 
245 andreas 524
	ui_sportwatcherWidgetBase.imgMap->setCursor(cs);
88 andreas 525
}
526
 
527
void sportwatcherWidget::btGlasSlot()
528
{
132 andreas 529
QCursor cs;
530
 
531
	if (stateHand)
532
	{
533
	   stateHand = false;
245 andreas 534
	   ui_sportwatcherWidgetBase.btHand->toggle();
132 andreas 535
	}
536
 
537
	stateGlas = (stateGlas) ? false : true;
538
 
539
	if (stateGlas)
232 andreas 540
	   cs.setShape(Qt::ForbiddenCursor);
132 andreas 541
	else
232 andreas 542
	   cs.setShape(Qt::ArrowCursor);
132 andreas 543
 
245 andreas 544
	ui_sportwatcherWidgetBase.imgMap->setCursor(cs);
88 andreas 545
}
546
 
547
void sportwatcherWidget::btFlagSlot()
548
{
549
}
550
 
232 andreas 551
void sportwatcherWidget::liLapsSlot(Q3ListViewItem *item)
88 andreas 552
{
132 andreas 553
QString sl;
554
int l;
555
int idx;
556
RUN_NODE *rn;
557
LAP *lap;
558
 
559
	if (!item)
560
	   return;
561
 
246 andreas 562
	DIRTY = true;
132 andreas 563
	sl = item->text(0).mid(4, 3);
564
	l = sl.toInt();
565
 
566
	if (l <= 0)
567
	{
245 andreas 568
	   // Show the whole map and track
132 andreas 569
	   showTrack(zfactor, mapPan, 0);
245 andreas 570
	   // Don't mark any lap. Just display normal.
148 andreas 571
	   showCurves(0);
132 andreas 572
	   return;
573
	}
574
 
575
	rn = ds.getRunNode();
576
	idx = rn->run->first_lap_index;
577
	lap = ds.getLap(idx + l - 1);
245 andreas 578
	// Show the part of the track, corresponding to the selected lap
132 andreas 579
	showTrack(zfactor, mapPan, lap);
245 andreas 580
	// Mark the selected lap
148 andreas 581
	showCurves(lap);
246 andreas 582
	DIRTY = false;
88 andreas 583
}
584
 
246 andreas 585
void sportwatcherWidget::liActivitiesSlot(QTreeWidgetItem *item, int)
88 andreas 586
{
587
	if (!item)
588
	   return;
589
 
245 andreas 590
	spw.destroy();
88 andreas 591
 
246 andreas 592
	if (spw.setFileName(item->data(0, Qt::UserRole).toString().toAscii().constData()) == -1)
245 andreas 593
	   return;
88 andreas 594
 
245 andreas 595
	if (gmn)
596
	   garmin_free_data (gmn);
88 andreas 597
 
245 andreas 598
	gmn = spw.readFile();
599
	zfactor = 0;
248 andreas 600
 
601
	// Make sure, the currently not visible tabs will be redrawn as soon
602
	// as they are visible.
603
	switch (curTab)
604
	{
605
	   case 0: tabDirt1 = tabDirt2 = tabDirt3 = true; break;
606
	   case 1: tabDirt0 = tabDirt2 = tabDirt3 = true; break;
607
	   case 2: tabDirt0 = tabDirt1 = tabDirt3 = true; break;
608
	   case 3: tabDirt0 = tabDirt1 = tabDirt2 = true; break;
609
	}
610
 
245 andreas 611
	// Display the just loaded sport session
246 andreas 612
	DIRTY = true;
245 andreas 613
	showLaps();
614
	showTrack();
615
	showCurves();
250 andreas 616
 
617
	if (curTab == 2)
618
	{
619
	   showThreeCurve();
620
	   tabDirt2 = false;
621
	}
622
 
246 andreas 623
	DIRTY = false;
88 andreas 624
}
625
 
626
void sportwatcherWidget::filePrint()
627
{
230 andreas 628
	KMessageBox::information(this, i18n("This function is currently not implemented!"));
88 andreas 629
}
630
 
104 andreas 631
/*
632
 * This function allows the user to choose a file name, where we save the
633
 * actual lap in Garmins own TCX format. This format is simply a XML-file.
634
 * For details about the schema of this file look at
635
 * http://developer.garmin.com/schemas/tcx/v2/
636
 */
88 andreas 637
void sportwatcherWidget::fileSaveAs()
638
{
104 andreas 639
QString fname;
640
QFile fn;
641
QString buffer;
642
RUN_NODE *rn, *rakt;
643
LAP *lap;
644
POINT *point;
645
int indent, i;
646
QDateTime *qt;
232 andreas 647
KUrl sDir("~/");
246 andreas 648
QRegExp rx("(\\.tcx|\\.gpx|\\.osm)$");
104 andreas 649
 
650
	if (!gmn)
651
	{
652
	   KMessageBox::error(this, i18n("Currently no activity is selected!"));
653
	   return;
654
	}
655
 
246 andreas 656
	rx.setPatternSyntax(QRegExp::RegExp);
232 andreas 657
	fname = KFileDialog::getSaveFileName(sDir, QString("*.tcx|Garmin Training Center (*.tcx)\n*.gpx|GPS Excange Format (*.gpx)\n*.osm|OpenStreetMap (*.osm)"), this, QString("SportWatcher"));
104 andreas 658
 
659
	if (fname.isEmpty())
660
	   return;
661
 
246 andreas 662
	if (rx.indexIn(fname) < 0)
172 andreas 663
	{
232 andreas 664
	   KMessageBox::error(this, i18n("The file %1 has no valid file extension!").arg(fname));
172 andreas 665
	   return;
666
	}
667
 
232 andreas 668
	fn.setFileName(fname);
104 andreas 669
 
670
	if (fn.exists())
671
	{
672
	   if (KMessageBox::questionYesNo(this, i18n("Do you really want to overwrite this file?")) == KMessageBox::No)
673
	      return;
674
	}
675
 
246 andreas 676
	rx.setPattern("*.gpx");
677
	rx.setPatternSyntax(QRegExp::Wildcard);
172 andreas 678
 
246 andreas 679
	if (rx.exactMatch(fname))	// Should we create a *.gpx file?
172 andreas 680
	{
681
	   sportwatcherWidget::saveGPX(fname);
682
	   return;
683
	}
684
 
246 andreas 685
	rx.setPattern("*.osm");
686
	rx.setPatternSyntax(QRegExp::Wildcard);
172 andreas 687
 
246 andreas 688
	if (rx.exactMatch(fname))	// Should we create a *.osm file?
172 andreas 689
	{
690
	   sportwatcherWidget::saveOSM(fname);
691
	   return;
692
	}
693
 
694
	// No, we create a *.tcx file!
171 andreas 695
	indent = 0;
104 andreas 696
	rn = ds.getRunNode();
697
	lap = ds.getLap(rn->run->first_lap_index);
698
 
699
	if ((point = ds.getPoint(lap->start_time)) == 0)
700
	{
701
	   KMessageBox::error(this, i18n("No data to save!"));
702
	   return;
703
	}
704
 
232 andreas 705
	if (!fn.open(QIODevice::ReadWrite | QIODevice::Truncate))
104 andreas 706
	{
232 andreas 707
	   KMessageBox::error(this, i18n("Error creating file %1!\nPlease check permissions").arg(fname));
104 andreas 708
	   return;
709
	}
710
 
711
	buffer = QString("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>\n");
712
	buffer.append("<TrainingCenterDatabase xmlns=\"http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2\" ");
713
	buffer.append("xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ");
714
	buffer.append("xsi:schemaLocation=\"http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2 ");
715
	buffer.append("http://www.garmin.com/xmlschemas/TrainingCenterDatabasev2.xsd\">\n\n");
716
	writeTag (fn, buffer, indent);
717
	buffer = QString("<folders/>\n\n");
718
	writeTag (fn, buffer, indent);
719
 
720
	// Open a course
721
	QFileInfo finfo(fname);
232 andreas 722
	buffer = QString("<Courses>\n   <Course>\n      <name>%1</name>\n").arg(QFileInfo(finfo).baseName());
104 andreas 723
	writeTag (fn, buffer, indent);
724
	indent = 2;
725
 
726
	rakt = rn;
727
 
728
	while (rakt)
729
	{
730
	   if (rakt->run->type != data_D1000 && rakt->run->type != data_D1009 &&
731
	   	rakt->run->type != data_D1010)
732
	   {
733
	      rakt = rakt->next;
734
	      continue;
735
	   }
736
 
737
	   for (i = rakt->run->first_lap_index; (unsigned int)i <= rakt->run->last_lap_index; i++)
738
	   {
739
	      if ((lap = ds.getLap(i)) == NULL)
740
		 continue;
741
 
742
	      // Write the information of the lap
743
	      writeTag (fn, QString("<Lap>\n"), indent);
744
	      indent++;
745
	      buffer.sprintf("<TotalTimeSeconds>%f</TotalTimeSeconds>\n", (double)lap->total_time / 100.0);
746
	      writeTag (fn, buffer, indent);
172 andreas 747
	      qt = garmin_dtime(lap->start_time);
748
	      buffer = QString("<StartTime>%1</StartTime>\n").arg(qt->toString("yyyy-MM-ddThh:mm:ssZ"));
749
	      writeTag (fn, buffer, indent);
104 andreas 750
	      buffer.sprintf("<DistanceMeters>%f</DistanceMeters>\n", lap->total_distance);
751
	      writeTag (fn, buffer, indent);
752
 
753
	      writeTag (fn, QString("<BeginPosition>\n"), indent);
754
	      indent++;
755
	      buffer.sprintf("<LatitudeDegrees>%f</LatitudeDegrees>\n", SEMI2DEG(lap->begin.lat));
756
	      writeTag (fn, buffer, indent);
757
	      buffer.sprintf("<LongitudeDegrees>%f</LongitudeDegrees>\n", SEMI2DEG(lap->begin.lon));
758
	      writeTag (fn, buffer, indent);
759
	      indent--;
760
	      writeTag (fn, QString("</BeginPosition>\n"), indent);
761
 
762
	      writeTag (fn, QString("<EndPosition>\n"), indent);
763
	      indent++;
764
	      buffer.sprintf("<LatitudeDegrees>%f</LatitudeDegrees>\n", SEMI2DEG(lap->end.lat));
765
	      writeTag (fn, buffer, indent);
766
	      buffer.sprintf("<LongitudeDegrees>%f</LongitudeDegrees>\n", SEMI2DEG(lap->end.lon));
767
	      writeTag (fn, buffer, indent);
768
	      indent--;
769
	      writeTag (fn, QString("</EndPosition>\n"), indent);
770
 
771
	      writeTag (fn, QString("<AverageHeartRateBpm xsi:type=\"HeartRateInBeatsPerMinute_t\">\n"), indent);
772
	      indent++;
773
	      buffer.sprintf("<Value>%d</Value>\n", lap->avg_heart_rate);
774
	      writeTag (fn, buffer, indent);
775
	      indent--;
776
	      writeTag (fn, QString("</AverageHeartRateBpm>\n"), indent);
777
 
778
	      writeTag (fn, QString("<MaximumHeartRateBpm xsi:type=\"HeartRateInBeatsPerMinute_t\">\n"), indent);
779
	      indent++;
172 andreas 780
	      buffer.sprintf("<Value>%d</Value>\n", lap->max_heart_rate);
104 andreas 781
	      writeTag (fn, buffer, indent);
782
	      indent--;
783
	      writeTag (fn, QString("</MaximumHeartRateBpm>\n"), indent);
784
 
172 andreas 785
	      if (lap->avg_cadence < 255)
786
	      {
787
		 buffer.sprintf("<AverageCadence>%d</AverageCadence>\n", lap->avg_cadence);
788
		 writeTag (fn, buffer, indent);
215 andreas 789
		 buffer.sprintf("<Cadence>%d</Cadence>\n", lap->avg_cadence);
790
		 writeTag (fn, buffer, indent);
172 andreas 791
	      }
792
 
215 andreas 793
	      buffer = QString("<Intensity>%1</Intensity>\n").arg((!lap->intensity) ? "Active" : "Resting");
104 andreas 794
	      writeTag (fn, buffer, indent);
217 andreas 795
 
796
	      buffer.sprintf("<Calories>%d</Calories>\n", lap->calories);
797
	      writeTag (fn, buffer, indent);
798
 
799
	      buffer.sprintf("<MaximumSpeed>%f</MaximumSpeed>\n", lap->max_speed);
800
	      writeTag (fn, buffer, indent);
104 andreas 801
	      indent--;
802
	      writeTag (fn, QString("</Lap>\n"), indent);
803
 
804
	      point = ds.getPoint(lap->start_time);
805
	      writeTag (fn, QString("<Track>\n"), indent);
806
	      indent++;
807
 
808
	      while (point)
809
	      {
810
		 if (point->time > (lap->start_time + (lap->total_time / 100)))
811
		    break;
812
 
813
		 writeTag (fn, QString("<Trackpoint>\n"), indent);
814
		 indent++;
815
		 qt = garmin_dtime(point->time);
816
		 buffer = QString("<Time>%1</Time>\n").arg(qt->toString("yyyy-MM-ddThh:mm:ssZ"));
817
		 writeTag (fn, buffer, indent);
818
		 delete qt;
819
		 writeTag (fn, QString("<Position>\n"), indent);
820
		 indent++;
821
		 buffer.sprintf("<LatitudeDegrees>%f</LatitudeDegrees>\n", SEMI2DEG(point->posn.lat));
822
		 writeTag (fn, buffer, indent);
823
		 buffer.sprintf("<LongitudeDegrees>%f</LongitudeDegrees>\n", SEMI2DEG(point->posn.lon));
824
		 writeTag (fn, buffer, indent);
825
		 indent--;
826
		 writeTag (fn, QString("</Position>\n"), indent);
827
 
828
		 if (point->alt < 20000.0)
829
		 {
830
		    buffer.sprintf("<AltitudeMeters>%f</AltitudeMeters>\n", point->alt);
831
		    writeTag (fn, buffer, indent);
832
		 }
833
 
834
		 buffer.sprintf("<DistanceMeters>%f</DistanceMeters>\n", point->distance);
835
		 writeTag (fn, buffer, indent);
836
 
837
		 if (point->heart_rate > 0 && point->heart_rate < 250)
838
		 {
839
		    writeTag (fn, QString("<HeartRateBpm xsi:type=\"HeartRateInBeatsPerMinute_t\">\n"), indent);
840
		    indent++;
841
		    buffer.sprintf("<Value>%d</Value>\n", point->heart_rate);
842
		    writeTag (fn, buffer, indent);
843
		    indent--;
844
		    writeTag (fn, QString("</HeartRateBpm>\n"), indent);
845
		 }
846
 
249 andreas 847
		 if (point->cadence < 0xff)
215 andreas 848
		 {
849
		    buffer.sprintf("<Cadence>%d</Cadence>\n", point->cadence);
850
		    writeTag (fn, buffer, indent);
851
		 }
852
 
853
		 buffer.sprintf("<SensorState>%s</SensorState>\n", (!point->sensor) ? "Absent" : "Present");
104 andreas 854
		 writeTag (fn, buffer, indent);
855
		 indent--;
856
		 writeTag (fn, QString("</Trackpoint>\n"), indent);
857
		 point = ds.getPoint(point->time + 1);
858
	      }
859
 
860
	      indent--;
861
	      writeTag (fn, QString("</Track>\n"), indent);
862
	   }
863
 
864
	   indent--;
865
	   writeTag (fn, QString("</Course>\n"), indent);
866
	   indent--;
867
	   writeTag (fn, QString("</Courses>\n"), indent);
868
	   rakt = rakt->next;
869
	}
870
 
871
	// Write information about device
872
	// Here my personal signature is written :-)
873
	writeTag (fn, QString("<Author xsi:type=\"Application_t\">\n"), indent);
874
	indent++;
875
	writeTag (fn, QString("<Name>SportWatcher</Name>\n"), indent);
876
	writeTag (fn, QString("<Build>\n"), indent);
877
	indent++;
878
	writeTag (fn, QString("<Version>\n"), indent);
879
	indent++;
880
	writeTag (fn, QString("<VersionMajor>0</VersionMajor>\n"), indent);
881
	writeTag (fn, QString("<VersionMinor>1</VersionMinor>\n"), indent);
882
	writeTag (fn, QString("<BuildMajor>0</BuildMajor>\n"), indent);
883
	writeTag (fn, QString("<BuildMinor>0</BuildMinor>\n"), indent);
884
	indent--;
885
	writeTag (fn, QString("</Version>\n"), indent);
886
	writeTag (fn, QString("<Type>Beta</Type>\n"), indent);
887
	writeTag (fn, QString("<Time>Jan 31 2008, 00:00:00</Time>\n"), indent);
888
	writeTag (fn, QString("<Builder>theosys</Builder>\n"), indent);
889
	indent--;
890
	writeTag (fn, QString("</Build>\n"), indent);
891
	writeTag (fn, QString("<LangID>EN</LangID>\n"), indent);
892
	writeTag (fn, QString("<PartNumber>000-00000-00</PartNumber>\n"), indent);
893
	indent--;
894
	writeTag (fn, QString("</Author>\n"), indent);
895
	writeTag (fn, QString("</TrainingCenterDatabase>\n"), indent);
896
 
897
	fn.close();
898
	KMessageBox::information(this, i18n("File ") + fname + i18n(" was written successfully."));
88 andreas 899
}
900
 
901
void sportwatcherWidget::fileSave()
902
{
172 andreas 903
	KMessageBox::information(this, i18n("This function is currently not implemented!"));
88 andreas 904
}
905
 
172 andreas 906
void sportwatcherWidget::saveGPX(const QString &fn)
907
{
908
QFile qf;
909
QString buffer;
910
RUN_NODE *rn, *rakt;
911
LAP *lap;
912
POINT *point;
913
int indent;
914
unsigned int i;
915
QDateTime *qt;
916
double minLat, minLon, maxLat, maxLon;
917
 
918
	indent = 0;
919
	rn = ds.getRunNode();
920
	lap = ds.getLap(rn->run->first_lap_index);
921
 
922
	if ((point = ds.getPoint(lap->start_time)) == 0)
923
	{
924
	   KMessageBox::error(this, i18n("No data to save!"));
925
	   return;
926
	}
927
 
232 andreas 928
	qf.setFileName(fn);
172 andreas 929
 
232 andreas 930
	if (!qf.open(QIODevice::ReadWrite | QIODevice::Truncate))
172 andreas 931
	{
232 andreas 932
	   KMessageBox::error(this, i18n("Error creating file %1!\nPlease check permissions").arg(fn));
172 andreas 933
	   return;
934
	}
935
 
936
	buffer = QString("<?xml version='1.0' encoding='UTF-8'?>\n");
937
	buffer.append("<gpx version=\"1.1\" creator=\"TheoSys SportWatcher\" xmlns=\"http://www.topografix.com/GPX/1/1\">\n");
938
	buffer.append("   <metadata>\n");
939
	indent = 0;
940
	writeTag (qf, buffer, indent);
941
 
942
	// Find the edges of our coordinates
943
	// We need this information in the header (metadata)
944
	rakt = rn;
945
	minLat = -90.0;
946
	minLon = -180.0;
947
	maxLat = 90.0;
948
	maxLon = 180.0;
949
 
950
	while (rakt)
951
	{
952
	   if (rakt->run->type != data_D1000 && rakt->run->type != data_D1009 &&
953
	   	rakt->run->type != data_D1010)
954
	   {
955
	      rakt = rakt->next;
956
	      continue;
957
	   }
958
 
959
	   i = rakt->run->first_lap_index;
960
	   // get the first lap
961
	   if ((lap = ds.getLap(i)) == NULL)
962
	      continue;
963
 
964
	   i = 0;
965
	   // iterate the points associated with the laps
966
	   while ((point = ds.getPoint(i)) != 0)
967
	   {
968
	      if (point->posn.lat == 0x7fffffff || point->posn.lon == 0x7fffffff)
969
	      {
970
		 i = point->time + 1;
971
		 continue;
972
	      }
973
 
974
	      if (SEMI2DEG(point->posn.lat) > minLat)
975
		 minLat = SEMI2DEG(point->posn.lat);
976
 
977
	      if (SEMI2DEG(point->posn.lat) < maxLat)
978
		 maxLat = SEMI2DEG(point->posn.lat);
979
 
980
	      if (SEMI2DEG(point->posn.lon) > minLon)
981
		 minLon = SEMI2DEG(point->posn.lon);
982
 
983
	      if (SEMI2DEG(point->posn.lon) < maxLon)
984
		 maxLon = SEMI2DEG(point->posn.lon);
985
 
986
	      i = point->time + 1;
987
	   }
988
 
989
	   rakt = rakt->next;
990
	}
991
 
992
	buffer.sprintf("      <bounds minlat=\"%f\" minlon=\"%f\" maxlat=\"%f\" maxlon=\"%f\" />\n",
993
		maxLat, minLon, minLat, maxLon);
994
	buffer.append("   </metadata>\n");
995
	buffer.append("   <trk>\n");
996
	buffer.append("      <trkseg>\n");
997
	writeTag (qf, buffer, indent);
998
	indent = 3;
999
	rn = ds.getRunNode();
1000
	lap = ds.getLap(rn->run->first_lap_index);
1001
	i = 0;
1002
 
1003
	while ((point = ds.getPoint(i)) != 0)
1004
	{
1005
	   if (point->posn.lat == 0x7fffffff || point->posn.lon == 0x7fffffff)
1006
	   {
1007
	      i = point->time + 1;
1008
	      continue;
1009
	   }
1010
 
1011
	   buffer.sprintf("<trkpt lat=\"%f\" lon=\"%f\">\n",
1012
		SEMI2DEG(point->posn.lat), SEMI2DEG(point->posn.lon));
1013
	   writeTag(qf, buffer, indent);
1014
	   indent++;
1015
	   buffer.sprintf("<ele>%f</ele>\n", point->alt);
1016
	   writeTag(qf, buffer, indent);
1017
	   qt = garmin_dtime(point->time);
1018
	   buffer = QString("<Time>%1</Time>\n").arg(qt->toString("yyyy-MM-ddThh:mm:ssZ"));
1019
	   writeTag(qf, buffer, indent);
1020
	   indent--;
1021
	   writeTag(qf, QString("</trkpt>\n"), indent);
1022
	   i = point->time + 1;
1023
	}
1024
 
1025
	indent = 0;
1026
	buffer = QString("      </trkseg>\n");
1027
	buffer.append("   </trk>\n");
1028
	buffer.append("</gpx>\n");
1029
	writeTag(qf, buffer, indent);
1030
	qf.close();
1031
	KMessageBox::information(this, i18n("File ") + fn + i18n(" was written successfully."));
1032
}
1033
 
1034
void sportwatcherWidget::saveOSM(const QString &fn)
1035
{
1036
QFile qf;
1037
QString buffer;
1038
RUN_NODE *rn, *rakt;
1039
LAP *lap;
1040
POINT *point;
1041
int indent, id, j;
1042
unsigned int i;
1043
double minLat, minLon, maxLat, maxLon;
1044
QDateTime *qt;
1045
 
1046
	indent = 0;
1047
	rn = ds.getRunNode();
1048
	lap = ds.getLap(rn->run->first_lap_index);
1049
 
1050
	if ((point = ds.getPoint(lap->start_time)) == 0)
1051
	{
1052
	   KMessageBox::error(this, i18n("No data to save!"));
1053
	   return;
1054
	}
1055
 
232 andreas 1056
	qf.setFileName(fn);
172 andreas 1057
 
232 andreas 1058
	if (!qf.open(QIODevice::ReadWrite | QIODevice::Truncate))
172 andreas 1059
	{
232 andreas 1060
	   KMessageBox::error(this, i18n("Error creating file %1!\nPlease check permissions").arg(fn));
172 andreas 1061
	   return;
1062
	}
1063
 
1064
	buffer = QString("<?xml version='1.0' encoding='UTF-8'?>\n");
1065
	buffer.append("<osm version=\"0.5\" generator=\"TheoSys SportWatcher\">\n");
1066
	indent = 0;
1067
	writeTag (qf, buffer, indent);
1068
	// Find the edges of our coordinates
1069
	// We need this information in the header (metadata)
1070
	rakt = rn;
1071
	minLat = -90.0;
1072
	minLon = -180.0;
1073
	maxLat = 90.0;
1074
	maxLon = 180.0;
1075
 
1076
	while (rakt)
1077
	{
1078
	   if (rakt->run->type != data_D1000 && rakt->run->type != data_D1009 &&
1079
	   	rakt->run->type != data_D1010)
1080
	   {
1081
	      rakt = rakt->next;
1082
	      continue;
1083
	   }
1084
 
1085
	   i = rakt->run->first_lap_index;
1086
	   // get the first lap
1087
	   if ((lap = ds.getLap(i)) == NULL)
1088
	      continue;
1089
 
1090
	   i = 0;
1091
	   // iterate the points associated with the laps
1092
	   while ((point = ds.getPoint(i)) != 0)
1093
	   {
1094
	      if (point->posn.lat == 0x7fffffff || point->posn.lon == 0x7fffffff)
1095
	      {
1096
		 i = point->time + 1;
1097
		 continue;
1098
	      }
1099
 
1100
	      if (SEMI2DEG(point->posn.lat) > minLat)
1101
		 minLat = SEMI2DEG(point->posn.lat);
1102
 
1103
	      if (SEMI2DEG(point->posn.lat) < maxLat)
1104
		 maxLat = SEMI2DEG(point->posn.lat);
1105
 
1106
	      if (SEMI2DEG(point->posn.lon) > minLon)
1107
		 minLon = SEMI2DEG(point->posn.lon);
1108
 
1109
	      if (SEMI2DEG(point->posn.lon) < maxLon)
1110
		 maxLon = SEMI2DEG(point->posn.lon);
1111
 
1112
	      i = point->time + 1;
1113
	   }
1114
 
1115
	   rakt = rakt->next;
1116
	}
1117
 
1118
	buffer.sprintf("   <bound box='%f,%f,%f,%f' origin='http://www.openstreetmap.org/api/0.5' />\n",
1119
		maxLat, minLon, minLat, maxLon);
1120
	writeTag (qf, buffer, indent);
1121
	indent = 1;
1122
	rn = ds.getRunNode();
1123
	lap = ds.getLap(rn->run->first_lap_index);
1124
	i = 0;
1125
	id = -1;
1126
 
1127
	while ((point = ds.getPoint(i)) != 0)
1128
	{
1129
	   if (point->posn.lat == 0x7fffffff || point->posn.lon == 0x7fffffff)
1130
	   {
1131
	      i = point->time + 1;
1132
	      continue;
1133
	   }
1134
 
1135
	   buffer.sprintf("<node id='%d' action='modify' visible='true' lat=\"%f\" lon=\"%f\">\n",
1136
		id, SEMI2DEG(point->posn.lat), SEMI2DEG(point->posn.lon));
1137
	   writeTag(qf, buffer, indent);
1138
	   indent++;
1139
	   buffer = QString("<tag k='created_by' v='TheoSys Sportwatcher' />\n");
1140
	   writeTag(qf, buffer, indent);
1141
	   buffer = QString("<tag k='highway' v='tertiary' />\n");
1142
	   writeTag(qf, buffer, indent);
1143
	   indent--;
1144
	   writeTag(qf, QString("</node>\n"), indent);
1145
	   id--;
1146
	   i = point->time + 1;
1147
	}
1148
 
1149
	qt = garmin_dtime(lap->start_time);
1150
	buffer.sprintf("<way id='%d' action='modify' visible='true' timestamp='%s'>\n",
232 andreas 1151
		id, QString(qt->toString("yyyy-MM-ddThh:mm:ssZ")).toAscii().data());
172 andreas 1152
	writeTag(qf, buffer, indent);
1153
	indent++;
1154
 
1155
	for (j = -1; j > id; j--)
1156
	{
1157
	   buffer.sprintf("<nd ref='%d' />\n", j);
1158
	   writeTag(qf, buffer, indent);
1159
	}
1160
 
1161
	indent--;
1162
	writeTag(qf, QString("</way>\n"), indent);
1163
	indent = 0;
1164
	writeTag(qf, QString("</osm>\n"), indent);
1165
	qf.close();
232 andreas 1166
	KMessageBox::information(this, i18n("File %1 was written successfully.").arg(fn));
172 andreas 1167
}
1168
 
88 andreas 1169
void sportwatcherWidget::fileOpen()
1170
{
1171
QString fname = KFileDialog::getOpenFileName(Data, QString("*.gmn"), this, QString("SportWatcher"));
137 andreas 1172
int m;
88 andreas 1173
 
1174
        if (fname.isEmpty())
1175
           return;
1176
 
1177
	spw.destroy();
1178
 
232 andreas 1179
        if (spw.setFileName(fname.toAscii().data()) == -1)
88 andreas 1180
	   return;
1181
 
1182
	if (gmn)
1183
	   garmin_free_data (gmn);
1184
 
1185
	gmn = spw.readFile();
104 andreas 1186
	zfactor = 0;
137 andreas 1187
 
1188
	if ((m = garmin_count_error()) > 0)
1189
	{
1190
	int i, key = -1;
1191
 
1192
	   for (i = 0; i < m; i++)
1193
	      KMessageBox::error(this, QString(garmin_get_next_error(&key)));
1194
 
1195
	   garmin_clear_errors();
1196
	   return;
1197
	}
1198
 
246 andreas 1199
	DIRTY = true;
250 andreas 1200
	tabDirt0 = tabDirt1 = tabDirt2 = tabDirt3 = true;
88 andreas 1201
	showLaps();
100 andreas 1202
	showTrack();
88 andreas 1203
	showCurves();
250 andreas 1204
 
1205
	if (curTab == 2)
1206
	{
1207
	   showThreeCurve();
1208
	   tabDirt2 = false;
1209
	}
1210
 
1211
	tabDirt0 = tabDirt3 = false;
246 andreas 1212
	DIRTY = false;
88 andreas 1213
}
1214
 
217 andreas 1215
void sportwatcherWidget::fileImport()
1216
{
1217
QString fname = KFileDialog::getOpenFileName(QString("~/"), QString("*.tcx"), this, QString("SportWatcher"));
1218
gmn_import import;
1219
int m;
225 andreas 1220
QString tgfile, fld, px;
232 andreas 1221
QPixmap qpx;
225 andreas 1222
QFileInfo datei;
246 andreas 1223
QList<QTreeWidgetItem *>item;
1224
QTreeWidgetItem *el, *it;
225 andreas 1225
LAP *lap;
1226
RUN_NODE *rn;
217 andreas 1227
 
1228
        if (fname.isEmpty())
1229
           return;
1230
 
1231
        import.setFile(fname);
1232
 
1233
	if ((m = import.import()) != 0)
1234
	{
1235
	   KMessageBox::error(this, QString(import.getError(m)));
1236
	   return;
1237
	}
1238
 
1239
	if (gmn)
246 andreas 1240
	{
217 andreas 1241
	   garmin_free_data (gmn);
246 andreas 1242
	   gmn = 0;
1243
	}
217 andreas 1244
 
246 andreas 1245
	if (!(gmn = import.getGarminData ()))
1246
	   return;
217 andreas 1247
 
246 andreas 1248
	DIRTY = true;
250 andreas 1249
	tabDirt0 = tabDirt1 = tabDirt2 = tabDirt3 = true;
217 andreas 1250
	showLaps();
1251
	showTrack();
1252
	showCurves();
250 andreas 1253
 
1254
	if (curTab == 2)
1255
	{
1256
	   showThreeCurve();
1257
	   tabDirt2 = false;
1258
	}
1259
 
1260
	tabDirt0 = tabDirt3 = false;
246 andreas 1261
	DIRTY = false;
225 andreas 1262
 
1263
	// Find the filename;
1264
	// It consists of the date and the time.
1265
	// We need this information to set the correct path to store the file.
1266
	tgfile = Data;		// The base path
1267
	rn = ds.getRunNode();
1268
	lap = ds.getLap(rn->run->first_lap_index);
1269
	QDateTime *qt = garmin_dtime (lap->start_time);
1270
	tgfile.append (qt->toString ("/yyyy")); // year is a folder
1271
	tgfile.append (qt->toString ("/MM"));	// month is a folder
1272
	tgfile.append (qt->toString ("/yyyyMMddThhmmss"));	// The file name
1273
	tgfile.append (".gmn");		// Extension of file name
1274
	datei.setFile (tgfile);
1275
	// save the data to a real file, but only if it doesn't exist allready.
232 andreas 1276
	garmin_save_all (gmn, datei.fileName().toAscii().data(), datei.absolutePath().toAscii().data(), 0);
225 andreas 1277
 
1278
	// in case the item is already in the list on the left side, we
1279
	// only highlight the item.
246 andreas 1280
	item = ui_sportwatcherWidgetBase.liActivities->findItems (tgfile, Qt::MatchExactly);
1281
 
1282
	if (item.size() > 0)
225 andreas 1283
	{
246 andreas 1284
	   ui_sportwatcherWidgetBase.liActivities->setItemSelected (item.at(0), true);
1285
	   ui_sportwatcherWidgetBase.liActivities->setCurrentItem (item.at(0));
225 andreas 1286
	   return;
1287
	}
1288
 
1289
	// insert everything into the list on the left side
1290
	switch (rn->run->sport_type)
1291
	{
1292
	   case D1000_running:
1293
	      fld = i18n("Running");
247 andreas 1294
	      px = QString("spw-running");
225 andreas 1295
	   break;
1296
 
1297
	   case D1000_biking:
1298
	      fld = i18n("Biking");
245 andreas 1299
	      px = QString("bike");
225 andreas 1300
	   break;
1301
 
1302
	   default:
1303
	      fld = i18n("Others");
245 andreas 1304
	      px = QString("other");
225 andreas 1305
	}
1306
 
1307
	// Do we have allready so items in the list?
246 andreas 1308
	item = ui_sportwatcherWidgetBase.liActivities->findItems (fld, Qt::MatchExactly);
1309
 
1310
	if (item.size() > 0)
225 andreas 1311
	{
246 andreas 1312
	   el = new QTreeWidgetItem(item.at(0));
1313
	   el->setText(0, kl->formatDateTime(*qt, KLocale::ShortDate, true));
1314
	   el->setData(0, Qt::UserRole, tgfile);
1315
	   el->setIcon(0, KIcon(px));
225 andreas 1316
	}
1317
	else	// no, this is the first item. (shouldn't be!)
1318
	{
246 andreas 1319
	   it = new QTreeWidgetItem(ui_sportwatcherWidgetBase.liActivities);
1320
	   it->setText(0, fld);
1321
	   it->setIcon(0, KIcon(QString("history")));
1322
 
1323
	   el = new QTreeWidgetItem(item.at(0));
1324
	   el->setText(0, kl->formatDateTime(*qt, KLocale::ShortDate, true));
1325
	   el->setData(0, Qt::UserRole, tgfile);
1326
	   el->setIcon(0, KIcon(px));
225 andreas 1327
	}
217 andreas 1328
}
1329
 
218 andreas 1330
/*
1331
 * Display a small dialog to rename the currently loaded session.
1332
 */
1333
void sportwatcherWidget::editRename()
1334
{
1335
bool ok;
1336
QString name, inhalt;
246 andreas 1337
QList<QTreeWidgetItem *> item;
1338
QTreeWidgetItem *lvItem;
218 andreas 1339
QFileInfo datei;
1340
RUN_NODE *rn;
1341
LAP *lap;
1342
garmin_list *list;
1343
D1009 *n;
1344
 
1345
	if (!gmn)
1346
	{
1347
	   KMessageBox::error(this, i18n("There is no session selected!"));
1348
	   return;
1349
	}
1350
 
1351
	rn = ds.getRunNode();
246 andreas 1352
	item = ui_sportwatcherWidgetBase.liActivities->selectedItems ();
218 andreas 1353
	lvItem = item.first();
1354
 
1355
	if (!isdigit(rn->run->workout.name[0]))
1356
	   inhalt = lvItem->text(0);
1357
	else
246 andreas 1358
	   inhalt.clear();
218 andreas 1359
 
1360
	name = KInputDialog::getText(i18n("Rename session"), i18n("Session name"),
246 andreas 1361
		inhalt, &ok, this, (QValidator *)0, QString("Nxxxxxxxxxxxxxx"),
1362
		i18n("Enter a new name for the currently selected activity."));
218 andreas 1363
 
1364
	if (!ok)
1365
	   return;
1366
 
1367
	if (name.length() <= 1)
1368
	{
1369
	   lap = ds.getLap(rn->run->first_lap_index);
1370
	   const QDateTime *qt = garmin_dtime (lap->start_time);
232 andreas 1371
	   QString idx = kl->formatDateTime(*qt, KLocale::ShortDate, true);
218 andreas 1372
	   lvItem->setText (0, idx);
246 andreas 1373
	   datei.setFile (lvItem->data(0, Qt::UserRole).toString());
232 andreas 1374
	   garmin_save_all (gmn, datei.fileName().toAscii().data(), datei.absolutePath().toAscii().data(), 1);
218 andreas 1375
	   delete qt;
1376
	   return;
1377
	}
1378
 
232 andreas 1379
	strncpy (rn->run->workout.name, name.toAscii().data(), 16);
218 andreas 1380
 
1381
	if (gmn->type != data_Dlist)
1382
	{
1383
	   KMessageBox::error(this, i18n("editRename: Unexpected structure type %1 found!").arg(gmn->type));
1384
	   return;
1385
	}
1386
 
1387
	list = (garmin_list *)gmn->data;
1388
 
1389
	if (list->head->data->type != data_D1009)	// This should be the run node
1390
	{
1391
	   KMessageBox::error(this, i18n("editRename: The run node was not found!"));
1392
	   return;
1393
	}
1394
 
1395
	n = (D1009 *)list->head->data->data;
246 andreas 1396
	strncpy (n->workout.name, rn->run->workout.name, 15);
218 andreas 1397
	lvItem->setText (0, name);
246 andreas 1398
	datei.setFile (lvItem->data(0, Qt::UserRole).toString());
232 andreas 1399
	garmin_save_all (gmn, datei.fileName().toAscii().data(), datei.absolutePath().toAscii().data(), 1);
218 andreas 1400
}
1401
 
88 andreas 1402
void sportwatcherWidget::fileNew()
1403
{
232 andreas 1404
progressWidget *dlg = new progressWidget(this);
96 andreas 1405
 
100 andreas 1406
	dlg->show();
137 andreas 1407
 
1408
	if (!dlg->Download())
1409
	{
1410
	int m, key;
1411
 
1412
	   key = -1;
1413
 
1414
	   for (m = 0; m < garmin_count_error(); m++)
1415
	      KMessageBox::error(this, QString(garmin_get_next_error(&key)));
1416
	}
1417
	else
1418
	   getActivities();
1419
 
1420
	garmin_clear_errors();
96 andreas 1421
	delete dlg;
88 andreas 1422
}
1423
 
1424
/*
1425
 * This function is called, when the user clicks at the menu point
1426
 * "Save Heart Rate".
1427
 * First, a file dialog box is displayed, where the user can choose a
1428
 * directory and a file name to save the heart rate.
1429
 * If the file could successfully be created, the heart rate is saved
137 andreas 1430
 * in the "HRM"-format. This is the native format Polar uses to store
88 andreas 1431
 * heart rate data. I've choosen this format, because it's popular and
1432
 * used by many other software too.
1433
 */
1434
void sportwatcherWidget::extrasSaveHR()
1435
{
1436
QString fname, str1, str2;
1437
QFile fdfile;
1438
QDateTime *qt, *oldqt;
1439
QDate dat;
1440
QTime t;
1441
QDir dir = QDir::home();
1442
char hv0[256];
1443
RUN_NODE *rn;
1444
LAP *lap, *alap;
1445
POINT *point;
1446
int samples, smp, seconds, anz, nsec, samsec;
1447
int avgHeart, minHeart, maxHeart, aktHeart;
1448
int secRange1, secRange2, secRange3, secAbove, secBeyond;
1449
 
1450
	if (!gmn)
1451
	{
1452
	   KMessageBox::information(this, i18n("There is no activity open"));
1453
	   return;
1454
	}
1455
 
1456
	if (HRM.isEmpty())
1457
	   str1 = dir.path();
1458
	else
1459
	   str1 = HRM;
1460
 
1461
	str1 +=  "/" + StartTime.toString("yyyyMMddThhmmss.zzz.hrm");
1462
	fname = KFileDialog::getSaveFileName(str1, QString("*.hrm"), this, QString("SportWatcher"));
1463
 
1464
	if (fname.isEmpty())
1465
	   return;
1466
 
232 andreas 1467
	fdfile.setFileName(fname);
88 andreas 1468
 
1469
	if (fdfile.exists())
1470
	{
1471
	   if (KMessageBox::questionYesNo(this, i18n("Do you really want to overwrite this file?")) == KMessageBox::No)
1472
	      return;
1473
	}
1474
 
232 andreas 1475
	if (!fdfile.open(QIODevice::ReadWrite | QIODevice::Truncate))
88 andreas 1476
	{
1477
	   KMessageBox::error(this, i18n("Error creating a file!\nPlease check permissions."));
1478
	   return;
1479
	}
1480
 
1481
	rn = ds.getRunNode();
1482
	lap = ds.getLap(rn->run->first_lap_index);
1483
	t = StartTime.time();
1484
	dat = StartTime.date();
1485
 
1486
	if ((point = ds.getPoint(lap->start_time)) == 0)
1487
	{
1488
	   fdfile.close();
1489
	   return;
1490
	}
1491
 
1492
	strcpy (hv0, "[Params]\n");
1493
	write(fdfile.handle(), &hv0[0], strlen(hv0));
1494
	str1 = dat.toString("yyyyMMdd");
1495
	str2 = t.toString("hh:mm:ss.z");
1496
	sprintf(hv0, "Version=106\nMonitor=11\nSMode=000000000\nDate=%s\nStartTime=%s\n",
232 andreas 1497
		str1.toAscii().data(), str2.toAscii().data());
88 andreas 1498
	write(fdfile.handle(), &hv0[0], strlen(hv0));
1499
	t.setHMS(0, 0, 0);
1500
	t = t.addSecs(max_time);
1501
	str2 = t.toString("hh:mm:ss.z");
1502
 
1503
	switch (sampleTime)
1504
	{
1505
	   case 0: samsec = 5; break;
1506
	   case 1: samsec = 15; break;
1507
	   case 2: samsec = 30; break;
1508
	   case 3: samsec = 60; break;
1509
	   default:
1510
	      samsec = 15;
1511
	}
1512
 
1513
	sprintf(hv0, "Length=%s\nInterval=%d\nUpper1=%d\nLower1=%d\nUpper2=%d\n",
232 andreas 1514
	   str2.toAscii().data(), samsec, upper1, lower1, upper2);
88 andreas 1515
	write(fdfile.handle(), &hv0[0], strlen(hv0));
1516
	sprintf(hv0, "Lower2=%d\nUpper3=%d\nLower3=%d\nTimer1=00:00:00.0\n",
1517
		lower2, upper3, lower3);
1518
	write(fdfile.handle(), &hv0[0], strlen(hv0));
1519
	strcpy(hv0, "Timer2=00:00:00.0\nTimer3=00:00:00.0\nActiveLimit=0\n");
1520
	write(fdfile.handle(), &hv0[0], strlen(hv0));
1521
	sprintf(hv0, "MaxHR=%d\nRestHR=%d\nStartDelay=0\nVO2max=%d\nWeight=%d\n\n",
1522
		MaxHr, restHr, vo2max, weight);
1523
	write(fdfile.handle(), &hv0[0], strlen(hv0));
1524
 
1525
	// Write the intervall times. One block for every lap
1526
	secRange1 = secRange2 = secRange3 = secAbove = secBeyond = 0;
1527
	strcpy(hv0, "[IntTimes]\n");
1528
	write(fdfile.handle(), &hv0[0], strlen(hv0));
1529
	t.setHMS(0, 0, 0);
1530
 
1531
	for (unsigned int i = rn->run->first_lap_index; i < rn->run->last_lap_index; i++)
1532
	{
1533
	   alap = ds.getLap(i);
1534
	   point = ds.getPoint(alap->start_time);
1535
	   oldqt = garmin_dtime(point->time);
1536
	   avgHeart = minHeart = maxHeart = aktHeart = 0;
1537
	   anz = 0;
1538
	   unsigned long lastTime = point->time;
1539
	   int totSec = 0;
1540
 
1541
	   while (point)
1542
	   {
1543
	      if (point->time > (alap->start_time + (alap->total_time / 100)))
1544
		 break;
1545
 
1546
	      if (point->heart_rate > 0)
1547
	      {
1548
		 avgHeart += point->heart_rate;
1549
		 nsec = point->time - lastTime;
1550
		 totSec += nsec;
1551
 
1552
		 if (minHeart == 0 || minHeart > point->heart_rate)
1553
		    minHeart = point->heart_rate;
1554
 
1555
		 if (maxHeart < point->heart_rate)
1556
		    maxHeart = point->heart_rate;
1557
 
1558
		 if (aktHeart == 0 && totSec >= samsec)
1559
		    aktHeart = avgHeart / (anz + 1);
1560
 
1561
		 if (point->heart_rate < lower1)
1562
		    secBeyond += nsec;
1563
		 else if (point->heart_rate < lower2)
1564
		    secRange1 += nsec;
1565
		 else if (point->heart_rate < lower3)
1566
		    secRange2 += nsec;
1567
		 else if (point->heart_rate < upper3)
1568
		    secRange3 += nsec;
1569
		 else
1570
		    secAbove += nsec;
1571
 
1572
		 lastTime = point->time;
1573
		 anz++;
1574
	      }
1575
 
1576
	      point = ds.getPoint(point->time+1);
1577
	   }
1578
 
1579
	   t = t.addSecs(alap->total_time / 100);
1580
	   str1 = t.toString("hh:mm:ss.z");
166 andreas 1581
 
1582
	   if (anz > 0)
1583
	      avgHeart = avgHeart / anz;
1584
	   else
1585
	      avgHeart = 0;
1586
 
88 andreas 1587
	   sprintf(hv0, "%s\t %d\t %d\t %d\t %d\n",
232 andreas 1588
	      str1.toAscii().data(), aktHeart, minHeart, avgHeart, maxHeart);
88 andreas 1589
	   write(fdfile.handle(), &hv0[0], strlen(hv0));
1590
	   strcpy(hv0, "32\t 0\t 0\t 0\t 0\t 0\n");
1591
	   write(fdfile.handle(), &hv0[0], strlen(hv0));
1592
	   strcpy(hv0, "0\t 0\t 0\t 0\t 0\n");
1593
	   write(fdfile.handle(), &hv0[0], strlen(hv0));
1594
	   sprintf(hv0, "0\t %d\t 0\t 0\t 0\t 0\n", (int)alap->total_distance);
1595
	   write(fdfile.handle(), &hv0[0], strlen(hv0));
1596
	   strcpy(hv0, "0\t 0\t 0\t 0\t 0\t 0\n");
1597
	   write(fdfile.handle(), &hv0[0], strlen(hv0));
1598
	}
1599
 
1600
	strcpy(hv0, "\n[IntNotes]\n\n[ExtraData]\n\n");
1601
	write(fdfile.handle(), &hv0[0], strlen(hv0));
1602
 
1603
	strcpy(hv0, "[Summary-123]\n");
1604
	write(fdfile.handle(), &hv0[0], strlen(hv0));	// Time limits 1
1605
	smp = max_time - secBeyond - secRange1 - secRange2 - secRange3 - secAbove;
245 andreas 1606
	sprintf(hv0, "%lu\t %u\t %u\t %u\t %u\n",
88 andreas 1607
		max_time, secRange1, secRange2 + secRange3,
1608
		secAbove + secBeyond, smp);
1609
	write(fdfile.handle(), &hv0[0], strlen(hv0));	// limits 1
1610
	sprintf(hv0, "%d\t %d\t %d\t %d\n",
1611
		MaxHr, upper1, lower1, restHr);
1612
	write(fdfile.handle(), &hv0[0], strlen(hv0));	// Time limits 1
245 andreas 1613
	sprintf(hv0, "%lu\t %u\t %u\t %u\t %u\n",
88 andreas 1614
		max_time, secRange2, secRange1 + secRange3,
1615
		secAbove + secBeyond, smp);
1616
	write(fdfile.handle(), &hv0[0], strlen(hv0));	// limits 2
1617
	sprintf(hv0, "%d\t %d\t %d\t %d\n",
1618
		MaxHr, upper2, lower2, restHr);
1619
	write(fdfile.handle(), &hv0[0], strlen(hv0));	// Time limits 2
245 andreas 1620
	sprintf(hv0, "%lu\t %u\t %u\t %u\t %u\n",
88 andreas 1621
		max_time, secRange3, secRange1 + secRange2,
1622
		secAbove + secBeyond, smp);
1623
	write(fdfile.handle(), &hv0[0], strlen(hv0));	// limits 3
1624
	sprintf(hv0, "%d\t %d\t %d\t %d\n",
1625
		MaxHr, upper3, lower3, restHr);
1626
	write(fdfile.handle(), &hv0[0], strlen(hv0));	// Time limits 3
1627
	samples = max_time / samsec;
1628
	sprintf(hv0, "0\t %u\n\n", samples);	// samples
1629
	write(fdfile.handle(), &hv0[0], strlen(hv0));
1630
 
1631
	strcpy(hv0, "[Summary-TH]\n");
1632
	write(fdfile.handle(), &hv0[0], strlen(hv0));
245 andreas 1633
	sprintf(hv0, "%lu\t 0\t %lu\t %d\t %d\t 0\n", max_time, max_time - max_hr - restHr, max_hr, restHr);
88 andreas 1634
	write(fdfile.handle(), &hv0[0], strlen(hv0));
1635
	sprintf(hv0, "%d\t %d\t %d\t %d\n", MaxHr, upper3, lower1, restHr);
1636
	write(fdfile.handle(), &hv0[0], strlen(hv0));
1637
	sprintf(hv0, "0\t %u\n\n", samples);	// samples
1638
	write(fdfile.handle(), &hv0[0], strlen(hv0));
1639
 
1640
	sprintf(hv0, "[HRZones]\n%d\n%d\n%d\n%d\n%d\n%d\n0\n0\n0\n0\n0\n\n",
1641
		MaxHr, upper3, upper2, upper1, lower1, restHr);
1642
	write(fdfile.handle(), &hv0[0], strlen(hv0));
1643
 
1644
	strcpy(hv0, "[HRData]\n");
1645
	write(fdfile.handle(), &hv0[0], strlen(hv0));
1646
 
1647
	smp = 0;		// average heart rate of 15 seconds
1648
	seconds = 0;
1649
	anz = 0;
1650
	nsec = samsec;
1651
	oldqt = garmin_dtime(lap->start_time);
1652
	qt = 0;
1653
	point = ds.getPoint(lap->start_time);
1654
 
1655
	while (point)
1656
	{
1657
	   if (seconds >= nsec)
1658
	   {
1659
	      if (anz > 0)
1660
	      {
1661
		 sprintf(hv0, "%d\n", smp / anz);
1662
		 write(fdfile.handle(), &hv0[0], strlen(hv0));
1663
	      }
1664
 
1665
	      if (smp > 0 && seconds >= (nsec + samsec))
1666
	      {
1667
		 if (anz <= 0)
1668
		    anz = 0;
1669
 
1670
		 for (int x = nsec; x < seconds; x += samsec)
1671
		 {
1672
		    sprintf(hv0, "%d\n", smp / anz);
1673
		    write(fdfile.handle(), &hv0[0], strlen(hv0));
1674
		    nsec += samsec;
1675
		 }
1676
	      }
1677
 
1678
	      anz = 0;
1679
	      smp = 0;
1680
	      nsec += samsec;
1681
	   }
1682
 
1683
	   qt = garmin_dtime (point->time);
1684
	   seconds += oldqt->secsTo(*qt);
1685
 
1686
	   if (point->heart_rate > 0)
1687
	   {
1688
	      smp += point->heart_rate;
1689
	      anz++;
1690
	   }
1691
 
1692
	   delete oldqt;
1693
	   oldqt = qt;
1694
	   point = ds.getPoint(point->time + 1);
1695
	}
1696
 
1697
	fdfile.close();
1698
	KMessageBox::information(this, i18n("File successfully written."));
1699
}
1700
 
1701
void sportwatcherWidget::extrasSettings()
1702
{
232 andreas 1703
settingsWidget *dlg = new settingsWidget(this);
88 andreas 1704
 
1705
	if (dlg->exec() == QDialog::Accepted)
1706
	{
232 andreas 1707
	   KConfig cfg(QString("sportwatcher.rc"), KConfig::SimpleConfig);
1708
	   KConfigGroup ic (&cfg, "SportWatcher");
1709
	   lower1 = ic.readEntry("lower1", 0);
1710
	   lower2 = ic.readEntry("lower2", 0);
1711
	   lower3 = ic.readEntry("lower3", 0);
1712
	   upper1 = ic.readEntry("upper1", 0);
1713
	   upper2 = ic.readEntry("upper2", 0);
1714
	   upper3 = ic.readEntry("upper3", 0);
1715
	   MaxHr = ic.readEntry("maxHr", 0);
1716
	   restHr = ic.readEntry("restHr", 0);
1717
	   vo2max = ic.readEntry("vo2max", 0);
1718
	   weight = ic.readEntry("weight", 0);
1719
	   sampleTime = ic.readEntry("seconds", 1);
1720
	   Serial = ic.readEntry("Serial", false);
1721
	   Contour = ic.readEntry("Contour", false);
1722
	   Device = ic.readEntry("Device", QString("/dev/ttyUSB0"));
1723
	   Forerunner = ic.readEntry("Forerunner", false);
1724
	   Data = ic.readEntry("Data", QString("/"));
1725
	   HRM = ic.readEntry("HRM", QString("/"));
1726
	   MAP = ic.readEntry("MAP", QString("/"));
1727
	   Units = ic.readEntry("Units", 0);
1728
	   MapType = ic.readEntry("MapType", 0);
88 andreas 1729
	}
1730
 
1731
	delete dlg;
152 andreas 1732
}
151 andreas 1733
 
152 andreas 1734
void sportwatcherWidget::extrasWMSSettings()
1735
{
232 andreas 1736
#if defined HAVE_GDAL
158 andreas 1737
	if (MapType == MPT_BMP || MapType == MPT_GIF || MapType == MPT_PNG ||
1738
	    MapType == MPT_TIF)
1739
	{
232 andreas 1740
	   coordinatesWidget *idlg = new coordinatesWidget(this);
158 andreas 1741
	   idlg->exec();
1742
	   delete idlg;
1743
	   return;
1744
	}
274 andreas 1745
 
1746
	if (MapType == MPT_WMS)
158 andreas 1747
	{
274 andreas 1748
	   wmsbase *dlg = new wmsbase(this);
1749
	   dlg->exec();
1750
	   delete dlg;
1751
	}
1752
 
1753
	if (MapType == MPT_SHP)
1754
	{
1755
	   shapeWidget *dlg = new shapeWidget(this);
1756
	   dlg->exec();
1757
	   delete dlg;
1758
	}
1759
 
1760
	if (MapType != MPT_WMS && MapType != MPT_SHP)
1761
	{
158 andreas 1762
	   KMessageBox::detailedSorry(this,
274 andreas 1763
	      i18n("You have not choosen a WMS tag file or shape file directory!"),
1764
	      i18n("This dialog is especialy to set map specific parameters. ") +
158 andreas 1765
	      i18n("Therefore this dialog is temporary disabled. It will be ") +
274 andreas 1766
	      i18n("available again, as soon as you choose \"WMS server\" or ") +
1767
	      i18n("Shape file as your map type."));
158 andreas 1768
	      return;
1769
	}
156 andreas 1770
#else
1771
	KMessageBox::detailedSorry(this,
1772
	   i18n("This function was disabled at compile time because of missing GDAL v1.5.x!"),
1773
	   i18n("Sportwatcher needs GDAL v1.5.x to enable this function.\n") +
1774
	   i18n("If you like this to be working, install GDAL version 1.5.x and recompile the source!"));
1775
#endif
88 andreas 1776
}
1777
 
1778
/*
1779
 * Functions to fill in the boxes of the main mask.
1780
 */
1781
void sportwatcherWidget::showLaps()
1782
{
1783
QString qs_name, qs_distance, qs_etime, qs_avgpace, qs_avgspeed, qs_maxspeed;
1784
QString qs_calories, qs_avghr, qs_maxhr, qs_avgcadence, qs_ascent, qs_descent;
248 andreas 1785
QString qs_totdist;
88 andreas 1786
QDateTime dt;
1787
QTime t, st;
249 andreas 1788
QDateTime *qt;
1789
LAP *lap;
1790
POINT *point;
88 andreas 1791
RUN_NODE *rakt, *rn;
149 andreas 1792
int laps, i, anz, men, cad;
249 andreas 1793
double alt_asc, alt_dsc, sum_asc, sum_dsc, old_asc, old_dsc;
248 andreas 1794
double totdist;
216 andreas 1795
bool pause;
88 andreas 1796
 
246 andreas 1797
	if (!DIRTY)
1798
	   return;
1799
 
88 andreas 1800
	if (!gmn)
1801
	{
248 andreas 1802
//	   KMessageBox::error(this, i18n("No data were loaded!"));
88 andreas 1803
	   return;
1804
	}
1805
 
1806
	if (gmn->type == data_Dnil)
1807
	{
1808
	   KMessageBox::error(0, i18n("No data found!"));
1809
	   return;
1810
	}
1811
 
1812
	if (gmn->type != data_Dlist)     /* List of data */
1813
	{
221 andreas 1814
	   KMessageBox::error(0, i18n("Found unexpected data type %1!").arg(gmn->type));
88 andreas 1815
	   return;
1816
	}
1817
 
1818
	ds.destroy();
221 andreas 1819
	min_hr = max_hr = avg_hr = 0;
88 andreas 1820
	min_height = max_height = 0.0;
218 andreas 1821
	min_speed = max_speed = 0.0;
248 andreas 1822
	totdist = 0.0;
1823
	// Tab Summary
245 andreas 1824
	ui_sportwatcherWidgetBase.liLaps->clear();
1825
	ui_sportwatcherWidgetBase.liLaps->setAllColumnsShowFocus(true);
248 andreas 1826
	// Tab Laps
1827
	ui_sportwatcherWidgetBase.twLaps->clear();
88 andreas 1828
	ds.garmin_print_data(gmn);
245 andreas 1829
 
1830
	if (!(rn = ds.getRunNode()))
1831
	   return;
1832
 
88 andreas 1833
	rakt = rn;
248 andreas 1834
	// Tab Summary
245 andreas 1835
	ui_sportwatcherWidgetBase.liLaps->setRootIsDecorated(true);
88 andreas 1836
 
248 andreas 1837
	for (i = 1; i < 12; i++)
1838
	   ui_sportwatcherWidgetBase.liLaps->setColumnAlignment(i, Qt::AlignRight);
1839
	// Tab Laps
1840
	ui_sportwatcherWidgetBase.edTotalDistance->clear();
1841
	ui_sportwatcherWidgetBase.edTotalTime->clear();
1842
	ui_sportwatcherWidgetBase.edAvgSpeed->clear();
1843
	ui_sportwatcherWidgetBase.edTotalHeight->clear();
1844
	ui_sportwatcherWidgetBase.edAvgHR->clear();
1845
	ui_sportwatcherWidgetBase.edLapNumber->clear();
1846
 
88 andreas 1847
	qs_name = qs_distance = qs_etime = qs_avgpace = qs_avgspeed = qs_maxspeed = QString("");
1848
	qs_calories = qs_avghr = qs_maxhr = qs_avgcadence = qs_ascent = qs_descent = QString("");
1849
	men = 0;
149 andreas 1850
	cad = 0;
88 andreas 1851
 
249 andreas 1852
	// The main loop.
1853
	// If a supported run type is detected, it will be processed.
88 andreas 1854
	while (rakt)
1855
	{
249 andreas 1856
	   // Check for a supported run type
88 andreas 1857
	   if (rakt->run->type == data_D1000 || rakt->run->type == data_D1009 ||
1858
	   	rakt->run->type == data_D1010)
1859
	   {
249 andreas 1860
	   int cal, ahr, mhr;
88 andreas 1861
	   double distance, speed, mspeed;
1862
	   QDate dat;
1863
 
249 andreas 1864
	      // Set the name depending on the sport type
1865
	      // This is used on the tab "Summary"
88 andreas 1866
	      switch (rakt->run->sport_type)
1867
	      {
1868
		 case D1000_running: qs_name = QString("Running: "); break;
1869
		 case D1000_biking:  qs_name = QString("Biking: "); break;
1870
		 case D1000_other:   qs_name = QString("Other: "); break;
1871
		 default:
1872
		    qs_name = QString("Unknown: ");
1873
	      }
1874
 
245 andreas 1875
	      if (!(lap = ds.getLap(rakt->run->first_lap_index)))
1876
		 return;
1877
 
88 andreas 1878
	      qt = garmin_dtime (lap->start_time);
1879
	      StartTime = *qt;
1880
	      st = qt->time();
1881
	      dat = qt->date();
1882
	      delete qt;
213 andreas 1883
	      qt = 0;
1884
	      // Find the last track;
1885
	      //    It is possible to delete laps directly on the watch,
1886
	      //    so we can't be sure the last lap is really the last one.
1887
	      //    Tracks are not deleted and the last track contains the
1888
	      //    summuraries we need.
249 andreas 1889
	      if (!(point = ds.getLastPoint()))
213 andreas 1890
	      {
249 andreas 1891
		 KMessageBox::error(this, i18n("Error getting the last messure point!"));
245 andreas 1892
		 return;
215 andreas 1893
	      }
1894
 
249 andreas 1895
	      qt = garmin_dtime(point->time);
1896
	      t = qt->time();
88 andreas 1897
	      t.setHMS(0, 0, 0);
249 andreas 1898
	      t = t.addSecs(ds.getTotalTime());
88 andreas 1899
	      qt->setDate(dat);
1900
	      qt->setTime(t);
232 andreas 1901
	      qs_name.append(kl->formatDate(dat, KLocale::ShortDate));
88 andreas 1902
	      qs_name.append(" ");
230 andreas 1903
	      qs_name.append(kl->formatTime(st, true));
249 andreas 1904
	      max_time = ds.getTotalTime();
88 andreas 1905
	      qs_etime = QString(qt->toString("hh:mm:ss.zzz"));
1906
 
1907
	      distance = 0.0;
1908
	      cal = 0;
1909
	      mspeed = 0;
1910
	      ahr = mhr = 0;
1911
	      anz = 0;
149 andreas 1912
	      cad = 0;
1913
	      sum_asc = sum_dsc = old_asc = old_dsc = 0;
88 andreas 1914
 
249 andreas 1915
	      // Find out the total distance, calories, maximum speed,
1916
	      // maximum heart rate and the average heart rate. Get this
1917
	      // values from the lap summary the watch made.
88 andreas 1918
	      for (i = rakt->run->first_lap_index; (unsigned int)i <= rakt->run->last_lap_index; i++)
1919
	      {
1920
		 if ((lap = ds.getLap(i)) == NULL)
1921
		    continue;
1922
 
1923
		 distance += lap->total_distance;
1924
		 cal += lap->calories;
149 andreas 1925
 
1926
		 if (lap->avg_cadence != 0xff)
1927
		    cad += lap->avg_cadence;
1928
 
88 andreas 1929
		 ahr += lap->avg_heart_rate;
1930
		 anz++;
1931
 
1932
		 if (lap->max_speed > mspeed)
1933
		    mspeed = lap->max_speed;
1934
 
1935
		 if (lap->max_heart_rate > mhr)
1936
		    mhr = lap->max_heart_rate;
1937
	      }
1938
 
249 andreas 1939
	      total_distance = distance = ds.getTotalDistance();
213 andreas 1940
 
149 andreas 1941
	      if (Units == 1)		// Statute?
1942
		 qs_distance.sprintf("%.2f ft", distance / 0.304);
1943
	      else
1944
	         qs_distance.sprintf("%.2f m", distance);
1945
 
88 andreas 1946
	      if (distance > 0)
1947
	      {
1948
		 QTime tt = qt->time();
156 andreas 1949
		 long secs = (double)(tt.hour() * 3600 + tt.minute() * 60 + tt.second()) / 100.0;
1950
 
1951
		 if (Units == 0)
1952
		    secs = secs * (1000.0 / distance * 100.0);
1953
		 else
1954
		    secs = secs * (1609.344 / distance * 100.0);
1955
 
88 andreas 1956
		 int h = secs / 3600;
1957
		 int m = (secs - (h * 3600)) / 60;
1958
		 int s = secs - ((h * 3600) + (m * 60));
1959
		 t = QTime(h, m, s, 0);
230 andreas 1960
		 qs_avgpace = QString("  ") + kl->formatTime(t, true);
156 andreas 1961
 
1962
		 if (Units == 0)
1963
		    qs_avgpace.append(QString(" /km"));
1964
		 else
1965
		    qs_avgpace.append(QString(" /mi"));
88 andreas 1966
	      }
1967
 
149 andreas 1968
	      if (Units == 1)		// Statute?
249 andreas 1969
		 speed = distance / ds.getTotalTime() * 3.6 / 1.609344;
149 andreas 1970
	      else
249 andreas 1971
		 speed = distance / ds.getTotalTime() * 3.6;
149 andreas 1972
 
156 andreas 1973
	      qs_avgspeed.sprintf("%.2f %s", speed, (Units == 1) ? "mph" : "km/h");
1974
	      qs_maxspeed.sprintf("%.2f %s", (Units == 1) ? mspeed * 3.6 / 1.609344 : mspeed * 3.6, (Units == 1) ? "mph" : "km/h");
88 andreas 1975
	      qs_calories.sprintf("%d", cal);
1976
	      qs_avghr.sprintf("%d bpm", ahr / anz);
1977
	      qs_maxhr.sprintf("%d bpm", mhr);
1978
 
149 andreas 1979
	      if (cad > 0)
1980
		 qs_avgcadence.sprintf("%d", cad / anz);
1981
 
248 andreas 1982
	      // Add the summary line columns to the tab "Summary"
1983
	      K3ListViewItem *element = new K3ListViewItem(ui_sportwatcherWidgetBase.liLaps,
1984
	        qs_name, kl->formatNumber(qs_distance, false),
1985
		qs_etime, qs_avgpace, kl->formatNumber(qs_avgspeed, false),
1986
		kl->formatNumber(qs_maxspeed, false), qs_calories, qs_avghr);
88 andreas 1987
	      element->setText(8, qs_maxhr);
1988
	      element->setText(9, qs_avgcadence);
248 andreas 1989
	      element->setText(10, kl->formatNumber(qs_ascent, false));
1990
	      element->setText(11, kl->formatNumber(qs_descent, false));
88 andreas 1991
	      element->sortChildItems(0, false);
1992
	      element->setOpen(true);
245 andreas 1993
	      element->setPixmap(0, KIcon(QString("activity")).pixmap(16));
1994
	      ui_sportwatcherWidgetBase.liLaps->insertItem(element);
248 andreas 1995
	      // Add some of the summaries to the fields on the tab "Lap details"
1996
	      ui_sportwatcherWidgetBase.edTotalDistance->setAlignment(Qt::AlignRight);
1997
	      ui_sportwatcherWidgetBase.edTotalDistance->insert(kl->formatNumber(qs_distance, false));
1998
	      ui_sportwatcherWidgetBase.edTotalTime->setAlignment(Qt::AlignRight);
1999
	      ui_sportwatcherWidgetBase.edTotalTime->insert(qs_etime);
2000
	      ui_sportwatcherWidgetBase.edAvgSpeed->setAlignment(Qt::AlignRight);
2001
	      ui_sportwatcherWidgetBase.edAvgSpeed->insert(kl->formatNumber(qs_avgspeed, false));
2002
	      ui_sportwatcherWidgetBase.edTotalHeight->setAlignment(Qt::AlignRight);
2003
	      ui_sportwatcherWidgetBase.edTotalHeight->insert(kl->formatNumber(qs_ascent, false));
2004
	      ui_sportwatcherWidgetBase.edAvgHR->setAlignment(Qt::AlignRight);
2005
	      ui_sportwatcherWidgetBase.edAvgHR->insert(qs_avghr);
88 andreas 2006
	      delete qt;
2007
	      /* Get the laps. */
2008
	      laps = 1;
2009
 
2010
	      for (i = rakt->run->first_lap_index; (unsigned int)i <= rakt->run->last_lap_index; i++)
2011
	      {
149 andreas 2012
		 double spd;
2013
		 char *un;
2014
 
88 andreas 2015
		 if ((lap = ds.getLap(i)) == NULL)
2016
		    continue;
2017
 
2018
		 qt = garmin_dtime (lap->start_time);
2019
		 qs_name.sprintf("Lap %03d - ", laps);
230 andreas 2020
		 qs_name.append(kl->formatTime(qt->time(), true));
149 andreas 2021
		 qs_distance.sprintf("%.2f %s", (Units == 1) ? lap->total_distance / 0.304 : lap->total_distance, (Units == 1) ? "ft" : "m");
248 andreas 2022
		 totdist += (Units == 1) ? lap->total_distance / 0.304 : lap->total_distance;
2023
		 qs_totdist.sprintf("%2.f %s", totdist, (Units == 1) ? "ft" : "m");
88 andreas 2024
		 t = QTime(0, 0, 0, 0);
2025
		 t = t.addMSecs(lap->total_time * 10);
2026
		 qs_etime = t.toString("hh:mm:ss.zzz");
149 andreas 2027
		 spd = lap->total_distance / (lap->total_time / 100.0);
249 andreas 2028
		 delete qt;
2029
		 qt = 0;
149 andreas 2030
 
2031
		 if (Units == 0)
2032
		 {
2033
		    un = (char *)"km/h";
2034
		    spd *= 3.6;
2035
		 }
2036
		 else
156 andreas 2037
		 {
2038
		    spd *= 3.6 / 1.609344;
2039
		    un = (char *)"mph";
2040
		 }
149 andreas 2041
 
2042
		 qs_avgspeed.sprintf("%.2f %s", spd, un);
156 andreas 2043
		 qs_maxspeed.sprintf("%.2f %s", (Units == 1) ? lap->max_speed * 3.6 / 1.609344 : lap->max_speed * 3.6, un);
88 andreas 2044
		 qs_calories.sprintf("%d", lap->calories);
2045
 
2046
		 if (lap->total_distance > 0 && lap->total_time != 0)
2047
		 {
156 andreas 2048
		    double fact;
2049
 
2050
		    if (Units == 0)
2051
		       fact = 1000.0;		// 1 km
2052
		    else
2053
		       fact = 1609.344;		// 1 mile in meters
2054
 
2055
		    long secs = (double)lap->total_time / 10000.0 * (fact / lap->total_distance * 100.0);
88 andreas 2056
		    int h = secs / 3600;
2057
		    int m = (secs - (h * 3600)) / 60;
2058
		    int s = secs - ((h * 3600) + (m * 60));
2059
		    t = QTime(h, m, s, 0);
230 andreas 2060
		    qs_avgpace = kl->formatTime(t, true);
156 andreas 2061
 
2062
		    if (Units == 0)
2063
		       qs_avgpace.append(QString(" /km"));
2064
		    else
2065
		       qs_avgpace.append(QString(" /mi"));
88 andreas 2066
		 }
2067
 
2068
		 qs_avghr.sprintf("%d bpm", lap->avg_heart_rate);
2069
		 qs_maxhr.sprintf("%d bpm", lap->max_heart_rate);
2070
 
2071
		 anz = 0;
2072
		 alt_asc = alt_dsc = 0;
249 andreas 2073
		 // Add a new detail line to the tab "Lap details"
2074
		 QTreeWidgetItem * trdetail = new QTreeWidgetItem(ui_sportwatcherWidgetBase.twLaps);
88 andreas 2075
 
2076
		 if ((point = ds.getPoint(lap->start_time)) != 0)
2077
		 {
2078
		    if (point->alt < 20000)
149 andreas 2079
		    {
88 andreas 2080
		       alt_dsc = alt_asc = point->alt;
149 andreas 2081
 
2082
		       if (old_asc == 0)
2083
			  old_asc = alt_asc;
2084
 
2085
		       if (old_dsc == 0)
2086
			  old_dsc = alt_dsc;
2087
		    }
88 andreas 2088
		    else
2089
		       alt_dsc = alt_asc = 0;
2090
 
218 andreas 2091
		    POINT *oldPoint = 0;
2092
		    double sc, dist, speed;
222 andreas 2093
		    unsigned long t1, t2;
2094
		    t1 = t2 = 0;
2095
		    pause = false;
2096
		    bool ignore = false;
218 andreas 2097
 
88 andreas 2098
		    while (point)
2099
		    {
2100
		       if (point->time > (lap->start_time + (lap->total_time / 100)))
2101
			 break;
2102
 
249 andreas 2103
		       QTreeWidgetItem *child = new QTreeWidgetItem(trdetail);
2104
		       qt = garmin_dtime (point->time);
2105
		       child->setText(0, kl->formatTime(qt->time(), true));
2106
		       child->setTextAlignment(0, Qt::AlignRight);
2107
		       child->setText(8, QString("%1 %2").arg(kl->formatNumber((double)point->heart_rate, 0)).arg(" bpm"));
2108
		       child->setTextAlignment(8, Qt::AlignRight);
2109
 
2110
		       if (point->cadence < 0xff)
2111
		       {
2112
			  child->setText(10, kl->formatNumber((double)point->cadence, 0));
2113
			  child->setTextAlignment(10, Qt::AlignRight);
2114
		       }
2115
 
2116
		       if (point->alt < 20000)
2117
		       {
2118
		       double alt = (Units == 0) ? (double)point->alt : (double)point->alt / 0.304;
2119
 
2120
			  child->setText(11, QString("%1 %2").arg(kl->formatNumber(alt, 2)).arg((Units == 0) ? QString(" m") : QString(" ft")));
2121
			  child->setTextAlignment(11, Qt::AlignRight);
2122
		       }
2123
 
218 andreas 2124
		       if (!oldPoint)
2125
			  oldPoint = point;
2126
 
88 andreas 2127
		       if (point->alt > alt_asc && point->alt < 20000)
2128
		       {
2129
			  alt_asc = point->alt;
2130
 
2131
			  if (alt_dsc == 0)
2132
			     alt_dsc = point->alt;
2133
		       }
2134
 
2135
		       if (point->alt < alt_dsc)
2136
			  alt_dsc = point->alt;
2137
 
2138
		       // save the min and max values. We need this information to
2139
		       // build the graphics.
221 andreas 2140
		       if (point->heart_rate > max_hr && point->heart_rate < 250)
88 andreas 2141
			  max_hr = point->heart_rate;
2142
 
221 andreas 2143
		       if ((min_hr == 0 && point->heart_rate > 0 && point->heart_rate < 250)
2144
			   || (point->heart_rate > 0 && point->heart_rate < min_hr))
88 andreas 2145
			  min_hr = point->heart_rate;
2146
 
2147
		       if (point->alt < 20000 && max_height < point->alt)
2148
			  max_height = point->alt;
2149
 
2150
		       if (point->alt < 20000 && (min_height == 0.0 || min_height > point->alt))
2151
			  min_height = point->alt;
2152
 
218 andreas 2153
		       // Calculate speed of current track
222 andreas 2154
		       if (!pause && point->distance > 1.0e10)
2155
		       {
2156
			  t1 = point->time;
2157
			  pause = true;
2158
			  ignore = true;
2159
		       }
2160
		       else if (pause)
2161
		       {
2162
			  t2 = point->time;
2163
			  pause = false;
2164
			  point = ds.getPoint(point->time + 1);
2165
			  continue;
2166
		       }
218 andreas 2167
 
222 andreas 2168
		       if (!ignore && !pause)
2169
		       {
2170
			  sc = point->time - oldPoint->time;
2171
			  dist = point->distance - oldPoint->distance;
218 andreas 2172
 
249 andreas 2173
			  child->setText(1, QString("%1 %2").arg(kl->formatNumber((Units == 0) ? (double)dist : (double)dist / 0.304, 2)).arg((Units == 0) ? QString(" m") : QString(" ft")));
2174
			  child->setTextAlignment(1, Qt::AlignRight);
2175
 
222 andreas 2176
			  if (t2 > t1)
2177
			     sc -= t2 - t1;
218 andreas 2178
 
222 andreas 2179
			  if (sc > 0.0)
223 andreas 2180
			  {
222 andreas 2181
			     speed = (dist / sc) * 3.6;
223 andreas 2182
 
2183
			     if (speed > lap->max_speed * 3.6)
2184
			        speed = lap->max_speed * 3.6;
2185
			  }
222 andreas 2186
			  else
2187
			     speed = 0.0;
218 andreas 2188
 
222 andreas 2189
			  if (Units == 1)
2190
			     speed /= 1.609344;
218 andreas 2191
 
249 andreas 2192
			  child->setText(5, QString("%1 %2").arg(kl->formatNumber(speed, 2)).arg((Units == 0) ? QString(" Km/h") : QString(" mi/h")));
2193
			  child->setTextAlignment(5, Qt::AlignRight);
2194
 
222 andreas 2195
			  if (speed > 0.0 && speed < 400.0 && max_speed < speed)
2196
			     max_speed = speed;
2197
 
2198
			  if (speed > 0.0 && (min_speed == 0.0 || min_speed > speed))
2199
			     min_speed = speed;
2200
 
2201
			  oldPoint = point;
2202
		       }
2203
 
2204
		       if (!pause && ignore)
2205
			  ignore = false;
2206
 
221 andreas 2207
		       if (point->heart_rate > 0 && point->heart_rate < 250)
88 andreas 2208
		       {
2209
			  avg_hr += point->heart_rate;
2210
			  men++;
2211
		       }
2212
 
2213
		       point = ds.getPoint(point->time + 1);
2214
		    }
2215
 
149 andreas 2216
		    if (old_asc < alt_asc)
2217
		       sum_asc += (alt_asc - old_asc);
2218
 
2219
		    if (old_dsc > alt_dsc)
2220
		       sum_dsc += (old_dsc - alt_dsc);
2221
 
2222
		    old_asc = alt_asc;
2223
		    old_dsc = alt_dsc;
2224
		    qs_ascent.sprintf("%.2f %s", (Units == 1) ? (alt_asc / 0.304) : alt_asc, (Units == 1) ? "ft" : "m");
2225
		    qs_descent.sprintf("%.2f %s", (Units == 1) ? (alt_dsc / 0.304) : alt_dsc, (Units == 1) ? "ft" : "m");
88 andreas 2226
		 }
2227
 
2228
		 if (lap->avg_cadence != 0xff)
2229
		    qs_avgcadence.sprintf("%d", lap->avg_cadence);
248 andreas 2230
		 // Add a new detail line to the tab "Summary"
2231
		 K3ListViewItem *edetail = new K3ListViewItem(element, qs_name,
2232
			kl->formatNumber(qs_distance, false),
2233
			qs_etime, qs_avgpace, kl->formatNumber(qs_avgspeed, false),
2234
			kl->formatNumber(qs_maxspeed, false), qs_calories, qs_avghr);
88 andreas 2235
		 edetail->setText(8, qs_maxhr);
2236
		 edetail->setText(9, qs_avgcadence);
248 andreas 2237
		 edetail->setText(10, kl->formatNumber(qs_ascent, false));
2238
		 edetail->setText(11, kl->formatNumber(qs_descent, false));
245 andreas 2239
		 edetail->setPixmap(0, KIcon(QString("history")).pixmap(16));
2240
		 QPixmap qpx = KIcon(QString("other")).pixmap(16);
249 andreas 2241
 
248 andreas 2242
		 trdetail->setText(0, qs_etime);
2243
		 trdetail->setTextAlignment(0, Qt::AlignRight);
2244
		 trdetail->setText(1, kl->formatNumber(qs_distance));
2245
		 trdetail->setTextAlignment(1, Qt::AlignRight);
2246
		 trdetail->setText(2, kl->formatNumber(qs_totdist));
2247
		 trdetail->setTextAlignment(2, Qt::AlignRight);
2248
		 trdetail->setText(4, qs_avgpace);
2249
		 trdetail->setTextAlignment(4, Qt::AlignRight);
2250
		 trdetail->setText(5, kl->formatNumber(qs_avgspeed, false));
2251
		 trdetail->setTextAlignment(5, Qt::AlignRight);
2252
		 trdetail->setText(6, kl->formatNumber(qs_maxspeed, false));
2253
		 trdetail->setTextAlignment(6, Qt::AlignRight);
2254
		 trdetail->setText(7, qs_calories);
2255
		 trdetail->setTextAlignment(7, Qt::AlignRight);
2256
		 trdetail->setText(8, qs_avghr);
2257
		 trdetail->setTextAlignment(8, Qt::AlignRight);
2258
		 trdetail->setText(9, qs_maxhr);
2259
		 trdetail->setTextAlignment(9, Qt::AlignRight);
2260
		 trdetail->setText(10, qs_avgcadence);
2261
		 trdetail->setTextAlignment(10, Qt::AlignRight);
2262
		 trdetail->setText(11, kl->formatNumber(qs_ascent, false));
2263
		 trdetail->setTextAlignment(11, Qt::AlignRight);
2264
 
128 andreas 2265
		 switch (rakt->run->sport_type)
2266
		 {
232 andreas 2267
		    case D1000_running:
247 andreas 2268
		       edetail->setPixmap(0, KIcon(QString("spw-running")).pixmap(16));
232 andreas 2269
		    break;
2270
 
2271
		    case D1000_biking:
245 andreas 2272
		       edetail->setPixmap(0, KIcon(QString("bike")).pixmap(16));
232 andreas 2273
		    break;
2274
 
2275
		    case D1000_other:
2276
		       edetail->setPixmap(0, qpx);
2277
		    break;
2278
 
128 andreas 2279
		    default:
232 andreas 2280
		       edetail->setPixmap(0, qpx);
128 andreas 2281
		 }
2282
 
245 andreas 2283
		 ui_sportwatcherWidgetBase.liLaps->clearSelection();
88 andreas 2284
		 element->insertItem(edetail);
2285
		 delete qt;
2286
		 laps++;
2287
	      }
149 andreas 2288
 
2289
	      qs_ascent.sprintf("%.2f %s", (Units == 1) ? sum_asc / 0.304 : sum_asc, (Units == 1) ? "ft" : "m");
2290
	      qs_descent.sprintf("%.2f %s", (Units == 1) ? sum_dsc / 0.304 : sum_dsc, (Units == 1) ? "ft" : "m");
2291
      	      element->setText(10, qs_ascent);
2292
	      element->setText(11, qs_descent);
248 andreas 2293
	      qs_ascent.sprintf("%s %s", (Units == 1) ? kl->formatNumber(ds.getAscend() / 0.304, 2).toAscii().data() : kl->formatNumber(ds.getAscend(), 2).toAscii().data(), (Units == 1) ? "ft" : "m");
2294
	      ui_sportwatcherWidgetBase.edTotalHeight->clear();
2295
	      ui_sportwatcherWidgetBase.edTotalHeight->insert(qs_ascent);
2296
	      ui_sportwatcherWidgetBase.edLapNumber->setAlignment(Qt::AlignRight);
2297
	      ui_sportwatcherWidgetBase.edLapNumber->insert(kl->formatNumber((double)laps, 0));
88 andreas 2298
	   }
2299
 
2300
	   rakt = rakt->next;
2301
	}
2302
 
2303
	if (men > 0)
2304
	   avg_hr /= men;
221 andreas 2305
	else
2306
	   min_hr = max_hr = avg_hr = 0;
88 andreas 2307
}
2308
 
100 andreas 2309
void sportwatcherWidget::showTrack()
2310
{
132 andreas 2311
	showTrack(0, QRect(0, 0, 0, 0), 0);
104 andreas 2312
}
2313
 
2314
void sportwatcherWidget::showTrack(int zoom)
2315
{
132 andreas 2316
	showTrack(zoom, mapPan, mapLap);
2317
}
2318
 
2319
void sportwatcherWidget::showTrack(int zoom, const QRect &pan, LAP *lap)
2320
{
100 andreas 2321
int width, height;
2322
double x1, y1, x2, y2;
132 andreas 2323
int a, top, left, panX, panY;
2324
uint32 i;
109 andreas 2325
double coordW, coordH, tick;
156 andreas 2326
double meterW, dist, fact;
100 andreas 2327
QPainter paint;
152 andreas 2328
posn_type posNW, posSE, posLXY, posRXY;
100 andreas 2329
POINT *point;
152 andreas 2330
bool Fgeo = false;
157 andreas 2331
bool Data = false;
232 andreas 2332
#if defined HAVE_GDAL
158 andreas 2333
QString fName = MAP;
2334
//double adfGeoTransform[6];
2335
GDALDataset *poDataset = 0;
246 andreas 2336
GDALRasterBand *poBand = 0;
2337
unsigned char *pafScanline = 0;
2338
unsigned char *pafScanlineRed = 0;
2339
unsigned char *pafScanlineGreen = 0;
2340
unsigned char *pafScanlineBlue = 0;
2341
unsigned char *pafScanlineAlpha = 0;
151 andreas 2342
int nXSize, nYSize;
159 andreas 2343
int xOff, yOff;
158 andreas 2344
double oriLeftLon, oriLeftLat, oriRightLon, oriRightLat;
151 andreas 2345
#endif
100 andreas 2346
 
248 andreas 2347
	if (!DIRTY || curTab == 2 || curTab == 3)
246 andreas 2348
	   return;
2349
 
109 andreas 2350
	if (!gmn)
2351
	   return;
2352
 
154 andreas 2353
	QApplication::setOverrideCursor (QCursor(Qt::WaitCursor));
2354
 
104 andreas 2355
	if (zoom != zfactor)
2356
	   zfactor = zoom;
2357
 
132 andreas 2358
	if (mapLap != lap)
2359
	   mapLap = lap;
2360
 
232 andreas 2361
#if defined HAVE_GDAL
2362
	KConfig cfg (QString("sportwatcher.rc"), KConfig::SimpleConfig);
2363
	KConfigGroup wms (&cfg, "WMS");
2364
	bool square = wms.readEntry("Square", false);
2365
	int CorrX = wms.readEntry("CorrX", 0);
2366
	int CorrY = wms.readEntry("CorrY", 0);
2367
	KConfigGroup ic (&cfg, "ImageCoords");
2368
	oriLeftLon = ic.readEntry("LeftLon", 0.0);
2369
	oriLeftLat = ic.readEntry("LeftLat", 0.0);
2370
	oriRightLon = ic.readEntry("RightLon", 0.0);
2371
	oriRightLat = ic.readEntry("RightLat", 0.0);
2372
//	int isrs = ic.readEntry("SRS", 0);
157 andreas 2373
#endif
248 andreas 2374
	if (curTab == 0)
2375
	{
2376
	   width = ui_sportwatcherWidgetBase.imgMap->width() - 2;
2377
	   height = ui_sportwatcherWidgetBase.imgMap->height();
2378
	}
2379
	else
2380
	{
2381
	   width = ui_sportwatcherWidgetBase.grMap->width() - 2;
2382
	   height = ui_sportwatcherWidgetBase.grMap->height();
2383
	}
232 andreas 2384
#if defined HAVE_GDAL
158 andreas 2385
	if (MapType == MPT_WMS && square)
232 andreas 2386
	   pmMap = QPixmap(width / (int)mFactor * (int)mFactor, height / (int)mFactor * (int)mFactor);
157 andreas 2387
	else
232 andreas 2388
	   pmMap = QPixmap(width, height);
157 andreas 2389
#else
232 andreas 2390
	pmMap = QPixmap(width, height);
157 andreas 2391
#endif
245 andreas 2392
	if (pmMap.isNull())
2393
	   return;
2394
 
2395
	// Here we begin do draw something
100 andreas 2396
	paint.begin(&pmMap);
2397
 
132 andreas 2398
	panX = panY = 0;
2399
 
2400
	if (stateHand && mapPan != pan)
2401
	{
2402
	   mapPan = pan;
2403
	   panX = mapPan.right() - mapPan.left();
2404
	   panY = mapPan.bottom() - mapPan.top();
2405
	   oldTransX += (double)panX;
2406
	   oldTransY += (double)panY;
2407
	}
2408
 
104 andreas 2409
	memset(&posNW, 0, sizeof(posn_type));
2410
	memset(&posSE, 0, sizeof(posn_type));
100 andreas 2411
 
156 andreas 2412
	posSE.lat = 90.0;
2413
	posSE.lon = 180.0;
2414
	posNW.lat = -90.0;
2415
	posNW.lon = -180.0;
100 andreas 2416
 
2417
	/*
2418
	 * Find out the corners of our track (NW, NE, SE, SW)
2419
	 */
132 andreas 2420
	if (mapLap)
2421
	   i = mapLap->start_time;
2422
	else
2423
	   i = 0;
100 andreas 2424
 
2425
	while ((point = ds.getPoint(i)) != 0)
2426
	{
132 andreas 2427
	   if (mapLap && point->time > (mapLap->start_time + (mapLap->total_time / 100)))
2428
	      break;
2429
 
100 andreas 2430
	   if (point->posn.lat == 0x7fffffff || point->posn.lon == 0x7fffffff)
2431
	   {
132 andreas 2432
	      i = point->time + 1;
100 andreas 2433
	      continue;
2434
	   }
2435
 
2436
	   if (SEMI2DEG(point->posn.lat) > posNW.lat)
2437
	      posNW.lat = SEMI2DEG(point->posn.lat);
2438
 
2439
	   if (SEMI2DEG(point->posn.lat) < posSE.lat)
2440
	      posSE.lat = SEMI2DEG(point->posn.lat);
2441
 
156 andreas 2442
	   if (SEMI2DEG(point->posn.lon) > posNW.lon)
100 andreas 2443
	      posNW.lon = SEMI2DEG(point->posn.lon);
2444
 
156 andreas 2445
	   if (SEMI2DEG(point->posn.lon) < posSE.lon)
100 andreas 2446
	      posSE.lon = SEMI2DEG(point->posn.lon);
2447
 
132 andreas 2448
	   i = point->time + 1;
157 andreas 2449
	   Data = true;
100 andreas 2450
	}
104 andreas 2451
 
2452
	coordW = (posNW.lon > posSE.lon) ? posNW.lon - posSE.lon : posSE.lon - posNW.lon;
2453
	coordH = (posNW.lat > posSE.lat) ? posNW.lat - posSE.lat : posSE.lat - posNW.lat;
109 andreas 2454
	meterW = ds.earth_distance(posNW.lat, posNW.lon, posNW.lat, posSE.lon);
104 andreas 2455
 
2456
	// define the ticks to translate the GPS coordinates into pixels.
2457
	// The track should be centered and we have to calculate the
2458
	// rectangular within we draw the track.
152 andreas 2459
	if (coordW < coordH)
100 andreas 2460
	{
152 andreas 2461
	   tick = (double)width / coordW + (double)zoom;
2462
 
2463
	   if ((tick * coordH) > height)
109 andreas 2464
	      tick = (double)height / coordH + (double)zoom;
100 andreas 2465
	}
2466
	else
2467
	{
152 andreas 2468
	   tick = (double)height / coordH + (double)zoom;
2469
 
2470
	   if ((tick * coordW) > width)
109 andreas 2471
	      tick = (double)width / coordW + (double)zoom;
100 andreas 2472
	}
104 andreas 2473
 
156 andreas 2474
	left = width - (width - tick * coordW) / 2;
152 andreas 2475
	top = (height - tick * coordH) / 2;
2476
 
132 andreas 2477
	a = tick * coordW;
156 andreas 2478
 
2479
	if (Units == 0)
2480
	   dist = meterW / a;			// Meters
2481
	else
2482
	   dist = meterW * 1.609344 / a;	// 1/1000 mile (5.28 feet)
2483
 
232 andreas 2484
#if defined HAVE_GDAL
159 andreas 2485
	geoRect.llat = 0.0;
2486
	geoRect.llon = 0.0;
2487
	geoRect.rlat = 0.0;
2488
	geoRect.rlon = 0.0;
158 andreas 2489
	geoRect.width = width;
2490
	geoRect.height = height;
146 andreas 2491
	/*
2492
	 * If we have a map file, we try to read it and if successfull,
2493
	 * we should get a map painted.
154 andreas 2494
	 *
2495
	 * Currently only WMS-Server is supported, allthough GDAL allows
2496
	 * several other formats too.
146 andreas 2497
	 */
157 andreas 2498
	if (!MAP.isEmpty() && Data)
146 andreas 2499
	{
158 andreas 2500
	bool writeTag = true;
2501
	double mtx, mty;
2502
	double vx, vy;
152 andreas 2503
 
158 andreas 2504
	   xOff = yOff = 0;
2505
	   posRXY.lon = posNW.lon + (width - left + oldTransX) / tick;
2506
	   posLXY.lat = posNW.lat + (top + oldTransY) / tick;
2507
	   posLXY.lon = posSE.lon - (left - a - oldTransX) / tick;
2508
	   posRXY.lat = posSE.lat - (height - top - (tick * coordH) - oldTransY) / tick;
159 andreas 2509
	   geoRect.llat = posLXY.lat;
2510
	   geoRect.llon = posLXY.lon;
2511
	   geoRect.rlat = posRXY.lat;
2512
	   geoRect.rlon = posRXY.lon;
158 andreas 2513
	   // width and height of map in meters
2514
	   mtx = ds.earth_distance(posRXY.lat, posRXY.lon, posRXY.lat, posLXY.lon);
2515
	   mty = ds.earth_distance(posRXY.lat, posRXY.lon, posLXY.lat, posRXY.lon);
157 andreas 2516
 
158 andreas 2517
	   // factor to correct the map, in case we use a WMS server
2518
	   if (MapType == MPT_WMS)
2519
	   {
2520
	      vx = (posRXY.lon - posLXY.lon) / mtx * CorrX;
2521
	      vy = (posRXY.lat - posLXY.lat) / mty * CorrY;
2522
	      posRXY.lon += vx;
2523
	      posRXY.lat += vy;
2524
	      posLXY.lon += vx;
2525
	      posLXY.lat += vy;
2526
	   }
2527
 
154 andreas 2528
	   /*
158 andreas 2529
	    * Write a control file for GDAL, if we use a WMS server.
2530
	    * Warp an image if we use PNG or BMP or GIF.
2531
	    * Warp a region if we use TIFF
154 andreas 2532
	    */
158 andreas 2533
	   if (MapType == MPT_WMS)
2534
	      writeTag = writeWMSTag(posLXY.lon, posLXY.lat, posRXY.lon, posRXY.lat, width, height);
2535
 
159 andreas 2536
	   if (MapType == MPT_GIF || MapType == MPT_BMP || MapType == MPT_PNG ||
2537
	       MapType == MPT_SGI || MapType == MPT_TIF)
158 andreas 2538
	      writeTag = warpImage(MAP, &fName);
2539
 
2540
	   if (writeTag)
151 andreas 2541
	   {
246 andreas 2542
	      if (MapType != MPT_SHP && (poDataset = (GDALDataset *)GDALOpen (fName.toAscii().constData(), GA_ReadOnly)) != NULL)
151 andreas 2543
	      {
2544
		 QPixmap bild;
2545
		 int nRasterCount = poDataset->GetRasterCount();
2546
		 int nXBlock, nYBlock;
154 andreas 2547
		 GDALColorTable *pCT, *pCTb, *pCTr, *pCTg, *pCTa;
146 andreas 2548
 
151 andreas 2549
		 int             bGotMin, bGotMax;
2550
		 int		 tTypeLen, tColor, tColorEntrys;
2551
		 GDALDataType    tRasterType;
2552
		 double          adfMinMax[2];
2553
 
154 andreas 2554
		 pafScanlineRed = pafScanlineGreen = pafScanlineBlue = pafScanlineAlpha = 0;
246 andreas 2555
		 Fgeo = true;
154 andreas 2556
		 /*
2557
		  * Read every raster band.
2558
		  *
2559
		  * If we get 3 raster bands, the image is a 24 bit image.
2560
		  * If we get 4 raster bands, the image is probably a 24 bit
2561
		  * image with an alpha channel. Currently the alpha channel
2562
		  * is ignored!
2563
		  * If we have 1 raster band, the image is 8 bit monochrom.
2564
		  * Otherwise the image is undefined and the results are also.
2565
		  */
151 andreas 2566
		 for (a = 1; a <= nRasterCount; a++)
2567
		 {
246 andreas 2568
		    if (!Fgeo)
2569
		       break;
2570
 
245 andreas 2571
		    if (!(poBand = poDataset->GetRasterBand (a)))
2572
		    {
2573
		       paint.end();
2574
		       return;
2575
		    }
2576
 
151 andreas 2577
		    poBand->GetBlockSize (&nXBlock, &nYBlock);
2578
		    nXSize = poBand->GetXSize();
2579
		    nYSize = poBand->GetYSize();
2580
		    tRasterType = poBand->GetRasterDataType ();
2581
		    tTypeLen = GDALGetDataTypeSize (tRasterType) / 8;	// We need Bytes not Bits!
2582
		    tColor = poBand->GetColorInterpretation ();
2583
 
2584
		    adfMinMax[0] = poBand->GetMinimum (&bGotMin);
2585
		    adfMinMax[1] = poBand->GetMaximum (&bGotMax);
2586
 
2587
		    if (!(bGotMin && bGotMax))
2588
		       GDALComputeRasterMinMax ((GDALRasterBandH)poBand, TRUE, adfMinMax);
2589
 
152 andreas 2590
		    if ((pCT = poBand->GetColorTable()) != NULL)
151 andreas 2591
		       tColorEntrys = poBand->GetColorTable()->GetColorEntryCount();
2592
 
2593
		    switch (a)
2594
		    {
152 andreas 2595
		       case 1: pafScanlineRed   = new unsigned char[tTypeLen * nXSize * nYSize]; pafScanline = pafScanlineRed; pCTr = pCT; break;
2596
		       case 2: pafScanlineGreen = new unsigned char[tTypeLen * nXSize * nYSize]; pafScanline = pafScanlineGreen; pCTg = pCT; break;
2597
		       case 3: pafScanlineBlue  = new unsigned char[tTypeLen * nXSize * nYSize]; pafScanline = pafScanlineBlue; pCTb = pCT; break;
154 andreas 2598
		       case 4: pafScanlineAlpha  = new unsigned char[tTypeLen * nXSize * nYSize]; pafScanline = pafScanlineAlpha; pCTa = pCT; break;
151 andreas 2599
		    }
2600
 
246 andreas 2601
		    if (!pafScanline)
2602
		    {
2603
		       paint.end();
2604
		       KMessageBox::error(this, i18n("Not enough memory for a raster operation!"));
2605
		       return;
2606
		    }
2607
 
152 andreas 2608
		    memset (pafScanline, 0, tTypeLen * nXSize * nYSize);
151 andreas 2609
 
154 andreas 2610
		    /*
158 andreas 2611
		     * Get the image (from the server) and put the tiles together.
154 andreas 2612
		     *
2613
		     * The function reads only one raster band. This is,
2614
		     * because the function is called for every raster band and
2615
		     * every raster band is stored into a separate array.
2616
		     */
152 andreas 2617
		    if (poBand->RasterIO (GF_Read, 0, 0, nXSize, nYSize, pafScanline, nXSize, nYSize, tRasterType, 0, 0) == CE_Failure)
2618
		    {
248 andreas 2619
		       paint.end();
151 andreas 2620
		       KMessageBox::error(this, i18n("Error reading a raster band!"));
248 andreas 2621
		       paint.begin(&pmMap);
152 andreas 2622
		       Fgeo = false;
2623
		       break;
2624
		    }
2625
		    else
2626
		       Fgeo = true;
151 andreas 2627
		 }
2628
 
154 andreas 2629
		 /*
2630
		  * Only if Fgeo is TRUE, we've read successfully all raster
2631
		  * bands. Now we have to put the bands together to get
2632
		  * an image.
2633
		  */
152 andreas 2634
		 if (Fgeo)
2635
		 {
2636
		 unsigned char *pCombinedBytes = new unsigned char[(tTypeLen * nXSize * nYSize * nRasterCount)];
2637
		 unsigned char *ptr_dest, *ptr_src;
2638
		 int j;
151 andreas 2639
 
245 andreas 2640
		    ptr_dest = ptr_src = 0;
2641
 
154 andreas 2642
		    /*
2643
		     * We need two nested loops to set the pixels in the wanted
2644
		     * order.
2645
		     */
152 andreas 2646
		    for (a = 0, j = 0; a < (nXSize * nYSize * nRasterCount); a += nRasterCount, j++)
151 andreas 2647
		    {
152 andreas 2648
		       int k = a;
2649
 
2650
		       for (int m = nRasterCount - 1; m >= 0; m--, k++)
2651
		       {
245 andreas 2652
		       unsigned char *pBytes = 0;
152 andreas 2653
 
2654
			  switch (m)
2655
			  {
154 andreas 2656
			     case 3: pBytes = pafScanlineAlpha; pCT = pCTa; break;
152 andreas 2657
			     case 2: pBytes = pafScanlineBlue; pCT = pCTb; break;
2658
			     case 1: pBytes = pafScanlineGreen; pCT = pCTg; break;
2659
			     default: pBytes = pafScanlineRed; pCT = pCTr;
2660
			  }
2661
 
2662
			  ptr_dest = pCombinedBytes + k;
2663
			  unsigned char b = pBytes[j];
2664
 
154 andreas 2665
			  /*
2666
			   * If we have a color table, the pixels are pointers
2667
			   * to the color table. We need to convert them into
2668
			   * 24 bit pixels plus an optional alpha channel.
2669
			   */
152 andreas 2670
			  if (pCT != NULL)
2671
			  {
2672
			     GDALColorEntry ce;
2673
			     unsigned int c = (unsigned int)b;
2674
			     c = pCT->GetColorEntryAsRGB (c, &ce);
2675
 
2676
			     if  (m == 0) c = ce.c1;
2677
			     if  (m == 1) c = ce.c2;
2678
			     if  (m == 2) c = ce.c3;
154 andreas 2679
			     if  (m == 3) c = ce.c4;
152 andreas 2680
 
2681
			     b = (unsigned char)c;
2682
			  }
2683
 
2684
			  ptr_src = &b;
2685
			  memcpy (ptr_dest, ptr_src, 1);
2686
		       }
151 andreas 2687
		    }
152 andreas 2688
 
2689
		    x1 = y1 = 0;
2690
 
154 andreas 2691
		    /*
2692
		     * The following loop is QT specific! It sets the pixels
2693
		     * of the raw image, pixel by pixel. This may be slow, but
2694
		     * everything else didn't work :-(
2695
		     *
2696
		     * FIXME: We need a more effective routine to put the
158 andreas 2697
		     *        raw image into QT's "painter" class.
154 andreas 2698
		     */
2699
		    for (a = 0; a < (nXSize * nYSize * nRasterCount); a += nRasterCount)
152 andreas 2700
		    {
158 andreas 2701
		       if (x1 < width && y1 < height)
2702
		       {
2703
			  if (nRasterCount == 3)
232 andreas 2704
			     paint.setPen (QPen(QColor((int)pCombinedBytes[a+2], (int)pCombinedBytes[a+1], (int)pCombinedBytes[a]), Qt::SolidLine));
158 andreas 2705
			  else if (nRasterCount > 3)
232 andreas 2706
			     paint.setPen (QPen(QColor(qRgba((int)pCombinedBytes[a+3], (int)pCombinedBytes[a+2], (int)pCombinedBytes[a+1], (int)pCombinedBytes[a])), Qt::SolidLine));
158 andreas 2707
			  else if (nRasterCount == 2)
232 andreas 2708
			     paint.setPen (QPen(QColor((int)pCombinedBytes[a+1], (int)pCombinedBytes[a], (int)pCombinedBytes[a+1]), Qt::SolidLine));
158 andreas 2709
			  else if (nRasterCount == 1)
232 andreas 2710
			     paint.setPen (QPen(QColor((int)pCombinedBytes[a], (int)pCombinedBytes[a], (int)pCombinedBytes[a]), Qt::SolidLine));
154 andreas 2711
 
158 andreas 2712
			  paint.drawPoint(x1, y1);
2713
		       }
2714
 
152 andreas 2715
		       x1++;
2716
 
2717
		       if (x1 >= nXSize)
2718
		       {
2719
			  x1 = 0;
2720
			  y1++;
2721
		       }
2722
		    }
2723
 
2724
		    delete pCombinedBytes;
245 andreas 2725
		    pCombinedBytes = 0;
151 andreas 2726
		 }
2727
 
152 andreas 2728
		 if (pafScanlineRed)
2729
		    delete pafScanlineRed;
151 andreas 2730
 
152 andreas 2731
		 if (pafScanlineGreen)
2732
		    delete pafScanlineGreen;
2733
 
2734
		 if (pafScanlineBlue)
2735
		    delete pafScanlineBlue;
2736
 
154 andreas 2737
		 if (pafScanlineAlpha)
2738
		    delete pafScanlineAlpha;
2739
 
152 andreas 2740
		 GDALClose (poDataset);
2741
		 poDataset = 0;
158 andreas 2742
 
2743
		 if (MAP != fName)
232 andreas 2744
		    unlink (fName.toAscii().data());
151 andreas 2745
	      }
158 andreas 2746
	      else if (MapType == MPT_SHP)
2747
	      {
2748
		 QDir shpd(MAP, QString("*.shp"));
2749
 
2750
		 if (shpd.count() < 1)
2751
		 {
275 andreas 2752
		    KMessageBox::error(this, i18n("There is no shape file in directory %1").arg(MAP));
158 andreas 2753
		    Fgeo = false;
2754
		 }
2755
		 else
2756
		 {
274 andreas 2757
		 SRender rd;
275 andreas 2758
		 QColor bg(220, 220, 220);		// background color
158 andreas 2759
 
275 andreas 2760
		    if (curTab == 0)
2761
		       rd.setDrawArea(*ui_sportwatcherWidgetBase.imgMap);
2762
		    else
2763
		       rd.setDrawArea(*ui_sportwatcherWidgetBase.grMap);
2764
 
2765
		    if (rd.getMap(posLXY.lon, posLXY.lat, posRXY.lon, posRXY.lat))
2766
		    {
2767
		       paint.fillRect(0, 0, width+2, height+2, bg);
2768
//		       QPixmap qpx;
2769
//		       qpx.load(rd.getOutBuf());
2770
//cout << "Pixmap loaded from: " << rd.getOutBuf().toAscii().data() << endl;
2771
		       if (curTab == 0)
2772
			  paint.drawPixmap(0, 0, *ui_sportwatcherWidgetBase.imgMap->pixmap());
2773
		       else
2774
			  paint.drawPixmap(0, 0, *ui_sportwatcherWidgetBase.grMap->pixmap());
2775
 
2776
		       Fgeo = true;
2777
		    }
2778
		    else
2779
		       Fgeo = false;
158 andreas 2780
		 }
2781
	      }
151 andreas 2782
	      else
157 andreas 2783
	      {
158 andreas 2784
		 KMessageBox::error(this, i18n("Error opening map file!"));
157 andreas 2785
		 Fgeo = false;
2786
	      }
151 andreas 2787
	   }
146 andreas 2788
	}
151 andreas 2789
#endif
154 andreas 2790
	/*
2791
	 * Here we come to draw the track. It will be drawn over the previous
2792
	 * created map image.
2793
	 */
100 andreas 2794
	// Colors and fonts
154 andreas 2795
	QColor background(220, 220, 220);		// background color
2796
	QColor red(255, 0, 0);				// mile marker
2797
	QColor black(0, 0, 0);				// Text, center of track
2798
//	QColor yellow(255, 255, 0);
2799
	QColor yellow(0x00cf, 0x00ff, 0x0000);		// color of track
100 andreas 2800
	QFont fntNormal("Helvetica");
2801
	fntNormal.setPixelSize(10);
2802
	fntNormal.setStyleHint(QFont::Helvetica);
232 andreas 2803
	QPen dot(red, 4, Qt::SolidLine);
2804
	QPen line(black, 2, Qt::SolidLine);
247 andreas 2805
	QPen yline(yellow, 4, Qt::SolidLine);
154 andreas 2806
	// Fill background with background colors, if there is no map.
152 andreas 2807
	if (!Fgeo)
2808
	   paint.fillRect(0, 0, width+2, height+2, background);
2809
 
156 andreas 2810
	if (Units == 0)
2811
	   fact = 1000.0;
2812
	else
2813
	   fact = 1609.344;
2814
 
109 andreas 2815
	paint.setPen(line);
2816
	paint.drawLine(10, height - 9, 10, height - 4);
156 andreas 2817
	paint.drawLine(10, height - 4, 10 + (fact / dist), height - 4);
2818
	paint.drawLine(10 + (fact / dist), height - 9, 10 + (fact / dist), height - 4);
109 andreas 2819
	paint.setFont(fntNormal);
2820
 
156 andreas 2821
	if (Units == 0)
2822
	   paint.drawText(10, height - 10, QString("1000 m"));
2823
	else
2824
	   paint.drawText(10, height - 10, QString("5280 ft"));
2825
 
100 andreas 2826
	// Draw track
132 andreas 2827
	if (mapLap)
2828
	   i = mapLap->start_time;
2829
	else
2830
	   i = 0;
2831
 
100 andreas 2832
	x1 = y1 = 0.0;
157 andreas 2833
	bool wStart = false;
104 andreas 2834
 
100 andreas 2835
	while ((point = ds.getPoint(i)) != 0)
2836
	{
132 andreas 2837
	   if (mapLap && point->time > (mapLap->start_time + (mapLap->total_time / 100)))
2838
	      break;
2839
 
100 andreas 2840
	   if (point->posn.lat == 0x7fffffff || point->posn.lon == 0x7fffffff)
2841
	   {
132 andreas 2842
	      i = point->time + 1;
100 andreas 2843
	      continue;
2844
	   }
2845
 
157 andreas 2846
	   x2 = (left + ((posNW.lon - SEMI2DEG(point->posn.lon)) * tick * -1)) + oldTransX;
2847
	   y2 = (top + ((posNW.lat - SEMI2DEG(point->posn.lat)) * tick)) + oldTransY;
100 andreas 2848
 
157 andreas 2849
	   if (!wStart && x1 != 0.0 && y1 != 0.0)
2850
	   {
2851
	      // Load the start symbol
245 andreas 2852
	      QPixmap qpx (KIcon(QString("wstart")).pixmap(16));
157 andreas 2853
	      // Find the angle of the track and turn the symbol accordingly
2854
	      // we use Pythagoras to calculate the triangle
2855
	      double xl = (x1 < x2) ? x2 - x1 : x1 - x2;
2856
	      double yl = (y1 < y2) ? y2 - y1 : y1 - y2;
2857
	      double da = fmin (xl, yl);
2858
	      double db = fmax (xl, yl);
2859
	      double zl = sqrt (pow (da, 2) + pow (db, 2));
2860
	      double angle = (asin(da / zl) / M_PIl) * 180.0;
2861
 
2862
	      angle = (angle > 45.0) ? 90.0 - angle : angle;
2863
// cout << "Winkel: " << angle << " ---- X: " << xl << ", Y: " << yl << ", Z: " << zl << ", Point (x1,y1,x2,y2): " << x1 << ", " << y1 << ", " << x2 << ", " << y2 << endl;
2864
	      if (x1 < x2 && y1 < y2)		// right, down
2865
		 angle = 90.0 + angle;
2866
	      else if (x1 > x2 && y1 < y2)	// left, down
2867
		 angle = 270.0 - angle;
2868
	      else if (x1 > x2 && y1 > y2)	// left, up
2869
		 angle = 270.0 + angle;
2870
	      else				// right, up
2871
		 angle = 90.0 - angle;
2872
// cout << "Realer Winkel: " << angle << endl;
2873
	      // Set the center of the symbol
2874
	      paint.save ();
2875
	      paint.translate (x1, y1);
2876
	      // rotate the symbol
2877
	      paint.rotate (angle);
2878
	      paint.drawPixmap (-8, -8, qpx);
2879
	      paint.restore ();
2880
	      wStart = true;
2881
	   }
2882
 
100 andreas 2883
	   if (x1 == 0.0 && y1 == 0.0)
2884
	   {
2885
	      x1 = x2;
2886
	      y1 = y2;
2887
	   }
104 andreas 2888
 
100 andreas 2889
	   paint.setPen(yline);
104 andreas 2890
	   paint.drawLine(x1, y1, x2, y2);
2891
 
156 andreas 2892
	   if ((point->distance - dist) >= fact)	// a dot at every 1000 meters or at 1 mile
104 andreas 2893
	   {
2894
	      paint.setPen(dot);
154 andreas 2895
	      paint.drawEllipse(x2-2, y2-2, 3, 3);
156 andreas 2896
	      dist = (int)(point->distance / fact) * fact;
104 andreas 2897
	   }
2898
 
100 andreas 2899
	   paint.setPen(line);
2900
	   paint.drawLine(x1, y1, x2, y2);
2901
	   x1 = x2;
2902
	   y1 = y2;
132 andreas 2903
	   i = point->time + 1;
100 andreas 2904
	}
2905
 
157 andreas 2906
	bool lastLap = false;
2907
 
2908
	if (mapLap)
2909
	   if (ds.getRunNode()->run->last_lap_index == mapLap->index)
2910
	      lastLap = true;
2911
 
2912
	if ((!mapLap || lastLap) && wStart)
2913
	{
2914
	   // load the end symbol
245 andreas 2915
	   QPixmap qpx (KIcon(QString("wtarget")).pixmap(16));
157 andreas 2916
	   paint.drawPixmap (x2, y2 - 16, qpx);
2917
	}
2918
 
100 andreas 2919
	paint.end();
248 andreas 2920
 
2921
	if (curTab == 0)
2922
	   ui_sportwatcherWidgetBase.imgMap->setPixmap(pmMap);
2923
	else
2924
	   ui_sportwatcherWidgetBase.grMap->setPixmap(pmMap);
2925
 
154 andreas 2926
	QApplication::restoreOverrideCursor();
100 andreas 2927
}
2928
 
245 andreas 2929
void sportwatcherWidget::kcbCurveSlot(int)
2930
{
246 andreas 2931
	DIRTY = true;
245 andreas 2932
	showCurves();
246 andreas 2933
	DIRTY = false;
245 andreas 2934
}
2935
 
248 andreas 2936
void sportwatcherWidget::tabViewSlot(int tab)
2937
{
2938
	curTab = tab;
2939
 
2940
	if (tab == 0 && tabDirt0)
2941
	{
2942
	   DIRTY = true;
2943
	   showLaps();
2944
	   showTrack();
2945
	   showCurves();
2946
	   DIRTY = false;
2947
	   tabDirt0 = false;
2948
	}
2949
	else if (tab == 1 && tabDirt1)
2950
	{
2951
	   DIRTY = true;
2952
 
2953
	   if (tabDirt0)
2954
	      showLaps();
2955
 
2956
	   showTrack();
2957
	   DIRTY = false;
2958
	   tabDirt1 = false;
2959
	}
250 andreas 2960
	else if (tab == 2 && tabDirt2)
2961
	{
2962
	   DIRTY = true;
2963
 
2964
	   if (tabDirt0)
2965
	      showLaps();
2966
 
2967
	   setMouseTracking (true);
2968
	   ui_sportwatcherWidgetBase.tabView->setMouseTracking (true);
2969
	   ui_sportwatcherWidgetBase.grHR->setMouseTracking (true);
2970
	   ui_sportwatcherWidgetBase.grElevation->setMouseTracking (true);
2971
	   ui_sportwatcherWidgetBase.grSpeed->setMouseTracking (true);
2972
	   showThreeCurve();
2973
	   tabDirt2 = false;
2974
	   DIRTY = false;
2975
	}
248 andreas 2976
}
2977
 
88 andreas 2978
void sportwatcherWidget::showCurves()
2979
{
148 andreas 2980
	showCurves (mapLap);
2981
}
2982
 
2983
void sportwatcherWidget::showCurves(LAP *lap)
2984
{
88 andreas 2985
QPainter paint;
2986
int width, height;
218 andreas 2987
int i, secs, cuType;
88 andreas 2988
int lineHeight, margin_left, margin_right, margin_bottom;
2989
int x1, y1, x2, y2;		// Coordinates
2990
bool meter;
218 andreas 2991
double maxHeight, minHeight, maxSpeed, minSpeed;
88 andreas 2992
int maxHr, minHr, rh;
2993
POINT *point;
148 andreas 2994
RUN_NODE *rn;
2995
LAP *lp;
88 andreas 2996
double w_tick, h_tick;		// Number of pixels one "tick" has;
2997
				// This depends on the width and height
2998
				// of the image.
2999
	// First we draw a grid based on the min and max
3000
	// values detected in the function showLap(). In case
3001
	// all values are 0, we exit here.
3002
	if (min_hr == 0 && max_hr == 0 && min_height == 0.0 && max_height == 0.0)
3003
	   return;
3004
 
248 andreas 3005
	if (!DIRTY || curTab != 0)
246 andreas 3006
	   return;
3007
 
218 andreas 3008
	// Look up, what curves we should draw
245 andreas 3009
	cuType = ui_sportwatcherWidgetBase.kcbCurveTypes->currentIndex();
218 andreas 3010
	// Get the dimensions of the available draw area
245 andreas 3011
	width = ui_sportwatcherWidgetBase.imgProfile->width() - 2;
3012
	height = ui_sportwatcherWidgetBase.imgProfile->height();
232 andreas 3013
	pmProfile = QPixmap(width, height);
88 andreas 3014
	paint.begin(&pmProfile);
3015
 
3016
	// we need a somewhat bigger area to draw our curves than
3017
	// we have with the real min and max values.
3018
	if (max_height > 0.0)
3019
	{
148 andreas 3020
	double add = (max_height - min_height) / 100.0 * 5.0;	// Percent
88 andreas 3021
 
3022
	   maxHeight = max_height + add;
3023
	   minHeight = min_height - add;
3024
 
3025
	   if (minHeight < 0.0)		// make sure, we are not too deep
3026
	      minHeight = 0.0;
3027
	}
221 andreas 3028
	else
3029
	   maxHeight = minHeight = 0.0;
88 andreas 3030
 
218 andreas 3031
	if (max_speed > 0.0)
3032
	{
3033
	double add = (max_speed - min_speed) / 100.0 * 5.0;	// Percent
3034
 
3035
	   maxSpeed = max_speed + add;
3036
	   minSpeed = min_speed - add;
3037
 
3038
	   if (minSpeed < 0.0)		// make sure, we are not too deep
3039
	      minSpeed = 0.0;
3040
	}
221 andreas 3041
	else
3042
	   maxSpeed = minSpeed = 0.0;
218 andreas 3043
 
88 andreas 3044
	if (max_hr > 0)
3045
	{
3046
	   maxHr = max_hr + 10;
3047
	   minHr = min_hr - 10;
3048
 
3049
	   if (minHr < 0)
3050
	      minHr = 0;
3051
	}
221 andreas 3052
	else
3053
	   maxHr = minHr = 0;
88 andreas 3054
 
3055
	// Define colors
148 andreas 3056
	QColor background(220, 220, 220);	// Background of graphic
3057
	QColor mark(255, 255, 255);		// Lines inside curve area
3058
	QColor hlight(180, 180, 180);		// area of current lap
3059
//	hlight.setAlpha(128);			// 50% transparent
3060
	QColor frame(0, 0, 0);			// Text and borders
3061
	QColor barcol(151, 190, 13);		// heart rate
3062
	QColor barcol2(190, 151, 13);		// height over NN
222 andreas 3063
	QColor red(220, 128, 128);		// speed
88 andreas 3064
	QColor blue(0, 0, 240);
3065
	QFont fntNormal("Helvetica");
3066
//	QFont fntBold("Helvetica", 10, QFont::Bold);
3067
	fntNormal.setPixelSize(10);
3068
	fntNormal.setStyleHint(QFont::Helvetica);
3069
//	fntBold.setPixelSize(10);
3070
//	fntBold.setStyleHint(QFont::Helvetica);
3071
	// Calculate ticks
3072
	margin_left = 52;
3073
	margin_right = 40;
3074
	margin_bottom = 12;
3075
	lineHeight = 10;
3076
	rh = height - margin_bottom - 1;
3077
 
249 andreas 3078
	w_tick = (double)(width - (margin_left + margin_right)) / (max_time + ds.getPauseTime());	// 1 tick = 1 second
88 andreas 3079
 
222 andreas 3080
	if (cuType == 1)	// Speed and heart rate?
88 andreas 3081
	{
218 andreas 3082
	   if ((maxSpeed - minSpeed) > (double)(maxHr - minHr))
3083
	   {
222 andreas 3084
	      h_tick = (double)rh / (maxSpeed - minSpeed);		// 1 tick = 1 km/h
218 andreas 3085
	      meter = true;
3086
	   }
3087
	   else
3088
	   {
3089
	      h_tick = (double)rh / ((double)maxHr - (double)minHr);	// 1 tick = 1 bpm
3090
	      meter = false;
3091
	   }
88 andreas 3092
	}
222 andreas 3093
	else if (cuType == 2)	// Elevation and speed?
88 andreas 3094
	{
218 andreas 3095
	   if ((maxHeight - minHeight) > (double)(maxHr - minHr))
3096
	   {
3097
	      h_tick = (double)rh / (maxHeight - minHeight);		// 1 tick = 1 meter
3098
	      meter = true;
3099
	   }
3100
	   else
3101
	   {
222 andreas 3102
	      h_tick = (double)rh / (maxSpeed - minSpeed);		// 1 tick = 1 km/h
3103
	      meter = false;
3104
	   }
3105
	}
3106
	else			// Elevation and heart rate
3107
	{
3108
	   if ((maxHeight - minHeight) > (double)(maxHr - minHr))
3109
	   {
3110
	      h_tick = (double)rh / (maxHeight - minHeight);		// 1 tick = 1 meter
3111
	      meter = true;
3112
	   }
3113
	   else
3114
	   {
218 andreas 3115
	      h_tick = (double)rh / ((double)maxHr - (double)minHr);	// 1 tick = 1 bpm
3116
	      meter = false;
3117
	   }
88 andreas 3118
	}
218 andreas 3119
 
88 andreas 3120
	// Fill background with background colors
3121
	paint.fillRect(0, 0, width + 4, height + 4, background);
3122
	// Draw a grid with markers at every 10 minutes
232 andreas 3123
	paint.setPen(QPen(frame, 1, Qt::SolidLine));
88 andreas 3124
	// Bottom border line
3125
	x1 = margin_left;
3126
	y1 = height - margin_bottom;
3127
	x2 = width - margin_right;
3128
	y2 = y1;
3129
	paint.drawLine(x1, y1, x2, y2);
3130
	// Left border line
3131
	x1 = x2 = margin_left;
3132
	y1 = 2;
3133
	y2 = height - margin_bottom;
3134
	paint.drawLine(x1, y1, x2, y2);
3135
	// right border line
3136
	x1 = x2 = width - margin_right;
3137
	paint.drawLine(x1, y1, x2, y2);
148 andreas 3138
 
3139
	// Draw some darker lines to show the laps, if we have one
3140
	// and, in case we have a given lap, we fill the area.
3141
	QDateTime *qt;
3142
	QTime zeit = StartTime.time();
3143
	rn = ds.getRunNode();
232 andreas 3144
	paint.setPen(QPen(hlight, 1, Qt::SolidLine));
148 andreas 3145
 
3146
	for (i = rn->run->first_lap_index; (unsigned int)i <= rn->run->last_lap_index; i++)
3147
	{
3148
	   if ((lp = ds.getLap(i)) == NULL)
3149
	      continue;
3150
 
3151
	   qt = garmin_dtime(lp->start_time);
3152
	   secs = zeit.secsTo(qt->time());
3153
	   delete qt;
3154
	   x1 = secs * w_tick + margin_left + 1;
3155
 
3156
	   if (lap && lp->start_time == lap->start_time)
3157
	      paint.fillRect(x1, 2, (int)((double)lap->total_time / 100.0 * w_tick), height - margin_bottom - 2, hlight);
3158
	   else
3159
	      paint.drawLine(x1, 2, x1, height - margin_bottom);
3160
	}
3161
 
88 andreas 3162
	// Grid vertical
232 andreas 3163
	paint.setPen(QPen(frame, 1, Qt::SolidLine));
88 andreas 3164
	paint.setFont(fntNormal);
3165
	paint.drawText(margin_left - 20, height - lineHeight, 40, lineHeight, Qt::AlignCenter, QString("00:00"));
3166
	paint.save();
3167
	paint.rotate(270);
218 andreas 3168
 
222 andreas 3169
	if (cuType == 1)
232 andreas 3170
	   paint.setPen(QPen(red, 1, Qt::SolidLine));
222 andreas 3171
	else
232 andreas 3172
	   paint.setPen(QPen(barcol, 1, Qt::SolidLine));
222 andreas 3173
 
3174
	// Information on left side
218 andreas 3175
	if (cuType == 0)
3176
	   paint.drawText((height + 4) * -1, 3, height - 2, lineHeight, Qt::AlignCenter, i18n((Units == 1) ? "Elevation (ft)" : "Elevation (m)"));
3177
	else if (cuType == 1)
3178
	   paint.drawText((height + 4) * -1, 3, height - 2, lineHeight, Qt::AlignCenter, i18n((Units == 1) ? "Speed (mph)" : "Speed (km/h)"));
3179
	else
3180
	   paint.drawText((height + 4) * -1, 3, height - 2, lineHeight, Qt::AlignCenter, i18n((Units == 1) ? "Elevation (ft)" : "Elevation (m)"));
3181
 
222 andreas 3182
	if (cuType == 2)
232 andreas 3183
	   paint.setPen(QPen(red, 1, Qt::SolidLine));
222 andreas 3184
	else
232 andreas 3185
	   paint.setPen(QPen(blue, 1, Qt::SolidLine));
218 andreas 3186
 
222 andreas 3187
	// Information on right side
218 andreas 3188
	if (cuType < 2)
3189
	   paint.drawText((height + 4) * -1, width - 1 - lineHeight, height - 2, lineHeight, Qt::AlignCenter, i18n("Heart Rate (bpm)"));
3190
	else
3191
	   paint.drawText((height + 4) * -1, width - 1 - lineHeight, height - 2, lineHeight, Qt::AlignCenter, i18n((Units == 1) ? "Speed (mph)" : "Speed (km/h)"));
3192
 
88 andreas 3193
	paint.restore();
232 andreas 3194
	paint.setPen(QPen(mark, 1, Qt::SolidLine));
222 andreas 3195
	// Draw the time scale on the bottom of the graphic
249 andreas 3196
	for (i = 0; (unsigned int)i < (max_time + ds.getPauseTime()); i++)
88 andreas 3197
	{
3198
	   if (i > 0 && !(i % 600))	// every 10 minutes
3199
	   {
3200
	      x1 = x2 = margin_left + w_tick * i;
3201
 
3202
	      if (x1 == (width - margin_right))
3203
		 continue;
3204
 
3205
	      y1 = 2;
3206
	      y2 = height - margin_bottom;
3207
	      paint.drawLine(x1, y1, x2, y2);
3208
	      QTime tm(0, 0, 0);
3209
	      tm = tm.addSecs(i);
232 andreas 3210
	      paint.setPen(QPen(frame, 1, Qt::SolidLine));
230 andreas 3211
//	      paint.drawText(x1 - 25, height - lineHeight, 50, lineHeight, Qt::AlignCenter, tm.toString((i >= 3600) ? "hh:mm:ss" : "mm:ss"));
3212
	      paint.drawText(x1 - 25, height - lineHeight, 50, lineHeight, Qt::AlignCenter, kl->formatTime (tm, (i >= 3600) ? true : false));
232 andreas 3213
	      paint.setPen(QPen(mark, 1, Qt::SolidLine));
88 andreas 3214
	   }
3215
	}
222 andreas 3216
 
3217
	// This is the total time, with pauses included, at the lower right
3218
	// corner of the graphic.
88 andreas 3219
	QTime tm(0, 0, 0);
3220
	QString qs;
249 andreas 3221
	tm = tm.addSecs(max_time + ds.getPauseTime());
232 andreas 3222
	paint.setPen(QPen(frame, 1, Qt::SolidLine));
230 andreas 3223
//	paint.drawText(width - margin_right - 25, height - lineHeight, 50, lineHeight, Qt::AlignCenter, tm.toString((max_time >= 3600) ? "hh:mm:ss" : "mm:ss"));
3224
	paint.drawText(width - margin_right - 25, height - lineHeight, 50, lineHeight, Qt::AlignCenter, kl->formatTime(tm, (max_time >= 3600) ? true : false));
88 andreas 3225
 
222 andreas 3226
	// Draw the minimal elevation, speed and/or heart rate
218 andreas 3227
	if (max_height > 0.0 || max_speed > 0.0)
88 andreas 3228
	{
222 andreas 3229
	   // left side
218 andreas 3230
	   if (cuType == 1)
222 andreas 3231
	   {
232 andreas 3232
	      paint.setPen(QPen(red, 1, Qt::SolidLine));
218 andreas 3233
	      paint.drawText(12, height - margin_bottom - lineHeight / 2, margin_left - 14, lineHeight, Qt::AlignRight, qs.sprintf("%.0f", minSpeed));
222 andreas 3234
	   }
218 andreas 3235
	   else
222 andreas 3236
	   {
232 andreas 3237
	      paint.setPen(QPen(barcol, 1, Qt::SolidLine));
218 andreas 3238
	      paint.drawText(12, height - margin_bottom - lineHeight / 2, margin_left - 14, lineHeight, Qt::AlignRight, qs.sprintf("%.0f", (Units == 1) ? minHeight / 0.304 : minHeight));
222 andreas 3239
	   }
88 andreas 3240
	}
3241
 
222 andreas 3242
	if (max_hr > 0 || max_speed > 0.0)
88 andreas 3243
	{
222 andreas 3244
	   // right side
3245
	   if (cuType == 2)
3246
	   {
232 andreas 3247
	      paint.setPen(QPen(red, 1, Qt::SolidLine));
222 andreas 3248
	      paint.drawText(width - margin_right + 2, height - margin_bottom - lineHeight / 2, margin_right - 14, lineHeight, Qt::AlignLeft, qs.sprintf("%.0f", minSpeed));
3249
	   }
3250
	   else
3251
	   {
232 andreas 3252
	      paint.setPen(QPen(blue, 1, Qt::SolidLine));
222 andreas 3253
	      paint.drawText(width - margin_right + 2, height - margin_bottom - lineHeight / 2, margin_right - 14, lineHeight, Qt::AlignLeft, qs.sprintf("%d", minHr));
3254
	   }
88 andreas 3255
	}
3256
 
232 andreas 3257
	paint.setPen(QPen(mark, 1, Qt::SolidLine));
88 andreas 3258
 
3259
	// Grid horizontal
218 andreas 3260
	int factor = 0;
3261
	int target = 0;
3262
 
222 andreas 3263
	if (cuType == 0)	// Elevation and heart rate
218 andreas 3264
	{
222 andreas 3265
	   factor = (meter) ? (maxHeight - minHeight) / (rh / 12) : (maxHr - minHr) / (rh / 12);
3266
	   target = (meter) ? (int)(maxHeight - minHeight) : (maxHr - minHr);
3267
	}
3268
	else if (cuType == 1)	// Speed and heart rate
3269
	{
218 andreas 3270
	   factor = (meter) ? (maxSpeed - minSpeed) / (rh / 12) : (maxHr - minHr) / (rh / 12);
3271
	   target = (meter) ? (int)(maxSpeed - minSpeed) : (maxHr - minHr);
3272
	}
222 andreas 3273
	else			// Elevation and speed
218 andreas 3274
	{
222 andreas 3275
	   factor = (meter) ? (maxHeight - minHeight) / (rh /12) : (maxSpeed - minSpeed) / (rh / 12);
3276
	   target = (meter) ? (int)(maxHeight - minHeight) : (int)(maxSpeed - minSpeed);
218 andreas 3277
	}
3278
 
222 andreas 3279
	// To prevent a division by zero error, we check the <factor>
3280
	if (factor == 0)
3281
	   factor = 1;
3282
 
3283
	// Beside the horizontal part of the grid, we draw the scale on the
3284
	// left and the right side.
88 andreas 3285
	int oldy = height;
3286
 
3287
	for (i = 0; i < target; i++)
3288
	{
3289
	   if (i > 0 && !(i % factor))
3290
	   {
3291
	      x1 = margin_left + 1;
3292
	      x2 = width - margin_right - 1;
3293
	      y1 = y2 = rh - h_tick * i;
3294
 
3295
	      if (y1 < 12)
3296
		 break;
3297
 
3298
	      paint.drawLine(x1, y1, x2, y2);
3299
 
3300
	      if (y1 < (oldy - lineHeight))
3301
	      {
3302
		 if (meter)
3303
		 {
232 andreas 3304
		    paint.setPen(QPen(barcol, 1, Qt::SolidLine));
222 andreas 3305
		    // left side
218 andreas 3306
		    if (cuType == 1)
222 andreas 3307
		    {
232 andreas 3308
		       paint.setPen(QPen(red, 1, Qt::SolidLine));
222 andreas 3309
		       paint.drawText(12, y1 - lineHeight / 2, margin_left - 14, lineHeight, Qt::AlignRight, qs.sprintf("%.1f", minSpeed + i));
3310
		    }
218 andreas 3311
		    else
3312
		       paint.drawText(12, y1 - lineHeight / 2, margin_left - 14, lineHeight, Qt::AlignRight, qs.sprintf("%.0f", (Units == 1) ? (minHeight + i) / 0.304 : minHeight + i));
3313
 
222 andreas 3314
		    // right side
3315
		    if (maxHr > 0 && cuType != 2)
88 andreas 3316
		    {
3317
		       double hrscale = (double)(maxHr - minHr) / (double)target;
232 andreas 3318
		       paint.setPen(QPen(blue, 1, Qt::SolidLine));
88 andreas 3319
		       paint.drawText(width - margin_right + 2, y1 - lineHeight / 2, margin_right - 14, lineHeight, Qt::AlignLeft, qs.sprintf("%d", (int)((double)minHr + hrscale * (double)i)));
3320
		    }
222 andreas 3321
		    else
3322
		    {
3323
		       double spscale = (maxSpeed - minSpeed) / (double)target;
3324
 
3325
		       if (cuType == 2)
232 andreas 3326
			  paint.setPen(QPen(red, 1, Qt::SolidLine));
222 andreas 3327
		       else
232 andreas 3328
			  paint.setPen(QPen(blue, 1, Qt::SolidLine));
222 andreas 3329
 
3330
		       paint.drawText(width - margin_right + 2, y1 - lineHeight / 2, margin_right - 14, lineHeight, Qt::AlignLeft, qs.sprintf("%.1f", (minSpeed + spscale * (double)i)));
3331
		    }
88 andreas 3332
		 }
3333
		 else
3334
		 {
222 andreas 3335
		    // right side
3336
		    if (cuType == 2)
3337
		    {
232 andreas 3338
		       paint.setPen(QPen(red, 1, Qt::SolidLine));
222 andreas 3339
		       paint.drawText(width - margin_right + 2, y1 - lineHeight / 2, margin_right - 14, lineHeight, Qt::AlignLeft, qs.sprintf("%.1f", minSpeed + i));
3340
		    }
3341
		    else
3342
		    {
232 andreas 3343
		       paint.setPen(QPen(blue, 1, Qt::SolidLine));
222 andreas 3344
		       paint.drawText(width - margin_right + 2, y1 - lineHeight / 2, margin_right - 14, lineHeight, Qt::AlignLeft, qs.sprintf("%d", minHr + i));
3345
		    }
88 andreas 3346
 
222 andreas 3347
		    // left side
3348
		    if ((cuType == 0 || cuType == 2) && max_height > 0)
88 andreas 3349
		    {
3350
		       double hrscale = (maxHeight - minHeight) / (double)target;
232 andreas 3351
		       paint.setPen(QPen(barcol, 1, Qt::SolidLine));
88 andreas 3352
		       paint.drawText(12, y1 - lineHeight / 2, margin_left - 14, lineHeight, Qt::AlignRight, qs.sprintf("%.0f", minHeight + hrscale * (double)i));
3353
		    }
222 andreas 3354
		    else if (max_speed > 0 && cuType == 1)
218 andreas 3355
		    {
3356
		       double hrscale = (maxSpeed - minSpeed) / (double)target;
232 andreas 3357
		       paint.setPen(QPen(red, 1, Qt::SolidLine));
222 andreas 3358
		       paint.drawText(12, y1 - lineHeight / 2, margin_left - 14, lineHeight, Qt::AlignRight, qs.sprintf("%.1f", minSpeed + hrscale * (double)i));
218 andreas 3359
		    }
88 andreas 3360
		}
3361
 
232 andreas 3362
		 paint.setPen(QPen(mark, 1, Qt::SolidLine));
88 andreas 3363
		 oldy = y1;
3364
	      }
3365
	   }
3366
	}
3367
 
168 andreas 3368
	// To make our graphics more beautiful, we draw lines for the
88 andreas 3369
	// heart rate limits and the average heart rate.
222 andreas 3370
	if (max_hr > 0 && cuType != 2)
88 andreas 3371
	{
3372
	int ay1, ay2, ay3, ay4, ay5;
3373
 
3374
	   x1 = margin_left + 1;
3375
	   x2 = width - margin_right - 1;
3376
 
3377
	   if (meter)
3378
	   {
3379
	      double hrscale = rh / (double)(maxHr - minHr);
3380
	      ay1 = (double)rh - (double)(lower1 - minHr) * hrscale;
3381
	      ay2 = (double)rh - (double)(lower2 - minHr) * hrscale;
3382
	      ay3 = (double)rh - (double)(lower3 - minHr) * hrscale;
3383
	      ay4 = (double)rh - (double)(upper3 - minHr) * hrscale;
3384
	      ay5 = (double)rh - (double)(avg_hr - minHr) * hrscale;
3385
	   }
3386
	   else
3387
	   {
3388
	      ay1 = (double)rh - (double)(lower1 - minHr) * h_tick;
3389
	      ay2 = (double)rh - (double)(lower2 - minHr) * h_tick;
3390
	      ay3 = (double)rh - (double)(lower3 - minHr) * h_tick;
3391
	      ay4 = (double)rh - (double)(upper3 - minHr) * h_tick;
3392
	      ay5 = (double)rh - (double)(avg_hr - minHr) * h_tick;
3393
	   }
3394
 
232 andreas 3395
	   paint.setPen(QPen(barcol2, 1, Qt::DashLine));	// color for limits
88 andreas 3396
 
3397
	   if (lower1 > minHr && lower1 < maxHr)
3398
	      paint.drawLine(x1, ay1, x2, ay1);
3399
 
3400
	   if (lower2 > minHr && lower2 < maxHr)
3401
	      paint.drawLine(x1, ay2, x2, ay2);
3402
 
3403
	   if (lower3 > minHr && lower3 < maxHr)
3404
	      paint.drawLine(x1, ay3, x2, ay3);
3405
 
3406
	   if (upper3 > minHr && upper3 < maxHr)
3407
	      paint.drawLine(x1, ay4, x2, ay4);
3408
 
232 andreas 3409
	   paint.setPen(QPen(red, 1, Qt::DashDotLine));	// color for average heart rate
88 andreas 3410
 
3411
	   if (avg_hr > minHr && avg_hr < maxHr)
3412
	      paint.drawLine(x1, ay5, x2, ay5);
3413
	}
3414
 
3415
	// Now we have a grid and we've done the scaling.
3416
	// This is the point where we draw the curves itself.
223 andreas 3417
	// We use different colors to draw the lines:
3418
	//
3419
	// Green: Elevation
3420
	// Red:   Speed
3421
	// Blue   Heart Rate
3422
	//
88 andreas 3423
	x1 = x2 = y1 = y2 = 0;
148 andreas 3424
	int hy1, hy2, hx1, hx2;
222 andreas 3425
	int sy1, sy2, sx1, sx2;
88 andreas 3426
	hy1 = hy2 = hx1 = hx2 = 0;
222 andreas 3427
	sy1 = sy2 = sx1 = sx2 = 0;
169 andreas 3428
	int hEc = 0;
3429
	i = 0;
3430
	AVGHEIGHT *avgHakt, *avgHfirst, *avgHlast, *avgHeight = 0;
170 andreas 3431
	avgHfirst = avgHlast = 0;
169 andreas 3432
	// To even the surface lines, we store every altitude in the
3433
	// memory, by building a chain. Then, if the user has set in the
3434
	// settings (Contour == true), we will even the line by calculating
3435
	// the average of 10 messure points and setting every value to the
3436
	// average, who is up or down more than 2 meters from the average.
3437
	while ((point = ds.getPoint(i)) != 0)
3438
	{
3439
	   if (point->alt > 20000.0 || point->alt < -1000.0)
3440
	   {
3441
	      i++;
3442
	      continue;
3443
	   }
168 andreas 3444
 
169 andreas 3445
	   if (!avgHeight)
3446
	   {
3447
	      avgHeight = new AVGHEIGHT;
3448
	      avgHeight->alt = point->alt;
3449
	      avgHeight->pos = hEc;
3450
	      avgHeight->prev = 0;
3451
	      avgHeight->next = 0;
3452
	      avgHakt = avgHeight;
3453
	      avgHfirst = avgHeight;
3454
	   }
3455
	   else
3456
	   {
3457
	      avgHakt = new AVGHEIGHT;
3458
	      avgHakt->alt = point->alt;
3459
	      avgHakt->pos = hEc;
3460
	      avgHakt->next = 0;
3461
	      avgHakt->prev = avgHeight;
3462
	      avgHeight->next = avgHakt;
3463
	      avgHeight = avgHakt;
3464
	   }
3465
 
3466
	   // FIXME: Currently we can not draw below 0 meters, because the
3467
	   // base line is always 0!
222 andreas 3468
	   if (avgHakt->alt < minHeight)
3469
	      avgHakt->alt = minHeight;
169 andreas 3470
 
3471
	   hEc++;
3472
	   i++;
3473
	}
3474
 
3475
	avgHlast = avgHeight;
3476
	// If wanted, even the lines
218 andreas 3477
	if (Contour && hEc > 0 && cuType != 0)
169 andreas 3478
	{
213 andreas 3479
	double alt[100], avg, avg1, avg2, avg3, avg4;
3480
	int a, pos;
169 andreas 3481
 
213 andreas 3482
	   for (i = 0; i < (hEc + 100); i += 100)
169 andreas 3483
	   {
213 andreas 3484
	      avg = avg1 = avg2 = avg3 = avg4 = 0.0;
3485
	      pos = 0;
169 andreas 3486
 
213 andreas 3487
	      for (a = 0; a < 100; a++)
169 andreas 3488
	      {
3489
		 alt[a] = getAvgAlt(avgHfirst, i + a);
3490
		 avg += alt[a];
213 andreas 3491
 
3492
		 if (a < 25)
3493
		    avg1 += alt[a];
3494
		 else if (a < 50)
3495
		    avg2 += alt[a];
3496
		 else if (a < 75)
3497
		    avg3 += alt[a];
3498
		 else
3499
		    avg4 += alt[a];
169 andreas 3500
	      }
3501
 
213 andreas 3502
	      if ((i + 100) >= hEc)
169 andreas 3503
		 avg /= (double)(hEc - i) + 1.0;
3504
	      else
213 andreas 3505
		 avg /= 100.0;
169 andreas 3506
 
213 andreas 3507
	      for (a = 0; a < 100; a++)
169 andreas 3508
	      {
3509
		 if ((avgHakt = getAvgPtr(avgHfirst, i + a)) != 0)
3510
		 {
3511
		    if ((avgHakt->alt - avg) > 2 || (avgHakt->alt - avg) < -2)
3512
		       avgHakt->alt = avg;
3513
		 }
3514
	      }
3515
	   }
3516
	}
3517
 
222 andreas 3518
	// plot the elevation, speed and/or heart rate. Depends on <cuType>)
168 andreas 3519
	i = 0;
169 andreas 3520
	int j = 0;
218 andreas 3521
	POINT *oldPoint = 0;
222 andreas 3522
	double speed = 0.0;	// calculated speed
3523
	bool pause = false;	// filter pause out of speed
3524
	unsigned long t1, t2;
3525
	t1 = t2 = 0;
218 andreas 3526
 
88 andreas 3527
	while ((point = ds.getPoint(i)) != 0)
3528
	{
218 andreas 3529
	   if (!oldPoint)
3530
	      oldPoint = point;
3531
 
88 andreas 3532
	   // calculate the y position based on the time
3533
	   qt = garmin_dtime(point->time);
3534
	   secs = zeit.secsTo(qt->time());
3535
	   delete qt;
3536
	   x2 = secs * w_tick + margin_left + 1;
3537
	   hx2 = x2;
222 andreas 3538
	   sx2 = x2;
88 andreas 3539
 
3540
	   if (x1 == 0)
3541
	      x1 = x2;
3542
 
3543
	   if (hx1 == 0)
3544
	      hx1 = hx2;
3545
 
222 andreas 3546
	   if (sx1 == 0)
3547
	      sx1 = sx2;
3548
 
3549
	   // The speed is not very exact, because smallest time is
3550
	   // one second. This allows a maximum error of 99 hundredths
3551
	   // of a second, what is very close to one second. Because of
3552
	   // this, speed seems to hop for every messure point. This
3553
	   // looks ugly, but currently I don't know how to make it
3554
	   // better.
3555
	   if (cuType == 1 || cuType == 2)	// Draw speed?
88 andreas 3556
	   {
218 andreas 3557
	      double dist;
3558
	      double sc;
168 andreas 3559
 
222 andreas 3560
	      if (!pause && point->distance > 1.0e10)
218 andreas 3561
	      {
222 andreas 3562
		 pause = true;
3563
		 t1 = point->time;
3564
	      }
3565
	      else if (pause)
3566
	      {
3567
		 pause = false;
3568
		 t2 = point->time;
3569
		 i += 2;
3570
		 continue;
3571
	      }
3572
 
3573
	      if (point->distance >= 0.1 && point->distance < 1.0e10)
3574
	      {
218 andreas 3575
		 dist = point->distance - oldPoint->distance;
3576
		 sc = point->time - oldPoint->time;
223 andreas 3577
		 LAP *runde = ds.getLapT (point->time);
222 andreas 3578
 
3579
		 if (t2 > t1)
3580
		 {
3581
		    sc -= t2 - t1;
3582
 
3583
		    if (sc <= 0.0)
3584
		       sc = 1.0;		// at least 1 second!
3585
		 }
3586
 
218 andreas 3587
		 speed = (dist / sc) * 3.6;
168 andreas 3588
 
223 andreas 3589
		 if (runde && runde->max_speed > 0.0 && speed > (runde->max_speed * 3.6))
3590
		    speed = runde->max_speed * 3.6;
3591
 
218 andreas 3592
		 if (Units == 1)
3593
		    speed /= 1.609344;
3594
 
222 andreas 3595
		 if (speed < minSpeed || speed > 400.0)
3596
		    speed = minSpeed;
218 andreas 3597
 
222 andreas 3598
		 if ((meter && cuType == 1) || (!meter && cuType == 2))
218 andreas 3599
		    y2 = (double)rh - (speed - minSpeed) * h_tick;
3600
		 else
3601
		 {
3602
		    double hrscale = rh / (maxSpeed - minSpeed);
3603
		    y2 = (double)rh - (speed - minSpeed) * hrscale;
3604
		 }
3605
 
3606
		 if (y1 == 0)
3607
		    y1 = y2;
3608
 
232 andreas 3609
		 paint.setPen(QPen(red, 1, Qt::SolidLine));
218 andreas 3610
		 paint.drawLine(x1, y1, x2, y2);
3611
		 y1 = y2;
3612
		 x1 = x2;
222 andreas 3613
		 t1 = t2 = 0;
3614
		 oldPoint = point;
218 andreas 3615
	      }
3616
	   }
222 andreas 3617
 
3618
	   if (cuType == 0 || cuType == 2)		// Draw elevation?
218 andreas 3619
	   {
3620
	      if (point->alt < 20000.0 && point->alt > -1000.0)
88 andreas 3621
	      {
218 andreas 3622
	      double alt = getAvgAlt(avgHfirst, j);
88 andreas 3623
 
218 andreas 3624
		 j++;
3625
 
3626
		 if (meter)
222 andreas 3627
		    sy2 = (double)rh - (alt - minHeight) * h_tick;
218 andreas 3628
		 else
3629
		 {
3630
		    double hrscale = rh / (maxHeight - minHeight);
222 andreas 3631
		    sy2 = (double)rh - (alt - minHeight) * hrscale;
218 andreas 3632
		 }
3633
 
222 andreas 3634
		 if (sy1 == 0)
3635
		    sy1 = sy2;
218 andreas 3636
 
232 andreas 3637
		 paint.setPen(QPen(barcol, 1, Qt::SolidLine));
222 andreas 3638
		 paint.drawLine(sx1, sy1, sx2, sy2);
3639
		 sy1 = sy2;
3640
		 sx1 = sx2;
218 andreas 3641
	      }
88 andreas 3642
	   }
3643
 
222 andreas 3644
	   if (point->heart_rate > 0 && cuType < 2)	// Draw heart rate?
88 andreas 3645
	   {
3646
	      if (meter)
3647
	      {
3648
		 double hrscale = rh / (double)(maxHr - minHr);
3649
		 hy2 = (double)rh - (double)(point->heart_rate - minHr) * hrscale;
3650
	      }
3651
	      else
3652
		 hy2 = (double)rh - (double)(point->heart_rate - minHr) * h_tick;
3653
 
3654
	      if (hy1 == 0)
3655
		 hy1 = hy2;
3656
 
232 andreas 3657
	      paint.setPen(QPen(blue, 1, Qt::SolidLine));
88 andreas 3658
	      paint.drawLine(hx1, hy1, hx2, hy2);
3659
	      hy1 = hy2;
3660
	      hx1 = hx2;
3661
	   }
3662
 
3663
	   i++;
3664
	}
3665
 
3666
	paint.end();
245 andreas 3667
	ui_sportwatcherWidgetBase.imgProfile->setPixmap(pmProfile);
88 andreas 3668
 
169 andreas 3669
	// free the chain of altitudes
3670
	avgHakt = avgHfirst;
3671
 
3672
	while (avgHakt)
3673
	{
3674
	   avgHeight = avgHakt->next;
3675
	   delete avgHakt;
3676
	   avgHakt = avgHeight;
3677
	}
3678
 
246 andreas 3679
	DIRTY = false;
88 andreas 3680
}
3681
 
250 andreas 3682
void sportwatcherWidget::showThreeCurve()
3683
{
3684
QPainter ptHR, ptElevation, ptSpeed;
3685
int width, height, wdHR, htHR, wdElev, htElev, wdSpeed, htSpeed;
3686
int i, secs, cuType;
3687
int lineHeight, margin_left, margin_right, margin_bottom;
3688
int x1, y1, x2, y2;		// Coordinates
274 andreas 3689
bool meterHR;
250 andreas 3690
double maxHeight, minHeight, maxSpeed, minSpeed;
3691
int maxHr, minHr, rh, rhHR, rhElev, rhSpeed;
3692
POINT *point;
3693
RUN_NODE *rn;
3694
LAP *lp;
3695
double wtiHR, htiHR, wtiElev, htiElev, wtiSpeed, htiSpeed;
3696
double w_tick, h_tick;		// Number of pixels one "tick" has;
3697
				// This depends on the width and height
3698
				// of the image.
3699
	// First we draw a grid based on the min and max
3700
	// values detected in the function showLap(). In case
3701
	// all values are 0, we exit here.
3702
	if (min_hr == 0 && max_hr == 0 && min_height == 0.0 && max_height == 0.0)
3703
	   return;
3704
 
3705
	if (!DIRTY || curTab != 2)
3706
	   return;
3707
 
3708
	// Get the dimensions of the available draw area
3709
	// First for heart rate
3710
	wdHR = ui_sportwatcherWidgetBase.grHR->width() - 2;
3711
	htHR = ui_sportwatcherWidgetBase.grHR->height();
3712
	pmHR = QPixmap(wdHR, htHR);
3713
	// Then for elevation
3714
	wdElev = ui_sportwatcherWidgetBase.grElevation->width() - 2;
3715
	htElev = ui_sportwatcherWidgetBase.grElevation->height();
3716
	pmElevation = QPixmap(wdElev, htElev);
3717
	// And at last for speed
3718
	wdSpeed = ui_sportwatcherWidgetBase.grSpeed->width() - 2;
3719
	htSpeed = ui_sportwatcherWidgetBase.grSpeed->height();
3720
	pmSpeed = QPixmap(wdSpeed, htSpeed);
3721
	// Initialize QPainter
3722
	ptHR.begin(&pmHR);
3723
	ptElevation.begin(&pmElevation);
3724
	ptSpeed.begin(&pmSpeed);
3725
 
3726
	// we need a somewhat bigger area to draw our curves than
3727
	// we have with the real min and max values.
3728
	if (max_height > 0.0)
3729
	{
3730
	double add = (max_height - min_height) / 100.0 * 5.0;	// Percent
3731
 
3732
	   maxHeight = max_height + add;
3733
	   minHeight = min_height - add;
3734
 
3735
	   if (minHeight < 0.0)		// make sure, we are not too deep
3736
	      minHeight = 0.0;
3737
	}
3738
	else
3739
	   maxHeight = minHeight = 0.0;
3740
 
3741
	if (max_speed > 0.0)
3742
	{
3743
	double add = (max_speed - min_speed) / 100.0 * 5.0;	// Percent
3744
 
3745
	   maxSpeed = max_speed + add;
3746
	   minSpeed = min_speed - add;
3747
 
3748
	   if (minSpeed < 0.0)		// make sure, we are not too deep
3749
	      minSpeed = 0.0;
3750
	}
3751
	else
3752
	   maxSpeed = minSpeed = 0.0;
3753
 
3754
	if (max_hr > 0)
3755
	{
3756
	   maxHr = max_hr + 10;
3757
	   minHr = min_hr - 10;
3758
 
3759
	   if (minHr < 0)
3760
	      minHr = 0;
3761
	}
3762
	else
3763
	   maxHr = minHr = 0;
3764
 
3765
	// Define colors
3766
	QColor background(220, 220, 220);	// Background of graphic
3767
	QColor mark(255, 255, 255);		// Lines inside curve area
3768
	QColor hlight(180, 180, 180);		// area of current lap
3769
	hlight.setAlpha(128);			// 50% transparent
3770
	QColor frame(0, 0, 0);			// Text and borders
3771
	QColor barcol(151, 190, 13);		// heart rate
3772
	QColor barcol2(190, 151, 13);		// height over NN
3773
	QColor red(220, 128, 128);		// speed
3774
	QColor blue(0, 0, 240);
3775
	QFont fntNormal("Helvetica");
3776
//	QFont fntBold("Helvetica", 10, QFont::Bold);
3777
	fntNormal.setPixelSize(10);
3778
	fntNormal.setStyleHint(QFont::Helvetica);
3779
//	fntBold.setPixelSize(10);
3780
//	fntBold.setStyleHint(QFont::Helvetica);
3781
	// Calculate ticks
3782
	margin_left = 1;
3783
	margin_right = 40;
3784
	margin_bottom = 12;
3785
	lineHeight = 10;
3786
//	rh = height - margin_bottom - 1;
3787
 
3788
	// Calculate the ticks for width and height for every draw area
3789
	for (i = 0; i < 3; i++)
3790
	{
3791
	   if (i == 2)	// Speed?
3792
	   {
3793
	      rhSpeed = htSpeed - margin_bottom - 1;
3794
	      wtiSpeed = (double)(wdSpeed - (margin_left + margin_right)) / (max_time + ds.getPauseTime());	// 1 tick = 1 second
3795
	      htiSpeed = (double)rhSpeed / (maxSpeed - minSpeed);		// 1 tick = 1 km/h
3796
	   }
3797
	   else if (i == 1)	// Elevation?
3798
	   {
3799
	      rhElev = htElev - margin_bottom - 1;
3800
	      wtiElev = (double)(wdElev - (margin_left + margin_right)) / (max_time + ds.getPauseTime());	// 1 tick = 1 second
3801
	      htiElev = (double)rhElev / (maxHeight - minHeight);		// 1 tick = 1 meter
3802
	   }
3803
	   else			// heart rate
3804
	   {
3805
	      rhHR = htHR - margin_bottom - 1;
3806
	      wtiHR = (double)(wdHR - (margin_left + margin_right)) / (max_time + ds.getPauseTime());	// 1 tick = 1 second
3807
	      htiHR = (double)rhHR / ((double)maxHr - (double)minHr);	// 1 tick = 1 bpm
3808
	   }
3809
	}
3810
 
3811
	// Fill background with background colors
3812
	ptHR.fillRect(0, 0, wdHR + 4, htHR + 4, background);
3813
	ptElevation.fillRect(0, 0, wdElev + 4, htElev + 4, background);
3814
	ptSpeed.fillRect(0, 0, wdSpeed + 4, htSpeed + 4, background);
3815
	// Draw a grid with markers at every 10 minutes
3816
	ptHR.setPen(QPen(frame, 1, Qt::SolidLine));
3817
	ptElevation.setPen(QPen(frame, 1, Qt::SolidLine));
3818
	ptSpeed.setPen(QPen(frame, 1, Qt::SolidLine));
3819
	// Bottom border line
3820
	x1 = margin_left;
3821
 
3822
	y1 = htHR - margin_bottom;
3823
	x2 = wdHR - margin_right;
3824
	y2 = y1;
3825
	ptHR.drawLine(x1, y1, x2, y2);
3826
 
3827
	y1 = htElev - margin_bottom;
3828
	x2 = wdElev - margin_right;
3829
	y2 = y1;
3830
	ptElevation.drawLine(x1, y1, x2, y2);
3831
 
3832
	y1 = htSpeed - margin_bottom;
3833
	x2 = wdSpeed - margin_right;
3834
	y2 = y1;
3835
	ptSpeed.drawLine(x1, y1, x2, y2);
3836
 
3837
	// Left border line
3838
	x1 = x2 = margin_left;
3839
	y1 = 2;
3840
	y2 = htHR - margin_bottom;
3841
	ptHR.drawLine(x1, y1, x2, y2);
3842
 
3843
	y2 = htElev - margin_bottom;
3844
	ptElevation.drawLine(x1, y1, x2, y2);
3845
 
3846
	y2 = htSpeed - margin_bottom;
3847
	ptSpeed.drawLine(x1, y1, x2, y2);
3848
 
3849
	// right border line
3850
	x1 = x2 = wdHR - margin_right;
3851
	ptHR.drawLine(x1, y1, x2, y2);
3852
 
3853
	x1 = x2 = wdElev - margin_right;
3854
	ptElevation.drawLine(x1, y1, x2, y2);
3855
 
3856
	x1 = x2 = wdSpeed - margin_right;
3857
	ptSpeed.drawLine(x1, y1, x2, y2);
3858
 
3859
	// Draw some darker lines to show the laps, if we have one
3860
	QDateTime *qt;
3861
	QTime zeit = StartTime.time();
3862
	rn = ds.getRunNode();
3863
	ptHR.setPen(QPen(hlight, 1, Qt::SolidLine));
3864
	ptElevation.setPen(QPen(hlight, 1, Qt::SolidLine));
3865
	ptSpeed.setPen(QPen(hlight, 1, Qt::SolidLine));
3866
 
3867
	for (i = rn->run->first_lap_index; (unsigned int)i <= rn->run->last_lap_index; i++)
3868
	{
3869
	   if ((lp = ds.getLap(i)) == NULL)
3870
	      continue;
3871
 
3872
	   qt = garmin_dtime(lp->start_time);
3873
	   secs = zeit.secsTo(qt->time());
3874
	   delete qt;
3875
	   // heart rate
3876
	   x1 = secs * wtiHR + margin_left + 1;
3877
	   ptHR.drawLine(x1, 2, x1, htHR - margin_bottom);
3878
	   // Elevation
3879
	   x1 = secs * wtiElev + margin_left + 1;
3880
	   ptElevation.drawLine(x1, 2, x1, htElev - margin_bottom);
3881
	   // Speed
3882
	   x1 = secs * wtiSpeed + margin_left + 1;
3883
	   ptSpeed.drawLine(x1, 2, x1, htSpeed - margin_bottom);
3884
	}
3885
 
3886
	// Grid vertical
3887
	ptHR.setPen(QPen(frame, 1, Qt::SolidLine));
3888
	ptHR.setFont(fntNormal);
3889
	ptHR.drawText(margin_left, htHR - lineHeight, 40, lineHeight, Qt::AlignLeft, QString("0"));
3890
 
3891
	ptElevation.setPen(QPen(frame, 1, Qt::SolidLine));
3892
	ptElevation.setFont(fntNormal);
3893
	ptElevation.drawText(margin_left, htElev - lineHeight, 40, lineHeight, Qt::AlignLeft, QString("0"));
3894
 
3895
	ptSpeed.setPen(QPen(frame, 1, Qt::SolidLine));
3896
	ptSpeed.setFont(fntNormal);
3897
	ptSpeed.drawText(margin_left, htSpeed - lineHeight, 40, lineHeight, Qt::AlignLeft, QString("0"));
3898
 
3899
	ptHR.save();
3900
	ptHR.rotate(270);
3901
	ptHR.setPen(QPen(blue, 1, Qt::SolidLine));
3902
 
3903
	ptElevation.save();
3904
	ptElevation.rotate(270);
3905
	ptElevation.setPen(QPen(barcol, 1, Qt::SolidLine));
3906
 
3907
	ptSpeed.save();
3908
	ptSpeed.rotate(270);
3909
	ptSpeed.setPen(QPen(red, 1, Qt::SolidLine));
3910
 
3911
	// Information on right side
3912
	ptHR.drawText((htHR + 4) * -1, wdHR - 1 - lineHeight, htHR - 2, lineHeight, Qt::AlignCenter, i18n("Heart Rate (bpm)"));
3913
	ptElevation.drawText((htElev + 4) * -1, wdElev - 1 - lineHeight, htElev - 2, lineHeight, Qt::AlignCenter, i18n((Units == 1) ? "Elevation (ft)" : "Elevation (m)"));
3914
	ptSpeed.drawText((htSpeed + 4) * -1, wdSpeed - 1 - lineHeight, htSpeed - 2, lineHeight, Qt::AlignCenter, i18n((Units == 1) ? "Speed (mph)" : "Speed (km/h)"));
3915
 
3916
	// restore to normal
3917
	ptHR.restore();
3918
	ptHR.setPen(QPen(mark, 1, Qt::SolidLine));
3919
 
3920
	ptElevation.restore();
3921
	ptElevation.setPen(QPen(mark, 1, Qt::SolidLine));
3922
 
3923
	ptSpeed.restore();
3924
	ptSpeed.setPen(QPen(mark, 1, Qt::SolidLine));
3925
	// Draw the time scale on the bottom of the graphic
3926
	for (i = 0; (unsigned int)i < (max_time + ds.getPauseTime()); i++)
3927
	{
3928
	bool loop = false;
3929
 
3930
	   if (i > 0 && !(i % 600))	// every 10 minutes
3931
	   {
3932
	      for (int j = 0; j < 3; j++)
3933
	      {
3934
		 switch (j)
3935
		 {
3936
		    case 0: w_tick = wtiHR; width = wdHR; height = htHR; break;
3937
		    case 1: w_tick = wtiElev; width = wdElev; height = htElev; break;
3938
		    case 2: w_tick = wtiSpeed; width = wdSpeed; height = htSpeed; break;
3939
		 }
3940
 
3941
		 x1 = x2 = margin_left + w_tick * i;
3942
 
3943
		 if (x1 == (width - margin_right - 25))
3944
		 {
3945
		    loop = true;
3946
		    break;
3947
		 }
3948
 
3949
		 y1 = 2;
3950
		 y2 = height - margin_bottom;
3951
		 QTime tm(0, 0, 0);
3952
		 tm = tm.addSecs(i);
3953
 
3954
		 if (j == 0)
3955
		 {
3956
		    ptHR.drawLine(x1, y1, x2, y2);
3957
		    ptHR.setPen(QPen(frame, 1, Qt::SolidLine));
3958
		    ptHR.drawText(x1 - 25, height - lineHeight, 50, lineHeight, Qt::AlignCenter, kl->formatTime (tm, (i >= 3600) ? true : false));
3959
		    ptHR.setPen(QPen(mark, 1, Qt::SolidLine));
3960
		 }
3961
		 else if (j == 1)
3962
		 {
3963
		    ptElevation.drawLine(x1, y1, x2, y2);
3964
		    ptElevation.setPen(QPen(frame, 1, Qt::SolidLine));
3965
		    ptElevation.drawText(x1 - 25, height - lineHeight, 50, lineHeight, Qt::AlignCenter, kl->formatTime (tm, (i >= 3600) ? true : false));
3966
		    ptElevation.setPen(QPen(mark, 1, Qt::SolidLine));
3967
		 }
3968
		 else
3969
		 {
3970
		    ptSpeed.drawLine(x1, y1, x2, y2);
3971
		    ptSpeed.setPen(QPen(frame, 1, Qt::SolidLine));
3972
		    ptSpeed.drawText(x1 - 25, height - lineHeight, 50, lineHeight, Qt::AlignCenter, kl->formatTime (tm, (i >= 3600) ? true : false));
3973
		    ptSpeed.setPen(QPen(mark, 1, Qt::SolidLine));
3974
		 }
3975
	      }
3976
 
3977
	      if (loop)
3978
	      {
3979
		 loop = false;
3980
		 continue;
3981
	      }
3982
	   }
3983
	}
3984
 
3985
	// This is the total time, with pauses included, at the lower right
3986
	// corner of the graphic.
3987
	QTime tm(0, 0, 0);
3988
	QString qs;
3989
	tm = tm.addSecs(max_time + ds.getPauseTime());
3990
	ptHR.setPen(QPen(frame, 1, Qt::SolidLine));
3991
	ptHR.drawText(wdHR - margin_right - 25, htHR - lineHeight, 50, lineHeight, Qt::AlignCenter, kl->formatTime(tm, (max_time >= 3600) ? true : false));
3992
 
3993
	ptElevation.setPen(QPen(frame, 1, Qt::SolidLine));
3994
	ptElevation.drawText(wdElev - margin_right - 25, htElev - lineHeight, 50, lineHeight, Qt::AlignCenter, kl->formatTime(tm, (max_time >= 3600) ? true : false));
3995
 
3996
	ptSpeed.setPen(QPen(frame, 1, Qt::SolidLine));
3997
	ptSpeed.drawText(wdSpeed - margin_right - 25, htSpeed - lineHeight, 50, lineHeight, Qt::AlignCenter, kl->formatTime(tm, (max_time >= 3600) ? true : false));
3998
 
3999
	// Draw the minimal elevation, speed and heart rate
4000
	// Heart rate
4001
	ptHR.setPen(QPen(blue, 1, Qt::SolidLine));
4002
	ptHR.drawText(wdHR - margin_right + 2, htHR - margin_bottom - lineHeight / 2, margin_right - 14, lineHeight, Qt::AlignLeft, qs.sprintf("%d", minHr));
4003
	// Elevation
4004
	ptElevation.setPen(QPen(barcol, 1, Qt::SolidLine));
4005
	ptElevation.drawText(wdElev - margin_right + 2, htElev - margin_bottom - lineHeight / 2, margin_right - 14, lineHeight, Qt::AlignLeft, qs.sprintf("%.0f", (Units == 1) ? minHeight / 0.304 : minHeight));
4006
	// Speed
4007
	ptSpeed.setPen(QPen(red, 1, Qt::SolidLine));
4008
	ptSpeed.drawText(wdSpeed - margin_right + 2, htSpeed - margin_bottom - lineHeight / 2, margin_right - 14, lineHeight, Qt::AlignLeft, qs.sprintf("%.0f", minSpeed));
4009
 
4010
	ptHR.setPen(QPen(mark, 1, Qt::SolidLine));
4011
	ptElevation.setPen(QPen(mark, 1, Qt::SolidLine));
4012
	ptSpeed.setPen(QPen(mark, 1, Qt::SolidLine));
4013
 
4014
	// Grid horizontal
4015
	int factor = 0;
4016
	int target = 0;
4017
 
4018
	for (int j = 0; j < 3; j++)
4019
	{
4020
	   switch (j)
4021
	   {
4022
	      case 0: width = wdHR; height = htHR; w_tick = wtiHR; h_tick = htiHR; rh = rhHR;
4023
		      factor = (maxHr - minHr) / (rhHR / 12);
4024
		      target = (maxHr - minHr);
4025
	      break;
4026
 
4027
	      case 1: width = wdElev; height = htElev; w_tick = wtiElev; h_tick = htiElev; rh = rhElev;
4028
		      factor = (maxHeight - minHeight) / (rhElev / 12);
4029
		      target = (int)(maxHeight - minHeight);
4030
	      break;
4031
 
4032
	      case 2: width = wdSpeed; height = htSpeed; w_tick = wtiSpeed; h_tick = htiSpeed; rh = rhSpeed;
4033
		      factor = (maxSpeed - minSpeed) / (rhSpeed / 12);
4034
		      target = (int)(maxSpeed - minSpeed);
4035
	      break;
4036
	   }
4037
 
4038
	   // To prevent a division by zero error, we check the <factor>
4039
	   if (factor == 0)
4040
	      factor = 1;
4041
 
4042
	   // Beside the horizontal part of the grid, we draw the scale on the
4043
	   // the right side too.
4044
	   int oldy = height;
4045
 
4046
	   for (i = 0; i < target; i++)
4047
	   {
4048
	      if (i > 0 && !(i % factor))
4049
	      {
4050
		 x1 = margin_left + 1;
4051
		 x2 = width - margin_right - 1;
4052
		 y1 = y2 = rh - h_tick * i;
4053
 
4054
		 if (y1 < 12)
4055
		    break;
4056
 
4057
		 switch (j)
4058
		 {
4059
		    case 0:
4060
		       ptHR.drawLine(x1, y1, x2, y2);
4061
		       ptHR.setPen(QPen(blue, 1, Qt::SolidLine));
4062
		       ptHR.drawText(width - margin_right + 2, y1 - lineHeight / 2, margin_right - 14, lineHeight, Qt::AlignLeft, qs.sprintf("%d", minHr + i));
4063
		       ptHR.setPen(QPen(mark, 1, Qt::SolidLine));
4064
		    break;
4065
 
4066
		    case 1:
4067
		       ptElevation.drawLine(x1, y1, x2, y2);
4068
		       ptElevation.setPen(QPen(barcol, 1, Qt::SolidLine));
4069
		       ptElevation.drawText(width - margin_right + 2, y1 - lineHeight / 2, margin_right - 14, lineHeight, Qt::AlignLeft, qs.sprintf("%.0f", (Units == 1) ? (minHeight + i) / 0.304 : minHeight + i));
4070
		       ptElevation.setPen(QPen(mark, 1, Qt::SolidLine));
4071
		    break;
4072
 
4073
		    case 2:
4074
		       ptSpeed.drawLine(x1, y1, x2, y2);
4075
		       ptSpeed.setPen(QPen(red, 1, Qt::SolidLine));
4076
		       ptSpeed.drawText(width - margin_right + 2, y1 - lineHeight / 2, margin_right - 14, lineHeight, Qt::AlignLeft, qs.sprintf("%.1f", minSpeed + i));
4077
		       ptSpeed.setPen(QPen(mark, 1, Qt::SolidLine));
4078
		    break;
4079
		 }
4080
 
4081
		 oldy = y1;
4082
	      }
4083
	   }
4084
	}
4085
 
4086
	// To make our graphics more beautiful, we draw lines for the
4087
	// heart rate limits and the average heart rate.
4088
	if (max_hr > 0)
4089
	{
4090
	int ay1, ay2, ay3, ay4, ay5;
4091
 
4092
	   x1 = margin_left + 1;
4093
	   x2 = wdHR - margin_right - 1;
4094
 
4095
	   if (meterHR)
4096
	   {
4097
	      double hrscale = rh / (double)(maxHr - minHr);
4098
	      ay1 = (double)rh - (double)(lower1 - minHr) * hrscale;
4099
	      ay2 = (double)rh - (double)(lower2 - minHr) * hrscale;
4100
	      ay3 = (double)rh - (double)(lower3 - minHr) * hrscale;
4101
	      ay4 = (double)rh - (double)(upper3 - minHr) * hrscale;
4102
	      ay5 = (double)rh - (double)(avg_hr - minHr) * hrscale;
4103
	   }
4104
	   else
4105
	   {
4106
	      ay1 = (double)rh - (double)(lower1 - minHr) * htiHR;
4107
	      ay2 = (double)rh - (double)(lower2 - minHr) * htiHR;
4108
	      ay3 = (double)rh - (double)(lower3 - minHr) * htiHR;
4109
	      ay4 = (double)rh - (double)(upper3 - minHr) * htiHR;
4110
	      ay5 = (double)rh - (double)(avg_hr - minHr) * htiHR;
4111
	   }
4112
 
4113
	   ptHR.setPen(QPen(barcol2, 1, Qt::DashLine));	// color for limits
4114
 
4115
	   if (lower1 > minHr && lower1 < maxHr)
4116
	      ptHR.drawLine(x1, ay1, x2, ay1);
4117
 
4118
	   if (lower2 > minHr && lower2 < maxHr)
4119
	      ptHR.drawLine(x1, ay2, x2, ay2);
4120
 
4121
	   if (lower3 > minHr && lower3 < maxHr)
4122
	      ptHR.drawLine(x1, ay3, x2, ay3);
4123
 
4124
	   if (upper3 > minHr && upper3 < maxHr)
4125
	      ptHR.drawLine(x1, ay4, x2, ay4);
4126
 
4127
	   ptHR.setPen(QPen(red, 1, Qt::DashDotLine));	// color for average heart rate
4128
 
4129
	   if (avg_hr > minHr && avg_hr < maxHr)
4130
	      ptHR.drawLine(x1, ay5, x2, ay5);
4131
	}
4132
 
4133
	// Now we have a grid and we've done the scaling.
4134
	// This is the point where we draw the curves itself.
4135
	// We use different colors to draw the lines:
4136
	//
4137
	// Green: Elevation
4138
	// Red:   Speed
4139
	// Blue   Heart Rate
4140
	//
4141
	x1 = x2 = y1 = y2 = 0;
4142
	int hy1, hy2, hx1, hx2;
4143
	int sy1, sy2, sx1, sx2;
4144
	hy1 = hy2 = hx1 = hx2 = 0;
4145
	sy1 = sy2 = sx1 = sx2 = 0;
4146
	int hEc = 0;
4147
	i = 0;
4148
	AVGHEIGHT *avgHakt, *avgHfirst, *avgHlast, *avgHeight = 0;
4149
	avgHfirst = avgHlast = 0;
4150
	// To even the surface lines, we store every altitude in the
4151
	// memory, by building a chain. Then, if the user has set in the
4152
	// settings (Contour == true), we will even the line by calculating
4153
	// the average of 10 messure points and setting every value to the
4154
	// average, who is up or down more than 2 meters from the average.
4155
	while ((point = ds.getPoint(i)) != 0)
4156
	{
4157
	   if (point->alt > 20000.0 || point->alt < -1000.0)
4158
	   {
4159
	      i++;
4160
	      continue;
4161
	   }
4162
 
4163
	   if (!avgHeight)
4164
	   {
4165
	      avgHeight = new AVGHEIGHT;
4166
	      avgHeight->alt = point->alt;
4167
	      avgHeight->pos = hEc;
4168
	      avgHeight->prev = 0;
4169
	      avgHeight->next = 0;
4170
	      avgHakt = avgHeight;
4171
	      avgHfirst = avgHeight;
4172
	   }
4173
	   else
4174
	   {
4175
	      avgHakt = new AVGHEIGHT;
4176
	      avgHakt->alt = point->alt;
4177
	      avgHakt->pos = hEc;
4178
	      avgHakt->next = 0;
4179
	      avgHakt->prev = avgHeight;
4180
	      avgHeight->next = avgHakt;
4181
	      avgHeight = avgHakt;
4182
	   }
4183
 
4184
	   // FIXME: Currently we can not draw below 0 meters, because the
4185
	   // base line is always 0!
4186
	   if (avgHakt->alt < minHeight)
4187
	      avgHakt->alt = minHeight;
4188
 
4189
	   hEc++;
4190
	   i++;
4191
	}
4192
 
4193
	avgHlast = avgHeight;
4194
	// If wanted, even the lines
4195
	if (Contour && hEc > 0 && cuType != 0)
4196
	{
4197
	double alt[100], avg, avg1, avg2, avg3, avg4;
4198
	int a, pos;
4199
 
4200
	   for (i = 0; i < (hEc + 100); i += 100)
4201
	   {
4202
	      avg = avg1 = avg2 = avg3 = avg4 = 0.0;
4203
	      pos = 0;
4204
 
4205
	      for (a = 0; a < 100; a++)
4206
	      {
4207
		 alt[a] = getAvgAlt(avgHfirst, i + a);
4208
		 avg += alt[a];
4209
 
4210
		 if (a < 25)
4211
		    avg1 += alt[a];
4212
		 else if (a < 50)
4213
		    avg2 += alt[a];
4214
		 else if (a < 75)
4215
		    avg3 += alt[a];
4216
		 else
4217
		    avg4 += alt[a];
4218
	      }
4219
 
4220
	      if ((i + 100) >= hEc)
4221
		 avg /= (double)(hEc - i) + 1.0;
4222
	      else
4223
		 avg /= 100.0;
4224
 
4225
	      for (a = 0; a < 100; a++)
4226
	      {
4227
		 if ((avgHakt = getAvgPtr(avgHfirst, i + a)) != 0)
4228
		 {
4229
		    if ((avgHakt->alt - avg) > 2 || (avgHakt->alt - avg) < -2)
4230
		       avgHakt->alt = avg;
4231
		 }
4232
	      }
4233
	   }
4234
	}
4235
 
4236
	// plot the elevation, speed and/or heart rate. Depends on <cuType>)
4237
	i = 0;
4238
	int j = 0;
4239
	POINT *oldPoint = 0;
4240
	double speed = 0.0;	// calculated speed
4241
	bool pause = false;	// filter pause out of speed
4242
	unsigned long t1, t2;
4243
	t1 = t2 = 0;
4244
 
4245
	while ((point = ds.getPoint(i)) != 0)
4246
	{
4247
	bool loop = false;
4248
 
4249
	   if (!oldPoint)
4250
	      oldPoint = point;
4251
 
4252
	   // calculate the y position based on the time
4253
	   qt = garmin_dtime(point->time);
4254
	   secs = zeit.secsTo(qt->time());
4255
	   delete qt;
4256
 
4257
	   for (int c = 0; c < 3; c++)
4258
	   {
4259
	      if (c == 0)
4260
	      {
4261
		 x2 = secs * wtiHR + margin_left + 1;
4262
		 hx2 = x2;
4263
		 sx2 = x2;
4264
 
4265
		 if (x1 == 0)
4266
		    x1 = x2;
4267
 
4268
		 if (hx1 == 0)
4269
		    hx1 = hx2;
4270
 
4271
		 if (sx1 == 0)
4272
		    sx1 = sx2;
4273
	      }
4274
	      else if (c == 1)
4275
	      {
4276
		 x2 = secs * wtiElev + margin_left + 1;
4277
		 hx2 = x2;
4278
		 sx2 = x2;
4279
 
4280
		 if (x1 == 0)
4281
		    x1 = x2;
4282
 
4283
		 if (hx1 == 0)
4284
		    hx1 = hx2;
4285
 
4286
		 if (sx1 == 0)
4287
		    sx1 = sx2;
4288
	      }
4289
	      else
4290
	      {
4291
		 x2 = secs * wtiSpeed + margin_left + 1;
4292
		 hx2 = x2;
4293
		 sx2 = x2;
4294
 
4295
		 if (x1 == 0)
4296
		    x1 = x2;
4297
 
4298
		 if (hx1 == 0)
4299
		    hx1 = hx2;
4300
 
4301
		 if (sx1 == 0)
4302
		    sx1 = sx2;
4303
	      }
4304
	      // The speed is not very exact, because smallest time is
4305
	      // one second. This allows a maximum error of 99 hundredths
4306
	      // of a second, what is very close to one second. Because of
4307
	      // this, speed seems to hop for every messure point. This
4308
	      // looks ugly, but currently I don't know how to make it
4309
	      // better.
4310
	      if (c == 2)	// Draw speed?
4311
	      {
4312
	      double dist;
4313
	      double sc;
4314
 
4315
		 if (!pause && point->distance > 1.0e10)
4316
		 {
4317
		    pause = true;
4318
		    t1 = point->time;
4319
		 }
4320
		 else if (pause)
4321
		 {
4322
		    pause = false;
4323
		    t2 = point->time;
4324
		    i += 2;
4325
		    loop = true;
4326
		 }
4327
 
4328
		 if (point->distance >= 0.1 && point->distance < 1.0e10)
4329
		 {
4330
		    dist = point->distance - oldPoint->distance;
4331
		    sc = point->time - oldPoint->time;
4332
		    LAP *runde = ds.getLapT (point->time);
4333
 
4334
		    if (t2 > t1)
4335
		    {
4336
		       sc -= t2 - t1;
4337
 
4338
		       if (sc <= 0.0)
4339
			  sc = 1.0;		// at least 1 second!
4340
		    }
4341
 
4342
		    speed = (dist / sc) * 3.6;
4343
 
4344
		    if (runde && runde->max_speed > 0.0 && speed > (runde->max_speed * 3.6))
4345
		       speed = runde->max_speed * 3.6;
4346
 
4347
		    if (Units == 1)
4348
		       speed /= 1.609344;
4349
 
4350
		    if (speed < minSpeed || speed > 400.0)
4351
		       speed = minSpeed;
4352
 
4353
		    y2 = (double)rh - (speed - minSpeed) * htiSpeed;
4354
 
4355
		    if (y1 == 0)
4356
		       y1 = y2;
4357
 
4358
		    ptSpeed.setPen(QPen(red, 1, Qt::SolidLine));
4359
		    ptSpeed.drawLine(x1, y1, x2, y2);
4360
		    y1 = y2;
4361
		    x1 = x2;
4362
		    t1 = t2 = 0;
4363
		    oldPoint = point;
4364
		 }
4365
	      }
4366
 
4367
	      if (c == 1)		// Draw elevation?
4368
	      {
4369
		 if (point->alt < 20000.0 && point->alt > -1000.0)
4370
		 {
4371
		 double alt = getAvgAlt(avgHfirst, j);
4372
 
4373
		    j++;
4374
 
4375
		    sy2 = (double)rh - (alt - minHeight) * htiElev;
4376
 
4377
		    if (sy1 == 0)
4378
		       sy1 = sy2;
4379
 
4380
		    ptElevation.setPen(QPen(barcol, 1, Qt::SolidLine));
4381
		    ptElevation.drawLine(sx1, sy1, sx2, sy2);
4382
		    sy1 = sy2;
4383
		    sx1 = sx2;
4384
		 }
4385
	      }
4386
 
4387
	      if (point->heart_rate > 0 && c == 0)	// Draw heart rate?
4388
	      {
4389
		 hy2 = (double)rh - (double)(point->heart_rate - minHr) * htiHR;
4390
 
4391
		 if (hy1 == 0)
4392
		    hy1 = hy2;
4393
 
4394
		 ptHR.setPen(QPen(blue, 1, Qt::SolidLine));
4395
		 ptHR.drawLine(hx1, hy1, hx2, hy2);
4396
		 hy1 = hy2;
4397
		 hx1 = hx2;
4398
	      }
4399
	   }
4400
 
4401
	   if (loop)
4402
	   {
4403
	      loop = false;
4404
	      continue;
4405
	   }
4406
 
4407
	   i++;
4408
	}
4409
 
4410
	ptHR.end();
4411
	ptElevation.end();
4412
	ptSpeed.end();
4413
	ui_sportwatcherWidgetBase.grHR->setPixmap(pmHR);
4414
	ui_sportwatcherWidgetBase.grElevation->setPixmap(pmElevation);
4415
	ui_sportwatcherWidgetBase.grSpeed->setPixmap(pmSpeed);
4416
 
4417
	// free the chain of altitudes
4418
	avgHakt = avgHfirst;
4419
 
4420
	while (avgHakt)
4421
	{
4422
	   avgHeight = avgHakt->next;
4423
	   delete avgHakt;
4424
	   avgHakt = avgHeight;
4425
	}
4426
 
4427
	DIRTY = false;
4428
}
4429
 
169 andreas 4430
double sportwatcherWidget::getAvgAlt(AVGHEIGHT *avgHeight, int pos)
4431
{
4432
AVGHEIGHT *akt;
4433
 
170 andreas 4434
	if (!avgHeight)
4435
	   return 0.0;
4436
 
169 andreas 4437
	akt = avgHeight;
4438
 
4439
	while (akt)
4440
	{
4441
	   if (akt->pos == pos)
4442
	      return akt->alt;
4443
 
4444
	   akt = akt->next;
4445
	}
4446
 
4447
	return 0.0;
4448
}
4449
 
4450
AVGHEIGHT *sportwatcherWidget::getAvgPtr(AVGHEIGHT *avgHeight, int pos)
4451
{
4452
AVGHEIGHT *akt;
4453
 
4454
	akt = avgHeight;
4455
 
4456
	while (akt)
4457
	{
4458
	   if (akt->pos == pos)
4459
	      return akt;
4460
 
4461
	   akt = akt->next;
4462
	}
4463
 
4464
	return 0;
4465
}
4466
 
246 andreas 4467
void sportwatcherWidget::resizeEvent(QResizeEvent *e)
88 andreas 4468
{
246 andreas 4469
	if (e->size() != e->oldSize())
4470
	   DIRTY=true;
4471
 
132 andreas 4472
	showTrack(zfactor);
88 andreas 4473
	showCurves();
250 andreas 4474
	tabDirt2 = true;
4475
 
4476
	if (curTab == 2)
4477
	{
4478
	   showThreeCurve();
4479
	   tabDirt2 = false;
4480
	}
4481
 
246 andreas 4482
	DIRTY=false;
88 andreas 4483
}
4484
 
132 andreas 4485
void sportwatcherWidget::mouseMoveEvent(QMouseEvent *e)
4486
{
4487
QPoint pos(0, 0);
245 andreas 4488
QPoint ev = ui_sportwatcherWidgetBase.imgMap->mapFrom(this, e->pos());
132 andreas 4489
static QRect coord;
88 andreas 4490
 
246 andreas 4491
	DIRTY=true;
4492
 
250 andreas 4493
	if (curTab == 0)
132 andreas 4494
	{
250 andreas 4495
	   if (!stateHand)
4496
	      return;
4497
 
4498
	   if (ev.x() >= pos.x() &&
4499
	       ev.y() >= pos.y() &&
4500
	       ev.x() <= (pos.x() + ui_sportwatcherWidgetBase.imgMap->geometry().width()) &&
4501
	       ev.y() <= (pos.y() + ui_sportwatcherWidgetBase.imgMap->geometry().height()))
132 andreas 4502
	   {
250 andreas 4503
	      if (lmbPressed == 1)
4504
	      {
4505
		 coord.setCoords(ev.x(), ev.y(), 0, 0);
4506
		 lmbPressed = 0;
4507
	      }
4508
	      else
4509
	      {
4510
		 coord.setRight(ev.x());
4511
		 coord.setBottom(ev.y());
4512
	      }
4513
 
4514
	      if (lmbPressed == 2)
4515
	      {
4516
		 showTrack(zfactor, coord, mapLap);
4517
		 lmbPressed = 0;
4518
	      }
132 andreas 4519
	   }
250 andreas 4520
	}
4521
 
4522
	if (curTab == 2)
4523
	{
4524
	   // look in which of the three QLabels the mouse is, if it is in
4525
	   // one of them.
4526
	   ev = ui_sportwatcherWidgetBase.grHR->mapFrom(this, e->pos());
4527
 
4528
	   if (ev.x() >= pos.x() &&
4529
	       ev.y() >= pos.y() &&
4530
	       ev.x() <= (pos.x() + ui_sportwatcherWidgetBase.grHR->geometry().width()) &&
4531
	       ev.y() <= (pos.y() + ui_sportwatcherWidgetBase.grHR->geometry().height()))
132 andreas 4532
	   {
250 andreas 4533
	      drawGrHR (ev.x(), ev.y());
4534
	      drawGrElev (ev.x(), -1);
4535
	      drawGrSpeed (ev.x(), -1);
132 andreas 4536
	   }
4537
 
250 andreas 4538
	   ev = ui_sportwatcherWidgetBase.grElevation->mapFrom(this, e->pos());
4539
 
4540
	   if (ev.x() >= pos.x() &&
4541
	       ev.y() >= pos.y() &&
4542
	       ev.x() <= (pos.x() + ui_sportwatcherWidgetBase.grElevation->geometry().width()) &&
4543
	       ev.y() <= (pos.y() + ui_sportwatcherWidgetBase.grElevation->geometry().height()))
132 andreas 4544
	   {
250 andreas 4545
	      drawGrHR (ev.x(), -1);
4546
	      drawGrElev (ev.x(), ev.y());
4547
	      drawGrSpeed (ev.x(), -1);
132 andreas 4548
	   }
250 andreas 4549
 
4550
	   ev = ui_sportwatcherWidgetBase.grSpeed->mapFrom(this, e->pos());
4551
 
4552
	   if (ev.x() >= pos.x() &&
4553
	       ev.y() >= pos.y() &&
4554
	       ev.x() <= (pos.x() + ui_sportwatcherWidgetBase.grSpeed->geometry().width()) &&
4555
	       ev.y() <= (pos.y() + ui_sportwatcherWidgetBase.grSpeed->geometry().height()))
4556
	   {
4557
	      drawGrHR (ev.x(), -1);
4558
	      drawGrElev (ev.x(), -1);
4559
	      drawGrSpeed (ev.x(), ev.y());
4560
	   }
132 andreas 4561
	}
246 andreas 4562
 
4563
	DIRTY=false;
132 andreas 4564
}
4565
 
4566
void sportwatcherWidget::mousePressEvent(QMouseEvent *e)
4567
{
232 andreas 4568
	if (stateHand && e->button() == Qt::LeftButton)
132 andreas 4569
	   lmbPressed = 1;	// Left Mouse Button is pressed
4570
	else if (stateHand)
4571
	   lmbPressed = 0;	// Wrong button is pressed
4572
 
4573
	if (stateGlas)
4574
	{
232 andreas 4575
	   if (e->button() == Qt::LeftButton)
132 andreas 4576
	      btGlasPlusSlot();
232 andreas 4577
	   else if (e->button() == Qt::RightButton)
132 andreas 4578
	      btGlasMinusSlot();
4579
	}
4580
}
4581
 
4582
void sportwatcherWidget::mouseReleaseEvent(QMouseEvent *e)
4583
{
232 andreas 4584
	if (stateHand && e->button() == Qt::LeftButton)
132 andreas 4585
	{
4586
	   lmbPressed = 2;	// Left Mouse Button was released
4587
	   mouseMoveEvent(e);
4588
	}
4589
}
4590
 
88 andreas 4591
/*
250 andreas 4592
 * Private functions to draw cross and/or a bar to reflect the mouse
4593
 * pointer on tab 2.
4594
 */
4595
void sportwatcherWidget::drawGrHR (int x, int y)
4596
{
4597
int width, height;
4598
QPixmap pm = pmHR.copy(pmHR.rect());
4599
QPainter paint;
4600
 
4601
	width = ui_sportwatcherWidgetBase.grHR->width();
4602
	height = ui_sportwatcherWidgetBase.grHR->height();
4603
	ui_sportwatcherWidgetBase.grHR->setPixmap(pmHR);
4604
 
4605
	if (x > (width - 40) || y > (height - 12) || x < 1)
4606
	{
4607
	   ui_sportwatcherWidgetBase.grElevation->setPixmap(pmElevation);
4608
	   ui_sportwatcherWidgetBase.grSpeed->setPixmap(pmSpeed);
4609
	   return;
4610
	}
4611
 
4612
	if (tabDirt2)
4613
	{
4614
	   DIRTY = true;
4615
	   showThreeCurve ();
4616
	   tabDirt2 = false;
4617
	   DIRTY = false;
4618
	}
4619
 
4620
	paint.begin(&pm);
4621
	QColor black(0, 0, 0);
4622
	black.setAlpha (128);
4623
	paint.setPen(QPen(black, 1, Qt::SolidLine));
4624
	// horizontal line, if y != -1
4625
	if (y >= 0)
4626
	   paint.drawLine(2, y, width - 41, y);
4627
 
4628
	// vertical line
4629
	paint.drawLine(x, 1, x, height - 13);
4630
	paint.end();
4631
	ui_sportwatcherWidgetBase.grHR->setPixmap(pm);
4632
}
4633
 
4634
void sportwatcherWidget::drawGrElev (int x, int y)
4635
{
4636
int width, height;
4637
QPixmap pm = pmElevation.copy(pmElevation.rect());
4638
QPainter paint;
4639
 
4640
	width = ui_sportwatcherWidgetBase.grElevation->width();
4641
	height = ui_sportwatcherWidgetBase.grElevation->height();
4642
	ui_sportwatcherWidgetBase.grElevation->setPixmap(pmElevation);
4643
 
4644
	if (x > (width - 40) || y > (height - 12) || x < 1)
4645
	{
4646
	   ui_sportwatcherWidgetBase.grHR->setPixmap(pmHR);
4647
	   ui_sportwatcherWidgetBase.grSpeed->setPixmap(pmSpeed);
4648
	   return;
4649
	}
4650
 
4651
	if (tabDirt2)
4652
	{
4653
	   DIRTY = true;
4654
	   showThreeCurve ();
4655
	   tabDirt2 = false;
4656
	   DIRTY = false;
4657
	}
4658
 
4659
	paint.begin(&pm);
4660
	QColor black(0, 0, 0);
4661
	black.setAlpha (128);
4662
	paint.setPen(QPen(black, 1, Qt::SolidLine));
4663
	// horizontal line, if y != -1
4664
	if (y >= 0)
4665
	   paint.drawLine(2, y, width - 41, y);
4666
 
4667
	// vertical line
4668
	paint.drawLine(x, 1, x, height - 13);
4669
	paint.end();
4670
	ui_sportwatcherWidgetBase.grElevation->setPixmap(pm);
4671
}
4672
 
4673
void sportwatcherWidget::drawGrSpeed (int x, int y)
4674
{
4675
int width, height;
4676
QPixmap pm = pmSpeed.copy(pmSpeed.rect());
4677
QPainter paint;
4678
 
4679
	width = ui_sportwatcherWidgetBase.grSpeed->width();
4680
	height = ui_sportwatcherWidgetBase.grSpeed->height();
4681
	ui_sportwatcherWidgetBase.grSpeed->setPixmap(pmSpeed);
4682
 
4683
	if (x > (width - 40) || y > (height - 12) || x < 1)
4684
	{
4685
	   ui_sportwatcherWidgetBase.grHR->setPixmap(pmHR);
4686
	   ui_sportwatcherWidgetBase.grElevation->setPixmap(pmElevation);
4687
	   return;
4688
	}
4689
 
4690
	if (tabDirt2)
4691
	{
4692
	   DIRTY = true;
4693
	   showThreeCurve ();
4694
	   tabDirt2 = false;
4695
	   DIRTY = false;
4696
	}
4697
 
4698
	paint.begin(&pm);
4699
	QColor black(0, 0, 0);
4700
	black.setAlpha (128);
4701
	paint.setPen(QPen(black, 1, Qt::SolidLine));
4702
	// horizontal line, if y != -1
4703
	if (y >= 0)
4704
	   paint.drawLine(2, y, width - 41, y);
4705
 
4706
	// vertical line
4707
	paint.drawLine(x, 1, x, height - 13);
4708
	paint.end();
4709
	ui_sportwatcherWidgetBase.grSpeed->setPixmap(pm);
4710
}
4711
 
4712
/*
88 andreas 4713
 * Private functions to help decode the data
4714
 */
4715
QDateTime *sportwatcherWidget::garmin_dtime (uint32 t)
4716
{
4717
time_t     tval;
4718
struct tm  tmval;
4719
QTime ti;
4720
QDate dt;
4721
QDateTime *qt;
4722
 
4723
	if (t == 0)
4724
	   return new QDateTime(QDate(1900, 1, 1), QTime(0, 0, 0, 0));
4725
 
4726
	tval = t + TIME_OFFSET;
4727
	localtime_r (&tval, &tmval);
4728
	qt = new QDateTime();
4729
	qt->setDate(QDate(tmval.tm_year+1900, tmval.tm_mon+1, tmval.tm_mday));
4730
	qt->setTime(QTime(tmval.tm_hour, tmval.tm_min, tmval.tm_sec, 0));
4731
	/* OK.  Done. */
4732
	return qt;
4733
}
4734
 
104 andreas 4735
bool sportwatcherWidget::writeTag(const QFile &fn, const QString &str, int indent)
4736
{
4737
QString qs;
232 andreas 4738
char *p;
4739
//QCString qcs;
104 andreas 4740
int i;
88 andreas 4741
 
171 andreas 4742
	if (indent > 0)
4743
	   qs.fill(' ', indent * 3);
4744
 
104 andreas 4745
	qs.append(str);
232 andreas 4746
//	qcs = qs.utf8();
4747
//	qstrcpy(p, qcs);
4748
	p = strdup (qs.toUtf8().data());
104 andreas 4749
	i = strlen(p);
4750
 
4751
	if (write(fn.handle(), p, i) != i)
4752
	{
232 andreas 4753
	   free (p);
104 andreas 4754
	   return false;
4755
	}
4756
 
232 andreas 4757
	free (p);
104 andreas 4758
	return true;
4759
}
4760
 
232 andreas 4761
#if defined HAVE_GDAL
151 andreas 4762
bool sportwatcherWidget::writeWMSTag(double llat, double llon, double rlat, double rlon, int width, int height)
4763
{
4764
QFile fl(MAP);
152 andreas 4765
QString xml, s, srs, crs, styles, bSize, ext;
4766
QDir dir = QDir::home();
232 andreas 4767
QString path = dir.absolutePath();
157 andreas 4768
int item, isrs;
4769
double _llat, _llon, _rlat, _rlon;
4770
bool offline, square;
151 andreas 4771
 
232 andreas 4772
	if (!fl.open(QIODevice::ReadWrite | QIODevice::Truncate))
151 andreas 4773
	{
4774
	   KMessageBox::error (this, i18n("Error opening or creating the WMS tag file!\nPlease check file name and/or permissions."));
4775
	   return false;
4776
	}
4777
 
232 andreas 4778
	KConfig cfg (QString("sportwatcher.rc"), KConfig::SimpleConfig);
4779
	KConfigGroup wms (&cfg, "WMS");
4780
	square = wms.readEntry("Square", false);
4781
	styles = wms.readEntry("Styles", QString(""));
152 andreas 4782
 
151 andreas 4783
	xml = "<GDAL_WMS>\n";
4784
	xml += "   <Service name=\"WMS\">\n";
4785
	xml += "      <Version>1.1.1</Version>\n";
232 andreas 4786
	xml += "      <ServerURL>" + wms.readEntry("ServerURL", "http://onearth.jpl.nasa.gov/wms.cgi") + "?</serverURL>\n";
4787
	isrs = wms.readEntry("SRS", 0);
157 andreas 4788
	_llon = llon;
4789
	_llat = llat;
4790
	_rlon = rlon;
4791
	_rlat = rlat;
4792
	offline = false;
152 andreas 4793
 
157 andreas 4794
	switch (isrs)
152 andreas 4795
	{
4796
	   case 0: srs = QString("EPSG:4326"); break;
157 andreas 4797
 
4798
	   case 1:
4799
	      srs = QString("EPSG:31257");
4800
	      offline = transCoords(&_llat, &_llon, &_rlat, &_rlon, 31257, width, height, square);
4801
	   break;
4802
 
4803
	   case 2:
4804
	      srs = QString("EPSG:31258");
4805
	      offline = transCoords(&_llat, &_llon, &_rlat, &_rlon, 31258, width, height, square);
4806
	   break;
4807
 
4808
	   case 3:
4809
	      srs = QString("EPSG:31259");
4810
	      offline = transCoords(&_llat, &_llon, &_rlat, &_rlon, 31259, width, height, square);
4811
	   break;
4812
 
4813
	   case 4:
4814
	      srs = QString("EPSG:31286");
4815
	      offline = transCoords(&_llat, &_llon, &_rlat, &_rlon, 31286, width, height, square);
4816
	   break;
4817
 
4818
	   case 5:
4819
	      srs = QString("EPSG:31287");
4820
	      offline = transCoords(&_llat, &_llon, &_rlat, &_rlon, 31287, width, height, square);
4821
	   break;
4822
 
4823
	   case 6:
4824
	      srs = QString("EPSG:31288");
4825
	      offline = transCoords(&_llat, &_llon, &_rlat, &_rlon, 31288, width, height, square);
4826
	   break;
4827
 
152 andreas 4828
	   default: srs = QString("EPSG:4326");
4829
	}
4830
 
4831
	xml += "      <SRS>" + srs + "</SRS>\n";
232 andreas 4832
	item = wms.readEntry("CRS", 0);
152 andreas 4833
 
4834
	switch (item)
4835
	{
4836
	   case 0: crs = QString("CRS:83"); break;
157 andreas 4837
	   case 1: crs = QString("CRS:84"); break;
4838
	   case 2: crs = QString("EPSG:4326"); break;
4839
	   case 3: crs = QString("EPSG:31259"); break;
4840
	   case 4: crs = QString("EPSG:31287"); break;
152 andreas 4841
	   default: crs = QString("CRS:83"); break;
4842
	}
4843
 
4844
	xml += "      <CRS>" + crs + "</CRS>\n";
232 andreas 4845
	item = wms.readEntry("Image", 2);
152 andreas 4846
	xml += "      <ImageFormat>image/";
4847
 
4848
	switch (item)
4849
	{
4850
	   case 0: xml += "gif"; ext = QString(".gif"); break;
4851
	   case 1: xml += "jpeg"; ext = QString(".jpg"); break;
4852
	   case 2: xml += "png"; ext = QString(".png"); break;
4853
	   case 3: xml += "tiff"; ext = QString(".tif"); break;
4854
	   default: xml += "png"; ext = QString(".png");
4855
	}
4856
 
4857
	xml += "</ImageFormat>\n";
4858
 
232 andreas 4859
	xml += "      <Layers>" + wms.readEntry("Layer", QString("")) + "</Layers>\n";
152 andreas 4860
 
4861
	if (!styles.isEmpty())
4862
	   xml += "      <Styles>" + styles + "</Styles>\n";
4863
 
151 andreas 4864
	xml += "      <BBoxOrder>xyXY</BBoxOrder>\n";
4865
	xml += "   </Service>\n";
4866
	xml += "   <DataWindow>\n";
157 andreas 4867
	s.sprintf ("%f", _llat);
151 andreas 4868
	xml += "      <UpperLeftX>" + s + "</UpperLeftX>\n";
157 andreas 4869
	s.sprintf ("%f", _llon);
151 andreas 4870
	xml += "      <UpperLeftY>" + s + "</UpperLeftY>\n";
157 andreas 4871
	s.sprintf ("%f", _rlat);
151 andreas 4872
	xml += "      <LowerRightX>" + s + "</LowerRightX>\n";
157 andreas 4873
	s.sprintf ("%f", _rlon);
151 andreas 4874
	xml += "      <LowerRightY>" + s + "</LowerRightY>\n";
4875
	s.sprintf ("%d", width);
4876
	xml += "      <SizeX>" + s + "</SizeX>\n";
4877
	s.sprintf ("%d", height);
4878
	xml += "      <SizeY>" + s + "</SizeY>\n";
4879
	xml += "   </DataWindow>\n";
157 andreas 4880
 
4881
/*	switch (isrs)
4882
	{
4883
	   case 0: srs = QString("EPSG:4326"); break;
4884
	   case 1: srs = QString("EPSG:31259"); break;
4885
	   case 2: srs = QString("EPSG:31286"); break;
4886
	   case 3: srs = QString("EPSG:31287"); break;
4887
	   case 4: srs = QString("EPSG:31288"); break;
4888
	   default: srs = QString("EPSG:4326");
4889
	}
4890
*/
4891
//	srs = QString("EPSG:4326");
4892
	xml += "   <Projection>" + srs + "</Projection>\n";
232 andreas 4893
	xml += "   <BandsCount>" + wms.readEntry("Bands", QString("3")) + "</BandsCount>\n";
4894
	item = wms.readEntry("Tile", 2);
152 andreas 4895
 
4896
	switch (item)
4897
	{
4898
	   case 0: bSize = QString("64"); break;
4899
	   case 1: bSize = QString("128"); break;
4900
	   case 2: bSize = QString("256"); break;
4901
	   case 3: bSize = QString("512"); break;
4902
	   case 4: bSize = QString("1024"); break;
4903
	   default: bSize = QString("256");
4904
	}
4905
 
4906
	xml += "   <BlockSizeX>" + bSize + "</BlockSizeX>\n";
4907
	xml += "   <BlockSizeY>" + bSize + "</BlockSizeY>\n";
232 andreas 4908
	xml += "   <OverviewCount>" + wms.readEntry("Overview", QString("10")) + "</OverviewCount>\n";
151 andreas 4909
	xml += "   <Cache>\n";
152 andreas 4910
	xml += "      <Path>" + path + "/.gdalwmscache" + "</Path>\n";
232 andreas 4911
	xml += "      <Depth>" + wms.readEntry("Depth", QString("2")) + "</Depth>\n";
152 andreas 4912
	xml += "      <Extension>" + ext + "</Extension>\n";
151 andreas 4913
	xml += "   </Cache>\n";
232 andreas 4914
	QString off((wms.readEntry("Offline", false)) ? "true" : "false");
4915
	QString adv((wms.readEntry("Advice", false)) ? "true" : "false");
4916
	QString ver((wms.readEntry("Verify", true)) ? "true" : "false");
157 andreas 4917
 
4918
	if (offline)
4919
	   xml += "   <OfflineMode>true</OfflineMode>\n";
4920
	else
4921
	   xml += "   <OfflineMode>" + off + "</OfflineMode>\n";
4922
 
152 andreas 4923
	xml += "   <AdviseRead>" + adv + "</AdviseRead>\n";
4924
	xml += "   <VerifyAdviseRead>" + ver + "</VerifyAdviseRead>\n";
151 andreas 4925
	xml += "</GDAL_WMS>\n";
4926
 
232 andreas 4927
	write (fl.handle(), xml.toAscii().data(), strlen (xml.toAscii().data()));
151 andreas 4928
	fl.close();
4929
	return true;
4930
}
4931
 
157 andreas 4932
bool sportwatcherWidget::transCoords (double *x1, double *y1, double *x2, double *y2, int code, int width, int height, bool square)
151 andreas 4933
{
157 andreas 4934
OGRSpatialReference oSourceSRS, oTargetSRS;
4935
OGRCoordinateTransformation *poCT;
4936
 
4937
	oSourceSRS.SetWellKnownGeogCS ("WGS84");
4938
	oTargetSRS.importFromEPSG(code);
4939
	poCT = OGRCreateCoordinateTransformation (&oSourceSRS, &oTargetSRS);
4940
 
4941
	if (poCT == NULL || !poCT->Transform( 1, x1, y1))
4942
	{
4943
	   KMessageBox::error(this, i18n("Translation between coordinate systems failed!"));
4944
 
4945
	   if (poCT != NULL)
4946
	      delete poCT;
4947
 
4948
	   return true;
4949
	}
4950
 
4951
	if (poCT != NULL)
4952
	{
4953
	   poCT->Transform (1, x2, y2);
4954
	   delete poCT;
4955
	}
4956
 
4957
	if (square)
4958
	{
4959
	double wdiff = (double)((long)(*x1 - *x2) / (width / 2 * 2) * (width / 2 * 2));
4960
	double hdiff = (double)((long)(*y2 - *y1) / (height / 2 * 2) * (height / 2 * 2));
4961
 
4962
	   *x2 = *x1 - wdiff; // * (double)mFactor;
4963
	   *y2 = *y1 + hdiff; // * (double)mFactor;
4964
//	   *x2 = *x1 - (double)((long)(wdiff / mFactor * mFactor));
4965
//	   *y2 = *y1 - (double)((long)(hdiff / mFactor * mFactor));
4966
/*	   wdiff = wdiff - (*x1 - *x2);
4967
	   hdiff = hdiff - (*y2 - *y1);
4968
	   *x1 -= wdiff / 2.0;
4969
	   *x2 -= wdiff / 2.0;
4970
	   *y1 += hdiff / 2.0;
4971
	   *y2 += hdiff / 2.0; */
4972
	}
4973
 
4974
	return false;
151 andreas 4975
}
4976
 
158 andreas 4977
QString *sportwatcherWidget::getProjection (int isrs, QString *srs)
4978
{
4979
	switch (isrs)
4980
	{
4981
	   case 0: *srs = QString("EPSG:4326"); break;
4982
	   case 1: *srs = QString("EPSG:31257"); break;
4983
	   case 2: *srs = QString("EPSG:31258"); break;
4984
	   case 3: *srs = QString("EPSG:31259"); break;
4985
	   case 4: *srs = QString("EPSG:31286"); break;
4986
	   case 5: *srs = QString("EPSG:31287"); break;
4987
	   case 6: *srs = QString("EPSG:31288"); break;
4988
	   default: *srs = QString("EPSG:4326");
4989
	}
4990
 
4991
	return srs;
4992
}
4993
 
4994
bool sportwatcherWidget::warpImage(QString fn, QString *fName)
4995
{
4996
GDALDatasetH  hSrcDS, hDstDS;
4997
GDALDataset *inSet, *outSet;
4998
GDALDataType eDT;
4999
GDALRasterBand *poBand;
5000
GDALDriverH hDriver;
5001
char hv0[256];
5002
int nXSize, nYSize;
5003
double adfGeoTransform[6];
5004
double oriLeftLon, oriRightLon, oriLeftLat, oriRightLat;
5005
 
159 andreas 5006
 
5007
	// Loading the user set geo coords of our source image and
5008
	// load the projection used for that image
232 andreas 5009
	KConfig cfg (QString("sportwatcher.rc"), KConfig::SimpleConfig);
5010
	KConfigGroup ic (&cfg, "ImageCoords");
5011
	oriLeftLon = ic.readEntry("LeftLon", 0.0);
5012
	oriLeftLat = ic.readEntry("LeftLat", 0.0);
5013
	oriRightLon = ic.readEntry("RightLon", 0.0);
5014
	oriRightLat = ic.readEntry("RightLat", 0.0);
5015
	int isrs = ic.readEntry("SRS", 0);
159 andreas 5016
 
158 andreas 5017
	// Create a temporary file name for our output file
5018
	strcpy (hv0, "/tmp/SportWatcherTIFFXXXXXX");
216 andreas 5019
	mkdtemp (&hv0[0]);
158 andreas 5020
	*fName = QString(hv0) + ".tif";
5021
 
5022
	// Open input and output files.
232 andreas 5023
	if ((hSrcDS = GDALOpen(fn.toAscii().data(), GA_ReadOnly)) == NULL)
158 andreas 5024
	{
5025
	   KMessageBox::error(this, i18n("Error opening an image file!"));
5026
	   return false;
5027
	}
5028
 
5029
	inSet = (GDALDataset *)hSrcDS;
5030
	// Create output with same datatype as first input band.
5031
	poBand = inSet->GetRasterBand (1);
5032
	eDT = poBand->GetRasterDataType ();
5033
 
5034
	if ((hDriver = GDALGetDriverByName ("GTiff")) == NULL)
5035
	{
5036
	   KMessageBox::error(this, i18n("Error loading the TIFF driver!"));
5037
	   GDALClose (hSrcDS);
5038
	   return false;
5039
	}
5040
 
5041
	// Get dimensions of image and set transform data
5042
	int nRasterCount = inSet->GetRasterCount();
5043
	nXSize = inSet->GetRasterXSize();
5044
	nYSize = inSet->GetRasterYSize();
5045
 
159 andreas 5046
	// cut the wanted region out of image
5047
	transform *tf = new transform (oriLeftLat, oriLeftLon, oriRightLat, oriRightLon);
5048
	tf->setDimensions(nXSize, nYSize);
158 andreas 5049
 
159 andreas 5050
	if (!tf->cutImage (geoRect.llat, geoRect.llon, geoRect.rlat, geoRect.rlon, fn))
5051
	{
5052
	   GDALClose (hSrcDS);
5053
	   return false;
5054
	}
158 andreas 5055
 
159 andreas 5056
	GDALClose (hSrcDS);
5057
	QString nfn = fn + "_tmp.png";
158 andreas 5058
 
159 andreas 5059
	// repeat the part above and open the now cutted part of the image.
5060
	// Open input and output files.
232 andreas 5061
	if ((hSrcDS = GDALOpen(nfn.toAscii().data(), GA_ReadOnly)) == NULL)
159 andreas 5062
	{
5063
	   KMessageBox::error(this, i18n("Error opening an image file!"));
5064
	   return false;
5065
	}
158 andreas 5066
 
159 andreas 5067
	inSet = (GDALDataset *)hSrcDS;
5068
	// Create output with same datatype as first input band.
5069
	poBand = inSet->GetRasterBand (1);
5070
	eDT = poBand->GetRasterDataType ();
158 andreas 5071
 
159 andreas 5072
	if ((hDriver = GDALGetDriverByName ("GTiff")) == NULL)
158 andreas 5073
	{
159 andreas 5074
	   KMessageBox::error(this, i18n("Error loading the TIFF driver!"));
5075
	   GDALClose (hSrcDS);
5076
	   return false;
158 andreas 5077
	}
5078
 
159 andreas 5079
	// Get dimensions of image and set transform data
5080
	nRasterCount = inSet->GetRasterCount();
5081
	nXSize = inSet->GetRasterXSize();
5082
	nYSize = inSet->GetRasterYSize();
5083
 
158 andreas 5084
	// Set the values needed to transform the image
5085
	OGRSpatialReference iSRS;
5086
	const char *iWKT;
5087
 
5088
	switch (isrs)
5089
	{
5090
	   case 0: iSRS.importFromEPSG(4326); break;
5091
	   case 1: iSRS.importFromEPSG(31257); break;
5092
	   case 2: iSRS.importFromEPSG(31258); break;
5093
	   case 3: iSRS.importFromEPSG(31259); break;
5094
	   case 4: iSRS.importFromEPSG(31286); break;
5095
	   case 5: iSRS.importFromEPSG(31287); break;
5096
	   case 6: iSRS.importFromEPSG(31288); break;
5097
	   default: iSRS.importFromEPSG(4326);
5098
	}
5099
 
5100
	iSRS.exportToWkt ((char **)&iWKT);
5101
 
5102
	if (inSet->SetProjection (iWKT) != CE_None)
5103
	{
5104
	   KMessageBox::error(this, i18n("Error setting projection on source!"));
5105
	   GDALClose (hSrcDS);
5106
	   return false;
5107
	}
5108
 
159 andreas 5109
	adfGeoTransform[0] = geoRect.llon;
5110
	adfGeoTransform[1] = (geoRect.rlon - geoRect.llon) / (double)nXSize;
158 andreas 5111
	adfGeoTransform[2] = 0.0;
159 andreas 5112
	adfGeoTransform[3] = geoRect.llat;
158 andreas 5113
	adfGeoTransform[4] = 0.0;
159 andreas 5114
	adfGeoTransform[5] = -1.0 * ((geoRect.llat - geoRect.rlat) / (double)nYSize);
158 andreas 5115
 
5116
	if (inSet->SetGeoTransform (&adfGeoTransform[0]) != CE_None)
5117
	{
5118
	   KMessageBox::error(this, i18n("Error setting geo transform data to source!"));
5119
	   GDALClose (hSrcDS);
5120
	   return false;
5121
	}
5122
 
159 andreas 5123
	// Get Source coordinate system.
158 andreas 5124
	const char *pszSrcWKT, *pszDstWKT = NULL;
5125
 
5126
	if ((pszSrcWKT = GDALGetProjectionRef (hSrcDS)) == NULL)
5127
	{
5128
	   KMessageBox::error(this, i18n("Error getting the projection reference"));
5129
	   GDALClose (hSrcDS);
5130
	   return false;
5131
	}
5132
 
5133
	// Setup output coordinate system that is UTM ? WGS84.
5134
	OGRSpatialReference oSRS;
5135
 
159 andreas 5136
//	oSRS.SetUTM( 0, TRUE );
158 andreas 5137
	oSRS.SetWellKnownGeogCS("WGS84");
5138
	oSRS.exportToWkt ((char **)&pszDstWKT);
5139
 
159 andreas 5140
	// Create the output file.
158 andreas 5141
	double adfDstGeoTransform[6];
159 andreas 5142
	adfDstGeoTransform[0] = geoRect.llon;
5143
	adfDstGeoTransform[1] = (geoRect.rlon - geoRect.llon) / (double)geoRect.width;
158 andreas 5144
	adfDstGeoTransform[2] = 0.0;
5145
	adfDstGeoTransform[3] = geoRect.llat;
5146
	adfDstGeoTransform[4] = 0.0;
159 andreas 5147
	adfDstGeoTransform[5] = -1.0 * ((geoRect.llat - geoRect.rlat) / (double)geoRect.height);
158 andreas 5148
 
232 andreas 5149
	if ((hDstDS = GDALCreate(hDriver, fName->toAscii().data(), geoRect.width, geoRect.height,
158 andreas 5150
			nRasterCount, eDT, NULL )) == NULL)
5151
	{
232 andreas 5152
	   KMessageBox::error(this, i18n("Error creating a temporary image file! (%1)").arg(*fName));
158 andreas 5153
	   GDALClose (hSrcDS);
5154
	   return false;
5155
	}
5156
 
5157
	outSet = (GDALDataset *)hDstDS;
5158
 
159 andreas 5159
	for (int i = 0; i < nRasterCount; i++)
5160
	{
5161
	   poBand = outSet->GetRasterBand (i+1);
5162
	   poBand->Fill (0.0);
5163
	}
5164
 
158 andreas 5165
	if (outSet->SetProjection (pszDstWKT) != CE_None)
5166
	{
5167
	   KMessageBox::error(this, i18n("Error setting projection on destination!"));
5168
	   GDALClose (hDstDS);
5169
	   GDALClose (hSrcDS);
232 andreas 5170
	   unlink (fName->toAscii().data());
158 andreas 5171
	   return false;
5172
	}
5173
 
5174
	if (outSet->SetGeoTransform (&adfDstGeoTransform[0]) != CE_None)
5175
	{
159 andreas 5176
	   KMessageBox::error(this, i18n("Error setting geo transform data to destination!"));
158 andreas 5177
	   GDALClose (hDstDS);
5178
	   GDALClose (hSrcDS);
232 andreas 5179
	   unlink (fName->toAscii().data());
158 andreas 5180
	   return false;
5181
	}
159 andreas 5182
 
158 andreas 5183
	// Copy the color table, if required.
5184
	GDALColorTableH hCT;
5185
 
5186
	for (int i = 0; i < nRasterCount; i++)
5187
	{
5188
	   hCT = GDALGetRasterColorTable (inSet->GetRasterBand (i+1));
5189
 
5190
	   if (hCT != NULL)
5191
              GDALSetRasterColorTable (outSet->GetRasterBand (i+1), hCT);
5192
	}
5193
 
5194
	// Setup warp options.
5195
	GDALWarpOptions *psWarpOptions = GDALCreateWarpOptions();
5196
 
5197
	psWarpOptions->hSrcDS = hSrcDS;
5198
	psWarpOptions->hDstDS = hDstDS;
5199
 
5200
	psWarpOptions->nBandCount = nRasterCount;
5201
	psWarpOptions->panSrcBands =
5202
        	(int *) CPLMalloc(sizeof(int) * psWarpOptions->nBandCount );
5203
	psWarpOptions->panDstBands =
5204
		(int *) CPLMalloc(sizeof(int) * psWarpOptions->nBandCount );
5205
 
5206
	for (int i = 0; i < nRasterCount; i++)
5207
	{
5208
	   psWarpOptions->panSrcBands[i] = i+1;
5209
	   psWarpOptions->panDstBands[i] = i+1;
5210
	}
5211
 
159 andreas 5212
//	psWarpOptions->pfnProgress = GDALTermProgress;
158 andreas 5213
 
5214
	// Establish reprojection transformer.
5215
	psWarpOptions->pTransformerArg =
5216
        	GDALCreateGenImgProjTransformer(hSrcDS,
5217
					 GDALGetProjectionRef(hSrcDS), 
5218
					 hDstDS,
5219
					 GDALGetProjectionRef(hDstDS),
159 andreas 5220
					 FALSE, 0.0, 1);
158 andreas 5221
 
5222
	psWarpOptions->pfnTransformer = GDALGenImgProjTransform;
5223
 
5224
	// Initialize and execute the warp operation.
5225
	GDALWarpOperation oOperation;
5226
 
5227
	if (oOperation.Initialize (psWarpOptions) != CE_None)
5228
	{
5229
	   KMessageBox::error(this, i18n("Error initializing warp operation!"));
5230
	   GDALClose (hDstDS);
5231
	   GDALClose (hSrcDS);
232 andreas 5232
	   unlink (fName->toAscii().data());
158 andreas 5233
	   return false;
5234
	}
5235
 
159 andreas 5236
	oOperation.ChunkAndWarpMulti (0, 0, geoRect.width, geoRect.height);
158 andreas 5237
	GDALDestroyGenImgProjTransformer (psWarpOptions->pTransformerArg);
5238
	GDALDestroyWarpOptions(psWarpOptions);
5239
 
5240
	GDALClose (hDstDS);
5241
	GDALClose (hSrcDS);
232 andreas 5242
	unlink (nfn.toAscii().data());
158 andreas 5243
	return true;
5244
}
5245
 
151 andreas 5246
#endif
5247
 
88 andreas 5248
#include "sportwatcherwidget.moc"
5249