Subversion Repositories public

Rev

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