Subversion Repositories public

Rev

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

Rev Author Line No. Line
88 andreas 1
/***************************************************************************
221 andreas 2
 *   Copyright (C) 2007 - 2009 by Andreas Theofilu                         *
119 andreas 3
 *   andreas@theosys.at                                                    *
88 andreas 4
 *                                                                         *
5
 *   This program is free software; you can redistribute it and/or modify  *
6
 *   it under the terms of the GNU General Public License as published by  *
7
 *   the Free Software Foundation version 3 of the License.                *
8
 *                                                                         *
9
 *   This program is distributed in the hope that it will be useful,       *
10
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
11
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
12
 *   GNU General Public License for more details.                          *
13
 *                                                                         *
14
 *   You should have received a copy of the GNU General Public License     *
15
 *   along with this program; if not, write to the                         *
16
 *   Free Software Foundation, Inc.,                                       *
17
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
18
 ***************************************************************************/
19
 
119 andreas 20
#include "config.h"
88 andreas 21
#include "managefile.h"
22
#include "sportwatcherwidget.h"
23
#include "settingswidget.h"
96 andreas 24
#include "progresswidget.h"
152 andreas 25
#include "wmsbase.h"
158 andreas 26
#include "coordinateswidget.h"
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)
2022
			     speed = (dist / sc) * 3.6;
2023
			  else
2024
			     speed = 0.0;
218 andreas 2025
 
222 andreas 2026
			  if (Units == 1)
2027
			     speed /= 1.609344;
218 andreas 2028
 
222 andreas 2029
			  if (speed > 0.0 && speed < 400.0 && max_speed < speed)
2030
			     max_speed = speed;
2031
 
2032
			  if (speed > 0.0 && (min_speed == 0.0 || min_speed > speed))
2033
			     min_speed = speed;
2034
 
2035
			  oldPoint = point;
2036
		       }
2037
 
2038
		       if (!pause && ignore)
2039
			  ignore = false;
2040
 
221 andreas 2041
		       if (point->heart_rate > 0 && point->heart_rate < 250)
88 andreas 2042
		       {
2043
			  avg_hr += point->heart_rate;
2044
			  men++;
2045
		       }
2046
 
2047
		       point = ds.getPoint(point->time + 1);
2048
		    }
2049
 
149 andreas 2050
		    if (old_asc < alt_asc)
2051
		       sum_asc += (alt_asc - old_asc);
2052
 
2053
		    if (old_dsc > alt_dsc)
2054
		       sum_dsc += (old_dsc - alt_dsc);
2055
 
2056
		    old_asc = alt_asc;
2057
		    old_dsc = alt_dsc;
2058
		    qs_ascent.sprintf("%.2f %s", (Units == 1) ? (alt_asc / 0.304) : alt_asc, (Units == 1) ? "ft" : "m");
2059
		    qs_descent.sprintf("%.2f %s", (Units == 1) ? (alt_dsc / 0.304) : alt_dsc, (Units == 1) ? "ft" : "m");
88 andreas 2060
		 }
2061
 
2062
		 if (lap->avg_cadence != 0xff)
2063
		    qs_avgcadence.sprintf("%d", lap->avg_cadence);
2064
 
128 andreas 2065
		 KListViewItem *edetail = new KListViewItem(element, qs_name, qs_distance,
88 andreas 2066
			qs_etime, qs_avgpace, qs_avgspeed, qs_maxspeed, qs_calories, qs_avghr);
2067
		 edetail->setText(8, qs_maxhr);
2068
		 edetail->setText(9, qs_avgcadence);
2069
		 edetail->setText(10, qs_ascent);
2070
		 edetail->setText(11, qs_descent);
128 andreas 2071
		 edetail->setPixmap(0, QPixmap::fromMimeSource(QString("history.png")));
2072
 
2073
		 switch (rakt->run->sport_type)
2074
		 {
2075
		    case D1000_running: edetail->setPixmap(0, QPixmap::fromMimeSource(QString("run.png"))); break;
2076
		    case D1000_biking:  edetail->setPixmap(0, QPixmap::fromMimeSource(QString("bike.png"))); break;
2077
		    case D1000_other:   edetail->setPixmap(0, QPixmap::fromMimeSource(QString("other.png"))); break;
2078
		    default:
2079
		       edetail->setPixmap(0, QPixmap::fromMimeSource(QString("other.png")));
2080
		 }
2081
 
88 andreas 2082
		 liLaps->clearSelection();
2083
		 element->insertItem(edetail);
2084
		 delete qt;
2085
		 laps++;
2086
	      }
149 andreas 2087
 
2088
	      qs_ascent.sprintf("%.2f %s", (Units == 1) ? sum_asc / 0.304 : sum_asc, (Units == 1) ? "ft" : "m");
2089
	      qs_descent.sprintf("%.2f %s", (Units == 1) ? sum_dsc / 0.304 : sum_dsc, (Units == 1) ? "ft" : "m");
2090
      	      element->setText(10, qs_ascent);
2091
	      element->setText(11, qs_descent);
88 andreas 2092
	   }
2093
 
2094
	   rakt = rakt->next;
2095
	}
2096
 
2097
	if (men > 0)
2098
	   avg_hr /= men;
221 andreas 2099
	else
2100
	   min_hr = max_hr = avg_hr = 0;
88 andreas 2101
}
2102
 
100 andreas 2103
void sportwatcherWidget::showTrack()
2104
{
132 andreas 2105
	showTrack(0, QRect(0, 0, 0, 0), 0);
104 andreas 2106
}
2107
 
2108
void sportwatcherWidget::showTrack(int zoom)
2109
{
132 andreas 2110
	showTrack(zoom, mapPan, mapLap);
2111
}
2112
 
2113
void sportwatcherWidget::showTrack(int zoom, const QRect &pan, LAP *lap)
2114
{
100 andreas 2115
int width, height;
2116
double x1, y1, x2, y2;
132 andreas 2117
int a, top, left, panX, panY;
2118
uint32 i;
109 andreas 2119
double coordW, coordH, tick;
156 andreas 2120
double meterW, dist, fact;
100 andreas 2121
QPainter paint;
152 andreas 2122
posn_type posNW, posSE, posLXY, posRXY;
100 andreas 2123
POINT *point;
152 andreas 2124
bool Fgeo = false;
157 andreas 2125
bool Data = false;
155 andreas 2126
#if defined HAVE_GDAL && HAVE_LIBGDAL1_5_0
158 andreas 2127
QString fName = MAP;
2128
//double adfGeoTransform[6];
2129
GDALDataset *poDataset = 0;
151 andreas 2130
GDALRasterBand *poBand;
2131
unsigned char *pafScanline;
2132
unsigned char *pafScanlineRed;
2133
unsigned char *pafScanlineGreen;
2134
unsigned char *pafScanlineBlue;
154 andreas 2135
unsigned char *pafScanlineAlpha;
151 andreas 2136
int nXSize, nYSize;
159 andreas 2137
int xOff, yOff;
158 andreas 2138
double oriLeftLon, oriLeftLat, oriRightLon, oriRightLat;
151 andreas 2139
#endif
100 andreas 2140
 
109 andreas 2141
	if (!gmn)
2142
	   return;
2143
 
154 andreas 2144
	QApplication::setOverrideCursor (QCursor(Qt::WaitCursor));
2145
 
104 andreas 2146
	if (zoom != zfactor)
2147
	   zfactor = zoom;
2148
 
132 andreas 2149
	if (mapLap != lap)
2150
	   mapLap = lap;
2151
 
157 andreas 2152
#if defined HAVE_GDAL && HAVE_LIBGDAL1_5_0
2153
	KSimpleConfig *cfg = new KSimpleConfig(QString("sportwatcher.rc"));
2154
	cfg->setGroup(QString("WMS"));
2155
	bool square = cfg->readBoolEntry("Square", false);
2156
	int CorrX = cfg->readNumEntry("CorrX", 0);
2157
	int CorrY = cfg->readNumEntry("CorrY", 0);
158 andreas 2158
	cfg->setGroup(QString("ImageCoords"));
2159
	oriLeftLon = cfg->readDoubleNumEntry("LeftLon", 0.0);
2160
	oriLeftLat = cfg->readDoubleNumEntry("LeftLat", 0.0);
2161
	oriRightLon = cfg->readDoubleNumEntry("RightLon", 0.0);
2162
	oriRightLat = cfg->readDoubleNumEntry("RightLat", 0.0);
2163
//	int isrs = cfg->readNumEntry("SRS", 0);
157 andreas 2164
#endif
148 andreas 2165
	width = imgMap->width() - 2;
2166
	height = imgMap->height();
157 andreas 2167
#if defined HAVE_GDAL && HAVE_LIBGDAL1_5_0
158 andreas 2168
	if (MapType == MPT_WMS && square)
157 andreas 2169
	   pmMap.resize(width / (int)mFactor * (int)mFactor, height / (int)mFactor * (int)mFactor);
2170
	else
2171
	   pmMap.resize(width, height);
2172
#else
100 andreas 2173
	pmMap.resize(width, height);
157 andreas 2174
#endif
100 andreas 2175
	paint.begin(&pmMap);
2176
 
132 andreas 2177
	panX = panY = 0;
2178
 
2179
	if (stateHand && mapPan != pan)
2180
	{
2181
	   mapPan = pan;
2182
	   panX = mapPan.right() - mapPan.left();
2183
	   panY = mapPan.bottom() - mapPan.top();
2184
	   oldTransX += (double)panX;
2185
	   oldTransY += (double)panY;
2186
	}
2187
 
104 andreas 2188
	memset(&posNW, 0, sizeof(posn_type));
2189
	memset(&posSE, 0, sizeof(posn_type));
100 andreas 2190
 
156 andreas 2191
	posSE.lat = 90.0;
2192
	posSE.lon = 180.0;
2193
	posNW.lat = -90.0;
2194
	posNW.lon = -180.0;
100 andreas 2195
 
2196
	/*
2197
	 * Find out the corners of our track (NW, NE, SE, SW)
2198
	 */
132 andreas 2199
	if (mapLap)
2200
	   i = mapLap->start_time;
2201
	else
2202
	   i = 0;
100 andreas 2203
 
2204
	while ((point = ds.getPoint(i)) != 0)
2205
	{
132 andreas 2206
	   if (mapLap && point->time > (mapLap->start_time + (mapLap->total_time / 100)))
2207
	      break;
2208
 
100 andreas 2209
	   if (point->posn.lat == 0x7fffffff || point->posn.lon == 0x7fffffff)
2210
	   {
132 andreas 2211
	      i = point->time + 1;
100 andreas 2212
	      continue;
2213
	   }
2214
 
2215
	   if (SEMI2DEG(point->posn.lat) > posNW.lat)
2216
	      posNW.lat = SEMI2DEG(point->posn.lat);
2217
 
2218
	   if (SEMI2DEG(point->posn.lat) < posSE.lat)
2219
	      posSE.lat = SEMI2DEG(point->posn.lat);
2220
 
156 andreas 2221
	   if (SEMI2DEG(point->posn.lon) > posNW.lon)
100 andreas 2222
	      posNW.lon = SEMI2DEG(point->posn.lon);
2223
 
156 andreas 2224
	   if (SEMI2DEG(point->posn.lon) < posSE.lon)
100 andreas 2225
	      posSE.lon = SEMI2DEG(point->posn.lon);
2226
 
132 andreas 2227
	   i = point->time + 1;
157 andreas 2228
	   Data = true;
100 andreas 2229
	}
104 andreas 2230
 
2231
	coordW = (posNW.lon > posSE.lon) ? posNW.lon - posSE.lon : posSE.lon - posNW.lon;
2232
	coordH = (posNW.lat > posSE.lat) ? posNW.lat - posSE.lat : posSE.lat - posNW.lat;
109 andreas 2233
	meterW = ds.earth_distance(posNW.lat, posNW.lon, posNW.lat, posSE.lon);
104 andreas 2234
 
2235
	// define the ticks to translate the GPS coordinates into pixels.
2236
	// The track should be centered and we have to calculate the
2237
	// rectangular within we draw the track.
152 andreas 2238
	if (coordW < coordH)
100 andreas 2239
	{
152 andreas 2240
	   tick = (double)width / coordW + (double)zoom;
2241
 
2242
	   if ((tick * coordH) > height)
109 andreas 2243
	      tick = (double)height / coordH + (double)zoom;
100 andreas 2244
	}
2245
	else
2246
	{
152 andreas 2247
	   tick = (double)height / coordH + (double)zoom;
2248
 
2249
	   if ((tick * coordW) > width)
109 andreas 2250
	      tick = (double)width / coordW + (double)zoom;
100 andreas 2251
	}
104 andreas 2252
 
156 andreas 2253
	left = width - (width - tick * coordW) / 2;
152 andreas 2254
	top = (height - tick * coordH) / 2;
2255
 
132 andreas 2256
	a = tick * coordW;
156 andreas 2257
 
2258
	if (Units == 0)
2259
	   dist = meterW / a;			// Meters
2260
	else
2261
	   dist = meterW * 1.609344 / a;	// 1/1000 mile (5.28 feet)
2262
 
155 andreas 2263
#if defined HAVE_GDAL && HAVE_LIBGDAL1_5_0
159 andreas 2264
	geoRect.llat = 0.0;
2265
	geoRect.llon = 0.0;
2266
	geoRect.rlat = 0.0;
2267
	geoRect.rlon = 0.0;
158 andreas 2268
	geoRect.width = width;
2269
	geoRect.height = height;
146 andreas 2270
	/*
2271
	 * If we have a map file, we try to read it and if successfull,
2272
	 * we should get a map painted.
154 andreas 2273
	 *
2274
	 * Currently only WMS-Server is supported, allthough GDAL allows
2275
	 * several other formats too.
146 andreas 2276
	 */
157 andreas 2277
	if (!MAP.isEmpty() && Data)
146 andreas 2278
	{
158 andreas 2279
	bool writeTag = true;
2280
	double mtx, mty;
2281
	double vx, vy;
152 andreas 2282
 
158 andreas 2283
	   xOff = yOff = 0;
2284
	   posRXY.lon = posNW.lon + (width - left + oldTransX) / tick;
2285
	   posLXY.lat = posNW.lat + (top + oldTransY) / tick;
2286
	   posLXY.lon = posSE.lon - (left - a - oldTransX) / tick;
2287
	   posRXY.lat = posSE.lat - (height - top - (tick * coordH) - oldTransY) / tick;
159 andreas 2288
	   geoRect.llat = posLXY.lat;
2289
	   geoRect.llon = posLXY.lon;
2290
	   geoRect.rlat = posRXY.lat;
2291
	   geoRect.rlon = posRXY.lon;
158 andreas 2292
	   // width and height of map in meters
2293
	   mtx = ds.earth_distance(posRXY.lat, posRXY.lon, posRXY.lat, posLXY.lon);
2294
	   mty = ds.earth_distance(posRXY.lat, posRXY.lon, posLXY.lat, posRXY.lon);
157 andreas 2295
 
158 andreas 2296
	   // factor to correct the map, in case we use a WMS server
2297
	   if (MapType == MPT_WMS)
2298
	   {
2299
	      vx = (posRXY.lon - posLXY.lon) / mtx * CorrX;
2300
	      vy = (posRXY.lat - posLXY.lat) / mty * CorrY;
2301
	      posRXY.lon += vx;
2302
	      posRXY.lat += vy;
2303
	      posLXY.lon += vx;
2304
	      posLXY.lat += vy;
2305
	   }
2306
 
154 andreas 2307
	   /*
158 andreas 2308
	    * Write a control file for GDAL, if we use a WMS server.
2309
	    * Warp an image if we use PNG or BMP or GIF.
2310
	    * Warp a region if we use TIFF
154 andreas 2311
	    */
158 andreas 2312
	   if (MapType == MPT_WMS)
2313
	      writeTag = writeWMSTag(posLXY.lon, posLXY.lat, posRXY.lon, posRXY.lat, width, height);
2314
 
159 andreas 2315
	   if (MapType == MPT_GIF || MapType == MPT_BMP || MapType == MPT_PNG ||
2316
	       MapType == MPT_SGI || MapType == MPT_TIF)
158 andreas 2317
	      writeTag = warpImage(MAP, &fName);
2318
 
2319
	   if (writeTag)
151 andreas 2320
	   {
158 andreas 2321
	      if (MapType != MPT_SHP && (poDataset = (GDALDataset *)GDALOpen (fName.ascii(), GA_ReadOnly)) != NULL)
151 andreas 2322
	      {
2323
		 QPixmap bild;
2324
		 int nRasterCount = poDataset->GetRasterCount();
2325
		 int nXBlock, nYBlock;
154 andreas 2326
		 GDALColorTable *pCT, *pCTb, *pCTr, *pCTg, *pCTa;
146 andreas 2327
 
151 andreas 2328
		 int             bGotMin, bGotMax;
2329
		 int		 tTypeLen, tColor, tColorEntrys;
2330
		 GDALDataType    tRasterType;
2331
		 double          adfMinMax[2];
2332
 
154 andreas 2333
		 pafScanlineRed = pafScanlineGreen = pafScanlineBlue = pafScanlineAlpha = 0;
152 andreas 2334
 
154 andreas 2335
		 /*
2336
		  * Read every raster band.
2337
		  *
2338
		  * If we get 3 raster bands, the image is a 24 bit image.
2339
		  * If we get 4 raster bands, the image is probably a 24 bit
2340
		  * image with an alpha channel. Currently the alpha channel
2341
		  * is ignored!
2342
		  * If we have 1 raster band, the image is 8 bit monochrom.
2343
		  * Otherwise the image is undefined and the results are also.
2344
		  */
151 andreas 2345
		 for (a = 1; a <= nRasterCount; a++)
2346
		 {
2347
		    poBand = poDataset->GetRasterBand (a);
2348
		    poBand->GetBlockSize (&nXBlock, &nYBlock);
2349
		    nXSize = poBand->GetXSize();
2350
		    nYSize = poBand->GetYSize();
2351
		    tRasterType = poBand->GetRasterDataType ();
2352
		    tTypeLen = GDALGetDataTypeSize (tRasterType) / 8;	// We need Bytes not Bits!
2353
		    tColor = poBand->GetColorInterpretation ();
2354
 
2355
		    adfMinMax[0] = poBand->GetMinimum (&bGotMin);
2356
		    adfMinMax[1] = poBand->GetMaximum (&bGotMax);
2357
 
2358
		    if (!(bGotMin && bGotMax))
2359
		       GDALComputeRasterMinMax ((GDALRasterBandH)poBand, TRUE, adfMinMax);
2360
 
152 andreas 2361
		    if ((pCT = poBand->GetColorTable()) != NULL)
151 andreas 2362
		       tColorEntrys = poBand->GetColorTable()->GetColorEntryCount();
2363
 
2364
		    switch (a)
2365
		    {
152 andreas 2366
		       case 1: pafScanlineRed   = new unsigned char[tTypeLen * nXSize * nYSize]; pafScanline = pafScanlineRed; pCTr = pCT; break;
2367
		       case 2: pafScanlineGreen = new unsigned char[tTypeLen * nXSize * nYSize]; pafScanline = pafScanlineGreen; pCTg = pCT; break;
2368
		       case 3: pafScanlineBlue  = new unsigned char[tTypeLen * nXSize * nYSize]; pafScanline = pafScanlineBlue; pCTb = pCT; break;
154 andreas 2369
		       case 4: pafScanlineAlpha  = new unsigned char[tTypeLen * nXSize * nYSize]; pafScanline = pafScanlineAlpha; pCTa = pCT; break;
151 andreas 2370
		    }
2371
 
152 andreas 2372
		    memset (pafScanline, 0, tTypeLen * nXSize * nYSize);
151 andreas 2373
 
154 andreas 2374
		    /*
158 andreas 2375
		     * Get the image (from the server) and put the tiles together.
154 andreas 2376
		     *
2377
		     * The function reads only one raster band. This is,
2378
		     * because the function is called for every raster band and
2379
		     * every raster band is stored into a separate array.
2380
		     */
152 andreas 2381
		    if (poBand->RasterIO (GF_Read, 0, 0, nXSize, nYSize, pafScanline, nXSize, nYSize, tRasterType, 0, 0) == CE_Failure)
2382
		    {
151 andreas 2383
		       KMessageBox::error(this, i18n("Error reading a raster band!"));
152 andreas 2384
		       Fgeo = false;
2385
		       break;
2386
		    }
2387
		    else
2388
		       Fgeo = true;
151 andreas 2389
		 }
2390
 
154 andreas 2391
		 /*
2392
		  * Only if Fgeo is TRUE, we've read successfully all raster
2393
		  * bands. Now we have to put the bands together to get
2394
		  * an image.
2395
		  */
152 andreas 2396
		 if (Fgeo)
2397
		 {
2398
		 unsigned char *pCombinedBytes = new unsigned char[(tTypeLen * nXSize * nYSize * nRasterCount)];
2399
		 unsigned char *ptr_dest, *ptr_src;
2400
		 int j;
151 andreas 2401
 
154 andreas 2402
		    /*
2403
		     * We need two nested loops to set the pixels in the wanted
2404
		     * order.
2405
		     */
152 andreas 2406
		    for (a = 0, j = 0; a < (nXSize * nYSize * nRasterCount); a += nRasterCount, j++)
151 andreas 2407
		    {
152 andreas 2408
		       int k = a;
2409
 
2410
		       for (int m = nRasterCount - 1; m >= 0; m--, k++)
2411
		       {
2412
		       unsigned char *pBytes;
2413
 
2414
			  switch (m)
2415
			  {
154 andreas 2416
			     case 3: pBytes = pafScanlineAlpha; pCT = pCTa; break;
152 andreas 2417
			     case 2: pBytes = pafScanlineBlue; pCT = pCTb; break;
2418
			     case 1: pBytes = pafScanlineGreen; pCT = pCTg; break;
2419
			     default: pBytes = pafScanlineRed; pCT = pCTr;
2420
			  }
2421
 
2422
			  ptr_dest = pCombinedBytes + k;
2423
			  unsigned char b = pBytes[j];
2424
 
154 andreas 2425
			  /*
2426
			   * If we have a color table, the pixels are pointers
2427
			   * to the color table. We need to convert them into
2428
			   * 24 bit pixels plus an optional alpha channel.
2429
			   */
152 andreas 2430
			  if (pCT != NULL)
2431
			  {
2432
			     GDALColorEntry ce;
2433
			     unsigned int c = (unsigned int)b;
2434
			     c = pCT->GetColorEntryAsRGB (c, &ce);
2435
 
2436
			     if  (m == 0) c = ce.c1;
2437
			     if  (m == 1) c = ce.c2;
2438
			     if  (m == 2) c = ce.c3;
154 andreas 2439
			     if  (m == 3) c = ce.c4;
152 andreas 2440
 
2441
			     b = (unsigned char)c;
2442
			  }
2443
 
2444
			  ptr_src = &b;
2445
			  memcpy (ptr_dest, ptr_src, 1);
2446
		       }
151 andreas 2447
		    }
152 andreas 2448
 
2449
		    x1 = y1 = 0;
2450
 
154 andreas 2451
		    /*
2452
		     * The following loop is QT specific! It sets the pixels
2453
		     * of the raw image, pixel by pixel. This may be slow, but
2454
		     * everything else didn't work :-(
2455
		     *
2456
		     * FIXME: We need a more effective routine to put the
158 andreas 2457
		     *        raw image into QT's "painter" class.
154 andreas 2458
		     */
2459
		    for (a = 0; a < (nXSize * nYSize * nRasterCount); a += nRasterCount)
152 andreas 2460
		    {
158 andreas 2461
		       if (x1 < width && y1 < height)
2462
		       {
2463
			  if (nRasterCount == 3)
2464
			     paint.setPen (QPen(QColor((int)pCombinedBytes[a+2], (int)pCombinedBytes[a+1], (int)pCombinedBytes[a]), QPen::SolidLine));
2465
			  else if (nRasterCount > 3)
159 andreas 2466
			     paint.setPen (QPen(QColor(qRgba((int)pCombinedBytes[a+3], (int)pCombinedBytes[a+2], (int)pCombinedBytes[a+1], (int)pCombinedBytes[a])), QPen::SolidLine));
158 andreas 2467
			  else if (nRasterCount == 2)
2468
			     paint.setPen (QPen(QColor((int)pCombinedBytes[a+1], (int)pCombinedBytes[a], (int)pCombinedBytes[a+1]), QPen::SolidLine));
2469
			  else if (nRasterCount == 1)
2470
			     paint.setPen (QPen(QColor((int)pCombinedBytes[a], (int)pCombinedBytes[a], (int)pCombinedBytes[a]), QPen::SolidLine));
154 andreas 2471
 
158 andreas 2472
			  paint.drawPoint(x1, y1);
2473
		       }
2474
 
152 andreas 2475
		       x1++;
2476
 
2477
		       if (x1 >= nXSize)
2478
		       {
2479
			  x1 = 0;
2480
			  y1++;
2481
		       }
2482
		    }
2483
 
2484
		    delete pCombinedBytes;
151 andreas 2485
		 }
2486
 
152 andreas 2487
		 if (pafScanlineRed)
2488
		    delete pafScanlineRed;
151 andreas 2489
 
152 andreas 2490
		 if (pafScanlineGreen)
2491
		    delete pafScanlineGreen;
2492
 
2493
		 if (pafScanlineBlue)
2494
		    delete pafScanlineBlue;
2495
 
154 andreas 2496
		 if (pafScanlineAlpha)
2497
		    delete pafScanlineAlpha;
2498
 
152 andreas 2499
		 GDALClose (poDataset);
2500
		 poDataset = 0;
158 andreas 2501
 
2502
		 if (MAP != fName)
2503
		    unlink (fName.ascii());
151 andreas 2504
	      }
158 andreas 2505
	      else if (MapType == MPT_SHP)
2506
	      {
2507
		 QDir shpd(MAP, QString("*.shp"));
2508
 
2509
		 if (shpd.count() < 1)
2510
		 {
2511
		    KMessageBox::error(this, i18n("There is no shape file in directory ") + MAP);
2512
		    Fgeo = false;
2513
		 }
2514
		 else
2515
		 {
2516
		 OGRDataSource *poDS = 0;
165 andreas 2517
		 OGRLayer *poLy;
2518
		 OGRFeature *poFeat;
2519
		 OGRFeatureDefn *poFDefn;
2520
		 OGRFieldDefn *poFieldDefn;
2521
		 OGRGeometry *poGeometry;
2522
		 OGRPoint *poPoint;
2523
		 int nLayers, iField;
2524
		 QString sfn;
158 andreas 2525
 
165 andreas 2526
		    OGRRegisterAll ();
158 andreas 2527
		    // read all shape files and put them together
2528
		    for (a = 0; a < shpd.count(); a++)
2529
		    {
165 andreas 2530
		       sfn = MAP + shpd[a];
2531
		       poDS = OGRSFDriverRegistrar::Open(sfn.ascii(), false);
158 andreas 2532
 
2533
		       if (!poDS)
165 andreas 2534
		       {
2535
			  cerr << "Error opening the file " << sfn.ascii() << "!" << endl;
158 andreas 2536
			  break;
165 andreas 2537
		       }
158 andreas 2538
 
165 andreas 2539
		       nLayers = poDS->GetLayerCount ();
2540
 
2541
		       // Read all layers of a shape file
2542
		       for (int j = 0; j< nLayers; j++)
2543
		       {
2544
			  if ((poLy = poDS->GetLayer (j)) == NULL)
2545
			  {
2546
			     cerr << "Error getting layer " << j << "!" << endl;
2547
			     continue;
2548
			  }
2549
 
2550
			  poLy->SetSpatialFilterRect (geoRect.llon, geoRect.llat, geoRect.rlon, geoRect.rlat);
2551
 
2552
			  // Read all features of a layer and get the fields
2553
			  // of the features
2554
			  poLy->ResetReading();
2555
 
2556
			  while ((poFeat = poLy->GetNextFeature()) != NULL)
2557
			  {
2558
			     if ((poFDefn = poLy->GetLayerDefn()) == NULL)
2559
			     {
2560
			        cerr << "Error getting a layer defination!" << endl;
2561
			        continue;
2562
			     }
2563
 
2564
			     poGeometry = poFeat->GetGeometryRef();
2565
 
2566
			     if (poGeometry != NULL && wkbFlatten (poGeometry->getGeometryType()) == wkbPoint)
2567
			     {
2568
			        poPoint = (OGRPoint *) poGeometry;
2569
			        cout << "pointX: " << poPoint->getX() << ", pointY: " << poPoint->getY() << endl;
2570
			     }
2571
 
2572
			     for (iField = 0; iField < poFDefn->GetFieldCount(); iField++)
2573
			     {
2574
			        poFieldDefn = poFDefn->GetFieldDefn (iField);
2575
 
2576
				if (poFieldDefn->GetType() == OFTInteger)
2577
				   cout << "Layer: " << j << " int: " << poFeat->GetFieldAsInteger (iField) << endl;
2578
				else if (poFieldDefn->GetType() == OFTReal)
2579
				   cout << "Layer: " << j << " float: " << poFeat->GetFieldAsDouble (iField) << endl;
2580
				else if (poFieldDefn->GetType() == OFTString)
2581
				   cout << "Layer: " << j << " string: " << poFeat->GetFieldAsString (iField) << endl;
2582
				else
2583
				   cout << "Layer: " << j << " Unkn.: " << poFeat->GetFieldAsString (iField) << endl;
2584
			     }
2585
 
2586
			     cout << "----------------------------" << endl;
2587
        		  }
2588
 
2589
        		  OGRFeature::DestroyFeature (poFeat);
2590
		       }
2591
 
158 andreas 2592
		       OGRDataSource::DestroyDataSource(poDS);
2593
		    }
2594
		 }
2595
	      }
151 andreas 2596
	      else
157 andreas 2597
	      {
158 andreas 2598
		 KMessageBox::error(this, i18n("Error opening map file!"));
157 andreas 2599
		 Fgeo = false;
2600
	      }
151 andreas 2601
	   }
146 andreas 2602
	}
151 andreas 2603
#endif
154 andreas 2604
	/*
2605
	 * Here we come to draw the track. It will be drawn over the previous
2606
	 * created map image.
2607
	 */
100 andreas 2608
	// Colors and fonts
154 andreas 2609
	QColor background(220, 220, 220);		// background color
2610
	QColor red(255, 0, 0);				// mile marker
2611
	QColor black(0, 0, 0);				// Text, center of track
2612
//	QColor yellow(255, 255, 0);
2613
	QColor yellow(0x00cf, 0x00ff, 0x0000);		// color of track
100 andreas 2614
	QFont fntNormal("Helvetica");
2615
	fntNormal.setPixelSize(10);
2616
	fntNormal.setStyleHint(QFont::Helvetica);
104 andreas 2617
	QPen dot(red, 4, QPen::SolidLine);
154 andreas 2618
	QPen line(black, 2, QPen::SolidLine);
2619
	QPen yline(yellow, 5, QPen::SolidLine);
2620
	// Fill background with background colors, if there is no map.
152 andreas 2621
	if (!Fgeo)
2622
	   paint.fillRect(0, 0, width+2, height+2, background);
2623
 
156 andreas 2624
	if (Units == 0)
2625
	   fact = 1000.0;
2626
	else
2627
	   fact = 1609.344;
2628
 
109 andreas 2629
	paint.setPen(line);
2630
	paint.drawLine(10, height - 9, 10, height - 4);
156 andreas 2631
	paint.drawLine(10, height - 4, 10 + (fact / dist), height - 4);
2632
	paint.drawLine(10 + (fact / dist), height - 9, 10 + (fact / dist), height - 4);
109 andreas 2633
	paint.setFont(fntNormal);
2634
 
156 andreas 2635
	if (Units == 0)
2636
	   paint.drawText(10, height - 10, QString("1000 m"));
2637
	else
2638
	   paint.drawText(10, height - 10, QString("5280 ft"));
2639
 
100 andreas 2640
	// Draw track
132 andreas 2641
	if (mapLap)
2642
	   i = mapLap->start_time;
2643
	else
2644
	   i = 0;
2645
 
100 andreas 2646
	x1 = y1 = 0.0;
157 andreas 2647
	bool wStart = false;
104 andreas 2648
 
100 andreas 2649
	while ((point = ds.getPoint(i)) != 0)
2650
	{
132 andreas 2651
	   if (mapLap && point->time > (mapLap->start_time + (mapLap->total_time / 100)))
2652
	      break;
2653
 
100 andreas 2654
	   if (point->posn.lat == 0x7fffffff || point->posn.lon == 0x7fffffff)
2655
	   {
132 andreas 2656
	      i = point->time + 1;
100 andreas 2657
	      continue;
2658
	   }
2659
 
157 andreas 2660
	   x2 = (left + ((posNW.lon - SEMI2DEG(point->posn.lon)) * tick * -1)) + oldTransX;
2661
	   y2 = (top + ((posNW.lat - SEMI2DEG(point->posn.lat)) * tick)) + oldTransY;
100 andreas 2662
 
157 andreas 2663
	   if (!wStart && x1 != 0.0 && y1 != 0.0)
2664
	   {
2665
	      // Load the start symbol
2666
	      QPixmap qpx = QPixmap::fromMimeSource(QString("wstart.png"));
2667
	      // Find the angle of the track and turn the symbol accordingly
2668
	      // we use Pythagoras to calculate the triangle
2669
	      double xl = (x1 < x2) ? x2 - x1 : x1 - x2;
2670
	      double yl = (y1 < y2) ? y2 - y1 : y1 - y2;
2671
	      double da = fmin (xl, yl);
2672
	      double db = fmax (xl, yl);
2673
	      double zl = sqrt (pow (da, 2) + pow (db, 2));
2674
	      double angle = (asin(da / zl) / M_PIl) * 180.0;
2675
 
2676
	      angle = (angle > 45.0) ? 90.0 - angle : angle;
2677
// cout << "Winkel: " << angle << " ---- X: " << xl << ", Y: " << yl << ", Z: " << zl << ", Point (x1,y1,x2,y2): " << x1 << ", " << y1 << ", " << x2 << ", " << y2 << endl;
2678
	      if (x1 < x2 && y1 < y2)		// right, down
2679
		 angle = 90.0 + angle;
2680
	      else if (x1 > x2 && y1 < y2)	// left, down
2681
		 angle = 270.0 - angle;
2682
	      else if (x1 > x2 && y1 > y2)	// left, up
2683
		 angle = 270.0 + angle;
2684
	      else				// right, up
2685
		 angle = 90.0 - angle;
2686
// cout << "Realer Winkel: " << angle << endl;
2687
	      // Set the center of the symbol
2688
	      paint.save ();
2689
	      paint.translate (x1, y1);
2690
	      // rotate the symbol
2691
	      paint.rotate (angle);
2692
	      paint.drawPixmap (-8, -8, qpx);
2693
	      paint.restore ();
2694
	      wStart = true;
2695
	   }
2696
 
100 andreas 2697
	   if (x1 == 0.0 && y1 == 0.0)
2698
	   {
2699
	      x1 = x2;
2700
	      y1 = y2;
2701
	   }
104 andreas 2702
 
100 andreas 2703
	   paint.setPen(yline);
104 andreas 2704
	   paint.drawLine(x1, y1, x2, y2);
2705
 
156 andreas 2706
	   if ((point->distance - dist) >= fact)	// a dot at every 1000 meters or at 1 mile
104 andreas 2707
	   {
2708
	      paint.setPen(dot);
154 andreas 2709
	      paint.drawEllipse(x2-2, y2-2, 3, 3);
156 andreas 2710
	      dist = (int)(point->distance / fact) * fact;
104 andreas 2711
	   }
2712
 
100 andreas 2713
	   paint.setPen(line);
2714
	   paint.drawLine(x1, y1, x2, y2);
2715
	   x1 = x2;
2716
	   y1 = y2;
132 andreas 2717
	   i = point->time + 1;
100 andreas 2718
	}
2719
 
157 andreas 2720
	bool lastLap = false;
2721
 
2722
	if (mapLap)
2723
	   if (ds.getRunNode()->run->last_lap_index == mapLap->index)
2724
	      lastLap = true;
2725
 
2726
	if ((!mapLap || lastLap) && wStart)
2727
	{
2728
	   // load the end symbol
2729
	   QPixmap qpx = QPixmap::fromMimeSource(QString("wtarget.png"));
2730
	   paint.drawPixmap (x2, y2 - 16, qpx);
2731
	}
2732
 
100 andreas 2733
	paint.end();
2734
	imgMap->setPixmap(pmMap);
154 andreas 2735
	QApplication::restoreOverrideCursor();
100 andreas 2736
}
2737
 
88 andreas 2738
void sportwatcherWidget::showCurves()
2739
{
148 andreas 2740
	showCurves (mapLap);
2741
}
2742
 
2743
void sportwatcherWidget::showCurves(LAP *lap)
2744
{
88 andreas 2745
QPainter paint;
2746
int width, height;
218 andreas 2747
int i, secs, cuType;
88 andreas 2748
int lineHeight, margin_left, margin_right, margin_bottom;
2749
int x1, y1, x2, y2;		// Coordinates
2750
bool meter;
218 andreas 2751
double maxHeight, minHeight, maxSpeed, minSpeed;
88 andreas 2752
int maxHr, minHr, rh;
2753
POINT *point;
148 andreas 2754
RUN_NODE *rn;
2755
LAP *lp;
88 andreas 2756
double w_tick, h_tick;		// Number of pixels one "tick" has;
2757
				// This depends on the width and height
2758
				// of the image.
2759
	// First we draw a grid based on the min and max
2760
	// values detected in the function showLap(). In case
2761
	// all values are 0, we exit here.
2762
	if (min_hr == 0 && max_hr == 0 && min_height == 0.0 && max_height == 0.0)
2763
	   return;
2764
 
218 andreas 2765
	// Look up, what curves we should draw
2766
	cuType = kcbCurveTypes->currentItem();
2767
	// Get the dimensions of the available draw area
148 andreas 2768
	width = imgProfile->width() - 2;
2769
	height = imgProfile->height();
2770
	pmProfile.resize(width, height);
88 andreas 2771
	paint.begin(&pmProfile);
2772
 
2773
	// we need a somewhat bigger area to draw our curves than
2774
	// we have with the real min and max values.
2775
	if (max_height > 0.0)
2776
	{
148 andreas 2777
	double add = (max_height - min_height) / 100.0 * 5.0;	// Percent
88 andreas 2778
 
2779
	   maxHeight = max_height + add;
2780
	   minHeight = min_height - add;
2781
 
2782
	   if (minHeight < 0.0)		// make sure, we are not too deep
2783
	      minHeight = 0.0;
2784
	}
221 andreas 2785
	else
2786
	   maxHeight = minHeight = 0.0;
88 andreas 2787
 
218 andreas 2788
	if (max_speed > 0.0)
2789
	{
2790
	double add = (max_speed - min_speed) / 100.0 * 5.0;	// Percent
2791
 
2792
	   maxSpeed = max_speed + add;
2793
	   minSpeed = min_speed - add;
2794
 
2795
	   if (minSpeed < 0.0)		// make sure, we are not too deep
2796
	      minSpeed = 0.0;
2797
	}
221 andreas 2798
	else
2799
	   maxSpeed = minSpeed = 0.0;
218 andreas 2800
 
88 andreas 2801
	if (max_hr > 0)
2802
	{
2803
	   maxHr = max_hr + 10;
2804
	   minHr = min_hr - 10;
2805
 
2806
	   if (minHr < 0)
2807
	      minHr = 0;
2808
	}
221 andreas 2809
	else
2810
	   maxHr = minHr = 0;
88 andreas 2811
 
2812
	// Define colors
148 andreas 2813
	QColor background(220, 220, 220);	// Background of graphic
2814
	QColor mark(255, 255, 255);		// Lines inside curve area
2815
	QColor hlight(180, 180, 180);		// area of current lap
2816
//	hlight.setAlpha(128);			// 50% transparent
2817
	QColor frame(0, 0, 0);			// Text and borders
2818
	QColor barcol(151, 190, 13);		// heart rate
2819
	QColor barcol2(190, 151, 13);		// height over NN
222 andreas 2820
	QColor red(220, 128, 128);		// speed
88 andreas 2821
	QColor blue(0, 0, 240);
2822
	QFont fntNormal("Helvetica");
2823
//	QFont fntBold("Helvetica", 10, QFont::Bold);
2824
	fntNormal.setPixelSize(10);
2825
	fntNormal.setStyleHint(QFont::Helvetica);
2826
//	fntBold.setPixelSize(10);
2827
//	fntBold.setStyleHint(QFont::Helvetica);
2828
	// Calculate ticks
2829
	margin_left = 52;
2830
	margin_right = 40;
2831
	margin_bottom = 12;
2832
	lineHeight = 10;
2833
	rh = height - margin_bottom - 1;
2834
 
2835
	w_tick = (double)(width - (margin_left + margin_right)) / max_time;	// 1 tick = 1 second
2836
 
222 andreas 2837
	if (cuType == 1)	// Speed and heart rate?
88 andreas 2838
	{
218 andreas 2839
	   if ((maxSpeed - minSpeed) > (double)(maxHr - minHr))
2840
	   {
222 andreas 2841
	      h_tick = (double)rh / (maxSpeed - minSpeed);		// 1 tick = 1 km/h
218 andreas 2842
	      meter = true;
2843
	   }
2844
	   else
2845
	   {
2846
	      h_tick = (double)rh / ((double)maxHr - (double)minHr);	// 1 tick = 1 bpm
2847
	      meter = false;
2848
	   }
88 andreas 2849
	}
222 andreas 2850
	else if (cuType == 2)	// Elevation and speed?
88 andreas 2851
	{
218 andreas 2852
	   if ((maxHeight - minHeight) > (double)(maxHr - minHr))
2853
	   {
2854
	      h_tick = (double)rh / (maxHeight - minHeight);		// 1 tick = 1 meter
2855
	      meter = true;
2856
	   }
2857
	   else
2858
	   {
222 andreas 2859
	      h_tick = (double)rh / (maxSpeed - minSpeed);		// 1 tick = 1 km/h
2860
	      meter = false;
2861
	   }
2862
	}
2863
	else			// Elevation and heart rate
2864
	{
2865
	   if ((maxHeight - minHeight) > (double)(maxHr - minHr))
2866
	   {
2867
	      h_tick = (double)rh / (maxHeight - minHeight);		// 1 tick = 1 meter
2868
	      meter = true;
2869
	   }
2870
	   else
2871
	   {
218 andreas 2872
	      h_tick = (double)rh / ((double)maxHr - (double)minHr);	// 1 tick = 1 bpm
2873
	      meter = false;
2874
	   }
88 andreas 2875
	}
218 andreas 2876
 
88 andreas 2877
	// Fill background with background colors
2878
	paint.fillRect(0, 0, width + 4, height + 4, background);
2879
	// Draw a grid with markers at every 10 minutes
2880
	paint.setPen(QPen(frame, 1, QPen::SolidLine));
2881
	// Bottom border line
2882
	x1 = margin_left;
2883
	y1 = height - margin_bottom;
2884
	x2 = width - margin_right;
2885
	y2 = y1;
2886
	paint.drawLine(x1, y1, x2, y2);
2887
	// Left border line
2888
	x1 = x2 = margin_left;
2889
	y1 = 2;
2890
	y2 = height - margin_bottom;
2891
	paint.drawLine(x1, y1, x2, y2);
2892
	// right border line
2893
	x1 = x2 = width - margin_right;
2894
	paint.drawLine(x1, y1, x2, y2);
148 andreas 2895
 
2896
	// Draw some darker lines to show the laps, if we have one
2897
	// and, in case we have a given lap, we fill the area.
2898
	QDateTime *qt;
2899
	QTime zeit = StartTime.time();
2900
	rn = ds.getRunNode();
2901
	paint.setPen(QPen(hlight, 1, QPen::SolidLine));
2902
 
2903
	for (i = rn->run->first_lap_index; (unsigned int)i <= rn->run->last_lap_index; i++)
2904
	{
2905
	   if ((lp = ds.getLap(i)) == NULL)
2906
	      continue;
2907
 
2908
	   qt = garmin_dtime(lp->start_time);
2909
	   secs = zeit.secsTo(qt->time());
2910
	   delete qt;
2911
	   x1 = secs * w_tick + margin_left + 1;
2912
 
2913
	   if (lap && lp->start_time == lap->start_time)
2914
	      paint.fillRect(x1, 2, (int)((double)lap->total_time / 100.0 * w_tick), height - margin_bottom - 2, hlight);
2915
	   else
2916
	      paint.drawLine(x1, 2, x1, height - margin_bottom);
2917
	}
2918
 
88 andreas 2919
	// Grid vertical
2920
	paint.setPen(QPen(frame, 1, QPen::SolidLine));
2921
	paint.setFont(fntNormal);
2922
	paint.drawText(margin_left - 20, height - lineHeight, 40, lineHeight, Qt::AlignCenter, QString("00:00"));
2923
	paint.save();
2924
	paint.rotate(270);
218 andreas 2925
 
222 andreas 2926
	if (cuType == 1)
2927
	   paint.setPen(QPen(red, 1, QPen::SolidLine));
2928
	else
2929
	   paint.setPen(QPen(barcol, 1, QPen::SolidLine));
2930
 
2931
	// Information on left side
218 andreas 2932
	if (cuType == 0)
2933
	   paint.drawText((height + 4) * -1, 3, height - 2, lineHeight, Qt::AlignCenter, i18n((Units == 1) ? "Elevation (ft)" : "Elevation (m)"));
2934
	else if (cuType == 1)
2935
	   paint.drawText((height + 4) * -1, 3, height - 2, lineHeight, Qt::AlignCenter, i18n((Units == 1) ? "Speed (mph)" : "Speed (km/h)"));
2936
	else
2937
	   paint.drawText((height + 4) * -1, 3, height - 2, lineHeight, Qt::AlignCenter, i18n((Units == 1) ? "Elevation (ft)" : "Elevation (m)"));
2938
 
222 andreas 2939
	if (cuType == 2)
2940
	   paint.setPen(QPen(red, 1, QPen::SolidLine));
2941
	else
2942
	   paint.setPen(QPen(blue, 1, QPen::SolidLine));
218 andreas 2943
 
222 andreas 2944
	// Information on right side
218 andreas 2945
	if (cuType < 2)
2946
	   paint.drawText((height + 4) * -1, width - 1 - lineHeight, height - 2, lineHeight, Qt::AlignCenter, i18n("Heart Rate (bpm)"));
2947
	else
2948
	   paint.drawText((height + 4) * -1, width - 1 - lineHeight, height - 2, lineHeight, Qt::AlignCenter, i18n((Units == 1) ? "Speed (mph)" : "Speed (km/h)"));
2949
 
88 andreas 2950
	paint.restore();
2951
	paint.setPen(QPen(mark, 1, QPen::SolidLine));
222 andreas 2952
	// Draw the time scale on the bottom of the graphic
88 andreas 2953
	for (i = 0; (unsigned int)i < max_time; i++)
2954
	{
2955
	   if (i > 0 && !(i % 600))	// every 10 minutes
2956
	   {
2957
	      x1 = x2 = margin_left + w_tick * i;
2958
 
2959
	      if (x1 == (width - margin_right))
2960
		 continue;
2961
 
2962
	      y1 = 2;
2963
	      y2 = height - margin_bottom;
2964
	      paint.drawLine(x1, y1, x2, y2);
2965
	      QTime tm(0, 0, 0);
2966
	      tm = tm.addSecs(i);
2967
	      paint.setPen(QPen(frame, 1, QPen::SolidLine));
2968
	      paint.drawText(x1 - 25, height - lineHeight, 50, lineHeight, Qt::AlignCenter, tm.toString((i >= 3600) ? "hh:mm:ss" : "mm:ss"));
2969
	      paint.setPen(QPen(mark, 1, QPen::SolidLine));
2970
	   }
2971
	}
222 andreas 2972
 
2973
	// This is the total time, with pauses included, at the lower right
2974
	// corner of the graphic.
88 andreas 2975
	QTime tm(0, 0, 0);
2976
	QString qs;
2977
	tm = tm.addSecs(max_time);
2978
	paint.setPen(QPen(frame, 1, QPen::SolidLine));
2979
	paint.drawText(width - margin_right - 25, height - lineHeight, 50, lineHeight, Qt::AlignCenter, tm.toString((max_time >= 3600) ? "hh:mm:ss" : "mm:ss"));
2980
 
222 andreas 2981
	// Draw the minimal elevation, speed and/or heart rate
218 andreas 2982
	if (max_height > 0.0 || max_speed > 0.0)
88 andreas 2983
	{
222 andreas 2984
	   // left side
218 andreas 2985
	   if (cuType == 1)
222 andreas 2986
	   {
2987
	      paint.setPen(QPen(red, 1, QPen::SolidLine));
218 andreas 2988
	      paint.drawText(12, height - margin_bottom - lineHeight / 2, margin_left - 14, lineHeight, Qt::AlignRight, qs.sprintf("%.0f", minSpeed));
222 andreas 2989
	   }
218 andreas 2990
	   else
222 andreas 2991
	   {
2992
	      paint.setPen(QPen(barcol, 1, QPen::SolidLine));
218 andreas 2993
	      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 2994
	   }
88 andreas 2995
	}
2996
 
222 andreas 2997
	if (max_hr > 0 || max_speed > 0.0)
88 andreas 2998
	{
222 andreas 2999
	   // right side
3000
	   if (cuType == 2)
3001
	   {
3002
	      paint.setPen(QPen(red, 1, QPen::SolidLine));
3003
	      paint.drawText(width - margin_right + 2, height - margin_bottom - lineHeight / 2, margin_right - 14, lineHeight, Qt::AlignLeft, qs.sprintf("%.0f", minSpeed));
3004
	   }
3005
	   else
3006
	   {
3007
	      paint.setPen(QPen(blue, 1, QPen::SolidLine));
3008
	      paint.drawText(width - margin_right + 2, height - margin_bottom - lineHeight / 2, margin_right - 14, lineHeight, Qt::AlignLeft, qs.sprintf("%d", minHr));
3009
	   }
88 andreas 3010
	}
3011
 
3012
	paint.setPen(QPen(mark, 1, QPen::SolidLine));
3013
 
3014
	// Grid horizontal
218 andreas 3015
	int factor = 0;
3016
	int target = 0;
3017
 
222 andreas 3018
	if (cuType == 0)	// Elevation and heart rate
218 andreas 3019
	{
222 andreas 3020
	   factor = (meter) ? (maxHeight - minHeight) / (rh / 12) : (maxHr - minHr) / (rh / 12);
3021
	   target = (meter) ? (int)(maxHeight - minHeight) : (maxHr - minHr);
3022
	}
3023
	else if (cuType == 1)	// Speed and heart rate
3024
	{
218 andreas 3025
	   factor = (meter) ? (maxSpeed - minSpeed) / (rh / 12) : (maxHr - minHr) / (rh / 12);
3026
	   target = (meter) ? (int)(maxSpeed - minSpeed) : (maxHr - minHr);
3027
	}
222 andreas 3028
	else			// Elevation and speed
218 andreas 3029
	{
222 andreas 3030
	   factor = (meter) ? (maxHeight - minHeight) / (rh /12) : (maxSpeed - minSpeed) / (rh / 12);
3031
	   target = (meter) ? (int)(maxHeight - minHeight) : (int)(maxSpeed - minSpeed);
218 andreas 3032
	}
3033
 
222 andreas 3034
	// To prevent a division by zero error, we check the <factor>
3035
	if (factor == 0)
3036
	   factor = 1;
3037
 
3038
	// Beside the horizontal part of the grid, we draw the scale on the
3039
	// left and the right side.
88 andreas 3040
	int oldy = height;
3041
 
3042
	for (i = 0; i < target; i++)
3043
	{
3044
	   if (i > 0 && !(i % factor))
3045
	   {
3046
	      x1 = margin_left + 1;
3047
	      x2 = width - margin_right - 1;
3048
	      y1 = y2 = rh - h_tick * i;
3049
 
3050
	      if (y1 < 12)
3051
		 break;
3052
 
3053
	      paint.drawLine(x1, y1, x2, y2);
3054
 
3055
	      if (y1 < (oldy - lineHeight))
3056
	      {
3057
		 if (meter)
3058
		 {
3059
		    paint.setPen(QPen(barcol, 1, QPen::SolidLine));
222 andreas 3060
		    // left side
218 andreas 3061
		    if (cuType == 1)
222 andreas 3062
		    {
3063
		       paint.setPen(QPen(red, 1, QPen::SolidLine));
3064
		       paint.drawText(12, y1 - lineHeight / 2, margin_left - 14, lineHeight, Qt::AlignRight, qs.sprintf("%.1f", minSpeed + i));
3065
		    }
218 andreas 3066
		    else
3067
		       paint.drawText(12, y1 - lineHeight / 2, margin_left - 14, lineHeight, Qt::AlignRight, qs.sprintf("%.0f", (Units == 1) ? (minHeight + i) / 0.304 : minHeight + i));
3068
 
222 andreas 3069
		    // right side
3070
		    if (maxHr > 0 && cuType != 2)
88 andreas 3071
		    {
3072
		       double hrscale = (double)(maxHr - minHr) / (double)target;
3073
		       paint.setPen(QPen(blue, 1, QPen::SolidLine));
3074
		       paint.drawText(width - margin_right + 2, y1 - lineHeight / 2, margin_right - 14, lineHeight, Qt::AlignLeft, qs.sprintf("%d", (int)((double)minHr + hrscale * (double)i)));
3075
		    }
222 andreas 3076
		    else
3077
		    {
3078
		       double spscale = (maxSpeed - minSpeed) / (double)target;
3079
 
3080
		       if (cuType == 2)
3081
			  paint.setPen(QPen(red, 1, QPen::SolidLine));
3082
		       else
3083
			  paint.setPen(QPen(blue, 1, QPen::SolidLine));
3084
 
3085
		       paint.drawText(width - margin_right + 2, y1 - lineHeight / 2, margin_right - 14, lineHeight, Qt::AlignLeft, qs.sprintf("%.1f", (minSpeed + spscale * (double)i)));
3086
		    }
88 andreas 3087
		 }
3088
		 else
3089
		 {
222 andreas 3090
		    // right side
3091
		    if (cuType == 2)
3092
		    {
3093
		       paint.setPen(QPen(red, 1, QPen::SolidLine));
3094
		       paint.drawText(width - margin_right + 2, y1 - lineHeight / 2, margin_right - 14, lineHeight, Qt::AlignLeft, qs.sprintf("%.1f", minSpeed + i));
3095
		    }
3096
		    else
3097
		    {
3098
		       paint.setPen(QPen(blue, 1, QPen::SolidLine));
3099
		       paint.drawText(width - margin_right + 2, y1 - lineHeight / 2, margin_right - 14, lineHeight, Qt::AlignLeft, qs.sprintf("%d", minHr + i));
3100
		    }
88 andreas 3101
 
222 andreas 3102
		    // left side
3103
		    if ((cuType == 0 || cuType == 2) && max_height > 0)
88 andreas 3104
		    {
3105
		       double hrscale = (maxHeight - minHeight) / (double)target;
3106
		       paint.setPen(QPen(barcol, 1, QPen::SolidLine));
3107
		       paint.drawText(12, y1 - lineHeight / 2, margin_left - 14, lineHeight, Qt::AlignRight, qs.sprintf("%.0f", minHeight + hrscale * (double)i));
3108
		    }
222 andreas 3109
		    else if (max_speed > 0 && cuType == 1)
218 andreas 3110
		    {
3111
		       double hrscale = (maxSpeed - minSpeed) / (double)target;
222 andreas 3112
		       paint.setPen(QPen(red, 1, QPen::SolidLine));
3113
		       paint.drawText(12, y1 - lineHeight / 2, margin_left - 14, lineHeight, Qt::AlignRight, qs.sprintf("%.1f", minSpeed + hrscale * (double)i));
218 andreas 3114
		    }
88 andreas 3115
		}
3116
 
3117
		 paint.setPen(QPen(mark, 1, QPen::SolidLine));
3118
		 oldy = y1;
3119
	      }
3120
	   }
3121
	}
3122
 
168 andreas 3123
	// To make our graphics more beautiful, we draw lines for the
88 andreas 3124
	// heart rate limits and the average heart rate.
222 andreas 3125
	if (max_hr > 0 && cuType != 2)
88 andreas 3126
	{
3127
	int ay1, ay2, ay3, ay4, ay5;
3128
 
3129
	   x1 = margin_left + 1;
3130
	   x2 = width - margin_right - 1;
3131
 
3132
	   if (meter)
3133
	   {
3134
	      double hrscale = rh / (double)(maxHr - minHr);
3135
	      ay1 = (double)rh - (double)(lower1 - minHr) * hrscale;
3136
	      ay2 = (double)rh - (double)(lower2 - minHr) * hrscale;
3137
	      ay3 = (double)rh - (double)(lower3 - minHr) * hrscale;
3138
	      ay4 = (double)rh - (double)(upper3 - minHr) * hrscale;
3139
	      ay5 = (double)rh - (double)(avg_hr - minHr) * hrscale;
3140
	   }
3141
	   else
3142
	   {
3143
	      ay1 = (double)rh - (double)(lower1 - minHr) * h_tick;
3144
	      ay2 = (double)rh - (double)(lower2 - minHr) * h_tick;
3145
	      ay3 = (double)rh - (double)(lower3 - minHr) * h_tick;
3146
	      ay4 = (double)rh - (double)(upper3 - minHr) * h_tick;
3147
	      ay5 = (double)rh - (double)(avg_hr - minHr) * h_tick;
3148
	   }
3149
 
3150
	   paint.setPen(QPen(barcol2, 1, QPen::DashLine));	// color for limits
3151
 
3152
	   if (lower1 > minHr && lower1 < maxHr)
3153
	      paint.drawLine(x1, ay1, x2, ay1);
3154
 
3155
	   if (lower2 > minHr && lower2 < maxHr)
3156
	      paint.drawLine(x1, ay2, x2, ay2);
3157
 
3158
	   if (lower3 > minHr && lower3 < maxHr)
3159
	      paint.drawLine(x1, ay3, x2, ay3);
3160
 
3161
	   if (upper3 > minHr && upper3 < maxHr)
3162
	      paint.drawLine(x1, ay4, x2, ay4);
3163
 
3164
	   paint.setPen(QPen(red, 1, QPen::DashDotLine));	// color for average heart rate
3165
 
3166
	   if (avg_hr > minHr && avg_hr < maxHr)
3167
	      paint.drawLine(x1, ay5, x2, ay5);
3168
	}
3169
 
3170
	// Now we have a grid and we've done the scaling.
3171
	// This is the point where we draw the curves itself.
3172
	// We use different colors to draw the lines.
3173
	x1 = x2 = y1 = y2 = 0;
148 andreas 3174
	int hy1, hy2, hx1, hx2;
222 andreas 3175
	int sy1, sy2, sx1, sx2;
88 andreas 3176
	hy1 = hy2 = hx1 = hx2 = 0;
222 andreas 3177
	sy1 = sy2 = sx1 = sx2 = 0;
169 andreas 3178
	int hEc = 0;
3179
	i = 0;
3180
	AVGHEIGHT *avgHakt, *avgHfirst, *avgHlast, *avgHeight = 0;
170 andreas 3181
	avgHfirst = avgHlast = 0;
169 andreas 3182
	// To even the surface lines, we store every altitude in the
3183
	// memory, by building a chain. Then, if the user has set in the
3184
	// settings (Contour == true), we will even the line by calculating
3185
	// the average of 10 messure points and setting every value to the
3186
	// average, who is up or down more than 2 meters from the average.
3187
	while ((point = ds.getPoint(i)) != 0)
3188
	{
3189
	   if (point->alt > 20000.0 || point->alt < -1000.0)
3190
	   {
3191
	      i++;
3192
	      continue;
3193
	   }
168 andreas 3194
 
169 andreas 3195
	   if (!avgHeight)
3196
	   {
3197
	      avgHeight = new AVGHEIGHT;
3198
	      avgHeight->alt = point->alt;
3199
	      avgHeight->pos = hEc;
3200
	      avgHeight->prev = 0;
3201
	      avgHeight->next = 0;
3202
	      avgHakt = avgHeight;
3203
	      avgHfirst = avgHeight;
3204
	   }
3205
	   else
3206
	   {
3207
	      avgHakt = new AVGHEIGHT;
3208
	      avgHakt->alt = point->alt;
3209
	      avgHakt->pos = hEc;
3210
	      avgHakt->next = 0;
3211
	      avgHakt->prev = avgHeight;
3212
	      avgHeight->next = avgHakt;
3213
	      avgHeight = avgHakt;
3214
	   }
3215
 
3216
	   // FIXME: Currently we can not draw below 0 meters, because the
3217
	   // base line is always 0!
222 andreas 3218
	   if (avgHakt->alt < minHeight)
3219
	      avgHakt->alt = minHeight;
169 andreas 3220
 
3221
	   hEc++;
3222
	   i++;
3223
	}
3224
 
3225
	avgHlast = avgHeight;
3226
	// If wanted, even the lines
218 andreas 3227
	if (Contour && hEc > 0 && cuType != 0)
169 andreas 3228
	{
213 andreas 3229
	double alt[100], avg, avg1, avg2, avg3, avg4;
3230
	int a, pos;
169 andreas 3231
 
213 andreas 3232
	   for (i = 0; i < (hEc + 100); i += 100)
169 andreas 3233
	   {
213 andreas 3234
	      avg = avg1 = avg2 = avg3 = avg4 = 0.0;
3235
	      pos = 0;
169 andreas 3236
 
213 andreas 3237
	      for (a = 0; a < 100; a++)
169 andreas 3238
	      {
3239
		 alt[a] = getAvgAlt(avgHfirst, i + a);
3240
		 avg += alt[a];
213 andreas 3241
 
3242
		 if (a < 25)
3243
		    avg1 += alt[a];
3244
		 else if (a < 50)
3245
		    avg2 += alt[a];
3246
		 else if (a < 75)
3247
		    avg3 += alt[a];
3248
		 else
3249
		    avg4 += alt[a];
169 andreas 3250
	      }
3251
 
213 andreas 3252
	      if ((i + 100) >= hEc)
169 andreas 3253
		 avg /= (double)(hEc - i) + 1.0;
3254
	      else
213 andreas 3255
		 avg /= 100.0;
169 andreas 3256
 
213 andreas 3257
	      for (a = 0; a < 100; a++)
169 andreas 3258
	      {
3259
		 if ((avgHakt = getAvgPtr(avgHfirst, i + a)) != 0)
3260
		 {
3261
		    if ((avgHakt->alt - avg) > 2 || (avgHakt->alt - avg) < -2)
3262
		       avgHakt->alt = avg;
3263
		 }
3264
	      }
3265
	   }
3266
	}
3267
 
222 andreas 3268
	// plot the elevation, speed and/or heart rate. Depends on <cuType>)
168 andreas 3269
	i = 0;
169 andreas 3270
	int j = 0;
218 andreas 3271
	POINT *oldPoint = 0;
222 andreas 3272
	double speed = 0.0;	// calculated speed
3273
	bool pause = false;	// filter pause out of speed
3274
	unsigned long t1, t2;
3275
	t1 = t2 = 0;
218 andreas 3276
 
88 andreas 3277
	while ((point = ds.getPoint(i)) != 0)
3278
	{
218 andreas 3279
	   if (!oldPoint)
3280
	      oldPoint = point;
3281
 
88 andreas 3282
	   // calculate the y position based on the time
3283
	   qt = garmin_dtime(point->time);
3284
	   secs = zeit.secsTo(qt->time());
3285
	   delete qt;
3286
	   x2 = secs * w_tick + margin_left + 1;
3287
	   hx2 = x2;
222 andreas 3288
	   sx2 = x2;
88 andreas 3289
 
3290
	   if (x1 == 0)
3291
	      x1 = x2;
3292
 
3293
	   if (hx1 == 0)
3294
	      hx1 = hx2;
3295
 
222 andreas 3296
	   if (sx1 == 0)
3297
	      sx1 = sx2;
3298
 
3299
	   // The speed is not very exact, because smallest time is
3300
	   // one second. This allows a maximum error of 99 hundredths
3301
	   // of a second, what is very close to one second. Because of
3302
	   // this, speed seems to hop for every messure point. This
3303
	   // looks ugly, but currently I don't know how to make it
3304
	   // better.
3305
	   if (cuType == 1 || cuType == 2)	// Draw speed?
88 andreas 3306
	   {
218 andreas 3307
	      double dist;
3308
	      double sc;
168 andreas 3309
 
222 andreas 3310
	      if (!pause && point->distance > 1.0e10)
218 andreas 3311
	      {
222 andreas 3312
		 pause = true;
3313
		 t1 = point->time;
3314
	      }
3315
	      else if (pause)
3316
	      {
3317
		 pause = false;
3318
		 t2 = point->time;
3319
		 i += 2;
3320
		 continue;
3321
	      }
3322
 
3323
	      if (point->distance >= 0.1 && point->distance < 1.0e10)
3324
	      {
218 andreas 3325
		 dist = point->distance - oldPoint->distance;
3326
		 sc = point->time - oldPoint->time;
222 andreas 3327
 
3328
		 if (t2 > t1)
3329
		 {
3330
		    sc -= t2 - t1;
3331
 
3332
		    if (sc <= 0.0)
3333
		       sc = 1.0;		// at least 1 second!
3334
		 }
3335
 
218 andreas 3336
		 speed = (dist / sc) * 3.6;
168 andreas 3337
 
218 andreas 3338
		 if (Units == 1)
3339
		    speed /= 1.609344;
3340
 
222 andreas 3341
		 if (speed < minSpeed || speed > 400.0)
3342
		    speed = minSpeed;
218 andreas 3343
 
222 andreas 3344
		 if ((meter && cuType == 1) || (!meter && cuType == 2))
218 andreas 3345
		    y2 = (double)rh - (speed - minSpeed) * h_tick;
3346
		 else
3347
		 {
3348
		    double hrscale = rh / (maxSpeed - minSpeed);
3349
		    y2 = (double)rh - (speed - minSpeed) * hrscale;
3350
		 }
3351
 
3352
		 if (y1 == 0)
3353
		    y1 = y2;
3354
 
222 andreas 3355
		 paint.setPen(QPen(red, 1, QPen::SolidLine));
218 andreas 3356
		 paint.drawLine(x1, y1, x2, y2);
3357
		 y1 = y2;
3358
		 x1 = x2;
222 andreas 3359
		 t1 = t2 = 0;
3360
		 oldPoint = point;
218 andreas 3361
	      }
3362
	   }
222 andreas 3363
 
3364
	   if (cuType == 0 || cuType == 2)		// Draw elevation?
218 andreas 3365
	   {
3366
	      if (point->alt < 20000.0 && point->alt > -1000.0)
88 andreas 3367
	      {
218 andreas 3368
	      double alt = getAvgAlt(avgHfirst, j);
88 andreas 3369
 
218 andreas 3370
		 j++;
3371
 
3372
		 if (meter)
222 andreas 3373
		    sy2 = (double)rh - (alt - minHeight) * h_tick;
218 andreas 3374
		 else
3375
		 {
3376
		    double hrscale = rh / (maxHeight - minHeight);
222 andreas 3377
		    sy2 = (double)rh - (alt - minHeight) * hrscale;
218 andreas 3378
		 }
3379
 
222 andreas 3380
		 if (sy1 == 0)
3381
		    sy1 = sy2;
218 andreas 3382
 
3383
		 paint.setPen(QPen(barcol, 1, QPen::SolidLine));
222 andreas 3384
		 paint.drawLine(sx1, sy1, sx2, sy2);
3385
		 sy1 = sy2;
3386
		 sx1 = sx2;
218 andreas 3387
	      }
88 andreas 3388
	   }
3389
 
222 andreas 3390
	   if (point->heart_rate > 0 && cuType < 2)	// Draw heart rate?
88 andreas 3391
	   {
3392
	      if (meter)
3393
	      {
3394
		 double hrscale = rh / (double)(maxHr - minHr);
3395
		 hy2 = (double)rh - (double)(point->heart_rate - minHr) * hrscale;
3396
	      }
3397
	      else
3398
		 hy2 = (double)rh - (double)(point->heart_rate - minHr) * h_tick;
3399
 
3400
	      if (hy1 == 0)
3401
		 hy1 = hy2;
3402
 
3403
	      paint.setPen(QPen(blue, 1, QPen::SolidLine));
3404
	      paint.drawLine(hx1, hy1, hx2, hy2);
3405
	      hy1 = hy2;
3406
	      hx1 = hx2;
3407
	   }
3408
 
3409
	   i++;
3410
	}
3411
 
3412
	paint.end();
3413
	imgProfile->setPixmap(pmProfile);
3414
 
169 andreas 3415
	// free the chain of altitudes
3416
	avgHakt = avgHfirst;
3417
 
3418
	while (avgHakt)
3419
	{
3420
	   avgHeight = avgHakt->next;
3421
	   delete avgHakt;
3422
	   avgHakt = avgHeight;
3423
	}
3424
 
88 andreas 3425
//	if (bProfile)
3426
//	   bitBlt(imgProfile, 0, 0, &pmProfile);
3427
}
3428
 
169 andreas 3429
double sportwatcherWidget::getAvgAlt(AVGHEIGHT *avgHeight, int pos)
3430
{
3431
AVGHEIGHT *akt;
3432
 
170 andreas 3433
	if (!avgHeight)
3434
	   return 0.0;
3435
 
169 andreas 3436
	akt = avgHeight;
3437
 
3438
	while (akt)
3439
	{
3440
	   if (akt->pos == pos)
3441
	      return akt->alt;
3442
 
3443
	   akt = akt->next;
3444
	}
3445
 
3446
	return 0.0;
3447
}
3448
 
3449
AVGHEIGHT *sportwatcherWidget::getAvgPtr(AVGHEIGHT *avgHeight, int pos)
3450
{
3451
AVGHEIGHT *akt;
3452
 
3453
	akt = avgHeight;
3454
 
3455
	while (akt)
3456
	{
3457
	   if (akt->pos == pos)
3458
	      return akt;
3459
 
3460
	   akt = akt->next;
3461
	}
3462
 
3463
	return 0;
3464
}
3465
 
88 andreas 3466
void sportwatcherWidget::resizeEvent(QResizeEvent */* *e */)
3467
{
132 andreas 3468
	showTrack(zfactor);
88 andreas 3469
	showCurves();
3470
}
3471
 
3472
void sportwatcherWidget::paintEvent(QPaintEvent */* *e */)
3473
{
132 andreas 3474
	showTrack(zfactor);
88 andreas 3475
	showCurves();
3476
}
3477
 
132 andreas 3478
void sportwatcherWidget::mouseMoveEvent(QMouseEvent *e)
3479
{
3480
QPoint pos(0, 0);
3481
QPoint ev = imgMap->mapFrom(this, e->pos());
3482
static QRect coord;
88 andreas 3483
 
132 andreas 3484
	if (!stateHand)
3485
	   return;
3486
 
3487
	if (ev.x() >= pos.x() &&
3488
	    ev.y() >= pos.y() &&
3489
	    ev.x() <= (pos.x() + imgMap->geometry().width()) &&
3490
	    ev.y() <= (pos.y() + imgMap->geometry().height()))
3491
	{
3492
	   if (lmbPressed == 1)
3493
	   {
3494
	      coord.setCoords(ev.x(), ev.y(), 0, 0);
3495
	      lmbPressed = 0;
3496
	   }
3497
	   else
3498
	   {
3499
	      coord.setRight(ev.x());
3500
	      coord.setBottom(ev.y());
3501
	   }
3502
 
3503
	   if (lmbPressed == 2)
3504
	   {
3505
	      showTrack(zfactor, coord, mapLap);
3506
	      lmbPressed = 0;
3507
	   }
3508
	}
3509
}
3510
 
3511
void sportwatcherWidget::mousePressEvent(QMouseEvent *e)
3512
{
3513
	if (stateHand && e->button() == QMouseEvent::LeftButton)
3514
	   lmbPressed = 1;	// Left Mouse Button is pressed
3515
	else if (stateHand)
3516
	   lmbPressed = 0;	// Wrong button is pressed
3517
 
3518
	if (stateGlas)
3519
	{
3520
	   if (e->button() == QMouseEvent::LeftButton)
3521
	      btGlasPlusSlot();
3522
	   else if (e->button() == QMouseEvent::RightButton)
3523
	      btGlasMinusSlot();
3524
	}
3525
}
3526
 
3527
void sportwatcherWidget::mouseReleaseEvent(QMouseEvent *e)
3528
{
3529
	if (stateHand && e->button() == QMouseEvent::LeftButton)
3530
	{
3531
	   lmbPressed = 2;	// Left Mouse Button was released
3532
	   mouseMoveEvent(e);
3533
	}
3534
}
3535
 
88 andreas 3536
/*
3537
 * Private functions to help decode the data
3538
 */
3539
QDateTime *sportwatcherWidget::garmin_dtime (uint32 t)
3540
{
3541
time_t     tval;
3542
struct tm  tmval;
3543
QTime ti;
3544
QDate dt;
3545
QDateTime *qt;
3546
 
3547
	if (t == 0)
3548
	   return new QDateTime(QDate(1900, 1, 1), QTime(0, 0, 0, 0));
3549
 
3550
	tval = t + TIME_OFFSET;
3551
	localtime_r (&tval, &tmval);
3552
	qt = new QDateTime();
3553
	qt->setDate(QDate(tmval.tm_year+1900, tmval.tm_mon+1, tmval.tm_mday));
3554
	qt->setTime(QTime(tmval.tm_hour, tmval.tm_min, tmval.tm_sec, 0));
3555
	/* OK.  Done. */
3556
	return qt;
3557
}
3558
 
104 andreas 3559
bool sportwatcherWidget::writeTag(const QFile &fn, const QString &str, int indent)
3560
{
3561
QString qs;
3562
char *p = new char[str.length()+100];
3563
QCString qcs;
3564
int i;
88 andreas 3565
 
171 andreas 3566
	if (indent > 0)
3567
	   qs.fill(' ', indent * 3);
3568
 
104 andreas 3569
	qs.append(str);
3570
	qcs = qs.utf8();
3571
	qstrcpy(p, qcs);
3572
	i = strlen(p);
3573
 
3574
	if (write(fn.handle(), p, i) != i)
3575
	{
3576
	   delete p;
3577
	   return false;
3578
	}
3579
 
3580
	delete p;
3581
	return true;
3582
}
3583
 
155 andreas 3584
#if defined HAVE_GDAL && HAVE_LIBGDAL1_5_0
151 andreas 3585
bool sportwatcherWidget::writeWMSTag(double llat, double llon, double rlat, double rlon, int width, int height)
3586
{
3587
QFile fl(MAP);
152 andreas 3588
QString xml, s, srs, crs, styles, bSize, ext;
3589
QDir dir = QDir::home();
3590
QString path = dir.absPath();
157 andreas 3591
int item, isrs;
3592
double _llat, _llon, _rlat, _rlon;
3593
bool offline, square;
151 andreas 3594
 
3595
	if (!fl.open(IO_ReadWrite | IO_Truncate))
3596
	{
3597
	   KMessageBox::error (this, i18n("Error opening or creating the WMS tag file!\nPlease check file name and/or permissions."));
3598
	   return false;
3599
	}
3600
 
152 andreas 3601
	KSimpleConfig *cfg = new KSimpleConfig(QString("sportwatcher.rc"));
3602
	cfg->setGroup(QString("WMS"));
157 andreas 3603
	square = cfg->readBoolEntry("Square", false);
152 andreas 3604
	styles = cfg->readEntry("Styles");
3605
 
151 andreas 3606
	xml = "<GDAL_WMS>\n";
3607
	xml += "   <Service name=\"WMS\">\n";
3608
	xml += "      <Version>1.1.1</Version>\n";
152 andreas 3609
	xml += "      <ServerURL>" + cfg->readEntry("ServerURL", "http://onearth.jpl.nasa.gov/wms.cgi") + "?</serverURL>\n";
157 andreas 3610
	isrs = cfg->readNumEntry("SRS", 0);
3611
	_llon = llon;
3612
	_llat = llat;
3613
	_rlon = rlon;
3614
	_rlat = rlat;
3615
	offline = false;
152 andreas 3616
 
157 andreas 3617
	switch (isrs)
152 andreas 3618
	{
3619
	   case 0: srs = QString("EPSG:4326"); break;
157 andreas 3620
 
3621
	   case 1:
3622
	      srs = QString("EPSG:31257");
3623
	      offline = transCoords(&_llat, &_llon, &_rlat, &_rlon, 31257, width, height, square);
3624
	   break;
3625
 
3626
	   case 2:
3627
	      srs = QString("EPSG:31258");
3628
	      offline = transCoords(&_llat, &_llon, &_rlat, &_rlon, 31258, width, height, square);
3629
	   break;
3630
 
3631
	   case 3:
3632
	      srs = QString("EPSG:31259");
3633
	      offline = transCoords(&_llat, &_llon, &_rlat, &_rlon, 31259, width, height, square);
3634
	   break;
3635
 
3636
	   case 4:
3637
	      srs = QString("EPSG:31286");
3638
	      offline = transCoords(&_llat, &_llon, &_rlat, &_rlon, 31286, width, height, square);
3639
	   break;
3640
 
3641
	   case 5:
3642
	      srs = QString("EPSG:31287");
3643
	      offline = transCoords(&_llat, &_llon, &_rlat, &_rlon, 31287, width, height, square);
3644
	   break;
3645
 
3646
	   case 6:
3647
	      srs = QString("EPSG:31288");
3648
	      offline = transCoords(&_llat, &_llon, &_rlat, &_rlon, 31288, width, height, square);
3649
	   break;
3650
 
152 andreas 3651
	   default: srs = QString("EPSG:4326");
3652
	}
3653
 
3654
	xml += "      <SRS>" + srs + "</SRS>\n";
3655
	item = cfg->readNumEntry("CRS", 0);
3656
 
3657
	switch (item)
3658
	{
3659
	   case 0: crs = QString("CRS:83"); break;
157 andreas 3660
	   case 1: crs = QString("CRS:84"); break;
3661
	   case 2: crs = QString("EPSG:4326"); break;
3662
	   case 3: crs = QString("EPSG:31259"); break;
3663
	   case 4: crs = QString("EPSG:31287"); break;
152 andreas 3664
	   default: crs = QString("CRS:83"); break;
3665
	}
3666
 
3667
	xml += "      <CRS>" + crs + "</CRS>\n";
3668
	item = cfg->readNumEntry("Image", 2);
3669
	xml += "      <ImageFormat>image/";
3670
 
3671
	switch (item)
3672
	{
3673
	   case 0: xml += "gif"; ext = QString(".gif"); break;
3674
	   case 1: xml += "jpeg"; ext = QString(".jpg"); break;
3675
	   case 2: xml += "png"; ext = QString(".png"); break;
3676
	   case 3: xml += "tiff"; ext = QString(".tif"); break;
3677
	   default: xml += "png"; ext = QString(".png");
3678
	}
3679
 
3680
	xml += "</ImageFormat>\n";
3681
 
3682
	xml += "      <Layers>" + cfg->readEntry("Layer") + "</Layers>\n";
3683
 
3684
	if (!styles.isEmpty())
3685
	   xml += "      <Styles>" + styles + "</Styles>\n";
3686
 
151 andreas 3687
	xml += "      <BBoxOrder>xyXY</BBoxOrder>\n";
3688
	xml += "   </Service>\n";
3689
	xml += "   <DataWindow>\n";
157 andreas 3690
	s.sprintf ("%f", _llat);
151 andreas 3691
	xml += "      <UpperLeftX>" + s + "</UpperLeftX>\n";
157 andreas 3692
	s.sprintf ("%f", _llon);
151 andreas 3693
	xml += "      <UpperLeftY>" + s + "</UpperLeftY>\n";
157 andreas 3694
	s.sprintf ("%f", _rlat);
151 andreas 3695
	xml += "      <LowerRightX>" + s + "</LowerRightX>\n";
157 andreas 3696
	s.sprintf ("%f", _rlon);
151 andreas 3697
	xml += "      <LowerRightY>" + s + "</LowerRightY>\n";
3698
	s.sprintf ("%d", width);
3699
	xml += "      <SizeX>" + s + "</SizeX>\n";
3700
	s.sprintf ("%d", height);
3701
	xml += "      <SizeY>" + s + "</SizeY>\n";
3702
	xml += "   </DataWindow>\n";
157 andreas 3703
 
3704
/*	switch (isrs)
3705
	{
3706
	   case 0: srs = QString("EPSG:4326"); break;
3707
	   case 1: srs = QString("EPSG:31259"); break;
3708
	   case 2: srs = QString("EPSG:31286"); break;
3709
	   case 3: srs = QString("EPSG:31287"); break;
3710
	   case 4: srs = QString("EPSG:31288"); break;
3711
	   default: srs = QString("EPSG:4326");
3712
	}
3713
*/
3714
//	srs = QString("EPSG:4326");
3715
	xml += "   <Projection>" + srs + "</Projection>\n";
152 andreas 3716
	xml += "   <BandsCount>" + cfg->readEntry("Bands", "3") + "</BandsCount>\n";
3717
	item = cfg->readNumEntry("Tile", 2);
3718
 
3719
	switch (item)
3720
	{
3721
	   case 0: bSize = QString("64"); break;
3722
	   case 1: bSize = QString("128"); break;
3723
	   case 2: bSize = QString("256"); break;
3724
	   case 3: bSize = QString("512"); break;
3725
	   case 4: bSize = QString("1024"); break;
3726
	   default: bSize = QString("256");
3727
	}
3728
 
3729
	xml += "   <BlockSizeX>" + bSize + "</BlockSizeX>\n";
3730
	xml += "   <BlockSizeY>" + bSize + "</BlockSizeY>\n";
3731
	xml += "   <OverviewCount>" + cfg->readEntry("Overview", "10") + "</OverviewCount>\n";
151 andreas 3732
	xml += "   <Cache>\n";
152 andreas 3733
	xml += "      <Path>" + path + "/.gdalwmscache" + "</Path>\n";
3734
	xml += "      <Depth>" + cfg->readEntry("Depth", "2") + "</Depth>\n";
3735
	xml += "      <Extension>" + ext + "</Extension>\n";
151 andreas 3736
	xml += "   </Cache>\n";
152 andreas 3737
	QString off((cfg->readBoolEntry("Offline", false)) ? "true" : "false");
3738
	QString adv((cfg->readBoolEntry("Advice", false)) ? "true" : "false");
3739
	QString ver((cfg->readBoolEntry("Verify", true)) ? "true" : "false");
157 andreas 3740
 
3741
	if (offline)
3742
	   xml += "   <OfflineMode>true</OfflineMode>\n";
3743
	else
3744
	   xml += "   <OfflineMode>" + off + "</OfflineMode>\n";
3745
 
152 andreas 3746
	xml += "   <AdviseRead>" + adv + "</AdviseRead>\n";
3747
	xml += "   <VerifyAdviseRead>" + ver + "</VerifyAdviseRead>\n";
151 andreas 3748
	xml += "</GDAL_WMS>\n";
3749
 
3750
	write (fl.handle(), xml.ascii(), strlen (xml.ascii()));
3751
	fl.close();
152 andreas 3752
	delete cfg;
151 andreas 3753
	return true;
3754
}
3755
 
157 andreas 3756
bool sportwatcherWidget::transCoords (double *x1, double *y1, double *x2, double *y2, int code, int width, int height, bool square)
151 andreas 3757
{
157 andreas 3758
OGRSpatialReference oSourceSRS, oTargetSRS;
3759
OGRCoordinateTransformation *poCT;
3760
 
3761
	oSourceSRS.SetWellKnownGeogCS ("WGS84");
3762
	oTargetSRS.importFromEPSG(code);
3763
	poCT = OGRCreateCoordinateTransformation (&oSourceSRS, &oTargetSRS);
3764
 
3765
	if (poCT == NULL || !poCT->Transform( 1, x1, y1))
3766
	{
3767
	   KMessageBox::error(this, i18n("Translation between coordinate systems failed!"));
3768
 
3769
	   if (poCT != NULL)
3770
	      delete poCT;
3771
 
3772
	   return true;
3773
	}
3774
 
3775
	if (poCT != NULL)
3776
	{
3777
	   poCT->Transform (1, x2, y2);
3778
	   delete poCT;
3779
	}
3780
 
3781
	if (square)
3782
	{
3783
	double wdiff = (double)((long)(*x1 - *x2) / (width / 2 * 2) * (width / 2 * 2));
3784
	double hdiff = (double)((long)(*y2 - *y1) / (height / 2 * 2) * (height / 2 * 2));
3785
 
3786
	   *x2 = *x1 - wdiff; // * (double)mFactor;
3787
	   *y2 = *y1 + hdiff; // * (double)mFactor;
3788
//	   *x2 = *x1 - (double)((long)(wdiff / mFactor * mFactor));
3789
//	   *y2 = *y1 - (double)((long)(hdiff / mFactor * mFactor));
3790
/*	   wdiff = wdiff - (*x1 - *x2);
3791
	   hdiff = hdiff - (*y2 - *y1);
3792
	   *x1 -= wdiff / 2.0;
3793
	   *x2 -= wdiff / 2.0;
3794
	   *y1 += hdiff / 2.0;
3795
	   *y2 += hdiff / 2.0; */
3796
	}
3797
 
3798
	return false;
151 andreas 3799
}
3800
 
158 andreas 3801
QString *sportwatcherWidget::getProjection (int isrs, QString *srs)
3802
{
3803
	switch (isrs)
3804
	{
3805
	   case 0: *srs = QString("EPSG:4326"); break;
3806
	   case 1: *srs = QString("EPSG:31257"); break;
3807
	   case 2: *srs = QString("EPSG:31258"); break;
3808
	   case 3: *srs = QString("EPSG:31259"); break;
3809
	   case 4: *srs = QString("EPSG:31286"); break;
3810
	   case 5: *srs = QString("EPSG:31287"); break;
3811
	   case 6: *srs = QString("EPSG:31288"); break;
3812
	   default: *srs = QString("EPSG:4326");
3813
	}
3814
 
3815
	return srs;
3816
}
3817
 
3818
bool sportwatcherWidget::warpImage(QString fn, QString *fName)
3819
{
3820
GDALDatasetH  hSrcDS, hDstDS;
3821
GDALDataset *inSet, *outSet;
3822
GDALDataType eDT;
3823
GDALRasterBand *poBand;
3824
GDALDriverH hDriver;
3825
char hv0[256];
3826
int nXSize, nYSize;
3827
double adfGeoTransform[6];
3828
double oriLeftLon, oriRightLon, oriLeftLat, oriRightLat;
3829
 
159 andreas 3830
 
3831
	// Loading the user set geo coords of our source image and
3832
	// load the projection used for that image
3833
	KSimpleConfig *cfg = new KSimpleConfig(QString("sportwatcher.rc"));
3834
	cfg->setGroup(QString("ImageCoords"));
3835
	oriLeftLon = cfg->readDoubleNumEntry("LeftLon", 0.0);
3836
	oriLeftLat = cfg->readDoubleNumEntry("LeftLat", 0.0);
3837
	oriRightLon = cfg->readDoubleNumEntry("RightLon", 0.0);
3838
	oriRightLat = cfg->readDoubleNumEntry("RightLat", 0.0);
3839
	int isrs = cfg->readNumEntry("SRS", 0);
3840
 
158 andreas 3841
	// Create a temporary file name for our output file
3842
	strcpy (hv0, "/tmp/SportWatcherTIFFXXXXXX");
216 andreas 3843
	mkdtemp (&hv0[0]);
158 andreas 3844
	*fName = QString(hv0) + ".tif";
3845
 
3846
	// Open input and output files.
3847
	if ((hSrcDS = GDALOpen(fn.ascii(), GA_ReadOnly)) == NULL)
3848
	{
3849
	   KMessageBox::error(this, i18n("Error opening an image file!"));
3850
	   return false;
3851
	}
3852
 
3853
	inSet = (GDALDataset *)hSrcDS;
3854
	// Create output with same datatype as first input band.
3855
	poBand = inSet->GetRasterBand (1);
3856
	eDT = poBand->GetRasterDataType ();
3857
 
3858
	if ((hDriver = GDALGetDriverByName ("GTiff")) == NULL)
3859
	{
3860
	   KMessageBox::error(this, i18n("Error loading the TIFF driver!"));
3861
	   GDALClose (hSrcDS);
3862
	   return false;
3863
	}
3864
 
3865
	// Get dimensions of image and set transform data
3866
	int nRasterCount = inSet->GetRasterCount();
3867
	nXSize = inSet->GetRasterXSize();
3868
	nYSize = inSet->GetRasterYSize();
3869
 
159 andreas 3870
	// cut the wanted region out of image
3871
	transform *tf = new transform (oriLeftLat, oriLeftLon, oriRightLat, oriRightLon);
3872
	tf->setDimensions(nXSize, nYSize);
158 andreas 3873
 
159 andreas 3874
	if (!tf->cutImage (geoRect.llat, geoRect.llon, geoRect.rlat, geoRect.rlon, fn))
3875
	{
3876
	   GDALClose (hSrcDS);
3877
	   return false;
3878
	}
158 andreas 3879
 
159 andreas 3880
	GDALClose (hSrcDS);
3881
	QString nfn = fn + "_tmp.png";
158 andreas 3882
 
159 andreas 3883
	// repeat the part above and open the now cutted part of the image.
3884
	// Open input and output files.
3885
	if ((hSrcDS = GDALOpen(nfn.ascii(), GA_ReadOnly)) == NULL)
3886
	{
3887
	   KMessageBox::error(this, i18n("Error opening an image file!"));
3888
	   return false;
3889
	}
158 andreas 3890
 
159 andreas 3891
	inSet = (GDALDataset *)hSrcDS;
3892
	// Create output with same datatype as first input band.
3893
	poBand = inSet->GetRasterBand (1);
3894
	eDT = poBand->GetRasterDataType ();
158 andreas 3895
 
159 andreas 3896
	if ((hDriver = GDALGetDriverByName ("GTiff")) == NULL)
158 andreas 3897
	{
159 andreas 3898
	   KMessageBox::error(this, i18n("Error loading the TIFF driver!"));
3899
	   GDALClose (hSrcDS);
3900
	   return false;
158 andreas 3901
	}
3902
 
159 andreas 3903
	// Get dimensions of image and set transform data
3904
	nRasterCount = inSet->GetRasterCount();
3905
	nXSize = inSet->GetRasterXSize();
3906
	nYSize = inSet->GetRasterYSize();
3907
 
158 andreas 3908
	// Set the values needed to transform the image
3909
	OGRSpatialReference iSRS;
3910
	const char *iWKT;
3911
 
3912
	switch (isrs)
3913
	{
3914
	   case 0: iSRS.importFromEPSG(4326); break;
3915
	   case 1: iSRS.importFromEPSG(31257); break;
3916
	   case 2: iSRS.importFromEPSG(31258); break;
3917
	   case 3: iSRS.importFromEPSG(31259); break;
3918
	   case 4: iSRS.importFromEPSG(31286); break;
3919
	   case 5: iSRS.importFromEPSG(31287); break;
3920
	   case 6: iSRS.importFromEPSG(31288); break;
3921
	   default: iSRS.importFromEPSG(4326);
3922
	}
3923
 
3924
	iSRS.exportToWkt ((char **)&iWKT);
3925
 
3926
	if (inSet->SetProjection (iWKT) != CE_None)
3927
	{
3928
	   KMessageBox::error(this, i18n("Error setting projection on source!"));
3929
	   GDALClose (hSrcDS);
3930
	   return false;
3931
	}
3932
 
159 andreas 3933
	adfGeoTransform[0] = geoRect.llon;
3934
	adfGeoTransform[1] = (geoRect.rlon - geoRect.llon) / (double)nXSize;
158 andreas 3935
	adfGeoTransform[2] = 0.0;
159 andreas 3936
	adfGeoTransform[3] = geoRect.llat;
158 andreas 3937
	adfGeoTransform[4] = 0.0;
159 andreas 3938
	adfGeoTransform[5] = -1.0 * ((geoRect.llat - geoRect.rlat) / (double)nYSize);
158 andreas 3939
 
3940
	if (inSet->SetGeoTransform (&adfGeoTransform[0]) != CE_None)
3941
	{
3942
	   KMessageBox::error(this, i18n("Error setting geo transform data to source!"));
3943
	   GDALClose (hSrcDS);
3944
	   return false;
3945
	}
3946
 
159 andreas 3947
	// Get Source coordinate system.
158 andreas 3948
	const char *pszSrcWKT, *pszDstWKT = NULL;
3949
 
3950
	if ((pszSrcWKT = GDALGetProjectionRef (hSrcDS)) == NULL)
3951
	{
3952
	   KMessageBox::error(this, i18n("Error getting the projection reference"));
3953
	   GDALClose (hSrcDS);
3954
	   return false;
3955
	}
3956
 
3957
	// Setup output coordinate system that is UTM ? WGS84.
3958
	OGRSpatialReference oSRS;
3959
 
159 andreas 3960
//	oSRS.SetUTM( 0, TRUE );
158 andreas 3961
	oSRS.SetWellKnownGeogCS("WGS84");
3962
	oSRS.exportToWkt ((char **)&pszDstWKT);
3963
 
159 andreas 3964
	// Create the output file.
158 andreas 3965
	double adfDstGeoTransform[6];
159 andreas 3966
	adfDstGeoTransform[0] = geoRect.llon;
3967
	adfDstGeoTransform[1] = (geoRect.rlon - geoRect.llon) / (double)geoRect.width;
158 andreas 3968
	adfDstGeoTransform[2] = 0.0;
3969
	adfDstGeoTransform[3] = geoRect.llat;
3970
	adfDstGeoTransform[4] = 0.0;
159 andreas 3971
	adfDstGeoTransform[5] = -1.0 * ((geoRect.llat - geoRect.rlat) / (double)geoRect.height);
158 andreas 3972
 
159 andreas 3973
	if ((hDstDS = GDALCreate(hDriver, fName->ascii(), geoRect.width, geoRect.height,
158 andreas 3974
			nRasterCount, eDT, NULL )) == NULL)
3975
	{
3976
	   KMessageBox::error(this, i18n("Error creating a temporary image file! (" + *fName + ")"));
3977
	   GDALClose (hSrcDS);
3978
	   return false;
3979
	}
3980
 
3981
	outSet = (GDALDataset *)hDstDS;
3982
 
159 andreas 3983
	for (int i = 0; i < nRasterCount; i++)
3984
	{
3985
	   poBand = outSet->GetRasterBand (i+1);
3986
	   poBand->Fill (0.0);
3987
	}
3988
 
158 andreas 3989
	if (outSet->SetProjection (pszDstWKT) != CE_None)
3990
	{
3991
	   KMessageBox::error(this, i18n("Error setting projection on destination!"));
3992
	   GDALClose (hDstDS);
3993
	   GDALClose (hSrcDS);
3994
	   unlink (fName->ascii());
3995
	   return false;
3996
	}
3997
 
3998
	if (outSet->SetGeoTransform (&adfDstGeoTransform[0]) != CE_None)
3999
	{
159 andreas 4000
	   KMessageBox::error(this, i18n("Error setting geo transform data to destination!"));
158 andreas 4001
	   GDALClose (hDstDS);
4002
	   GDALClose (hSrcDS);
4003
	   unlink (fName->ascii());
4004
	   return false;
4005
	}
159 andreas 4006
 
158 andreas 4007
	// Copy the color table, if required.
4008
	GDALColorTableH hCT;
4009
 
4010
	for (int i = 0; i < nRasterCount; i++)
4011
	{
4012
	   hCT = GDALGetRasterColorTable (inSet->GetRasterBand (i+1));
4013
 
4014
	   if (hCT != NULL)
4015
              GDALSetRasterColorTable (outSet->GetRasterBand (i+1), hCT);
4016
	}
4017
 
4018
	// Setup warp options.
4019
	GDALWarpOptions *psWarpOptions = GDALCreateWarpOptions();
4020
 
4021
	psWarpOptions->hSrcDS = hSrcDS;
4022
	psWarpOptions->hDstDS = hDstDS;
4023
 
4024
	psWarpOptions->nBandCount = nRasterCount;
4025
	psWarpOptions->panSrcBands =
4026
        	(int *) CPLMalloc(sizeof(int) * psWarpOptions->nBandCount );
4027
	psWarpOptions->panDstBands =
4028
		(int *) CPLMalloc(sizeof(int) * psWarpOptions->nBandCount );
4029
 
4030
	for (int i = 0; i < nRasterCount; i++)
4031
	{
4032
	   psWarpOptions->panSrcBands[i] = i+1;
4033
	   psWarpOptions->panDstBands[i] = i+1;
4034
	}
4035
 
159 andreas 4036
//	psWarpOptions->pfnProgress = GDALTermProgress;
158 andreas 4037
 
4038
	// Establish reprojection transformer.
4039
	psWarpOptions->pTransformerArg =
4040
        	GDALCreateGenImgProjTransformer(hSrcDS,
4041
					 GDALGetProjectionRef(hSrcDS), 
4042
					 hDstDS,
4043
					 GDALGetProjectionRef(hDstDS),
159 andreas 4044
					 FALSE, 0.0, 1);
158 andreas 4045
 
4046
	psWarpOptions->pfnTransformer = GDALGenImgProjTransform;
4047
 
4048
	// Initialize and execute the warp operation.
4049
	GDALWarpOperation oOperation;
4050
 
4051
	if (oOperation.Initialize (psWarpOptions) != CE_None)
4052
	{
4053
	   KMessageBox::error(this, i18n("Error initializing warp operation!"));
4054
	   GDALClose (hDstDS);
4055
	   GDALClose (hSrcDS);
4056
	   unlink (fName->ascii());
4057
	   return false;
4058
	}
4059
 
159 andreas 4060
	oOperation.ChunkAndWarpMulti (0, 0, geoRect.width, geoRect.height);
158 andreas 4061
	GDALDestroyGenImgProjTransformer (psWarpOptions->pTransformerArg);
4062
	GDALDestroyWarpOptions(psWarpOptions);
4063
 
4064
	GDALClose (hDstDS);
4065
	GDALClose (hSrcDS);
159 andreas 4066
	unlink (nfn.ascii());
158 andreas 4067
	return true;
4068
}
4069
 
151 andreas 4070
#endif
4071
 
88 andreas 4072
#include "sportwatcherwidget.moc"
4073