Subversion Repositories public

Rev

Go to most recent revision | Details | 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"
151 andreas 27
#include <string.h>
96 andreas 28
 
137 andreas 29
#include <iostream>
88 andreas 30
#include <kfiledialog.h>
31
#include <kmessagebox.h>
32
#include <ksimpleconfig.h>
33
#include <klocale.h>
34
#include <klistview.h>
100 andreas 35
#include <kaboutdialog.h>
36
#include <kaboutdata.h>
218 andreas 37
#include <kinputdialog.h>
128 andreas 38
#include <kglobalsettings.h>
218 andreas 39
#include <kcombobox.h>
154 andreas 40
#include <qapplication.h>
88 andreas 41
#include <qstring.h>
42
#include <qdatetime.h>
109 andreas 43
#include <qtoolbutton.h>
132 andreas 44
#include <qcursor.h>
151 andreas 45
#include <qcstring.h>
172 andreas 46
#include <qregexp.h>
151 andreas 47
 
157 andreas 48
#if defined HAVE_GDAL && HAVE_LIBGDAL1_5_0
158 andreas 49
   #include <gdal/ogr_spatialref.h>
50
   #include <gdal/ogrsf_frmts.h>
51
   #include <gdal/gdalwarper.h>
165 andreas 52
   #include <gdal/ogrsf_frmts.h>
157 andreas 53
#endif
54
 
218 andreas 55
#include "garmin.h"
137 andreas 56
#include "copy.h"
158 andreas 57
#include "transform.h"
217 andreas 58
#include "import.h"
88 andreas 59
 
216 andreas 60
// #define DEBUG	1
151 andreas 61
 
137 andreas 62
using std::cout;
158 andreas 63
using std::cerr;
64
using std::clog;
137 andreas 65
using std::endl;
66
 
67
 
104 andreas 68
typedef struct
69
{
70
	double lon;
71
	double lat;
72
} posn_type;
73
 
88 andreas 74
sportwatcherWidget::sportwatcherWidget(QWidget* parent, const char* name, WFlags fl)
75
: sportwatcherWidgetBase(parent,name,fl)
76
{
157 andreas 77
#if defined HAVE_GDAL && HAVE_LIBGDAL1_5_0
78
	mFactor = 10;		// Factor to calculate square pixels
79
#endif
88 andreas 80
	mama = parent;
81
	gmn = 0;
82
	min_hr = max_hr = avg_hr = 0;
83
	min_height = max_height = 0.0;
84
	max_time = 0;
85
	index = 0;
104 andreas 86
	zfactor = 0;
132 andreas 87
	mapLap = 0;
88
	mapPan = QRect(0, 0, 0, 0);
89
	stateHand = stateFlag = stateGlas = false;
90
	oldTransX = oldTransY = 0.0;
91
	lmbPressed = 0;
92
 
88 andreas 93
	// Load the config parameters
94
	KSimpleConfig *cfg = new KSimpleConfig(QString("sportwatcher.rc"), true);
95
	cfg->setGroup(QString("SportWatcher"));
143 andreas 96
	lower1 = cfg->readNumEntry("lower1", 0);
97
	lower2 = cfg->readNumEntry("lower2", 0);
98
	lower3 = cfg->readNumEntry("lower3", 0);
99
	upper1 = cfg->readNumEntry("upper1", 0);
100
	upper2 = cfg->readNumEntry("upper2", 0);
101
	upper3 = cfg->readNumEntry("upper3", 0);
102
	MaxHr = cfg->readNumEntry("maxHr", 180);
103
	restHr = cfg->readNumEntry("restHr", 60);
104
	vo2max = cfg->readNumEntry("vo2max", 50);
105
	weight = cfg->readNumEntry("weight", 70);
106
	sampleTime = cfg->readNumEntry("seconds", 15);
149 andreas 107
	Serial = cfg->readBoolEntry("Serial", false);
169 andreas 108
	Contour = cfg->readBoolEntry("Contour", false);
88 andreas 109
	Device = cfg->readEntry("Device", "/dev/ttyUSB0");
143 andreas 110
	Data = cfg->readEntry("Data", QDir::home().absPath() + "/.sportwatcher");
111
	HRM = cfg->readEntry("HRM", QDir::home().absPath() + "/polar");
151 andreas 112
	MAP = cfg->readEntry("MAP", QDir::home().absPath() + "/.sportwatcher/track.wms");
149 andreas 113
	Units = cfg->readNumEntry("Units", 0);
158 andreas 114
	MapType = cfg->readNumEntry("MapType", 7);
88 andreas 115
	delete cfg;
132 andreas 116
	// Set some widget settings
117
	btHand->setToggleButton(true);
118
	btGlas->setToggleButton(true);
88 andreas 119
	// Fill the activities
120
	getActivities();
155 andreas 121
#if defined HAVE_GDAL && HAVE_LIBGDAL1_5_0
151 andreas 122
	// Initialize the GDAL
123
	GDALAllRegister();
124
	poDataset = 0;
125
#endif
88 andreas 126
}
127
 
128
sportwatcherWidget::~sportwatcherWidget()
129
{
104 andreas 130
	destroy();
88 andreas 131
}
132
 
100 andreas 133
void sportwatcherWidget::destroy()
134
{
135
	if (gmn)
136
	   garmin_free_data (gmn);
137
 
138
	if (index)
139
	{
140
	INDEX *n, *akt = index;
141
 
142
	   while (akt)
143
	   {
144
	      n = akt;
145
	      akt = akt->next;
146
	      delete n;
147
	   }
148
	}
149
 
150
	index = 0;
151
	gmn = 0;
132 andreas 152
	oldTransX = oldTransY = 0.0;
100 andreas 153
}
154
 
132 andreas 155
bool sportwatcherWidget::findIndex(const QString &key)
156
{
157
INDEX *akt = index;
158
 
159
	while (akt)
160
	{
161
	   if (akt->path == key || akt->activ == key)
162
	      return true;
163
 
164
	   akt = akt->next;
165
	}
166
 
167
	return false;
168
}
169
 
88 andreas 170
/*
171
 * Search for a directory named .sportwatcher in the home directory of
172
 * the user and search for *.gmn files. Open the files and read the header
173
 * to find the basic data of activities. Then add the information into
174
 * the activities KListView.
175
 */
176
void sportwatcherWidget::getActivities()
177
{
178
QString path, txt;
132 andreas 179
QDir mdir, dir = QDir::homeDirPath();
88 andreas 180
QFileInfo *entries;
181
QStringList years, months;
128 andreas 182
KListViewItem *running, *biking, *other;
183
KListViewItem *el;
88 andreas 184
int anz;
185
RUN_NODE *rn;
186
LAP *lap;
187
 
188
	if (Data.isEmpty())
189
	{
128 andreas 190
	   path = dir.homeDirPath();
88 andreas 191
	   path.append("/.sportwatcher");
192
	}
193
	else
194
	   path = Data;
195
 
196
	dir.setPath(path);
132 andreas 197
	dir.refresh();
88 andreas 198
 
199
	if (!dir.exists())
200
	{
201
	   dir.mkdir(path);
202
	   return;
203
	}
204
 
132 andreas 205
	destroy();
100 andreas 206
	liActivities->clear();
88 andreas 207
	liActivities->setRootIsDecorated(true);
208
	liActivities->setSortColumn(-1);
218 andreas 209
	liActivities->addColumn(QString("Path"), 0);
210
	liActivities->hideColumn(1);
128 andreas 211
	other = new KListViewItem(liActivities, i18n("Others"));
212
	biking = new KListViewItem(liActivities, i18n("Biking"));
213
	running = new KListViewItem(liActivities, i18n("Running"));
214
 
215
	other->setPixmap(0, QPixmap::fromMimeSource(QString("history.png")));
216
	biking->setPixmap(0, QPixmap::fromMimeSource(QString("history.png")));
217
	running->setPixmap(0, QPixmap::fromMimeSource(QString("history.png")));
218
 
88 andreas 219
	liActivities->insertItem(other);
220
	liActivities->insertItem(biking);
221
	liActivities->insertItem(running);
222
 
223
	dir.cd(path);
224
	dir.setFilter(QDir::Dirs | QDir::NoSymLinks);
225
	dir.setSorting(QDir::Name);
132 andreas 226
	dir.refresh();
128 andreas 227
	QFileInfoList *list = (QFileInfoList *)dir.entryInfoList();
88 andreas 228
 
229
	if (!list)
230
	   return;
231
 
232
	QFileInfoListIterator it(*list);
233
 
234
	while ((entries = it.current()) != 0)		// Years
235
	{
236
	   if (entries->fileName() == QString(".") || entries->fileName() == QString(".."))
237
	   {
238
	      ++it;
239
	      continue;
240
	   }
241
 
242
	   years += entries->absFilePath();
243
	   ++it;
244
	}
245
 
246
	for (QStringList::Iterator strit = years.begin(); strit != years.end(); ++strit)
247
	{
248
	   if (months.count() > 0)
249
	      months.clear();
250
 
251
	   dir.setPath(*strit);
132 andreas 252
	   dir.refresh();
128 andreas 253
	   list = (QFileInfoList *)dir.entryInfoList();
88 andreas 254
 
255
	   if (!list)
256
	      continue;
257
 
258
	   it = QFileInfoListIterator (*list);
259
 
260
	   while ((entries = it.current()) != 0)	// Months
261
	   {
262
	      if (entries->fileName() == QString(".") || entries->fileName() == QString(".."))
263
	      {
264
		 ++it;
265
		 continue;
266
	      }
267
 
268
	      months += entries->absFilePath();
269
	      ++it;
270
	   }
271
 
272
	   for (QStringList::Iterator strit1 = months.begin(); strit1 != months.end(); ++strit1)
273
	   {
274
	      mdir.setPath(*strit1);
275
	      mdir.cd(*strit1);
276
	      mdir.setFilter(QDir::Files | QDir::NoSymLinks);
277
	      mdir.setNameFilter(QString("*.gmn"));
132 andreas 278
	      mdir.refresh();
128 andreas 279
	      list = (QFileInfoList *)mdir.entryInfoList();
88 andreas 280
 
281
	      if (!list)
282
		 continue;
283
 
284
	      it = QFileInfoListIterator (*list);
285
	      anz = 0;
286
 
287
	      while ((entries = it.current()) != 0)		// Files
288
	      {
289
		 files += entries->absFilePath();
290
		 ++it;
291
	      }
292
	   }
293
	}
294
 
295
	INDEX *akt, *n;
296
	// Open every file and read its head
297
	for (QStringList::Iterator strfl = files.begin(); strfl != files.end(); ++strfl)
298
	{
132 andreas 299
	   if (findIndex(*strfl))	// avoid duplicate entries
300
	      continue;
301
 
88 andreas 302
	   spw.destroy();
303
 
304
	   if (spw.setFileName(*strfl) == -1)
305
	      return;
306
 
307
	   if (gmn)
308
	      garmin_free_data (gmn);
309
 
310
	   gmn = spw.readFile();
311
	   ds.destroy();
312
	   ds.garmin_print_data(gmn);
313
	   rn = ds.getRunNode();
314
 
315
	   lap = ds.getLap(rn->run->first_lap_index);
316
	   const QDateTime *qt = garmin_dtime (lap->start_time);
317
	   QString idx = qt->toString("dd.MM.yyyy hh:mm.ss");
318
 
217 andreas 319
	   if (strlen (rn->run->workout.name) > 1 && strlen (rn->run->workout.name) < 16 && isalpha (rn->run->workout.name[0]))
320
	      idx.setAscii (rn->run->workout.name);
321
 
88 andreas 322
	   if (!index)
323
	   {
324
	      index = new INDEX;
325
	      index->path = *strfl;
326
	      index->activ = idx;
327
	      index->next = 0;
328
	   }
329
	   else
330
	   {
331
	      n = new INDEX;
332
	      n->path = *strfl;
333
	      n->activ = idx;
334
	      n->next = 0;
335
	      akt = index;
336
 
337
	      while (akt->next)
338
		 akt = akt->next;
339
 
340
	      akt->next = n;
341
	   }
342
 
343
	   switch (rn->run->sport_type)
344
	   {
345
	      case D1000_running:
128 andreas 346
		 el = new KListViewItem(running, idx);
218 andreas 347
		 el->setText(1, *strfl);
128 andreas 348
		 el->setPixmap(0, QPixmap::fromMimeSource(QString("run.png")));
88 andreas 349
		 running->insertItem(el);
350
	      break;
351
 
352
	      case D1000_biking:
128 andreas 353
		 el = new KListViewItem(biking, idx);
218 andreas 354
		 el->setText(1, *strfl);
128 andreas 355
		 el->setPixmap(0, QPixmap::fromMimeSource(QString("bike.png")));
88 andreas 356
		 biking->insertItem(el);
357
	      break;
358
 
359
	      case D1000_other:
128 andreas 360
		 el = new KListViewItem(other, idx);
218 andreas 361
		 el->setText(1, *strfl);
128 andreas 362
		 el->setPixmap(0, QPixmap::fromMimeSource(QString("other.png")));
88 andreas 363
		 other->insertItem(el);
364
	      break;
365
 
366
	      default:
128 andreas 367
		 el = new KListViewItem(other, idx);
218 andreas 368
		 el->setText(1, *strfl);
128 andreas 369
		 el->setPixmap(0, QPixmap::fromMimeSource(QString("other.png")));
88 andreas 370
		 other->insertItem(el);
371
	   }
372
 
373
	   delete qt;
374
	}
375
 
376
	running->setOpen(true);
377
 
378
	if (gmn)
379
	   garmin_free_data (gmn);
380
 
381
	gmn = 0;
382
}
383
 
384
/*$SPECIALIZATION$*/
385
void sportwatcherWidget::btFullscreenSlot()
386
{
132 andreas 387
	oldTransX = oldTransY = 0.0;
388
	mapPan.setCoords(0, 0, 0, 0);
104 andreas 389
	showTrack(0);
88 andreas 390
}
391
 
392
void sportwatcherWidget::btGlasMinusSlot()
393
{
132 andreas 394
bool sh = stateHand;
395
 
396
	stateHand = false;
104 andreas 397
	showTrack(zfactor - 1000);
132 andreas 398
	stateHand = sh;
88 andreas 399
}
400
 
401
void sportwatcherWidget::btGlasPlusSlot()
402
{
132 andreas 403
bool sh = stateHand;
404
 
405
	stateHand = false;
104 andreas 406
	showTrack(zfactor + 1000);
132 andreas 407
	stateHand = sh;
88 andreas 408
}
409
 
410
void sportwatcherWidget::btHandSlot()
411
{
132 andreas 412
QCursor cs;
413
 
414
	if (stateGlas)
415
	{
416
	   stateGlas = false;
417
	   btGlas->toggle();
418
	}
419
 
420
	stateHand = (stateHand) ? false : true;
421
 
422
	if (stateHand)
423
	   cs.setShape(QCursor::PointingHandCursor);
424
	else
425
	   cs.setShape(QCursor::ArrowCursor);
426
 
427
	imgMap->setCursor(cs);
88 andreas 428
}
429
 
430
void sportwatcherWidget::btGlasSlot()
431
{
132 andreas 432
QCursor cs;
433
 
434
	if (stateHand)
435
	{
436
	   stateHand = false;
437
	   btHand->toggle();
438
	}
439
 
440
	stateGlas = (stateGlas) ? false : true;
441
 
442
	if (stateGlas)
443
	   cs.setShape(QCursor::ForbiddenCursor);
444
	else
445
	   cs.setShape(QCursor::ArrowCursor);
446
 
447
	imgMap->setCursor(cs);
88 andreas 448
}
449
 
450
void sportwatcherWidget::btFlagSlot()
451
{
452
}
453
 
132 andreas 454
void sportwatcherWidget::liLapsSlot(QListViewItem *item)
88 andreas 455
{
132 andreas 456
QString sl;
457
int l;
458
int idx;
459
RUN_NODE *rn;
460
LAP *lap;
461
 
462
	if (!item)
463
	   return;
464
 
465
	sl = item->text(0).mid(4, 3);
466
	l = sl.toInt();
467
 
468
	if (l <= 0)
469
	{
470
	   showTrack(zfactor, mapPan, 0);
148 andreas 471
	   showCurves(0);
132 andreas 472
	   return;
473
	}
474
 
475
	rn = ds.getRunNode();
476
	idx = rn->run->first_lap_index;
477
	lap = ds.getLap(idx + l - 1);
478
	showTrack(zfactor, mapPan, lap);
148 andreas 479
	showCurves(lap);
88 andreas 480
}
481
 
482
void sportwatcherWidget::liActivitiesSlot(QListViewItem *item)
483
{
484
INDEX *akt;
485
 
486
	if (!item)
487
	   return;
488
 
218 andreas 489
//	akt = index;
88 andreas 490
 
218 andreas 491
//	while (akt)
492
//	{
493
//	   if (akt->activ == item->text(0))
494
//	   {
88 andreas 495
	      spw.destroy();
496
 
218 andreas 497
//	      if (spw.setFileName(akt->path.ascii()) == -1)
498
	      if (spw.setFileName(item->text(1).ascii()) == -1)
88 andreas 499
		 return;
500
 
501
	      if (gmn)
502
		 garmin_free_data (gmn);
503
 
504
	      gmn = spw.readFile();
104 andreas 505
	      zfactor = 0;
88 andreas 506
	      showLaps();
100 andreas 507
	      showTrack();
88 andreas 508
	      showCurves();
218 andreas 509
//	      return;
510
//	   }
88 andreas 511
 
218 andreas 512
//	   akt = akt->next;
513
//	}
88 andreas 514
}
515
 
516
void sportwatcherWidget::helpAbout()
517
{
119 andreas 518
KAboutData about("SportWatcher", "SportWatcher", VERSION);
100 andreas 519
QString ab = ("About");
520
QString liz = ("License");
521
 
522
	KAboutDialog *info = new KAboutDialog(KAboutDialog::AbtProduct|KAboutDialog::AbtTabbed,
137 andreas 523
		QString("SportWatcher"), KAboutDialog::Close, KAboutDialog::Close, 0,
100 andreas 524
		i18n("About"), false, false, QString::null, QString::null, QString::null);
213 andreas 525
	info->setProduct("SportWatcher", QString("Version %1").arg(VERSION), "Andreas Theofilu", "2007 - 2009");
100 andreas 526
	KAboutContainer *infoAppl = info->addContainerPage(ab, AlignCenter, AlignCenter);
119 andreas 527
	infoAppl->addTitle(QString("SportWatcher"), AlignCenter, false, false);
137 andreas 528
//	infoAppl->addTitle(QString("(C) 2007, 2008, Andreas Theofilu <andreas@theosys.at>"));
529
	infoAppl->addPerson(QString("Andreas Theofilu"), QString("andreas@theosys.at"), QString("http://www.theosys.at"), NULL);
221 andreas 530
	infoAppl->addTitle(i18n("About this Program", "\nRead out the data of a Garmin GPS device over USB, and visualize them on screen"));
137 andreas 531
	about.setLicense(KAboutData::License_Custom);
532
	about.setLicenseText(I18N_NOOP(gpl3));
100 andreas 533
	info->addLicensePage(liz, about.license(), 10);
137 andreas 534
	info->setGeometry(0, 0, 800, 400);
100 andreas 535
	info->centerOnScreen(info, 0);
536
	info->exec();
537
	delete info;
88 andreas 538
}
539
 
540
void sportwatcherWidget::helpContents()
541
{
542
}
543
 
544
void sportwatcherWidget::helpIndex()
545
{
546
}
547
 
548
void sportwatcherWidget::fileExit()
549
{
550
	if (mama)
551
	   mama->close();
552
}
553
 
554
void sportwatcherWidget::filePrint()
555
{
556
}
557
 
104 andreas 558
/*
559
 * This function allows the user to choose a file name, where we save the
560
 * actual lap in Garmins own TCX format. This format is simply a XML-file.
561
 * For details about the schema of this file look at
562
 * http://developer.garmin.com/schemas/tcx/v2/
563
 */
88 andreas 564
void sportwatcherWidget::fileSaveAs()
565
{
104 andreas 566
QString fname;
567
QFile fn;
568
QString buffer;
569
RUN_NODE *rn, *rakt;
570
LAP *lap;
571
POINT *point;
572
int indent, i;
573
QDateTime *qt;
172 andreas 574
QRegExp rx("(.tcx|.gpx|.osm)$");
104 andreas 575
 
576
	if (!gmn)
577
	{
578
	   KMessageBox::error(this, i18n("Currently no activity is selected!"));
579
	   return;
580
	}
581
 
172 andreas 582
	fname = KFileDialog::getSaveFileName(0, QString("*.tcx|Garmin Training Center (*.tcx)\n*.gpx|GPS Excange Format (*.gpx)\n*.osm|OpenStreetMap (*.osm)"), this, QString("SportWatcher"));
104 andreas 583
 
584
	if (fname.isEmpty())
585
	   return;
586
 
172 andreas 587
	if (rx.search(fname) < 0)
588
	{
589
	   KMessageBox::error(this, i18n("The file " + fname + " has no valid file extension!"));
590
	   return;
591
	}
592
 
104 andreas 593
	fn.setName(fname);
594
 
595
	if (fn.exists())
596
	{
597
	   if (KMessageBox::questionYesNo(this, i18n("Do you really want to overwrite this file?")) == KMessageBox::No)
598
	      return;
599
	}
600
 
172 andreas 601
	rx.setPattern(".gpx$");
602
 
603
	if (rx.search(fname) >= 0)	// Should we create a *.gpx file?
604
	{
605
	   sportwatcherWidget::saveGPX(fname);
606
	   return;
607
	}
608
 
609
	rx.setPattern(".osm$");
610
 
611
	if (rx.search(fname) >= 0)	// Should we create a *.osm file?
612
	{
613
	   sportwatcherWidget::saveOSM(fname);
614
	   return;
615
	}
616
 
617
	// No, we create a *.tcx file!
171 andreas 618
	indent = 0;
104 andreas 619
	rn = ds.getRunNode();
620
	lap = ds.getLap(rn->run->first_lap_index);
621
 
622
	if ((point = ds.getPoint(lap->start_time)) == 0)
623
	{
624
	   KMessageBox::error(this, i18n("No data to save!"));
625
	   return;
626
	}
627
 
628
	if (!fn.open(IO_ReadWrite | IO_Truncate))
629
	{
172 andreas 630
	   KMessageBox::error(this, i18n("Error creating file " + fname + "!\nPlease check permissions"));
104 andreas 631
	   return;
632
	}
633
 
634
	buffer = QString("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>\n");
635
	buffer.append("<TrainingCenterDatabase xmlns=\"http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2\" ");
636
	buffer.append("xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ");
637
	buffer.append("xsi:schemaLocation=\"http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2 ");
638
	buffer.append("http://www.garmin.com/xmlschemas/TrainingCenterDatabasev2.xsd\">\n\n");
639
	writeTag (fn, buffer, indent);
640
	buffer = QString("<folders/>\n\n");
641
	writeTag (fn, buffer, indent);
642
 
643
	// Open a course
644
	QFileInfo finfo(fname);
645
	buffer = QString("<Courses>\n   <Course>\n      <name>%1</name>\n").arg(finfo.baseName(true));
646
	writeTag (fn, buffer, indent);
647
	indent = 2;
648
 
649
	rakt = rn;
650
 
651
	while (rakt)
652
	{
653
	   if (rakt->run->type != data_D1000 && rakt->run->type != data_D1009 &&
654
	   	rakt->run->type != data_D1010)
655
	   {
656
	      rakt = rakt->next;
657
	      continue;
658
	   }
659
 
660
	   for (i = rakt->run->first_lap_index; (unsigned int)i <= rakt->run->last_lap_index; i++)
661
	   {
662
	      if ((lap = ds.getLap(i)) == NULL)
663
		 continue;
664
 
665
	      // Write the information of the lap
666
	      writeTag (fn, QString("<Lap>\n"), indent);
667
	      indent++;
668
	      buffer.sprintf("<TotalTimeSeconds>%f</TotalTimeSeconds>\n", (double)lap->total_time / 100.0);
669
	      writeTag (fn, buffer, indent);
172 andreas 670
	      qt = garmin_dtime(lap->start_time);
671
	      buffer = QString("<StartTime>%1</StartTime>\n").arg(qt->toString("yyyy-MM-ddThh:mm:ssZ"));
672
	      writeTag (fn, buffer, indent);
104 andreas 673
	      buffer.sprintf("<DistanceMeters>%f</DistanceMeters>\n", lap->total_distance);
674
	      writeTag (fn, buffer, indent);
675
 
676
	      writeTag (fn, QString("<BeginPosition>\n"), indent);
677
	      indent++;
678
	      buffer.sprintf("<LatitudeDegrees>%f</LatitudeDegrees>\n", SEMI2DEG(lap->begin.lat));
679
	      writeTag (fn, buffer, indent);
680
	      buffer.sprintf("<LongitudeDegrees>%f</LongitudeDegrees>\n", SEMI2DEG(lap->begin.lon));
681
	      writeTag (fn, buffer, indent);
682
	      indent--;
683
	      writeTag (fn, QString("</BeginPosition>\n"), indent);
684
 
685
	      writeTag (fn, QString("<EndPosition>\n"), indent);
686
	      indent++;
687
	      buffer.sprintf("<LatitudeDegrees>%f</LatitudeDegrees>\n", SEMI2DEG(lap->end.lat));
688
	      writeTag (fn, buffer, indent);
689
	      buffer.sprintf("<LongitudeDegrees>%f</LongitudeDegrees>\n", SEMI2DEG(lap->end.lon));
690
	      writeTag (fn, buffer, indent);
691
	      indent--;
692
	      writeTag (fn, QString("</EndPosition>\n"), indent);
693
 
694
	      writeTag (fn, QString("<AverageHeartRateBpm xsi:type=\"HeartRateInBeatsPerMinute_t\">\n"), indent);
695
	      indent++;
696
	      buffer.sprintf("<Value>%d</Value>\n", lap->avg_heart_rate);
697
	      writeTag (fn, buffer, indent);
698
	      indent--;
699
	      writeTag (fn, QString("</AverageHeartRateBpm>\n"), indent);
700
 
701
	      writeTag (fn, QString("<MaximumHeartRateBpm xsi:type=\"HeartRateInBeatsPerMinute_t\">\n"), indent);
702
	      indent++;
172 andreas 703
	      buffer.sprintf("<Value>%d</Value>\n", lap->max_heart_rate);
104 andreas 704
	      writeTag (fn, buffer, indent);
705
	      indent--;
706
	      writeTag (fn, QString("</MaximumHeartRateBpm>\n"), indent);
707
 
172 andreas 708
	      if (lap->avg_cadence < 255)
709
	      {
710
		 buffer.sprintf("<AverageCadence>%d</AverageCadence>\n", lap->avg_cadence);
711
		 writeTag (fn, buffer, indent);
215 andreas 712
		 buffer.sprintf("<Cadence>%d</Cadence>\n", lap->avg_cadence);
713
		 writeTag (fn, buffer, indent);
172 andreas 714
	      }
715
 
215 andreas 716
	      buffer = QString("<Intensity>%1</Intensity>\n").arg((!lap->intensity) ? "Active" : "Resting");
104 andreas 717
	      writeTag (fn, buffer, indent);
217 andreas 718
 
719
	      buffer.sprintf("<Calories>%d</Calories>\n", lap->calories);
720
	      writeTag (fn, buffer, indent);
721
 
722
	      buffer.sprintf("<MaximumSpeed>%f</MaximumSpeed>\n", lap->max_speed);
723
	      writeTag (fn, buffer, indent);
104 andreas 724
	      indent--;
725
	      writeTag (fn, QString("</Lap>\n"), indent);
726
 
727
	      point = ds.getPoint(lap->start_time);
728
	      writeTag (fn, QString("<Track>\n"), indent);
729
	      indent++;
730
 
731
	      while (point)
732
	      {
733
		 if (point->time > (lap->start_time + (lap->total_time / 100)))
734
		    break;
735
 
736
		 writeTag (fn, QString("<Trackpoint>\n"), indent);
737
		 indent++;
738
		 qt = garmin_dtime(point->time);
739
		 buffer = QString("<Time>%1</Time>\n").arg(qt->toString("yyyy-MM-ddThh:mm:ssZ"));
740
		 writeTag (fn, buffer, indent);
741
		 delete qt;
742
		 writeTag (fn, QString("<Position>\n"), indent);
743
		 indent++;
744
		 buffer.sprintf("<LatitudeDegrees>%f</LatitudeDegrees>\n", SEMI2DEG(point->posn.lat));
745
		 writeTag (fn, buffer, indent);
746
		 buffer.sprintf("<LongitudeDegrees>%f</LongitudeDegrees>\n", SEMI2DEG(point->posn.lon));
747
		 writeTag (fn, buffer, indent);
748
		 indent--;
749
		 writeTag (fn, QString("</Position>\n"), indent);
750
 
751
		 if (point->alt < 20000.0)
752
		 {
753
		    buffer.sprintf("<AltitudeMeters>%f</AltitudeMeters>\n", point->alt);
754
		    writeTag (fn, buffer, indent);
755
		 }
756
 
757
		 buffer.sprintf("<DistanceMeters>%f</DistanceMeters>\n", point->distance);
758
		 writeTag (fn, buffer, indent);
759
 
760
		 if (point->heart_rate > 0 && point->heart_rate < 250)
761
		 {
762
		    writeTag (fn, QString("<HeartRateBpm xsi:type=\"HeartRateInBeatsPerMinute_t\">\n"), indent);
763
		    indent++;
764
		    buffer.sprintf("<Value>%d</Value>\n", point->heart_rate);
765
		    writeTag (fn, buffer, indent);
766
		    indent--;
767
		    writeTag (fn, QString("</HeartRateBpm>\n"), indent);
768
		 }
769
 
215 andreas 770
		 if (point->cadence >= 0 && point->cadence < 250)
771
		 {
772
		    buffer.sprintf("<Cadence>%d</Cadence>\n", point->cadence);
773
		    writeTag (fn, buffer, indent);
774
		 }
775
 
776
		 buffer.sprintf("<SensorState>%s</SensorState>\n", (!point->sensor) ? "Absent" : "Present");
104 andreas 777
		 writeTag (fn, buffer, indent);
778
		 indent--;
779
		 writeTag (fn, QString("</Trackpoint>\n"), indent);
780
		 point = ds.getPoint(point->time + 1);
781
	      }
782
 
783
	      indent--;
784
	      writeTag (fn, QString("</Track>\n"), indent);
785
	   }
786
 
787
	   indent--;
788
	   writeTag (fn, QString("</Course>\n"), indent);
789
	   indent--;
790
	   writeTag (fn, QString("</Courses>\n"), indent);
791
	   rakt = rakt->next;
792
	}
793
 
794
	// Write information about device
795
	// Here my personal signature is written :-)
796
	writeTag (fn, QString("<Author xsi:type=\"Application_t\">\n"), indent);
797
	indent++;
798
	writeTag (fn, QString("<Name>SportWatcher</Name>\n"), indent);
799
	writeTag (fn, QString("<Build>\n"), indent);
800
	indent++;
801
	writeTag (fn, QString("<Version>\n"), indent);
802
	indent++;
803
	writeTag (fn, QString("<VersionMajor>0</VersionMajor>\n"), indent);
804
	writeTag (fn, QString("<VersionMinor>1</VersionMinor>\n"), indent);
805
	writeTag (fn, QString("<BuildMajor>0</BuildMajor>\n"), indent);
806
	writeTag (fn, QString("<BuildMinor>0</BuildMinor>\n"), indent);
807
	indent--;
808
	writeTag (fn, QString("</Version>\n"), indent);
809
	writeTag (fn, QString("<Type>Beta</Type>\n"), indent);
810
	writeTag (fn, QString("<Time>Jan 31 2008, 00:00:00</Time>\n"), indent);
811
	writeTag (fn, QString("<Builder>theosys</Builder>\n"), indent);
812
	indent--;
813
	writeTag (fn, QString("</Build>\n"), indent);
814
	writeTag (fn, QString("<LangID>EN</LangID>\n"), indent);
815
	writeTag (fn, QString("<PartNumber>000-00000-00</PartNumber>\n"), indent);
816
	indent--;
817
	writeTag (fn, QString("</Author>\n"), indent);
818
	writeTag (fn, QString("</TrainingCenterDatabase>\n"), indent);
819
 
820
	fn.close();
821
	KMessageBox::information(this, i18n("File ") + fname + i18n(" was written successfully."));
88 andreas 822
}
823
 
824
void sportwatcherWidget::fileSave()
825
{
172 andreas 826
	KMessageBox::information(this, i18n("This function is currently not implemented!"));
88 andreas 827
}
828
 
172 andreas 829
void sportwatcherWidget::saveGPX(const QString &fn)
830
{
831
QFile qf;
832
QString buffer;
833
RUN_NODE *rn, *rakt;
834
LAP *lap;
835
POINT *point;
836
int indent;
837
unsigned int i;
838
QDateTime *qt;
839
double minLat, minLon, maxLat, maxLon;
840
 
841
	indent = 0;
842
	rn = ds.getRunNode();
843
	lap = ds.getLap(rn->run->first_lap_index);
844
 
845
	if ((point = ds.getPoint(lap->start_time)) == 0)
846
	{
847
	   KMessageBox::error(this, i18n("No data to save!"));
848
	   return;
849
	}
850
 
851
	qf.setName(fn);
852
 
853
	if (!qf.open(IO_ReadWrite | IO_Truncate))
854
	{
855
	   KMessageBox::error(this, i18n("Error creating file " + fn + "!\nPlease check permissions"));
856
	   return;
857
	}
858
 
859
	buffer = QString("<?xml version='1.0' encoding='UTF-8'?>\n");
860
	buffer.append("<gpx version=\"1.1\" creator=\"TheoSys SportWatcher\" xmlns=\"http://www.topografix.com/GPX/1/1\">\n");
861
	buffer.append("   <metadata>\n");
862
	indent = 0;
863
	writeTag (qf, buffer, indent);
864
 
865
	// Find the edges of our coordinates
866
	// We need this information in the header (metadata)
867
	rakt = rn;
868
	minLat = -90.0;
869
	minLon = -180.0;
870
	maxLat = 90.0;
871
	maxLon = 180.0;
872
 
873
	while (rakt)
874
	{
875
	   if (rakt->run->type != data_D1000 && rakt->run->type != data_D1009 &&
876
	   	rakt->run->type != data_D1010)
877
	   {
878
	      rakt = rakt->next;
879
	      continue;
880
	   }
881
 
882
	   i = rakt->run->first_lap_index;
883
	   // get the first lap
884
	   if ((lap = ds.getLap(i)) == NULL)
885
	      continue;
886
 
887
	   i = 0;
888
	   // iterate the points associated with the laps
889
	   while ((point = ds.getPoint(i)) != 0)
890
	   {
891
	      if (point->posn.lat == 0x7fffffff || point->posn.lon == 0x7fffffff)
892
	      {
893
		 i = point->time + 1;
894
		 continue;
895
	      }
896
 
897
	      if (SEMI2DEG(point->posn.lat) > minLat)
898
		 minLat = SEMI2DEG(point->posn.lat);
899
 
900
	      if (SEMI2DEG(point->posn.lat) < maxLat)
901
		 maxLat = SEMI2DEG(point->posn.lat);
902
 
903
	      if (SEMI2DEG(point->posn.lon) > minLon)
904
		 minLon = SEMI2DEG(point->posn.lon);
905
 
906
	      if (SEMI2DEG(point->posn.lon) < maxLon)
907
		 maxLon = SEMI2DEG(point->posn.lon);
908
 
909
	      i = point->time + 1;
910
	   }
911
 
912
	   rakt = rakt->next;
913
	}
914
 
915
	buffer.sprintf("      <bounds minlat=\"%f\" minlon=\"%f\" maxlat=\"%f\" maxlon=\"%f\" />\n",
916
		maxLat, minLon, minLat, maxLon);
917
	buffer.append("   </metadata>\n");
918
	buffer.append("   <trk>\n");
919
	buffer.append("      <trkseg>\n");
920
	writeTag (qf, buffer, indent);
921
	indent = 3;
922
	rn = ds.getRunNode();
923
	lap = ds.getLap(rn->run->first_lap_index);
924
	i = 0;
925
 
926
	while ((point = ds.getPoint(i)) != 0)
927
	{
928
	   if (point->posn.lat == 0x7fffffff || point->posn.lon == 0x7fffffff)
929
	   {
930
	      i = point->time + 1;
931
	      continue;
932
	   }
933
 
934
	   buffer.sprintf("<trkpt lat=\"%f\" lon=\"%f\">\n",
935
		SEMI2DEG(point->posn.lat), SEMI2DEG(point->posn.lon));
936
	   writeTag(qf, buffer, indent);
937
	   indent++;
938
	   buffer.sprintf("<ele>%f</ele>\n", point->alt);
939
	   writeTag(qf, buffer, indent);
940
	   qt = garmin_dtime(point->time);
941
	   buffer = QString("<Time>%1</Time>\n").arg(qt->toString("yyyy-MM-ddThh:mm:ssZ"));
942
	   writeTag(qf, buffer, indent);
943
	   indent--;
944
	   writeTag(qf, QString("</trkpt>\n"), indent);
945
	   i = point->time + 1;
946
	}
947
 
948
	indent = 0;
949
	buffer = QString("      </trkseg>\n");
950
	buffer.append("   </trk>\n");
951
	buffer.append("</gpx>\n");
952
	writeTag(qf, buffer, indent);
953
	qf.close();
954
	KMessageBox::information(this, i18n("File ") + fn + i18n(" was written successfully."));
955
}
956
 
957
void sportwatcherWidget::saveOSM(const QString &fn)
958
{
959
QFile qf;
960
QString buffer;
961
RUN_NODE *rn, *rakt;
962
LAP *lap;
963
POINT *point;
964
int indent, id, j;
965
unsigned int i;
966
double minLat, minLon, maxLat, maxLon;
967
QDateTime *qt;
968
 
969
	indent = 0;
970
	rn = ds.getRunNode();
971
	lap = ds.getLap(rn->run->first_lap_index);
972
 
973
	if ((point = ds.getPoint(lap->start_time)) == 0)
974
	{
975
	   KMessageBox::error(this, i18n("No data to save!"));
976
	   return;
977
	}
978
 
979
	qf.setName(fn);
980
 
981
	if (!qf.open(IO_ReadWrite | IO_Truncate))
982
	{
983
	   KMessageBox::error(this, i18n("Error creating file " + fn + "!\nPlease check permissions"));
984
	   return;
985
	}
986
 
987
	buffer = QString("<?xml version='1.0' encoding='UTF-8'?>\n");
988
	buffer.append("<osm version=\"0.5\" generator=\"TheoSys SportWatcher\">\n");
989
	indent = 0;
990
	writeTag (qf, buffer, indent);
991
	// Find the edges of our coordinates
992
	// We need this information in the header (metadata)
993
	rakt = rn;
994
	minLat = -90.0;
995
	minLon = -180.0;
996
	maxLat = 90.0;
997
	maxLon = 180.0;
998
 
999
	while (rakt)
1000
	{
1001
	   if (rakt->run->type != data_D1000 && rakt->run->type != data_D1009 &&
1002
	   	rakt->run->type != data_D1010)
1003
	   {
1004
	      rakt = rakt->next;
1005
	      continue;
1006
	   }
1007
 
1008
	   i = rakt->run->first_lap_index;
1009
	   // get the first lap
1010
	   if ((lap = ds.getLap(i)) == NULL)
1011
	      continue;
1012
 
1013
	   i = 0;
1014
	   // iterate the points associated with the laps
1015
	   while ((point = ds.getPoint(i)) != 0)
1016
	   {
1017
	      if (point->posn.lat == 0x7fffffff || point->posn.lon == 0x7fffffff)
1018
	      {
1019
		 i = point->time + 1;
1020
		 continue;
1021
	      }
1022
 
1023
	      if (SEMI2DEG(point->posn.lat) > minLat)
1024
		 minLat = SEMI2DEG(point->posn.lat);
1025
 
1026
	      if (SEMI2DEG(point->posn.lat) < maxLat)
1027
		 maxLat = SEMI2DEG(point->posn.lat);
1028
 
1029
	      if (SEMI2DEG(point->posn.lon) > minLon)
1030
		 minLon = SEMI2DEG(point->posn.lon);
1031
 
1032
	      if (SEMI2DEG(point->posn.lon) < maxLon)
1033
		 maxLon = SEMI2DEG(point->posn.lon);
1034
 
1035
	      i = point->time + 1;
1036
	   }
1037
 
1038
	   rakt = rakt->next;
1039
	}
1040
 
1041
	buffer.sprintf("   <bound box='%f,%f,%f,%f' origin='http://www.openstreetmap.org/api/0.5' />\n",
1042
		maxLat, minLon, minLat, maxLon);
1043
	writeTag (qf, buffer, indent);
1044
	indent = 1;
1045
	rn = ds.getRunNode();
1046
	lap = ds.getLap(rn->run->first_lap_index);
1047
	i = 0;
1048
	id = -1;
1049
 
1050
	while ((point = ds.getPoint(i)) != 0)
1051
	{
1052
	   if (point->posn.lat == 0x7fffffff || point->posn.lon == 0x7fffffff)
1053
	   {
1054
	      i = point->time + 1;
1055
	      continue;
1056
	   }
1057
 
1058
	   buffer.sprintf("<node id='%d' action='modify' visible='true' lat=\"%f\" lon=\"%f\">\n",
1059
		id, SEMI2DEG(point->posn.lat), SEMI2DEG(point->posn.lon));
1060
	   writeTag(qf, buffer, indent);
1061
	   indent++;
1062
	   buffer = QString("<tag k='created_by' v='TheoSys Sportwatcher' />\n");
1063
	   writeTag(qf, buffer, indent);
1064
	   buffer = QString("<tag k='highway' v='tertiary' />\n");
1065
	   writeTag(qf, buffer, indent);
1066
	   indent--;
1067
	   writeTag(qf, QString("</node>\n"), indent);
1068
	   id--;
1069
	   i = point->time + 1;
1070
	}
1071
 
1072
	qt = garmin_dtime(lap->start_time);
1073
	buffer.sprintf("<way id='%d' action='modify' visible='true' timestamp='%s'>\n",
1074
		id, QString(qt->toString("yyyy-MM-ddThh:mm:ssZ")).ascii());
1075
	writeTag(qf, buffer, indent);
1076
	indent++;
1077
 
1078
	for (j = -1; j > id; j--)
1079
	{
1080
	   buffer.sprintf("<nd ref='%d' />\n", j);
1081
	   writeTag(qf, buffer, indent);
1082
	}
1083
 
1084
	indent--;
1085
	writeTag(qf, QString("</way>\n"), indent);
1086
	indent = 0;
1087
	writeTag(qf, QString("</osm>\n"), indent);
1088
	qf.close();
1089
	KMessageBox::information(this, i18n("File ") + fn + i18n(" was written successfully."));
1090
}
1091
 
88 andreas 1092
void sportwatcherWidget::fileOpen()
1093
{
1094
QString fname = KFileDialog::getOpenFileName(Data, QString("*.gmn"), this, QString("SportWatcher"));
137 andreas 1095
int m;
88 andreas 1096
 
1097
        if (fname.isEmpty())
1098
           return;
1099
 
1100
	spw.destroy();
1101
 
1102
        if (spw.setFileName(fname.ascii()) == -1)
1103
	   return;
1104
 
1105
	if (gmn)
1106
	   garmin_free_data (gmn);
1107
 
1108
	gmn = spw.readFile();
104 andreas 1109
	zfactor = 0;
137 andreas 1110
 
1111
	if ((m = garmin_count_error()) > 0)
1112
	{
1113
	int i, key = -1;
1114
 
1115
	   for (i = 0; i < m; i++)
1116
	      KMessageBox::error(this, QString(garmin_get_next_error(&key)));
1117
 
1118
	   garmin_clear_errors();
1119
	   return;
1120
	}
1121
 
88 andreas 1122
	showLaps();
100 andreas 1123
	showTrack();
88 andreas 1124
	showCurves();
1125
}
1126
 
217 andreas 1127
void sportwatcherWidget::fileImport()
1128
{
1129
QString fname = KFileDialog::getOpenFileName(QString("~/"), QString("*.tcx"), this, QString("SportWatcher"));
1130
gmn_import import;
1131
int m;
1132
 
1133
        if (fname.isEmpty())
1134
           return;
1135
 
1136
        import.setFile(fname);
1137
 
1138
	if ((m = import.import()) != 0)
1139
	{
1140
	   KMessageBox::error(this, QString(import.getError(m)));
1141
	   return;
1142
	}
1143
 
1144
	if (gmn)
1145
	   garmin_free_data (gmn);
1146
 
1147
	gmn = import.getGarminData ();
1148
 
1149
	showLaps();
1150
	showTrack();
1151
	showCurves();
1152
}
1153
 
218 andreas 1154
/*
1155
 * Display a small dialog to rename the currently loaded session.
1156
 */
1157
void sportwatcherWidget::editRename()
1158
{
1159
bool ok;
1160
QString name, inhalt;
1161
QPtrList<QListViewItem> item;
1162
QListViewItem *lvItem;
1163
QFileInfo datei;
1164
RUN_NODE *rn;
1165
LAP *lap;
1166
garmin_list *list;
1167
D1009 *n;
1168
 
1169
	if (!gmn)
1170
	{
1171
	   KMessageBox::error(this, i18n("There is no session selected!"));
1172
	   return;
1173
	}
1174
 
1175
	rn = ds.getRunNode();
1176
	item = liActivities->selectedItems (false);
1177
	lvItem = item.first();
1178
 
1179
	if (!isdigit(rn->run->workout.name[0]))
1180
	   inhalt = lvItem->text(0);
1181
	else
1182
	   inhalt = QString::null;
1183
 
1184
	name = KInputDialog::getText(i18n("Rename session"), i18n("Session name"),
1185
		inhalt, &ok, this, "dialogRename", 0,
1186
		QString("Nxxxxxxxxxxxxxx"));
1187
 
1188
	if (!ok)
1189
	   return;
1190
 
1191
	if (name.length() <= 1)
1192
	{
1193
	   lap = ds.getLap(rn->run->first_lap_index);
1194
	   const QDateTime *qt = garmin_dtime (lap->start_time);
1195
	   QString idx = qt->toString("dd.MM.yyyy hh:mm.ss");
1196
	   lvItem->setText (0, idx);
1197
	   datei.setFile (lvItem->text(1));
1198
	   garmin_save_all (gmn, datei.fileName().ascii(), datei.dirPath(true).ascii(), 1);
1199
	   delete qt;
1200
	   return;
1201
	}
1202
 
1203
	strncpy (rn->run->workout.name, name.ascii(), 16);
1204
 
1205
	if (gmn->type != data_Dlist)
1206
	{
1207
	   KMessageBox::error(this, i18n("editRename: Unexpected structure type %1 found!").arg(gmn->type));
1208
	   return;
1209
	}
1210
 
1211
	list = (garmin_list *)gmn->data;
1212
 
1213
	if (list->head->data->type != data_D1009)	// This should be the run node
1214
	{
1215
	   KMessageBox::error(this, i18n("editRename: The run node was not found!"));
1216
	   return;
1217
	}
1218
 
1219
	n = (D1009 *)list->head->data->data;
1220
	strcpy (n->workout.name, rn->run->workout.name);
1221
	lvItem->setText (0, name);
1222
	datei.setFile (lvItem->text(1));
1223
	garmin_save_all (gmn, datei.fileName().ascii(), datei.dirPath(true).ascii(), 1);
1224
}
1225
 
88 andreas 1226
void sportwatcherWidget::fileNew()
1227
{
132 andreas 1228
progressWidget *dlg = new progressWidget(this, "progressWidgetBase");
96 andreas 1229
 
100 andreas 1230
	dlg->show();
137 andreas 1231
 
1232
	if (!dlg->Download())
1233
	{
1234
	int m, key;
1235
 
1236
	   key = -1;
1237
 
1238
	   for (m = 0; m < garmin_count_error(); m++)
1239
	      KMessageBox::error(this, QString(garmin_get_next_error(&key)));
1240
	}
1241
	else
1242
	   getActivities();
1243
 
1244
	garmin_clear_errors();
96 andreas 1245
	delete dlg;
88 andreas 1246
}
1247
 
1248
/*
1249
 * This function is called, when the user clicks at the menu point
1250
 * "Save Heart Rate".
1251
 * First, a file dialog box is displayed, where the user can choose a
1252
 * directory and a file name to save the heart rate.
1253
 * If the file could successfully be created, the heart rate is saved
137 andreas 1254
 * in the "HRM"-format. This is the native format Polar uses to store
88 andreas 1255
 * heart rate data. I've choosen this format, because it's popular and
1256
 * used by many other software too.
1257
 */
1258
void sportwatcherWidget::extrasSaveHR()
1259
{
1260
QString fname, str1, str2;
1261
QFile fdfile;
1262
QDateTime *qt, *oldqt;
1263
QDate dat;
1264
QTime t;
1265
QDir dir = QDir::home();
1266
char hv0[256];
1267
RUN_NODE *rn;
1268
LAP *lap, *alap;
1269
POINT *point;
1270
int samples, smp, seconds, anz, nsec, samsec;
1271
int avgHeart, minHeart, maxHeart, aktHeart;
1272
int secRange1, secRange2, secRange3, secAbove, secBeyond;
1273
 
1274
	if (!gmn)
1275
	{
1276
	   KMessageBox::information(this, i18n("There is no activity open"));
1277
	   return;
1278
	}
1279
 
1280
	if (HRM.isEmpty())
1281
	   str1 = dir.path();
1282
	else
1283
	   str1 = HRM;
1284
 
1285
	str1 +=  "/" + StartTime.toString("yyyyMMddThhmmss.zzz.hrm");
1286
	fname = KFileDialog::getSaveFileName(str1, QString("*.hrm"), this, QString("SportWatcher"));
1287
 
1288
	if (fname.isEmpty())
1289
	   return;
1290
 
1291
	fdfile.setName(fname);
1292
 
1293
	if (fdfile.exists())
1294
	{
1295
	   if (KMessageBox::questionYesNo(this, i18n("Do you really want to overwrite this file?")) == KMessageBox::No)
1296
	      return;
1297
	}
1298
 
1299
	if (!fdfile.open(IO_ReadWrite | IO_Truncate))
1300
	{
1301
	   KMessageBox::error(this, i18n("Error creating a file!\nPlease check permissions."));
1302
	   return;
1303
	}
1304
 
1305
	rn = ds.getRunNode();
1306
	lap = ds.getLap(rn->run->first_lap_index);
1307
	t = StartTime.time();
1308
	dat = StartTime.date();
1309
 
1310
	if ((point = ds.getPoint(lap->start_time)) == 0)
1311
	{
1312
	   fdfile.close();
1313
	   return;
1314
	}
1315
 
1316
	strcpy (hv0, "[Params]\n");
1317
	write(fdfile.handle(), &hv0[0], strlen(hv0));
1318
	str1 = dat.toString("yyyyMMdd");
1319
	str2 = t.toString("hh:mm:ss.z");
1320
	sprintf(hv0, "Version=106\nMonitor=11\nSMode=000000000\nDate=%s\nStartTime=%s\n",
1321
		str1.ascii(), str2.ascii());
1322
	write(fdfile.handle(), &hv0[0], strlen(hv0));
1323
	t.setHMS(0, 0, 0);
1324
	t = t.addSecs(max_time);
1325
	str2 = t.toString("hh:mm:ss.z");
1326
 
1327
	switch (sampleTime)
1328
	{
1329
	   case 0: samsec = 5; break;
1330
	   case 1: samsec = 15; break;
1331
	   case 2: samsec = 30; break;
1332
	   case 3: samsec = 60; break;
1333
	   default:
1334
	      samsec = 15;
1335
	}
1336
 
1337
	sprintf(hv0, "Length=%s\nInterval=%d\nUpper1=%d\nLower1=%d\nUpper2=%d\n",
1338
	   str2.ascii(), samsec, upper1, lower1, upper2);
1339
	write(fdfile.handle(), &hv0[0], strlen(hv0));
1340
	sprintf(hv0, "Lower2=%d\nUpper3=%d\nLower3=%d\nTimer1=00:00:00.0\n",
1341
		lower2, upper3, lower3);
1342
	write(fdfile.handle(), &hv0[0], strlen(hv0));
1343
	strcpy(hv0, "Timer2=00:00:00.0\nTimer3=00:00:00.0\nActiveLimit=0\n");
1344
	write(fdfile.handle(), &hv0[0], strlen(hv0));
1345
	sprintf(hv0, "MaxHR=%d\nRestHR=%d\nStartDelay=0\nVO2max=%d\nWeight=%d\n\n",
1346
		MaxHr, restHr, vo2max, weight);
1347
	write(fdfile.handle(), &hv0[0], strlen(hv0));
1348
 
1349
	// Write the intervall times. One block for every lap
1350
	secRange1 = secRange2 = secRange3 = secAbove = secBeyond = 0;
1351
	strcpy(hv0, "[IntTimes]\n");
1352
	write(fdfile.handle(), &hv0[0], strlen(hv0));
1353
	t.setHMS(0, 0, 0);
1354
 
1355
	for (unsigned int i = rn->run->first_lap_index; i < rn->run->last_lap_index; i++)
1356
	{
1357
	   alap = ds.getLap(i);
1358
	   point = ds.getPoint(alap->start_time);
1359
	   oldqt = garmin_dtime(point->time);
1360
	   avgHeart = minHeart = maxHeart = aktHeart = 0;
1361
	   anz = 0;
1362
	   unsigned long lastTime = point->time;
1363
	   int totSec = 0;
1364
 
1365
	   while (point)
1366
	   {
1367
	      if (point->time > (alap->start_time + (alap->total_time / 100)))
1368
		 break;
1369
 
1370
	      if (point->heart_rate > 0)
1371
	      {
1372
		 avgHeart += point->heart_rate;
1373
		 nsec = point->time - lastTime;
1374
		 totSec += nsec;
1375
 
1376
		 if (minHeart == 0 || minHeart > point->heart_rate)
1377
		    minHeart = point->heart_rate;
1378
 
1379
		 if (maxHeart < point->heart_rate)
1380
		    maxHeart = point->heart_rate;
1381
 
1382
		 if (aktHeart == 0 && totSec >= samsec)
1383
		    aktHeart = avgHeart / (anz + 1);
1384
 
1385
		 if (point->heart_rate < lower1)
1386
		    secBeyond += nsec;
1387
		 else if (point->heart_rate < lower2)
1388
		    secRange1 += nsec;
1389
		 else if (point->heart_rate < lower3)
1390
		    secRange2 += nsec;
1391
		 else if (point->heart_rate < upper3)
1392
		    secRange3 += nsec;
1393
		 else
1394
		    secAbove += nsec;
1395
 
1396
		 lastTime = point->time;
1397
		 anz++;
1398
	      }
1399
 
1400
	      point = ds.getPoint(point->time+1);
1401
	   }
1402
 
1403
	   t = t.addSecs(alap->total_time / 100);
1404
	   str1 = t.toString("hh:mm:ss.z");
166 andreas 1405
 
1406
	   if (anz > 0)
1407
	      avgHeart = avgHeart / anz;
1408
	   else
1409
	      avgHeart = 0;
1410
 
88 andreas 1411
	   sprintf(hv0, "%s\t %d\t %d\t %d\t %d\n",
166 andreas 1412
	      str1.ascii(), aktHeart, minHeart, avgHeart, maxHeart);
88 andreas 1413
	   write(fdfile.handle(), &hv0[0], strlen(hv0));
1414
	   strcpy(hv0, "32\t 0\t 0\t 0\t 0\t 0\n");
1415
	   write(fdfile.handle(), &hv0[0], strlen(hv0));
1416
	   strcpy(hv0, "0\t 0\t 0\t 0\t 0\n");
1417
	   write(fdfile.handle(), &hv0[0], strlen(hv0));
1418
	   sprintf(hv0, "0\t %d\t 0\t 0\t 0\t 0\n", (int)alap->total_distance);
1419
	   write(fdfile.handle(), &hv0[0], strlen(hv0));
1420
	   strcpy(hv0, "0\t 0\t 0\t 0\t 0\t 0\n");
1421
	   write(fdfile.handle(), &hv0[0], strlen(hv0));
1422
	}
1423
 
1424
	strcpy(hv0, "\n[IntNotes]\n\n[ExtraData]\n\n");
1425
	write(fdfile.handle(), &hv0[0], strlen(hv0));
1426
 
1427
	strcpy(hv0, "[Summary-123]\n");
1428
	write(fdfile.handle(), &hv0[0], strlen(hv0));	// Time limits 1
1429
	smp = max_time - secBeyond - secRange1 - secRange2 - secRange3 - secAbove;
1430
	sprintf(hv0, "%u\t %u\t %u\t %u\t %u\n",
1431
		max_time, secRange1, secRange2 + secRange3,
1432
		secAbove + secBeyond, smp);
1433
	write(fdfile.handle(), &hv0[0], strlen(hv0));	// limits 1
1434
	sprintf(hv0, "%d\t %d\t %d\t %d\n",
1435
		MaxHr, upper1, lower1, restHr);
1436
	write(fdfile.handle(), &hv0[0], strlen(hv0));	// Time limits 1
1437
	sprintf(hv0, "%u\t %u\t %u\t %u\t %u\n",
1438
		max_time, secRange2, secRange1 + secRange3,
1439
		secAbove + secBeyond, smp);
1440
	write(fdfile.handle(), &hv0[0], strlen(hv0));	// limits 2
1441
	sprintf(hv0, "%d\t %d\t %d\t %d\n",
1442
		MaxHr, upper2, lower2, restHr);
1443
	write(fdfile.handle(), &hv0[0], strlen(hv0));	// Time limits 2
1444
	sprintf(hv0, "%u\t %u\t %u\t %u\t %u\n",
1445
		max_time, secRange3, secRange1 + secRange2,
1446
		secAbove + secBeyond, smp);
1447
	write(fdfile.handle(), &hv0[0], strlen(hv0));	// limits 3
1448
	sprintf(hv0, "%d\t %d\t %d\t %d\n",
1449
		MaxHr, upper3, lower3, restHr);
1450
	write(fdfile.handle(), &hv0[0], strlen(hv0));	// Time limits 3
1451
	samples = max_time / samsec;
1452
	sprintf(hv0, "0\t %u\n\n", samples);	// samples
1453
	write(fdfile.handle(), &hv0[0], strlen(hv0));
1454
 
1455
	strcpy(hv0, "[Summary-TH]\n");
1456
	write(fdfile.handle(), &hv0[0], strlen(hv0));
1457
	sprintf(hv0, "%u\t 0\t %u\t %d\t %d\t 0\n", max_time, max_time - max_hr - restHr, max_hr, restHr);
1458
	write(fdfile.handle(), &hv0[0], strlen(hv0));
1459
	sprintf(hv0, "%d\t %d\t %d\t %d\n", MaxHr, upper3, lower1, restHr);
1460
	write(fdfile.handle(), &hv0[0], strlen(hv0));
1461
	sprintf(hv0, "0\t %u\n\n", samples);	// samples
1462
	write(fdfile.handle(), &hv0[0], strlen(hv0));
1463
 
1464
	sprintf(hv0, "[HRZones]\n%d\n%d\n%d\n%d\n%d\n%d\n0\n0\n0\n0\n0\n\n",
1465
		MaxHr, upper3, upper2, upper1, lower1, restHr);
1466
	write(fdfile.handle(), &hv0[0], strlen(hv0));
1467
 
1468
	strcpy(hv0, "[HRData]\n");
1469
	write(fdfile.handle(), &hv0[0], strlen(hv0));
1470
 
1471
	smp = 0;		// average heart rate of 15 seconds
1472
	seconds = 0;
1473
	anz = 0;
1474
	nsec = samsec;
1475
	oldqt = garmin_dtime(lap->start_time);
1476
	qt = 0;
1477
	point = ds.getPoint(lap->start_time);
1478
 
1479
	while (point)
1480
	{
1481
	   if (seconds >= nsec)
1482
	   {
1483
	      if (anz > 0)
1484
	      {
1485
		 sprintf(hv0, "%d\n", smp / anz);
1486
		 write(fdfile.handle(), &hv0[0], strlen(hv0));
1487
	      }
1488
 
1489
	      if (smp > 0 && seconds >= (nsec + samsec))
1490
	      {
1491
		 if (anz <= 0)
1492
		    anz = 0;
1493
 
1494
		 for (int x = nsec; x < seconds; x += samsec)
1495
		 {
1496
		    sprintf(hv0, "%d\n", smp / anz);
1497
		    write(fdfile.handle(), &hv0[0], strlen(hv0));
1498
		    nsec += samsec;
1499
		 }
1500
	      }
1501
 
1502
	      anz = 0;
1503
	      smp = 0;
1504
	      nsec += samsec;
1505
	   }
1506
 
1507
	   qt = garmin_dtime (point->time);
1508
	   seconds += oldqt->secsTo(*qt);
1509
 
1510
	   if (point->heart_rate > 0)
1511
	   {
1512
	      smp += point->heart_rate;
1513
	      anz++;
1514
	   }
1515
 
1516
	   delete oldqt;
1517
	   oldqt = qt;
1518
	   point = ds.getPoint(point->time + 1);
1519
	}
1520
 
1521
	fdfile.close();
1522
	KMessageBox::information(this, i18n("File successfully written."));
1523
}
1524
 
1525
void sportwatcherWidget::extrasSettings()
1526
{
1527
settingsWidget *dlg = new settingsWidget(this, "settingsWidgetBase", TRUE, 0);
1528
 
1529
	if (dlg->exec() == QDialog::Accepted)
1530
	{
1531
	   KSimpleConfig *cfg = new KSimpleConfig(QString("sportwatcher.rc"), true);
1532
	   cfg->setGroup(QString("SportWatcher"));
1533
	   lower1 = cfg->readNumEntry("lower1");
1534
	   lower2 = cfg->readNumEntry("lower2");
1535
	   lower3 = cfg->readNumEntry("lower3");
1536
	   upper1 = cfg->readNumEntry("upper1");
1537
	   upper2 = cfg->readNumEntry("upper2");
1538
	   upper3 = cfg->readNumEntry("upper3");
1539
	   MaxHr = cfg->readNumEntry("maxHr");
1540
	   restHr = cfg->readNumEntry("restHr");
1541
	   vo2max = cfg->readNumEntry("vo2max");
1542
	   weight = cfg->readNumEntry("weight");
1543
	   sampleTime = cfg->readNumEntry("seconds");
149 andreas 1544
	   Serial = cfg->readBoolEntry("Serial");
168 andreas 1545
	   Contour = cfg->readBoolEntry("Contour");
88 andreas 1546
	   Device = cfg->readEntry("Device");
1547
	   Data = cfg->readEntry("Data");
1548
	   HRM = cfg->readEntry("HRM");
151 andreas 1549
	   MAP = cfg->readEntry("MAP");
149 andreas 1550
	   Units = cfg->readNumEntry("Units");
158 andreas 1551
	   MapType = cfg->readNumEntry("MapType");
88 andreas 1552
	   delete cfg;
1553
	}
1554
 
1555
	delete dlg;
152 andreas 1556
}
151 andreas 1557
 
152 andreas 1558
void sportwatcherWidget::extrasWMSSettings()
1559
{
156 andreas 1560
#if defined HAVE_GDAL && HAVE_LIBGDAL1_5_0
158 andreas 1561
	if (MapType == MPT_BMP || MapType == MPT_GIF || MapType == MPT_PNG ||
1562
	    MapType == MPT_TIF)
1563
	{
1564
	   coordinatesWidget *idlg = new coordinatesWidget(this, "coordinateswidgetbase", true, 0);
1565
	   idlg->exec();
1566
	   delete idlg;
1567
	   return;
1568
	}
1569
 
1570
	if (MapType != MPT_WMS)
1571
	{
1572
	   KMessageBox::detailedSorry(this,
1573
	      i18n("You have not choosen a WMS tag file!"),
1574
	      i18n("This dialog is especialy to set WMS specific parameters. ") +
1575
	      i18n("Therefore this dialog is temporary disabled. It will be ") +
1576
	      i18n("available again, as soon as you choose \"WMS server\" as ") +
1577
	      i18n("your map type."));
1578
	      return;
1579
	}
151 andreas 1580
 
158 andreas 1581
	wmsbase *dlg = new wmsbase(this, "wmswidgetbase", TRUE, 0);
152 andreas 1582
	dlg->exec();
1583
	delete dlg;
156 andreas 1584
#else
1585
	KMessageBox::detailedSorry(this,
1586
	   i18n("This function was disabled at compile time because of missing GDAL v1.5.x!"),
1587
	   i18n("Sportwatcher needs GDAL v1.5.x to enable this function.\n") +
1588
	   i18n("If you like this to be working, install GDAL version 1.5.x and recompile the source!"));
1589
#endif
88 andreas 1590
}
1591
 
1592
/*
1593
 * Functions to fill in the boxes of the main mask.
1594
 */
1595
void sportwatcherWidget::showLaps()
1596
{
1597
QString qs_name, qs_distance, qs_etime, qs_avgpace, qs_avgspeed, qs_maxspeed;
1598
QString qs_calories, qs_avghr, qs_maxhr, qs_avgcadence, qs_ascent, qs_descent;
1599
QDateTime dt;
1600
QTime t, st;
215 andreas 1601
QDateTime *qt, *ftt, *ltt;
1602
LAP *lap, *flp;
213 andreas 1603
POINT *point, *subPt;
88 andreas 1604
RUN_NODE *rakt, *rn;
149 andreas 1605
int laps, i, anz, men, cad;
1606
double alt_asc, alt_dsc, sum_asc, sum_dsc, old_asc, old_dsc;
216 andreas 1607
bool pause;
215 andreas 1608
long secs;
88 andreas 1609
 
1610
	if (!gmn)
1611
	{
156 andreas 1612
	   KMessageBox::error(this, i18n("No data were loaded!"));
88 andreas 1613
	   return;
1614
	}
1615
 
1616
	if (gmn->type == data_Dnil)
1617
	{
1618
	   KMessageBox::error(0, i18n("No data found!"));
1619
	   return;
1620
	}
1621
 
1622
	if (gmn->type != data_Dlist)     /* List of data */
1623
	{
221 andreas 1624
	   KMessageBox::error(0, i18n("Found unexpected data type %1!").arg(gmn->type));
88 andreas 1625
	   return;
1626
	}
1627
 
1628
	ds.destroy();
221 andreas 1629
	min_hr = max_hr = avg_hr = 0;
88 andreas 1630
	min_height = max_height = 0.0;
218 andreas 1631
	min_speed = max_speed = 0.0;
88 andreas 1632
	liLaps->clear();
100 andreas 1633
	liLaps->setAllColumnsShowFocus(true);
88 andreas 1634
	ds.garmin_print_data(gmn);
1635
	rn = ds.getRunNode();
1636
	rakt = rn;
1637
	liLaps->setRootIsDecorated(true);
128 andreas 1638
	liLaps->setAlternateBackground(KGlobalSettings::alternateBackgroundColor());
88 andreas 1639
	liLaps->setColumnAlignment(1, Qt::AlignRight);
1640
	liLaps->setColumnAlignment(2, Qt::AlignRight);
1641
	liLaps->setColumnAlignment(3, Qt::AlignRight);
1642
	liLaps->setColumnAlignment(4, Qt::AlignRight);
1643
	liLaps->setColumnAlignment(5, Qt::AlignRight);
1644
	liLaps->setColumnAlignment(6, Qt::AlignRight);
1645
	liLaps->setColumnAlignment(7, Qt::AlignRight);
1646
	liLaps->setColumnAlignment(8, Qt::AlignRight);
1647
	liLaps->setColumnAlignment(9, Qt::AlignRight);
1648
	liLaps->setColumnAlignment(10, Qt::AlignRight);
1649
	liLaps->setColumnAlignment(11, Qt::AlignRight);
1650
 
1651
	qs_name = qs_distance = qs_etime = qs_avgpace = qs_avgspeed = qs_maxspeed = QString("");
1652
	qs_calories = qs_avghr = qs_maxhr = qs_avgcadence = qs_ascent = qs_descent = QString("");
1653
	men = 0;
149 andreas 1654
	cad = 0;
88 andreas 1655
 
1656
	while (rakt)
1657
	{
1658
	   if (rakt->run->type == data_D1000 || rakt->run->type == data_D1009 ||
1659
	   	rakt->run->type == data_D1010)
1660
	   {
1661
	   int lt, cal, ahr, mhr;
1662
	   double distance, speed, mspeed;
1663
	   QDate dat;
1664
 
1665
	      switch (rakt->run->sport_type)
1666
	      {
1667
		 case D1000_running: qs_name = QString("Running: "); break;
1668
		 case D1000_biking:  qs_name = QString("Biking: "); break;
1669
		 case D1000_other:   qs_name = QString("Other: "); break;
1670
		 default:
1671
		    qs_name = QString("Unknown: ");
1672
	      }
1673
 
1674
	      lap = ds.getLap(rakt->run->first_lap_index);
1675
	      qt = garmin_dtime (lap->start_time);
1676
	      StartTime = *qt;
1677
	      st = qt->time();
1678
	      dat = qt->date();
1679
	      delete qt;
213 andreas 1680
	      qt = 0;
1681
	      // Find the last track;
1682
	      //    It is possible to delete laps directly on the watch,
1683
	      //    so we can't be sure the last lap is really the last one.
1684
	      //    Tracks are not deleted and the last track contains the
1685
	      //    summuraries we need.
88 andreas 1686
	      lap = ds.getLap(rakt->run->last_lap_index);
213 andreas 1687
	      point = ds.getPoint(lap->start_time);
1688
 
1689
	      while (point)
1690
	      {
1691
		 subPt = ds.getPoint(point->time + 1);
1692
 
1693
		 if (!subPt || subPt->distance >= 0x7fffffff)
1694
		 {
1695
		    qt = garmin_dtime(point->time);
1696
		    t = qt->time();	// Every point contains the date and time it was recorded
1697
		    break;
1698
		 }
1699
		 else
1700
		    point = subPt;
1701
	      }
1702
 
1703
	      if (!qt)		// only, if we've not found the last track!
1704
	      {
1705
		 qt = garmin_dtime (lap->start_time);
1706
		 t = qt->addSecs(lap->total_time / 100).time();
1707
	      }
1708
 
215 andreas 1709
	      // There can be pauses during a session. Here we find this pauses
1710
	      // and subtract the pause seconds from the total time.
1711
	      subPt = point;	// save this track temporary
1712
	      point = ds.getPoint(0);
1713
	      pause = false;
1714
	      ltt = ftt = 0;
1715
	      secs = 0;
1716
	      lap = ds.getLap(rakt->run->last_lap_index);
1717
	      flp = ds.getLap(rakt->run->first_lap_index);
1718
	      i = rakt->run->first_lap_index;
1719
 
1720
	      while (point)
1721
	      {
216 andreas 1722
		 if (point->distance >= 0x7fffffff && !pause)	// Start of pause?
215 andreas 1723
		 {
1724
		    if (ltt)
1725
		       delete ltt;
1726
 
1727
		    ltt = garmin_dtime (point->time);
1728
		    pause = true;
1729
		 }
216 andreas 1730
		 else if (pause)	// End of pause
215 andreas 1731
		 {
1732
		    QTime t1, t2;
216 andreas 1733
		    POINT *p;
215 andreas 1734
 
216 andreas 1735
		    // Take the track after the stop track to find the real
1736
		    // time of the pause.
1737
		    if (point->distance >= 0x7fffffff)
215 andreas 1738
		    {
216 andreas 1739
		       if ((p = ds.getPoint(point->time + 1)) == 0)
1740
			  p = point;
215 andreas 1741
		       else
216 andreas 1742
			  point = p;
215 andreas 1743
		    }
1744
 
216 andreas 1745
		    // In case there's no stop track, we take the one
1746
		    // immediateley after the stop track as our start track.
1747
		    ftt = garmin_dtime (point->time);
215 andreas 1748
		    t1 = ltt->time();
1749
		    t2 = ftt->time();
1750
 
1751
		    if (t1 < t2)
1752
		       secs += t1.secsTo(t2);
1753
 
1754
		    delete ltt;
1755
		    delete ftt;
1756
		    ltt = ftt = 0;
1757
		    pause = false;
1758
		 }
1759
 
1760
		 if (point->time >= flp->start_time)
1761
		 {
216 andreas 1762
		    if ((unsigned int)i < rakt->run->last_lap_index)
215 andreas 1763
		    {
1764
		       i++;
1765
		       flp = ds.getLap(i);
1766
		    }
1767
		 }
1768
 
1769
		 point = ds.getPoint(point->time + 1);
1770
	      }
1771
 
1772
	      if (ltt)
1773
		 delete ltt;
1774
 
1775
	      if (ftt)
1776
		 delete ftt;
1777
 
1778
	      point = subPt;
88 andreas 1779
	      lt = st.secsTo(t);
1780
	      t.setHMS(0, 0, 0);
215 andreas 1781
	      t = t.addSecs(lt - secs);
88 andreas 1782
	      qt->setDate(dat);
1783
	      qt->setTime(t);
1784
	      qs_name.append(dat.toString("dd.MM.yyyy"));
1785
	      qs_name.append(" ");
1786
	      qs_name.append(st.toString("hh:mm:ss"));
1787
	      max_time = lt;
1788
	      qs_etime = QString(qt->toString("hh:mm:ss.zzz"));
1789
 
1790
	      distance = 0.0;
1791
	      cal = 0;
1792
	      mspeed = 0;
1793
	      ahr = mhr = 0;
1794
	      anz = 0;
149 andreas 1795
	      cad = 0;
1796
	      sum_asc = sum_dsc = old_asc = old_dsc = 0;
88 andreas 1797
 
1798
	      for (i = rakt->run->first_lap_index; (unsigned int)i <= rakt->run->last_lap_index; i++)
1799
	      {
1800
		 if ((lap = ds.getLap(i)) == NULL)
1801
		    continue;
1802
 
1803
		 distance += lap->total_distance;
1804
		 cal += lap->calories;
149 andreas 1805
 
1806
		 if (lap->avg_cadence != 0xff)
1807
		    cad += lap->avg_cadence;
1808
 
88 andreas 1809
		 ahr += lap->avg_heart_rate;
1810
		 anz++;
1811
 
1812
		 if (lap->max_speed > mspeed)
1813
		    mspeed = lap->max_speed;
1814
 
1815
		 if (lap->max_heart_rate > mhr)
1816
		    mhr = lap->max_heart_rate;
1817
	      }
1818
 
213 andreas 1819
	      if (point)
1820
	      {
1821
		 total_distance = point->distance;
1822
		 distance = point->distance;
1823
	      }
1824
	      else
1825
		 total_distance = distance;
1826
 
149 andreas 1827
	      if (Units == 1)		// Statute?
1828
		 qs_distance.sprintf("%.2f ft", distance / 0.304);
1829
	      else
1830
	         qs_distance.sprintf("%.2f m", distance);
1831
 
88 andreas 1832
	      if (distance > 0)
1833
	      {
1834
		 QTime tt = qt->time();
156 andreas 1835
		 long secs = (double)(tt.hour() * 3600 + tt.minute() * 60 + tt.second()) / 100.0;
1836
 
1837
		 if (Units == 0)
1838
		    secs = secs * (1000.0 / distance * 100.0);
1839
		 else
1840
		    secs = secs * (1609.344 / distance * 100.0);
1841
 
88 andreas 1842
		 int h = secs / 3600;
1843
		 int m = (secs - (h * 3600)) / 60;
1844
		 int s = secs - ((h * 3600) + (m * 60));
1845
		 t = QTime(h, m, s, 0);
1846
		 qs_avgpace = t.toString("  hh:mm:ss");
156 andreas 1847
 
1848
		 if (Units == 0)
1849
		    qs_avgpace.append(QString(" /km"));
1850
		 else
1851
		    qs_avgpace.append(QString(" /mi"));
88 andreas 1852
	      }
1853
 
149 andreas 1854
	      if (Units == 1)		// Statute?
156 andreas 1855
		 speed = distance / lt * 3.6 / 1.609344;
149 andreas 1856
	      else
1857
		 speed = distance / lt * 3.6;
1858
 
156 andreas 1859
	      qs_avgspeed.sprintf("%.2f %s", speed, (Units == 1) ? "mph" : "km/h");
1860
	      qs_maxspeed.sprintf("%.2f %s", (Units == 1) ? mspeed * 3.6 / 1.609344 : mspeed * 3.6, (Units == 1) ? "mph" : "km/h");
88 andreas 1861
	      qs_calories.sprintf("%d", cal);
1862
	      qs_avghr.sprintf("%d bpm", ahr / anz);
1863
	      qs_maxhr.sprintf("%d bpm", mhr);
1864
 
149 andreas 1865
	      if (cad > 0)
1866
		 qs_avgcadence.sprintf("%d", cad / anz);
1867
 
128 andreas 1868
	      KListViewItem *element = new KListViewItem(liLaps, qs_name, qs_distance,
88 andreas 1869
		qs_etime, qs_avgpace, qs_avgspeed, qs_maxspeed, qs_calories, qs_avghr);
1870
	      element->setText(8, qs_maxhr);
1871
	      element->setText(9, qs_avgcadence);
1872
	      element->setText(10, qs_ascent);
1873
	      element->setText(11, qs_descent);
1874
	      element->sortChildItems(0, false);
1875
	      element->setOpen(true);
128 andreas 1876
	      element->setPixmap(0, QPixmap::fromMimeSource(QString("activity.png")));
88 andreas 1877
	      liLaps->insertItem(element);
1878
	      delete qt;
1879
	      /* Get the laps. */
1880
	      laps = 1;
1881
 
1882
	      for (i = rakt->run->first_lap_index; (unsigned int)i <= rakt->run->last_lap_index; i++)
1883
	      {
149 andreas 1884
		 double spd;
1885
		 char *un;
1886
 
88 andreas 1887
		 if ((lap = ds.getLap(i)) == NULL)
1888
		    continue;
1889
 
1890
		 qt = garmin_dtime (lap->start_time);
1891
		 qs_name.sprintf("Lap %03d - ", laps);
1892
		 qs_name.append(qt->toString("hh:mm:ss"));
149 andreas 1893
		 qs_distance.sprintf("%.2f %s", (Units == 1) ? lap->total_distance / 0.304 : lap->total_distance, (Units == 1) ? "ft" : "m");
88 andreas 1894
		 t = QTime(0, 0, 0, 0);
1895
		 t = t.addMSecs(lap->total_time * 10);
1896
		 qs_etime = t.toString("hh:mm:ss.zzz");
149 andreas 1897
		 spd = lap->total_distance / (lap->total_time / 100.0);
1898
 
1899
		 if (Units == 0)
1900
		 {
1901
		    un = (char *)"km/h";
1902
		    spd *= 3.6;
1903
		 }
1904
		 else
156 andreas 1905
		 {
1906
		    spd *= 3.6 / 1.609344;
1907
		    un = (char *)"mph";
1908
		 }
149 andreas 1909
 
1910
		 qs_avgspeed.sprintf("%.2f %s", spd, un);
156 andreas 1911
		 qs_maxspeed.sprintf("%.2f %s", (Units == 1) ? lap->max_speed * 3.6 / 1.609344 : lap->max_speed * 3.6, un);
88 andreas 1912
		 qs_calories.sprintf("%d", lap->calories);
1913
 
1914
		 if (lap->total_distance > 0 && lap->total_time != 0)
1915
		 {
156 andreas 1916
		    double fact;
1917
 
1918
		    if (Units == 0)
1919
		       fact = 1000.0;		// 1 km
1920
		    else
1921
		       fact = 1609.344;		// 1 mile in meters
1922
 
1923
		    long secs = (double)lap->total_time / 10000.0 * (fact / lap->total_distance * 100.0);
88 andreas 1924
		    int h = secs / 3600;
1925
		    int m = (secs - (h * 3600)) / 60;
1926
		    int s = secs - ((h * 3600) + (m * 60));
1927
		    t = QTime(h, m, s, 0);
1928
		    qs_avgpace = t.toString("hh:mm:ss");
156 andreas 1929
 
1930
		    if (Units == 0)
1931
		       qs_avgpace.append(QString(" /km"));
1932
		    else
1933
		       qs_avgpace.append(QString(" /mi"));
88 andreas 1934
		 }
1935
 
1936
		 qs_avghr.sprintf("%d bpm", lap->avg_heart_rate);
1937
		 qs_maxhr.sprintf("%d bpm", lap->max_heart_rate);
1938
 
1939
		 anz = 0;
1940
		 alt_asc = alt_dsc = 0;
1941
 
1942
		 if ((point = ds.getPoint(lap->start_time)) != 0)
1943
		 {
1944
		    if (point->alt < 20000)
149 andreas 1945
		    {
88 andreas 1946
		       alt_dsc = alt_asc = point->alt;
149 andreas 1947
 
1948
		       if (old_asc == 0)
1949
			  old_asc = alt_asc;
1950
 
1951
		       if (old_dsc == 0)
1952
			  old_dsc = alt_dsc;
1953
		    }
88 andreas 1954
		    else
1955
		       alt_dsc = alt_asc = 0;
1956
 
218 andreas 1957
		    POINT *oldPoint = 0;
1958
		    double sc, dist, speed;
222 andreas 1959
		    unsigned long t1, t2;
1960
		    t1 = t2 = 0;
1961
		    pause = false;
1962
		    bool ignore = false;
218 andreas 1963
 
88 andreas 1964
		    while (point)
1965
		    {
1966
		       if (point->time > (lap->start_time + (lap->total_time / 100)))
1967
			 break;
1968
 
218 andreas 1969
		       if (!oldPoint)
1970
			  oldPoint = point;
1971
 
88 andreas 1972
		       if (point->alt > alt_asc && point->alt < 20000)
1973
		       {
1974
			  alt_asc = point->alt;
1975
 
1976
			  if (alt_dsc == 0)
1977
			     alt_dsc = point->alt;
1978
		       }
1979
 
1980
		       if (point->alt < alt_dsc)
1981
			  alt_dsc = point->alt;
1982
 
1983
		       // save the min and max values. We need this information to
1984
		       // build the graphics.
221 andreas 1985
		       if (point->heart_rate > max_hr && point->heart_rate < 250)
88 andreas 1986
			  max_hr = point->heart_rate;
1987
 
221 andreas 1988
		       if ((min_hr == 0 && point->heart_rate > 0 && point->heart_rate < 250)
1989
			   || (point->heart_rate > 0 && point->heart_rate < min_hr))
88 andreas 1990
			  min_hr = point->heart_rate;
1991
 
1992
		       if (point->alt < 20000 && max_height < point->alt)
1993
			  max_height = point->alt;
1994
 
1995
		       if (point->alt < 20000 && (min_height == 0.0 || min_height > point->alt))
1996
			  min_height = point->alt;
1997
 
218 andreas 1998
		       // Calculate speed of current track
222 andreas 1999
		       if (!pause && point->distance > 1.0e10)
2000
		       {
2001
			  t1 = point->time;
2002
			  pause = true;
2003
			  ignore = true;
2004
		       }
2005
		       else if (pause)
2006
		       {
2007
			  t2 = point->time;
2008
			  pause = false;
2009
			  point = ds.getPoint(point->time + 1);
2010
			  continue;
2011
		       }
218 andreas 2012
 
222 andreas 2013
		       if (!ignore && !pause)
2014
		       {
2015
			  sc = point->time - oldPoint->time;
2016
			  dist = point->distance - oldPoint->distance;
218 andreas 2017
 
222 andreas 2018
			  if (t2 > t1)
2019
			     sc -= t2 - t1;
218 andreas 2020
 
222 andreas 2021
			  if (sc > 0.0)
223 andreas 2022
			  {
222 andreas 2023
			     speed = (dist / sc) * 3.6;
223 andreas 2024
 
2025
			     if (speed > lap->max_speed * 3.6)
2026
			        speed = lap->max_speed * 3.6;
2027
			  }
222 andreas 2028
			  else
2029
			     speed = 0.0;
218 andreas 2030
 
222 andreas 2031
			  if (Units == 1)
2032
			     speed /= 1.609344;
218 andreas 2033
 
222 andreas 2034
			  if (speed > 0.0 && speed < 400.0 && max_speed < speed)
2035
			     max_speed = speed;
2036
 
2037
			  if (speed > 0.0 && (min_speed == 0.0 || min_speed > speed))
2038
			     min_speed = speed;
2039
 
2040
			  oldPoint = point;
2041
		       }
2042
 
2043
		       if (!pause && ignore)
2044
			  ignore = false;
2045
 
221 andreas 2046
		       if (point->heart_rate > 0 && point->heart_rate < 250)
88 andreas 2047
		       {
2048
			  avg_hr += point->heart_rate;
2049
			  men++;
2050
		       }
2051
 
2052
		       point = ds.getPoint(point->time + 1);
2053
		    }
2054
 
149 andreas 2055
		    if (old_asc < alt_asc)
2056
		       sum_asc += (alt_asc - old_asc);
2057
 
2058
		    if (old_dsc > alt_dsc)
2059
		       sum_dsc += (old_dsc - alt_dsc);
2060
 
2061
		    old_asc = alt_asc;
2062
		    old_dsc = alt_dsc;
2063
		    qs_ascent.sprintf("%.2f %s", (Units == 1) ? (alt_asc / 0.304) : alt_asc, (Units == 1) ? "ft" : "m");
2064
		    qs_descent.sprintf("%.2f %s", (Units == 1) ? (alt_dsc / 0.304) : alt_dsc, (Units == 1) ? "ft" : "m");
88 andreas 2065
		 }
2066
 
2067
		 if (lap->avg_cadence != 0xff)
2068
		    qs_avgcadence.sprintf("%d", lap->avg_cadence);
2069
 
128 andreas 2070
		 KListViewItem *edetail = new KListViewItem(element, qs_name, qs_distance,
88 andreas 2071
			qs_etime, qs_avgpace, qs_avgspeed, qs_maxspeed, qs_calories, qs_avghr);
2072
		 edetail->setText(8, qs_maxhr);
2073
		 edetail->setText(9, qs_avgcadence);
2074
		 edetail->setText(10, qs_ascent);
2075
		 edetail->setText(11, qs_descent);
128 andreas 2076
		 edetail->setPixmap(0, QPixmap::fromMimeSource(QString("history.png")));
2077
 
2078
		 switch (rakt->run->sport_type)
2079
		 {
2080
		    case D1000_running: edetail->setPixmap(0, QPixmap::fromMimeSource(QString("run.png"))); break;
2081
		    case D1000_biking:  edetail->setPixmap(0, QPixmap::fromMimeSource(QString("bike.png"))); break;
2082
		    case D1000_other:   edetail->setPixmap(0, QPixmap::fromMimeSource(QString("other.png"))); break;
2083
		    default:
2084
		       edetail->setPixmap(0, QPixmap::fromMimeSource(QString("other.png")));
2085
		 }
2086
 
88 andreas 2087
		 liLaps->clearSelection();
2088
		 element->insertItem(edetail);
2089
		 delete qt;
2090
		 laps++;
2091
	      }
149 andreas 2092
 
2093
	      qs_ascent.sprintf("%.2f %s", (Units == 1) ? sum_asc / 0.304 : sum_asc, (Units == 1) ? "ft" : "m");
2094
	      qs_descent.sprintf("%.2f %s", (Units == 1) ? sum_dsc / 0.304 : sum_dsc, (Units == 1) ? "ft" : "m");
2095
      	      element->setText(10, qs_ascent);
2096
	      element->setText(11, qs_descent);
88 andreas 2097
	   }
2098
 
2099
	   rakt = rakt->next;
2100
	}
2101
 
2102
	if (men > 0)
2103
	   avg_hr /= men;
221 andreas 2104
	else
2105
	   min_hr = max_hr = avg_hr = 0;
88 andreas 2106
}
2107
 
100 andreas 2108
void sportwatcherWidget::showTrack()
2109
{
132 andreas 2110
	showTrack(0, QRect(0, 0, 0, 0), 0);
104 andreas 2111
}
2112
 
2113
void sportwatcherWidget::showTrack(int zoom)
2114
{
132 andreas 2115
	showTrack(zoom, mapPan, mapLap);
2116
}
2117
 
2118
void sportwatcherWidget::showTrack(int zoom, const QRect &pan, LAP *lap)
2119
{
100 andreas 2120
int width, height;
2121
double x1, y1, x2, y2;
132 andreas 2122
int a, top, left, panX, panY;
2123
uint32 i;
109 andreas 2124
double coordW, coordH, tick;
156 andreas 2125
double meterW, dist, fact;
100 andreas 2126
QPainter paint;
152 andreas 2127
posn_type posNW, posSE, posLXY, posRXY;
100 andreas 2128
POINT *point;
152 andreas 2129
bool Fgeo = false;
157 andreas 2130
bool Data = false;
155 andreas 2131
#if defined HAVE_GDAL && HAVE_LIBGDAL1_5_0
158 andreas 2132
QString fName = MAP;
2133
//double adfGeoTransform[6];
2134
GDALDataset *poDataset = 0;
151 andreas 2135
GDALRasterBand *poBand;
2136
unsigned char *pafScanline;
2137
unsigned char *pafScanlineRed;
2138
unsigned char *pafScanlineGreen;
2139
unsigned char *pafScanlineBlue;
154 andreas 2140
unsigned char *pafScanlineAlpha;
151 andreas 2141
int nXSize, nYSize;
159 andreas 2142
int xOff, yOff;
158 andreas 2143
double oriLeftLon, oriLeftLat, oriRightLon, oriRightLat;
151 andreas 2144
#endif
100 andreas 2145
 
109 andreas 2146
	if (!gmn)
2147
	   return;
2148
 
154 andreas 2149
	QApplication::setOverrideCursor (QCursor(Qt::WaitCursor));
2150
 
104 andreas 2151
	if (zoom != zfactor)
2152
	   zfactor = zoom;
2153
 
132 andreas 2154
	if (mapLap != lap)
2155
	   mapLap = lap;
2156
 
157 andreas 2157
#if defined HAVE_GDAL && HAVE_LIBGDAL1_5_0
2158
	KSimpleConfig *cfg = new KSimpleConfig(QString("sportwatcher.rc"));
2159
	cfg->setGroup(QString("WMS"));
2160
	bool square = cfg->readBoolEntry("Square", false);
2161
	int CorrX = cfg->readNumEntry("CorrX", 0);
2162
	int CorrY = cfg->readNumEntry("CorrY", 0);
158 andreas 2163
	cfg->setGroup(QString("ImageCoords"));
2164
	oriLeftLon = cfg->readDoubleNumEntry("LeftLon", 0.0);
2165
	oriLeftLat = cfg->readDoubleNumEntry("LeftLat", 0.0);
2166
	oriRightLon = cfg->readDoubleNumEntry("RightLon", 0.0);
2167
	oriRightLat = cfg->readDoubleNumEntry("RightLat", 0.0);
2168
//	int isrs = cfg->readNumEntry("SRS", 0);
157 andreas 2169
#endif
148 andreas 2170
	width = imgMap->width() - 2;
2171
	height = imgMap->height();
157 andreas 2172
#if defined HAVE_GDAL && HAVE_LIBGDAL1_5_0
158 andreas 2173
	if (MapType == MPT_WMS && square)
157 andreas 2174
	   pmMap.resize(width / (int)mFactor * (int)mFactor, height / (int)mFactor * (int)mFactor);
2175
	else
2176
	   pmMap.resize(width, height);
2177
#else
100 andreas 2178
	pmMap.resize(width, height);
157 andreas 2179
#endif
100 andreas 2180
	paint.begin(&pmMap);
2181
 
132 andreas 2182
	panX = panY = 0;
2183
 
2184
	if (stateHand && mapPan != pan)
2185
	{
2186
	   mapPan = pan;
2187
	   panX = mapPan.right() - mapPan.left();
2188
	   panY = mapPan.bottom() - mapPan.top();
2189
	   oldTransX += (double)panX;
2190
	   oldTransY += (double)panY;
2191
	}
2192
 
104 andreas 2193
	memset(&posNW, 0, sizeof(posn_type));
2194
	memset(&posSE, 0, sizeof(posn_type));
100 andreas 2195
 
156 andreas 2196
	posSE.lat = 90.0;
2197
	posSE.lon = 180.0;
2198
	posNW.lat = -90.0;
2199
	posNW.lon = -180.0;
100 andreas 2200
 
2201
	/*
2202
	 * Find out the corners of our track (NW, NE, SE, SW)
2203
	 */
132 andreas 2204
	if (mapLap)
2205
	   i = mapLap->start_time;
2206
	else
2207
	   i = 0;
100 andreas 2208
 
2209
	while ((point = ds.getPoint(i)) != 0)
2210
	{
132 andreas 2211
	   if (mapLap && point->time > (mapLap->start_time + (mapLap->total_time / 100)))
2212
	      break;
2213
 
100 andreas 2214
	   if (point->posn.lat == 0x7fffffff || point->posn.lon == 0x7fffffff)
2215
	   {
132 andreas 2216
	      i = point->time + 1;
100 andreas 2217
	      continue;
2218
	   }
2219
 
2220
	   if (SEMI2DEG(point->posn.lat) > posNW.lat)
2221
	      posNW.lat = SEMI2DEG(point->posn.lat);
2222
 
2223
	   if (SEMI2DEG(point->posn.lat) < posSE.lat)
2224
	      posSE.lat = SEMI2DEG(point->posn.lat);
2225
 
156 andreas 2226
	   if (SEMI2DEG(point->posn.lon) > posNW.lon)
100 andreas 2227
	      posNW.lon = SEMI2DEG(point->posn.lon);
2228
 
156 andreas 2229
	   if (SEMI2DEG(point->posn.lon) < posSE.lon)
100 andreas 2230
	      posSE.lon = SEMI2DEG(point->posn.lon);
2231
 
132 andreas 2232
	   i = point->time + 1;
157 andreas 2233
	   Data = true;
100 andreas 2234
	}
104 andreas 2235
 
2236
	coordW = (posNW.lon > posSE.lon) ? posNW.lon - posSE.lon : posSE.lon - posNW.lon;
2237
	coordH = (posNW.lat > posSE.lat) ? posNW.lat - posSE.lat : posSE.lat - posNW.lat;
109 andreas 2238
	meterW = ds.earth_distance(posNW.lat, posNW.lon, posNW.lat, posSE.lon);
104 andreas 2239
 
2240
	// define the ticks to translate the GPS coordinates into pixels.
2241
	// The track should be centered and we have to calculate the
2242
	// rectangular within we draw the track.
152 andreas 2243
	if (coordW < coordH)
100 andreas 2244
	{
152 andreas 2245
	   tick = (double)width / coordW + (double)zoom;
2246
 
2247
	   if ((tick * coordH) > height)
109 andreas 2248
	      tick = (double)height / coordH + (double)zoom;
100 andreas 2249
	}
2250
	else
2251
	{
152 andreas 2252
	   tick = (double)height / coordH + (double)zoom;
2253
 
2254
	   if ((tick * coordW) > width)
109 andreas 2255
	      tick = (double)width / coordW + (double)zoom;
100 andreas 2256
	}
104 andreas 2257
 
156 andreas 2258
	left = width - (width - tick * coordW) / 2;
152 andreas 2259
	top = (height - tick * coordH) / 2;
2260
 
132 andreas 2261
	a = tick * coordW;
156 andreas 2262
 
2263
	if (Units == 0)
2264
	   dist = meterW / a;			// Meters
2265
	else
2266
	   dist = meterW * 1.609344 / a;	// 1/1000 mile (5.28 feet)
2267
 
155 andreas 2268
#if defined HAVE_GDAL && HAVE_LIBGDAL1_5_0
159 andreas 2269
	geoRect.llat = 0.0;
2270
	geoRect.llon = 0.0;
2271
	geoRect.rlat = 0.0;
2272
	geoRect.rlon = 0.0;
158 andreas 2273
	geoRect.width = width;
2274
	geoRect.height = height;
146 andreas 2275
	/*
2276
	 * If we have a map file, we try to read it and if successfull,
2277
	 * we should get a map painted.
154 andreas 2278
	 *
2279
	 * Currently only WMS-Server is supported, allthough GDAL allows
2280
	 * several other formats too.
146 andreas 2281
	 */
157 andreas 2282
	if (!MAP.isEmpty() && Data)
146 andreas 2283
	{
158 andreas 2284
	bool writeTag = true;
2285
	double mtx, mty;
2286
	double vx, vy;
152 andreas 2287
 
158 andreas 2288
	   xOff = yOff = 0;
2289
	   posRXY.lon = posNW.lon + (width - left + oldTransX) / tick;
2290
	   posLXY.lat = posNW.lat + (top + oldTransY) / tick;
2291
	   posLXY.lon = posSE.lon - (left - a - oldTransX) / tick;
2292
	   posRXY.lat = posSE.lat - (height - top - (tick * coordH) - oldTransY) / tick;
159 andreas 2293
	   geoRect.llat = posLXY.lat;
2294
	   geoRect.llon = posLXY.lon;
2295
	   geoRect.rlat = posRXY.lat;
2296
	   geoRect.rlon = posRXY.lon;
158 andreas 2297
	   // width and height of map in meters
2298
	   mtx = ds.earth_distance(posRXY.lat, posRXY.lon, posRXY.lat, posLXY.lon);
2299
	   mty = ds.earth_distance(posRXY.lat, posRXY.lon, posLXY.lat, posRXY.lon);
157 andreas 2300
 
158 andreas 2301
	   // factor to correct the map, in case we use a WMS server
2302
	   if (MapType == MPT_WMS)
2303
	   {
2304
	      vx = (posRXY.lon - posLXY.lon) / mtx * CorrX;
2305
	      vy = (posRXY.lat - posLXY.lat) / mty * CorrY;
2306
	      posRXY.lon += vx;
2307
	      posRXY.lat += vy;
2308
	      posLXY.lon += vx;
2309
	      posLXY.lat += vy;
2310
	   }
2311
 
154 andreas 2312
	   /*
158 andreas 2313
	    * Write a control file for GDAL, if we use a WMS server.
2314
	    * Warp an image if we use PNG or BMP or GIF.
2315
	    * Warp a region if we use TIFF
154 andreas 2316
	    */
158 andreas 2317
	   if (MapType == MPT_WMS)
2318
	      writeTag = writeWMSTag(posLXY.lon, posLXY.lat, posRXY.lon, posRXY.lat, width, height);
2319
 
159 andreas 2320
	   if (MapType == MPT_GIF || MapType == MPT_BMP || MapType == MPT_PNG ||
2321
	       MapType == MPT_SGI || MapType == MPT_TIF)
158 andreas 2322
	      writeTag = warpImage(MAP, &fName);
2323
 
2324
	   if (writeTag)
151 andreas 2325
	   {
158 andreas 2326
	      if (MapType != MPT_SHP && (poDataset = (GDALDataset *)GDALOpen (fName.ascii(), GA_ReadOnly)) != NULL)
151 andreas 2327
	      {
2328
		 QPixmap bild;
2329
		 int nRasterCount = poDataset->GetRasterCount();
2330
		 int nXBlock, nYBlock;
154 andreas 2331
		 GDALColorTable *pCT, *pCTb, *pCTr, *pCTg, *pCTa;
146 andreas 2332
 
151 andreas 2333
		 int             bGotMin, bGotMax;
2334
		 int		 tTypeLen, tColor, tColorEntrys;
2335
		 GDALDataType    tRasterType;
2336
		 double          adfMinMax[2];
2337
 
154 andreas 2338
		 pafScanlineRed = pafScanlineGreen = pafScanlineBlue = pafScanlineAlpha = 0;
152 andreas 2339
 
154 andreas 2340
		 /*
2341
		  * Read every raster band.
2342
		  *
2343
		  * If we get 3 raster bands, the image is a 24 bit image.
2344
		  * If we get 4 raster bands, the image is probably a 24 bit
2345
		  * image with an alpha channel. Currently the alpha channel
2346
		  * is ignored!
2347
		  * If we have 1 raster band, the image is 8 bit monochrom.
2348
		  * Otherwise the image is undefined and the results are also.
2349
		  */
151 andreas 2350
		 for (a = 1; a <= nRasterCount; a++)
2351
		 {
2352
		    poBand = poDataset->GetRasterBand (a);
2353
		    poBand->GetBlockSize (&nXBlock, &nYBlock);
2354
		    nXSize = poBand->GetXSize();
2355
		    nYSize = poBand->GetYSize();
2356
		    tRasterType = poBand->GetRasterDataType ();
2357
		    tTypeLen = GDALGetDataTypeSize (tRasterType) / 8;	// We need Bytes not Bits!
2358
		    tColor = poBand->GetColorInterpretation ();
2359
 
2360
		    adfMinMax[0] = poBand->GetMinimum (&bGotMin);
2361
		    adfMinMax[1] = poBand->GetMaximum (&bGotMax);
2362
 
2363
		    if (!(bGotMin && bGotMax))
2364
		       GDALComputeRasterMinMax ((GDALRasterBandH)poBand, TRUE, adfMinMax);
2365
 
152 andreas 2366
		    if ((pCT = poBand->GetColorTable()) != NULL)
151 andreas 2367
		       tColorEntrys = poBand->GetColorTable()->GetColorEntryCount();
2368
 
2369
		    switch (a)
2370
		    {
152 andreas 2371
		       case 1: pafScanlineRed   = new unsigned char[tTypeLen * nXSize * nYSize]; pafScanline = pafScanlineRed; pCTr = pCT; break;
2372
		       case 2: pafScanlineGreen = new unsigned char[tTypeLen * nXSize * nYSize]; pafScanline = pafScanlineGreen; pCTg = pCT; break;
2373
		       case 3: pafScanlineBlue  = new unsigned char[tTypeLen * nXSize * nYSize]; pafScanline = pafScanlineBlue; pCTb = pCT; break;
154 andreas 2374
		       case 4: pafScanlineAlpha  = new unsigned char[tTypeLen * nXSize * nYSize]; pafScanline = pafScanlineAlpha; pCTa = pCT; break;
151 andreas 2375
		    }
2376
 
152 andreas 2377
		    memset (pafScanline, 0, tTypeLen * nXSize * nYSize);
151 andreas 2378
 
154 andreas 2379
		    /*
158 andreas 2380
		     * Get the image (from the server) and put the tiles together.
154 andreas 2381
		     *
2382
		     * The function reads only one raster band. This is,
2383
		     * because the function is called for every raster band and
2384
		     * every raster band is stored into a separate array.
2385
		     */
152 andreas 2386
		    if (poBand->RasterIO (GF_Read, 0, 0, nXSize, nYSize, pafScanline, nXSize, nYSize, tRasterType, 0, 0) == CE_Failure)
2387
		    {
151 andreas 2388
		       KMessageBox::error(this, i18n("Error reading a raster band!"));
152 andreas 2389
		       Fgeo = false;
2390
		       break;
2391
		    }
2392
		    else
2393
		       Fgeo = true;
151 andreas 2394
		 }
2395
 
154 andreas 2396
		 /*
2397
		  * Only if Fgeo is TRUE, we've read successfully all raster
2398
		  * bands. Now we have to put the bands together to get
2399
		  * an image.
2400
		  */
152 andreas 2401
		 if (Fgeo)
2402
		 {
2403
		 unsigned char *pCombinedBytes = new unsigned char[(tTypeLen * nXSize * nYSize * nRasterCount)];
2404
		 unsigned char *ptr_dest, *ptr_src;
2405
		 int j;
151 andreas 2406
 
154 andreas 2407
		    /*
2408
		     * We need two nested loops to set the pixels in the wanted
2409
		     * order.
2410
		     */
152 andreas 2411
		    for (a = 0, j = 0; a < (nXSize * nYSize * nRasterCount); a += nRasterCount, j++)
151 andreas 2412
		    {
152 andreas 2413
		       int k = a;
2414
 
2415
		       for (int m = nRasterCount - 1; m >= 0; m--, k++)
2416
		       {
2417
		       unsigned char *pBytes;
2418
 
2419
			  switch (m)
2420
			  {
154 andreas 2421
			     case 3: pBytes = pafScanlineAlpha; pCT = pCTa; break;
152 andreas 2422
			     case 2: pBytes = pafScanlineBlue; pCT = pCTb; break;
2423
			     case 1: pBytes = pafScanlineGreen; pCT = pCTg; break;
2424
			     default: pBytes = pafScanlineRed; pCT = pCTr;
2425
			  }
2426
 
2427
			  ptr_dest = pCombinedBytes + k;
2428
			  unsigned char b = pBytes[j];
2429
 
154 andreas 2430
			  /*
2431
			   * If we have a color table, the pixels are pointers
2432
			   * to the color table. We need to convert them into
2433
			   * 24 bit pixels plus an optional alpha channel.
2434
			   */
152 andreas 2435
			  if (pCT != NULL)
2436
			  {
2437
			     GDALColorEntry ce;
2438
			     unsigned int c = (unsigned int)b;
2439
			     c = pCT->GetColorEntryAsRGB (c, &ce);
2440
 
2441
			     if  (m == 0) c = ce.c1;
2442
			     if  (m == 1) c = ce.c2;
2443
			     if  (m == 2) c = ce.c3;
154 andreas 2444
			     if  (m == 3) c = ce.c4;
152 andreas 2445
 
2446
			     b = (unsigned char)c;
2447
			  }
2448
 
2449
			  ptr_src = &b;
2450
			  memcpy (ptr_dest, ptr_src, 1);
2451
		       }
151 andreas 2452
		    }
152 andreas 2453
 
2454
		    x1 = y1 = 0;
2455
 
154 andreas 2456
		    /*
2457
		     * The following loop is QT specific! It sets the pixels
2458
		     * of the raw image, pixel by pixel. This may be slow, but
2459
		     * everything else didn't work :-(
2460
		     *
2461
		     * FIXME: We need a more effective routine to put the
158 andreas 2462
		     *        raw image into QT's "painter" class.
154 andreas 2463
		     */
2464
		    for (a = 0; a < (nXSize * nYSize * nRasterCount); a += nRasterCount)
152 andreas 2465
		    {
158 andreas 2466
		       if (x1 < width && y1 < height)
2467
		       {
2468
			  if (nRasterCount == 3)
2469
			     paint.setPen (QPen(QColor((int)pCombinedBytes[a+2], (int)pCombinedBytes[a+1], (int)pCombinedBytes[a]), QPen::SolidLine));
2470
			  else if (nRasterCount > 3)
159 andreas 2471
			     paint.setPen (QPen(QColor(qRgba((int)pCombinedBytes[a+3], (int)pCombinedBytes[a+2], (int)pCombinedBytes[a+1], (int)pCombinedBytes[a])), QPen::SolidLine));
158 andreas 2472
			  else if (nRasterCount == 2)
2473
			     paint.setPen (QPen(QColor((int)pCombinedBytes[a+1], (int)pCombinedBytes[a], (int)pCombinedBytes[a+1]), QPen::SolidLine));
2474
			  else if (nRasterCount == 1)
2475
			     paint.setPen (QPen(QColor((int)pCombinedBytes[a], (int)pCombinedBytes[a], (int)pCombinedBytes[a]), QPen::SolidLine));
154 andreas 2476
 
158 andreas 2477
			  paint.drawPoint(x1, y1);
2478
		       }
2479
 
152 andreas 2480
		       x1++;
2481
 
2482
		       if (x1 >= nXSize)
2483
		       {
2484
			  x1 = 0;
2485
			  y1++;
2486
		       }
2487
		    }
2488
 
2489
		    delete pCombinedBytes;
151 andreas 2490
		 }
2491
 
152 andreas 2492
		 if (pafScanlineRed)
2493
		    delete pafScanlineRed;
151 andreas 2494
 
152 andreas 2495
		 if (pafScanlineGreen)
2496
		    delete pafScanlineGreen;
2497
 
2498
		 if (pafScanlineBlue)
2499
		    delete pafScanlineBlue;
2500
 
154 andreas 2501
		 if (pafScanlineAlpha)
2502
		    delete pafScanlineAlpha;
2503
 
152 andreas 2504
		 GDALClose (poDataset);
2505
		 poDataset = 0;
158 andreas 2506
 
2507
		 if (MAP != fName)
2508
		    unlink (fName.ascii());
151 andreas 2509
	      }
158 andreas 2510
	      else if (MapType == MPT_SHP)
2511
	      {
2512
		 QDir shpd(MAP, QString("*.shp"));
2513
 
2514
		 if (shpd.count() < 1)
2515
		 {
2516
		    KMessageBox::error(this, i18n("There is no shape file in directory ") + MAP);
2517
		    Fgeo = false;
2518
		 }
2519
		 else
2520
		 {
2521
		 OGRDataSource *poDS = 0;
165 andreas 2522
		 OGRLayer *poLy;
2523
		 OGRFeature *poFeat;
2524
		 OGRFeatureDefn *poFDefn;
2525
		 OGRFieldDefn *poFieldDefn;
2526
		 OGRGeometry *poGeometry;
2527
		 OGRPoint *poPoint;
2528
		 int nLayers, iField;
2529
		 QString sfn;
158 andreas 2530
 
165 andreas 2531
		    OGRRegisterAll ();
158 andreas 2532
		    // read all shape files and put them together
2533
		    for (a = 0; a < shpd.count(); a++)
2534
		    {
165 andreas 2535
		       sfn = MAP + shpd[a];
2536
		       poDS = OGRSFDriverRegistrar::Open(sfn.ascii(), false);
158 andreas 2537
 
2538
		       if (!poDS)
165 andreas 2539
		       {
2540
			  cerr << "Error opening the file " << sfn.ascii() << "!" << endl;
158 andreas 2541
			  break;
165 andreas 2542
		       }
158 andreas 2543
 
165 andreas 2544
		       nLayers = poDS->GetLayerCount ();
2545
 
2546
		       // Read all layers of a shape file
2547
		       for (int j = 0; j< nLayers; j++)
2548
		       {
2549
			  if ((poLy = poDS->GetLayer (j)) == NULL)
2550
			  {
2551
			     cerr << "Error getting layer " << j << "!" << endl;
2552
			     continue;
2553
			  }
2554
 
2555
			  poLy->SetSpatialFilterRect (geoRect.llon, geoRect.llat, geoRect.rlon, geoRect.rlat);
2556
 
2557
			  // Read all features of a layer and get the fields
2558
			  // of the features
2559
			  poLy->ResetReading();
2560
 
2561
			  while ((poFeat = poLy->GetNextFeature()) != NULL)
2562
			  {
2563
			     if ((poFDefn = poLy->GetLayerDefn()) == NULL)
2564
			     {
2565
			        cerr << "Error getting a layer defination!" << endl;
2566
			        continue;
2567
			     }
2568
 
2569
			     poGeometry = poFeat->GetGeometryRef();
2570
 
2571
			     if (poGeometry != NULL && wkbFlatten (poGeometry->getGeometryType()) == wkbPoint)
2572
			     {
2573
			        poPoint = (OGRPoint *) poGeometry;
2574
			        cout << "pointX: " << poPoint->getX() << ", pointY: " << poPoint->getY() << endl;
2575
			     }
2576
 
2577
			     for (iField = 0; iField < poFDefn->GetFieldCount(); iField++)
2578
			     {
2579
			        poFieldDefn = poFDefn->GetFieldDefn (iField);
2580
 
2581
				if (poFieldDefn->GetType() == OFTInteger)
2582
				   cout << "Layer: " << j << " int: " << poFeat->GetFieldAsInteger (iField) << endl;
2583
				else if (poFieldDefn->GetType() == OFTReal)
2584
				   cout << "Layer: " << j << " float: " << poFeat->GetFieldAsDouble (iField) << endl;
2585
				else if (poFieldDefn->GetType() == OFTString)
2586
				   cout << "Layer: " << j << " string: " << poFeat->GetFieldAsString (iField) << endl;
2587
				else
2588
				   cout << "Layer: " << j << " Unkn.: " << poFeat->GetFieldAsString (iField) << endl;
2589
			     }
2590
 
2591
			     cout << "----------------------------" << endl;
2592
        		  }
2593
 
2594
        		  OGRFeature::DestroyFeature (poFeat);
2595
		       }
2596
 
158 andreas 2597
		       OGRDataSource::DestroyDataSource(poDS);
2598
		    }
2599
		 }
2600
	      }
151 andreas 2601
	      else
157 andreas 2602
	      {
158 andreas 2603
		 KMessageBox::error(this, i18n("Error opening map file!"));
157 andreas 2604
		 Fgeo = false;
2605
	      }
151 andreas 2606
	   }
146 andreas 2607
	}
151 andreas 2608
#endif
154 andreas 2609
	/*
2610
	 * Here we come to draw the track. It will be drawn over the previous
2611
	 * created map image.
2612
	 */
100 andreas 2613
	// Colors and fonts
154 andreas 2614
	QColor background(220, 220, 220);		// background color
2615
	QColor red(255, 0, 0);				// mile marker
2616
	QColor black(0, 0, 0);				// Text, center of track
2617
//	QColor yellow(255, 255, 0);
2618
	QColor yellow(0x00cf, 0x00ff, 0x0000);		// color of track
100 andreas 2619
	QFont fntNormal("Helvetica");
2620
	fntNormal.setPixelSize(10);
2621
	fntNormal.setStyleHint(QFont::Helvetica);
104 andreas 2622
	QPen dot(red, 4, QPen::SolidLine);
154 andreas 2623
	QPen line(black, 2, QPen::SolidLine);
2624
	QPen yline(yellow, 5, QPen::SolidLine);
2625
	// Fill background with background colors, if there is no map.
152 andreas 2626
	if (!Fgeo)
2627
	   paint.fillRect(0, 0, width+2, height+2, background);
2628
 
156 andreas 2629
	if (Units == 0)
2630
	   fact = 1000.0;
2631
	else
2632
	   fact = 1609.344;
2633
 
109 andreas 2634
	paint.setPen(line);
2635
	paint.drawLine(10, height - 9, 10, height - 4);
156 andreas 2636
	paint.drawLine(10, height - 4, 10 + (fact / dist), height - 4);
2637
	paint.drawLine(10 + (fact / dist), height - 9, 10 + (fact / dist), height - 4);
109 andreas 2638
	paint.setFont(fntNormal);
2639
 
156 andreas 2640
	if (Units == 0)
2641
	   paint.drawText(10, height - 10, QString("1000 m"));
2642
	else
2643
	   paint.drawText(10, height - 10, QString("5280 ft"));
2644
 
100 andreas 2645
	// Draw track
132 andreas 2646
	if (mapLap)
2647
	   i = mapLap->start_time;
2648
	else
2649
	   i = 0;
2650
 
100 andreas 2651
	x1 = y1 = 0.0;
157 andreas 2652
	bool wStart = false;
104 andreas 2653
 
100 andreas 2654
	while ((point = ds.getPoint(i)) != 0)
2655
	{
132 andreas 2656
	   if (mapLap && point->time > (mapLap->start_time + (mapLap->total_time / 100)))
2657
	      break;
2658
 
100 andreas 2659
	   if (point->posn.lat == 0x7fffffff || point->posn.lon == 0x7fffffff)
2660
	   {
132 andreas 2661
	      i = point->time + 1;
100 andreas 2662
	      continue;
2663
	   }
2664
 
157 andreas 2665
	   x2 = (left + ((posNW.lon - SEMI2DEG(point->posn.lon)) * tick * -1)) + oldTransX;
2666
	   y2 = (top + ((posNW.lat - SEMI2DEG(point->posn.lat)) * tick)) + oldTransY;
100 andreas 2667
 
157 andreas 2668
	   if (!wStart && x1 != 0.0 && y1 != 0.0)
2669
	   {
2670
	      // Load the start symbol
2671
	      QPixmap qpx = QPixmap::fromMimeSource(QString("wstart.png"));
2672
	      // Find the angle of the track and turn the symbol accordingly
2673
	      // we use Pythagoras to calculate the triangle
2674
	      double xl = (x1 < x2) ? x2 - x1 : x1 - x2;
2675
	      double yl = (y1 < y2) ? y2 - y1 : y1 - y2;
2676
	      double da = fmin (xl, yl);
2677
	      double db = fmax (xl, yl);
2678
	      double zl = sqrt (pow (da, 2) + pow (db, 2));
2679
	      double angle = (asin(da / zl) / M_PIl) * 180.0;
2680
 
2681
	      angle = (angle > 45.0) ? 90.0 - angle : angle;
2682
// cout << "Winkel: " << angle << " ---- X: " << xl << ", Y: " << yl << ", Z: " << zl << ", Point (x1,y1,x2,y2): " << x1 << ", " << y1 << ", " << x2 << ", " << y2 << endl;
2683
	      if (x1 < x2 && y1 < y2)		// right, down
2684
		 angle = 90.0 + angle;
2685
	      else if (x1 > x2 && y1 < y2)	// left, down
2686
		 angle = 270.0 - angle;
2687
	      else if (x1 > x2 && y1 > y2)	// left, up
2688
		 angle = 270.0 + angle;
2689
	      else				// right, up
2690
		 angle = 90.0 - angle;
2691
// cout << "Realer Winkel: " << angle << endl;
2692
	      // Set the center of the symbol
2693
	      paint.save ();
2694
	      paint.translate (x1, y1);
2695
	      // rotate the symbol
2696
	      paint.rotate (angle);
2697
	      paint.drawPixmap (-8, -8, qpx);
2698
	      paint.restore ();
2699
	      wStart = true;
2700
	   }
2701
 
100 andreas 2702
	   if (x1 == 0.0 && y1 == 0.0)
2703
	   {
2704
	      x1 = x2;
2705
	      y1 = y2;
2706
	   }
104 andreas 2707
 
100 andreas 2708
	   paint.setPen(yline);
104 andreas 2709
	   paint.drawLine(x1, y1, x2, y2);
2710
 
156 andreas 2711
	   if ((point->distance - dist) >= fact)	// a dot at every 1000 meters or at 1 mile
104 andreas 2712
	   {
2713
	      paint.setPen(dot);
154 andreas 2714
	      paint.drawEllipse(x2-2, y2-2, 3, 3);
156 andreas 2715
	      dist = (int)(point->distance / fact) * fact;
104 andreas 2716
	   }
2717
 
100 andreas 2718
	   paint.setPen(line);
2719
	   paint.drawLine(x1, y1, x2, y2);
2720
	   x1 = x2;
2721
	   y1 = y2;
132 andreas 2722
	   i = point->time + 1;
100 andreas 2723
	}
2724
 
157 andreas 2725
	bool lastLap = false;
2726
 
2727
	if (mapLap)
2728
	   if (ds.getRunNode()->run->last_lap_index == mapLap->index)
2729
	      lastLap = true;
2730
 
2731
	if ((!mapLap || lastLap) && wStart)
2732
	{
2733
	   // load the end symbol
2734
	   QPixmap qpx = QPixmap::fromMimeSource(QString("wtarget.png"));
2735
	   paint.drawPixmap (x2, y2 - 16, qpx);
2736
	}
2737
 
100 andreas 2738
	paint.end();
2739
	imgMap->setPixmap(pmMap);
154 andreas 2740
	QApplication::restoreOverrideCursor();
100 andreas 2741
}
2742
 
88 andreas 2743
void sportwatcherWidget::showCurves()
2744
{
148 andreas 2745
	showCurves (mapLap);
2746
}
2747
 
2748
void sportwatcherWidget::showCurves(LAP *lap)
2749
{
88 andreas 2750
QPainter paint;
2751
int width, height;
218 andreas 2752
int i, secs, cuType;
88 andreas 2753
int lineHeight, margin_left, margin_right, margin_bottom;
2754
int x1, y1, x2, y2;		// Coordinates
2755
bool meter;
218 andreas 2756
double maxHeight, minHeight, maxSpeed, minSpeed;
88 andreas 2757
int maxHr, minHr, rh;
2758
POINT *point;
148 andreas 2759
RUN_NODE *rn;
2760
LAP *lp;
88 andreas 2761
double w_tick, h_tick;		// Number of pixels one "tick" has;
2762
				// This depends on the width and height
2763
				// of the image.
2764
	// First we draw a grid based on the min and max
2765
	// values detected in the function showLap(). In case
2766
	// all values are 0, we exit here.
2767
	if (min_hr == 0 && max_hr == 0 && min_height == 0.0 && max_height == 0.0)
2768
	   return;
2769
 
218 andreas 2770
	// Look up, what curves we should draw
2771
	cuType = kcbCurveTypes->currentItem();
2772
	// Get the dimensions of the available draw area
148 andreas 2773
	width = imgProfile->width() - 2;
2774
	height = imgProfile->height();
2775
	pmProfile.resize(width, height);
88 andreas 2776
	paint.begin(&pmProfile);
2777
 
2778
	// we need a somewhat bigger area to draw our curves than
2779
	// we have with the real min and max values.
2780
	if (max_height > 0.0)
2781
	{
148 andreas 2782
	double add = (max_height - min_height) / 100.0 * 5.0;	// Percent
88 andreas 2783
 
2784
	   maxHeight = max_height + add;
2785
	   minHeight = min_height - add;
2786
 
2787
	   if (minHeight < 0.0)		// make sure, we are not too deep
2788
	      minHeight = 0.0;
2789
	}
221 andreas 2790
	else
2791
	   maxHeight = minHeight = 0.0;
88 andreas 2792
 
218 andreas 2793
	if (max_speed > 0.0)
2794
	{
2795
	double add = (max_speed - min_speed) / 100.0 * 5.0;	// Percent
2796
 
2797
	   maxSpeed = max_speed + add;
2798
	   minSpeed = min_speed - add;
2799
 
2800
	   if (minSpeed < 0.0)		// make sure, we are not too deep
2801
	      minSpeed = 0.0;
2802
	}
221 andreas 2803
	else
2804
	   maxSpeed = minSpeed = 0.0;
218 andreas 2805
 
88 andreas 2806
	if (max_hr > 0)
2807
	{
2808
	   maxHr = max_hr + 10;
2809
	   minHr = min_hr - 10;
2810
 
2811
	   if (minHr < 0)
2812
	      minHr = 0;
2813
	}
221 andreas 2814
	else
2815
	   maxHr = minHr = 0;
88 andreas 2816
 
2817
	// Define colors
148 andreas 2818
	QColor background(220, 220, 220);	// Background of graphic
2819
	QColor mark(255, 255, 255);		// Lines inside curve area
2820
	QColor hlight(180, 180, 180);		// area of current lap
2821
//	hlight.setAlpha(128);			// 50% transparent
2822
	QColor frame(0, 0, 0);			// Text and borders
2823
	QColor barcol(151, 190, 13);		// heart rate
2824
	QColor barcol2(190, 151, 13);		// height over NN
222 andreas 2825
	QColor red(220, 128, 128);		// speed
88 andreas 2826
	QColor blue(0, 0, 240);
2827
	QFont fntNormal("Helvetica");
2828
//	QFont fntBold("Helvetica", 10, QFont::Bold);
2829
	fntNormal.setPixelSize(10);
2830
	fntNormal.setStyleHint(QFont::Helvetica);
2831
//	fntBold.setPixelSize(10);
2832
//	fntBold.setStyleHint(QFont::Helvetica);
2833
	// Calculate ticks
2834
	margin_left = 52;
2835
	margin_right = 40;
2836
	margin_bottom = 12;
2837
	lineHeight = 10;
2838
	rh = height - margin_bottom - 1;
2839
 
2840
	w_tick = (double)(width - (margin_left + margin_right)) / max_time;	// 1 tick = 1 second
2841
 
222 andreas 2842
	if (cuType == 1)	// Speed and heart rate?
88 andreas 2843
	{
218 andreas 2844
	   if ((maxSpeed - minSpeed) > (double)(maxHr - minHr))
2845
	   {
222 andreas 2846
	      h_tick = (double)rh / (maxSpeed - minSpeed);		// 1 tick = 1 km/h
218 andreas 2847
	      meter = true;
2848
	   }
2849
	   else
2850
	   {
2851
	      h_tick = (double)rh / ((double)maxHr - (double)minHr);	// 1 tick = 1 bpm
2852
	      meter = false;
2853
	   }
88 andreas 2854
	}
222 andreas 2855
	else if (cuType == 2)	// Elevation and speed?
88 andreas 2856
	{
218 andreas 2857
	   if ((maxHeight - minHeight) > (double)(maxHr - minHr))
2858
	   {
2859
	      h_tick = (double)rh / (maxHeight - minHeight);		// 1 tick = 1 meter
2860
	      meter = true;
2861
	   }
2862
	   else
2863
	   {
222 andreas 2864
	      h_tick = (double)rh / (maxSpeed - minSpeed);		// 1 tick = 1 km/h
2865
	      meter = false;
2866
	   }
2867
	}
2868
	else			// Elevation and heart rate
2869
	{
2870
	   if ((maxHeight - minHeight) > (double)(maxHr - minHr))
2871
	   {
2872
	      h_tick = (double)rh / (maxHeight - minHeight);		// 1 tick = 1 meter
2873
	      meter = true;
2874
	   }
2875
	   else
2876
	   {
218 andreas 2877
	      h_tick = (double)rh / ((double)maxHr - (double)minHr);	// 1 tick = 1 bpm
2878
	      meter = false;
2879
	   }
88 andreas 2880
	}
218 andreas 2881
 
88 andreas 2882
	// Fill background with background colors
2883
	paint.fillRect(0, 0, width + 4, height + 4, background);
2884
	// Draw a grid with markers at every 10 minutes
2885
	paint.setPen(QPen(frame, 1, QPen::SolidLine));
2886
	// Bottom border line
2887
	x1 = margin_left;
2888
	y1 = height - margin_bottom;
2889
	x2 = width - margin_right;
2890
	y2 = y1;
2891
	paint.drawLine(x1, y1, x2, y2);
2892
	// Left border line
2893
	x1 = x2 = margin_left;
2894
	y1 = 2;
2895
	y2 = height - margin_bottom;
2896
	paint.drawLine(x1, y1, x2, y2);
2897
	// right border line
2898
	x1 = x2 = width - margin_right;
2899
	paint.drawLine(x1, y1, x2, y2);
148 andreas 2900
 
2901
	// Draw some darker lines to show the laps, if we have one
2902
	// and, in case we have a given lap, we fill the area.
2903
	QDateTime *qt;
2904
	QTime zeit = StartTime.time();
2905
	rn = ds.getRunNode();
2906
	paint.setPen(QPen(hlight, 1, QPen::SolidLine));
2907
 
2908
	for (i = rn->run->first_lap_index; (unsigned int)i <= rn->run->last_lap_index; i++)
2909
	{
2910
	   if ((lp = ds.getLap(i)) == NULL)
2911
	      continue;
2912
 
2913
	   qt = garmin_dtime(lp->start_time);
2914
	   secs = zeit.secsTo(qt->time());
2915
	   delete qt;
2916
	   x1 = secs * w_tick + margin_left + 1;
2917
 
2918
	   if (lap && lp->start_time == lap->start_time)
2919
	      paint.fillRect(x1, 2, (int)((double)lap->total_time / 100.0 * w_tick), height - margin_bottom - 2, hlight);
2920
	   else
2921
	      paint.drawLine(x1, 2, x1, height - margin_bottom);
2922
	}
2923
 
88 andreas 2924
	// Grid vertical
2925
	paint.setPen(QPen(frame, 1, QPen::SolidLine));
2926
	paint.setFont(fntNormal);
2927
	paint.drawText(margin_left - 20, height - lineHeight, 40, lineHeight, Qt::AlignCenter, QString("00:00"));
2928
	paint.save();
2929
	paint.rotate(270);
218 andreas 2930
 
222 andreas 2931
	if (cuType == 1)
2932
	   paint.setPen(QPen(red, 1, QPen::SolidLine));
2933
	else
2934
	   paint.setPen(QPen(barcol, 1, QPen::SolidLine));
2935
 
2936
	// Information on left side
218 andreas 2937
	if (cuType == 0)
2938
	   paint.drawText((height + 4) * -1, 3, height - 2, lineHeight, Qt::AlignCenter, i18n((Units == 1) ? "Elevation (ft)" : "Elevation (m)"));
2939
	else if (cuType == 1)
2940
	   paint.drawText((height + 4) * -1, 3, height - 2, lineHeight, Qt::AlignCenter, i18n((Units == 1) ? "Speed (mph)" : "Speed (km/h)"));
2941
	else
2942
	   paint.drawText((height + 4) * -1, 3, height - 2, lineHeight, Qt::AlignCenter, i18n((Units == 1) ? "Elevation (ft)" : "Elevation (m)"));
2943
 
222 andreas 2944
	if (cuType == 2)
2945
	   paint.setPen(QPen(red, 1, QPen::SolidLine));
2946
	else
2947
	   paint.setPen(QPen(blue, 1, QPen::SolidLine));
218 andreas 2948
 
222 andreas 2949
	// Information on right side
218 andreas 2950
	if (cuType < 2)
2951
	   paint.drawText((height + 4) * -1, width - 1 - lineHeight, height - 2, lineHeight, Qt::AlignCenter, i18n("Heart Rate (bpm)"));
2952
	else
2953
	   paint.drawText((height + 4) * -1, width - 1 - lineHeight, height - 2, lineHeight, Qt::AlignCenter, i18n((Units == 1) ? "Speed (mph)" : "Speed (km/h)"));
2954
 
88 andreas 2955
	paint.restore();
2956
	paint.setPen(QPen(mark, 1, QPen::SolidLine));
222 andreas 2957
	// Draw the time scale on the bottom of the graphic
88 andreas 2958
	for (i = 0; (unsigned int)i < max_time; i++)
2959
	{
2960
	   if (i > 0 && !(i % 600))	// every 10 minutes
2961
	   {
2962
	      x1 = x2 = margin_left + w_tick * i;
2963
 
2964
	      if (x1 == (width - margin_right))
2965
		 continue;
2966
 
2967
	      y1 = 2;
2968
	      y2 = height - margin_bottom;
2969
	      paint.drawLine(x1, y1, x2, y2);
2970
	      QTime tm(0, 0, 0);
2971
	      tm = tm.addSecs(i);
2972
	      paint.setPen(QPen(frame, 1, QPen::SolidLine));
2973
	      paint.drawText(x1 - 25, height - lineHeight, 50, lineHeight, Qt::AlignCenter, tm.toString((i >= 3600) ? "hh:mm:ss" : "mm:ss"));
2974
	      paint.setPen(QPen(mark, 1, QPen::SolidLine));
2975
	   }
2976
	}
222 andreas 2977
 
2978
	// This is the total time, with pauses included, at the lower right
2979
	// corner of the graphic.
88 andreas 2980
	QTime tm(0, 0, 0);
2981
	QString qs;
2982
	tm = tm.addSecs(max_time);
2983
	paint.setPen(QPen(frame, 1, QPen::SolidLine));
2984
	paint.drawText(width - margin_right - 25, height - lineHeight, 50, lineHeight, Qt::AlignCenter, tm.toString((max_time >= 3600) ? "hh:mm:ss" : "mm:ss"));
2985
 
222 andreas 2986
	// Draw the minimal elevation, speed and/or heart rate
218 andreas 2987
	if (max_height > 0.0 || max_speed > 0.0)
88 andreas 2988
	{
222 andreas 2989
	   // left side
218 andreas 2990
	   if (cuType == 1)
222 andreas 2991
	   {
2992
	      paint.setPen(QPen(red, 1, QPen::SolidLine));
218 andreas 2993
	      paint.drawText(12, height - margin_bottom - lineHeight / 2, margin_left - 14, lineHeight, Qt::AlignRight, qs.sprintf("%.0f", minSpeed));
222 andreas 2994
	   }
218 andreas 2995
	   else
222 andreas 2996
	   {
2997
	      paint.setPen(QPen(barcol, 1, QPen::SolidLine));
218 andreas 2998
	      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 2999
	   }
88 andreas 3000
	}
3001
 
222 andreas 3002
	if (max_hr > 0 || max_speed > 0.0)
88 andreas 3003
	{
222 andreas 3004
	   // right side
3005
	   if (cuType == 2)
3006
	   {
3007
	      paint.setPen(QPen(red, 1, QPen::SolidLine));
3008
	      paint.drawText(width - margin_right + 2, height - margin_bottom - lineHeight / 2, margin_right - 14, lineHeight, Qt::AlignLeft, qs.sprintf("%.0f", minSpeed));
3009
	   }
3010
	   else
3011
	   {
3012
	      paint.setPen(QPen(blue, 1, QPen::SolidLine));
3013
	      paint.drawText(width - margin_right + 2, height - margin_bottom - lineHeight / 2, margin_right - 14, lineHeight, Qt::AlignLeft, qs.sprintf("%d", minHr));
3014
	   }
88 andreas 3015
	}
3016
 
3017
	paint.setPen(QPen(mark, 1, QPen::SolidLine));
3018
 
3019
	// Grid horizontal
218 andreas 3020
	int factor = 0;
3021
	int target = 0;
3022
 
222 andreas 3023
	if (cuType == 0)	// Elevation and heart rate
218 andreas 3024
	{
222 andreas 3025
	   factor = (meter) ? (maxHeight - minHeight) / (rh / 12) : (maxHr - minHr) / (rh / 12);
3026
	   target = (meter) ? (int)(maxHeight - minHeight) : (maxHr - minHr);
3027
	}
3028
	else if (cuType == 1)	// Speed and heart rate
3029
	{
218 andreas 3030
	   factor = (meter) ? (maxSpeed - minSpeed) / (rh / 12) : (maxHr - minHr) / (rh / 12);
3031
	   target = (meter) ? (int)(maxSpeed - minSpeed) : (maxHr - minHr);
3032
	}
222 andreas 3033
	else			// Elevation and speed
218 andreas 3034
	{
222 andreas 3035
	   factor = (meter) ? (maxHeight - minHeight) / (rh /12) : (maxSpeed - minSpeed) / (rh / 12);
3036
	   target = (meter) ? (int)(maxHeight - minHeight) : (int)(maxSpeed - minSpeed);
218 andreas 3037
	}
3038
 
222 andreas 3039
	// To prevent a division by zero error, we check the <factor>
3040
	if (factor == 0)
3041
	   factor = 1;
3042
 
3043
	// Beside the horizontal part of the grid, we draw the scale on the
3044
	// left and the right side.
88 andreas 3045
	int oldy = height;
3046
 
3047
	for (i = 0; i < target; i++)
3048
	{
3049
	   if (i > 0 && !(i % factor))
3050
	   {
3051
	      x1 = margin_left + 1;
3052
	      x2 = width - margin_right - 1;
3053
	      y1 = y2 = rh - h_tick * i;
3054
 
3055
	      if (y1 < 12)
3056
		 break;
3057
 
3058
	      paint.drawLine(x1, y1, x2, y2);
3059
 
3060
	      if (y1 < (oldy - lineHeight))
3061
	      {
3062
		 if (meter)
3063
		 {
3064
		    paint.setPen(QPen(barcol, 1, QPen::SolidLine));
222 andreas 3065
		    // left side
218 andreas 3066
		    if (cuType == 1)
222 andreas 3067
		    {
3068
		       paint.setPen(QPen(red, 1, QPen::SolidLine));
3069
		       paint.drawText(12, y1 - lineHeight / 2, margin_left - 14, lineHeight, Qt::AlignRight, qs.sprintf("%.1f", minSpeed + i));
3070
		    }
218 andreas 3071
		    else
3072
		       paint.drawText(12, y1 - lineHeight / 2, margin_left - 14, lineHeight, Qt::AlignRight, qs.sprintf("%.0f", (Units == 1) ? (minHeight + i) / 0.304 : minHeight + i));
3073
 
222 andreas 3074
		    // right side
3075
		    if (maxHr > 0 && cuType != 2)
88 andreas 3076
		    {
3077
		       double hrscale = (double)(maxHr - minHr) / (double)target;
3078
		       paint.setPen(QPen(blue, 1, QPen::SolidLine));
3079
		       paint.drawText(width - margin_right + 2, y1 - lineHeight / 2, margin_right - 14, lineHeight, Qt::AlignLeft, qs.sprintf("%d", (int)((double)minHr + hrscale * (double)i)));
3080
		    }
222 andreas 3081
		    else
3082
		    {
3083
		       double spscale = (maxSpeed - minSpeed) / (double)target;
3084
 
3085
		       if (cuType == 2)
3086
			  paint.setPen(QPen(red, 1, QPen::SolidLine));
3087
		       else
3088
			  paint.setPen(QPen(blue, 1, QPen::SolidLine));
3089
 
3090
		       paint.drawText(width - margin_right + 2, y1 - lineHeight / 2, margin_right - 14, lineHeight, Qt::AlignLeft, qs.sprintf("%.1f", (minSpeed + spscale * (double)i)));
3091
		    }
88 andreas 3092
		 }
3093
		 else
3094
		 {
222 andreas 3095
		    // right side
3096
		    if (cuType == 2)
3097
		    {
3098
		       paint.setPen(QPen(red, 1, QPen::SolidLine));
3099
		       paint.drawText(width - margin_right + 2, y1 - lineHeight / 2, margin_right - 14, lineHeight, Qt::AlignLeft, qs.sprintf("%.1f", minSpeed + i));
3100
		    }
3101
		    else
3102
		    {
3103
		       paint.setPen(QPen(blue, 1, QPen::SolidLine));
3104
		       paint.drawText(width - margin_right + 2, y1 - lineHeight / 2, margin_right - 14, lineHeight, Qt::AlignLeft, qs.sprintf("%d", minHr + i));
3105
		    }
88 andreas 3106
 
222 andreas 3107
		    // left side
3108
		    if ((cuType == 0 || cuType == 2) && max_height > 0)
88 andreas 3109
		    {
3110
		       double hrscale = (maxHeight - minHeight) / (double)target;
3111
		       paint.setPen(QPen(barcol, 1, QPen::SolidLine));
3112
		       paint.drawText(12, y1 - lineHeight / 2, margin_left - 14, lineHeight, Qt::AlignRight, qs.sprintf("%.0f", minHeight + hrscale * (double)i));
3113
		    }
222 andreas 3114
		    else if (max_speed > 0 && cuType == 1)
218 andreas 3115
		    {
3116
		       double hrscale = (maxSpeed - minSpeed) / (double)target;
222 andreas 3117
		       paint.setPen(QPen(red, 1, QPen::SolidLine));
3118
		       paint.drawText(12, y1 - lineHeight / 2, margin_left - 14, lineHeight, Qt::AlignRight, qs.sprintf("%.1f", minSpeed + hrscale * (double)i));
218 andreas 3119
		    }
88 andreas 3120
		}
3121
 
3122
		 paint.setPen(QPen(mark, 1, QPen::SolidLine));
3123
		 oldy = y1;
3124
	      }
3125
	   }
3126
	}
3127
 
168 andreas 3128
	// To make our graphics more beautiful, we draw lines for the
88 andreas 3129
	// heart rate limits and the average heart rate.
222 andreas 3130
	if (max_hr > 0 && cuType != 2)
88 andreas 3131
	{
3132
	int ay1, ay2, ay3, ay4, ay5;
3133
 
3134
	   x1 = margin_left + 1;
3135
	   x2 = width - margin_right - 1;
3136
 
3137
	   if (meter)
3138
	   {
3139
	      double hrscale = rh / (double)(maxHr - minHr);
3140
	      ay1 = (double)rh - (double)(lower1 - minHr) * hrscale;
3141
	      ay2 = (double)rh - (double)(lower2 - minHr) * hrscale;
3142
	      ay3 = (double)rh - (double)(lower3 - minHr) * hrscale;
3143
	      ay4 = (double)rh - (double)(upper3 - minHr) * hrscale;
3144
	      ay5 = (double)rh - (double)(avg_hr - minHr) * hrscale;
3145
	   }
3146
	   else
3147
	   {
3148
	      ay1 = (double)rh - (double)(lower1 - minHr) * h_tick;
3149
	      ay2 = (double)rh - (double)(lower2 - minHr) * h_tick;
3150
	      ay3 = (double)rh - (double)(lower3 - minHr) * h_tick;
3151
	      ay4 = (double)rh - (double)(upper3 - minHr) * h_tick;
3152
	      ay5 = (double)rh - (double)(avg_hr - minHr) * h_tick;
3153
	   }
3154
 
3155
	   paint.setPen(QPen(barcol2, 1, QPen::DashLine));	// color for limits
3156
 
3157
	   if (lower1 > minHr && lower1 < maxHr)
3158
	      paint.drawLine(x1, ay1, x2, ay1);
3159
 
3160
	   if (lower2 > minHr && lower2 < maxHr)
3161
	      paint.drawLine(x1, ay2, x2, ay2);
3162
 
3163
	   if (lower3 > minHr && lower3 < maxHr)
3164
	      paint.drawLine(x1, ay3, x2, ay3);
3165
 
3166
	   if (upper3 > minHr && upper3 < maxHr)
3167
	      paint.drawLine(x1, ay4, x2, ay4);
3168
 
3169
	   paint.setPen(QPen(red, 1, QPen::DashDotLine));	// color for average heart rate
3170
 
3171
	   if (avg_hr > minHr && avg_hr < maxHr)
3172
	      paint.drawLine(x1, ay5, x2, ay5);
3173
	}
3174
 
3175
	// Now we have a grid and we've done the scaling.
3176
	// This is the point where we draw the curves itself.
223 andreas 3177
	// We use different colors to draw the lines:
3178
	//
3179
	// Green: Elevation
3180
	// Red:   Speed
3181
	// Blue   Heart Rate
3182
	//
88 andreas 3183
	x1 = x2 = y1 = y2 = 0;
148 andreas 3184
	int hy1, hy2, hx1, hx2;
222 andreas 3185
	int sy1, sy2, sx1, sx2;
88 andreas 3186
	hy1 = hy2 = hx1 = hx2 = 0;
222 andreas 3187
	sy1 = sy2 = sx1 = sx2 = 0;
169 andreas 3188
	int hEc = 0;
3189
	i = 0;
3190
	AVGHEIGHT *avgHakt, *avgHfirst, *avgHlast, *avgHeight = 0;
170 andreas 3191
	avgHfirst = avgHlast = 0;
169 andreas 3192
	// To even the surface lines, we store every altitude in the
3193
	// memory, by building a chain. Then, if the user has set in the
3194
	// settings (Contour == true), we will even the line by calculating
3195
	// the average of 10 messure points and setting every value to the
3196
	// average, who is up or down more than 2 meters from the average.
3197
	while ((point = ds.getPoint(i)) != 0)
3198
	{
3199
	   if (point->alt > 20000.0 || point->alt < -1000.0)
3200
	   {
3201
	      i++;
3202
	      continue;
3203
	   }
168 andreas 3204
 
169 andreas 3205
	   if (!avgHeight)
3206
	   {
3207
	      avgHeight = new AVGHEIGHT;
3208
	      avgHeight->alt = point->alt;
3209
	      avgHeight->pos = hEc;
3210
	      avgHeight->prev = 0;
3211
	      avgHeight->next = 0;
3212
	      avgHakt = avgHeight;
3213
	      avgHfirst = avgHeight;
3214
	   }
3215
	   else
3216
	   {
3217
	      avgHakt = new AVGHEIGHT;
3218
	      avgHakt->alt = point->alt;
3219
	      avgHakt->pos = hEc;
3220
	      avgHakt->next = 0;
3221
	      avgHakt->prev = avgHeight;
3222
	      avgHeight->next = avgHakt;
3223
	      avgHeight = avgHakt;
3224
	   }
3225
 
3226
	   // FIXME: Currently we can not draw below 0 meters, because the
3227
	   // base line is always 0!
222 andreas 3228
	   if (avgHakt->alt < minHeight)
3229
	      avgHakt->alt = minHeight;
169 andreas 3230
 
3231
	   hEc++;
3232
	   i++;
3233
	}
3234
 
3235
	avgHlast = avgHeight;
3236
	// If wanted, even the lines
218 andreas 3237
	if (Contour && hEc > 0 && cuType != 0)
169 andreas 3238
	{
213 andreas 3239
	double alt[100], avg, avg1, avg2, avg3, avg4;
3240
	int a, pos;
169 andreas 3241
 
213 andreas 3242
	   for (i = 0; i < (hEc + 100); i += 100)
169 andreas 3243
	   {
213 andreas 3244
	      avg = avg1 = avg2 = avg3 = avg4 = 0.0;
3245
	      pos = 0;
169 andreas 3246
 
213 andreas 3247
	      for (a = 0; a < 100; a++)
169 andreas 3248
	      {
3249
		 alt[a] = getAvgAlt(avgHfirst, i + a);
3250
		 avg += alt[a];
213 andreas 3251
 
3252
		 if (a < 25)
3253
		    avg1 += alt[a];
3254
		 else if (a < 50)
3255
		    avg2 += alt[a];
3256
		 else if (a < 75)
3257
		    avg3 += alt[a];
3258
		 else
3259
		    avg4 += alt[a];
169 andreas 3260
	      }
3261
 
213 andreas 3262
	      if ((i + 100) >= hEc)
169 andreas 3263
		 avg /= (double)(hEc - i) + 1.0;
3264
	      else
213 andreas 3265
		 avg /= 100.0;
169 andreas 3266
 
213 andreas 3267
	      for (a = 0; a < 100; a++)
169 andreas 3268
	      {
3269
		 if ((avgHakt = getAvgPtr(avgHfirst, i + a)) != 0)
3270
		 {
3271
		    if ((avgHakt->alt - avg) > 2 || (avgHakt->alt - avg) < -2)
3272
		       avgHakt->alt = avg;
3273
		 }
3274
	      }
3275
	   }
3276
	}
3277
 
222 andreas 3278
	// plot the elevation, speed and/or heart rate. Depends on <cuType>)
168 andreas 3279
	i = 0;
169 andreas 3280
	int j = 0;
218 andreas 3281
	POINT *oldPoint = 0;
222 andreas 3282
	double speed = 0.0;	// calculated speed
3283
	bool pause = false;	// filter pause out of speed
3284
	unsigned long t1, t2;
3285
	t1 = t2 = 0;
218 andreas 3286
 
88 andreas 3287
	while ((point = ds.getPoint(i)) != 0)
3288
	{
218 andreas 3289
	   if (!oldPoint)
3290
	      oldPoint = point;
3291
 
88 andreas 3292
	   // calculate the y position based on the time
3293
	   qt = garmin_dtime(point->time);
3294
	   secs = zeit.secsTo(qt->time());
3295
	   delete qt;
3296
	   x2 = secs * w_tick + margin_left + 1;
3297
	   hx2 = x2;
222 andreas 3298
	   sx2 = x2;
88 andreas 3299
 
3300
	   if (x1 == 0)
3301
	      x1 = x2;
3302
 
3303
	   if (hx1 == 0)
3304
	      hx1 = hx2;
3305
 
222 andreas 3306
	   if (sx1 == 0)
3307
	      sx1 = sx2;
3308
 
3309
	   // The speed is not very exact, because smallest time is
3310
	   // one second. This allows a maximum error of 99 hundredths
3311
	   // of a second, what is very close to one second. Because of
3312
	   // this, speed seems to hop for every messure point. This
3313
	   // looks ugly, but currently I don't know how to make it
3314
	   // better.
3315
	   if (cuType == 1 || cuType == 2)	// Draw speed?
88 andreas 3316
	   {
218 andreas 3317
	      double dist;
3318
	      double sc;
168 andreas 3319
 
222 andreas 3320
	      if (!pause && point->distance > 1.0e10)
218 andreas 3321
	      {
222 andreas 3322
		 pause = true;
3323
		 t1 = point->time;
3324
	      }
3325
	      else if (pause)
3326
	      {
3327
		 pause = false;
3328
		 t2 = point->time;
3329
		 i += 2;
3330
		 continue;
3331
	      }
3332
 
3333
	      if (point->distance >= 0.1 && point->distance < 1.0e10)
3334
	      {
218 andreas 3335
		 dist = point->distance - oldPoint->distance;
3336
		 sc = point->time - oldPoint->time;
223 andreas 3337
		 LAP *runde = ds.getLapT (point->time);
222 andreas 3338
 
3339
		 if (t2 > t1)
3340
		 {
3341
		    sc -= t2 - t1;
3342
 
3343
		    if (sc <= 0.0)
3344
		       sc = 1.0;		// at least 1 second!
3345
		 }
3346
 
218 andreas 3347
		 speed = (dist / sc) * 3.6;
168 andreas 3348
 
223 andreas 3349
		 if (runde && runde->max_speed > 0.0 && speed > (runde->max_speed * 3.6))
3350
		    speed = runde->max_speed * 3.6;
3351
 
218 andreas 3352
		 if (Units == 1)
3353
		    speed /= 1.609344;
3354
 
222 andreas 3355
		 if (speed < minSpeed || speed > 400.0)
3356
		    speed = minSpeed;
218 andreas 3357
 
222 andreas 3358
		 if ((meter && cuType == 1) || (!meter && cuType == 2))
218 andreas 3359
		    y2 = (double)rh - (speed - minSpeed) * h_tick;
3360
		 else
3361
		 {
3362
		    double hrscale = rh / (maxSpeed - minSpeed);
3363
		    y2 = (double)rh - (speed - minSpeed) * hrscale;
3364
		 }
3365
 
3366
		 if (y1 == 0)
3367
		    y1 = y2;
3368
 
222 andreas 3369
		 paint.setPen(QPen(red, 1, QPen::SolidLine));
218 andreas 3370
		 paint.drawLine(x1, y1, x2, y2);
3371
		 y1 = y2;
3372
		 x1 = x2;
222 andreas 3373
		 t1 = t2 = 0;
3374
		 oldPoint = point;
218 andreas 3375
	      }
3376
	   }
222 andreas 3377
 
3378
	   if (cuType == 0 || cuType == 2)		// Draw elevation?
218 andreas 3379
	   {
3380
	      if (point->alt < 20000.0 && point->alt > -1000.0)
88 andreas 3381
	      {
218 andreas 3382
	      double alt = getAvgAlt(avgHfirst, j);
88 andreas 3383
 
218 andreas 3384
		 j++;
3385
 
3386
		 if (meter)
222 andreas 3387
		    sy2 = (double)rh - (alt - minHeight) * h_tick;
218 andreas 3388
		 else
3389
		 {
3390
		    double hrscale = rh / (maxHeight - minHeight);
222 andreas 3391
		    sy2 = (double)rh - (alt - minHeight) * hrscale;
218 andreas 3392
		 }
3393
 
222 andreas 3394
		 if (sy1 == 0)
3395
		    sy1 = sy2;
218 andreas 3396
 
3397
		 paint.setPen(QPen(barcol, 1, QPen::SolidLine));
222 andreas 3398
		 paint.drawLine(sx1, sy1, sx2, sy2);
3399
		 sy1 = sy2;
3400
		 sx1 = sx2;
218 andreas 3401
	      }
88 andreas 3402
	   }
3403
 
222 andreas 3404
	   if (point->heart_rate > 0 && cuType < 2)	// Draw heart rate?
88 andreas 3405
	   {
3406
	      if (meter)
3407
	      {
3408
		 double hrscale = rh / (double)(maxHr - minHr);
3409
		 hy2 = (double)rh - (double)(point->heart_rate - minHr) * hrscale;
3410
	      }
3411
	      else
3412
		 hy2 = (double)rh - (double)(point->heart_rate - minHr) * h_tick;
3413
 
3414
	      if (hy1 == 0)
3415
		 hy1 = hy2;
3416
 
3417
	      paint.setPen(QPen(blue, 1, QPen::SolidLine));
3418
	      paint.drawLine(hx1, hy1, hx2, hy2);
3419
	      hy1 = hy2;
3420
	      hx1 = hx2;
3421
	   }
3422
 
3423
	   i++;
3424
	}
3425
 
3426
	paint.end();
3427
	imgProfile->setPixmap(pmProfile);
3428
 
169 andreas 3429
	// free the chain of altitudes
3430
	avgHakt = avgHfirst;
3431
 
3432
	while (avgHakt)
3433
	{
3434
	   avgHeight = avgHakt->next;
3435
	   delete avgHakt;
3436
	   avgHakt = avgHeight;
3437
	}
3438
 
88 andreas 3439
//	if (bProfile)
3440
//	   bitBlt(imgProfile, 0, 0, &pmProfile);
3441
}
3442
 
169 andreas 3443
double sportwatcherWidget::getAvgAlt(AVGHEIGHT *avgHeight, int pos)
3444
{
3445
AVGHEIGHT *akt;
3446
 
170 andreas 3447
	if (!avgHeight)
3448
	   return 0.0;
3449
 
169 andreas 3450
	akt = avgHeight;
3451
 
3452
	while (akt)
3453
	{
3454
	   if (akt->pos == pos)
3455
	      return akt->alt;
3456
 
3457
	   akt = akt->next;
3458
	}
3459
 
3460
	return 0.0;
3461
}
3462
 
3463
AVGHEIGHT *sportwatcherWidget::getAvgPtr(AVGHEIGHT *avgHeight, int pos)
3464
{
3465
AVGHEIGHT *akt;
3466
 
3467
	akt = avgHeight;
3468
 
3469
	while (akt)
3470
	{
3471
	   if (akt->pos == pos)
3472
	      return akt;
3473
 
3474
	   akt = akt->next;
3475
	}
3476
 
3477
	return 0;
3478
}
3479
 
88 andreas 3480
void sportwatcherWidget::resizeEvent(QResizeEvent */* *e */)
3481
{
132 andreas 3482
	showTrack(zfactor);
88 andreas 3483
	showCurves();
3484
}
3485
 
3486
void sportwatcherWidget::paintEvent(QPaintEvent */* *e */)
3487
{
132 andreas 3488
	showTrack(zfactor);
88 andreas 3489
	showCurves();
3490
}
3491
 
132 andreas 3492
void sportwatcherWidget::mouseMoveEvent(QMouseEvent *e)
3493
{
3494
QPoint pos(0, 0);
3495
QPoint ev = imgMap->mapFrom(this, e->pos());
3496
static QRect coord;
88 andreas 3497
 
132 andreas 3498
	if (!stateHand)
3499
	   return;
3500
 
3501
	if (ev.x() >= pos.x() &&
3502
	    ev.y() >= pos.y() &&
3503
	    ev.x() <= (pos.x() + imgMap->geometry().width()) &&
3504
	    ev.y() <= (pos.y() + imgMap->geometry().height()))
3505
	{
3506
	   if (lmbPressed == 1)
3507
	   {
3508
	      coord.setCoords(ev.x(), ev.y(), 0, 0);
3509
	      lmbPressed = 0;
3510
	   }
3511
	   else
3512
	   {
3513
	      coord.setRight(ev.x());
3514
	      coord.setBottom(ev.y());
3515
	   }
3516
 
3517
	   if (lmbPressed == 2)
3518
	   {
3519
	      showTrack(zfactor, coord, mapLap);
3520
	      lmbPressed = 0;
3521
	   }
3522
	}
3523
}
3524
 
3525
void sportwatcherWidget::mousePressEvent(QMouseEvent *e)
3526
{
3527
	if (stateHand && e->button() == QMouseEvent::LeftButton)
3528
	   lmbPressed = 1;	// Left Mouse Button is pressed
3529
	else if (stateHand)
3530
	   lmbPressed = 0;	// Wrong button is pressed
3531
 
3532
	if (stateGlas)
3533
	{
3534
	   if (e->button() == QMouseEvent::LeftButton)
3535
	      btGlasPlusSlot();
3536
	   else if (e->button() == QMouseEvent::RightButton)
3537
	      btGlasMinusSlot();
3538
	}
3539
}
3540
 
3541
void sportwatcherWidget::mouseReleaseEvent(QMouseEvent *e)
3542
{
3543
	if (stateHand && e->button() == QMouseEvent::LeftButton)
3544
	{
3545
	   lmbPressed = 2;	// Left Mouse Button was released
3546
	   mouseMoveEvent(e);
3547
	}
3548
}
3549
 
88 andreas 3550
/*
3551
 * Private functions to help decode the data
3552
 */
3553
QDateTime *sportwatcherWidget::garmin_dtime (uint32 t)
3554
{
3555
time_t     tval;
3556
struct tm  tmval;
3557
QTime ti;
3558
QDate dt;
3559
QDateTime *qt;
3560
 
3561
	if (t == 0)
3562
	   return new QDateTime(QDate(1900, 1, 1), QTime(0, 0, 0, 0));
3563
 
3564
	tval = t + TIME_OFFSET;
3565
	localtime_r (&tval, &tmval);
3566
	qt = new QDateTime();
3567
	qt->setDate(QDate(tmval.tm_year+1900, tmval.tm_mon+1, tmval.tm_mday));
3568
	qt->setTime(QTime(tmval.tm_hour, tmval.tm_min, tmval.tm_sec, 0));
3569
	/* OK.  Done. */
3570
	return qt;
3571
}
3572
 
104 andreas 3573
bool sportwatcherWidget::writeTag(const QFile &fn, const QString &str, int indent)
3574
{
3575
QString qs;
3576
char *p = new char[str.length()+100];
3577
QCString qcs;
3578
int i;
88 andreas 3579
 
171 andreas 3580
	if (indent > 0)
3581
	   qs.fill(' ', indent * 3);
3582
 
104 andreas 3583
	qs.append(str);
3584
	qcs = qs.utf8();
3585
	qstrcpy(p, qcs);
3586
	i = strlen(p);
3587
 
3588
	if (write(fn.handle(), p, i) != i)
3589
	{
3590
	   delete p;
3591
	   return false;
3592
	}
3593
 
3594
	delete p;
3595
	return true;
3596
}
3597
 
155 andreas 3598
#if defined HAVE_GDAL && HAVE_LIBGDAL1_5_0
151 andreas 3599
bool sportwatcherWidget::writeWMSTag(double llat, double llon, double rlat, double rlon, int width, int height)
3600
{
3601
QFile fl(MAP);
152 andreas 3602
QString xml, s, srs, crs, styles, bSize, ext;
3603
QDir dir = QDir::home();
3604
QString path = dir.absPath();
157 andreas 3605
int item, isrs;
3606
double _llat, _llon, _rlat, _rlon;
3607
bool offline, square;
151 andreas 3608
 
3609
	if (!fl.open(IO_ReadWrite | IO_Truncate))
3610
	{
3611
	   KMessageBox::error (this, i18n("Error opening or creating the WMS tag file!\nPlease check file name and/or permissions."));
3612
	   return false;
3613
	}
3614
 
152 andreas 3615
	KSimpleConfig *cfg = new KSimpleConfig(QString("sportwatcher.rc"));
3616
	cfg->setGroup(QString("WMS"));
157 andreas 3617
	square = cfg->readBoolEntry("Square", false);
152 andreas 3618
	styles = cfg->readEntry("Styles");
3619
 
151 andreas 3620
	xml = "<GDAL_WMS>\n";
3621
	xml += "   <Service name=\"WMS\">\n";
3622
	xml += "      <Version>1.1.1</Version>\n";
152 andreas 3623
	xml += "      <ServerURL>" + cfg->readEntry("ServerURL", "http://onearth.jpl.nasa.gov/wms.cgi") + "?</serverURL>\n";
157 andreas 3624
	isrs = cfg->readNumEntry("SRS", 0);
3625
	_llon = llon;
3626
	_llat = llat;
3627
	_rlon = rlon;
3628
	_rlat = rlat;
3629
	offline = false;
152 andreas 3630
 
157 andreas 3631
	switch (isrs)
152 andreas 3632
	{
3633
	   case 0: srs = QString("EPSG:4326"); break;
157 andreas 3634
 
3635
	   case 1:
3636
	      srs = QString("EPSG:31257");
3637
	      offline = transCoords(&_llat, &_llon, &_rlat, &_rlon, 31257, width, height, square);
3638
	   break;
3639
 
3640
	   case 2:
3641
	      srs = QString("EPSG:31258");
3642
	      offline = transCoords(&_llat, &_llon, &_rlat, &_rlon, 31258, width, height, square);
3643
	   break;
3644
 
3645
	   case 3:
3646
	      srs = QString("EPSG:31259");
3647
	      offline = transCoords(&_llat, &_llon, &_rlat, &_rlon, 31259, width, height, square);
3648
	   break;
3649
 
3650
	   case 4:
3651
	      srs = QString("EPSG:31286");
3652
	      offline = transCoords(&_llat, &_llon, &_rlat, &_rlon, 31286, width, height, square);
3653
	   break;
3654
 
3655
	   case 5:
3656
	      srs = QString("EPSG:31287");
3657
	      offline = transCoords(&_llat, &_llon, &_rlat, &_rlon, 31287, width, height, square);
3658
	   break;
3659
 
3660
	   case 6:
3661
	      srs = QString("EPSG:31288");
3662
	      offline = transCoords(&_llat, &_llon, &_rlat, &_rlon, 31288, width, height, square);
3663
	   break;
3664
 
152 andreas 3665
	   default: srs = QString("EPSG:4326");
3666
	}
3667
 
3668
	xml += "      <SRS>" + srs + "</SRS>\n";
3669
	item = cfg->readNumEntry("CRS", 0);
3670
 
3671
	switch (item)
3672
	{
3673
	   case 0: crs = QString("CRS:83"); break;
157 andreas 3674
	   case 1: crs = QString("CRS:84"); break;
3675
	   case 2: crs = QString("EPSG:4326"); break;
3676
	   case 3: crs = QString("EPSG:31259"); break;
3677
	   case 4: crs = QString("EPSG:31287"); break;
152 andreas 3678
	   default: crs = QString("CRS:83"); break;
3679
	}
3680
 
3681
	xml += "      <CRS>" + crs + "</CRS>\n";
3682
	item = cfg->readNumEntry("Image", 2);
3683
	xml += "      <ImageFormat>image/";
3684
 
3685
	switch (item)
3686
	{
3687
	   case 0: xml += "gif"; ext = QString(".gif"); break;
3688
	   case 1: xml += "jpeg"; ext = QString(".jpg"); break;
3689
	   case 2: xml += "png"; ext = QString(".png"); break;
3690
	   case 3: xml += "tiff"; ext = QString(".tif"); break;
3691
	   default: xml += "png"; ext = QString(".png");
3692
	}
3693
 
3694
	xml += "</ImageFormat>\n";
3695
 
3696
	xml += "      <Layers>" + cfg->readEntry("Layer") + "</Layers>\n";
3697
 
3698
	if (!styles.isEmpty())
3699
	   xml += "      <Styles>" + styles + "</Styles>\n";
3700
 
151 andreas 3701
	xml += "      <BBoxOrder>xyXY</BBoxOrder>\n";
3702
	xml += "   </Service>\n";
3703
	xml += "   <DataWindow>\n";
157 andreas 3704
	s.sprintf ("%f", _llat);
151 andreas 3705
	xml += "      <UpperLeftX>" + s + "</UpperLeftX>\n";
157 andreas 3706
	s.sprintf ("%f", _llon);
151 andreas 3707
	xml += "      <UpperLeftY>" + s + "</UpperLeftY>\n";
157 andreas 3708
	s.sprintf ("%f", _rlat);
151 andreas 3709
	xml += "      <LowerRightX>" + s + "</LowerRightX>\n";
157 andreas 3710
	s.sprintf ("%f", _rlon);
151 andreas 3711
	xml += "      <LowerRightY>" + s + "</LowerRightY>\n";
3712
	s.sprintf ("%d", width);
3713
	xml += "      <SizeX>" + s + "</SizeX>\n";
3714
	s.sprintf ("%d", height);
3715
	xml += "      <SizeY>" + s + "</SizeY>\n";
3716
	xml += "   </DataWindow>\n";
157 andreas 3717
 
3718
/*	switch (isrs)
3719
	{
3720
	   case 0: srs = QString("EPSG:4326"); break;
3721
	   case 1: srs = QString("EPSG:31259"); break;
3722
	   case 2: srs = QString("EPSG:31286"); break;
3723
	   case 3: srs = QString("EPSG:31287"); break;
3724
	   case 4: srs = QString("EPSG:31288"); break;
3725
	   default: srs = QString("EPSG:4326");
3726
	}
3727
*/
3728
//	srs = QString("EPSG:4326");
3729
	xml += "   <Projection>" + srs + "</Projection>\n";
152 andreas 3730
	xml += "   <BandsCount>" + cfg->readEntry("Bands", "3") + "</BandsCount>\n";
3731
	item = cfg->readNumEntry("Tile", 2);
3732
 
3733
	switch (item)
3734
	{
3735
	   case 0: bSize = QString("64"); break;
3736
	   case 1: bSize = QString("128"); break;
3737
	   case 2: bSize = QString("256"); break;
3738
	   case 3: bSize = QString("512"); break;
3739
	   case 4: bSize = QString("1024"); break;
3740
	   default: bSize = QString("256");
3741
	}
3742
 
3743
	xml += "   <BlockSizeX>" + bSize + "</BlockSizeX>\n";
3744
	xml += "   <BlockSizeY>" + bSize + "</BlockSizeY>\n";
3745
	xml += "   <OverviewCount>" + cfg->readEntry("Overview", "10") + "</OverviewCount>\n";
151 andreas 3746
	xml += "   <Cache>\n";
152 andreas 3747
	xml += "      <Path>" + path + "/.gdalwmscache" + "</Path>\n";
3748
	xml += "      <Depth>" + cfg->readEntry("Depth", "2") + "</Depth>\n";
3749
	xml += "      <Extension>" + ext + "</Extension>\n";
151 andreas 3750
	xml += "   </Cache>\n";
152 andreas 3751
	QString off((cfg->readBoolEntry("Offline", false)) ? "true" : "false");
3752
	QString adv((cfg->readBoolEntry("Advice", false)) ? "true" : "false");
3753
	QString ver((cfg->readBoolEntry("Verify", true)) ? "true" : "false");
157 andreas 3754
 
3755
	if (offline)
3756
	   xml += "   <OfflineMode>true</OfflineMode>\n";
3757
	else
3758
	   xml += "   <OfflineMode>" + off + "</OfflineMode>\n";
3759
 
152 andreas 3760
	xml += "   <AdviseRead>" + adv + "</AdviseRead>\n";
3761
	xml += "   <VerifyAdviseRead>" + ver + "</VerifyAdviseRead>\n";
151 andreas 3762
	xml += "</GDAL_WMS>\n";
3763
 
3764
	write (fl.handle(), xml.ascii(), strlen (xml.ascii()));
3765
	fl.close();
152 andreas 3766
	delete cfg;
151 andreas 3767
	return true;
3768
}
3769
 
157 andreas 3770
bool sportwatcherWidget::transCoords (double *x1, double *y1, double *x2, double *y2, int code, int width, int height, bool square)
151 andreas 3771
{
157 andreas 3772
OGRSpatialReference oSourceSRS, oTargetSRS;
3773
OGRCoordinateTransformation *poCT;
3774
 
3775
	oSourceSRS.SetWellKnownGeogCS ("WGS84");
3776
	oTargetSRS.importFromEPSG(code);
3777
	poCT = OGRCreateCoordinateTransformation (&oSourceSRS, &oTargetSRS);
3778
 
3779
	if (poCT == NULL || !poCT->Transform( 1, x1, y1))
3780
	{
3781
	   KMessageBox::error(this, i18n("Translation between coordinate systems failed!"));
3782
 
3783
	   if (poCT != NULL)
3784
	      delete poCT;
3785
 
3786
	   return true;
3787
	}
3788
 
3789
	if (poCT != NULL)
3790
	{
3791
	   poCT->Transform (1, x2, y2);
3792
	   delete poCT;
3793
	}
3794
 
3795
	if (square)
3796
	{
3797
	double wdiff = (double)((long)(*x1 - *x2) / (width / 2 * 2) * (width / 2 * 2));
3798
	double hdiff = (double)((long)(*y2 - *y1) / (height / 2 * 2) * (height / 2 * 2));
3799
 
3800
	   *x2 = *x1 - wdiff; // * (double)mFactor;
3801
	   *y2 = *y1 + hdiff; // * (double)mFactor;
3802
//	   *x2 = *x1 - (double)((long)(wdiff / mFactor * mFactor));
3803
//	   *y2 = *y1 - (double)((long)(hdiff / mFactor * mFactor));
3804
/*	   wdiff = wdiff - (*x1 - *x2);
3805
	   hdiff = hdiff - (*y2 - *y1);
3806
	   *x1 -= wdiff / 2.0;
3807
	   *x2 -= wdiff / 2.0;
3808
	   *y1 += hdiff / 2.0;
3809
	   *y2 += hdiff / 2.0; */
3810
	}
3811
 
3812
	return false;
151 andreas 3813
}
3814
 
158 andreas 3815
QString *sportwatcherWidget::getProjection (int isrs, QString *srs)
3816
{
3817
	switch (isrs)
3818
	{
3819
	   case 0: *srs = QString("EPSG:4326"); break;
3820
	   case 1: *srs = QString("EPSG:31257"); break;
3821
	   case 2: *srs = QString("EPSG:31258"); break;
3822
	   case 3: *srs = QString("EPSG:31259"); break;
3823
	   case 4: *srs = QString("EPSG:31286"); break;
3824
	   case 5: *srs = QString("EPSG:31287"); break;
3825
	   case 6: *srs = QString("EPSG:31288"); break;
3826
	   default: *srs = QString("EPSG:4326");
3827
	}
3828
 
3829
	return srs;
3830
}
3831
 
3832
bool sportwatcherWidget::warpImage(QString fn, QString *fName)
3833
{
3834
GDALDatasetH  hSrcDS, hDstDS;
3835
GDALDataset *inSet, *outSet;
3836
GDALDataType eDT;
3837
GDALRasterBand *poBand;
3838
GDALDriverH hDriver;
3839
char hv0[256];
3840
int nXSize, nYSize;
3841
double adfGeoTransform[6];
3842
double oriLeftLon, oriRightLon, oriLeftLat, oriRightLat;
3843
 
159 andreas 3844
 
3845
	// Loading the user set geo coords of our source image and
3846
	// load the projection used for that image
3847
	KSimpleConfig *cfg = new KSimpleConfig(QString("sportwatcher.rc"));
3848
	cfg->setGroup(QString("ImageCoords"));
3849
	oriLeftLon = cfg->readDoubleNumEntry("LeftLon", 0.0);
3850
	oriLeftLat = cfg->readDoubleNumEntry("LeftLat", 0.0);
3851
	oriRightLon = cfg->readDoubleNumEntry("RightLon", 0.0);
3852
	oriRightLat = cfg->readDoubleNumEntry("RightLat", 0.0);
3853
	int isrs = cfg->readNumEntry("SRS", 0);
3854
 
158 andreas 3855
	// Create a temporary file name for our output file
3856
	strcpy (hv0, "/tmp/SportWatcherTIFFXXXXXX");
216 andreas 3857
	mkdtemp (&hv0[0]);
158 andreas 3858
	*fName = QString(hv0) + ".tif";
3859
 
3860
	// Open input and output files.
3861
	if ((hSrcDS = GDALOpen(fn.ascii(), GA_ReadOnly)) == NULL)
3862
	{
3863
	   KMessageBox::error(this, i18n("Error opening an image file!"));
3864
	   return false;
3865
	}
3866
 
3867
	inSet = (GDALDataset *)hSrcDS;
3868
	// Create output with same datatype as first input band.
3869
	poBand = inSet->GetRasterBand (1);
3870
	eDT = poBand->GetRasterDataType ();
3871
 
3872
	if ((hDriver = GDALGetDriverByName ("GTiff")) == NULL)
3873
	{
3874
	   KMessageBox::error(this, i18n("Error loading the TIFF driver!"));
3875
	   GDALClose (hSrcDS);
3876
	   return false;
3877
	}
3878
 
3879
	// Get dimensions of image and set transform data
3880
	int nRasterCount = inSet->GetRasterCount();
3881
	nXSize = inSet->GetRasterXSize();
3882
	nYSize = inSet->GetRasterYSize();
3883
 
159 andreas 3884
	// cut the wanted region out of image
3885
	transform *tf = new transform (oriLeftLat, oriLeftLon, oriRightLat, oriRightLon);
3886
	tf->setDimensions(nXSize, nYSize);
158 andreas 3887
 
159 andreas 3888
	if (!tf->cutImage (geoRect.llat, geoRect.llon, geoRect.rlat, geoRect.rlon, fn))
3889
	{
3890
	   GDALClose (hSrcDS);
3891
	   return false;
3892
	}
158 andreas 3893
 
159 andreas 3894
	GDALClose (hSrcDS);
3895
	QString nfn = fn + "_tmp.png";
158 andreas 3896
 
159 andreas 3897
	// repeat the part above and open the now cutted part of the image.
3898
	// Open input and output files.
3899
	if ((hSrcDS = GDALOpen(nfn.ascii(), GA_ReadOnly)) == NULL)
3900
	{
3901
	   KMessageBox::error(this, i18n("Error opening an image file!"));
3902
	   return false;
3903
	}
158 andreas 3904
 
159 andreas 3905
	inSet = (GDALDataset *)hSrcDS;
3906
	// Create output with same datatype as first input band.
3907
	poBand = inSet->GetRasterBand (1);
3908
	eDT = poBand->GetRasterDataType ();
158 andreas 3909
 
159 andreas 3910
	if ((hDriver = GDALGetDriverByName ("GTiff")) == NULL)
158 andreas 3911
	{
159 andreas 3912
	   KMessageBox::error(this, i18n("Error loading the TIFF driver!"));
3913
	   GDALClose (hSrcDS);
3914
	   return false;
158 andreas 3915
	}
3916
 
159 andreas 3917
	// Get dimensions of image and set transform data
3918
	nRasterCount = inSet->GetRasterCount();
3919
	nXSize = inSet->GetRasterXSize();
3920
	nYSize = inSet->GetRasterYSize();
3921
 
158 andreas 3922
	// Set the values needed to transform the image
3923
	OGRSpatialReference iSRS;
3924
	const char *iWKT;
3925
 
3926
	switch (isrs)
3927
	{
3928
	   case 0: iSRS.importFromEPSG(4326); break;
3929
	   case 1: iSRS.importFromEPSG(31257); break;
3930
	   case 2: iSRS.importFromEPSG(31258); break;
3931
	   case 3: iSRS.importFromEPSG(31259); break;
3932
	   case 4: iSRS.importFromEPSG(31286); break;
3933
	   case 5: iSRS.importFromEPSG(31287); break;
3934
	   case 6: iSRS.importFromEPSG(31288); break;
3935
	   default: iSRS.importFromEPSG(4326);
3936
	}
3937
 
3938
	iSRS.exportToWkt ((char **)&iWKT);
3939
 
3940
	if (inSet->SetProjection (iWKT) != CE_None)
3941
	{
3942
	   KMessageBox::error(this, i18n("Error setting projection on source!"));
3943
	   GDALClose (hSrcDS);
3944
	   return false;
3945
	}
3946
 
159 andreas 3947
	adfGeoTransform[0] = geoRect.llon;
3948
	adfGeoTransform[1] = (geoRect.rlon - geoRect.llon) / (double)nXSize;
158 andreas 3949
	adfGeoTransform[2] = 0.0;
159 andreas 3950
	adfGeoTransform[3] = geoRect.llat;
158 andreas 3951
	adfGeoTransform[4] = 0.0;
159 andreas 3952
	adfGeoTransform[5] = -1.0 * ((geoRect.llat - geoRect.rlat) / (double)nYSize);
158 andreas 3953
 
3954
	if (inSet->SetGeoTransform (&adfGeoTransform[0]) != CE_None)
3955
	{
3956
	   KMessageBox::error(this, i18n("Error setting geo transform data to source!"));
3957
	   GDALClose (hSrcDS);
3958
	   return false;
3959
	}
3960
 
159 andreas 3961
	// Get Source coordinate system.
158 andreas 3962
	const char *pszSrcWKT, *pszDstWKT = NULL;
3963
 
3964
	if ((pszSrcWKT = GDALGetProjectionRef (hSrcDS)) == NULL)
3965
	{
3966
	   KMessageBox::error(this, i18n("Error getting the projection reference"));
3967
	   GDALClose (hSrcDS);
3968
	   return false;
3969
	}
3970
 
3971
	// Setup output coordinate system that is UTM ? WGS84.
3972
	OGRSpatialReference oSRS;
3973
 
159 andreas 3974
//	oSRS.SetUTM( 0, TRUE );
158 andreas 3975
	oSRS.SetWellKnownGeogCS("WGS84");
3976
	oSRS.exportToWkt ((char **)&pszDstWKT);
3977
 
159 andreas 3978
	// Create the output file.
158 andreas 3979
	double adfDstGeoTransform[6];
159 andreas 3980
	adfDstGeoTransform[0] = geoRect.llon;
3981
	adfDstGeoTransform[1] = (geoRect.rlon - geoRect.llon) / (double)geoRect.width;
158 andreas 3982
	adfDstGeoTransform[2] = 0.0;
3983
	adfDstGeoTransform[3] = geoRect.llat;
3984
	adfDstGeoTransform[4] = 0.0;
159 andreas 3985
	adfDstGeoTransform[5] = -1.0 * ((geoRect.llat - geoRect.rlat) / (double)geoRect.height);
158 andreas 3986
 
159 andreas 3987
	if ((hDstDS = GDALCreate(hDriver, fName->ascii(), geoRect.width, geoRect.height,
158 andreas 3988
			nRasterCount, eDT, NULL )) == NULL)
3989
	{
3990
	   KMessageBox::error(this, i18n("Error creating a temporary image file! (" + *fName + ")"));
3991
	   GDALClose (hSrcDS);
3992
	   return false;
3993
	}
3994
 
3995
	outSet = (GDALDataset *)hDstDS;
3996
 
159 andreas 3997
	for (int i = 0; i < nRasterCount; i++)
3998
	{
3999
	   poBand = outSet->GetRasterBand (i+1);
4000
	   poBand->Fill (0.0);
4001
	}
4002
 
158 andreas 4003
	if (outSet->SetProjection (pszDstWKT) != CE_None)
4004
	{
4005
	   KMessageBox::error(this, i18n("Error setting projection on destination!"));
4006
	   GDALClose (hDstDS);
4007
	   GDALClose (hSrcDS);
4008
	   unlink (fName->ascii());
4009
	   return false;
4010
	}
4011
 
4012
	if (outSet->SetGeoTransform (&adfDstGeoTransform[0]) != CE_None)
4013
	{
159 andreas 4014
	   KMessageBox::error(this, i18n("Error setting geo transform data to destination!"));
158 andreas 4015
	   GDALClose (hDstDS);
4016
	   GDALClose (hSrcDS);
4017
	   unlink (fName->ascii());
4018
	   return false;
4019
	}
159 andreas 4020
 
158 andreas 4021
	// Copy the color table, if required.
4022
	GDALColorTableH hCT;
4023
 
4024
	for (int i = 0; i < nRasterCount; i++)
4025
	{
4026
	   hCT = GDALGetRasterColorTable (inSet->GetRasterBand (i+1));
4027
 
4028
	   if (hCT != NULL)
4029
              GDALSetRasterColorTable (outSet->GetRasterBand (i+1), hCT);
4030
	}
4031
 
4032
	// Setup warp options.
4033
	GDALWarpOptions *psWarpOptions = GDALCreateWarpOptions();
4034
 
4035
	psWarpOptions->hSrcDS = hSrcDS;
4036
	psWarpOptions->hDstDS = hDstDS;
4037
 
4038
	psWarpOptions->nBandCount = nRasterCount;
4039
	psWarpOptions->panSrcBands =
4040
        	(int *) CPLMalloc(sizeof(int) * psWarpOptions->nBandCount );
4041
	psWarpOptions->panDstBands =
4042
		(int *) CPLMalloc(sizeof(int) * psWarpOptions->nBandCount );
4043
 
4044
	for (int i = 0; i < nRasterCount; i++)
4045
	{
4046
	   psWarpOptions->panSrcBands[i] = i+1;
4047
	   psWarpOptions->panDstBands[i] = i+1;
4048
	}
4049
 
159 andreas 4050
//	psWarpOptions->pfnProgress = GDALTermProgress;
158 andreas 4051
 
4052
	// Establish reprojection transformer.
4053
	psWarpOptions->pTransformerArg =
4054
        	GDALCreateGenImgProjTransformer(hSrcDS,
4055
					 GDALGetProjectionRef(hSrcDS), 
4056
					 hDstDS,
4057
					 GDALGetProjectionRef(hDstDS),
159 andreas 4058
					 FALSE, 0.0, 1);
158 andreas 4059
 
4060
	psWarpOptions->pfnTransformer = GDALGenImgProjTransform;
4061
 
4062
	// Initialize and execute the warp operation.
4063
	GDALWarpOperation oOperation;
4064
 
4065
	if (oOperation.Initialize (psWarpOptions) != CE_None)
4066
	{
4067
	   KMessageBox::error(this, i18n("Error initializing warp operation!"));
4068
	   GDALClose (hDstDS);
4069
	   GDALClose (hSrcDS);
4070
	   unlink (fName->ascii());
4071
	   return false;
4072
	}
4073
 
159 andreas 4074
	oOperation.ChunkAndWarpMulti (0, 0, geoRect.width, geoRect.height);
158 andreas 4075
	GDALDestroyGenImgProjTransformer (psWarpOptions->pTransformerArg);
4076
	GDALDestroyWarpOptions(psWarpOptions);
4077
 
4078
	GDALClose (hDstDS);
4079
	GDALClose (hSrcDS);
159 andreas 4080
	unlink (nfn.ascii());
158 andreas 4081
	return true;
4082
}
4083
 
151 andreas 4084
#endif
4085
 
88 andreas 4086
#include "sportwatcherwidget.moc"
4087