1
0
mirror of https://github.com/tumic0/GPXSee.git synced 2025-07-01 13:29:16 +02:00

Compare commits

..

200 Commits
3.10 ... 4.13

Author SHA1 Message Date
b14eeb58ab Fixed scale size in hi-res prints 2017-08-31 16:28:37 +02:00
8e932b966c Fixed msvc warning 2017-08-31 15:32:44 +02:00
35818ce16e Removed obsolete size guard 2017-08-31 08:10:09 +02:00
6ef7537dff Added some more paper sizes 2017-08-31 07:57:46 +02:00
abbb823890 Removed DPI dependency in print font size computation 2017-08-31 00:07:29 +02:00
0a4f8a46d4 Update gpxsee_sv.ts (#31)
* Update gpxsee_sv.ts

* Update gpxsee_sv.ts

Sorry, missed 2 strings.
2017-08-30 21:59:14 +02:00
fd2823c703 Version++ 2017-08-30 13:59:22 +02:00
d16b61051f Localization update 2017-08-30 13:56:23 +02:00
e69f17aad5 Print font size id now appropriate to the page size 2017-08-30 13:09:54 +02:00
33b1e179d3 Use the correct DPI value for zooming 2017-08-29 15:31:12 +02:00
5efb9f8a4e Added resolution setting to export dialogue. 2017-08-28 17:48:46 +02:00
ebf39f11bd Added support for hi-resolution printing 2017-08-28 15:25:45 +02:00
8b7422b70a Code cleanup 2017-08-27 12:19:33 +02:00
ef3da2e156 Removed obsolete Windows XP bug workaround 2017-08-24 21:04:01 +02:00
6e13c2b704 Translations update 2017-08-24 19:40:52 +02:00
f3e4719439 Added map opacity (brightness) settings 2017-08-24 17:29:59 +02:00
7b6789e78d Version++ 2017-08-23 15:42:00 +02:00
95442461fc Added 4UMaps to map sources 2017-08-23 15:41:23 +02:00
729cbd641c Added support for the VICGRID and VICGRID94 projections 2017-08-23 10:46:28 +02:00
2e2dad8d04 Fixed broken xy2ll computation on southern hemispheres 2017-08-23 10:45:23 +02:00
4e3b6c2eb2 Added missing error check 2017-08-22 23:14:32 +02:00
6430933a96 Use the (incorrect) scale factor of 1 in France zone projections like OziExplorer does 2017-08-22 22:59:59 +02:00
3e14d4afda Added France Zone I-IV projections support 2017-08-22 19:03:35 +02:00
ebb30a3fca Made OZF3 files parsing more robust. 2017-08-22 15:57:37 +02:00
bd20d40ba7 Fixed content margin computation.
Code cleanup.
2017-08-20 10:49:58 +02:00
77823fba14 Added missing newlines 2017-08-15 15:58:23 +02:00
dcc5cbe9bc Added appveyor build config 2017-08-15 15:49:28 +02:00
cd3c99b065 Added QT4 Travis CI build config 2017-08-15 15:42:47 +02:00
83189a4e65 Version++ 2017-08-15 15:14:44 +02:00
797fd7f02b Fixed QT4 build 2017-08-15 15:13:34 +02:00
a45125be9a Code cleanup 2017-08-15 13:36:18 +02:00
a7154988ab Added support for maps with only 2 reference points 2017-08-14 23:57:53 +02:00
afe9a14d5b Improved debug output 2017-08-14 11:16:48 +02:00
b3f1596918 Make Coverity happy 2017-08-11 09:56:45 +02:00
cd90407f56 Version++ 2017-08-11 09:38:50 +02:00
73f06e61f0 Added support for OZF zoom levels 2017-08-11 00:22:21 +02:00
c708fa35fd Cosmetics 2017-08-10 08:58:21 +02:00
dcedfe1e9f Wrong parameters usage fix 2017-08-09 20:29:49 +02:00
daa9d296bd Code cleanup 2017-08-09 20:25:02 +02:00
b8a9a4481c Improved image part drawing procedure 2017-08-09 17:58:37 +02:00
e792bf3b23 Optimization 2017-08-09 11:32:05 +02:00
359a9f0a5a Avoid error summing when computing map positions 2017-08-08 18:41:19 +02:00
4b0b6513d1 Added missing endianity handling 2017-07-31 00:46:10 +02:00
c7762e26fb Added support for LinearRings in KML 2017-07-30 12:13:45 +02:00
5b8d41afb7 Detect OZF files by contents rather than by file extension 2017-07-29 22:19:03 +02:00
81e1664a9b Data/map loading code cleanup 2017-07-27 19:47:46 +02:00
fad3f116f5 Added missing error checks 2017-07-27 19:45:04 +02:00
a6e522d758 Make Coverity happy 2017-07-12 22:07:18 +02:00
ab65deadb6 Some more cosmetics 2017-07-12 21:30:54 +02:00
7f80e8f7b7 Cosmetics 2017-07-12 21:26:00 +02:00
9a5c5eaf61 Unified isNull() logic 2017-07-12 21:23:56 +02:00
9bc5016141 Indent cleanup 2017-07-12 20:54:00 +02:00
a4a46232e4 Version++ 2017-07-09 10:36:39 +02:00
d85fbe5b48 Do not duplicate Waypoints in POI search structures 2017-07-06 09:37:44 +02:00
141e0cb404 isNull() & isValid() logic improvement 2017-07-02 09:39:31 +02:00
2b7d0cd631 Unified isNull() and isValid() logic with other (QT) classes 2017-06-30 18:38:16 +02:00
d106f47771 Some more code cleanup 2017-06-30 18:15:22 +02:00
e48729fc84 Now using a separate class (RectC) for Coordinates rectangles 2017-06-29 22:29:27 +02:00
dca53bc622 Code cleanup 2017-06-29 19:53:42 +02:00
65045dfee4 Code cleanup 2017-06-27 22:42:59 +02:00
002b9c35e1 Don't rescale the view on map change 2017-06-26 00:20:42 +02:00
945528d6b1 Cosmetics 2017-06-26 00:16:38 +02:00
4697ba4ef0 Unify zoom level calculation logic 2017-06-25 16:25:29 +02:00
9bf1447a7e Back to zoom based zoom values 2017-06-25 16:23:43 +02:00
1a8114af8e Proper cleanup. 2017-06-25 12:34:48 +02:00
ad154dfd7d code cleanup 2017-06-25 12:27:53 +02:00
c2004ded31 Now using tmi index files (if present) when loading tar files 2017-06-25 12:24:05 +02:00
3ced367fab Cosmetics 2017-06-22 22:40:43 +02:00
506d1998f8 Updated project home page URL 2017-06-22 01:40:48 +02:00
afc5e9ca4b Using the platform-correct delimiter 2017-06-19 22:48:48 +02:00
425d0e3013 Cosmetics 2017-06-18 16:06:59 +02:00
3a8b1107fe Explicitly set compression method in NSIS scripts 2017-06-18 13:23:00 +02:00
ad7a413d50 Unified MSVC redistributables names with names used by windeployqt 2017-06-18 12:23:54 +02:00
8d5f72de64 Now using proper menu entries location on OS X
+ proper qt stuff localization
2017-05-31 23:37:02 +02:00
9e798e626c Decreased outlier detection window 2017-05-25 01:55:09 +02:00
cb70f0dded Merge pull request #27 from eson57/patch-1
Update gpxsee_sv.ts
2017-05-23 23:30:38 +02:00
400003f684 Update gpxsee_sv.ts 2017-05-23 21:50:21 +02:00
69db510b10 Decreased default speed filter value 2017-05-23 16:06:05 +02:00
cd9ea0f8a9 Unified settingsorder 2017-05-23 13:43:40 +02:00
0f6c8eb896 Code cleanup 2017-05-23 13:23:14 +02:00
6b3c0d05ca Merge branch 'master' of https://github.com/tumic0/GPXSee 2017-05-23 13:22:41 +02:00
b0cc028c4c Localization update 2017-05-23 13:03:28 +02:00
1513130435 Settings polishing on OS X 2017-05-23 12:50:46 +02:00
ec798451e8 Fixed POI radius setting handling 2017-05-23 00:26:59 +02:00
ffc61552d2 Code cleanup 2017-05-22 23:42:15 +02:00
aff7b1c13f Allow only odd window sizes for moving average filter 2017-05-22 23:41:01 +02:00
d54f22d3f0 Fixed crash with 0 window width 2017-05-22 22:37:35 +02:00
dba6291f3e Better (consistent) graph definition 2017-05-22 18:42:23 +02:00
e96cee2ea8 Improved filtering settings layout 2017-05-22 17:04:37 +02:00
1eaaea98a3 Version++ 2017-05-22 16:12:30 +02:00
a90073c422 Added missing icon 2017-05-22 16:10:44 +02:00
223a13583c Added data filtering settings 2017-05-22 14:54:22 +02:00
4386e1f2e1 Code cleanup 2017-05-16 13:18:57 +02:00
5bfe9c2527 Added missing ellipses 2017-05-16 12:59:59 +02:00
efa2b1c366 Code cleanup 2017-05-16 12:59:40 +02:00
e0ad64a902 Added missing units type setup for new items 2017-05-16 11:51:48 +02:00
f0a1acb96a Added missing libgeotrans Source Code Disclaimer 2017-05-08 20:39:42 +02:00
5f3bdb87f8 Added support for British, Irish and Swedish grid projections 2017-05-08 20:17:14 +02:00
90d062e097 Switched to latitude origin capable transverse mercator implementation 2017-05-08 19:53:50 +02:00
58b4c87d46 Fixed broken southern hemisphere reference points conversion
Fixed broken UTM zone setup
Added New Zealand TM 2000 "projection" support
2017-05-06 00:53:39 +02:00
02654ec862 Removed obsolete check 2017-05-05 09:09:32 +02:00
ff015c8714 Added missing data validity checks 2017-05-05 09:00:57 +02:00
c339116cd1 Added support for Albers Equal-Area projection 2017-05-04 20:25:47 +02:00
d8d70bfd8b Added missing MB->kB conversion 2017-05-04 00:04:28 +02:00
7d8149ace3 Fixed typo 2017-05-04 00:01:27 +02:00
4460b454c4 Added pixmap cache configuration to options. 2017-05-03 23:55:16 +02:00
211310f377 Version++ 2017-05-03 22:00:10 +02:00
1e4bcd0ac1 Added support for OZF3 map files 2017-05-03 21:34:13 +02:00
1a66ed0a36 Use the proper layer when displaying a single waypoint on an atlas. 2017-05-01 22:49:01 +02:00
273a127069 Version++ 2017-05-01 13:04:15 +02:00
1c0a0fd0b3 Fixed broken print/PDF export
(wrong map scale/waypoints size)
2017-05-01 12:59:56 +02:00
713e331b2a Some more OZFx extensions 2017-04-30 18:27:12 +02:00
96f406aad7 Removed Thunderforest map (requires API key)
Added USGS maps (topo & imagery)
2017-04-30 13:21:32 +02:00
0aedec66c4 Fixed atlas ll2xy() caching 2017-04-30 00:19:53 +02:00
b500031713 Atlas ll2xy() optimization 2017-04-29 23:15:44 +02:00
699e4f32d5 Version++ 2017-04-23 18:15:08 +02:00
992c8aaaf9 Improved error reporting 2017-04-23 13:37:17 +02:00
68a72c5809 Added proper OZF files detection 2017-04-23 12:49:40 +02:00
eace308774 Properly open all selected files (tar content/atlas structure is however still case sensitive) 2017-04-23 12:26:01 +02:00
e4e3f7d143 Added missing atlas maps unloading on atlas unload 2017-04-22 10:19:02 +02:00
acc49d015e Use only the "Map" word for maps/atlases in the GUI 2017-04-21 21:57:29 +02:00
b48652cb78 Localization update 2017-04-21 21:25:56 +02:00
0808f6679e Added "runtime" offline map loading
Offline map loading & error handling cleanup
2017-04-21 21:15:58 +02:00
610ac3d73f Fixed atlas zoom fitting algorithm 2017-04-19 00:07:01 +02:00
1d719fdcc8 Localization files update 2017-04-17 22:13:30 +02:00
1746e1cf08 Merge pull request #25 from mkroehnert/german-translation
add german translation
2017-04-17 21:58:05 +02:00
5d5a5365cd add german translation 2017-04-17 20:56:56 +02:00
7dfdeac1da Version++ 2017-04-17 19:57:52 +02:00
1ff13ee9f8 Added datum files to packages 2017-04-17 19:56:29 +02:00
34b1fb6b5d Cosmetics 2017-04-17 19:37:03 +02:00
02bf85780a Improved OZF files handling. 2017-04-17 19:34:44 +02:00
47199348d8 Improved error reporting 2017-04-17 19:15:20 +02:00
3b55bc0efc Added missing Lat/Lon based calibration points conversion to WGS84 2017-04-17 19:01:01 +02:00
4de3ddf71b Switched from hardcoded values to CSV files for datum definitions.
Non-WGS84 maps now fit correctly when defined using map grid.
2017-04-17 18:03:04 +02:00
e26fa92ce6 Code cleanup 2017-04-15 13:13:26 +02:00
dfb69b2755 Yet another error handling fix. 2017-04-15 11:47:30 +02:00
c2a30738cb Update README.md 2017-04-15 09:11:16 +02:00
fd53e89ea5 Improved error handling 2017-04-15 08:59:31 +02:00
ccf91bb29f Added support for ozf2 files 2017-04-14 22:39:33 +02:00
75bd388be0 Try to load maps with incorrect (windows absolute) image paths. 2017-04-13 20:00:27 +02:00
aef0357204 Version++ 2017-04-12 18:19:03 +02:00
d073d606d0 Added missing cache reset (causing huge redraw rects causing system memory exhaustion) 2017-04-12 18:11:53 +02:00
8822bf7e5f Code cleanup 2017-04-09 10:26:09 +02:00
051a3ed303 Replaced wrong NAD27 ellipsoid with the correct one 2017-04-07 18:19:56 +02:00
96437ae6ab Cosmetics 2017-04-07 10:16:14 +02:00
89c25bbc3a Update README.md 2017-04-07 10:02:41 +02:00
322792ea04 Improved digital zoom/fullscreen interaction 2017-04-06 19:54:50 +02:00
ce1c76a315 translation cleanup 2017-04-06 09:11:36 +02:00
804e9594ad Merge pull request #21 from eson57/patch-4
Update gpxsee_sv.ts
2017-04-06 09:10:13 +02:00
651973c524 Merge branch 'master' into patch-4 2017-04-06 09:09:51 +02:00
533af66080 Fixed typo 2017-04-06 09:08:25 +02:00
bab5750cf7 Update gpxsee_sv.ts 2017-04-06 06:36:18 +02:00
0d6f3ea162 Version++ 2017-04-05 22:56:37 +02:00
b915302e2f Localization update 2017-04-05 22:53:44 +02:00
03ef7a9147 Added digital zoom 2017-04-05 22:53:25 +02:00
33cb944e36 Code cleanup/optimization 2017-04-04 22:03:42 +02:00
8bc575aef2 Fixed map fitting algorithm 2017-04-04 01:19:17 +02:00
f0b7abdb72 Added SAD69 ellipsoid 2017-04-03 20:59:17 +02:00
6ce14734cd Use ellipsoids defined by the map file for the projection computation 2017-04-03 20:29:35 +02:00
925a0e2951 version++ 2017-04-02 22:19:24 +02:00
e46bba18f2 Optimized projection computation 2017-04-02 22:18:03 +02:00
a56aa4e706 Added support for Lambert Conformal Conic projection 2017-04-02 22:17:16 +02:00
c4b3a81b0b Make coverity happy 2017-04-02 09:32:40 +02:00
957cc6f4f3 Code cleanup 2017-04-02 00:39:12 +02:00
ebad0832ee Update README.md 2017-04-01 19:48:39 +02:00
186c135ad5 Update README.md 2017-04-01 19:47:14 +02:00
72b5b1ea97 Update README.md 2017-04-01 19:46:11 +02:00
106d4c6e0b Installer polishing 2017-04-01 18:02:34 +02:00
8f815a6af0 Missing file changes... 2017-04-01 16:55:46 +02:00
60f107d7cd Added possibility to compute the UTM zone from lat/lon reference points 2017-04-01 16:25:33 +02:00
e87fff4bf8 Added UTM projection support
Fixed broken map fitting
2017-04-01 15:58:32 +02:00
e6547d92f0 Fixed zoom speed issue on touchpads 2017-04-01 06:56:50 +02:00
bfcc577f64 Added missing destructor 2017-04-01 06:10:36 +02:00
a56ad8a933 Code cleanup/optimizations 2017-04-01 05:59:55 +02:00
b1748c848b Fixed broken atlas maps fitting in non-orthogonal projections. 2017-03-31 19:18:01 +02:00
3763d44662 Added Latitude/Longitude projection 2017-03-29 22:51:32 +02:00
b3e8081942 Added support for Transversal Mercator projection 2017-03-29 00:17:47 +02:00
b3dc886afc Localization update 2017-03-27 23:59:26 +02:00
431002fd62 Added offline map info to data sources info page 2017-03-27 23:58:36 +02:00
63c3a50ca6 Fixed scene (map) bounds not updating issue
Code cleanup
2017-03-27 23:52:24 +02:00
7fd30bbda3 Improved error handling 2017-03-27 10:31:41 +02:00
c1844f9557 Atlas loading optimization 2017-03-27 02:41:30 +02:00
0c7601c831 Fixed TAR parser 2017-03-26 18:08:37 +02:00
19eb3fba7f Merge branch 'master' of https://github.com/tumic0/GPXSee 2017-03-26 15:33:49 +02:00
bde3c8cc3d Added support for Trekbuddy atlases 2017-03-26 15:32:55 +02:00
b0ce471ea8 Markup syntax fix 2017-03-24 22:53:26 +01:00
bd23120c2c Improved image/tiles info fetching 2017-03-21 20:51:23 +01:00
ac4ef0631e Do not depend on a specific tile name when gathering tile info. 2017-03-21 19:02:29 +01:00
60d9a172b6 Refactoring 2017-03-21 09:27:44 +01:00
b8eede21c0 Improved tared maps scrolling performance 2017-03-21 09:01:30 +01:00
70ddbe192f Added support for tared maps 2017-03-21 01:15:29 +01:00
d8477571cc Added missing coordinates transformation 2017-03-20 22:52:39 +01:00
92545acba0 Added support for tiled offline maps 2017-03-20 10:05:07 +01:00
2bf66ea912 Tile loading code cleanup 2017-03-20 09:25:05 +01:00
b21c2267cf Added support for OziExplorer offline maps 2017-03-18 01:30:31 +01:00
278aa904c1 Human-friendly links 2017-03-05 10:39:50 +01:00
b369985f0a Updated Linux packages download URL 2017-03-05 10:35:19 +01:00
6a5781771f Updated program screenshot 2017-02-28 11:53:25 +01:00
1b616f3c81 Added installer executable description 2017-02-16 18:59:37 +01:00
99dfbc1d2f Added Windows installer code sign certificate 2017-02-13 23:58:19 +01:00
128 changed files with 7761 additions and 1598 deletions

52
.appveyor.yml Normal file
View File

@ -0,0 +1,52 @@
version: 4.13.{build}
configuration: Release
platform: Any CPU
environment:
NSISDIR: C:\Program Files (x86)\NSIS
matrix:
- QTDIR: C:\Qt\5.9\msvc2015
PLATFORM: x86
NSI: gpxsee.nsi
OPENSSLDIR: C:\OpenSSL-Win32\bin
- QTDIR: C:\Qt\5.9\msvc2015_64
PLATFORM: x86_amd64
NSI: gpxsee64.nsi
OPENSSLDIR: C:\OpenSSL-Win64\bin
install:
- cmd: >-
set PATH=%QTDIR%\bin;%NSISDIR%;%PATH%
call "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat" %PLATFORM%
build_script:
- cmd: >-
lrelease gpxsee.pro
qmake gpxsee.pro
nmake release
md installer
copy release\GPXSee.exe installer
windeployqt --no-svg --release installer\GPXSee.exe
copy pkg\%NSI% installer
copy pkg\datums.csv installer
copy pkg\ellipsoids.csv installer
copy pkg\maps.txt installer
copy licence.txt installer
copy %OPENSSLDIR%\libeay32.dll installer
copy %OPENSSLDIR%\ssleay32.dll installer
makensis.exe installer\%NSI%
artifacts:
- path: installer\GPXSee-*.exe

9
.travis.yml Normal file
View File

@ -0,0 +1,9 @@
language: c++
install:
- sudo apt-get install libqt4-dev
script:
- lrelease gpxsee.pro
- qmake gpxsee.pro
- make

View File

@ -15,7 +15,7 @@
<key>CFBundleExecutable</key>
<string>@EXECUTABLE@</string>
<key>CFBundleIdentifier</key>
<string>cz.wz.tumic.GPXSee</string>
<string>org.gpxsee.GPXSee</string>
<key>CFBundleDocumentTypes</key>
<array>

View File

@ -3,7 +3,8 @@ GPXSee is a Qt-based GPS log file viewer and analyzer that supports GPX, TCX,
KML, FIT, IGC and NMEA files.
## Features
* User-definable map sources.
* User-definable online maps.
* Offline maps (OziExplorer maps and TrekBuddy maps/atlases).
* Elevation, speed, heart rate, cadence, power and temperature graphs.
* Support for multiple tracks in one view.
* Support for POI files.
@ -12,25 +13,21 @@ KML, FIT, IGC and NMEA files.
* Native GUI for Windows, Mac OS X and Linux.
* Opens GPX, TCX, FIT, KML, IGC, NMEA and Garmin CSV files.
![GPXSee - Linux](https://a.fsdn.com/con/app/proj/gpxsee/screenshots/linux.png)
![GPXSee - Linux](https://a.fsdn.com/con/app/proj/gpxsee/screenshots/linux2.png)
## Build
### Linux/OS X
```shell
lrelease gpxsee.pro
qmake gpxsee.pro
make
```
### Windows
```shell
lrelease gpxsee.pro
qmake gpxsee.pro
nmake release
```
## Binaries
* Windows & OS X builds: http://sourceforge.net/projects/gpxsee
* Linux packages: https://build.opensuse.org/project/repositories/home:tumic:GPXSee
## Download
* [Windows & OS X builds](http://sourceforge.net/projects/gpxsee)
* [Linux packages](http://software.opensuse.org/download.html?project=home%3Atumic%3AGPXSee&package=gpxsee)
## Changelog
[Changelog](https://build.opensuse.org/package/view_file/home:tumic:GPXSee/gpxsee/gpxsee.changes)
## Homepage
GPXSee homepage: http://tumic.wz.cz/gpxsee
http://www.gpxsee.org

View File

@ -1,5 +1,5 @@
TARGET = GPXSee
VERSION = 3.10
VERSION = 4.13
QT += core \
gui \
network
@ -22,7 +22,7 @@ HEADERS += src/config.h \
src/sliderinfoitem.h \
src/filebrowser.h \
src/map.h \
src/maplist.h \
src/onlinemap.h \
src/downloader.h \
src/units.h \
src/scaleitem.h \
@ -77,7 +77,27 @@ HEADERS += src/config.h \
src/colorbox.h \
src/stylecombobox.h \
src/opengl.h \
src/timetype.h
src/timetype.h \
src/emptymap.h \
src/offlinemap.h \
src/matrix.h \
src/tar.h \
src/atlas.h \
src/projection.h \
src/mercator.h \
src/transversemercator.h \
src/latlon.h \
src/utm.h \
src/lambertconic.h \
src/ellipsoid.h \
src/ozf.h \
src/datum.h \
src/maplist.h \
src/albersequal.h \
src/oddspinbox.h \
src/rectc.h \
src/searchpointer.h \
src/percentslider.h
SOURCES += src/main.cpp \
src/gui.cpp \
src/poi.cpp \
@ -89,8 +109,7 @@ SOURCES += src/main.cpp \
src/speedgraph.cpp \
src/sliderinfoitem.cpp \
src/filebrowser.cpp \
src/map.cpp \
src/maplist.cpp \
src/onlinemap.cpp \
src/downloader.cpp \
src/scaleitem.cpp \
src/track.cpp \
@ -131,10 +150,28 @@ SOURCES += src/main.cpp \
src/nmeaparser.cpp \
src/optionsdialog.cpp \
src/colorbox.cpp \
src/stylecombobox.cpp
src/stylecombobox.cpp \
src/emptymap.cpp \
src/offlinemap.cpp \
src/matrix.cpp \
src/tar.cpp \
src/atlas.cpp \
src/mercator.cpp \
src/transversemercator.cpp \
src/utm.cpp \
src/lambertconic.cpp \
src/ellipsoid.cpp \
src/ozf.cpp \
src/datum.cpp \
src/maplist.cpp \
src/albersequal.cpp \
src/oddspinbox.cpp \
src/rectc.cpp \
src/percentslider.cpp
RESOURCES += gpxsee.qrc
TRANSLATIONS = lang/gpxsee_cs.ts \
lang/gpxsee_sv.ts
lang/gpxsee_sv.ts \
lang/gpxsee_de.ts
macx {
ICON = icons/gpxsee.icns
QMAKE_INFO_PLIST = Info.plist
@ -144,7 +181,9 @@ macx {
icons/fit.icns \
icons/igc.icns \
icons/nmea.icns \
pkg/maps.txt
pkg/maps.txt \
pkg/ellipsoids.csv \
pkg/datums.csv
APP_RESOURCES.path = Contents/Resources
QMAKE_BUNDLE_DATA += APP_RESOURCES
}

View File

@ -14,12 +14,14 @@
<file>icons/arrow-left-double.png</file>
<file>icons/arrow-right-double.png</file>
<file>icons/view-fullscreen.png</file>
<file>icons/office-chart-line-stacked.png</file>
<file>icons/office-chart-line.png</file>
<file>icons/preferences-desktop-display.png</file>
<file>icons/flag_48.png</file>
<file>icons/system-run.png</file>
<file>icons/document-print-preview.png</file>
<file>icons/view-filter.png</file>
<file>lang/gpxsee_cs.qm</file>
<file>lang/gpxsee_sv.qm</file>
<file>lang/gpxsee_de.qm</file>
</qresource>
</RCC>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 727 B

BIN
icons/office-chart-line.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 728 B

BIN
icons/view-filter.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

File diff suppressed because it is too large Load Diff

1256
lang/gpxsee_de.ts Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

123
pkg/datums.csv Normal file
View File

@ -0,0 +1,123 @@
Adindan,4201,5,-162,-12,206
Afgooye,4205,15,-43,-163,45
Ain el Abd 1970,4204,14,-150,-251,-2
Anna 1 Astro 1965,4708,2,-491,-22,435
Arc 1950,4209,5,-143,-90,-294
Arc 1960,4210,5,-160,-8,-300
Ascension Island 1958,4712,14,-207,107,52
Astro B4 Sorol Atoll,4707,14,114,-116,-333
Astro Beacon 1945,4709,14,145,75,-272
Astro DOS 71/4,4710,14,-320,550,-494
Astronomic Stn 1952,4711,14,124,-234,-25
Australian Geodetic 1966,4202,2,-133,-48,148
Australian Geodetic 1984,4203,2,-134,-48,149
Australian Geocentric 1994 (GDA94),4283,11,0,0,0
Austrian,4312,3,594,84,471
Bellevue (IGN),4714,14,-127,-769,472
Bermuda 1957,4216,4,-73,213,296
Bogota Observatory,4218,14,307,304,-318
Campo Inchauspe,4221,14,-148,136,90
Canton Astro 1966,4716,14,298,-304,-375
Cape,4222,5,-136,-108,-292
Cape Canaveral,4717,4,-2,150,181
Carthage,4223,5,-263,6,431
CH-1903,4149,3,674,15,405
Chatham 1971,4672,14,175,-38,113
Chua Astro,4224,14,-134,229,-29
Corrego Alegre,4225,14,-206,172,-6
Djakarta (Batavia),4211,3,-377,681,-50
DOS 1968,,14,230,-199,-752
Easter Island 1967,4719,14,211,147,111
Egypt,,14,-130,-117,-151
European 1950,4230,14,-87,-98,-121
European 1950 (Mean France),,14,-87,-96,-120
European 1950 (Spain and Portugal),,14,-84,-107,-120
European 1979,4668,14,-86,-98,-119
Finland Hayford,4123,14,-78,-231,-97
Gandajika Base,4233,14,-133,-321,50
Geodetic Datum 1949,4272,14,84,-22,209
GGRS 87,4121,11,-199.87,74.79,246.62
Guam 1963,4675,4,-100,-248,259
GUX 1 Astro,4718,14,252,-209,-751
Hartebeeshoek94,4148,20,0,0,0
Hermannskogel,3906,3,653,-212,449
Hjorsey 1955,4658,14,-73,46,-86
Hong Kong 1963,4739,14,-156,-271,-189
Hu-Tzu-Shan,4236,14,-634,-549,-201
Indian Bangladesh,4682,6,289,734,257
Indian Thailand,4240,6,214,836,303
Israeli,4281,23,-235,-85,264
Ireland 1965,4299,1,506,-122,611
ISTS 073 Astro 1969,4724,14,208,-435,-229
Johnston Island,4725,14,191,-77,-204
Kandawala,4244,6,-97,787,86
Kerguelen Island,4698,14,145,-187,103
Kertau 1948,4245,7,-11,851,5
L.C. 5 Astro,4726,4,42,124,147
Liberia 1964,4251,5,-90,40,88
Luzon Mindanao,,4,-133,-79,-72
Luzon Philippines,4253,4,-133,-77,-51
Mahe 1971,4256,5,41,-220,-134
Marco Astro,4616,14,-289,-124,60
Massawa,4262,3,639,405,60
Merchich,4261,5,31,146,47
Midway Astro 1961,4727,14,912,-58,1227
Minna,4263,5,-92,-93,122
NAD27 Alaska,,4,-5,135,172
NAD27 Bahamas,,4,-4,154,178
NAD27 Canada,,4,-10,158,187
NAD27 Canal Zone,,4,0,125,201
NAD27 Caribbean,,4,-7,152,178
NAD27 Central,,4,0,125,194
NAD27 CONUS,,4,-8,160,176
NAD27 Cuba,,4,-9,152,178
NAD27 Greenland,,4,11,114,195
NAD27 Mexico,,4,-12,130,190
NAD27 San Salvador,,4,1,140,165
NAD83,4269,11,0,0,0
Nahrwn Masirah Ilnd,,5,-247,-148,369
Nahrwn Saudi Arbia,,5,-231,-196,482
Nahrwn United Arab,,5,-249,-156,381
Naparima BWI,4271,14,-2,374,172
NGO1948,4273,27,315,-217,528
NTF France,4275,24,-168,-60,320
Norsk,4817,27,278,93,474
NZGD1949,4272,14,84,-22,209
NZGD2000,4167,20,0,0,0
Observatorio 1966,4182,14,-425,-169,81
Old Egyptian,4229,12,-130,110,-13
Old Hawaiian,4135,4,61,-285,-181
Oman,4232,5,-346,-1,224
Ord Srvy Grt Britn,4277,0,375,-111,431
Pico De Las Nieves,4728,14,-307,-92,127
Pitcairn Astro 1967,4729,14,185,165,42
Potsdam Rauenberg DHDN,4314,3,606,23,413
Prov So Amrican 1956,4248,14,-288,175,-376
Prov So Chilean 1963,4254,14,16,196,93
Puerto Rico,4139,4,11,72,-101
Pulkovo 1942 (1),4284,15,28,-130,-95
Pulkovo 1942 (2),4284,15,28,-130,-95
Qatar National,4285,14,-128,-283,22
Qornoq,4287,14,164,138,-189
Reunion,4626,14,94,-948,-1262
Rijksdriehoeksmeting,4289,3,593,26,478
Rome 1940,4806,14,-225,-65,9
RT 90,4124,3,498,-36,568
S42,4179,15,28,-121,-77
Santo (DOS),4730,14,170,42,84
Sao Braz,4184,14,-203,141,53
Sapper Hill 1943,4292,14,-355,16,74
Schwarzeck,4293,21,616,97,-251
South American 1969,4291,16,-57,1,-41
South Asia,,8,7,-10,-26
Southeast Base,4615,14,-499,-249,314
Southwest Base,4183,14,-104,167,-38
Timbalai 1948,4298,6,-689,691,-46
Tokyo,4301,3,-128,481,664
Tristan Astro 1968,4734,14,-632,438,-609
Viti Levu 1916,4731,5,51,391,-36
Wake-Eniwetok 1960,4732,13,101,52,-39
WGS 72,4322,19,0,0,5
WGS 84,4326,20,0,0,0
Yacare,4309,14,-155,171,37
Zanderij,4311,14,-265,120,-358
1 Adindan 4201 5 -162 -12 206
2 Afgooye 4205 15 -43 -163 45
3 Ain el Abd 1970 4204 14 -150 -251 -2
4 Anna 1 Astro 1965 4708 2 -491 -22 435
5 Arc 1950 4209 5 -143 -90 -294
6 Arc 1960 4210 5 -160 -8 -300
7 Ascension Island 1958 4712 14 -207 107 52
8 Astro B4 Sorol Atoll 4707 14 114 -116 -333
9 Astro Beacon 1945 4709 14 145 75 -272
10 Astro DOS 71/4 4710 14 -320 550 -494
11 Astronomic Stn 1952 4711 14 124 -234 -25
12 Australian Geodetic 1966 4202 2 -133 -48 148
13 Australian Geodetic 1984 4203 2 -134 -48 149
14 Australian Geocentric 1994 (GDA94) 4283 11 0 0 0
15 Austrian 4312 3 594 84 471
16 Bellevue (IGN) 4714 14 -127 -769 472
17 Bermuda 1957 4216 4 -73 213 296
18 Bogota Observatory 4218 14 307 304 -318
19 Campo Inchauspe 4221 14 -148 136 90
20 Canton Astro 1966 4716 14 298 -304 -375
21 Cape 4222 5 -136 -108 -292
22 Cape Canaveral 4717 4 -2 150 181
23 Carthage 4223 5 -263 6 431
24 CH-1903 4149 3 674 15 405
25 Chatham 1971 4672 14 175 -38 113
26 Chua Astro 4224 14 -134 229 -29
27 Corrego Alegre 4225 14 -206 172 -6
28 Djakarta (Batavia) 4211 3 -377 681 -50
29 DOS 1968 14 230 -199 -752
30 Easter Island 1967 4719 14 211 147 111
31 Egypt 14 -130 -117 -151
32 European 1950 4230 14 -87 -98 -121
33 European 1950 (Mean France) 14 -87 -96 -120
34 European 1950 (Spain and Portugal) 14 -84 -107 -120
35 European 1979 4668 14 -86 -98 -119
36 Finland Hayford 4123 14 -78 -231 -97
37 Gandajika Base 4233 14 -133 -321 50
38 Geodetic Datum 1949 4272 14 84 -22 209
39 GGRS 87 4121 11 -199.87 74.79 246.62
40 Guam 1963 4675 4 -100 -248 259
41 GUX 1 Astro 4718 14 252 -209 -751
42 Hartebeeshoek94 4148 20 0 0 0
43 Hermannskogel 3906 3 653 -212 449
44 Hjorsey 1955 4658 14 -73 46 -86
45 Hong Kong 1963 4739 14 -156 -271 -189
46 Hu-Tzu-Shan 4236 14 -634 -549 -201
47 Indian Bangladesh 4682 6 289 734 257
48 Indian Thailand 4240 6 214 836 303
49 Israeli 4281 23 -235 -85 264
50 Ireland 1965 4299 1 506 -122 611
51 ISTS 073 Astro 1969 4724 14 208 -435 -229
52 Johnston Island 4725 14 191 -77 -204
53 Kandawala 4244 6 -97 787 86
54 Kerguelen Island 4698 14 145 -187 103
55 Kertau 1948 4245 7 -11 851 5
56 L.C. 5 Astro 4726 4 42 124 147
57 Liberia 1964 4251 5 -90 40 88
58 Luzon Mindanao 4 -133 -79 -72
59 Luzon Philippines 4253 4 -133 -77 -51
60 Mahe 1971 4256 5 41 -220 -134
61 Marco Astro 4616 14 -289 -124 60
62 Massawa 4262 3 639 405 60
63 Merchich 4261 5 31 146 47
64 Midway Astro 1961 4727 14 912 -58 1227
65 Minna 4263 5 -92 -93 122
66 NAD27 Alaska 4 -5 135 172
67 NAD27 Bahamas 4 -4 154 178
68 NAD27 Canada 4 -10 158 187
69 NAD27 Canal Zone 4 0 125 201
70 NAD27 Caribbean 4 -7 152 178
71 NAD27 Central 4 0 125 194
72 NAD27 CONUS 4 -8 160 176
73 NAD27 Cuba 4 -9 152 178
74 NAD27 Greenland 4 11 114 195
75 NAD27 Mexico 4 -12 130 190
76 NAD27 San Salvador 4 1 140 165
77 NAD83 4269 11 0 0 0
78 Nahrwn Masirah Ilnd 5 -247 -148 369
79 Nahrwn Saudi Arbia 5 -231 -196 482
80 Nahrwn United Arab 5 -249 -156 381
81 Naparima BWI 4271 14 -2 374 172
82 NGO1948 4273 27 315 -217 528
83 NTF France 4275 24 -168 -60 320
84 Norsk 4817 27 278 93 474
85 NZGD1949 4272 14 84 -22 209
86 NZGD2000 4167 20 0 0 0
87 Observatorio 1966 4182 14 -425 -169 81
88 Old Egyptian 4229 12 -130 110 -13
89 Old Hawaiian 4135 4 61 -285 -181
90 Oman 4232 5 -346 -1 224
91 Ord Srvy Grt Britn 4277 0 375 -111 431
92 Pico De Las Nieves 4728 14 -307 -92 127
93 Pitcairn Astro 1967 4729 14 185 165 42
94 Potsdam Rauenberg DHDN 4314 3 606 23 413
95 Prov So Amrican 1956 4248 14 -288 175 -376
96 Prov So Chilean 1963 4254 14 16 196 93
97 Puerto Rico 4139 4 11 72 -101
98 Pulkovo 1942 (1) 4284 15 28 -130 -95
99 Pulkovo 1942 (2) 4284 15 28 -130 -95
100 Qatar National 4285 14 -128 -283 22
101 Qornoq 4287 14 164 138 -189
102 Reunion 4626 14 94 -948 -1262
103 Rijksdriehoeksmeting 4289 3 593 26 478
104 Rome 1940 4806 14 -225 -65 9
105 RT 90 4124 3 498 -36 568
106 S42 4179 15 28 -121 -77
107 Santo (DOS) 4730 14 170 42 84
108 Sao Braz 4184 14 -203 141 53
109 Sapper Hill 1943 4292 14 -355 16 74
110 Schwarzeck 4293 21 616 97 -251
111 South American 1969 4291 16 -57 1 -41
112 South Asia 8 7 -10 -26
113 Southeast Base 4615 14 -499 -249 314
114 Southwest Base 4183 14 -104 167 -38
115 Timbalai 1948 4298 6 -689 691 -46
116 Tokyo 4301 3 -128 481 664
117 Tristan Astro 1968 4734 14 -632 438 -609
118 Viti Levu 1916 4731 5 51 391 -36
119 Wake-Eniwetok 1960 4732 13 101 52 -39
120 WGS 72 4322 19 0 0 5
121 WGS 84 4326 20 0 0 0
122 Yacare 4309 14 -155 171 37
123 Zanderij 4311 14 -265 120 -358

30
pkg/ellipsoids.csv Normal file
View File

@ -0,0 +1,30 @@
0,Airy 1830,6377563.396,299.3249646
1,Modified Airy,6377340.189,299.3249646
2,Australian National,6378160.0,298.25
3,Bessel 1841,6377397.155,299.1528128
4,Clarke 1866,6378206.4,294.9786982
5,Clarke 1880,6378249.145,293.465
6,Everest (India 1830),6377276.345,300.8017
7,Everest (1948),6377304.063,300.8017
8,Modified Fischer 1960,6378155.0,298.3
9,Everest (Pakistan),6377309.613,300.8017
10,Indonesian 1974,6378160.0,298.247
11,GRS 80,6378137.0,298.257222101
12,Helmert 1906,6378200.0,298.3
13,Hough 1960,6378270.0,297.0
14,International 1924,6378388.0,297.0
15,Krassovsky 1940,6378245.0,298.3
16,South American 1969,6378160.0,298.25
17,Everest (Malaysia 1969),6377295.664,300.8017
18,Everest (Sabah Sarawak),6377298.556,300.8017
19,WGS 72,6378135.0,298.26
20,WGS 84,6378137.0,298.257223563
21,Bessel 1841 (Namibia),6377483.865,299.1528128
22,Everest (India 1956),6377301.243,300.8017
23,Clarke 1880 Palestine,6378300.789,293.466
24,Clarke 1880 IGN,6378249.2,293.466021
25,Hayford 1909,6378388.0,296.959263
26,Clarke 1858,6378350.87,294.26
27,Bessel 1841 (Norway),6377492.0176,299.1528
28,Plessis 1817 (France),6376523.0,308.6409971
29,Hayford 1924,6378388.0,297.0
1 0 Airy 1830 6377563.396 299.3249646
2 1 Modified Airy 6377340.189 299.3249646
3 2 Australian National 6378160.0 298.25
4 3 Bessel 1841 6377397.155 299.1528128
5 4 Clarke 1866 6378206.4 294.9786982
6 5 Clarke 1880 6378249.145 293.465
7 6 Everest (India 1830) 6377276.345 300.8017
8 7 Everest (1948) 6377304.063 300.8017
9 8 Modified Fischer 1960 6378155.0 298.3
10 9 Everest (Pakistan) 6377309.613 300.8017
11 10 Indonesian 1974 6378160.0 298.247
12 11 GRS 80 6378137.0 298.257222101
13 12 Helmert 1906 6378200.0 298.3
14 13 Hough 1960 6378270.0 297.0
15 14 International 1924 6378388.0 297.0
16 15 Krassovsky 1940 6378245.0 298.3
17 16 South American 1969 6378160.0 298.25
18 17 Everest (Malaysia 1969) 6377295.664 300.8017
19 18 Everest (Sabah Sarawak) 6377298.556 300.8017
20 19 WGS 72 6378135.0 298.26
21 20 WGS 84 6378137.0 298.257223563
22 21 Bessel 1841 (Namibia) 6377483.865 299.1528128
23 22 Everest (India 1956) 6377301.243 300.8017
24 23 Clarke 1880 Palestine 6378300.789 293.466
25 24 Clarke 1880 IGN 6378249.2 293.466021
26 25 Hayford 1909 6378388.0 296.959263
27 26 Clarke 1858 6378350.87 294.26
28 27 Bessel 1841 (Norway) 6377492.0176 299.1528
29 28 Plessis 1817 (France) 6376523.0 308.6409971
30 29 Hayford 1924 6378388.0 297.0

BIN
pkg/gpxsee.cer Normal file

Binary file not shown.

View File

@ -5,10 +5,12 @@
; The name of the installer
Name "GPXSee"
; Program version
!define VERSION "3.10"
!define VERSION "4.13"
; The file to write
OutFile "GPXSee-${VERSION}.exe"
; Compression method
SetCompressor /SOLID lzma
; Required execution level
RequestExecutionLevel admin
@ -16,6 +18,14 @@ RequestExecutionLevel admin
; The default installation directory
InstallDir "$PROGRAMFILES\GPXSee"
; Installer executable info
VIProductVersion "${VERSION}.0.0"
VIAddVersionKey "ProductVersion" ${VERSION}
VIAddVersionKey "FileVersion" "${VERSION}.0.0"
VIAddVersionKey "ProductName" "GPXSee"
VIAddVersionKey "LegalCopyright" "GPXSee project"
VIAddVersionKey "FileDescription" "GPXSee installer"
; Registry key to check for directory (so if you install again, it will
; overwrite the old one automatically)
InstallDirRegKey HKLM "Software\GPXSee" "Install_Dir"
@ -74,6 +84,8 @@ Section "GPXSee" SEC_APP
; Put the files there
File "gpxsee.exe"
File "maps.txt"
File "ellipsoids.csv"
File "datums.csv"
; Create start menu entry and add links
SetShellVarContext all
@ -161,8 +173,8 @@ Section "MSVC runtime" SEC_MSVC
DetailPrint "Installing Visual C++ 2015 Redistributable..."
SetOutPath $TEMP
File "VC_redist.x86.exe"
ExecWait '"$TEMP/VC_redist.x86.exe" /install /quiet /norestart'
File "vcredist_x86.exe"
ExecWait '"$TEMP\vcredist_x86.exe" /install /quiet /norestart'
SetOutPath $INSTDIR
done:
@ -242,4 +254,4 @@ LangString DESC_APP ${LANG_ENGLISH} \
!insertmacro MUI_DESCRIPTION_TEXT ${SEC_ANGLE} $(DESC_ANGLE)
!insertmacro MUI_DESCRIPTION_TEXT ${SEC_MSVC} $(DESC_MSVC)
!insertmacro MUI_DESCRIPTION_TEXT ${SEC_APP} $(DESC_APP)
!insertmacro MUI_FUNCTION_DESCRIPTION_END
!insertmacro MUI_FUNCTION_DESCRIPTION_END

View File

@ -5,10 +5,12 @@
; The name of the installer
Name "GPXSee"
; Program version
!define VERSION "3.10"
!define VERSION "4.13"
; The file to write
OutFile "GPXSee-${VERSION}_x64.exe"
; Compression method
SetCompressor /SOLID lzma
; Required execution level
RequestExecutionLevel admin
@ -16,6 +18,14 @@ RequestExecutionLevel admin
; The default installation directory
InstallDir "$PROGRAMFILES64\GPXSee"
; Installer executable info
VIProductVersion "${VERSION}.0.0"
VIAddVersionKey "ProductVersion" ${VERSION}
VIAddVersionKey "FileVersion" "${VERSION}.0.0"
VIAddVersionKey "ProductName" "GPXSee"
VIAddVersionKey "LegalCopyright" "GPXSee project"
VIAddVersionKey "FileDescription" "GPXSee installer (x64)"
; Registry key to check for directory (so if you install again, it will
; overwrite the old one automatically)
InstallDirRegKey HKLM "Software\GPXSee" "Install_Dir"
@ -81,6 +91,8 @@ Section "GPXSee" SEC_APP
; Put the files there
File "gpxsee.exe"
File "maps.txt"
File "ellipsoids.csv"
File "datums.csv"
; Create start menu entry and add links
SetShellVarContext all
@ -98,7 +110,7 @@ Section "GPXSee" SEC_APP
WriteRegStr HKLM SOFTWARE\GPXSee "Install_Dir" "$INSTDIR"
; Write the uninstall keys for Windows
WriteRegStr HKLM "${REGENTRY}" "DisplayName" "GPXSee"
WriteRegStr HKLM "${REGENTRY}" "DisplayName" "GPXSee (x64)"
WriteRegStr HKLM "${REGENTRY}" "Publisher" "Martin Tuma"
WriteRegStr HKLM "${REGENTRY}" "DisplayVersion" "${VERSION}"
WriteRegStr HKLM "${REGENTRY}" "UninstallString" '"$INSTDIR\uninstall.exe"'
@ -163,8 +175,8 @@ Section "MSVC runtime" SEC_MSVC
DetailPrint "Installing Visual C++ 2015 Redistributable..."
SetOutPath $TEMP
File "VC_redist.x64.exe"
ExecWait '"$TEMP/VC_redist.x64.exe" /install /quiet /norestart'
File "vcredist_x64.exe"
ExecWait '"$TEMP\vcredist_x64.exe" /install /quiet /norestart'
SetOutPath $INSTDIR
done:
@ -245,4 +257,4 @@ LangString DESC_APP ${LANG_ENGLISH} \
!insertmacro MUI_DESCRIPTION_TEXT ${SEC_ANGLE} $(DESC_ANGLE)
!insertmacro MUI_DESCRIPTION_TEXT ${SEC_MSVC} $(DESC_MSVC)
!insertmacro MUI_DESCRIPTION_TEXT ${SEC_APP} $(DESC_APP)
!insertmacro MUI_FUNCTION_DESCRIPTION_END
!insertmacro MUI_FUNCTION_DESCRIPTION_END

View File

@ -1,3 +1,5 @@
Open Topo Map https://a.tile.opentopomap.org/$z/$x/$y.png
Thunderforest http://tile.thunderforest.com/outdoors/$z/$x/$y.png
4UMaps http://4umaps.eu/$z/$x/$y.png
Open Street Map http://tile.openstreetmap.org/$z/$x/$y.png
USGS Topo https://navigator.er.usgs.gov/tiles/tcr.cgi/$z/$x/$y.png
USGS Imagery https://navigator.er.usgs.gov/tiles/aerial_Imagery.cgi/$z/$x/$y

229
src/albersequal.cpp Normal file
View File

@ -0,0 +1,229 @@
/*
* Based on libgeotrans with the following Source Code Disclaimer:
1. The GEOTRANS source code ("the software") is provided free of charge by
the National Imagery and Mapping Agency (NIMA) of the United States
Department of Defense. Although NIMA makes no copyright claim under Title 17
U.S.C., NIMA claims copyrights in the source code under other legal regimes.
NIMA hereby grants to each user of the software a license to use and
distribute the software, and develop derivative works.
2. Warranty Disclaimer: The software was developed to meet only the internal
requirements of the U.S. National Imagery and Mapping Agency. The software
is provided "as is," and no warranty, express or implied, including but not
limited to the implied warranties of merchantability and fitness for
particular purpose or arising by statute or otherwise in law or from a
course of dealing or usage in trade, is made by NIMA as to the accuracy and
functioning of the software.
3. NIMA and its personnel are not required to provide technical support or
general assistance with respect to the software.
4. Neither NIMA nor its personnel will be liable for any claims, losses, or
damages arising from or connected with the use of the software. The user
agrees to hold harmless the United States National Imagery and Mapping
Agency. The user's sole and exclusive remedy is to stop using the software.
5. NIMA requests that products developed using the software credit the
source of the software with the following statement, "The product was
developed using GEOTRANS, a product of the National Imagery and Mapping
Agency and U.S. Army Engineering Research and Development Center."
6. For any products developed using the software, NIMA requires a disclaimer
that use of the software does not indicate endorsement or approval of the
product by the Secretary of Defense or the National Imagery and Mapping
Agency. Pursuant to the United States Code, 10 U.S.C. Sec. 2797, the name of
the National Imagery and Mapping Agency, the initials "NIMA", the seal of
the National Imagery and Mapping Agency, or any colorable imitation thereof
shall not be used to imply approval, endorsement, or authorization of a
product without prior written permission from United States Secretary of
Defense.
*/
#include "ellipsoid.h"
#include "rd.h"
#include "albersequal.h"
#ifndef M_PI_2
#define M_PI_2 1.57079632679489661923
#endif // M_PI_2
#define ONE_MINUS_SQR(x) (1.0 - (x) * (x))
#define ALBERS_Q(slat, one_minus_sqr_es_sin, es_sin) \
(_one_minus_es2 * ((slat) / (one_minus_sqr_es_sin) - \
(1 / (_two_es)) * log((1 - (es_sin)) / (1 + (es_sin)))))
#define ALBERS_M(clat, one_minus_sqr_es_sin) \
((clat) / sqrt(one_minus_sqr_es_sin))
AlbersEqual::AlbersEqual(const Ellipsoid &ellipsoid, double standardParallel1,
double standardParallel2, double latitudeOrigin, double longitudeOrigin,
double falseEasting, double falseNorthing)
{
double sin_lat, sin_lat1, sin_lat2, cos_lat1, cos_lat2;
double m1, m2, sqr_m1, sqr_m2;
double q0, q1, q2;
double es_sin, es_sin1, es_sin2;
double one_minus_sqr_es_sin1, one_minus_sqr_es_sin2;
double nq0;
double sp1, sp2;
_e = ellipsoid;
_latitudeOrigin = deg2rad(latitudeOrigin);
_longitudeOrigin = deg2rad(longitudeOrigin);
_falseEasting = falseEasting;
_falseNorthing = falseNorthing;
sp1 = deg2rad(standardParallel1);
sp2 = deg2rad(standardParallel2);
_es2 = 2 * _e.flattening() - _e.flattening() * _e.flattening();
_es = sqrt(_es2);
_one_minus_es2 = 1 - _es2;
_two_es = 2 * _es;
sin_lat = sin(_latitudeOrigin);
es_sin = _es * sin_lat;
q0 = ALBERS_Q(sin_lat, ONE_MINUS_SQR(es_sin), es_sin);
sin_lat1 = sin(sp1);
cos_lat1 = cos(sp1);
es_sin1 = _es * sin_lat1;
one_minus_sqr_es_sin1 = ONE_MINUS_SQR(es_sin1);
m1 = ALBERS_M(cos_lat1, one_minus_sqr_es_sin1);
q1 = ALBERS_Q(sin_lat1, one_minus_sqr_es_sin1, es_sin1);
sqr_m1 = m1 * m1;
if (fabs(sp1 - sp2) > 1.0e-10) {
sin_lat2 = sin(sp2);
cos_lat2 = cos(sp2);
es_sin2 = _es * sin_lat2;
one_minus_sqr_es_sin2 = ONE_MINUS_SQR(es_sin2);
m2 = ALBERS_M(cos_lat2, one_minus_sqr_es_sin2);
q2 = ALBERS_Q(sin_lat2, one_minus_sqr_es_sin2, es_sin2);
sqr_m2 = m2 * m2;
_n = (sqr_m1 - sqr_m2) / (q2 - q1);
} else
_n = sin_lat1;
_C = sqr_m1 + _n * q1;
_a_over_n = _e.radius() / _n;
nq0 = _n * q0;
_rho0 = (_C < nq0) ? 0 : _a_over_n * sqrt(_C - nq0);
}
QPointF AlbersEqual::ll2xy(const Coordinates &c) const
{
double dlam;
double sin_lat;
double es_sin;
double q;
double rho;
double theta;
double nq;
dlam = deg2rad(c.lon()) - _longitudeOrigin;
if (dlam > M_PI)
dlam -= 2.0 * M_PI;
if (dlam < -M_PI)
dlam += 2.0 * M_PI;
sin_lat = sin(deg2rad(c.lat()));
es_sin = _es * sin_lat;
q = ALBERS_Q(sin_lat, ONE_MINUS_SQR(es_sin), es_sin);
nq = _n * q;
rho = (_C < nq) ? 0 : _a_over_n * sqrt(_C - nq);
theta = _n * dlam;
return QPointF(rho * sin(theta) + _falseEasting,
_rho0 - rho * cos(theta) + _falseNorthing);
}
Coordinates AlbersEqual::xy2ll(const QPointF &p) const
{
double dy, dx;
double rho0_minus_dy;
double q, qc, q_over_2;
double rho, rho_n;
double phi, delta_phi = 1.0;
double sin_phi;
double es_sin, one_minus_sqr_es_sin;
double theta = 0.0;
int count = 30;
double tolerance = 4.85e-10;
double lat, lon;
dy = p.y() - _falseNorthing;
dx = p.x() - _falseEasting;
rho0_minus_dy = _rho0 - dy;
rho = sqrt(dx * dx + rho0_minus_dy * rho0_minus_dy);
if (_n < 0) {
rho *= -1.0;
dx *= -1.0;
rho0_minus_dy *= -1.0;
}
if (rho != 0.0)
theta = atan2(dx, rho0_minus_dy);
rho_n = rho * _n;
q = (_C - (rho_n * rho_n) / (_e.radius() * _e.radius())) / _n;
qc = 1 - ((_one_minus_es2) / (_two_es)) * log((1.0 - _es) / (1.0 + _es));
if (fabs(fabs(qc) - fabs(q)) > 1.0e-6) {
q_over_2 = q / 2.0;
if (q_over_2 > 1.0)
lat = M_PI_2;
else if (q_over_2 < -1.0)
lat = -M_PI_2;
else {
phi = asin(q_over_2);
if (_es < 1.0e-10)
lat = phi;
else {
while ((fabs(delta_phi) > tolerance) && count) {
sin_phi = sin(phi);
es_sin = _es * sin_phi;
one_minus_sqr_es_sin = ONE_MINUS_SQR(es_sin);
delta_phi = (one_minus_sqr_es_sin * one_minus_sqr_es_sin)
/ (2.0 * cos(phi)) * (q / (_one_minus_es2) - sin_phi
/ one_minus_sqr_es_sin + (log((1.0 - es_sin)
/ (1.0 + es_sin)) / (_two_es)));
phi += delta_phi;
count --;
}
lat = phi;
}
if (lat > M_PI_2)
lat = M_PI_2;
else if (lat < -M_PI_2)
lat = -M_PI_2;
}
} else {
if (q >= 0.0)
lat = M_PI_2;
else
lat = -M_PI_2;
}
lon = _longitudeOrigin + theta / _n;
if (lon > M_PI)
lon -= M_PI * 2;
if (lon < -M_PI)
lon += M_PI * 2;
if (lon > M_PI)
lon = M_PI;
else if (lon < -M_PI)
lon = -M_PI;
return Coordinates(rad2deg(lon), rad2deg(lat));
}

36
src/albersequal.h Normal file
View File

@ -0,0 +1,36 @@
#ifndef ALBERSEQUAL_H
#define ALBERSEQUAL_H
#include "projection.h"
class Ellipsoid;
class AlbersEqual : public Projection
{
public:
AlbersEqual(const Ellipsoid &ellipsoid, double standardParallel1,
double standardParallel2, double latitudeOrigin, double longitudeOrigin,
double falseEasting, double falseNorthing);
virtual QPointF ll2xy(const Coordinates &c) const;
virtual Coordinates xy2ll(const QPointF &p) const;
private:
Ellipsoid _e;
double _latitudeOrigin;
double _longitudeOrigin;
double _falseEasting;
double _falseNorthing;
double _rho0;
double _C;
double _n;
double _es;
double _es2;
double _a_over_n;
double _one_minus_es2;
double _two_es;
};
#endif // ALBERSEQUAL_H

View File

@ -3,26 +3,33 @@
#include <QLocale>
#include <QFileOpenEvent>
#include <QNetworkProxyFactory>
#include <QPixmapCache>
#include <QLibraryInfo>
#include "opengl.h"
#include "gui.h"
#include "onlinemap.h"
#include "downloader.h"
#include "app.h"
App::App(int &argc, char **argv) : QApplication(argc, argv),
_argc(argc), _argv(argv)
{
_translator = new QTranslator();
QTranslator *gpxsee = new QTranslator(this);
QString locale = QLocale::system().name();
_translator->load(QString(":/lang/gpxsee_") + locale);
installTranslator(_translator);
gpxsee->load(QString(":/lang/gpxsee_") + locale);
installTranslator(gpxsee);
QTranslator *qt = new QTranslator(this);
qt->load(QLocale::system(), "qt", "_", QLibraryInfo::location(
QLibraryInfo::TranslationsPath));
installTranslator(qt);
#ifdef Q_OS_MAC
setAttribute(Qt::AA_DontShowIconsInMenus);
#endif // Q_OS_MAC
QNetworkProxyFactory::setUseSystemConfiguration(true);
QPixmapCache::setCacheLimit(65536);
OnlineMap::setDownloader(new Downloader(this));
OPENGL_SET_SAMPLES(4);
_gui = new GUI();
@ -31,7 +38,6 @@ App::App(int &argc, char **argv) : QApplication(argc, argv),
App::~App()
{
delete _gui;
delete _translator;
}
void App::run()

View File

@ -4,7 +4,6 @@
#include <QApplication>
class GUI;
class QTranslator;
class App : QApplication
{
@ -22,7 +21,6 @@ private:
int &_argc;
char **_argv;
GUI *_gui;
QTranslator *_translator;
};
#endif // APP_H

338
src/atlas.cpp Normal file
View File

@ -0,0 +1,338 @@
#include <QDir>
#include <QtAlgorithms>
#include <QPainter>
#include "rectc.h"
#include "tar.h"
#include "atlas.h"
#define ZOOM_THRESHOLD 0.9
#define TL(m) ((m)->xy2pp((m)->bounds().topLeft()))
#define BR(m) ((m)->xy2pp((m)->bounds().bottomRight()))
static bool resCmp(const OfflineMap *m1, const OfflineMap *m2)
{
qreal r1, r2;
r1 = m1->resolution(m1->bounds().center());
r2 = m2->resolution(m2->bounds().center());
return r1 > r2;
}
static bool xCmp(const OfflineMap *m1, const OfflineMap *m2)
{
return TL(m1).x() < TL(m2).x();
}
static bool yCmp(const OfflineMap *m1, const OfflineMap *m2)
{
return TL(m1).y() > TL(m2).y();
}
bool Atlas::isAtlas(Tar &tar, const QString &path)
{
QFileInfo fi(path);
QByteArray ba;
QString suffix = fi.suffix().toLower();
if (suffix == "tar") {
if (!tar.load(path)) {
_errorString = "Error reading tar file";
return false;
}
QString tbaFileName = fi.completeBaseName() + ".tba";
ba = tar.file(tbaFileName);
} else if (suffix == "tba") {
QFile tbaFile(path);
if (!tbaFile.open(QIODevice::ReadOnly)) {
_errorString = QString("Error opening tba file: %1")
.arg(tbaFile.errorString());
return false;
}
ba = tbaFile.readAll();
}
if (ba.startsWith("Atlas 1.0"))
return true;
else {
_errorString = "Missing or invalid tba file";
return false;
}
}
void Atlas::computeZooms()
{
qSort(_maps.begin(), _maps.end(), resCmp);
_zooms.append(QPair<int, int>(0, _maps.count() - 1));
for (int i = 1; i < _maps.count(); i++) {
qreal last = _maps.at(i-1)->resolution(_maps.at(i)->bounds().center());
qreal cur = _maps.at(i)->resolution(_maps.at(i)->bounds().center());
if (cur < last * ZOOM_THRESHOLD) {
_zooms.last().second = i-1;
_zooms.append(QPair<int, int>(i, _maps.count() - 1));
}
}
}
void Atlas::computeBounds()
{
QList<QPointF> offsets;
for (int i = 0; i < _maps.count(); i++)
offsets.append(QPointF());
for (int z = 0; z < _zooms.count(); z++) {
QList<OfflineMap*> m;
for (int i = _zooms.at(z).first; i <= _zooms.at(z).second; i++)
m.append(_maps.at(i));
qSort(m.begin(), m.end(), xCmp);
offsets[_maps.indexOf(m.first())].setX(0);
for (int i = 1; i < m.size(); i++) {
qreal w = round(m.first()->pp2xy(TL(m.at(i))).x());
offsets[_maps.indexOf(m.at(i))].setX(w);
}
qSort(m.begin(), m.end(), yCmp);
offsets[_maps.indexOf(m.first())].setY(0);
for (int i = 1; i < m.size(); i++) {
qreal h = round(m.first()->pp2xy(TL(m.at(i))).y());
offsets[_maps.indexOf(m.at(i))].setY(h);
}
}
for (int i = 0; i < _maps.count(); i++)
_bounds.append(QPair<QRectF, QRectF>(QRectF(TL(_maps.at(i)),
BR(_maps.at(i))), QRectF(offsets.at(i), _maps.at(i)->bounds().size())));
}
Atlas::Atlas(const QString &fileName, QObject *parent) : Map(parent)
{
Tar tar;
QFileInfo fi(fileName);
_valid = false;
_zoom = 0;
_name = fi.dir().dirName();
_ci = -1; _cz = -1;
if (!isAtlas(tar, fileName))
return;
QDir dir(fi.absolutePath());
QFileInfoList layers = dir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot);
for (int n = 0; n < layers.count(); n++) {
QDir zdir(layers.at(n).absoluteFilePath());
QFileInfoList maps = zdir.entryInfoList(QDir::Dirs
| QDir::NoDotAndDotDot);
for (int i = 0; i < maps.count(); i++) {
QString mapFile = maps.at(i).absoluteFilePath() + "/"
+ maps.at(i).fileName() + ".map";
OfflineMap *map;
if (tar.isOpen())
map = new OfflineMap(mapFile, tar, this);
else
map = new OfflineMap(mapFile, this);
if (map->isValid())
_maps.append(map);
else {
_errorString = QString("Error loading map: %1: %2")
.arg(mapFile, map->errorString());
return;
}
}
}
if (_maps.isEmpty()) {
_errorString = "No maps found in atlas";
return;
}
computeZooms();
computeBounds();
_valid = true;
}
Atlas::~Atlas()
{
for (int i = 0; i < _maps.size(); i++)
delete _maps.at(i);
}
QRectF Atlas::bounds() const
{
QSizeF s(0, 0);
for (int i = _zooms.at(_zoom).first; i <= _zooms.at(_zoom).second; i++) {
if (_bounds.at(i).second.right() > s.width())
s.setWidth(_bounds.at(i).second.right());
if (_bounds.at(i).second.bottom() > s.height())
s.setHeight(_bounds.at(i).second.bottom());
}
return QRectF(QPointF(0, 0), s);
}
qreal Atlas::resolution(const QPointF &p) const
{
int idx = _zooms.at(_zoom).first;
for (int i = _zooms.at(_zoom).first; i <= _zooms.at(_zoom).second; i++) {
if (_bounds.at(i).second.contains(_maps.at(i)->xy2pp(p))) {
idx = i;
break;
}
}
return _maps.at(idx)->resolution(p);
}
qreal Atlas::zoom() const
{
return _zoom;
}
qreal Atlas::zoomFit(const QSize &size, const RectC &br)
{
_zoom = 0;
if (!br.isValid()) {
_zoom = _zooms.size() - 1;
return _zoom;
}
for (int z = 0; z < _zooms.count(); z++) {
for (int i = _zooms.at(z).first; i <= _zooms.at(z).second; i++) {
if (!_bounds.at(i).first.contains(_maps.at(i)->ll2pp(br.center())))
continue;
QRect sbr = QRectF(_maps.at(i)->ll2xy(br.topLeft()),
_maps.at(i)->ll2xy(br.bottomRight())).toRect().normalized();
if (sbr.size().width() > size.width()
|| sbr.size().height() > size.height())
return _zoom;
_zoom = z;
break;
}
}
return _zoom;
}
qreal Atlas::zoomFit(qreal resolution, const Coordinates &c)
{
_zoom = 0;
for (int z = 0; z < _zooms.count(); z++) {
for (int i = _zooms.at(z).first; i <= _zooms.at(z).second; i++) {
if (!_bounds.at(i).first.contains(_maps.at(i)->ll2pp(c)))
continue;
if (_maps.at(i)->resolution(_maps.at(i)->ll2xy(c)) < resolution)
return _zoom;
_zoom = z;
break;
}
}
return _zoom;
}
qreal Atlas::zoomIn()
{
_zoom = qMin(_zoom + 1, _zooms.size() - 1);
return _zoom;
}
qreal Atlas::zoomOut()
{
_zoom = qMax(_zoom - 1, 0);
return _zoom;
}
QPointF Atlas::ll2xy(const Coordinates &c)
{
QPointF pp;
if (_cz != _zoom) {
_ci = -1;
_cz = _zoom;
}
if (_ci >= 0)
pp = _maps.at(_ci)->ll2pp(c);
if (_ci < 0 || !_bounds.at(_ci).first.contains(pp)) {
_ci = _zooms.at(_zoom).first;
for (int i = _zooms.at(_zoom).first; i <= _zooms.at(_zoom).second; i++) {
pp = _maps.at(i)->ll2pp(c);
if (_bounds.at(i).first.contains(pp)) {
_ci = i;
break;
}
}
}
QPointF p = _maps.at(_ci)->pp2xy(pp);
return p + _bounds.at(_ci).second.topLeft();
}
Coordinates Atlas::xy2ll(const QPointF &p)
{
int idx = _zooms.at(_zoom).first;
for (int i = _zooms.at(_zoom).first; i <= _zooms.at(_zoom).second; i++) {
if (_bounds.at(i).second.contains(_maps.at(i)->xy2pp(p))) {
idx = i;
break;
}
}
QPointF p2 = p - _bounds.at(idx).second.topLeft();
return _maps.at(idx)->xy2ll(p2);
}
void Atlas::draw(QPainter *painter, const QRectF &rect)
{
// All in one map
for (int i = _zooms.at(_zoom).first; i <= _zooms.at(_zoom).second; i++) {
if (_bounds.at(i).second.contains(rect)) {
draw(painter, rect, i);
return;
}
}
// Multiple maps
painter->fillRect(rect, Qt::white);
for (int i = _zooms.at(_zoom).first; i <= _zooms.at(_zoom).second; i++) {
QRectF ir = rect.intersected(_bounds.at(i).second);
if (!ir.isNull())
draw(painter, ir, i);
}
}
void Atlas::draw(QPainter *painter, const QRectF &rect, int mapIndex)
{
OfflineMap *map = _maps.at(mapIndex);
const QPointF offset = _bounds.at(mapIndex).second.topLeft();
QRectF pr = QRectF(rect.topLeft() - offset, rect.size());
map->load();
painter->translate(offset);
map->draw(painter, pr);
painter->translate(-offset);
}
void Atlas::unload()
{
for (int i = 0; i < _maps.count(); i++)
_maps.at(i)->unload();
}

56
src/atlas.h Normal file
View File

@ -0,0 +1,56 @@
#ifndef ATLAS_H
#define ATLAS_H
#include <QFileInfoList>
#include "map.h"
#include "offlinemap.h"
class Atlas : public Map
{
Q_OBJECT
public:
Atlas(const QString &fileName, QObject *parent = 0);
~Atlas();
const QString &name() const {return _name;}
QRectF bounds() const;
qreal resolution(const QPointF &p) const;
qreal zoom() const;
qreal zoomFit(const QSize &size, const RectC &br);
qreal zoomFit(qreal resolution, const Coordinates &c);
qreal zoomIn();
qreal zoomOut();
QPointF ll2xy(const Coordinates &c);
Coordinates xy2ll(const QPointF &p);
void draw(QPainter *painter, const QRectF &rect);
void unload();
bool isValid() const {return _valid;}
const QString &errorString() const {return _errorString;}
private:
void draw(QPainter *painter, const QRectF &rect, int mapIndex);
bool isAtlas(Tar &tar, const QString &path);
void computeZooms();
void computeBounds();
QString _name;
bool _valid;
QString _errorString;
QList<OfflineMap*> _maps;
QVector<QPair<int, int> > _zooms;
QVector<QPair<QRectF, QRectF> > _bounds;
int _zoom;
int _ci, _cz;
};
#endif // ATLAS_H

View File

@ -7,13 +7,15 @@
#include <QString>
#define APP_NAME "GPXSee"
#define APP_HOMEPAGE "http://tumic.wz.cz/gpxsee"
#define APP_HOMEPAGE "http://www.gpxsee.org"
#define FONT_FAMILY "Arial"
#define FONT_SIZE 12
#define SCREEN_DPI 96.0
#define FONT_SIZE 12 // px
#define ELLIPSOID_FILE QString("ellipsoids.csv")
#define DATUM_FILE QString("datums.csv")
#define MAP_FILE QString("maps.txt")
#define MAP_DIR QString("maps")
#define POI_DIR QString("POI")
#if defined(Q_OS_WIN32)
@ -28,10 +30,16 @@
#define GLOBAL_DIR QString("/usr/share/gpxsee")
#endif
#define USER_MAP_FILE USER_DIR + QString("/") + MAP_FILE
#define USER_POI_DIR USER_DIR + QString("/") + POI_DIR
#define GLOBAL_MAP_FILE GLOBAL_DIR + QString("/") + MAP_FILE
#define GLOBAL_POI_DIR GLOBAL_DIR + QString("/") + POI_DIR
#define TILES_DIR USER_DIR + QString("/tiles")
#define USER_ELLIPSOID_FILE USER_DIR + QString("/") + ELLIPSOID_FILE
#define USER_DATUM_FILE USER_DIR + QString("/") + DATUM_FILE
#define USER_MAP_DIR USER_DIR + QString("/") + MAP_DIR
#define USER_MAP_FILE USER_DIR + QString("/") + MAP_FILE
#define USER_POI_DIR USER_DIR + QString("/") + POI_DIR
#define GLOBAL_ELLIPSOID_FILE GLOBAL_DIR + QString("/") + ELLIPSOID_FILE
#define GLOBAL_DATUM_FILE GLOBAL_DIR + QString("/") + DATUM_FILE
#define GLOBAL_MAP_DIR GLOBAL_DIR + QString("/") + MAP_DIR
#define GLOBAL_MAP_FILE GLOBAL_DIR + QString("/") + MAP_FILE
#define GLOBAL_POI_DIR GLOBAL_DIR + QString("/") + POI_DIR
#define TILES_DIR USER_DIR + QString("/tiles")
#endif /* CONFIG_H */

View File

@ -17,27 +17,11 @@ qreal Coordinates::distanceTo(const Coordinates &c) const
return (WGS84_RADIUS * (2.0 * atan2(sqrt(a), sqrt(1.0 - a))));
}
QPointF Coordinates::toMercator() const
{
return QPointF(_lon, rad2deg(log(tan(M_PI/4.0 + deg2rad(_lat)/2.0))));
}
Coordinates Coordinates::fromMercator(const QPointF &m)
{
return Coordinates(m.x(), rad2deg(2 * atan(exp(deg2rad(m.y()))) - M_PI/2));
}
bool operator==(const Coordinates &c1, const Coordinates &c2)
{
return (c1.lat() == c2.lat() && c1.lon() == c2.lon());
}
QDebug operator<<(QDebug dbg, const Coordinates &coordinates)
{
dbg.nospace() << "Coordinates(" << coordinates.lon() << ", "
<< coordinates.lat() << ")";
return dbg.maybeSpace();
return dbg.space();
}
QPair<Coordinates, Coordinates> Coordinates::boundingRect(qreal distance) const

View File

@ -2,7 +2,7 @@
#define COORDINATES_H
#include <cmath>
#include <QPointF>
#include <QPair>
#include <QDebug>
class Coordinates
@ -20,22 +20,23 @@ public:
qreal lat() const {return _lat;}
bool isNull() const
{return (std::isnan(_lon) || std::isnan(_lat)) ? true : false;}
{return std::isnan(_lon) && std::isnan(_lat);}
bool isValid() const
{return (_lon >= -180.0 && _lon <= 180.0 && _lat >= -90.0
&& _lat <= 90.0) ? true : false;}
{return (_lon >= -180.0 && _lon <= 180.0
&& _lat >= -90.0 && _lat <= 90.0);}
qreal distanceTo(const Coordinates &c) const;
QPair<Coordinates, Coordinates> boundingRect(qreal distance) const;
QPointF toMercator() const;
static Coordinates fromMercator(const QPointF &m);
private:
qreal _lat, _lon;
};
bool operator==(const Coordinates &c1, const Coordinates &c2);
inline bool operator==(const Coordinates &c1, const Coordinates &c2)
{return (c1.lat() == c2.lat() && c1.lon() == c2.lon());}
inline bool operator!=(const Coordinates &c1, const Coordinates &c2)
{return !(c1 == c2);}
QDebug operator<<(QDebug dbg, const Coordinates &trackpoint);
#endif // COORDINATES_H

View File

@ -1,7 +1,10 @@
#include "csvparser.h"
bool CSVParser::loadFile(QFile *file)
bool CSVParser::parse(QFile *file, QList<TrackData> &track,
QList<RouteData> &routes, QList<Waypoint> &waypoints)
{
Q_UNUSED(track);
Q_UNUSED(routes);
bool res;
_errorLine = 1;
@ -36,7 +39,7 @@ bool CSVParser::loadFile(QFile *file)
wp.setDescription(QString::fromUtf8(ba.data(), ba.size()));
}
_waypoints.append(wp);
waypoints.append(wp);
_errorLine++;
}

View File

@ -6,12 +6,11 @@
class CSVParser : public Parser
{
public:
CSVParser(QList<TrackData> &tracks, QList<RouteData> &routes,
QList<Waypoint> &waypoints) : Parser(tracks, routes, waypoints)
{_errorLine = 0;}
CSVParser() : _errorLine(0) {}
~CSVParser() {}
bool loadFile(QFile *file);
bool parse(QFile *file, QList<TrackData> &track, QList<RouteData> &routes,
QList<Waypoint> &waypoints);
QString errorString() const {return _errorString;}
int errorLine() const {return _errorLine;}

View File

@ -11,38 +11,32 @@
#include "data.h"
Data::Data() : _errorLine(0)
static QHash<QString, Parser*> parsers()
{
_parsers.insert("gpx", new GPXParser(_trackData, _routeData,
_waypointData));
_parsers.insert("tcx", new TCXParser(_trackData, _routeData,
_waypointData));
_parsers.insert("kml", new KMLParser(_trackData, _routeData,
_waypointData));
_parsers.insert("fit", new FITParser(_trackData, _routeData,
_waypointData));
_parsers.insert("csv", new CSVParser(_trackData, _routeData,
_waypointData));
_parsers.insert("igc", new IGCParser(_trackData, _routeData,
_waypointData));
_parsers.insert("nmea", new NMEAParser(_trackData, _routeData,
_waypointData));
QHash<QString, Parser*> hash;
hash.insert("gpx", new GPXParser());
hash.insert("tcx", new TCXParser());
hash.insert("kml", new KMLParser());
hash.insert("fit", new FITParser());
hash.insert("csv", new CSVParser());
hash.insert("igc", new IGCParser());
hash.insert("nmea", new NMEAParser());
return hash;
}
QHash<QString, Parser*> Data::_parsers = parsers();
Data::~Data()
{
QHash<QString, Parser*>::iterator it;
for (it = _parsers.begin(); it != _parsers.end(); it++)
delete it.value();
for (int i = 0; i < _tracks.count(); i++)
delete _tracks.at(i);
for (int i = 0; i < _routes.count(); i++)
delete _routes.at(i);
}
void Data::createData()
void Data::processData()
{
for (int i = 0; i < _trackData.count(); i++)
_tracks.append(new Track(_trackData.at(i)));
@ -66,8 +60,8 @@ bool Data::loadFile(const QString &fileName)
QHash<QString, Parser*>::iterator it;
if ((it = _parsers.find(fi.suffix().toLower())) != _parsers.end()) {
if (it.value()->loadFile(&file)) {
createData();
if (it.value()->parse(&file, _trackData, _routeData, _waypoints)) {
processData();
return true;
}
@ -75,16 +69,16 @@ bool Data::loadFile(const QString &fileName)
_errorString = it.value()->errorString();
} else {
for (it = _parsers.begin(); it != _parsers.end(); it++) {
if (it.value()->loadFile(&file)) {
createData();
if (it.value()->parse(&file, _trackData, _routeData, _waypoints)) {
processData();
return true;
}
file.reset();
}
fprintf(stderr, "Error loading data file: %s:\n", qPrintable(fileName));
qWarning("Error loading data file: %s:\n", qPrintable(fileName));
for (it = _parsers.begin(); it != _parsers.end(); it++)
fprintf(stderr, "%s: line %d: %s\n", qPrintable(it.key()),
qWarning("%s: line %d: %s\n", qPrintable(it.key()),
it.value()->errorLine(), qPrintable(it.value()->errorString()));
_errorLine = 0;
@ -93,3 +87,23 @@ bool Data::loadFile(const QString &fileName)
return false;
}
QString Data::formats()
{
return tr("Supported files (*.csv *.fit *.gpx *.igc *.kml *.nmea *.tcx)")
+ ";;" + tr("CSV files (*.csv)") + ";;" + tr("FIT files (*.fit)") + ";;"
+ tr("GPX files (*.gpx)") + ";;" + tr("IGC files (*.igc)") + ";;"
+ tr("KML files (*.kml)") + ";;" + tr("NMEA files (*.nmea)") + ";;"
+ tr("TCX files (*.tcx)") + ";;" + tr("All files (*)");
}
QStringList Data::filter()
{
QStringList filter;
QHash<QString, Parser*>::iterator it;
for (it = _parsers.begin(); it != _parsers.end(); it++)
filter << QString("*.%1").arg(it.key());
return filter;
}

View File

@ -6,16 +6,19 @@
#include <QHash>
#include <QPointF>
#include <QString>
#include <QStringList>
#include "waypoint.h"
#include "track.h"
#include "route.h"
#include "parser.h"
class Data
class Data : public QObject
{
Q_OBJECT
public:
Data();
Data(QObject *parent = 0) : QObject(parent), _errorLine(0) {}
~Data();
bool loadFile(const QString &fileName);
@ -24,21 +27,25 @@ public:
const QList<Track*> &tracks() const {return _tracks;}
const QList<Route*> &routes() const {return _routes;}
const QList<Waypoint> &waypoints() const {return _waypointData;}
const QList<Waypoint> &waypoints() const {return _waypoints;}
static QString formats();
static QStringList filter();
private:
void createData();
void processData();
QString _errorString;
int _errorLine;
QHash<QString, Parser*> _parsers;
QList<Track*> _tracks;
QList<Route*> _routes;
QList<Waypoint> _waypoints;
QList<TrackData> _trackData;
QList<RouteData> _routeData;
QList<Waypoint> _waypointData;
static QHash<QString, Parser*> _parsers;
};
#endif // DATA_H

121
src/datum.cpp Normal file
View File

@ -0,0 +1,121 @@
#include <cmath>
#include <QFile>
#include "wgs84.h"
#include "rd.h"
#include "datum.h"
static QMap<QString, Datum> WGS84()
{
QMap<QString, Datum> map;
map.insert("WGS 84", Datum(Ellipsoid(WGS84_RADIUS, WGS84_FLATTENING),
0.0, 0.0, 0.0));
return map;
}
QMap<QString, Datum> Datum::_datums = WGS84();
QString Datum::_errorString;
int Datum::_errorLine = 0;
Datum Datum::datum(const QString &name)
{
QMap<QString, Datum>::const_iterator it = _datums.find(name);
if (it == _datums.end())
return Datum();
return it.value();
}
bool Datum::loadList(const QString &path)
{
QFile file(path);
bool res;
if (!file.open(QFile::ReadOnly)) {
_errorString = qPrintable(file.errorString());
return false;
}
_errorLine = 1;
_errorString.clear();
while (!file.atEnd()) {
QByteArray line = file.readLine();
QList<QByteArray> list = line.split(',');
if (list.size() != 6) {
_errorString = "Format error";
return false;
}
int eid = list[2].trimmed().toInt(&res);
if (!res) {
_errorString = "Invalid ellipsoid id";
return false;
}
double dx = list[3].trimmed().toDouble(&res);
if (!res) {
_errorString = "Invalid dx";
return false;
}
double dy = list[4].trimmed().toDouble(&res);
if (!res) {
_errorString = "Invalid dy";
return false;
}
double dz = list[5].trimmed().toDouble(&res);
if (!res) {
_errorString = "Invalid dz";
return false;
}
Ellipsoid e = Ellipsoid::ellipsoid(eid);
if (e.isNull()) {
_errorString = "Unknown ellipsoid ID";
return false;
}
Datum d(e, dx, dy, dz);
_datums.insert(list[0].trimmed(), d);
_errorLine++;
}
return true;
}
// Abridged Molodensky transformation
Coordinates Datum::toWGS84(const Coordinates &c) const
{
if (_ellipsoid.radius() == WGS84_RADIUS
&& _ellipsoid.flattening() == WGS84_FLATTENING
&& _dx == 0.0 && _dy == 0.0 && _dz == 0.0)
return c;
double rlat = deg2rad(c.lat());
double rlon = deg2rad(c.lon());
double slat = sin(rlat);
double clat = cos(rlat);
double slon = sin(rlon);
double clon = cos(rlon);
double ssqlat = slat * slat;
double from_f = ellipsoid().flattening();
double df = WGS84_FLATTENING - from_f;
double from_a = ellipsoid().radius();
double da = WGS84_RADIUS - from_a;
double from_esq = ellipsoid().flattening()
* (2.0 - ellipsoid().flattening());
double adb = 1.0 / (1.0 - from_f);
double rn = from_a / sqrt(1 - from_esq * ssqlat);
double rm = from_a * (1 - from_esq) / pow((1 - from_esq * ssqlat), 1.5);
double from_h = 0.0;
double dlat = (-dx() * slat * clon - dy() * slat * slon + dz() * clat + da
* rn * from_esq * slat * clat / from_a + df * (rm * adb + rn / adb) * slat
* clat) / (rm + from_h);
double dlon = (-dx() * slon + dy() * clon) / ((rn + from_h) * clat);
return Coordinates(c.lon() + rad2deg(dlon), c.lat() + rad2deg(dlat));
}

40
src/datum.h Normal file
View File

@ -0,0 +1,40 @@
#ifndef DATUM_H
#define DATUM_H
#include <QMap>
#include "ellipsoid.h"
#include "coordinates.h"
class Datum
{
public:
Datum() : _ellipsoid(Ellipsoid()), _dx(0.0), _dy(0.0), _dz(0.0) {}
Datum(const Ellipsoid &ellipsoid, double dx, double dy, double dz)
: _ellipsoid(ellipsoid), _dx(dx), _dy(dy), _dz(dz) {}
const Ellipsoid &ellipsoid() const {return _ellipsoid;}
double dx() const {return _dx;}
double dy() const {return _dy;}
double dz() const {return _dz;}
bool isNull() const
{return (_ellipsoid.isNull() && _dx == 0.0 && _dy == 0.0 && _dz == 0.0);}
Coordinates toWGS84(const Coordinates &c) const;
static bool loadList(const QString &path);
static const QString &errorString() {return _errorString;}
static int errorLine() {return _errorLine;}
static Datum datum(const QString &name);
private:
Ellipsoid _ellipsoid;
double _dx, _dy, _dz;
static QMap<QString, Datum> _datums;
static QString _errorString;
static int _errorLine;
};
#endif // DATUM_H

View File

@ -61,7 +61,7 @@ bool Downloader::saveToDisk(const QString &filename, QIODevice *data)
QFile file(filename);
if (!file.open(QIODevice::WriteOnly)) {
fprintf(stderr, "Error writing map tile: %s: %s\n",
qWarning("Error writing map tile: %s: %s\n",
qPrintable(filename), qPrintable(file.errorString()));
return false;
}
@ -80,11 +80,11 @@ void Downloader::downloadFinished(QNetworkReply *reply)
QUrl origin = reply->request().attribute(ATTR_ORIGIN).toUrl();
if (origin.isEmpty()) {
_errorDownloads.insert(url);
fprintf(stderr, "Error downloading map tile: %s: %s\n",
qWarning("Error downloading map tile: %s: %s\n",
url.toEncoded().constData(), qPrintable(reply->errorString()));
} else {
_errorDownloads.insert(origin);
fprintf(stderr, "Error downloading map tile: %s -> %s: %s\n",
qWarning("Error downloading map tile: %s -> %s: %s\n",
origin.toEncoded().constData(), url.toEncoded().constData(),
qPrintable(reply->errorString()));
}
@ -99,11 +99,11 @@ void Downloader::downloadFinished(QNetworkReply *reply)
if (location == url) {
_errorDownloads.insert(url);
fprintf(stderr, "Error downloading map tile: %s: "
qWarning("Error downloading map tile: %s: "
"redirect loop\n", url.toEncoded().constData());
} else if (level >= MAX_REDIRECT_LEVEL) {
_errorDownloads.insert(origin);
fprintf(stderr, "Error downloading map tile: %s: "
qWarning("Error downloading map tile: %s: "
"redirect level limit reached\n",
origin.toEncoded().constData());
} else {

62
src/ellipsoid.cpp Normal file
View File

@ -0,0 +1,62 @@
#include <QFile>
#include "ellipsoid.h"
QMap<int, Ellipsoid> Ellipsoid::_ellipsoids;
QString Ellipsoid::_errorString;
int Ellipsoid::_errorLine = 0;
Ellipsoid Ellipsoid::ellipsoid(int id)
{
QMap<int, Ellipsoid>::const_iterator it = _ellipsoids.find(id);
if (it == _ellipsoids.end())
return Ellipsoid();
return it.value();
}
bool Ellipsoid::loadList(const QString &path)
{
QFile file(path);
bool res;
if (!file.open(QFile::ReadOnly)) {
_errorString = qPrintable(file.errorString());
return false;
}
_errorLine = 1;
_errorString.clear();
while (!file.atEnd()) {
QByteArray line = file.readLine();
QList<QByteArray> list = line.split(',');
if (list.size() != 4) {
_errorString = "Format error";
return false;
}
int id = list[0].trimmed().toInt(&res);
if (!res) {
_errorString = "Invalid ellipsoid id";
return false;
}
double radius = list[2].trimmed().toDouble(&res);
if (!res) {
_errorString = "Invalid ellipsoid radius";
return false;
}
double flattening = list[3].trimmed().toDouble(&res);
if (!res) {
_errorString = "Invalid ellipsoid flattening";
return false;
}
Ellipsoid e(radius, 1.0/flattening);
_ellipsoids.insert(id, e);
_errorLine++;
}
return true;
}

34
src/ellipsoid.h Normal file
View File

@ -0,0 +1,34 @@
#ifndef ELLIPSOID_H
#define ELLIPSOID_H
#include <QString>
#include <QMap>
class Ellipsoid
{
public:
Ellipsoid() : _radius(0.0), _flattening(0.0) {}
Ellipsoid(double radius, double flattening)
: _radius(radius), _flattening(flattening) {}
double radius() const {return _radius;}
double flattening() const {return _flattening;}
bool isNull() const {return (_radius == 0.0 && _flattening == 0.0);}
static bool loadList(const QString &path);
static const QString &errorString() {return _errorString;}
static int errorLine() {return _errorLine;}
static Ellipsoid ellipsoid(int id);
private:
double _radius;
double _flattening;
static QMap<int, Ellipsoid> _ellipsoids;
static QString _errorString;
static int _errorLine;
};
#endif // ELLIPSOID_H

86
src/emptymap.cpp Normal file
View File

@ -0,0 +1,86 @@
#include <QtGlobal>
#include <QPainter>
#include "rectc.h"
#include "misc.h"
#include "rd.h"
#include "wgs84.h"
#include "coordinates.h"
#include "mercator.h"
#include "emptymap.h"
#define SCALE_MIN 0.5
#define SCALE_MAX 1.0E-6
EmptyMap::EmptyMap(QObject *parent) : Map(parent)
{
_scale = SCALE_MAX;
}
QRectF EmptyMap::bounds() const
{
return scaled(QRectF(QPointF(-180, -180), QSizeF(360, 360)), 1.0/_scale);
}
qreal EmptyMap::zoomFit(const QSize &size, const RectC &br)
{
if (!br.isValid())
_scale = SCALE_MAX;
else {
QRectF tbr(Mercator().ll2xy(br.topLeft()),
Mercator().ll2xy(br.bottomRight()));
QPointF sc(tbr.width() / size.width(), tbr.height() / size.height());
_scale = qMax(sc.x(), sc.y());
}
_scale = qMax(_scale, SCALE_MAX);
_scale = qMin(_scale, SCALE_MIN);
return _scale;
}
qreal EmptyMap::zoomFit(qreal resolution, const Coordinates &c)
{
_scale = (360.0 * resolution) / (WGS84_RADIUS * 2 * M_PI
* cos(deg2rad(c.lat())));
_scale = qMax(_scale, SCALE_MAX);
_scale = qMin(_scale, SCALE_MIN);
return _scale;
}
qreal EmptyMap::resolution(const QPointF &p) const
{
return (WGS84_RADIUS * 2 * M_PI * _scale / 360.0
* cos(2.0 * atan(exp(deg2rad(-p.y() * _scale))) - M_PI/2));
}
qreal EmptyMap::zoomIn()
{
_scale = qMax(_scale / 2.0, SCALE_MAX);
return _scale;
}
qreal EmptyMap::zoomOut()
{
_scale = qMin(_scale * 2.0, SCALE_MIN);
return _scale;
}
void EmptyMap::draw(QPainter *painter, const QRectF &rect)
{
painter->fillRect(rect, Qt::white);
}
QPointF EmptyMap::ll2xy(const Coordinates &c)
{
QPointF m = Mercator().ll2xy(c);
return QPointF(m.x() / _scale, m.y() / -_scale);
}
Coordinates EmptyMap::xy2ll(const QPointF &p)
{
QPointF m(p.x() * _scale, -p.y() * _scale);
return Mercator().xy2ll(m);
}

34
src/emptymap.h Normal file
View File

@ -0,0 +1,34 @@
#ifndef EMPTYMAP_H
#define EMPTYMAP_H
#include "map.h"
class EmptyMap : public Map
{
Q_OBJECT
public:
EmptyMap(QObject *parent = 0);
const QString &name() const {return _name;}
QRectF bounds() const;
qreal resolution(const QPointF &p) const;
qreal zoom() const {return _scale;}
qreal zoomFit(const QSize &size, const RectC &br);
qreal zoomFit(qreal resolution, const Coordinates &c);
qreal zoomIn();
qreal zoomOut();
QPointF ll2xy(const Coordinates &c);
Coordinates xy2ll(const QPointF &p);
void draw(QPainter *painter, const QRectF &rect);
private:
QString _name;
qreal _scale;
};
#endif // EMPTYMAP_H

View File

@ -26,15 +26,28 @@ ExportDialog::ExportDialog(Export *exp, QWidget *parent)
_fileSelect->setFile(_export->fileName);
_paperSize = new QComboBox();
_paperSize->addItem("A2", QPrinter::A2);
_paperSize->addItem("A3", QPrinter::A3);
_paperSize->addItem("A4", QPrinter::A4);
_paperSize->addItem("A5", QPrinter::A5);
_paperSize->addItem("A6", QPrinter::A6);
_paperSize->addItem("B3", QPrinter::B3);
_paperSize->addItem("B4", QPrinter::B4);
_paperSize->addItem("B5", QPrinter::B5);
_paperSize->addItem("B6", QPrinter::B6);
_paperSize->addItem("Tabloid", QPrinter::Tabloid);
_paperSize->addItem("Legal", QPrinter::Legal);
_paperSize->addItem("Letter", QPrinter::Letter);
if ((index = _paperSize->findData(_export->paperSize)) >= 0)
_paperSize->setCurrentIndex(index);
_resolution = new QComboBox();
_resolution->addItem("300 DPI", 300);
_resolution->addItem("600 DPI", 600);
_resolution->addItem("1200 DPI", 1200);
if ((index = _resolution->findData(_export->resolution)) >= 0)
_resolution->setCurrentIndex(index);
_portrait = new QRadioButton(tr("Portrait"));
_landscape = new QRadioButton(tr("Landscape"));
QHBoxLayout *orientationLayout = new QHBoxLayout();
@ -81,6 +94,7 @@ ExportDialog::ExportDialog(Export *exp, QWidget *parent)
#endif // Q_OS_MAC
QFormLayout *pageSetupLayout = new QFormLayout;
pageSetupLayout->addRow(tr("Page size:"), _paperSize);
pageSetupLayout->addRow(tr("Resolution:"), _resolution);
pageSetupLayout->addRow(tr("Orientation:"), orientationLayout);
pageSetupLayout->addRow(tr("Margins:"), marginsLayout);
#ifdef Q_OS_MAC
@ -161,9 +175,11 @@ void ExportDialog::accept()
? QPrinter::Portrait : QPrinter::Landscape;
QPrinter::PaperSize paperSize = static_cast<QPrinter::PaperSize>
(_paperSize->itemData(_paperSize->currentIndex()).toInt());
int resolution = _resolution->itemData(_resolution->currentIndex()).toInt();
_export->fileName = _fileSelect->file();
_export->paperSize = paperSize;
_export->resolution = resolution;
_export->orientation = orientation;
if (_export->units == Imperial)
_export->margins = MarginsF(_leftMargin->value() / MM2IN,

View File

@ -16,6 +16,7 @@ struct Export {
QPrinter::PaperSize paperSize;
QPrinter::Orientation orientation;
MarginsF margins;
int resolution;
Units units;
};
@ -37,6 +38,7 @@ private:
FileSelectWidget *_fileSelect;
QComboBox *_paperSize;
QComboBox *_resolution;
QRadioButton *_portrait;
QRadioButton *_landscape;
QDoubleSpinBox *_topMargin;

View File

@ -10,8 +10,7 @@ const quint32 FIT_MAGIC = 0x5449462E; // .FIT
#define TIMESTAMP_FIELD 253
FITParser::FITParser(QList<TrackData> &tracks, QList<RouteData> &routes,
QList<Waypoint> &waypoints) : Parser(tracks, routes, waypoints)
FITParser::FITParser()
{
memset(_defs, 0, sizeof(_defs));
@ -36,8 +35,7 @@ void FITParser::clearDefinitions()
void FITParser::warning(const char *text) const
{
const QFile *file = static_cast<QFile *>(_device);
fprintf(stderr, "%s:%d: %s\n", qPrintable(file->fileName()),
_len, text);
qWarning("%s:%d: %s\n", qPrintable(file->fileName()), _len, text);
}
bool FITParser::readData(char *data, size_t size)
@ -192,7 +190,8 @@ bool FITParser::readField(Field *f, quint32 &val)
return ret;
}
bool FITParser::parseData(MessageDefinition *def, quint8 offset)
bool FITParser::parseData(TrackData &track, MessageDefinition *def,
quint8 offset)
{
Field *field;
quint32 timestamp = _timestamp + offset;
@ -269,7 +268,7 @@ bool FITParser::parseData(MessageDefinition *def, quint8 offset)
if (trackpoint.coordinates().isValid()) {
trackpoint.setTimestamp(QDateTime::fromTime_t(timestamp
+ 631065600));
_tracks.last().append(trackpoint);
track.append(trackpoint);
} else {
if (trackpoint.coordinates().isNull())
warning("Missing coordinates");
@ -283,21 +282,21 @@ bool FITParser::parseData(MessageDefinition *def, quint8 offset)
return true;
}
bool FITParser::parseDataMessage(quint8 header)
bool FITParser::parseDataMessage(TrackData &track, quint8 header)
{
int local_id = header & 0xf;
MessageDefinition* def = &_defs[local_id];
return parseData(def, 0);
return parseData(track, def, 0);
}
bool FITParser::parseCompressedMessage(quint8 header)
bool FITParser::parseCompressedMessage(TrackData &track, quint8 header)
{
int local_id = (header >> 5) & 3;
MessageDefinition* def = &_defs[local_id];
return parseData(def, header & 0x1f);
return parseData(track, def, header & 0x1f);
}
bool FITParser::parseRecord()
bool FITParser::parseRecord(TrackData &track)
{
quint8 header;
@ -305,11 +304,11 @@ bool FITParser::parseRecord()
return false;
if (header & 0x80)
return parseCompressedMessage(header);
return parseCompressedMessage(track, header);
else if (header & 0x40)
return parseDefinitionMessage(header);
else
return parseDataMessage(header);
return parseDataMessage(track, header);
}
bool FITParser::parseHeader()
@ -338,8 +337,11 @@ bool FITParser::parseHeader()
return true;
}
bool FITParser::loadFile(QFile *file)
bool FITParser::parse(QFile *file, QList<TrackData> &tracks,
QList<RouteData> &routes, QList<Waypoint> &waypoints)
{
Q_UNUSED(routes);
Q_UNUSED(waypoints);
bool ret = true;
_device = file;
@ -349,10 +351,11 @@ bool FITParser::loadFile(QFile *file)
if (!parseHeader())
return false;
_tracks.append(TrackData());
tracks.append(TrackData());
TrackData &track = tracks.last();
while (_len)
if ((ret = parseRecord()) == false)
if ((ret = parseRecord(track)) == false)
break;
clearDefinitions();

View File

@ -6,37 +6,37 @@
class FITParser : public Parser
{
public:
FITParser(QList<TrackData> &tracks, QList<RouteData> &routes,
QList<Waypoint> &waypoints);
FITParser();
~FITParser() {}
bool loadFile(QFile *file);
bool parse(QFile *file, QList<TrackData> &tracks, QList<RouteData> &routes,
QList<Waypoint> &waypoints);
QString errorString() const {return _errorString;}
int errorLine() const {return 0;}
private:
typedef struct {
struct FileHeader {
quint8 headerSize;
quint8 protocolVersion;
quint16 profileVersion;
quint32 dataSize;
quint32 magic;
} FileHeader;
};
typedef struct {
struct Field {
quint8 id;
quint8 size;
quint8 type;
} Field;
};
typedef struct {
struct MessageDefinition {
quint8 endian;
quint16 globalId;
quint8 numFields;
Field *fields;
quint8 numDevFields;
Field *devFields;
} MessageDefinition;
};
void warning(const char *text) const;
@ -47,11 +47,11 @@ private:
bool skipValue(size_t size);
bool parseHeader();
bool parseRecord();
bool parseRecord(TrackData &track);
bool parseDefinitionMessage(quint8 header);
bool parseCompressedMessage(quint8 header);
bool parseDataMessage(quint8 header);
bool parseData(MessageDefinition *def, quint8 offset);
bool parseCompressedMessage(TrackData &track, quint8 header);
bool parseDataMessage(TrackData &track, quint8 header);
bool parseData(TrackData &track, MessageDefinition *def, quint8 offset);
bool readField(Field *f, quint32 &val);
QIODevice *_device;

View File

@ -167,39 +167,36 @@ void GPXParser::track(TrackData &track)
}
}
void GPXParser::gpx()
void GPXParser::gpx(QList<TrackData> &tracks, QList<RouteData> &routes,
QList<Waypoint> &waypoints)
{
while (_reader.readNextStartElement()) {
if (_reader.name() == "trk") {
_tracks.append(TrackData());
track(_tracks.back());
tracks.append(TrackData());
track(tracks.back());
} else if (_reader.name() == "rte") {
_routes.append(RouteData());
routepoints(_routes.back());
routes.append(RouteData());
routepoints(routes.back());
} else if (_reader.name() == "wpt") {
_waypoints.append(Waypoint(coordinates()));
waypointData(_waypoints.last());
waypoints.append(Waypoint(coordinates()));
waypointData(waypoints.last());
} else
_reader.skipCurrentElement();
}
}
bool GPXParser::parse()
bool GPXParser::parse(QFile *file, QList<TrackData> &tracks,
QList<RouteData> &routes, QList<Waypoint> &waypoints)
{
_reader.clear();
_reader.setDevice(file);
if (_reader.readNextStartElement()) {
if (_reader.name() == "gpx")
gpx();
gpx(tracks, routes, waypoints);
else
_reader.raiseError("Not a GPX file");
}
return !_reader.error();
}
bool GPXParser::loadFile(QFile *file)
{
_reader.clear();
_reader.setDevice(file);
return parse();
}

View File

@ -8,17 +8,16 @@
class GPXParser : public Parser
{
public:
GPXParser(QList<TrackData> &tracks, QList<RouteData> &routes,
QList<Waypoint> &waypoints) : Parser(tracks, routes, waypoints) {}
~GPXParser() {}
bool loadFile(QFile *file);
bool parse(QFile *file, QList<TrackData> &tracks,
QList<RouteData> &routes, QList<Waypoint> &waypoints);
QString errorString() const {return _reader.errorString();}
int errorLine() const {return _reader.lineNumber();}
private:
bool parse();
void gpx();
void gpx(QList<TrackData> &tracks, QList<RouteData> &routes,
QList<Waypoint> &waypoints);
void track(TrackData &track);
void trackpoints(TrackData &track);
void routepoints(RouteData &route);

View File

@ -4,6 +4,5 @@ QDebug operator<<(QDebug dbg, const GraphPoint &point)
{
dbg.nospace() << "GraphPoint(" << point.s() << ", " << point.t() << ", "
<< point.y() << ")";
return dbg.maybeSpace();
return dbg.space();
}

View File

@ -31,22 +31,6 @@ private:
Q_DECLARE_TYPEINFO(GraphPoint, Q_PRIMITIVE_TYPE);
QDebug operator<<(QDebug dbg, const GraphPoint &point);
class Graph : public QVector<GraphPoint>
{
public:
Graph() : QVector<GraphPoint>() {_time = true;}
void append(const GraphPoint &p)
{
if (std::isnan(p.t()))
_time = false;
QVector<GraphPoint>::append(p);
}
bool hasTime() const {return _time;}
private:
bool _time;
};
typedef QVector<GraphPoint> Graph;
#endif // GRAPH_H

View File

@ -14,6 +14,14 @@ GraphItem::GraphItem(const Graph &graph, QGraphicsItem *parent)
_graph = graph;
_sx = 1.0; _sy = 1.0;
_time = true;
for (int i = 0; i < _graph.size(); i++) {
if (std::isnan(_graph.at(i).t())) {
_time = false;
break;
}
}
setZValue(1.0);
updatePath();
@ -124,7 +132,7 @@ qreal GraphItem::distanceAtTime(qreal time)
void GraphItem::emitSliderPositionChanged(qreal pos)
{
if (_type == Time) {
if (_graph.hasTime()) {
if (_time) {
if (pos >= _graph.first().t() && pos <= _graph.last().t())
emit sliderPositionChanged(distanceAtTime(pos));
else
@ -163,7 +171,7 @@ void GraphItem::updatePath()
{
_path = QPainterPath();
if (_type == Time && !_graph.hasTime())
if (_type == Time && !_time)
return;
_path.moveTo(_graph.first().x(_type) * _sx, -_graph.first().y() * _sy);
@ -173,7 +181,7 @@ void GraphItem::updatePath()
void GraphItem::updateBounds()
{
if (_type == Time && !_graph.hasTime()) {
if (_type == Time && !_time) {
_bounds = QRectF();
return;
}

View File

@ -50,6 +50,8 @@ private:
QPainterPath _path;
QRectF _bounds;
qreal _sx, _sy;
bool _time;
};
#endif // GRAPHITEM_H

View File

@ -326,11 +326,9 @@ void GraphView::mousePressEvent(QMouseEvent *e)
QGraphicsView::mousePressEvent(e);
}
void GraphView::plot(QPainter *painter, const QRectF &target)
void GraphView::plot(QPainter *painter, const QRectF &target, qreal scale)
{
qreal ratio = painter->paintEngine()->paintDevice()->logicalDpiX()
/ SCREEN_DPI;
QSizeF canvas = QSizeF(target.width() / ratio, target.height() / ratio);
QSizeF canvas = QSizeF(target.width() / scale, target.height() / scale);
setUpdatesEnabled(false);
redraw(canvas);

View File

@ -53,7 +53,7 @@ public:
qreal sliderPosition() const {return _sliderPos;}
void setSliderPosition(qreal pos);
void plot(QPainter *painter, const QRectF &target);
void plot(QPainter *painter, const QRectF &target, qreal scale);
void useOpenGL(bool use);

View File

@ -21,13 +21,17 @@
#include <QLocale>
#include <QMimeData>
#include <QUrl>
#include <QPixmapCache>
#include "config.h"
#include "icons.h"
#include "keys.h"
#include "settings.h"
#include "data.h"
#include "ellipsoid.h"
#include "datum.h"
#include "map.h"
#include "maplist.h"
#include "emptymap.h"
#include "elevationgraph.h"
#include "speedgraph.h"
#include "heartrategraph.h"
@ -36,7 +40,6 @@
#include "powergraph.h"
#include "pathview.h"
#include "trackinfo.h"
#include "downloader.h"
#include "filebrowser.h"
#include "cpuarch.h"
#include "graphtab.h"
@ -44,8 +47,9 @@
#include "gui.h"
GUI::GUI(QWidget *parent) : QMainWindow(parent)
GUI::GUI()
{
loadDatums();
loadMaps();
loadPOIs();
@ -98,32 +102,92 @@ GUI::~GUI()
}
}
const QString GUI::fileFormats() const
void GUI::loadDatums()
{
return tr("Supported files (*.csv *.fit *.gpx *.igc *.kml *.nmea *.tcx)")
+ ";;" + tr("CSV files (*.csv)") + ";;" + tr("FIT files (*.fit)") + ";;"
+ tr("GPX files (*.gpx)") + ";;" + tr("IGC files (*.igc)") + ";;"
+ tr("KML files (*.kml)") + ";;" + tr("NMEA files (*.nmea)") + ";;"
+ tr("TCX files (*.tcx)") + ";;" + tr("All files (*)");
}
QString ef, df;
bool ok = false;
void GUI::createBrowser()
{
QStringList filter;
filter << "*.gpx" << "*.tcx" << "*.kml" << "*.fit" << "*.csv" << "*.igc"
<< "*.nmea";
_browser = new FileBrowser(this);
_browser->setFilter(filter);
if (QFile::exists(USER_ELLIPSOID_FILE))
ef = USER_ELLIPSOID_FILE;
else if (QFile::exists(GLOBAL_ELLIPSOID_FILE))
ef = GLOBAL_ELLIPSOID_FILE;
else
qWarning("No ellipsoids file found.");
if (QFile::exists(USER_DATUM_FILE))
df = USER_DATUM_FILE;
else if (QFile::exists(GLOBAL_DATUM_FILE))
df = GLOBAL_DATUM_FILE;
else
qWarning("No datums file found.");
if (!ef.isNull() && !df.isNull()) {
if (!Ellipsoid::loadList(ef)) {
if (Ellipsoid::errorLine())
qWarning("%s: parse error on line %d: %s", qPrintable(ef),
Ellipsoid::errorLine(), qPrintable(Ellipsoid::errorString()));
else
qWarning("%s: %s", qPrintable(ef), qPrintable(
Ellipsoid::errorString()));
} else {
if (!Datum::loadList(df)) {
if (Datum::errorLine())
qWarning("%s: parse error on line %d: %s", qPrintable(ef),
Datum::errorLine(), qPrintable(Datum::errorString()));
else
qWarning("%s: %s", qPrintable(ef), qPrintable(
Datum::errorString()));
} else
ok = true;
}
}
if (!ok)
qWarning("Maps based on a datum different from WGS84 won't work.");
}
void GUI::loadMaps()
{
MapList ml(new Downloader(this));
_ml = new MapList(this);
QString offline, online;
if (QFile::exists(USER_MAP_FILE))
_maps = ml.load(USER_MAP_FILE, this);
else
_maps = ml.load(GLOBAL_MAP_FILE, this);
online = USER_MAP_FILE;
else if (QFile::exists(GLOBAL_MAP_FILE))
online = GLOBAL_MAP_FILE;
if (!online.isNull() && !_ml->loadFile(online))
qWarning("%s: %s", qPrintable(online), qPrintable(_ml->errorString()));
if (QFile::exists(USER_MAP_DIR))
offline = USER_MAP_DIR;
else if (QFile::exists(GLOBAL_MAP_DIR))
offline = GLOBAL_MAP_DIR;
if (!offline.isNull()) {
QDir md(offline);
QFileInfoList ml = md.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot);
for (int i = 0; i < ml.size(); i++) {
QDir dir(ml.at(i).absoluteFilePath());
QFileInfoList fl = dir.entryInfoList(MapList::filter(), QDir::Files);
if (fl.isEmpty())
qWarning("%s: no map/atlas file found",
qPrintable(ml.at(i).absoluteFilePath()));
else if (fl.size() > 1)
qWarning("%s: ambiguous directory content",
qPrintable(ml.at(i).absoluteFilePath()));
else
if (!_ml->loadFile(fl.first().absoluteFilePath()))
qWarning("%s: %s", qPrintable(fl.first().absoluteFilePath()),
qPrintable(_ml->errorString()));
}
}
_map = _ml->maps().isEmpty() ? new EmptyMap(this) : _ml->maps().first();
}
void GUI::loadPOIs()
@ -141,44 +205,51 @@ void GUI::loadPOIs()
for (int i = 0; i < list.size(); ++i) {
if (!_poi->loadFile(list.at(i).absoluteFilePath())) {
fprintf(stderr, "Error loading POI file: %s: %s\n",
qWarning("Error loading POI file: %s: %s\n",
qPrintable(list.at(i).fileName()),
qPrintable(_poi->errorString()));
if (_poi->errorLine())
fprintf(stderr, "Line: %d\n", _poi->errorLine());
qWarning("Line: %d\n", _poi->errorLine());
}
}
}
void GUI::createBrowser()
{
_browser = new FileBrowser(this);
_browser->setFilter(Data::filter());
}
void GUI::createMapActions()
{
QActionGroup *ag = new QActionGroup(this);
ag->setExclusive(true);
_mapsSignalMapper = new QSignalMapper(this);
_mapsActionGroup = new QActionGroup(this);
_mapsActionGroup->setExclusive(true);
QSignalMapper *sm = new QSignalMapper(this);
for (int i = 0; i < _maps.count(); i++) {
QAction *a = new QAction(_maps.at(i)->name(), this);
for (int i = 0; i < _ml->maps().count(); i++) {
QAction *a = new QAction(_ml->maps().at(i)->name(), this);
a->setCheckable(true);
a->setActionGroup(ag);
a->setActionGroup(_mapsActionGroup);
sm->setMapping(a, i);
connect(a, SIGNAL(triggered()), sm, SLOT(map()));
_mapsSignalMapper->setMapping(a, i);
connect(a, SIGNAL(triggered()), _mapsSignalMapper, SLOT(map()));
_mapActions.append(a);
}
connect(sm, SIGNAL(mapped(int)), this, SLOT(mapChanged(int)));
connect(_mapsSignalMapper, SIGNAL(mapped(int)), this,
SLOT(mapChanged(int)));
}
void GUI::createPOIFilesActions()
{
_poiFilesSM = new QSignalMapper(this);
_poiFilesSignalMapper = new QSignalMapper(this);
for (int i = 0; i < _poi->files().count(); i++)
createPOIFileAction(i);
connect(_poiFilesSM, SIGNAL(mapped(int)), this, SLOT(poiFileChecked(int)));
connect(_poiFilesSignalMapper, SIGNAL(mapped(int)), this,
SLOT(poiFileChecked(int)));
}
QAction *GUI::createPOIFileAction(int index)
@ -187,8 +258,8 @@ QAction *GUI::createPOIFileAction(int index)
this);
a->setCheckable(true);
_poiFilesSM->setMapping(a, index);
connect(a, SIGNAL(triggered()), _poiFilesSM, SLOT(map()));
_poiFilesSignalMapper->setMapping(a, index);
connect(a, SIGNAL(triggered()), _poiFilesSignalMapper, SLOT(map()));
_poiFilesActions.append(a);
@ -210,6 +281,7 @@ void GUI::createActions()
// General actions
_exitAction = new QAction(QIcon(QPixmap(QUIT_ICON)), tr("Quit"), this);
_exitAction->setShortcut(QUIT_SHORTCUT);
_exitAction->setMenuRole(QAction::QuitRole);
connect(_exitAction, SIGNAL(triggered()), this, SLOT(close()));
addAction(_exitAction);
@ -220,11 +292,12 @@ void GUI::createActions()
connect(_keysAction, SIGNAL(triggered()), this, SLOT(keys()));
_aboutAction = new QAction(QIcon(QPixmap(APP_ICON)),
tr("About GPXSee"), this);
_aboutAction->setMenuRole(QAction::AboutRole);
connect(_aboutAction, SIGNAL(triggered()), this, SLOT(about()));
// File actions
_openFileAction = new QAction(QIcon(QPixmap(OPEN_FILE_ICON)),
tr("Open"), this);
tr("Open..."), this);
_openFileAction->setShortcut(OPEN_SHORTCUT);
connect(_openFileAction, SIGNAL(triggered()), this, SLOT(openFile()));
addAction(_openFileAction);
@ -254,7 +327,7 @@ void GUI::createActions()
// POI actions
_openPOIAction = new QAction(QIcon(QPixmap(OPEN_FILE_ICON)),
tr("Load POI file"), this);
tr("Load POI file..."), this);
connect(_openPOIAction, SIGNAL(triggered()), this, SLOT(openPOIFile()));
_closePOIAction = new QAction(QIcon(QPixmap(CLOSE_FILE_ICON)),
tr("Close POI files"), this);
@ -281,25 +354,27 @@ void GUI::createActions()
this);
_showMapAction->setCheckable(true);
_showMapAction->setShortcut(SHOW_MAP_SHORTCUT);
connect(_showMapAction, SIGNAL(triggered(bool)), this, SLOT(showMap(bool)));
connect(_showMapAction, SIGNAL(triggered(bool)), _pathView,
SLOT(showMap(bool)));
addAction(_showMapAction);
_loadMapAction = new QAction(QIcon(QPixmap(OPEN_FILE_ICON)),
tr("Load map..."), this);
connect(_loadMapAction, SIGNAL(triggered()), this, SLOT(loadMap()));
_clearMapCacheAction = new QAction(tr("Clear tile cache"), this);
connect(_clearMapCacheAction, SIGNAL(triggered()), this,
SLOT(clearMapCache()));
if (_maps.empty()) {
createMapActions();
_nextMapAction = new QAction(tr("Next map"), this);
_nextMapAction->setShortcut(NEXT_MAP_SHORTCUT);
connect(_nextMapAction, SIGNAL(triggered()), this, SLOT(nextMap()));
addAction(_nextMapAction);
_prevMapAction = new QAction(tr("Next map"), this);
_prevMapAction->setShortcut(PREV_MAP_SHORTCUT);
connect(_prevMapAction, SIGNAL(triggered()), this, SLOT(prevMap()));
addAction(_prevMapAction);
if (_ml->maps().isEmpty()) {
_showMapAction->setEnabled(false);
_clearMapCacheAction->setEnabled(false);
} else {
createMapActions();
_nextMapAction = new QAction(tr("Next map"), this);
_nextMapAction->setShortcut(NEXT_MAP_SHORTCUT);
connect(_nextMapAction, SIGNAL(triggered()), this, SLOT(nextMap()));
addAction(_nextMapAction);
_prevMapAction = new QAction(tr("Next map"), this);
_prevMapAction->setShortcut(PREV_MAP_SHORTCUT);
connect(_prevMapAction, SIGNAL(triggered()), this, SLOT(prevMap()));
addAction(_prevMapAction);
}
// Data actions
@ -390,6 +465,7 @@ void GUI::createActions()
SLOT(showFullscreen(bool)));
addAction(_fullscreenAction);
_openOptionsAction = new QAction(tr("Options..."), this);
_openOptionsAction->setMenuRole(QAction::PreferencesRole);
connect(_openOptionsAction, SIGNAL(triggered()), this,
SLOT(openOptions()));
@ -426,12 +502,13 @@ void GUI::createMenus()
fileMenu->addAction(_exitAction);
#endif // Q_OS_MAC
QMenu *mapMenu = menuBar()->addMenu(tr("Map"));
mapMenu->addActions(_mapActions);
mapMenu->addSeparator();
mapMenu->addAction(_clearMapCacheAction);
mapMenu->addSeparator();
mapMenu->addAction(_showMapAction);
_mapMenu = menuBar()->addMenu(tr("Map"));
_mapMenu->addActions(_mapActions);
_mapsEnd = _mapMenu->addSeparator();
_mapMenu->addAction(_loadMapAction);
_mapMenu->addAction(_clearMapCacheAction);
_mapMenu->addSeparator();
_mapMenu->addAction(_showMapAction);
QMenu *graphMenu = menuBar()->addMenu(tr("Graph"));
graphMenu->addAction(_distanceGraphAction);
@ -508,15 +585,13 @@ void GUI::createToolBars()
void GUI::createPathView()
{
_pathView = new PathView(this);
_pathView = new PathView(_map, _poi, this);
_pathView->setSizePolicy(QSizePolicy(QSizePolicy::Ignored,
QSizePolicy::Expanding));
_pathView->setMinimumHeight(200);
#ifdef Q_OS_WIN32
_pathView->setFrameShape(QFrame::NoFrame);
#endif // Q_OS_WIN32
_pathView->setPOI(_poi);
}
void GUI::createGraphTabs()
@ -561,6 +636,7 @@ void GUI::createStatusBar()
void GUI::about()
{
QMessageBox msgBox(this);
QUrl homepage(APP_HOMEPAGE);
msgBox.setWindowTitle(tr("About GPXSee"));
msgBox.setText("<h2>" + QString(APP_NAME) + "</h2><p><p>" + tr("Version ")
@ -568,7 +644,8 @@ void GUI::about()
msgBox.setInformativeText("<table width=\"300\"><tr><td>"
+ tr("GPXSee is distributed under the terms of the GNU General Public "
"License version 3. For more info about GPXSee visit the project "
"homepage at ") + "<a href=\"" + APP_HOMEPAGE + "\">" + APP_HOMEPAGE
"homepage at ") + "<a href=\"" + homepage.toString() + "\">"
+ homepage.toString(QUrl::RemoveScheme).mid(2)
+ "</a>.</td></tr></table>");
QIcon icon = msgBox.windowIcon();
@ -585,18 +662,24 @@ void GUI::keys()
msgBox.setWindowTitle(tr("Keyboard controls"));
msgBox.setText("<h3>" + tr("Keyboard controls") + "</h3>");
msgBox.setInformativeText(
"<div><table width=\"300\"><tr><td>" + tr("Next file")
+ "</td><td><i>" + QKeySequence(NEXT_KEY).toString()
"<style>td {padding-right: 1.5em;}</style><div><table><tr><td>"
+ tr("Next file") + "</td><td><i>" + QKeySequence(NEXT_KEY).toString()
+ "</i></td></tr><tr><td>" + tr("Previous file")
+ "</td><td><i>" + QKeySequence(PREV_KEY).toString()
+ "</i></td></tr><tr><td>" + tr("First file") + "</td><td><i>"
+ QKeySequence(FIRST_KEY).toString() + "</i></td></tr><tr><td>"
+ tr("Last file") + "</td><td><i>" + QKeySequence(LAST_KEY).toString()
+ "</i></td></tr><tr><td>" + tr("Append modifier")
+ "</td><td><i>SHIFT</i></td></tr><tr><td></td><td></td></tr><tr><td>"
+ tr("Next map") + "</td><td><i>" + NEXT_MAP_SHORTCUT.toString()
+ "</i></td></tr><tr><td>" + tr("Previous map") + "</td><td><i>"
+ PREV_MAP_SHORTCUT.toString() + "</i></td></tr></table></div>");
+ "</i></td></tr><tr><td>" + tr("Append file")
+ "</td><td><i>" + QKeySequence(MODIFIER).toString() + tr("Next/Previous")
+ "</i></td></tr><tr><td></td><td></td></tr><tr><td>" + tr("Next map")
+ "</td><td><i>" + NEXT_MAP_SHORTCUT.toString() + "</i></td></tr><tr><td>"
+ tr("Previous map") + "</td><td><i>" + PREV_MAP_SHORTCUT.toString()
+ "</i></td></tr><tr><td></td><td></td></tr><tr><td>" + tr("Zoom in")
+ "</td><td><i>" + QKeySequence(ZOOM_IN).toString()
+ "</i></td></tr><tr><td>" + tr("Zoom out") + "</td><td><i>"
+ QKeySequence(ZOOM_OUT).toString() + "</i></td></tr><tr><td>"
+ tr("Digital zoom") + "</td><td><i>" + QKeySequence(MODIFIER).toString()
+ tr("Zoom") + "</i></td></tr></table></div>");
msgBox.exec();
}
@ -608,17 +691,25 @@ void GUI::dataSources()
msgBox.setWindowTitle(tr("Data sources"));
msgBox.setText("<h3>" + tr("Data sources") + "</h3>");
msgBox.setInformativeText(
"<h4>" + tr("Map sources") + "</h4><p>"
+ tr("Map (tiles) source URLs are read on program startup from the "
"<h4>" + tr("Online maps") + "</h4><p>"
+ tr("Online map URLs are read on program startup from the "
"following file:")
+ "</p><p><code>" + USER_MAP_FILE + "</code></p><p>"
+ tr("The file format is one map entry per line, consisting of the map "
"name and tiles URL delimited by a TAB character. The tile X and Y "
"coordinates are replaced with $x and $y in the URL and the zoom "
"level is replaced with $z. An example map file could look like:")
+ "</p><p><code>Map1 http://tile.server.com/map/$z/$x/$y.png"
+ "</p><p><code>" + USER_MAP_FILE + "</code></p><p>"
+ tr("The file format is one map entry per line, consisting of the map "
"name and tiles URL delimited by a TAB character. The tile X and Y "
"coordinates are replaced with $x and $y in the URL and the zoom "
"level is replaced with $z. An example map file could look like:")
+ "</p><p><code>Map1 http://tile.server.com/map/$z/$x/$y.png"
"<br/>Map2 http://mapserver.org/map/$z-$x-$y</code></p>"
+ "<h4>" + tr("Offline maps") + "</h4><p>"
+ tr("Offline maps are loaded on program startup from the following "
"directory:")
+ "</p><p><code>" + USER_MAP_DIR + "</code></p><p>"
+ tr("The expected structure is one map/atlas in a separate subdirectory."
" Supported map formats are OziExplorer maps and TrekBuddy maps/atlases"
" (tared and non-tared).") + "</p>"
+ "<h4>" + tr("POIs") + "</h4><p>"
+ tr("To make GPXSee load a POI file automatically on startup, add "
"the file to the following directory:")
@ -631,7 +722,7 @@ void GUI::dataSources()
void GUI::openFile()
{
QStringList files = QFileDialog::getOpenFileNames(this, tr("Open file"),
QString(), fileFormats());
QString(), Data::formats());
QStringList list = files;
for (QStringList::Iterator it = list.begin(); it != list.end(); it++)
@ -697,7 +788,7 @@ bool GUI::loadFile(const QString &fileName)
if (data.tracks().count() == 1 && !data.routes().count())
_pathName = data.tracks().first()->name();
else if (data.routes().count() == 1 && !data.tracks().count())
_pathName = data.routes().first()->routeData().name();
_pathName = data.routes().first()->name();
} else
_pathName = QString();
@ -721,7 +812,7 @@ bool GUI::loadFile(const QString &fileName)
void GUI::openPOIFile()
{
QStringList files = QFileDialog::getOpenFileNames(this, tr("Open POI file"),
QString(), fileFormats());
QString(), Data::formats());
QStringList list = files;
for (QStringList::Iterator it = list.begin(); it != list.end(); it++)
@ -763,18 +854,10 @@ void GUI::closePOIFiles()
_poi->clear();
}
void GUI::printFile()
{
QPrinter printer(QPrinter::HighResolution);
QPrintDialog dialog(&printer, this);
if (dialog.exec() == QDialog::Accepted)
plot(&printer);
}
void GUI::openOptions()
{
Options options(_options);
bool reload = false;
OptionsDialog dialog(&options, this);
if (dialog.exec() != QDialog::Accepted)
@ -785,6 +868,8 @@ void GUI::openOptions()
for (int i = 0; i < _tabs.count(); i++)
_tabs.at(i)->setPalette(options.palette);
}
if (options.mapOpacity != _options.mapOpacity)
_pathView->setMapOpacity(options.mapOpacity);
if (options.trackWidth != _options.trackWidth)
_pathView->setTrackWidth(options.trackWidth);
if (options.routeWidth != _options.routeWidth)
@ -804,6 +889,39 @@ void GUI::openOptions()
_tabs.at(i)->setRenderHint(QPainter::Antialiasing,
options.graphAntiAliasing);
if (options.elevationFilter != _options.elevationFilter) {
Track::setElevationFilter(options.elevationFilter);
reload = true;
}
if (options.speedFilter != _options.speedFilter) {
Track::setSpeedFilter(options.speedFilter);
reload = true;
}
if (options.heartRateFilter != _options.heartRateFilter) {
Track::setHeartRateFilter(options.heartRateFilter);
reload = true;
}
if (options.cadenceFilter != _options.cadenceFilter) {
Track::setCadenceFilter(options.cadenceFilter);
reload = true;
}
if (options.powerFilter != _options.powerFilter) {
Track::setPowerFilter(options.powerFilter);
reload = true;
}
if (options.outlierEliminate != _options.outlierEliminate) {
Track::setOutlierElimination(options.outlierEliminate);
reload = true;
}
if (options.pauseSpeed != _options.pauseSpeed) {
Track::setPauseSpeed(options.pauseSpeed);
reload = true;
}
if (options.pauseInterval != _options.pauseInterval) {
Track::setPauseInterval(options.pauseInterval);
reload = true;
}
if (options.poiRadius != _options.poiRadius)
_poi->setRadius(options.poiRadius);
@ -812,10 +930,24 @@ void GUI::openOptions()
for (int i = 0; i < _tabs.count(); i++)
_tabs.at(i)->useOpenGL(options.useOpenGL);
}
if (options.pixmapCache != _options.pixmapCache)
QPixmapCache::setCacheLimit(options.pixmapCache * 1024);
if (reload)
reloadFile();
_options = options;
}
void GUI::printFile()
{
QPrinter printer(QPrinter::HighResolution);
QPrintDialog dialog(&printer, this);
if (dialog.exec() == QDialog::Accepted)
plot(&printer);
}
void GUI::exportFile()
{
ExportDialog dialog(&_export, this);
@ -826,6 +958,7 @@ void GUI::exportFile()
printer.setOutputFormat(QPrinter::PdfFormat);
printer.setCreator(QString(APP_NAME) + QString(" ")
+ QString(APP_VERSION));
printer.setResolution(_export.resolution);
printer.setOrientation(_export.orientation);
printer.setOutputFileName(_export.fileName);
printer.setPaperSize(_export.paperSize);
@ -875,28 +1008,29 @@ void GUI::plot(QPrinter *printer)
if (tm > 0 && _options.printMovingTime)
info.insert(tr("Moving time"), Format::timeSpan(tm));
ratio = p.paintEngine()->paintDevice()->logicalDpiX() / SCREEN_DPI;
qreal fsr = 1085.0 / (qMax(printer->width(), printer->height())
/ (qreal)printer->resolution());
ratio = p.paintEngine()->paintDevice()->logicalDpiX() / fsr;
if (info.isEmpty()) {
ih = 0;
mh = 0;
} else {
ih = info.contentSize().height() * ratio;
mh = ih / 2;
info.plot(&p, QRectF(0, 0, printer->width(), ih));
info.plot(&p, QRectF(0, 0, printer->width(), ih), ratio);
}
if (_graphTabWidget->isVisible() && !_options.separateGraphPage) {
qreal r = (((qreal)(printer)->width()) / (qreal)(printer->height()));
gh = (printer->width() > printer->height())
? 0.15 * r * (printer->height() - ih - 2*mh)
: 0.15 * (printer->height() - ih - 2*mh);
gh = qMax(gh, ratio * 150);
GraphTab *gt = static_cast<GraphTab*>(_graphTabWidget->currentWidget());
gt->plot(&p, QRectF(0, printer->height() - gh, printer->width(), gh));
gt->plot(&p, QRectF(0, printer->height() - gh, printer->width(), gh),
ratio);
} else
gh = 0;
_pathView->plot(&p, QRectF(0, ih + mh, printer->width(), printer->height()
- (ih + 2*mh + gh)));
- (ih + 2*mh + gh)), _options.hiresPrint);
if (_graphTabWidget->isVisible() && _options.separateGraphPage) {
printer->newPage();
@ -913,7 +1047,8 @@ void GUI::plot(QPrinter *printer)
qreal y = 0;
for (int i = 0; i < _tabs.size(); i++) {
if (_tabs.at(i)->count()) {
_tabs.at(i)->plot(&p, QRectF(0, y, printer->width(), gh));
_tabs.at(i)->plot(&p, QRectF(0, y, printer->width(), gh),
ratio);
y += gh + sp;
}
}
@ -987,14 +1122,6 @@ void GUI::closeAll()
updatePathView();
}
void GUI::showMap(bool show)
{
if (show)
_pathView->setMap(_currentMap);
else
_pathView->setMap(0);
}
void GUI::showGraphs(bool show)
{
_graphTabWidget->setHidden(!show);
@ -1070,9 +1197,38 @@ void GUI::showGraphGrids(bool show)
_tabs.at(i)->showGrid(show);
}
void GUI::loadMap()
{
QString fileName = QFileDialog::getOpenFileName(this, tr("Open map file"),
QString(), MapList::formats());
if (fileName.isEmpty())
return;
int count = _ml->maps().count();
if (_ml->loadFile(fileName)) {
for (int i = count; i < _ml->maps().count(); i++) {
QAction *a = new QAction(_ml->maps().at(i)->name(), this);
a->setCheckable(true);
a->setActionGroup(_mapsActionGroup);
_mapsSignalMapper->setMapping(a, i);
connect(a, SIGNAL(triggered()), _mapsSignalMapper, SLOT(map()));
_mapActions.append(a);
_mapMenu->insertAction(_mapsEnd, a);
}
_showMapAction->setEnabled(true);
_clearMapCacheAction->setEnabled(true);
_mapActions.last()->activate(QAction::Trigger);
} else {
QString error = tr("Error loading map:") + "\n\n"
+ fileName + "\n\n" + _ml->errorString();
QMessageBox::critical(this, APP_NAME, error);
}
}
void GUI::clearMapCache()
{
_currentMap->clearCache();
_map->clearCache();
_pathView->redraw();
}
@ -1097,7 +1253,8 @@ void GUI::updateStatusBarInfo()
_timeLabel->setToolTip(Format::timeSpan(time()));
} else {
_timeLabel->setText(Format::timeSpan(time()));
_timeLabel->setToolTip(Format::timeSpan(movingTime()));
_timeLabel->setToolTip(Format::timeSpan(movingTime())
+ "<sub>M</sub>");
}
} else {
_timeLabel->clear();
@ -1115,26 +1272,27 @@ void GUI::updateWindowTitle()
void GUI::mapChanged(int index)
{
_currentMap = _maps.at(index);
if (_showMapAction->isChecked())
_pathView->setMap(_currentMap);
_map = _ml->maps().at(index);
_pathView->setMap(_map);
}
void GUI::nextMap()
{
if (_maps.count() < 2)
if (_ml->maps().count() < 2)
return;
int next = (_maps.indexOf(_currentMap) + 1) % _maps.count();
int next = (_ml->maps().indexOf(_map) + 1) % _ml->maps().count();
_mapActions.at(next)->setChecked(true);
mapChanged(next);
}
void GUI::prevMap()
{
if (_maps.count() < 2)
if (_ml->maps().count() < 2)
return;
int prev = (_maps.indexOf(_currentMap) + _maps.count() - 1) % _maps.count();
int prev = (_ml->maps().indexOf(_map) + _ml->maps().count() - 1)
% _ml->maps().count();
_mapActions.at(prev)->setChecked(true);
mapChanged(prev);
}
@ -1302,6 +1460,7 @@ void GUI::keyPressEvent(QKeyEvent *event)
if (_fullscreenAction->isChecked()) {
_fullscreenAction->setChecked(false);
showFullscreen(false);
return;
}
break;
}
@ -1310,7 +1469,10 @@ void GUI::keyPressEvent(QKeyEvent *event)
if (!(event->modifiers() & MODIFIER))
closeFiles();
openFile(file);
return;
}
QMainWindow::keyPressEvent(event);
}
void GUI::closeEvent(QCloseEvent *event)
@ -1368,8 +1530,7 @@ void GUI::writeSettings()
settings.endGroup();
settings.beginGroup(MAP_SETTINGS_GROUP);
if (_currentMap)
settings.setValue(CURRENT_MAP_SETTING, _currentMap->name());
settings.setValue(CURRENT_MAP_SETTING, _map->name());
if (_showMapAction->isChecked() != SHOW_MAP_DEFAULT)
settings.setValue(SHOW_MAP_SETTING, _showMapAction->isChecked());
settings.endGroup();
@ -1423,6 +1584,8 @@ void GUI::writeSettings()
settings.beginGroup(EXPORT_SETTINGS_GROUP);
if (_export.orientation != PAPER_ORIENTATION_DEFAULT)
settings.setValue(PAPER_ORIENTATION_SETTING, _export.orientation);
if (_export.resolution != RESOLUTION_DEFAULT)
settings.setValue(RESOLUTION_SETTING, _export.resolution);
if (_export.paperSize != PAPER_SIZE_DEFAULT)
settings.setValue(PAPER_SIZE_SETTING, _export.paperSize);
if (_export.margins.left() != MARGIN_LEFT_DEFAULT)
@ -1442,6 +1605,8 @@ void GUI::writeSettings()
settings.setValue(PALETTE_COLOR_SETTING, _options.palette.color());
if (_options.palette.shift() != PALETTE_SHIFT_DEFAULT)
settings.setValue(PALETTE_SHIFT_SETTING, _options.palette.shift());
if (_options.mapOpacity != MAP_OPACITY_DEFAULT)
settings.setValue(MAP_OPACITY_SETTING, _options.mapOpacity);
if (_options.trackWidth != TRACK_WIDTH_DEFAULT)
settings.setValue(TRACK_WIDTH_SETTING, _options.trackWidth);
if (_options.routeWidth != ROUTE_WIDTH_DEFAULT)
@ -1456,10 +1621,30 @@ void GUI::writeSettings()
settings.setValue(PATH_AA_SETTING, _options.pathAntiAliasing);
if (_options.graphAntiAliasing != GRAPH_AA_DEFAULT)
settings.setValue(GRAPH_AA_SETTING, _options.graphAntiAliasing);
if (_options.elevationFilter != ELEVATION_FILTER_DEFAULT)
settings.setValue(ELEVATION_FILTER_SETTING, _options.elevationFilter);
if (_options.speedFilter != SPEED_FILTER_DEFAULT)
settings.setValue(SPEED_FILTER_SETTING, _options.speedFilter);
if (_options.heartRateFilter != HEARTRATE_FILTER_DEFAULT)
settings.setValue(HEARTRATE_FILTER_SETTING, _options.heartRateFilter);
if (_options.cadenceFilter != CADENCE_FILTER_DEFAULT)
settings.setValue(CADENCE_FILTER_SETTING, _options.cadenceFilter);
if (_options.powerFilter != POWER_FILTER_DEFAULT)
settings.setValue(POWER_FILTER_SETTING, _options.powerFilter);
if (_options.outlierEliminate != OUTLIER_ELIMINATE_DEFAULT)
settings.setValue(OUTLIER_ELIMINATE_SETTING, _options.outlierEliminate);
if (_options.pauseSpeed != PAUSE_SPEED_DEFAULT)
settings.setValue(PAUSE_SPEED_SETTING, _options.pauseSpeed);
if (_options.pauseInterval != PAUSE_INTERVAL_DEFAULT)
settings.setValue(PAUSE_INTERVAL_SETTING, _options.pauseInterval);
if (_options.poiRadius != POI_RADIUS_DEFAULT)
settings.setValue(POI_RADIUS_SETTING, _options.poiRadius);
if (_options.useOpenGL != USE_OPENGL_DEFAULT)
settings.setValue(USE_OPENGL_SETTING, _options.useOpenGL);
if (_options.pixmapCache != PIXMAP_CACHE_DEFAULT)
settings.setValue(PIXMAP_CACHE_SETTING, _options.pixmapCache);
if (_options.hiresPrint != HIRES_PRINT_DEFAULT)
settings.setValue(HIRES_PRINT_SETTING, _options.hiresPrint);
if (_options.printName != PRINT_NAME_DEFAULT)
settings.setValue(PRINT_NAME_SETTING, _options.printName);
if (_options.printDate != PRINT_DATE_DEFAULT)
@ -1512,14 +1697,12 @@ void GUI::readSettings()
settings.beginGroup(MAP_SETTINGS_GROUP);
if (settings.value(SHOW_MAP_SETTING, SHOW_MAP_DEFAULT).toBool())
_showMapAction->setChecked(true);
if (_maps.count()) {
if (_ml->maps().count()) {
int index = mapIndex(settings.value(CURRENT_MAP_SETTING).toString());
_mapActions.at(index)->setChecked(true);
_currentMap = _maps.at(index);
if (_showMapAction->isChecked())
_pathView->setMap(_currentMap);
} else
_currentMap = 0;
_map = _ml->maps().at(index);
_pathView->setMap(_map);
}
settings.endGroup();
settings.beginGroup(GRAPH_SETTINGS_GROUP);
@ -1601,6 +1784,8 @@ void GUI::readSettings()
settings.beginGroup(EXPORT_SETTINGS_GROUP);
_export.orientation = (QPrinter::Orientation) settings.value(
PAPER_ORIENTATION_SETTING, PAPER_ORIENTATION_DEFAULT).toInt();
_export.resolution = settings.value(RESOLUTION_SETTING, RESOLUTION_DEFAULT)
.toInt();
_export.paperSize = (QPrinter::PaperSize) settings.value(PAPER_SIZE_SETTING,
PAPER_SIZE_DEFAULT).toInt();
qreal ml = settings.value(MARGIN_LEFT_SETTING, MARGIN_LEFT_DEFAULT)
@ -1621,6 +1806,8 @@ void GUI::readSettings()
qreal ps = settings.value(PALETTE_SHIFT_SETTING, PALETTE_SHIFT_DEFAULT)
.toDouble();
_options.palette = Palette(pc, ps);
_options.mapOpacity = settings.value(MAP_OPACITY_SETTING,
MAP_OPACITY_DEFAULT).toInt();
_options.trackWidth = settings.value(TRACK_WIDTH_SETTING,
TRACK_WIDTH_DEFAULT).toInt();
_options.routeWidth = settings.value(ROUTE_WIDTH_SETTING,
@ -1635,10 +1822,30 @@ void GUI::readSettings()
GRAPH_WIDTH_DEFAULT).toInt();
_options.graphAntiAliasing = settings.value(GRAPH_AA_SETTING,
GRAPH_AA_DEFAULT).toBool();
_options.elevationFilter = settings.value(ELEVATION_FILTER_SETTING,
ELEVATION_FILTER_DEFAULT).toInt();
_options.speedFilter = settings.value(SPEED_FILTER_SETTING,
SPEED_FILTER_DEFAULT).toInt();
_options.heartRateFilter = settings.value(HEARTRATE_FILTER_SETTING,
HEARTRATE_FILTER_DEFAULT).toInt();
_options.cadenceFilter = settings.value(CADENCE_FILTER_SETTING,
CADENCE_FILTER_DEFAULT).toInt();
_options.powerFilter = settings.value(POWER_FILTER_SETTING,
POWER_FILTER_DEFAULT).toInt();
_options.outlierEliminate = settings.value(OUTLIER_ELIMINATE_SETTING,
OUTLIER_ELIMINATE_DEFAULT).toBool();
_options.pauseSpeed = settings.value(PAUSE_SPEED_SETTING,
PAUSE_SPEED_DEFAULT).toFloat();
_options.pauseInterval = settings.value(PAUSE_INTERVAL_SETTING,
PAUSE_INTERVAL_DEFAULT).toInt();
_options.poiRadius = settings.value(POI_RADIUS_SETTING, POI_RADIUS_DEFAULT)
.toInt();
_options.useOpenGL = settings.value(USE_OPENGL_SETTING, USE_OPENGL_DEFAULT)
.toBool();
_options.pixmapCache = settings.value(PIXMAP_CACHE_SETTING,
PIXMAP_CACHE_DEFAULT).toInt();
_options.hiresPrint = settings.value(HIRES_PRINT_SETTING,
HIRES_PRINT_DEFAULT).toBool();
_options.printName = settings.value(PRINT_NAME_SETTING, PRINT_NAME_DEFAULT)
.toBool();
_options.printDate = settings.value(PRINT_DATE_SETTING, PRINT_DATE_DEFAULT)
@ -1655,6 +1862,7 @@ void GUI::readSettings()
SEPARATE_GRAPH_PAGE_DEFAULT).toBool();
_pathView->setPalette(_options.palette);
_pathView->setMapOpacity(_options.mapOpacity);
_pathView->setTrackWidth(_options.trackWidth);
_pathView->setRouteWidth(_options.routeWidth);
_pathView->setTrackStyle(_options.trackStyle);
@ -1672,15 +1880,26 @@ void GUI::readSettings()
_tabs.at(i)->useOpenGL(true);
}
Track::setElevationFilter(_options.elevationFilter);
Track::setSpeedFilter(_options.speedFilter);
Track::setHeartRateFilter(_options.heartRateFilter);
Track::setCadenceFilter(_options.cadenceFilter);
Track::setPowerFilter(_options.powerFilter);
Track::setOutlierElimination(_options.outlierEliminate);
Track::setPauseSpeed(_options.pauseSpeed);
Track::setPauseInterval(_options.pauseInterval);
_poi->setRadius(_options.poiRadius);
QPixmapCache::setCacheLimit(_options.pixmapCache * 1024);
settings.endGroup();
}
int GUI::mapIndex(const QString &name)
{
for (int i = 0; i < _maps.count(); i++)
if (_maps.at(i)->name() == name)
for (int i = 0; i < _ml->maps().count(); i++)
if (_ml->maps().at(i)->name() == name)
return i;
return 0;

View File

@ -13,6 +13,7 @@
#include "exportdialog.h"
#include "optionsdialog.h"
class QMenu;
class QToolBar;
class QTabWidget;
@ -25,13 +26,14 @@ class FileBrowser;
class GraphTab;
class PathView;
class Map;
class MapList;
class GUI : public QMainWindow
{
Q_OBJECT
public:
GUI(QWidget *parent = 0);
GUI();
~GUI();
bool openFile(const QString &fileName);
@ -47,13 +49,13 @@ private slots:
void reloadFile();
void openPOIFile();
void closePOIFiles();
void showMap(bool show);
void showGraphs(bool show);
void showGraphGrids(bool show);
void showToolbars(bool show);
void showFullscreen(bool show);
void showTracks(bool show);
void showRoutes(bool show);
void loadMap();
void clearMapCache();
void nextMap();
void prevMap();
@ -80,6 +82,7 @@ private slots:
private:
typedef QPair<QDate, QDate> DateRange;
void loadDatums();
void loadMaps();
void loadPOIs();
void closeFiles();
@ -118,8 +121,6 @@ private:
void readSettings();
void writeSettings();
const QString fileFormats() const;
void keyPressEvent(QKeyEvent *event);
void closeEvent(QCloseEvent *event);
void dragEnterEvent(QDragEnterEvent *event);
@ -129,9 +130,11 @@ private:
QToolBar *_showToolBar;
QToolBar *_navigationToolBar;
QMenu *_poiFilesMenu;
QMenu *_mapMenu;
QActionGroup *_fileActionGroup;
QActionGroup *_navigationActionGroup;
QActionGroup *_mapsActionGroup;
QAction *_exitAction;
QAction *_keysAction;
QAction *_dataSourcesAction;
@ -149,6 +152,7 @@ private:
QAction *_showPOILabelsAction;
QAction *_showMapAction;
QAction *_fullscreenAction;
QAction *_loadMapAction;
QAction *_clearMapCacheAction;
QAction *_showGraphsAction;
QAction *_showGraphGridAction;
@ -171,10 +175,12 @@ private:
QAction *_showWaypointLabelsAction;
QAction *_showRouteWaypointsAction;
QAction *_openOptionsAction;
QAction *_mapsEnd;
QList<QAction*> _mapActions;
QList<QAction*> _poiFilesActions;
QSignalMapper *_poiFilesSM;
QSignalMapper *_poiFilesSignalMapper;
QSignalMapper *_mapsSignalMapper;
QLabel *_fileNameLabel;
QLabel *_distanceLabel;
@ -185,12 +191,12 @@ private:
QList<GraphTab*> _tabs;
POI *_poi;
QList<Map*> _maps;
MapList *_ml;
FileBrowser *_browser;
QList<QString> _files;
Map *_currentMap;
Map *_map;
int _trackCount;
int _routeCount;
int _waypointCount;

View File

@ -10,7 +10,7 @@
#define CLOSE_FILE_ICON ":/icons/dialog-close.png"
#define SHOW_POI_ICON ":/icons/flag.png"
#define SHOW_MAP_ICON ":/icons/applications-internet.png"
#define SHOW_GRAPHS_ICON ":/icons/office-chart-line-stacked.png"
#define SHOW_GRAPHS_ICON ":/icons/office-chart-line.png"
#define QUIT_ICON ":/icons/application-exit.png"
#define RELOAD_FILE_ICON ":/icons/view-refresh.png"
#define NEXT_FILE_ICON ":/icons/arrow-right.png"
@ -24,5 +24,6 @@
#define POI_ICON ":/icons/flag_48.png"
#define SYSTEM_ICON ":/icons/system-run.png"
#define PRINT_EXPORT_ICON ":/icons/document-print-preview.png"
#define DATA_ICON ":/icons/view-filter.png"
#endif /* ICONS_H */

View File

@ -120,7 +120,7 @@ bool IGCParser::readHRecord(const char *line, int len)
return true;
}
bool IGCParser::readBRecord(const char *line, int len)
bool IGCParser::readBRecord(TrackData &track, const char *line, int len)
{
qreal lat, lon, ele;
QTime time;
@ -156,12 +156,12 @@ bool IGCParser::readBRecord(const char *line, int len)
Trackpoint t(Coordinates(lon, lat));
t.setTimestamp(QDateTime(_date, _time, Qt::UTC));
t.setElevation(ele);
_tracks.last().append(t);
track.append(t);
return true;
}
bool IGCParser::readCRecord(const char *line, int len)
bool IGCParser::readCRecord(RouteData &route, const char *line, int len)
{
qreal lat, lon;
@ -183,14 +183,16 @@ bool IGCParser::readCRecord(const char *line, int len)
Waypoint w(Coordinates(lon, lat));
w.setName(QString(ba.trimmed()));
_routes.last().append(w);
route.append(w);
}
return true;
}
bool IGCParser::loadFile(QFile *file)
bool IGCParser::parse(QFile *file, QList<TrackData> &tracks,
QList<RouteData> &routes, QList<Waypoint> &waypoints)
{
Q_UNUSED(waypoints);
qint64 len;
char line[76 + 2 + 1 + 1];
bool route = false, track = false;
@ -221,11 +223,11 @@ bool IGCParser::loadFile(QFile *file)
return false;
} else if (line[0] == 'C') {
if (route) {
if (!readCRecord(line, len))
if (!readCRecord(routes.last() ,line, len))
return false;
} else {
route = true;
_routes.append(RouteData());
routes.append(RouteData());
}
} else if (line[0] == 'B') {
if (_date.isNull()) {
@ -233,11 +235,11 @@ bool IGCParser::loadFile(QFile *file)
return false;
}
if (!track) {
_tracks.append(TrackData());
tracks.append(TrackData());
_time = QTime(0, 0);
track = true;
}
if (!readBRecord(line, len))
if (!readBRecord(tracks.last(), line, len))
return false;
}
}

View File

@ -9,19 +9,18 @@
class IGCParser : public Parser
{
public:
IGCParser(QList<TrackData> &tracks, QList<RouteData> &routes,
QList<Waypoint> &waypoints) : Parser(tracks, routes, waypoints)
{_errorLine = 0;}
IGCParser() : _errorLine(0) {}
~IGCParser() {}
bool loadFile(QFile *file);
bool parse(QFile *file, QList<TrackData> &tracks,
QList<RouteData> &routes, QList<Waypoint> &waypoints);
QString errorString() const {return _errorString;}
int errorLine() const {return _errorLine;}
private:
bool readHRecord(const char *line, int len);
bool readBRecord(const char *line, int len);
bool readCRecord(const char *line, int len);
bool readBRecord(TrackData &track, const char *line, int len);
bool readCRecord(RouteData &route, const char *line, int len);
int _errorLine;
QString _errorString;

View File

@ -10,6 +10,9 @@
#define LAST_KEY Qt::Key_End
#define MODIFIER Qt::ShiftModifier
#define ZOOM_IN QKeySequence::ZoomIn
#define ZOOM_OUT QKeySequence::ZoomOut
#define QUIT_SHORTCUT QKeySequence(QKeySequence::Quit)
#define OPEN_SHORTCUT QKeySequence(QKeySequence::Open)
#define CLOSE_SHORTCUT QKeySequence(QKeySequence::Close)
@ -22,6 +25,7 @@
#define SHOW_GRAPHS_SHORTCUT QKeySequence(Qt::CTRL + Qt::Key_G)
#define DISTANCE_GRAPH_SHORTCUT QKeySequence(Qt::CTRL + Qt::Key_D)
#define TIME_GRAPH_SHORTCUT QKeySequence(Qt::CTRL + Qt::Key_T)
#ifdef Q_OS_MAC
#define FULLSCREEN_SHORTCUT QKeySequence(Qt::META + Qt::CTRL + Qt::Key_F)
#else // Q_OS_MAC

View File

@ -251,20 +251,21 @@ void KMLParser::track(TrackData &track)
_reader.raiseError(mismatchError);
}
void KMLParser::multiGeometry(const QString &name, const QString &desc,
void KMLParser::multiGeometry(QList<TrackData> &tracks,
QList<Waypoint> &waypoints, const QString &name, const QString &desc,
const QDateTime timestamp)
{
while (_reader.readNextStartElement()) {
if (_reader.name() == "Point") {
_waypoints.append(Waypoint());
Waypoint &w = _waypoints.last();
waypoints.append(Waypoint());
Waypoint &w = waypoints.last();
w.setName(name);
w.setDescription(desc);
w.setTimestamp(timestamp);
point(w);
} else if (_reader.name() == "LineString") {
_tracks.append(TrackData());
TrackData &t = _tracks.last();
tracks.append(TrackData());
TrackData &t = tracks.last();
t.setName(name);
t.setDescription(desc);
lineString(t);
@ -273,7 +274,7 @@ void KMLParser::multiGeometry(const QString &name, const QString &desc,
}
}
void KMLParser::placemark()
void KMLParser::placemark(QList<TrackData> &tracks, QList<Waypoint> &waypoints)
{
QString name, desc;
QDateTime timestamp;
@ -286,23 +287,24 @@ void KMLParser::placemark()
else if (_reader.name() == "TimeStamp")
timestamp = timeStamp();
else if (_reader.name() == "MultiGeometry")
multiGeometry(name, desc, timestamp);
multiGeometry(tracks, waypoints, name, desc, timestamp);
else if (_reader.name() == "Point") {
_waypoints.append(Waypoint());
Waypoint &w = _waypoints.last();
waypoints.append(Waypoint());
Waypoint &w = waypoints.last();
w.setName(name);
w.setDescription(desc);
w.setTimestamp(timestamp);
point(w);
} else if (_reader.name() == "LineString") {
_tracks.append(TrackData());
TrackData &t = _tracks.last();
} else if (_reader.name() == "LineString"
|| _reader.name() == "LinearRing") {
tracks.append(TrackData());
TrackData &t = tracks.last();
t.setName(name);
t.setDescription(desc);
lineString(t);
} else if (_reader.name() == "Track") {
_tracks.append(TrackData());
TrackData &t = _tracks.last();
tracks.append(TrackData());
TrackData &t = tracks.last();
t.setName(name);
t.setDescription(desc);
track(t);
@ -311,58 +313,56 @@ void KMLParser::placemark()
}
}
void KMLParser::folder()
void KMLParser::folder(QList<TrackData> &tracks, QList<Waypoint> &waypoints)
{
while (_reader.readNextStartElement()) {
if (_reader.name() == "Placemark")
placemark();
placemark(tracks, waypoints);
else if (_reader.name() == "Folder")
folder();
folder(tracks, waypoints);
else
_reader.skipCurrentElement();
}
}
void KMLParser::document()
void KMLParser::document(QList<TrackData> &tracks, QList<Waypoint> &waypoints)
{
while (_reader.readNextStartElement()) {
if (_reader.name() == "Placemark")
placemark();
placemark(tracks, waypoints);
else if (_reader.name() == "Folder")
folder();
folder(tracks, waypoints);
else
_reader.skipCurrentElement();
}
}
void KMLParser::kml()
void KMLParser::kml(QList<TrackData> &tracks, QList<Waypoint> &waypoints)
{
while (_reader.readNextStartElement()) {
if (_reader.name() == "Document")
document();
document(tracks, waypoints);
else if (_reader.name() == "Placemark")
placemark();
placemark(tracks, waypoints);
else
_reader.skipCurrentElement();
}
}
bool KMLParser::parse()
bool KMLParser::parse(QFile *file, QList<TrackData> &tracks,
QList<RouteData> &routes, QList<Waypoint> &waypoints)
{
Q_UNUSED(routes);
_reader.clear();
_reader.setDevice(file);
if (_reader.readNextStartElement()) {
if (_reader.name() == "kml")
kml();
kml(tracks, waypoints);
else
_reader.raiseError("Not a KML file");
}
return !_reader.error();
}
bool KMLParser::loadFile(QFile *file)
{
_reader.clear();
_reader.setDevice(file);
return parse();
}

View File

@ -8,22 +8,20 @@
class KMLParser : public Parser
{
public:
KMLParser(QList<TrackData> &tracks, QList<RouteData> &routes,
QList<Waypoint> &waypoints) : Parser(tracks, routes, waypoints) {}
~KMLParser() {}
bool loadFile(QFile *file);
bool parse(QFile *file, QList<TrackData> &tracks,
QList<RouteData> &routes, QList<Waypoint> &waypoints);
QString errorString() const {return _reader.errorString();}
int errorLine() const {return _reader.lineNumber();}
private:
bool parse();
void kml();
void document();
void folder();
void placemark();
void multiGeometry(const QString &name, const QString &desc,
const QDateTime timestamp);
void kml(QList<TrackData> &tracks, QList<Waypoint> &waypoints);
void document(QList<TrackData> &tracks, QList<Waypoint> &waypoints);
void folder(QList<TrackData> &tracks, QList<Waypoint> &waypoints);
void placemark(QList<TrackData> &tracks, QList<Waypoint> &waypoints);
void multiGeometry(QList<TrackData> &tracks, QList<Waypoint> &waypoints,
const QString &name, const QString &desc, const QDateTime timestamp);
void track(TrackData &track);
void lineString(TrackData &track);
void point(Waypoint &waypoint);

81
src/lambertconic.cpp Normal file
View File

@ -0,0 +1,81 @@
#include <cmath>
#include "rd.h"
#include "lambertconic.h"
#ifndef M_PI_2
#define M_PI_2 1.57079632679489661923
#endif // M_PI_2
#ifndef M_PI_4
#define M_PI_4 0.78539816339744830962
#endif // M_PI_4
static double q(const Ellipsoid &el, double b)
{
double e = sqrt(el.flattening() * (2. - el.flattening()));
double esb = e * sin(b);
return log(tan(M_PI_4 + b / 2.) * pow((1. - esb) / (1. + esb), e / 2.));
}
static double iq(const Ellipsoid &el, double q)
{
double e = sqrt(el.flattening() * (2. - el.flattening()));
double b0 = 0.;
double b = 2. * atan(exp(q)) - M_PI_2;
do {
b0 = b;
double esb = e * sin(b);
b = 2. * atan(exp(q) * pow((1. - esb) / (1. + esb), -e / 2.)) - M_PI_2;
} while (fabs(b - b0) > 1e-10);
return b;
}
static double nradius(const Ellipsoid &el, double phi)
{
double sin_phi = sin(phi);
return (el.radius() / sqrt(1. - (el.flattening() * (2. - el.flattening()))
* sin_phi * sin_phi));
}
LambertConic::LambertConic(const Ellipsoid &ellipsoid, double standardParallel1,
double standardParallel2, double latitudeOrigin, double longitudeOrigin,
double scale, double falseEasting, double falseNorthing) : _e(ellipsoid)
{
_cm = longitudeOrigin;
_fe = falseEasting;
_fn = falseNorthing;
double sp1 = deg2rad(standardParallel1);
double sp2 = deg2rad(standardParallel2);
double N1 = nradius(_e, sp1);
double N2 = nradius(_e, sp2);
_q0 = q(_e, deg2rad(latitudeOrigin));
double q1 = q(_e, sp1);
double q2 = q(_e, sp2);
_n = log((N1 * cos(sp1)) / (N2 * cos(sp2))) / (q2 - q1);
double R1 = N1 * cos(sp1) / _n;
_R0 = scale * R1 * exp(_n * (q1 - _q0));
}
QPointF LambertConic::ll2xy(const Coordinates &c) const
{
double dl = _n * (deg2rad(c.lon()) - deg2rad(_cm));
double R = _R0 * exp(_n * (_q0 - q(_e, deg2rad(c.lat()))));
return QPointF(_fe + R * sin(dl), _fn + _R0 - R * cos(dl));
}
Coordinates LambertConic::xy2ll(const QPointF &p) const
{
double dl = atan((p.x() - _fe) / (_fn + _R0 - p.y()));
double dx = p.x() - _fe;
double dy = p.y() - _fn - _R0;
double R = sqrt(dx * dx + dy * dy);
double q = _q0 - log(fabs(R / _R0)) / _n;
return Coordinates(rad2deg(deg2rad(_cm) + dl / _n), rad2deg(iq(_e, q)));
}

29
src/lambertconic.h Normal file
View File

@ -0,0 +1,29 @@
#ifndef LAMBERTCONIC_H
#define LAMBERTCONIC_H
#include "ellipsoid.h"
#include "projection.h"
class LambertConic : public Projection
{
public:
LambertConic(const Ellipsoid &ellipsoid, double standardParallel1,
double standardParallel2, double latitudeOrigin, double longitudeOrigin,
double scale, double falseEasting, double falseNorthing);
virtual QPointF ll2xy(const Coordinates &c) const;
virtual Coordinates xy2ll(const QPointF &p) const;
private:
Ellipsoid _e;
double _cm;
double _fe;
double _fn;
double _q0;
double _R0;
double _n;
};
#endif // LAMBERTCONIC_H

15
src/latlon.h Normal file
View File

@ -0,0 +1,15 @@
#ifndef LATLON_H
#define LATLON_H
#include "projection.h"
class LatLon : public Projection
{
public:
virtual QPointF ll2xy(const Coordinates &c) const
{return QPointF(c.lon(), c.lat());}
virtual Coordinates xy2ll(const QPointF &p) const
{return Coordinates(p.x(), p.y());}
};
#endif // LATLON_H

View File

@ -1,136 +0,0 @@
#include <QFileInfo>
#include <QDir>
#include "downloader.h"
#include "config.h"
#include "map.h"
Map::Map(const QString &name, const QString &url, Downloader *downloader,
QObject *parent) : QObject(parent)
{
_name = name;
_url = url;
_downloader = downloader;
connect(_downloader, SIGNAL(finished()), this, SLOT(emitLoaded()));
QString path = TILES_DIR + QString("/") + _name;
if (!QDir().mkpath(path))
fprintf(stderr, "Error creating tiles dir: %s\n", qPrintable(path));
}
void Map::emitLoaded()
{
emit loaded();
}
void Map::loadTiles(QList<Tile> &list, bool block)
{
if (block)
loadTilesSync(list);
else
loadTilesAsync(list);
}
void Map::loadTilesAsync(QList<Tile> &list)
{
QList<Download> dl;
for (int i = 0; i < list.size(); i++) {
Tile &t = list[i];
QString file = tileFile(t);
QFileInfo fi(file);
if (!fi.exists()) {
fillTile(t);
dl.append(Download(tileUrl(t), file));
} else
loadTileFile(t, file);
}
if (!dl.empty())
_downloader->get(dl);
}
void Map::loadTilesSync(QList<Tile> &list)
{
QList<Download> dl;
for (int i = 0; i < list.size(); i++) {
Tile &t = list[i];
QString file = tileFile(t);
QFileInfo fi(file);
if (!fi.exists())
dl.append(Download(tileUrl(t), file));
else
loadTileFile(t, file);
}
if (dl.empty())
return;
QEventLoop wait;
connect(_downloader, SIGNAL(finished()), &wait, SLOT(quit()));
if (_downloader->get(dl))
wait.exec();
for (int i = 0; i < list.size(); i++) {
Tile &t = list[i];
if (t.pixmap().isNull()) {
QString file = tileFile(t);
QFileInfo fi(file);
if (!(fi.exists() && loadTileFile(t, file)))
fillTile(t);
}
}
}
void Map::fillTile(Tile &tile)
{
tile.pixmap() = QPixmap(Tile::size(), Tile::size());
tile.pixmap().fill();
}
bool Map::loadTileFile(Tile &tile, const QString &file)
{
if (!tile.pixmap().load(file)) {
fprintf(stderr, "%s: error loading tile file\n", qPrintable(file));
return false;
}
return true;
}
QString Map::tileUrl(const Tile &tile)
{
QString url(_url);
url.replace("$z", QString::number(tile.zoom()));
url.replace("$x", QString::number(tile.xy().x()));
url.replace("$y", QString::number(tile.xy().y()));
return url;
}
QString Map::tileFile(const Tile &tile)
{
QString file = TILES_DIR + QString("/%1/%2-%3-%4").arg(_name)
.arg(tile.zoom()).arg(tile.xy().x()).arg(tile.xy().y());
return file;
}
void Map::clearCache()
{
QString path = TILES_DIR + QString("/") + _name;
QDir dir = QDir(path);
QStringList list = dir.entryList();
for (int i = 0; i < list.count(); i++)
dir.remove(list.at(i));
}

View File

@ -1,41 +1,44 @@
#ifndef MAP_H
#define MAP_H
#include "tile.h"
#include <QObject>
#include <QString>
#include <QRectF>
class Downloader;
class QPainter;
class Coordinates;
class RectC;
class Map : public QObject
{
Q_OBJECT
public:
Map(const QString &name, const QString &url, Downloader *downloader,
QObject *parent = 0);
Map(QObject *parent = 0) : QObject(parent) {}
const QString &name() const {return _name;}
void loadTiles(QList<Tile> &list, bool block);
void clearCache();
virtual const QString &name() const = 0;
virtual QRectF bounds() const = 0;
virtual qreal resolution(const QPointF &p) const = 0;
virtual qreal zoom() const = 0;
virtual qreal zoomFit(const QSize &size, const RectC &br) = 0;
virtual qreal zoomFit(qreal resolution, const Coordinates &c) = 0;
virtual qreal zoomIn() = 0;
virtual qreal zoomOut() = 0;
virtual QPointF ll2xy(const Coordinates &c) = 0;
virtual Coordinates xy2ll(const QPointF &p) = 0;
virtual void draw(QPainter *painter, const QRectF &rect) = 0;
virtual void setBlockingMode(bool block) {Q_UNUSED(block);}
virtual void clearCache() {}
virtual void load() {}
virtual void unload() {}
signals:
void loaded();
private slots:
void emitLoaded();
private:
QString tileUrl(const Tile &tile);
QString tileFile(const Tile &tile);
bool loadTileFile(Tile &tile, const QString &file);
void fillTile(Tile &tile);
void loadTilesAsync(QList<Tile> &list);
void loadTilesSync(QList<Tile> &list);
Downloader *_downloader;
QString _name;
QString _url;
};
#endif // MAP_H

View File

@ -1,41 +1,136 @@
#include <QFile>
#include <QFileInfo>
#include "map.h"
#include <QDir>
#include "atlas.h"
#include "offlinemap.h"
#include "onlinemap.h"
#include "maplist.h"
QList<Map*> MapList::load(const QString &fileName, QObject *parent)
Map *MapList::loadListEntry(const QByteArray &line)
{
QList<Map*> mapList;
QFileInfo fi(fileName);
QList<QByteArray> list = line.split('\t');
if (list.size() != 2)
return 0;
if (!fi.exists())
return mapList;
QByteArray ba1 = list[0].trimmed();
QByteArray ba2 = list[1].trimmed();
if (ba1.isEmpty() || ba2.isEmpty())
return 0;
QFile file(fileName);
return new OnlineMap(QString::fromUtf8(ba1.data(), ba1.size()),
QString::fromLatin1(ba2.data(), ba2.size()), this);
}
bool MapList::loadList(const QString &path)
{
QFile file(path);
QList<Map*> maps;
if (!file.open(QFile::ReadOnly | QFile::Text)) {
fprintf(stderr, "Error opening map list file: %s: %s\n",
qPrintable(fileName), qPrintable(file.errorString()));
return mapList;
_errorString = file.errorString();
return false;
}
int ln = 0;
while (!file.atEnd()) {
ln++;
QByteArray line = file.readLine();
QList<QByteArray> list = line.split('\t');
if (list.size() != 2) {
fprintf(stderr, "Invalid map list entry on line %d\n", ln);
continue;
Map *map = loadListEntry(line);
if (map)
maps.append(map);
else {
for (int i = 0; i < maps.count(); i++)
delete maps.at(i);
_errorString = QString("Invalid map list entry on line %1.")
.arg(QString::number(ln));
return false;
}
QByteArray ba1 = list[0].trimmed();
QByteArray ba2 = list[1].trimmed();
mapList.append(new Map(QString::fromUtf8(ba1.data(), ba1.size()),
QString::fromLatin1(ba2.data(), ba2.size()), _downloader, parent));
}
return mapList;
_maps += maps;
return true;
}
bool MapList::loadMap(const QString &path)
{
OfflineMap *map = new OfflineMap(path, this);
if (map->isValid()) {
_maps.append(map);
return true;
} else {
_errorString = map->errorString();
delete map;
return false;
}
}
bool MapList::loadTba(const QString &path)
{
Atlas *atlas = new Atlas(path, this);
if (atlas->isValid()) {
_maps.append(atlas);
return true;
} else {
_errorString = atlas->errorString();
delete atlas;
return false;
}
}
bool MapList::loadTar(const QString &path)
{
Atlas *atlas = new Atlas(path, this);
if (atlas->isValid()) {
_maps.append(atlas);
return true;
} else {
_errorString = atlas->errorString();
delete atlas;
OfflineMap *map = new OfflineMap(path, this);
if (map->isValid()) {
_maps.append(map);
return true;
} else {
qWarning("%s: %s", qPrintable(path), qPrintable(_errorString));
qWarning("%s: %s", qPrintable(path),
qPrintable(map->errorString()));
_errorString = "Not a map/atlas file";
delete map;
return false;
}
}
}
bool MapList::loadFile(const QString &path)
{
QFileInfo fi(path);
QString suffix = fi.suffix().toLower();
if (suffix == "txt")
return loadList(path);
else if (suffix == "map")
return loadMap(path);
else if (suffix == "tba")
return loadTba(path);
else if (suffix == "tar")
return loadTar(path);
else {
_errorString = "Not a map/atlas file";
return false;
}
}
QString MapList::formats()
{
return tr("Map files (*.map *.tba *.tar)") + ";;"
+ tr("URL list files (*.txt)");
}
QStringList MapList::filter()
{
QStringList filter;
filter << "*.map" << "*.tba" << "*.tar" << "*.txt";
return filter;
}

View File

@ -1,21 +1,35 @@
#ifndef MAPLIST_H
#define MAPLIST_H
#include <QList>
#include <QString>
#include <QObject>
#include <QString>
#include "map.h"
class Map;
class Downloader;
class MapList
class MapList : public QObject
{
Q_OBJECT
public:
MapList(Downloader *downloader) : _downloader(downloader) {}
QList<Map*> load(const QString &fileName, QObject *parent = 0);
MapList(QObject *parent = 0) : QObject(parent) {}
bool loadFile(const QString &path);
const QList<Map*> &maps() const {return _maps;}
const QString &errorString() const {return _errorString;}
static QString formats();
static QStringList filter();
private:
Downloader *_downloader;
Map *loadListEntry(const QByteArray &line);
bool loadList(const QString &path);
bool loadMap(const QString &path);
bool loadTba(const QString &path);
bool loadTar(const QString &path);
QList<Map*> _maps;
QString _errorString;
};
#endif // MAPLIST_H

130
src/matrix.cpp Normal file
View File

@ -0,0 +1,130 @@
#include "matrix.h"
#define abs(x) ((x)<0 ? -(x) : (x))
Matrix::~Matrix()
{
if (isNull())
return;
delete[] _m;
}
Matrix::Matrix(size_t h, size_t w)
{
_h = h; _w = w;
if (isNull())
_m = 0;
else
_m = new double[_h * _w];
}
Matrix::Matrix(const Matrix& M)
{
_h = M._h; _w = M._w;
if (isNull())
_m = 0;
else
_m = new double[_h * _w];
for (size_t i = 0; i < _h; i++)
for (size_t j = 0; j < _w; j++)
m(i,j) = M.m(i,j);
}
Matrix &Matrix::operator=(const Matrix &M)
{
if (_h != M._h || _w != M._w) {
if (!isNull())
delete[] _m;
_h = M._h; _w = M._w;
if (isNull())
_m = 0;
else
_m = new double[_h * _w];
}
for (size_t i = 0; i < _h; i++)
for (size_t j = 0; j < _w; j++)
m(i,j) = M.m(i,j);
return *this;
}
bool Matrix::eliminate(double epsilon)
{
size_t i, j, k, maxrow;
double temp;
for (i = 0; i < _h; i++) {
maxrow = i;
for (j = i+1; j < _h; j++)
if (abs(m(j, i)) > abs(m(maxrow, i)))
maxrow = j;
for (j = 0; j < _w; j++) {
temp = m(i, j);
m(i, j) = m(maxrow, j);
m(maxrow, j) = temp;
}
if (abs(m(i, i)) <= epsilon)
return false;
for (j = i+1; j<_h; j++) {
temp = m(j, i) / m(i, i);
for (k = i; k < _w; k++)
m(j, k) -= m(i, k) * temp;
}
}
for (i = _h-1; i < i+1; i--) {
temp = m(i, i);
for (j = 0; j < i; j++)
for (k = _w-1; k >= i; k--)
m(j, k) -= m(i, k) * m(j, i) / temp;
m(i, i) /= temp;
for (j = _h; j < _w; j++)
m(i, j) /= temp;
}
return true;
}
Matrix Matrix::augemented(const Matrix &M) const
{
if (_h != M._h)
return Matrix();
Matrix A(_h, _w + M._w);
for (size_t i = 0; i < _h; i++)
for (size_t j = 0; j < _w; j++)
A.m(i, j) = m(i, j);
for (size_t i = 0; i < _h; i++)
for (size_t j = _w; j < A._w; j++)
A.m(i, j) = M.m(i, j-_w);
return A;
}
void Matrix::zeroize()
{
for (size_t i = 0; i < _h * _w; i++)
_m[i] = 0;
}
QDebug operator<<(QDebug dbg, const Matrix &matrix)
{
dbg.nospace() << "Matrix(" << endl;
for (size_t i = 0; i < matrix.h(); i++) {
for (size_t j = 0; j < matrix.w(); j++)
dbg << "\t" << matrix.m(i, j);
dbg << endl;
}
dbg << ")";
return dbg.space();
}

36
src/matrix.h Normal file
View File

@ -0,0 +1,36 @@
#ifndef MATRIX_H
#define MATRIX_H
#include <cstddef>
#include <cfloat>
#include <QDebug>
class Matrix {
public:
Matrix() {_h = 0; _w = 0; _m = 0;}
Matrix(size_t h, size_t w);
Matrix(const Matrix& M);
~Matrix();
Matrix &operator=(const Matrix &M);
size_t h() const {return _h;}
size_t w() const {return _w;}
double &m(size_t i, size_t j) {return _m[_w * i + j];}
double const &m(size_t i, size_t j) const {return _m[_w * i + j];}
bool isNull() const {return (_h == 0 || _w == 0);}
void zeroize();
bool eliminate(double epsilon = DBL_EPSILON);
Matrix augemented(const Matrix &M) const;
private:
double *_m;
size_t _h;
size_t _w;
};
QDebug operator<<(QDebug dbg, const Matrix &matrix);
#endif // MATRIX_H

13
src/mercator.cpp Normal file
View File

@ -0,0 +1,13 @@
#include <cmath>
#include "rd.h"
#include "mercator.h"
QPointF Mercator::ll2xy(const Coordinates &c) const
{
return QPointF(c.lon(), rad2deg(log(tan(M_PI/4.0 + deg2rad(c.lat())/2.0))));
}
Coordinates Mercator::xy2ll(const QPointF &p) const
{
return Coordinates(p.x(), rad2deg(2 * atan(exp(deg2rad(p.y()))) - M_PI/2));
}

13
src/mercator.h Normal file
View File

@ -0,0 +1,13 @@
#ifndef MERCATOR_H
#define MERCATOR_H
#include "projection.h"
class Mercator : public Projection
{
public:
virtual QPointF ll2xy(const Coordinates &c) const;
virtual Coordinates xy2ll(const QPointF &p) const;
};
#endif // MERCATOR_H

View File

@ -48,3 +48,9 @@ int str2int(const char *str, int len)
return res;
}
QRectF scaled(const QRectF &rect, qreal factor)
{
return QRectF(QPointF(rect.left() * factor, rect.top() * factor),
QSizeF(rect.width() * factor, rect.height() * factor));
}

View File

@ -1,7 +1,13 @@
#ifndef MISC_H
#define MISC_H
#include <QRectF>
#define ARRAY_SIZE(array) \
(sizeof(array) / sizeof((array)[0]))
double niceNum(double x, int round);
int str2int(const char *str, int len);
QRectF scaled(const QRectF &rect, qreal factor);
#endif // MISC_H

View File

@ -227,7 +227,7 @@ bool NMEAParser::readEW(const char *data, int len, qreal &lon)
return true;
}
bool NMEAParser::readRMC(const char *line, int len)
bool NMEAParser::readRMC(TrackData &track, const char *line, int len)
{
int col = 1;
const char *vp = line;
@ -280,22 +280,23 @@ bool NMEAParser::readRMC(const char *line, int len)
}
if (!date.isNull()) {
if (_date.isNull() && !_time.isNull() && !_tracks.last().isEmpty())
_tracks.last().last().setTimestamp(QDateTime(date, _time, Qt::UTC));
if (_date.isNull() && !_time.isNull() && !track.isEmpty())
track.last().setTimestamp(QDateTime(date, _time, Qt::UTC));
_date = date;
}
if (valid && !_GGA && !std::isnan(lat) && !std::isnan(lon)) {
Trackpoint t(Coordinates(lon, lat));
Coordinates c(lon, lat);
if (valid && !_GGA && c.isValid()) {
Trackpoint t(c);
if (!_date.isNull() && !time.isNull())
t.setTimestamp(QDateTime(_date, time, Qt::UTC));
_tracks.last().append(t);
track.append(t);
}
return true;
}
bool NMEAParser::readGGA(const char *line, int len)
bool NMEAParser::readGGA(TrackData &track, const char *line, int len)
{
int col = 1;
const char *vp = line;
@ -356,13 +357,14 @@ bool NMEAParser::readGGA(const char *line, int len)
return false;
}
if (!std::isnan(lat) && !std::isnan(lon)) {
Trackpoint t(Coordinates(lon, lat));
Coordinates c(lon, lat);
if (c.isValid()) {
Trackpoint t(c);
if (!(_time.isNull() || _date.isNull()))
t.setTimestamp(QDateTime(_date, _time, Qt::UTC));
if (!std::isnan(ele))
t.setElevation(ele - gh);
_tracks.last().append(t);
track.append(t);
_GGA = true;
}
@ -370,7 +372,7 @@ bool NMEAParser::readGGA(const char *line, int len)
return true;
}
bool NMEAParser::readWPL(const char *line, int len)
bool NMEAParser::readWPL(QList<Waypoint> &waypoints, const char *line, int len)
{
int col = 1;
const char *vp = line;
@ -411,10 +413,11 @@ bool NMEAParser::readWPL(const char *line, int len)
return false;
}
if (!std::isnan(lat) && !std::isnan(lon)) {
Waypoint w(Coordinates(lon, lat));
Coordinates c(lon, lat);
if (c.isValid()) {
Waypoint w(c);
w.setName(name);
_waypoints.append(w);
waypoints.append(w);
}
return true;
@ -474,8 +477,10 @@ bool NMEAParser::readZDA(const char *line, int len)
return true;
}
bool NMEAParser::loadFile(QFile *file)
bool NMEAParser::parse(QFile *file, QList<TrackData> &tracks,
QList<RouteData> &routes, QList<Waypoint> &waypoints)
{
Q_UNUSED(routes);
qint64 len;
char line[80 + 2 + 1 + 1];
@ -486,7 +491,8 @@ bool NMEAParser::loadFile(QFile *file)
_time = QTime();
_GGA = false;
_tracks.append(TrackData());
tracks.append(TrackData());
TrackData &track = tracks.last();
while (!file->atEnd()) {
len = file->readLine(line, sizeof(line));
@ -501,13 +507,13 @@ bool NMEAParser::loadFile(QFile *file)
if (validSentence(line, len)) {
if (!memcmp(line + 3, "RMC,", 4)) {
if (!readRMC(line + 7, len))
if (!readRMC(track, line + 7, len))
return false;
} else if (!memcmp(line + 3, "GGA,", 4)) {
if (!readGGA(line + 7, len))
if (!readGGA(track, line + 7, len))
return false;
} else if (!memcmp(line + 3, "WPL,", 4)) {
if (!readWPL(line + 7, len))
if (!readWPL(waypoints, line + 7, len))
return false;
} else if (!memcmp(line + 3, "ZDA,", 4)) {
if (!readZDA(line + 7, len))
@ -518,7 +524,7 @@ bool NMEAParser::loadFile(QFile *file)
_errorLine++;
}
if (!_tracks.last().size() && !_waypoints.size()) {
if (!tracks.last().size() && !waypoints.size()) {
_errorString = "No usable NMEA sentence found";
return false;
}

View File

@ -8,12 +8,11 @@
class NMEAParser : public Parser
{
public:
NMEAParser(QList<TrackData> &tracks, QList<RouteData> &routes,
QList<Waypoint> &waypoints) : Parser(tracks, routes, waypoints)
{_errorLine = 0; _GGA = false;}
NMEAParser() : _errorLine(0), _GGA(false) {}
~NMEAParser() {}
bool loadFile(QFile *file);
bool parse(QFile *file, QList<TrackData> &tracks,
QList<RouteData> &routes, QList<Waypoint> &waypoints);
QString errorString() const {return _errorString;}
int errorLine() const {return _errorLine;}
@ -27,9 +26,9 @@ private:
bool readAltitude(const char *data, int len, qreal &ele);
bool readGeoidHeight(const char *data, int len, qreal &gh);
bool readRMC(const char *line, int len);
bool readGGA(const char *line, int len);
bool readWPL(const char *line, int len);
bool readRMC(TrackData &track, const char *line, int len);
bool readGGA(TrackData &track, const char *line, int len);
bool readWPL(QList<Waypoint> &waypoints, const char *line, int len);
bool readZDA(const char *line, int len);
int _errorLine;

20
src/oddspinbox.cpp Normal file
View File

@ -0,0 +1,20 @@
#include "oddspinbox.h"
OddSpinBox::OddSpinBox(QWidget *parent) : QSpinBox(parent)
{
setSingleStep(2);
setMinimum(1);
}
QValidator::State OddSpinBox::validate(QString &text, int &pos) const
{
Q_UNUSED(pos);
bool ok;
int val;
val = text.toInt(&ok);
if (!ok || val < 0 || val % 2 == 0)
return QValidator::Invalid;
return QValidator::Acceptable;
}

15
src/oddspinbox.h Normal file
View File

@ -0,0 +1,15 @@
#ifndef ODDSPINBOX_H
#define ODDSPINBOX_H
#include <QSpinBox>
class OddSpinBox : public QSpinBox
{
public:
OddSpinBox(QWidget *parent = 0);
protected:
QValidator::State validate(QString &text, int &pos) const;
};
#endif // ODDSPINBOX_H

795
src/offlinemap.cpp Normal file
View File

@ -0,0 +1,795 @@
#include <QtGlobal>
#include <QPainter>
#include <QFileInfo>
#include <QMap>
#include <QDir>
#include <QBuffer>
#include <QImage>
#include <QImageReader>
#include <QPixmapCache>
#include "misc.h"
#include "rd.h"
#include "wgs84.h"
#include "coordinates.h"
#include "matrix.h"
#include "datum.h"
#include "latlon.h"
#include "mercator.h"
#include "transversemercator.h"
#include "utm.h"
#include "lambertconic.h"
#include "albersequal.h"
#include "ozf.h"
#include "rectc.h"
#include "offlinemap.h"
int OfflineMap::parse(QIODevice &device, QList<ReferencePoint> &points,
QString &projection, ProjectionSetup &setup, QString &datum)
{
bool res;
int ln = 1;
while (!device.atEnd()) {
QByteArray line = device.readLine();
if (ln == 1) {
if (!line.trimmed().startsWith("OziExplorer Map Data File"))
return ln;
} else if (ln == 2)
_name = line.trimmed();
else if (ln == 3)
_imgPath = line.trimmed();
else if (ln == 5)
datum = line.split(',').at(0).trimmed();
else {
QList<QByteArray> list = line.split(',');
QString key(list.at(0).trimmed());
bool ll = true; bool pp = true;
if (key.startsWith("Point") && list.count() == 17
&& !list.at(2).trimmed().isEmpty()) {
int x = list.at(2).trimmed().toInt(&res);
if (!res)
return ln;
int y = list.at(3).trimmed().toInt(&res);
if (!res)
return ln;
int latd = list.at(6).trimmed().toInt(&res);
if (!res)
ll = false;
qreal latm = list.at(7).trimmed().toFloat(&res);
if (!res)
ll = false;
int lond = list.at(9).trimmed().toInt(&res);
if (!res)
ll = false;
qreal lonm = list.at(10).trimmed().toFloat(&res);
if (!res)
ll = false;
if (ll && list.at(8).trimmed() == "S") {
latd = -latd;
latm = -latm;
}
if (ll && list.at(11).trimmed() == "W") {
lond = -lond;
lonm = -lonm;
}
setup.zone = list.at(13).trimmed().toInt(&res);
if (!res)
setup.zone = 0;
qreal ppx = list.at(14).trimmed().toFloat(&res);
if (!res)
pp = false;
qreal ppy = list.at(15).trimmed().toFloat(&res);
if (!res)
pp = false;
if (list.at(16).trimmed() == "S")
setup.zone = -setup.zone;
ReferencePoint p;
p.xy = QPoint(x, y);
if (ll) {
p.ll = Coordinates(lond + lonm/60.0, latd + latm/60.0);
if (p.ll.isValid())
points.append(p);
else
return ln;
} else if (pp) {
p.pp = QPointF(ppx, ppy);
points.append(p);
} else
return ln;
} else if (key == "IWH") {
if (list.count() < 4)
return ln;
int w = list.at(2).trimmed().toInt(&res);
if (!res)
return ln;
int h = list.at(3).trimmed().toInt(&res);
if (!res)
return ln;
_size = QSize(w, h);
} else if (key == "Map Projection") {
if (list.count() < 2)
return ln;
projection = list.at(1);
} else if (key == "Projection Setup") {
if (list.count() < 8)
return ln;
setup.latitudeOrigin = list.at(1).trimmed().toFloat(&res);
if (!res)
setup.latitudeOrigin = 0;
setup.longitudeOrigin = list.at(2).trimmed().toFloat(&res);
if (!res)
setup.longitudeOrigin = 0;
setup.scale = list.at(3).trimmed().toFloat(&res);
if (!res)
setup.scale = 1.0;
setup.falseEasting = list.at(4).trimmed().toFloat(&res);
if (!res)
setup.falseEasting = 0;
setup.falseNorthing = list.at(5).trimmed().toFloat(&res);
if (!res)
setup.falseNorthing = 0;
setup.standardParallel1 = list.at(6).trimmed().toFloat(&res);
if (!res)
setup.standardParallel1 = 0;
setup.standardParallel2 = list.at(7).trimmed().toFloat(&res);
if (!res)
setup.standardParallel2 = 0;
}
}
ln++;
}
return 0;
}
bool OfflineMap::parseMapFile(QIODevice &device, QList<ReferencePoint> &points,
QString &projection, ProjectionSetup &setup, QString &datum)
{
int el;
if (!device.open(QIODevice::ReadOnly)) {
_errorString = QString("Error opening map file: %1")
.arg(device.errorString());
return false;
}
if ((el = parse(device, points, projection, setup, datum))) {
_errorString = QString("Map file parse error on line %1").arg(el);
return false;
}
return true;
}
bool OfflineMap::createProjection(const QString &datum,
const QString &projection, const ProjectionSetup &setup,
QList<ReferencePoint> &points)
{
if (points.count() < 2) {
_errorString = "Insufficient number of reference points";
return false;
}
Datum d = Datum::datum(datum);
if (d.isNull()) {
_errorString = QString("%1: Unknown datum").arg(datum);
return false;
}
if (setup.latitudeOrigin < -90.0 || setup.latitudeOrigin > 90.0
|| setup.longitudeOrigin < -180.0 || setup.longitudeOrigin > 180.0
|| setup.standardParallel1 < -90.0 || setup.standardParallel1 > 90.0
|| setup.standardParallel2 < -90.0 || setup.standardParallel2 > 90.0) {
_errorString = "Invalid projection setup";
return false;
}
if (projection == "Mercator")
_projection = new Mercator();
else if (projection == "Transverse Mercator")
_projection = new TransverseMercator(d.ellipsoid(),
setup.latitudeOrigin, setup.longitudeOrigin, setup.scale,
setup.falseEasting, setup.falseNorthing);
else if (projection == "Latitude/Longitude")
_projection = new LatLon();
else if (projection == "Lambert Conformal Conic")
_projection = new LambertConic(d.ellipsoid(),
setup.standardParallel1, setup.standardParallel2,
setup.latitudeOrigin, setup.longitudeOrigin, setup.scale,
setup.falseEasting, setup.falseNorthing);
else if (projection == "Albers Equal Area")
_projection = new AlbersEqual(d.ellipsoid(), setup.standardParallel1,
setup.standardParallel2, setup.latitudeOrigin, setup.longitudeOrigin,
setup.falseEasting, setup.falseNorthing);
else if (projection == "(UTM) Universal Transverse Mercator") {
if (setup.zone)
_projection = new UTM(d.ellipsoid(), setup.zone);
else if (!points.first().ll.isNull())
_projection = new UTM(d.ellipsoid(), points.first().ll);
else {
_errorString = "Can not determine UTM zone";
return false;
}
} else if (projection == "(NZTM2) New Zealand TM 2000")
_projection = new TransverseMercator(d.ellipsoid(), 0, 173.0, 0.9996,
1600000, 10000000);
else if (projection == "(BNG) British National Grid")
_projection = new TransverseMercator(d.ellipsoid(), 49, -2, 0.999601,
400000, -100000);
else if (projection == "(IG) Irish Grid")
_projection = new TransverseMercator(d.ellipsoid(), 53.5, -8, 1.000035,
200000, 250000);
else if (projection == "(SG) Swedish Grid")
_projection = new TransverseMercator(d.ellipsoid(), 0, 15.808278, 1,
1500000, 0);
else if (projection == "(I) France Zone I")
_projection = new LambertConic(d.ellipsoid(), 48.598523, 50.395912,
49.5, 2.337229, 1 /*0.99987734*/, 600000, 1200000);
else if (projection == "(II) France Zone II")
_projection = new LambertConic(d.ellipsoid(), 45.898919, 47.696014,
46.8, 2.337229, 1 /*0.99987742*/, 600000, 2200000);
else if (projection == "(III) France Zone III")
_projection = new LambertConic(d.ellipsoid(), 43.199291, 44.996094,
44.1, 2.337229, 1 /*0.99987750*/, 600000, 3200000);
else if (projection == "(IV) France Zone IV")
_projection = new LambertConic(d.ellipsoid(), 41.560388, 42.767663,
42.165, 2.337229, 1 /*0.99994471*/, 234.358, 4185861.369);
else if (projection == "(VICGRID) Victoria Australia")
_projection = new LambertConic(d.ellipsoid(), -36, -38, -37, 145, 1,
2500000, 4500000);
else if (projection == "(VG94) VICGRID94 Victoria Australia")
_projection = new LambertConic(d.ellipsoid(), -36, -38, -37, 145, 1,
2500000, 2500000);
else {
_errorString = QString("%1: Unknown map projection").arg(projection);
return false;
}
for (int i = 0; i < points.size(); i++) {
if (points.at(i).ll.isNull())
points[i].ll = d.toWGS84(_projection->xy2ll(points.at(i).pp));
else
points[i].ll = d.toWGS84(points[i].ll);
}
return true;
}
bool OfflineMap::simpleTransformation(const QList<ReferencePoint> &points)
{
if (points.at(0).xy.x() == points.at(1).xy.x()
|| points.at(0).xy.y() == points.at(1).xy.y()) {
_errorString = "Invalid reference points tuple";
return false;
}
QPointF p0(_projection->ll2xy(points.at(0).ll));
QPointF p1(_projection->ll2xy(points.at(1).ll));
qreal dX, dY, lat0, lon0;
dX = (p0.x() - p1.x()) / (points.at(0).xy.x() - points.at(1).xy.x());
dY = (p1.y() - p0.y()) / (points.at(1).xy.y() - points.at(0).xy.y());
lat0 = p0.y() - points.at(0).xy.y() * dY;
lon0 = p1.x() - points.at(1).xy.x() * dX;
_transform = QTransform(1.0/dX, 0, 0, 1.0/dY, -lon0/dX, -lat0/dY);
_inverted = _transform.inverted();
return true;
}
bool OfflineMap::affineTransformation(const QList<ReferencePoint> &points)
{
Matrix c(3, 2);
c.zeroize();
for (size_t i = 0; i < c.h(); i++) {
for (size_t j = 0; j < c.w(); j++) {
for (int k = 0; k < points.size(); k++) {
double f[3], t[2];
QPointF p = _projection->ll2xy(points.at(k).ll);
f[0] = p.x();
f[1] = p.y();
f[2] = 1.0;
t[0] = points.at(k).xy.x();
t[1] = points.at(k).xy.y();
c.m(i,j) += f[i] * t[j];
}
}
}
Matrix Q(3, 3);
Q.zeroize();
for (int qi = 0; qi < points.size(); qi++) {
double v[3];
QPointF p = _projection->ll2xy(points.at(qi).ll);
v[0] = p.x();
v[1] = p.y();
v[2] = 1.0;
for (size_t i = 0; i < Q.h(); i++)
for (size_t j = 0; j < Q.w(); j++)
Q.m(i,j) += v[i] * v[j];
}
Matrix M = Q.augemented(c);
if (!M.eliminate()) {
_errorString = "Singular transformation matrix";
return false;
}
_transform = QTransform(M.m(0,3), M.m(0,4), M.m(1,3), M.m(1,4), M.m(2,3),
M.m(2,4));
_inverted = _transform.inverted();
return true;
}
bool OfflineMap::computeTransformation(const QList<ReferencePoint> &points)
{
Q_ASSERT(points.size() >= 2);
if (points.size() == 2)
return simpleTransformation(points);
else
return affineTransformation(points);
}
bool OfflineMap::computeResolution(QList<ReferencePoint> &points)
{
Q_ASSERT(points.count() >= 2);
int maxLon = 0, minLon = 0, maxLat = 0, minLat = 0;
qreal dLon, pLon, dLat, pLat;
for (int i = 1; i < points.size(); i++) {
if (points.at(i).ll.lon() < points.at(minLon).ll.lon())
minLon = i;
if (points.at(i).ll.lon() > points.at(maxLon).ll.lon())
maxLon = i;
if (points.at(i).ll.lat() < points.at(minLat).ll.lon())
minLat = i;
if (points.at(i).ll.lat() > points.at(maxLat).ll.lon())
maxLat = i;
}
dLon = points.at(minLon).ll.distanceTo(points.at(maxLon).ll);
pLon = QLineF(points.at(minLon).xy, points.at(maxLon).xy).length();
dLat = points.at(minLat).ll.distanceTo(points.at(maxLat).ll);
pLat = QLineF(points.at(minLat).xy, points.at(maxLat).xy).length();
_resolution = (dLon/pLon + dLat/pLat) / 2.0;
return true;
}
bool OfflineMap::getImageInfo(const QString &path)
{
QFileInfo ii(_imgPath);
if (ii.isRelative())
ii.setFile(path + "/" + _imgPath);
if (!ii.exists()) {
int last = _imgPath.lastIndexOf('\\');
if (last >= 0 && last < _imgPath.length() - 1) {
QStringRef fn(&_imgPath, last + 1, _imgPath.length() - last - 1);
ii.setFile(path + "/" + fn.toString());
}
}
if (ii.exists())
_imgPath = ii.absoluteFilePath();
else {
_errorString = QString("%1: No such image file").arg(_imgPath);
return false;
}
if (OZF::isOZF(_imgPath)) {
if (!_ozf.load(_imgPath)) {
_errorString = QString("%1: Error loading OZF file")
.arg(QFileInfo(_imgPath).fileName());
return false;
}
} else {
QImageReader img(_imgPath);
_size = img.size();
if (!_size.isValid()) {
_errorString = QString("%1: Error reading map image")
.arg(QFileInfo(_imgPath).fileName());
return false;
}
}
return true;
}
bool OfflineMap::getTileInfo(const QStringList &tiles, const QString &path)
{
QRegExp rx("_[0-9]+_[0-9]+\\.");
for (int i = 0; i < tiles.size(); i++) {
if (tiles.at(i).contains(rx)) {
_tileName = QString(tiles.at(i)).replace(rx, "_%1_%2.");
if (path.isNull()) {
QByteArray ba = _tar.file(tiles.at(i));
QBuffer buffer(&ba);
_tileSize = QImageReader(&buffer).size();
} else {
_tileName = path + "/" + _tileName;
_tileSize = QImageReader(path + "/" + tiles.at(i)).size();
}
if (!_tileSize.isValid()) {
_errorString = QString("Error retrieving tile size: "
"%1: Invalid image").arg(QFileInfo(tiles.at(i)).fileName());
return false;
}
return true;
}
}
_errorString = "Invalid/missing tile set";
return false;
}
bool OfflineMap::totalSizeSet()
{
if (!_size.isValid()) {
_errorString = "Missing total image size (IWH)";
return false;
} else
return true;
}
OfflineMap::OfflineMap(const QString &fileName, QObject *parent)
: Map(parent)
{
QList<ReferencePoint> points;
QString proj, datum;
ProjectionSetup setup;
QFileInfo fi(fileName);
QString suffix = fi.suffix().toLower();
_valid = false;
_img = 0;
_projection = 0;
_resolution = 0.0;
_zoom = 0;
_scale = QPointF(1.0, 1.0);
if (suffix == "tar") {
if (!_tar.load(fileName)) {
_errorString = "Error reading tar file";
return;
}
QString mapFileName = fi.completeBaseName() + ".map";
QByteArray ba = _tar.file(mapFileName);
if (ba.isNull()) {
_errorString = "Map file not found";
return;
}
QBuffer mapFile(&ba);
if (!parseMapFile(mapFile, points, proj, setup, datum))
return;
} else if (suffix =="map") {
QFile mapFile(fileName);
if (!parseMapFile(mapFile, points, proj, setup, datum))
return;
} else {
_errorString = "Not a map file";
return;
}
if (!createProjection(datum, proj, setup, points))
return;
if (!computeTransformation(points))
return;
computeResolution(points);
if (_tar.isOpen()) {
if (!totalSizeSet())
return;
if (!getTileInfo(_tar.files()))
return;
_imgPath = QString();
} else {
QDir set(fi.absolutePath() + "/" + "set");
if (set.exists()) {
if (!totalSizeSet())
return;
if (!getTileInfo(set.entryList(), set.absolutePath()))
return;
_imgPath = QString();
} else {
if (!getImageInfo(fi.absolutePath()))
return;
}
}
_valid = true;
}
OfflineMap::OfflineMap(const QString &fileName, Tar &tar, QObject *parent)
: Map(parent)
{
QList<ReferencePoint> points;
QString proj, datum;
ProjectionSetup setup;
QFileInfo fi(fileName);
_valid = false;
_img = 0;
_projection = 0;
_resolution = 0.0;
_zoom = 0;
_scale = QPointF(1.0, 1.0);
QFileInfo map(fi.absolutePath());
QFileInfo layer(map.absolutePath());
QString mapFile = layer.fileName() + "/" + map.fileName() + "/"
+ fi.fileName();
QByteArray ba = tar.file(mapFile);
if (ba.isNull()) {
_errorString = "Map file not found";
return;
}
QBuffer buffer(&ba);
if (!parseMapFile(buffer, points, proj, setup, datum))
return;
if (!createProjection(datum, proj, setup, points))
return;
if (!totalSizeSet())
return;
if (!computeTransformation(points))
return;
computeResolution(points);
_tarPath = fi.absolutePath() + "/" + fi.completeBaseName() + ".tar";
_imgPath = QString();
_valid = true;
}
OfflineMap::~OfflineMap()
{
if (_img)
delete _img;
if (_projection)
delete _projection;
}
void OfflineMap::load()
{
if (!_tarPath.isNull() && !_tileSize.isValid()) {
if (!_tar.load(_tarPath)) {
qWarning("%s: error loading tar file", qPrintable(_tarPath));
return;
}
if (!getTileInfo(_tar.files()))
qWarning("%s: %s", qPrintable(_tarPath), qPrintable(_errorString));
return;
}
if (!_img && !_imgPath.isNull() && !_ozf.isOpen()) {
_img = new QImage(_imgPath);
if (_img->isNull())
qWarning("%s: error loading map image", qPrintable(_imgPath));
}
}
void OfflineMap::unload()
{
if (_img) {
delete _img;
_img = 0;
}
}
void OfflineMap::drawTiled(QPainter *painter, const QRectF &rect)
{
QPoint tl = QPoint((int)floor(rect.left() / (qreal)_tileSize.width())
* _tileSize.width(), (int)floor(rect.top() / _tileSize.height())
* _tileSize.height());
QSizeF s(rect.right() - tl.x(), rect.bottom() - tl.y());
for (int i = 0; i < ceil(s.width() / _tileSize.width()); i++) {
for (int j = 0; j < ceil(s.height() / _tileSize.height()); j++) {
int x = tl.x() + i * _tileSize.width();
int y = tl.y() + j * _tileSize.height();
if (!QRectF(QPointF(x, y), _tileSize).intersects(bounds())) {
painter->fillRect(QRectF(QPoint(x, y), _tileSize), Qt::white);
continue;
}
QString tileName(_tileName.arg(QString::number(x),
QString::number(y)));
QPixmap pixmap;
if (_tar.isOpen()) {
QString key = _tar.fileName() + "/" + tileName;
if (!QPixmapCache::find(key, &pixmap)) {
QByteArray ba = _tar.file(tileName);
pixmap = QPixmap::fromImage(QImage::fromData(ba));
if (!pixmap.isNull())
QPixmapCache::insert(key, pixmap);
}
} else
pixmap = QPixmap(tileName);
if (pixmap.isNull()) {
qWarning("%s: error loading tile image", qPrintable(
_tileName.arg(QString::number(x), QString::number(y))));
painter->fillRect(QRectF(QPoint(x, y), _tileSize), Qt::white);
} else
painter->drawPixmap(QPoint(x, y), pixmap);
}
}
}
void OfflineMap::drawOZF(QPainter *painter, const QRectF &rect)
{
QPoint tl = QPoint((int)floor(rect.left() / _ozf.tileSize().width())
* _ozf.tileSize().width(), (int)floor(rect.top()
/ _ozf.tileSize().height()) * _ozf.tileSize().height());
QSizeF s(rect.right() - tl.x(), rect.bottom() - tl.y());
for (int i = 0; i < ceil(s.width() / _ozf.tileSize().width()); i++) {
for (int j = 0; j < ceil(s.height() / _ozf.tileSize().height()); j++) {
int x = tl.x() + i * _ozf.tileSize().width();
int y = tl.y() + j * _ozf.tileSize().height();
if (!QRectF(QPointF(x, y), _ozf.tileSize()).intersects(bounds())) {
painter->fillRect(QRectF(QPoint(x, y), _ozf.tileSize()),
Qt::white);
continue;
}
QPixmap pixmap;
QString key = _ozf.fileName() + "/" + QString::number(_zoom) + "_"
+ QString::number(x) + "_" + QString::number(y);
if (!QPixmapCache::find(key, &pixmap)) {
pixmap = _ozf.tile(_zoom, x, y);
if (!pixmap.isNull())
QPixmapCache::insert(key, pixmap);
}
if (pixmap.isNull()) {
qWarning("%s: error loading tile image", qPrintable(key));
painter->fillRect(QRectF(QPoint(x, y), _ozf.tileSize()),
Qt::white);
} else
painter->drawPixmap(QPoint(x, y), pixmap);
}
}
}
void OfflineMap::drawImage(QPainter *painter, const QRectF &rect)
{
if (!_img || _img->isNull())
painter->fillRect(rect, Qt::white);
else {
QRect r(rect.toRect());
painter->drawImage(r.left(), r.top(), *_img, r.left(), r.top(),
r.width(), r.height());
}
}
void OfflineMap::draw(QPainter *painter, const QRectF &rect)
{
if (_ozf.isOpen())
drawOZF(painter, rect);
else if (_tileSize.isValid())
drawTiled(painter, rect);
else
drawImage(painter, rect);
}
QPointF OfflineMap::ll2xy(const Coordinates &c)
{
if (_ozf.isOpen()) {
QPointF p(_transform.map(_projection->ll2xy(c)));
return QPointF(p.x() * _scale.x(), p.y() * _scale.y());
} else
return _transform.map(_projection->ll2xy(c));
}
Coordinates OfflineMap::xy2ll(const QPointF &p)
{
if (_ozf.isOpen()) {
return _projection->xy2ll(_inverted.map(QPointF(p.x() / _scale.x(),
p.y() / _scale.y())));
} else
return _projection->xy2ll(_inverted.map(p));
}
QRectF OfflineMap::bounds() const
{
if (_ozf.isOpen())
return QRectF(QPointF(0, 0), _ozf.size(_zoom));
else
return QRectF(QPointF(0, 0), _size);
}
qreal OfflineMap::resolution(const QPointF &p) const
{
Q_UNUSED(p);
if (_ozf.isOpen())
return _resolution / ((_scale.x() + _scale.y()) / 2.0);
else
return _resolution;
}
qreal OfflineMap::zoomFit(const QSize &size, const RectC &br)
{
if (_ozf.isOpen()) {
if (!br.isValid())
rescale(0);
else {
QRect sbr(QRectF(_transform.map(_projection->ll2xy(br.topLeft())),
_transform.map(_projection->ll2xy(br.bottomRight())))
.toRect().normalized());
for (int i = 0; i < _ozf.zooms(); i++) {
rescale(i);
if (sbr.size().width() * _scale.x() <= size.width()
&& sbr.size().height() * _scale.y() <= size.height())
break;
}
}
}
return _zoom;
}
qreal OfflineMap::zoomFit(qreal resolution, const Coordinates &c)
{
Q_UNUSED(c);
if (_ozf.isOpen()) {
for (int i = 0; i < _ozf.zooms(); i++) {
rescale(i);
qreal sr = _resolution / ((_scale.x() + _scale.y()) / 2.0);
if (sr >= resolution)
break;
}
}
return _zoom;
}
qreal OfflineMap::zoomIn()
{
if (_ozf.isOpen())
rescale(qMax(_zoom - 1, 0));
return _zoom;
}
qreal OfflineMap::zoomOut()
{
if (_ozf.isOpen())
rescale(qMin(_zoom + 1, _ozf.zooms() - 1));
return _zoom;
}
void OfflineMap::rescale(int zoom)
{
_zoom = zoom;
_scale = QPointF(
(qreal)_ozf.size(_zoom).width() / (qreal)_ozf.size(0).width(),
(qreal)_ozf.size(_zoom).height() / (qreal)_ozf.size(0).height());
}

112
src/offlinemap.h Normal file
View File

@ -0,0 +1,112 @@
#ifndef OFFLINEMAP_H
#define OFFLINEMAP_H
#include <QTransform>
#include "map.h"
#include "tar.h"
#include "ozf.h"
#include "coordinates.h"
#include "projection.h"
class QIODevice;
class QImage;
class OfflineMap : public Map
{
Q_OBJECT
public:
OfflineMap(const QString &fileName, QObject *parent = 0);
OfflineMap(const QString &fileName, Tar &tar, QObject *parent = 0);
~OfflineMap();
const QString &name() const {return _name;}
QRectF bounds() const;
qreal resolution(const QPointF &p) const;
qreal zoom() const {return _zoom;}
qreal zoomFit(const QSize &size, const RectC &br);
qreal zoomFit(qreal resolution, const Coordinates &c);
qreal zoomIn();
qreal zoomOut();
QPointF ll2xy(const Coordinates &c);
Coordinates xy2ll(const QPointF &p);
void draw(QPainter *painter, const QRectF &rect);
void load();
void unload();
bool isValid() const {return _valid;}
const QString &errorString() const {return _errorString;}
QPointF ll2pp(const Coordinates &c) const
{return _projection->ll2xy(c);}
QPointF xy2pp(const QPointF &p) const
{return _inverted.map(p);}
QPointF pp2xy(const QPointF &p) const
{return _transform.map(p);}
private:
struct ReferencePoint {
QPoint xy;
Coordinates ll;
QPointF pp;
};
struct ProjectionSetup {
double latitudeOrigin;
double longitudeOrigin;
double scale;
double falseEasting;
double falseNorthing;
double standardParallel1;
double standardParallel2;
int zone;
};
int parse(QIODevice &device, QList<ReferencePoint> &points,
QString &projection, ProjectionSetup &setup, QString &datum);
bool parseMapFile(QIODevice &device, QList<ReferencePoint> &points,
QString &projection, ProjectionSetup &setup, QString &datum);
bool totalSizeSet();
bool createProjection(const QString &datum, const QString &projection,
const ProjectionSetup &setup, QList<ReferencePoint> &points);
bool simpleTransformation(const QList<ReferencePoint> &points);
bool affineTransformation(const QList<ReferencePoint> &points);
bool computeTransformation(const QList<ReferencePoint> &points);
bool computeResolution(QList<ReferencePoint> &points);
bool getTileInfo(const QStringList &tiles, const QString &path = QString());
bool getImageInfo(const QString &path);
void drawTiled(QPainter *painter, const QRectF &rect);
void drawOZF(QPainter *painter, const QRectF &rect);
void drawImage(QPainter *painter, const QRectF &rect);
void rescale(int zoom);
QString _name;
bool _valid;
QString _errorString;
QSize _size;
Projection *_projection;
QTransform _transform, _inverted;
qreal _resolution;
OZF _ozf;
Tar _tar;
QString _tarPath;
QImage *_img;
QString _imgPath;
QSize _tileSize;
QString _tileName;
int _zoom;
QPointF _scale;
};
#endif // OFFLINEMAP_H

261
src/onlinemap.cpp Normal file
View File

@ -0,0 +1,261 @@
#include <QFileInfo>
#include <QDir>
#include <QPainter>
#include "rectc.h"
#include "downloader.h"
#include "config.h"
#include "rd.h"
#include "wgs84.h"
#include "misc.h"
#include "coordinates.h"
#include "mercator.h"
#include "onlinemap.h"
#define ZOOM_MAX 18
#define ZOOM_MIN 3
#define TILE_SIZE 256
static QPoint mercator2tile(const QPointF &m, int z)
{
QPoint tile;
tile.setX((int)(floor((m.x() + 180.0) / 360.0 * (1<<z))));
tile.setY((int)(floor((1.0 - (m.y() / 180.0)) / 2.0 * (1<<z))));
return tile;
}
static qreal zoom2scale(int zoom)
{
return (360.0/(qreal)((1<<zoom) * TILE_SIZE));
}
static int scale2zoom(qreal scale)
{
return (int)log2(360.0/(scale * (qreal)TILE_SIZE));
}
Downloader *OnlineMap::downloader;
OnlineMap::OnlineMap(const QString &name, const QString &url, QObject *parent)
: Map(parent)
{
_name = name;
_url = url;
_block = false;
_zoom = ZOOM_MAX;
connect(downloader, SIGNAL(finished()), this, SLOT(emitLoaded()));
QString path = TILES_DIR + QString("/") + name;
if (!QDir().mkpath(path))
qWarning("Error creating tiles dir: %s\n", qPrintable(path));
}
void OnlineMap::emitLoaded()
{
emit loaded();
}
void OnlineMap::loadTilesAsync(QList<Tile> &list)
{
QList<Download> dl;
for (int i = 0; i < list.size(); i++) {
Tile &t = list[i];
QString file = tileFile(t);
QFileInfo fi(file);
if (!fi.exists()) {
fillTile(t);
dl.append(Download(tileUrl(t), file));
} else
loadTileFile(t, file);
}
if (!dl.empty())
downloader->get(dl);
}
void OnlineMap::loadTilesSync(QList<Tile> &list)
{
QList<Download> dl;
for (int i = 0; i < list.size(); i++) {
Tile &t = list[i];
QString file = tileFile(t);
QFileInfo fi(file);
if (!fi.exists())
dl.append(Download(tileUrl(t), file));
else
loadTileFile(t, file);
}
if (dl.empty())
return;
QEventLoop wait;
connect(downloader, SIGNAL(finished()), &wait, SLOT(quit()));
if (downloader->get(dl))
wait.exec();
for (int i = 0; i < list.size(); i++) {
Tile &t = list[i];
if (t.pixmap().isNull()) {
QString file = tileFile(t);
QFileInfo fi(file);
if (!(fi.exists() && loadTileFile(t, file)))
fillTile(t);
}
}
}
void OnlineMap::fillTile(Tile &tile)
{
tile.pixmap() = QPixmap(TILE_SIZE, TILE_SIZE);
tile.pixmap().fill();
}
bool OnlineMap::loadTileFile(Tile &tile, const QString &file)
{
if (!tile.pixmap().load(file)) {
qWarning("%s: error loading tile file\n", qPrintable(file));
return false;
}
return true;
}
QString OnlineMap::tileUrl(const Tile &tile)
{
QString url(_url);
url.replace("$z", QString::number(tile.zoom()));
url.replace("$x", QString::number(tile.xy().x()));
url.replace("$y", QString::number(tile.xy().y()));
return url;
}
QString OnlineMap::tileFile(const Tile &tile)
{
QString file = TILES_DIR + QString("/%1/%2-%3-%4").arg(name())
.arg(tile.zoom()).arg(tile.xy().x()).arg(tile.xy().y());
return file;
}
void OnlineMap::clearCache()
{
QString path = TILES_DIR + QString("/") + name();
QDir dir = QDir(path);
QStringList list = dir.entryList();
for (int i = 0; i < list.count(); i++)
dir.remove(list.at(i));
}
QRectF OnlineMap::bounds() const
{
return scaled(QRectF(QPointF(-180, -180), QSizeF(360, 360)),
1.0/zoom2scale(_zoom));
}
qreal OnlineMap::zoomFit(const QSize &size, const RectC &br)
{
if (!br.isValid())
_zoom = ZOOM_MAX;
else {
QRectF tbr(Mercator().ll2xy(br.topLeft()),
Mercator().ll2xy(br.bottomRight()));
QPointF sc(tbr.width() / size.width(), tbr.height() / size.height());
_zoom = scale2zoom(qMax(sc.x(), sc.y()));
if (_zoom < ZOOM_MIN)
_zoom = ZOOM_MIN;
if (_zoom > ZOOM_MAX)
_zoom = ZOOM_MAX;
}
return _zoom;
}
qreal OnlineMap::zoomFit(qreal resolution, const Coordinates &c)
{
_zoom = (int)(log2((WGS84_RADIUS * 2 * M_PI * cos(deg2rad(c.lat())))
/ resolution) - log2(TILE_SIZE));
if (_zoom < ZOOM_MIN)
_zoom = ZOOM_MIN;
if (_zoom > ZOOM_MAX)
_zoom = ZOOM_MAX;
return _zoom;
}
qreal OnlineMap::resolution(const QPointF &p) const
{
qreal scale = zoom2scale(_zoom);
return (WGS84_RADIUS * 2 * M_PI * scale / 360.0
* cos(2.0 * atan(exp(deg2rad(-p.y() * scale))) - M_PI/2));
}
qreal OnlineMap::zoomIn()
{
_zoom = qMin(_zoom + 1, ZOOM_MAX);
return _zoom;
}
qreal OnlineMap::zoomOut()
{
_zoom = qMax(_zoom - 1, ZOOM_MIN);
return _zoom;
}
void OnlineMap::draw(QPainter *painter, const QRectF &rect)
{
qreal scale = zoom2scale(_zoom);
QPoint tile = mercator2tile(QPointF(rect.topLeft().x() * scale,
-rect.topLeft().y() * scale), _zoom);
QPoint tl = QPoint((int)floor(rect.left() / (qreal)TILE_SIZE)
* TILE_SIZE, (int)floor(rect.top() / TILE_SIZE) * TILE_SIZE);
QList<Tile> tiles;
QSizeF s(rect.right() - tl.x(), rect.bottom() - tl.y());
for (int i = 0; i < ceil(s.width() / TILE_SIZE); i++)
for (int j = 0; j < ceil(s.height() / TILE_SIZE); j++)
tiles.append(Tile(QPoint(tile.x() + i, tile.y() + j), _zoom));
if (_block)
loadTilesSync(tiles);
else
loadTilesAsync(tiles);
for (int i = 0; i < tiles.count(); i++) {
Tile &t = tiles[i];
QPoint tp(tl.x() + (t.xy().x() - tile.x()) * TILE_SIZE,
tl.y() + (t.xy().y() - tile.y()) * TILE_SIZE);
painter->drawPixmap(tp, t.pixmap());
}
}
QPointF OnlineMap::ll2xy(const Coordinates &c)
{
qreal scale = zoom2scale(_zoom);
QPointF m = Mercator().ll2xy(c);
return QPointF(m.x() / scale, m.y() / -scale);
}
Coordinates OnlineMap::xy2ll(const QPointF &p)
{
qreal scale = zoom2scale(_zoom);
QPointF m(p.x() * scale, -p.y() * scale);
return Mercator().xy2ll(m);
}

57
src/onlinemap.h Normal file
View File

@ -0,0 +1,57 @@
#ifndef ONLINEMAP_H
#define ONLINEMAP_H
#include "map.h"
#include "tile.h"
class Downloader;
class OnlineMap : public Map
{
Q_OBJECT
public:
OnlineMap(const QString &name, const QString &url, QObject *parent = 0);
const QString &name() const {return _name;}
QRectF bounds() const;
qreal resolution(const QPointF &p) const;
qreal zoom() const {return _zoom;}
qreal zoomFit(const QSize &size, const RectC &br);
qreal zoomFit(qreal resolution, const Coordinates &c);
qreal zoomIn();
qreal zoomOut();
QPointF ll2xy(const Coordinates &c);
Coordinates xy2ll(const QPointF &p);
void draw(QPainter *painter, const QRectF &rect);
void setBlockingMode(bool block) {_block = block;}
void clearCache();
static void setDownloader(Downloader *downloader)
{OnlineMap::downloader = downloader;}
private slots:
void emitLoaded();
private:
QString tileUrl(const Tile &tile);
QString tileFile(const Tile &tile);
bool loadTileFile(Tile &tile, const QString &file);
void fillTile(Tile &tile);
void loadTilesAsync(QList<Tile> &list);
void loadTilesSync(QList<Tile> &list);
int _zoom;
QString _name;
QString _url;
bool _block;
static Downloader *downloader;
};
#endif // ONLINEMAP_H

View File

@ -9,17 +9,21 @@
#include <QGroupBox>
#include <QCheckBox>
#include <QComboBox>
#include <QRadioButton>
#include <QLabel>
#include <QSysInfo>
#include "config.h"
#include "icons.h"
#include "colorbox.h"
#include "stylecombobox.h"
#include "oddspinbox.h"
#include "percentslider.h"
#include "optionsdialog.h"
#define MENU_MARGIN 20
#define MENU_ICON_SIZE 32
QWidget *OptionsDialog::createAppearancePage()
{
_baseColor = new ColorBox();
@ -29,14 +33,39 @@ QWidget *OptionsDialog::createAppearancePage()
_colorOffset->setMaximum(1.0);
_colorOffset->setSingleStep(0.01);
_colorOffset->setValue(_options->palette.shift());
QFormLayout *paletteLayout = new QFormLayout();
paletteLayout->addRow(tr("Base color:"), _baseColor);
paletteLayout->addRow(tr("Palette shift:"), _colorOffset);
#ifndef Q_OS_MAC
QGroupBox *pathsBox = new QGroupBox(tr("Paths"));
pathsBox->setLayout(paletteLayout);
#endif
_mapOpacity = new PercentSlider();
_mapOpacity->setValue(_options->mapOpacity);
QFormLayout *mapLayout = new QFormLayout();
mapLayout->addRow(tr("Map opacity:"), _mapOpacity);
#ifndef Q_OS_MAC
QGroupBox *mapBox = new QGroupBox(tr("Map"));
mapBox->setLayout(mapLayout);
#endif
QWidget *colorTab = new QWidget();
colorTab->setLayout(paletteLayout);
QVBoxLayout *colorTabLayout = new QVBoxLayout();
#ifdef Q_OS_MAC
QFrame *l0 = new QFrame();
l0->setFrameShape(QFrame::HLine);
l0->setFrameShadow(QFrame::Sunken);
colorTabLayout->addLayout(paletteLayout);
colorTabLayout->addWidget(l0);
colorTabLayout->addLayout(mapLayout);
#else // Q_OS_MAC
colorTabLayout->addWidget(pathsBox);
colorTabLayout->addWidget(mapBox);
#endif // O_OS_MAC
colorTabLayout->addStretch();
colorTab->setLayout(colorTabLayout);
_trackWidth = new QSpinBox();
_trackWidth->setValue(_options->trackWidth);
@ -83,11 +112,12 @@ QWidget *OptionsDialog::createAppearancePage()
pathTabLayout->addWidget(l1);
pathTabLayout->addLayout(routeLayout);
pathTabLayout->addWidget(l2);
#else
#else // Q_OS_MAC
pathTabLayout->addWidget(trackBox);
pathTabLayout->addWidget(routeBox);
#endif
#endif // Q_OS_MAC
pathTabLayout->addLayout(pathAALayout);
pathTabLayout->addStretch();
pathTab->setLayout(pathTabLayout);
_graphWidth = new QSpinBox();
@ -117,6 +147,98 @@ QWidget *OptionsDialog::createAppearancePage()
return appearancePage;
}
QWidget *OptionsDialog::createDataPage()
{
QString filterToolTip = tr("Moving average window size");
_elevationFilter = new OddSpinBox();
_elevationFilter->setValue(_options->elevationFilter);
_elevationFilter->setToolTip(filterToolTip);
_speedFilter = new OddSpinBox();
_speedFilter->setValue(_options->speedFilter);
_speedFilter->setToolTip(filterToolTip);
_heartRateFilter = new OddSpinBox();
_heartRateFilter->setValue(_options->heartRateFilter);
_heartRateFilter->setToolTip(filterToolTip);
_cadenceFilter = new OddSpinBox();
_cadenceFilter->setValue(_options->cadenceFilter);
_cadenceFilter->setToolTip(filterToolTip);
_powerFilter = new OddSpinBox();
_powerFilter->setValue(_options->powerFilter);
_powerFilter->setToolTip(filterToolTip);
QFormLayout *smoothLayout = new QFormLayout();
smoothLayout->addRow(tr("Elevation:"), _elevationFilter);
smoothLayout->addRow(tr("Speed:"), _speedFilter);
smoothLayout->addRow(tr("Heart rate:"), _heartRateFilter);
smoothLayout->addRow(tr("Cadence:"), _cadenceFilter);
smoothLayout->addRow(tr("Power:"), _powerFilter);
#ifndef Q_OS_MAC
QGroupBox *smoothBox = new QGroupBox(tr("Smoothing"));
smoothBox->setLayout(smoothLayout);
#endif // Q_OS_MAC
_outlierEliminate = new QCheckBox(tr("Eliminate GPS outliers"));
_outlierEliminate->setChecked(_options->outlierEliminate);
QFormLayout *outlierLayout = new QFormLayout();
outlierLayout->addWidget(_outlierEliminate);
#ifndef Q_OS_MAC
QGroupBox *outlierBox = new QGroupBox(tr("Outlier elimination"));
outlierBox->setLayout(outlierLayout);
#endif // Q_OS_MAC
QWidget *filterTab = new QWidget();
QVBoxLayout *filterTabLayout = new QVBoxLayout();
#ifdef Q_OS_MAC
QLabel *label = new QLabel(tr("Smoothing:"));
QFrame *line = new QFrame();
line->setFrameShape(QFrame::HLine);
line->setFrameShadow(QFrame::Sunken);
filterTabLayout->addWidget(label);
filterTabLayout->addLayout(smoothLayout);
filterTabLayout->addWidget(line);
filterTabLayout->addLayout(outlierLayout);
#else // Q_OS_MAC
filterTabLayout->addWidget(smoothBox);
filterTabLayout->addWidget(outlierBox);
#endif // Q_OS_MAC
filterTabLayout->addStretch();
filterTab->setLayout(filterTabLayout);
_pauseSpeed = new QDoubleSpinBox();
_pauseSpeed->setDecimals(1);
_pauseSpeed->setSingleStep(0.1);
_pauseSpeed->setMinimum(0.1);
if (_options->units == Imperial) {
_pauseSpeed->setValue(_options->pauseSpeed * MS2MIH);
_pauseSpeed->setSuffix(UNIT_SPACE + tr("mi/h"));
} else {
_pauseSpeed->setValue(_options->pauseSpeed * MS2KMH);
_pauseSpeed->setSuffix(UNIT_SPACE + tr("km/h"));
}
_pauseInterval = new QSpinBox();
_pauseInterval->setMinimum(1);
_pauseInterval->setSuffix(UNIT_SPACE + tr("s"));
_pauseInterval->setValue(_options->pauseInterval);
QFormLayout *pauseLayout = new QFormLayout();
pauseLayout->addRow(tr("Minimal speed:"), _pauseSpeed);
pauseLayout->addRow(tr("Minimal duration:"), _pauseInterval);
QWidget *pauseTab = new QWidget();
pauseTab->setLayout(pauseLayout);
QTabWidget *filterPage = new QTabWidget();
filterPage->addTab(filterTab, tr("Filtering"));
filterPage->addTab(pauseTab, tr("Pause detection"));
return filterPage;
}
QWidget *OptionsDialog::createPOIPage()
{
_poiRadius = new QDoubleSpinBox();
@ -144,6 +266,36 @@ QWidget *OptionsDialog::createPOIPage()
QWidget *OptionsDialog::createExportPage()
{
_wysiwyg = new QRadioButton(tr("WYSIWYG"));
_hires = new QRadioButton(tr("High-Resolution"));
if (_options->hiresPrint)
_hires->setChecked(true);
else
_wysiwyg->setChecked(true);
QLabel *lw = new QLabel(tr("The printed area is approximately the display"
" area. The map zoom level does not change."));
QLabel *lh = new QLabel(tr("The zoom level will be changed so that"
" the whole content (tracks/waypoints) fits to the printed area and"
" the map resolution is as close as possible to the print resolution."));
QFont f = lw->font();
f.setPointSize(f.pointSize() - 1);
lw->setWordWrap(true);
lh->setWordWrap(true);
lw->setFont(f);
lh->setFont(f);
QVBoxLayout *modeTabLayout = new QVBoxLayout();
modeTabLayout->addWidget(_wysiwyg);
modeTabLayout->addWidget(lw);
modeTabLayout->addSpacing(10);
modeTabLayout->addWidget(_hires);
modeTabLayout->addWidget(lh);
modeTabLayout->addStretch();
QWidget *modeTab = new QWidget();
modeTab->setLayout(modeTabLayout);
_name = new QCheckBox(tr("Name"));
_name->setChecked(_options->printName);
_date = new QCheckBox(tr("Date"));
@ -179,6 +331,7 @@ QWidget *OptionsDialog::createExportPage()
QTabWidget *exportPage = new QTabWidget();
exportPage->addTab(modeTab, tr("Print mode"));
exportPage->addTab(headerTab, tr("Header"));
exportPage->addTab(graphTab, tr("Graphs"));
@ -196,11 +349,24 @@ QWidget *OptionsDialog::createSystemPage()
#endif // Q_OS_WIN32
_useOpenGL->setChecked(_options->useOpenGL);
QFormLayout *systemLayout = new QFormLayout();
systemLayout->addWidget(_useOpenGL);
_pixmapCache = new QSpinBox();
_pixmapCache->setMinimum(16);
_pixmapCache->setMaximum(1024);
_pixmapCache->setSuffix(UNIT_SPACE + tr("MB"));
_pixmapCache->setValue(_options->pixmapCache);
QFormLayout *cacheLayout = new QFormLayout();
cacheLayout->addRow(tr("Image cache size:"), _pixmapCache);
QFormLayout *openGLLayout = new QFormLayout();
openGLLayout->addWidget(_useOpenGL);
QWidget *systemTab = new QWidget();
systemTab->setLayout(systemLayout);
QVBoxLayout *systemTabLayout = new QVBoxLayout();
systemTabLayout->addLayout(cacheLayout);
systemTabLayout->addLayout(openGLLayout);
systemTabLayout->addStretch();
systemTab->setLayout(systemTabLayout);
QTabWidget *systemPage = new QTabWidget();
systemPage->addTab(systemTab, tr("System"));
@ -213,6 +379,7 @@ OptionsDialog::OptionsDialog(Options *options, QWidget *parent)
{
QStackedWidget *pages = new QStackedWidget();
pages->addWidget(createAppearancePage());
pages->addWidget(createDataPage());
pages->addWidget(createPOIPage());
pages->addWidget(createExportPage());
pages->addWidget(createSystemPage());
@ -221,6 +388,7 @@ OptionsDialog::OptionsDialog(Options *options, QWidget *parent)
menu->setIconSize(QSize(MENU_ICON_SIZE, MENU_ICON_SIZE));
new QListWidgetItem(QIcon(QPixmap(APPEARANCE_ICON)), tr("Appearance"),
menu);
new QListWidgetItem(QIcon(QPixmap(DATA_ICON)), tr("Data"), menu);
new QListWidgetItem(QIcon(QPixmap(POI_ICON)), tr("POI"), menu);
new QListWidgetItem(QIcon(QPixmap(PRINT_EXPORT_ICON)), tr("Print & Export"),
menu);
@ -259,6 +427,7 @@ void OptionsDialog::accept()
{
_options->palette.setColor(_baseColor->color());
_options->palette.setShift(_colorOffset->value());
_options->mapOpacity = _mapOpacity->value();
_options->trackWidth = _trackWidth->value();
_options->trackStyle = (Qt::PenStyle) _trackStyle->itemData(
_trackStyle->currentIndex()).toInt();
@ -269,13 +438,23 @@ void OptionsDialog::accept()
_options->graphWidth = _graphWidth->value();
_options->graphAntiAliasing = _graphAA->isChecked();
if (_options->units == Imperial)
_options->poiRadius = _poiRadius->value() * MIINM;
else
_options->poiRadius = _poiRadius->value() * KMINM;
_options->elevationFilter = _elevationFilter->value();
_options->speedFilter = _speedFilter->value();
_options->heartRateFilter = _heartRateFilter->value();
_options->cadenceFilter = _cadenceFilter->value();
_options->powerFilter = _powerFilter->value();
_options->outlierEliminate = _outlierEliminate->isChecked();
_options->pauseSpeed = (_options->units == Imperial)
? _pauseSpeed->value() / MS2MIH : _pauseSpeed->value() / MS2KMH;
_options->pauseInterval = _pauseInterval->value();
_options->poiRadius = (_options->units == Imperial)
? _poiRadius->value() * MIINM : _poiRadius->value() * KMINM;
_options->useOpenGL = _useOpenGL->isChecked();
_options->pixmapCache = _pixmapCache->value();
_options->hiresPrint = _hires->isChecked();
_options->printName = _name->isChecked();
_options->printDate = _date->isChecked();
_options->printDistance = _distance->isChecked();

View File

@ -7,14 +7,18 @@
class ColorBox;
class StyleComboBox;
class OddSpinBox;
class QSpinBox;
class QDoubleSpinBox;
class QComboBox;
class QCheckBox;
class QRadioButton;
class PercentSlider;
struct Options {
// Appearance
Palette palette;
int mapOpacity;
int trackWidth;
int routeWidth;
Qt::PenStyle trackStyle;
@ -22,11 +26,22 @@ struct Options {
int graphWidth;
bool pathAntiAliasing;
bool graphAntiAliasing;
// Data
int elevationFilter;
int speedFilter;
int heartRateFilter;
int cadenceFilter;
int powerFilter;
bool outlierEliminate;
qreal pauseSpeed;
int pauseInterval;
// POI
int poiRadius;
// System
bool useOpenGL;
int pixmapCache;
// Print/Export
bool hiresPrint;
bool printName;
bool printDate;
bool printDistance;
@ -50,14 +65,17 @@ public slots:
private:
QWidget *createAppearancePage();
QWidget *createDataPage();
QWidget *createPOIPage();
QWidget *createSystemPage();
QWidget *createExportPage();
Options *_options;
// Appearance
ColorBox *_baseColor;
QDoubleSpinBox *_colorOffset;
PercentSlider *_mapOpacity;
QSpinBox *_trackWidth;
StyleComboBox *_trackStyle;
QSpinBox *_routeWidth;
@ -65,8 +83,23 @@ private:
QCheckBox *_pathAA;
QSpinBox *_graphWidth;
QCheckBox *_graphAA;
// Data
OddSpinBox *_elevationFilter;
OddSpinBox *_speedFilter;
OddSpinBox *_heartRateFilter;
OddSpinBox *_cadenceFilter;
OddSpinBox *_powerFilter;
QCheckBox *_outlierEliminate;
QDoubleSpinBox *_pauseSpeed;
QSpinBox *_pauseInterval;
// POI
QDoubleSpinBox *_poiRadius;
// System
QSpinBox *_pixmapCache;
QCheckBox *_useOpenGL;
// Print/Export
QRadioButton *_wysiwyg;
QRadioButton *_hires;
QCheckBox *_name;
QCheckBox *_date;
QCheckBox *_distance;

268
src/ozf.cpp Normal file
View File

@ -0,0 +1,268 @@
#include <cstring>
#include <QtEndian>
#include <QFile>
#include "ozf.h"
#define OZF2_MAGIC 0x7778
#define OZF3_MAGIC 0x7780
static const quint8 XKEY[] =
{
0x2D, 0x4A, 0x43, 0xF1, 0x27, 0x9B, 0x69, 0x4F,
0x36, 0x52, 0x87, 0xEC, 0x5F, 0x42, 0x53, 0x22,
0x9E, 0x8B, 0x2D, 0x83, 0x3D, 0xD2, 0x84, 0xBA,
0xD8, 0x5B
};
static void decrypt(void *data, size_t size, quint8 init)
{
for (size_t i = 0; i < size; i++)
reinterpret_cast<quint8*>(data)[i] ^= XKEY[i % sizeof(XKEY)] + init;
}
template<class T> bool OZF::readValue(T &val)
{
T data;
if (_file.read((char*)&data, sizeof(T)) < (qint64)sizeof(T))
return false;
if (_decrypt)
decrypt(&data, sizeof(T), _key);
if (sizeof(T) > 1)
val = qFromLittleEndian(data);
else
val = data;
return true;
}
bool OZF::read(void *data, size_t size, size_t decryptSize)
{
if (_file.read((char*)data, size) < (qint64)size)
return false;
if (_decrypt)
decrypt(data, decryptSize ? qMin(decryptSize, size) : size, _key);
return true;
}
bool OZF::initOZF3()
{
quint8 randomNumber, initial;
quint8 h1[8];
quint8 h2[16], h2d[16];
if (!_file.seek(14))
return false;
if (!readValue(randomNumber))
return false;
if (!_file.seek(162))
return false;
if (!readValue(initial))
return false;
_decrypt = true;
_key = initial;
if (!_file.seek(0))
return false;
if (!read(h1, sizeof(h1)))
return false;
_tileSize = *(h1 + 6);
if (!_file.seek(15 + randomNumber + 4))
return false;
if (_file.read((char*)h2, sizeof(h2)) != (qint64)sizeof(h2))
return false;
for (int i = 0; i < 256; i++) {
memcpy(h2d, h2, sizeof(h2d));
decrypt(h2d, sizeof(h2d), (quint8)i);
if ((quint32)*h2d == 40 && (quint16)*(h2d + 12) == 1
&& (quint16)*(h2d + 14) == 8) {
_key = (quint8)i;
return true;
}
}
return false;
}
bool OZF::initOZF2()
{
if (!_file.seek(6))
return false;
if (!readValue(_tileSize))
return false;
return true;
}
bool OZF::readHeaders()
{
quint16 magic;
if (!readValue(magic))
return false;
if (magic == OZF2_MAGIC) {
if (!initOZF2())
return false;
} else if (magic == OZF3_MAGIC) {
if (!initOZF3())
return false;
} else {
qWarning("%s: not a OZF2/OZF3 file", qPrintable(_file.fileName()));
return false;
}
return true;
}
bool OZF::readTileTable()
{
quint32 tableOffset, headerOffset, bgr0, w, h;
quint16 x, y;
int zooms;
if (!_file.seek(_file.size() - sizeof(tableOffset)))
return false;
if (!readValue(tableOffset))
return false;
zooms = (int)((_file.size() - tableOffset - sizeof(quint32))
/ sizeof(quint32));
for (int i = 0; i < zooms - 2; i++) {
if (!_file.seek(tableOffset + i * sizeof(quint32)))
return false;
if (!readValue(headerOffset))
return false;
if (!_file.seek(headerOffset))
return false;
if (!readValue(w))
return false;
if (!readValue(h))
return false;
if (!readValue(x))
return false;
if (!readValue(y))
return false;
Zoom zoom;
zoom.size = QSize(w, h);
zoom.dim = QSize(x, y);
zoom.palette = QVector<quint32>(256);
if (!read(&(zoom.palette[0]), sizeof(quint32) * 256))
return false;
for (int i = 0; i < zoom.palette.size(); i++) {
bgr0 = qFromLittleEndian(zoom.palette.at(i));
quint32 b = (bgr0 & 0x000000FF);
quint32 g = (bgr0 & 0x0000FF00) >> 8;
quint32 r = (bgr0 & 0x00FF0000) >> 16;
zoom.palette[i] = 0xFF000000 | r << 16 | g << 8 | b;
}
zoom.tiles = QVector<quint32>(zoom.dim.width() * zoom.dim.height() + 1);
for (int i = 0; i < zoom.tiles.size(); i++)
if (!readValue(zoom.tiles[i]))
return false;
_zooms.append(zoom);
}
return _zooms.isEmpty() ? false : true;
}
bool OZF::load(const QString &path)
{
if (_file.isOpen())
_file.close();
_file.setFileName(path);
if (!_file.open(QIODevice::ReadOnly))
return false;
if (!readHeaders()) {
qWarning("%s: Invalid header", qPrintable(_file.fileName()));
_file.close();
return false;
}
if (!readTileTable()) {
qWarning("%s: Invalid tile table", qPrintable(_file.fileName()));
_file.close();
return false;
}
return true;
}
QPixmap OZF::tile(int zoom, int x, int y)
{
Q_ASSERT(_file.isOpen());
Q_ASSERT(0 <= zoom && zoom < _zooms.count());
const Zoom &z = _zooms.at(zoom);
int i = (y/tileSize().height()) * z.dim.width() + (x/tileSize().width());
if (i >= z.tiles.size() - 1 || i < 0)
return QPixmap();
int size = z.tiles.at(i+1) - z.tiles.at(i);
if (!_file.seek(z.tiles.at(i)))
return QPixmap();
quint32 bes = qToBigEndian(tileSize().width() * tileSize().height());
QByteArray ba;
ba.resize(sizeof(bes) + size);
*(ba.data()) = bes;
if (!read(ba.data() + sizeof(bes), size, 16))
return QPixmap();
QByteArray uba = qUncompress(ba);
if (uba.size() != tileSize().width() * tileSize().height())
return QPixmap();
QImage img((const uchar*)uba.constData(), tileSize().width(),
tileSize().height(), QImage::Format_Indexed8);
img.setColorTable(z.palette);
return QPixmap::fromImage(img.mirrored());
}
QSize OZF::size(int zoom) const
{
Q_ASSERT(_file.isOpen());
Q_ASSERT(0 <= zoom && zoom < _zooms.count());
return _zooms.at(zoom).size;
}
bool OZF::isOZF(const QString &path)
{
QFile file(path);
quint16 magic;
if (!file.open(QIODevice::ReadOnly))
return false;
if (file.read((char*)&magic, sizeof(magic)) < (qint64)sizeof(magic))
return false;
magic = qFromLittleEndian(magic);
if (magic == OZF2_MAGIC || magic == OZF3_MAGIC)
return true;
return false;
}

51
src/ozf.h Normal file
View File

@ -0,0 +1,51 @@
#ifndef OZF_H
#define OZF_H
#include <QString>
#include <QSize>
#include <QColor>
#include <QList>
#include <QVector>
#include <QFile>
#include <QPixmap>
class OZF
{
public:
OZF() : _tileSize(0), _decrypt(false), _key(0) {}
bool load(const QString &path);
QString fileName() const {return _file.fileName();}
bool isOpen() const {return _file.isOpen();}
int zooms() const {return _zooms.size();}
QSize size(int zoom) const;
QSize tileSize() const {return QSize(_tileSize, _tileSize);}
QPixmap tile(int zoom, int x, int y);
static bool isOZF(const QString &path);
private:
struct Zoom {
QSize size;
QSize dim;
QVector<QRgb> palette;
QVector<quint32> tiles;
};
template<class T> bool readValue(T &val);
bool read(void *data, size_t size, size_t decryptSize = 0);
bool initOZF3();
bool initOZF2();
bool readHeaders();
bool readTileTable();
quint16 _tileSize;
bool _decrypt;
quint8 _key;
QList<Zoom> _zooms;
QFile _file;
};
#endif // OZF_H

View File

@ -41,6 +41,5 @@ QDebug operator<<(QDebug dbg, const Palette &palette)
{
dbg.nospace() << "Palette(" << palette.color() << ", " << palette.shift()
<< ")";
return dbg.maybeSpace();
return dbg.space();
}

View File

@ -12,19 +12,12 @@
class Parser
{
public:
Parser(QList<TrackData> &tracks, QList<RouteData> &routes,
QList<Waypoint> &waypoints) : _tracks(tracks), _routes(routes),
_waypoints(waypoints) {}
virtual ~Parser() {}
virtual bool loadFile(QFile *file) = 0;
virtual bool parse(QFile *file, QList<TrackData> &tracks,
QList<RouteData> &routes, QList<Waypoint> &waypoints) = 0;
virtual QString errorString() const = 0;
virtual int errorLine() const = 0;
protected:
QList<TrackData> &_tracks;
QList<RouteData> &_routes;
QList<Waypoint> &_waypoints;
};
#endif // PARSER_H

View File

@ -1,9 +1,20 @@
#include "path.h"
RectC Path::boundingRect() const
{
if (size() < 2)
return RectC();
RectC ret(first().coordinates(), first().coordinates());
for (int i = 1; i < size(); i++)
ret.unite(at(i).coordinates());
return ret;
}
QDebug operator<<(QDebug dbg, const PathPoint &point)
{
dbg.nospace() << "PathPoint(" << point.distance() << ", "
<< point.coordinates() << ")";
return dbg.maybeSpace();
return dbg.space();
}

View File

@ -2,7 +2,9 @@
#define PATH_H
#include <QVector>
#include <QRectF>
#include "coordinates.h"
#include "rectc.h"
class PathPoint
{
@ -23,6 +25,11 @@ private:
Q_DECLARE_TYPEINFO(PathPoint, Q_PRIMITIVE_TYPE);
QDebug operator<<(QDebug dbg, const PathPoint &point);
typedef QVector<PathPoint> Path;
class Path : public QVector<PathPoint>
{
public:
RectC boundingRect() const;
};
#endif // PATH_H

View File

@ -3,29 +3,49 @@
#include <QCursor>
#include <QPainter>
#include "tooltip.h"
#include "map.h"
#include "misc.h"
#include "pathitem.h"
PathItem::PathItem(const Path &path, Map *map, QGraphicsItem *parent)
: QGraphicsObject(parent)
{
Q_ASSERT(path.count() >= 2);
_path = path;
_map = map;
_digitalZoom = 0;
_width = 3;
QBrush brush(Qt::SolidPattern);
_pen = QPen(brush, _width);
updatePainterPath(map);
updateShape();
_marker = new MarkerItem(this);
_marker->setPos(position(_path.at(0).distance()));
_markerDistance = _path.at(0).distance();
setCursor(Qt::ArrowCursor);
setAcceptHoverEvents(true);
}
void PathItem::updateShape()
{
QPainterPathStroker s;
s.setWidth((_width + 1) * 1.0/scale());
_shape = s.createStroke(_path);
s.setWidth((_width + 1) * pow(2, -_digitalZoom));
_shape = s.createStroke(_painterPath);
}
PathItem::PathItem(QGraphicsItem *parent) : QGraphicsObject(parent)
void PathItem::updatePainterPath(Map *map)
{
_width = 3;
_painterPath = QPainterPath();
QBrush brush(Qt::SolidPattern);
_pen = QPen(brush, _width);
_units = Metric;
_marker = new MarkerItem(this);
setCursor(Qt::ArrowCursor);
setAcceptHoverEvents(true);
_painterPath.moveTo(map->ll2xy(_path.first().coordinates()));
for (int i = 1; i < _path.size(); i++)
_painterPath.lineTo(map->ll2xy(_path.at(i).coordinates()));
}
void PathItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option,
@ -35,7 +55,7 @@ void PathItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option,
Q_UNUSED(widget);
painter->setPen(_pen);
painter->drawPath(_path);
painter->drawPath(_painterPath);
/*
QPen p = QPen(QBrush(Qt::red), 0);
@ -44,15 +64,15 @@ void PathItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option,
*/
}
void PathItem::setScale(qreal scale)
void PathItem::setMap(Map *map)
{
_map = map;
prepareGeometryChange();
_pen.setWidthF(_width * 1.0/scale);
QGraphicsItem::setScale(scale);
_marker->setScale(1.0/scale);
updatePainterPath(map);
updateShape();
_marker->setPos(position(_markerDistance));
}
void PathItem::setColor(const QColor &color)
@ -61,12 +81,12 @@ void PathItem::setColor(const QColor &color)
update();
}
void PathItem::setWidth(int width)
void PathItem::setWidth(qreal width)
{
prepareGeometryChange();
_width = width;
_pen.setWidthF(_width * 1.0/scale());
_pen.setWidthF(_width * pow(2, -_digitalZoom));
updateShape();
}
@ -77,41 +97,47 @@ void PathItem::setStyle(Qt::PenStyle style)
update();
}
void PathItem::setUnits(enum Units units)
void PathItem::setDigitalZoom(int zoom)
{
_units = units;
prepareGeometryChange();
_digitalZoom = zoom;
_pen.setWidthF(_width * pow(2, -_digitalZoom));
_marker->setScale(pow(2, -_digitalZoom));
updateShape();
}
QPointF PathItem::position(qreal x) const
{
int low = 0;
int high = _distance.count() - 1;
int high = _path.count() - 1;
int mid = 0;
Q_ASSERT(_distance.count() == _path.elementCount());
Q_ASSERT(high > low);
Q_ASSERT(x >= _distance.at(low) && x <= _distance.at(high));
Q_ASSERT(x >= _path.at(low).distance() && x <= _path.at(high).distance());
while (low <= high) {
mid = low + ((high - low) / 2);
qreal val = _distance.at(mid);
qreal val = _path.at(mid).distance();
if (val > x)
high = mid - 1;
else if (val < x)
low = mid + 1;
else
return _path.elementAt(mid);
return _map->ll2xy(_path.at(mid).coordinates());
}
QLineF l;
qreal p1, p2;
if (_distance.at(mid) < x) {
l = QLineF(_path.elementAt(mid), _path.elementAt(mid+1));
p1 = _distance.at(mid); p2 = _distance.at(mid+1);
if (_path.at(mid).distance() < x) {
l = QLineF(_map->ll2xy(_path.at(mid).coordinates()),
_map->ll2xy(_path.at(mid+1).coordinates()));
p1 = _path.at(mid).distance(); p2 = _path.at(mid+1).distance();
} else {
l = QLineF(_path.elementAt(mid-1), _path.elementAt(mid));
p1 = _distance.at(mid-1); p2 = _distance.at(mid);
l = QLineF(_map->ll2xy(_path.at(mid-1).coordinates()),
_map->ll2xy(_path.at(mid).coordinates()));
p1 = _path.at(mid-1).distance(); p2 = _path.at(mid).distance();
}
return l.pointAt((x - p1) / (p2 - p1));
@ -119,9 +145,11 @@ QPointF PathItem::position(qreal x) const
void PathItem::moveMarker(qreal distance)
{
if (distance >= _distance.first() && distance <= _distance.last()) {
if (distance >= _path.first().distance()
&& distance <= _path.last().distance()) {
_marker->setVisible(true);
_marker->setPos(position(distance));
_markerDistance = distance;
} else
_marker->setVisible(false);
}
@ -130,7 +158,7 @@ void PathItem::hoverEnterEvent(QGraphicsSceneHoverEvent *event)
{
Q_UNUSED(event);
_pen.setWidthF((_width + 1) * 1.0/scale());
_pen.setWidthF((_width + 1) * pow(2, -_digitalZoom));
setZValue(zValue() + 1.0);
update();
@ -141,7 +169,7 @@ void PathItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *event)
{
Q_UNUSED(event);
_pen.setWidthF(_width * 1.0/scale());
_pen.setWidthF(_width * pow(2, -_digitalZoom));
setZValue(zValue() - 1.0);
update();

View File

@ -4,28 +4,31 @@
#include <QGraphicsObject>
#include <QPen>
#include "markeritem.h"
#include "units.h"
#include "path.h"
class Map;
class PathItem : public QGraphicsObject
{
Q_OBJECT
public:
PathItem(QGraphicsItem *parent = 0);
PathItem(const Path &path, Map *map, QGraphicsItem *parent = 0);
QPainterPath shape() const {return _shape;}
QRectF boundingRect() const {return _shape.boundingRect();}
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option,
QWidget *widget);
const QPainterPath &path() const {return _path;}
void showMarker(bool show) {_marker->setVisible(show);}
void setScale(qreal scale);
void setUnits(enum Units units);
const Path &path() const {return _path;}
void setMap(Map *map);
void setColor(const QColor &color);
void setWidth(int width);
void setWidth(qreal width);
void setStyle(Qt::PenStyle style);
void setDigitalZoom(int zoom);
public slots:
void moveMarker(qreal distance);
@ -34,22 +37,25 @@ signals:
void selected(bool);
protected:
void updateShape();
QVector<qreal> _distance;
QPainterPath _path;
Path _path;
MarkerItem *_marker;
Units _units;
private:
QPointF position(qreal distance) const;
void updatePainterPath(Map *map);
void updateShape();
void hoverEnterEvent(QGraphicsSceneHoverEvent *event);
void hoverLeaveEvent(QGraphicsSceneHoverEvent *event);
int _width;
Map *_map;
qreal _markerDistance;
int _digitalZoom;
qreal _width;
QPen _pen;
QPainterPath _shape;
QPainterPath _painterPath;
};
#endif // PATHITEM_H

View File

@ -1,9 +1,10 @@
#include <QGraphicsView>
#include <QGraphicsScene>
#include <QWheelEvent>
#include <QApplication>
#include <QPixmapCache>
#include "opengl.h"
#include "rd.h"
#include "wgs84.h"
#include "misc.h"
#include "poi.h"
#include "data.h"
#include "map.h"
@ -11,84 +12,21 @@
#include "routeitem.h"
#include "waypointitem.h"
#include "scaleitem.h"
#include "keys.h"
#include "pathview.h"
#define ZOOM_MAX 18
#define ZOOM_MIN 3
#define MARGIN 10.0
#define SCALE_OFFSET 7
#define MAX_DIGITAL_ZOOM 1
#define MIN_DIGITAL_ZOOM -3
#define MARGIN 10.0
#define SCALE_OFFSET 7
static QPoint mercator2tile(const QPointF &m, int z)
PathView::PathView(Map *map, POI *poi, QWidget *parent)
: QGraphicsView(parent)
{
QPoint tile;
Q_ASSERT(map != 0);
Q_ASSERT(poi != 0);
tile.setX((int)(floor((m.x() + 180.0) / 360.0 * (1<<z))));
tile.setY((int)(floor((1.0 - (m.y() / 180.0)) / 2.0 * (1<<z))));
return tile;
}
static QPointF tile2mercator(const QPoint &tile, int z)
{
QPointF m;
m.setX(((360.0 * tile.x()) / (qreal)(1<<z)) - 180.0);
m.setY((1.0 - (2.0 * tile.y()) / (qreal)(1<<z)) * 180.0);
return m;
}
static int scale2zoom(qreal scale)
{
int zoom = (int)log2(360.0/(scale * (qreal)Tile::size()));
if (zoom < ZOOM_MIN)
return ZOOM_MIN;
if (zoom > ZOOM_MAX)
return ZOOM_MAX;
return zoom;
}
qreal mapScale(int zoom)
{
return ((360.0/(qreal)(1<<zoom))/(qreal)Tile::size());
}
static QRectF mapBounds()
{
return QRectF(QPointF(-180, -180), QSizeF(360, 360));
}
static qreal zoom2resolution(int zoom, qreal y)
{
return (WGS84_RADIUS * 2 * M_PI / Tile::size()
* cos(2.0 * atan(exp(deg2rad(y))) - M_PI/2)) / (qreal)(1<<zoom);
}
static void unite(QRectF &rect, const QPointF &p)
{
if (p.x() < rect.left())
rect.setLeft(p.x());
if (p.x() > rect.right())
rect.setRight(p.x());
if (p.y() > rect.bottom())
rect.setBottom(p.y());
if (p.y() < rect.top())
rect.setTop(p.y());
}
static QRectF scaled(const QRectF &rect, qreal factor)
{
return QRectF(QPointF(rect.left() * factor, rect.top() * factor),
QSizeF(rect.width() * factor, rect.height() * factor));
}
PathView::PathView(QWidget *parent)
: QGraphicsView(parent)
{
_scene = new QGraphicsScene(this);
setScene(_scene);
setCacheMode(QGraphicsView::CacheBackground);
@ -102,13 +40,15 @@ PathView::PathView(QWidget *parent)
_mapScale = new ScaleItem();
_mapScale->setZValue(2.0);
_zoom = ZOOM_MAX;
_res = 1.0;
_map = 0;
_poi = 0;
_map = map;
_poi = poi;
connect(_map, SIGNAL(loaded()), this, SLOT(redraw()));
connect(_poi, SIGNAL(pointsChanged()), this, SLOT(updatePOI()));
_units = Metric;
_opacity = 1.0;
_showMap = true;
_showTracks = true;
_showRoutes = true;
_showWaypoints = true;
@ -123,8 +63,10 @@ PathView::PathView(QWidget *parent)
_routeStyle = Qt::DashLine;
_plot = false;
_digitalZoom = 0;
_scene->setSceneRect(scaled(mapBounds(), 1.0 / mapScale(_zoom)));
_scene->setSceneRect(_map->bounds());
_res = _map->resolution(_scene->sceneRect().center());
}
PathView::~PathView()
@ -140,19 +82,18 @@ PathItem *PathView::addTrack(const Track &track)
return 0;
}
TrackItem *ti = new TrackItem(track);
TrackItem *ti = new TrackItem(track, _map);
_tracks.append(ti);
_tr |= ti->path().boundingRect();
_zoom = scale2zoom(contentsScale());
ti->setScale(1.0/mapScale(_zoom));
ti->setColor(_palette.nextColor());
ti->setWidth(_trackWidth);
ti->setStyle(_trackStyle);
ti->setUnits(_units);
ti->setVisible(_showTracks);
ti->setDigitalZoom(_digitalZoom);
_scene->addItem(ti);
if (_poi)
addPOI(_poi->points(ti));
addPOI(_poi->points(ti->path()));
return ti;
}
@ -164,74 +105,66 @@ PathItem *PathView::addRoute(const Route &route)
return 0;
}
RouteItem *ri = new RouteItem(route);
RouteItem *ri = new RouteItem(route, _map);
_routes.append(ri);
_rr |= ri->path().boundingRect();
_zoom = scale2zoom(contentsScale());
ri->setScale(1.0/mapScale(_zoom));
ri->setColor(_palette.nextColor());
ri->setWidth(_routeWidth);
ri->setStyle(_routeStyle);
ri->setUnits(_units);
ri->setVisible(_showRoutes);
ri->showWaypoints(_showRouteWaypoints);
ri->showWaypointLabels(_showWaypointLabels);
ri->setDigitalZoom(_digitalZoom);
_scene->addItem(ri);
if (_poi)
addPOI(_poi->points(ri));
addPOI(_poi->points(ri->path()));
return ri;
}
void PathView::addWaypoints(const QList<Waypoint> &waypoints)
{
qreal scale = mapScale(_zoom);
for (int i = 0; i < waypoints.count(); i++) {
const Waypoint &w = waypoints.at(i);
WaypointItem *wi = new WaypointItem(w);
WaypointItem *wi = new WaypointItem(w, _map);
_waypoints.append(wi);
updateWaypointsBoundingRect(wi->coordinates());
wi->setScale(1.0/scale);
updateWaypointsBoundingRect(wi->waypoint().coordinates());
wi->setZValue(1);
wi->showLabel(_showWaypointLabels);
wi->setUnits(_units);
wi->setVisible(_showWaypoints);
wi->setDigitalZoom(_digitalZoom);
_scene->addItem(wi);
}
if (_poi)
addPOI(_poi->points(waypoints));
_zoom = scale2zoom(contentsScale());
addPOI(_poi->points(waypoints));
}
QList<PathItem *> PathView::loadData(const Data &data)
{
QList<PathItem *> paths;
int zoom = _zoom;
qreal zoom = _map->zoom();
for (int i = 0; i < data.tracks().count(); i++)
paths.append(addTrack(*(data.tracks().at(i))));
for (int i = 0; i < data.routes().count(); i++)
paths.append(addRoute(*(data.routes().at(i))));
addWaypoints(data.waypoints());
if (_tracks.empty() && _routes.empty() && _waypoints.empty())
return paths;
if (_zoom < zoom)
rescale(_zoom);
if (mapZoom() != zoom)
rescale();
else
updatePOIVisibility();
QPointF center = contentsCenter();
QPointF center = contentCenter();
centerOn(center);
_res = zoom2resolution(_zoom, -(center.y() * mapScale(_zoom)));
_res = _map->resolution(center);
_mapScale->setResolution(_res);
if (_mapScale->scene() != _scene)
_scene->addItem(_mapScale);
@ -239,51 +172,31 @@ QList<PathItem *> PathView::loadData(const Data &data)
return paths;
}
void PathView::updateWaypointsBoundingRect(const QPointF &wp)
void PathView::updateWaypointsBoundingRect(const Coordinates &wp)
{
if (_wr.isNull()) {
if (_wp.isNull())
_wp = wp;
else {
_wr = QRectF(_wp, wp).normalized();
_wp = QPointF();
}
} else
unite(_wr, wp);
}
qreal PathView::contentsScale() const
{
QRectF br = _tr | _rr | _wr;
if (!br.isNull() && !_wp.isNull())
unite(br, _wp);
if (br.isNull())
return mapScale(ZOOM_MAX);
QPointF sc(br.width() / (viewport()->width() - MARGIN/2),
br.height() / (viewport()->height() - MARGIN/2));
return qMax(sc.x(), sc.y());
}
QPointF PathView::contentsCenter() const
{
QRectF br = _tr | _rr | _wr;
if (!br.isNull() && !_wp.isNull())
unite(br, _wp);
qreal scale = mapScale(_zoom);
if (br.isNull())
return _wp / scale;
if (_wr.isNull())
_wr = RectC(wp, wp);
else
return scaled(br, 1.0/scale).center();
_wr.unite(wp);
}
qreal PathView::mapZoom() const
{
RectC br = _tr | _rr | _wr;
return _map->zoomFit(viewport()->size() - QSize(2*MARGIN, 2*MARGIN), br);
}
QPointF PathView::contentCenter() const
{
RectC br = _tr | _rr | _wr;
return _map->ll2xy(br.center());
}
void PathView::updatePOIVisibility()
{
QHash<Waypoint, WaypointItem*>::const_iterator it, jt;
QHash<SearchPointer<Waypoint>, WaypointItem*>::const_iterator it, jt;
if (!_showPOI)
return;
@ -302,25 +215,21 @@ void PathView::updatePOIVisibility()
}
}
void PathView::rescale(int zoom)
void PathView::rescale()
{
_zoom = zoom;
qreal scale = mapScale(zoom);
_scene->setSceneRect(scaled(mapBounds(), 1.0 / scale));
_scene->setSceneRect(_map->bounds());
resetCachedContent();
for (int i = 0; i < _tracks.size(); i++)
_tracks.at(i)->setScale(1.0/scale);
_tracks.at(i)->setMap(_map);
for (int i = 0; i < _routes.size(); i++)
_routes.at(i)->setScale(1.0/scale);
_routes.at(i)->setMap(_map);
for (int i = 0; i < _waypoints.size(); i++)
_waypoints.at(i)->setScale(1.0/scale);
_waypoints.at(i)->setMap(_map);
QHash<Waypoint, WaypointItem*>::const_iterator it;
QHash<SearchPointer<Waypoint>, WaypointItem*>::const_iterator it;
for (it = _pois.constBegin(); it != _pois.constEnd(); it++)
it.value()->setScale(1.0/scale);
it.value()->setMap(_map);
updatePOIVisibility();
}
@ -336,22 +245,59 @@ void PathView::setPalette(const Palette &palette)
_routes.at(i)->setColor(_palette.nextColor());
}
void PathView::setMap(Map *map)
{
QPointF pos = mapToScene(viewport()->rect().center());
Coordinates center = _map->xy2ll(pos);
qreal resolution = _map->resolution(pos);
_map->unload();
disconnect(_map, SIGNAL(loaded()), this, SLOT(redraw()));
_map = map;
_map->load();
connect(_map, SIGNAL(loaded()), this, SLOT(redraw()));
resetDigitalZoom();
_map->zoomFit(resolution, center);
_scene->setSceneRect(_map->bounds());
for (int i = 0; i < _tracks.size(); i++)
_tracks.at(i)->setMap(map);
for (int i = 0; i < _routes.size(); i++)
_routes.at(i)->setMap(map);
for (int i = 0; i < _waypoints.size(); i++)
_waypoints.at(i)->setMap(map);
QHash<SearchPointer<Waypoint>, WaypointItem*>::const_iterator it;
for (it = _pois.constBegin(); it != _pois.constEnd(); it++)
it.value()->setMap(_map);
updatePOIVisibility();
pos = _map->ll2xy(center);
centerOn(pos);
_res = _map->resolution(pos);
_mapScale->setResolution(_res);
resetCachedContent();
QPixmapCache::clear();
}
void PathView::setPOI(POI *poi)
{
if (_poi)
disconnect(_poi, SIGNAL(pointsChanged()), this, SLOT(updatePOI()));
disconnect(_poi, SIGNAL(pointsChanged()), this, SLOT(updatePOI()));
connect(poi, SIGNAL(pointsChanged()), this, SLOT(updatePOI()));
_poi = poi;
if (_poi)
connect(_poi, SIGNAL(pointsChanged()), this, SLOT(updatePOI()));
updatePOI();
}
void PathView::updatePOI()
{
QHash<Waypoint, WaypointItem*>::const_iterator it;
QHash<SearchPointer<Waypoint>, WaypointItem*>::const_iterator it;
for (it = _pois.constBegin(); it != _pois.constEnd(); it++) {
_scene->removeItem(it.value());
@ -359,13 +305,10 @@ void PathView::updatePOI()
}
_pois.clear();
if (!_poi)
return;
for (int i = 0; i < _tracks.size(); i++)
addPOI(_poi->points(_tracks.at(i)));
addPOI(_poi->points(_tracks.at(i)->path()));
for (int i = 0; i < _routes.size(); i++)
addPOI(_poi->points(_routes.at(i)));
addPOI(_poi->points(_routes.at(i)->path()));
addPOI(_poi->points(_waypoints));
updatePOIVisibility();
@ -373,38 +316,23 @@ void PathView::updatePOI()
void PathView::addPOI(const QVector<Waypoint> &waypoints)
{
qreal scale = mapScale(_zoom);
for (int i = 0; i < waypoints.size(); i++) {
const Waypoint &w = waypoints.at(i);
if (_pois.contains(w))
if (_pois.contains(SearchPointer<Waypoint>(&w)))
continue;
WaypointItem *pi = new WaypointItem(w);
pi->setScale(1.0/scale);
WaypointItem *pi = new WaypointItem(w, _map);
pi->setZValue(1);
pi->showLabel(_showPOILabels);
pi->setVisible(_showPOI);
pi->setDigitalZoom(_digitalZoom);
_scene->addItem(pi);
_pois.insert(w, pi);
_pois.insert(SearchPointer<Waypoint>(&(pi->waypoint())), pi);
}
}
void PathView::setMap(Map *map)
{
if (_map)
disconnect(_map, SIGNAL(loaded()), this, SLOT(redraw()));
_map = map;
if (_map)
connect(_map, SIGNAL(loaded()), this, SLOT(redraw()));
resetCachedContent();
}
void PathView::setUnits(enum Units units)
{
_units = units;
@ -418,7 +346,7 @@ void PathView::setUnits(enum Units units)
for (int i = 0; i < _waypoints.size(); i++)
_waypoints.at(i)->setUnits(units);
QHash<Waypoint, WaypointItem*>::const_iterator it;
QHash<SearchPointer<Waypoint>, WaypointItem*>::const_iterator it;
for (it = _pois.constBegin(); it != _pois.constEnd(); it++)
it.value()->setUnits(units);
}
@ -428,34 +356,88 @@ void PathView::redraw()
resetCachedContent();
}
void PathView::zoom(int z, const QPoint &pos)
void PathView::resetDigitalZoom()
{
if (_tracks.isEmpty() && _routes.isEmpty() && _waypoints.isEmpty())
return;
QHash<SearchPointer<Waypoint>, WaypointItem*>::const_iterator it;
QPoint offset = pos - viewport()->rect().center();
QPointF spos = mapToScene(pos);
_digitalZoom = 0;
resetTransform();
qreal os = mapScale(_zoom);
_zoom = z;
for (int i = 0; i < _tracks.size(); i++)
_tracks.at(i)->setDigitalZoom(0);
for (int i = 0; i < _routes.size(); i++)
_routes.at(i)->setDigitalZoom(0);
for (int i = 0; i < _waypoints.size(); i++)
_waypoints.at(i)->setDigitalZoom(0);
for (it = _pois.constBegin(); it != _pois.constEnd(); it++)
it.value()->setDigitalZoom(0);
rescale(_zoom);
_mapScale->setDigitalZoom(0);
}
QPointF center = (spos * (os/mapScale(_zoom))) - offset;
centerOn(center);
void PathView::digitalZoom(int zoom)
{
QHash<SearchPointer<Waypoint>, WaypointItem*>::const_iterator it;
_res = zoom2resolution(_zoom, -(center.y() * mapScale(_zoom)));
_mapScale->setResolution(_res);
_digitalZoom += zoom;
scale(pow(2, zoom), pow(2, zoom));
resetCachedContent();
for (int i = 0; i < _tracks.size(); i++)
_tracks.at(i)->setDigitalZoom(_digitalZoom);
for (int i = 0; i < _routes.size(); i++)
_routes.at(i)->setDigitalZoom(_digitalZoom);
for (int i = 0; i < _waypoints.size(); i++)
_waypoints.at(i)->setDigitalZoom(_digitalZoom);
for (it = _pois.constBegin(); it != _pois.constEnd(); it++)
it.value()->setDigitalZoom(_digitalZoom);
_mapScale->setDigitalZoom(_digitalZoom);
}
void PathView::zoom(int zoom, const QPoint &pos, const Coordinates &c)
{
bool shift = QApplication::keyboardModifiers() & Qt::ShiftModifier;
if (_digitalZoom) {
if (((_digitalZoom > 0 && zoom > 0) && (!shift || _digitalZoom
>= MAX_DIGITAL_ZOOM)) || ((_digitalZoom < 0 && zoom < 0) && (!shift
|| _digitalZoom <= MIN_DIGITAL_ZOOM)))
return;
digitalZoom(zoom);
} else {
qreal os, ns;
os = _map->zoom();
ns = (zoom > 0) ? _map->zoomIn() : _map->zoomOut();
if (ns != os) {
QPoint offset = pos - viewport()->rect().center();
rescale();
QPointF center = _map->ll2xy(c) - offset;
centerOn(center);
_res = _map->resolution(center);
_mapScale->setResolution(_res);
} else {
if (shift)
digitalZoom(zoom);
}
}
}
void PathView::wheelEvent(QWheelEvent *event)
{
int z = (event->delta() > 0) ?
qMin(_zoom + 1, ZOOM_MAX) : qMax(_zoom - 1, ZOOM_MIN);
static int deg = 0;
zoom(z, event->pos());
deg += event->delta() / 8;
if (qAbs(deg) < 15)
return;
deg = 0;
Coordinates c = _map->xy2ll(mapToScene(event->pos()));
zoom((event->delta() > 0) ? 1 : -1, event->pos(), c);
}
void PathView::mouseDoubleClickEvent(QMouseEvent *event)
@ -463,37 +445,49 @@ void PathView::mouseDoubleClickEvent(QMouseEvent *event)
if (event->button() != Qt::LeftButton && event->button() != Qt::RightButton)
return;
int z = (event->button() == Qt::LeftButton) ?
qMin(_zoom + 1, ZOOM_MAX) : qMax(_zoom - 1, ZOOM_MIN);
zoom(z, event->pos());
Coordinates c = _map->xy2ll(mapToScene(event->pos()));
zoom((event->button() == Qt::LeftButton) ? 1 : -1, event->pos(), c);
}
void PathView::keyPressEvent(QKeyEvent *event)
{
int z = -1;
int z;
if (event->matches(QKeySequence::ZoomIn))
z = qMin(_zoom + 1, ZOOM_MAX);
if (event->matches(QKeySequence::ZoomOut))
z = qMax(_zoom - 1, ZOOM_MIN);
QPoint pos = viewport()->rect().center();
Coordinates c = _map->xy2ll(mapToScene(pos));
if (z >= 0)
zoom(z, QRect(QPoint(), size()).center());
else
QWidget::keyPressEvent(event);
if (event->matches(ZOOM_IN))
z = 1;
else if (event->matches(ZOOM_OUT))
z = -1;
else if (_digitalZoom && event->key() == Qt::Key_Escape) {
resetDigitalZoom();
return;
} else {
QGraphicsView::keyPressEvent(event);
return;
}
zoom(z, pos, c);
}
void PathView::plot(QPainter *painter, const QRectF &target)
void PathView::plot(QPainter *painter, const QRectF &target, bool hires)
{
QRect orig, adj;
qreal ratio, diff;
qreal ratio, diff, origRes;
QPointF origScene, origPos;
Coordinates origLL;
setUpdatesEnabled(false);
_plot = true;
_map->setBlockingMode(true);
orig = viewport()->rect();
origPos = _mapScale->pos();
if (orig.height() * (target.width() / target.height()) - orig.width() < 0) {
ratio = target.height()/target.width();
ratio = target.height() / target.width();
diff = (orig.width() * ratio) - orig.height();
adj = orig.adjusted(0, -diff/2, 0, diff/2);
} else {
@ -502,18 +496,48 @@ void PathView::plot(QPainter *painter, const QRectF &target)
adj = orig.adjusted(-diff/2, 0, diff/2, 0);
}
setUpdatesEnabled(false);
_plot = true;
// Adjust the view for printing
if (hires) {
origScene = mapToScene(orig.center());
origLL = _map->xy2ll(origScene);
origRes = _map->resolution(origScene);
QPointF pos = _mapScale->pos();
_mapScale->setPos(mapToScene(QPoint(adj.bottomRight() + QPoint(
-(SCALE_OFFSET + _mapScale->boundingRect().width()),
-(SCALE_OFFSET + _mapScale->boundingRect().height())))));
QPointF s(painter->device()->logicalDpiX()
/ (qreal)metric(QPaintDevice::PdmDpiX),
painter->device()->logicalDpiY()
/ (qreal)metric(QPaintDevice::PdmDpiY));
adj = QRect(0, 0, adj.width() * s.x(), adj.height() * s.y());
_map->zoomFit(adj.size(), _tr | _rr | _wr);
rescale();
QPointF center = contentCenter();
centerOn(center);
adj.moveCenter(mapFromScene(center));
_mapScale->setResolution(_map->resolution(_map->ll2xy(origLL)));
_mapScale->setDigitalZoom(-log2(s.x()));
_mapScale->setPos(mapToScene(QPoint(adj.bottomRight() + QPoint(
-(SCALE_OFFSET + _mapScale->boundingRect().width()) * s.x(),
-(SCALE_OFFSET + _mapScale->boundingRect().height()) * s.x()))));
} else {
_mapScale->setPos(mapToScene(QPoint(adj.bottomRight() + QPoint(
-(SCALE_OFFSET + _mapScale->boundingRect().width()),
-(SCALE_OFFSET + _mapScale->boundingRect().height())))));
}
// Print the view
render(painter, target, adj);
_mapScale->setPos(pos);
// Revert view changes to display mode
if (hires) {
_map->zoomFit(origRes, origLL);
rescale();
centerOn(origScene);
_mapScale->setDigitalZoom(0);
_mapScale->setResolution(origRes);
}
_mapScale->setPos(origPos);
_map->setBlockingMode(false);
_plot = false;
setUpdatesEnabled(true);
}
@ -530,12 +554,13 @@ void PathView::clear()
_scene->clear();
_palette.reset();
_zoom = ZOOM_MAX;
_res = 1.0;
_tr = QRectF(); _rr = QRectF(); _wr = QRectF();
_wp = QPointF();
_tr = RectC();
_rr = RectC();
_wr = RectC();
_scene->setSceneRect(scaled(mapBounds(), 1.0 / mapScale(_zoom)));
resetDigitalZoom();
resetCachedContent();
QPixmapCache::clear();
}
void PathView::showTracks(bool show)
@ -581,11 +606,17 @@ void PathView::showRouteWaypoints(bool show)
_routes.at(i)->showWaypoints(show);
}
void PathView::showMap(bool show)
{
_showMap = show;
resetCachedContent();
}
void PathView::showPOI(bool show)
{
_showPOI = show;
QHash<Waypoint, WaypointItem*>::const_iterator it;
QHash<SearchPointer<Waypoint>, WaypointItem*>::const_iterator it;
for (it = _pois.constBegin(); it != _pois.constEnd(); it++)
it.value()->setVisible(show);
@ -596,7 +627,7 @@ void PathView::showPOILabels(bool show)
{
_showPOILabels = show;
QHash<Waypoint, WaypointItem*>::const_iterator it;
QHash<SearchPointer<Waypoint>, WaypointItem*>::const_iterator it;
for (it = _pois.constBegin(); it != _pois.constEnd(); it++)
it.value()->showLabel(show);
@ -642,56 +673,37 @@ void PathView::setRouteStyle(Qt::PenStyle style)
_routes.at(i)->setStyle(style);
}
void PathView::setMapOpacity(int opacity)
{
_opacity = opacity / 100.0;
resetCachedContent();
}
void PathView::drawBackground(QPainter *painter, const QRectF &rect)
{
if ((_tracks.isEmpty() && _routes.isEmpty() && _waypoints.isEmpty())
|| !_map) {
if (_showMap) {
if (_opacity < 1.0) {
painter->fillRect(rect, Qt::white);
painter->setOpacity(_opacity);
}
_map->draw(painter, rect);
} else
painter->fillRect(rect, Qt::white);
return;
}
qreal scale = mapScale(_zoom);
QRectF rr(rect.topLeft() * scale, rect.size());
QPoint tile = mercator2tile(QPointF(rr.topLeft().x(), -rr.topLeft().y()),
_zoom);
QPointF tm = tile2mercator(tile, _zoom);
QPoint tl = QPoint((int)(tm.x() / scale), (int)(-tm.y() / scale));
QList<Tile> tiles;
QSizeF s(rect.right() - tl.x(), rect.bottom() - tl.y());
for (int i = 0; i < ceil(s.width() / Tile::size()); i++)
for (int j = 0; j < ceil(s.height() / Tile::size()); j++)
tiles.append(Tile(QPoint(tile.x() + i, tile.y() + j), _zoom));
_map->loadTiles(tiles, _plot);
for (int i = 0; i < tiles.count(); i++) {
Tile &t = tiles[i];
QPoint tp(tl.x() + (t.xy().x() - tile.x()) * Tile::size(),
tl.y() + (t.xy().y() - tile.y()) * Tile::size());
painter->drawPixmap(tp, t.pixmap());
}
}
void PathView::resizeEvent(QResizeEvent *event)
{
Q_UNUSED(event);
qreal zoom = _map->zoom();
if (mapZoom() != zoom)
rescale();
if (_tracks.isEmpty() && _routes.isEmpty() && _waypoints.isEmpty())
return;
int zoom = scale2zoom(contentsScale());
if (zoom != _zoom)
rescale(zoom);
QPointF center = contentsCenter();
QPointF center = contentCenter();
centerOn(center);
_res = zoom2resolution(_zoom, -(center.y() * mapScale(_zoom)));
_res = _map->resolution(center);
_mapScale->setResolution(_res);
resetCachedContent();
QGraphicsView::resizeEvent(event);
}
void PathView::paintEvent(QPaintEvent *event)
@ -710,7 +722,7 @@ void PathView::scrollContentsBy(int dx, int dy)
QGraphicsView::scrollContentsBy(dx, dy);
QPointF center = mapToScene(viewport()->rect().center());
qreal res = zoom2resolution(_zoom, -(center.y() * mapScale(_zoom)));
qreal res = _map->resolution(center);
if (qMax(res, _res) / qMin(res, _res) > 1.1) {
_mapScale->setResolution(res);

View File

@ -8,6 +8,8 @@
#include "units.h"
#include "palette.h"
#include "waypoint.h"
#include "rectc.h"
#include "searchpointer.h"
class Data;
class POI;
@ -25,7 +27,7 @@ class PathView : public QGraphicsView
Q_OBJECT
public:
PathView(QWidget *parent = 0);
PathView(Map *map, POI *poi, QWidget *parent = 0);
~PathView();
QList<PathItem*> loadData(const Data &data);
@ -35,7 +37,7 @@ public:
void setMap(Map *map);
void setUnits(enum Units units);
void plot(QPainter *painter, const QRectF &target);
void plot(QPainter *painter, const QRectF &target, bool hires);
int trackCount() const {return _tracks.count();}
int routeCount() const {return _routes.count();}
@ -48,6 +50,7 @@ public:
public slots:
void redraw();
void showMap(bool show);
void showPOI(bool show);
void setPOIOverlap(bool overlap);
void showWaypointLabels(bool show);
@ -60,6 +63,7 @@ public slots:
void setRouteWidth(int width);
void setTrackStyle(Qt::PenStyle style);
void setRouteStyle(Qt::PenStyle style);
void setMapOpacity(int opacity);
private slots:
void updatePOI();
@ -72,12 +76,14 @@ private:
void loadPOI();
void clearPOI();
qreal contentsScale() const;
QPointF contentsCenter() const;
void rescale(int zoom);
void zoom(int z, const QPoint &pos);
qreal mapZoom() const;
QPointF contentCenter() const;
void rescale();
void zoom(int zoom, const QPoint &pos, const Coordinates &c);
void digitalZoom(int zoom);
void resetDigitalZoom();
void updatePOIVisibility();
void updateWaypointsBoundingRect(const QPointF &wp);
void updateWaypointsBoundingRect(const Coordinates &wp);
void mouseDoubleClickEvent(QMouseEvent *event);
void wheelEvent(QWheelEvent *event);
@ -92,18 +98,18 @@ private:
QList<TrackItem*> _tracks;
QList<RouteItem*> _routes;
QList<WaypointItem*> _waypoints;
QHash<Waypoint, WaypointItem*> _pois;
QHash<SearchPointer<Waypoint>, WaypointItem*> _pois;
int _zoom;
QRectF _tr, _rr, _wr;
QPointF _wp;
RectC _tr, _rr, _wr;
qreal _res;
Map *_map;
POI *_poi;
Palette _palette;
Units _units;
qreal _opacity;
bool _showMap;
bool _showTracks;
bool _showRoutes;
bool _showWaypoints;
@ -117,6 +123,7 @@ private:
Qt::PenStyle _trackStyle;
Qt::PenStyle _routeStyle;
int _digitalZoom;
bool _plot;
};

48
src/percentslider.cpp Normal file
View File

@ -0,0 +1,48 @@
#include <QSlider>
#include <QLabel>
#include <QHBoxLayout>
#include "units.h"
#include "percentslider.h"
static QString format(int value)
{
return QString::number(value) + UNIT_SPACE + QString("%");
}
PercentSlider::PercentSlider(QWidget *parent) : QWidget(parent)
{
_slider = new QSlider(Qt::Horizontal);
_label = new QLabel();
_slider->setMinimum(0);
_slider->setMaximum(100);
QFontMetrics fm(_label->font());
_label->setFixedWidth(fm.boundingRect(format(_slider->maximum())).width());
_label->setAlignment(Qt::AlignRight);
connect(_slider, SIGNAL(sliderMoved(int)), this, SLOT(updateLabel(int)));
QHBoxLayout *layout = new QHBoxLayout();
layout->addWidget(_slider);
layout->addWidget(_label);
setLayout(layout);
}
void PercentSlider::updateLabel(int value)
{
_label->setText(format(value));
}
int PercentSlider::value() const
{
return _slider->value();
}
void PercentSlider::setValue(int value)
{
_slider->setValue(value);
_label->setText(format(value));
}

29
src/percentslider.h Normal file
View File

@ -0,0 +1,29 @@
#ifndef PERCENTSLIDER_H
#define PERCENTSLIDER_H
#include <QWidget>
class QSlider;
class QLabel;
class PercentSlider : public QWidget
{
Q_OBJECT
public:
PercentSlider(QWidget *parent = 0);
int value() const;
public slots:
void setValue(int value);
private slots:
void updateLabel(int value);
private:
QSlider *_slider;
QLabel *_label;
};
#endif // PERCENTSLIDER_H

View File

@ -58,18 +58,15 @@ static bool cb(size_t data, void* context)
return true;
}
QVector<Waypoint> POI::points(const PathItem *path) const
QVector<Waypoint> POI::points(const Path &path) const
{
QVector<Waypoint> ret;
QSet<int> set;
qreal min[2], max[2];
const QPainterPath &pp = path->path();
for (int i = 0; i < pp.elementCount(); i++) {
const QPainterPath::Element &pe = pp.elementAt(i);
Coordinates p = Coordinates::fromMercator(QPointF(pe.x, -pe.y));
QPair<Coordinates, Coordinates> br = p.boundingRect(_radius);
for (int i = 0; i < path.count(); i++) {
const Coordinates &c = path.at(i).coordinates();
QPair<Coordinates, Coordinates> br = c.boundingRect(_radius);
min[0] = br.first.lon();
min[1] = br.first.lat();
max[0] = br.second.lon();

View File

@ -7,8 +7,8 @@
#include <QStringList>
#include "waypoint.h"
#include "rtree.h"
#include "path.h"
class PathItem;
class WaypointItem;
class POI : public QObject
@ -25,7 +25,7 @@ public:
unsigned radius() const {return _radius;}
void setRadius(unsigned radius);
QVector<Waypoint> points(const PathItem *path) const;
QVector<Waypoint> points(const Path &path) const;
QVector<Waypoint> points(const QList<WaypointItem*> &list) const;
QVector<Waypoint> points(const QList<Waypoint> &list) const;
@ -38,11 +38,11 @@ signals:
private:
typedef RTree<size_t, qreal, 2> POITree;
typedef struct {
struct FileIndex {
int start;
int end;
bool enabled;
} FileIndex;
};
POITree _tree;
QVector<Waypoint> _data;

15
src/projection.h Normal file
View File

@ -0,0 +1,15 @@
#ifndef PROJECTION_H
#define PROJECTION_H
#include <QPointF>
#include "coordinates.h"
class Projection {
public:
virtual ~Projection() {}
virtual QPointF ll2xy(const Coordinates &c) const = 0;
virtual Coordinates xy2ll(const QPointF &p) const = 0;
};
#endif // PROJECTION_H

View File

@ -11,5 +11,5 @@ void RangeF::resize(qreal size)
QDebug operator<<(QDebug dbg, const RangeF &range)
{
dbg.nospace() << "RangeF(" << range.min() << ", " << range.max() << ")";
return dbg.maybeSpace();
return dbg.space();
}

63
src/rectc.cpp Normal file
View File

@ -0,0 +1,63 @@
#include "rectc.h"
RectC RectC::operator|(const RectC &r) const
{
if (isNull())
return r;
if (r.isNull())
return *this;
qreal l1 = _tl.lon();
qreal r1 = _tl.lon();
if (_br.lon() - _tl.lon() < 0)
l1 = _br.lon();
else
r1 = _br.lon();
qreal l2 = r._tl.lon();
qreal r2 = r._tl.lon();
if (r._br.lon() - r._tl.lon() < 0)
l2 = r._br.lon();
else
r2 = r._br.lon();
qreal t1 = _tl.lat();
qreal b1 = _tl.lat();
if (_br.lat() - _tl.lat() < 0)
t1 = _br.lat();
else
b1 = _br.lat();
qreal t2 = r._tl.lat();
qreal b2 = r._tl.lat();
if (r._br.lat() - r._tl.lat() < 0)
t2 = r._br.lat();
else
b2 = r._br.lat();
RectC tmp;
tmp._tl.setLon(qMin(l1, l2));
tmp._br.setLon(qMax(r1, r2));
tmp._tl.setLat(qMin(t1, t2));
tmp._br.setLat(qMax(b1, b2));
return tmp;
}
void RectC::unite(const Coordinates &c)
{
if (c.lon() < _tl.lon())
_tl.setLon(c.lon());
if (c.lon() > _br.lon())
_br.setLon(c.lon());
if (c.lat() > _br.lat())
_br.setLat(c.lat());
if (c.lat() < _tl.lat())
_tl.setLat(c.lat());
}
QDebug operator<<(QDebug dbg, const RectC &rect)
{
dbg.nospace() << "RectC(" << rect.topLeft() << ", " << rect.size() << ")";
return dbg.space();
}

42
src/rectc.h Normal file
View File

@ -0,0 +1,42 @@
#ifndef RECTC_H
#define RECTC_H
#include <QDebug>
#include <QSizeF>
#include "coordinates.h"
class RectC
{
public:
RectC() {}
RectC(const Coordinates &topLeft, const Coordinates &bottomRight)
: _tl(topLeft), _br(bottomRight) {}
bool isNull() const
{return _tl.isNull() && _br.isNull();}
bool isValid() const
{return (_tl.isValid() && _br.isValid() && _tl != _br);}
Coordinates topLeft() const {return _tl;}
Coordinates bottomRight() const {return _br;}
Coordinates center() const
{return Coordinates((_tl.lon() + _br.lon()) / 2.0,
(_tl.lat() + _br.lat()) / 2.0);}
qreal width() const {return _br.lon() - _tl.lon();}
qreal height() const {return _br.lat() - _tl.lat();}
QSizeF size() const {return QSizeF(width(), height());}
RectC operator|(const RectC &r) const;
RectC &operator|=(const RectC &r) {*this = *this | r; return *this;}
void unite(const Coordinates &c);
private:
Coordinates _tl, _br;
};
QDebug operator<<(QDebug dbg, const RectC &rect);
#endif // RECTC_H

View File

@ -11,6 +11,16 @@ Route::Route(const RouteData &data) : _data(data)
}
}
Path Route::path() const
{
Path ret;
for (int i = 0; i < _data.size(); i++)
ret.append(PathPoint(_data.at(i).coordinates(), _distance.at(i)));
return ret;
}
Graph Route::elevation() const
{
Graph graph;

Some files were not shown because too many files have changed in this diff Show More