Subversion Repositories public

Rev

Rev 194 | Details | Compare with Previous | Last modification | View Log | RSS feed

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