Class: MainDlg

Inherits:
Qt::Widget
  • Object
show all
Defined in:
lib/main-dlg-impl.rb

Overview

Class MainDlg ############################################

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(parent, arg) ⇒ MainDlg

Returns a new instance of MainDlg.



93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
# File 'lib/main-dlg-impl.rb', line 93

def initialize(parent, arg)
	super(parent)
	@w=Ui::MainDlg.new
	@w.setupUi(self)
	@parent=parent

	@cfg=Qt::Settings.new("MMeltnerSoft", "fg_map")
	@metricUnit = @cfg.value("metricUnit",Qt::Variant.new(true)).toBool
	@zoom = @cfg.value("zoom",Qt::Variant.new(13)).toInt
	@lat = @cfg.value("lat",Qt::Variant.new(LATSTARTUP)).toDouble
	@lon = @cfg.value("lon",Qt::Variant.new(LONSTARTUP)).toDouble
	@w.cBrw.setChecked(@cfg.value("rwChecked",Qt::Variant.new(false)).toBool)
	@w.cBndb.setChecked(@cfg.value("nbdChecked",Qt::Variant.new(false)).toBool)
	@w.cBvor.setChecked(@cfg.value("vorChecked",Qt::Variant.new(true)).toBool)
	@opacity = @cfg.value("opacity",Qt::Variant.new(1.0)).toFloat

	@flag=Qt::Pixmap.new(":/icons/flag-blue.png")
	@pin=Qt::Pixmap.new(":/icons/wpttemp-red.png")
	@linepen = Qt::Pen.new
	@linepen.setWidth(5)
	@colors={:index => 0, :selection  => ["Red", "Yellow", "Green"]}
	@graphicsSceneFont = Qt::Font.new("Helvetica", 7)
	@graphicsSceneBrush = Qt::Brush.new(Qt::Color.new(255, 255, 255, 150))
	@ilsBrush = Qt::Brush.new(Qt::Color.new(0, 0, 0, 150))
	@noPen = Qt::Pen.new(Qt::NoPen)

	@wakeupTimer = Qt::Timer.new( self )
	Qt::Object.connect( @wakeupTimer, SIGNAL('timeout()'), self, SLOT('wakeupTimer()') )
	@wakeupTimer.start( FS_READ_INTERVAL )
	@wakeupCounter = 0
	@autosaveTimer = Qt::Timer.new( self )
	Qt::Object.connect( @autosaveTimer, SIGNAL('timeout()'), self, SLOT('autosaveTimer()') )
	@autosaveTimer.start( AUTOSAVE_INTERVAL )

	@offset_x=@offset_y=0
	@fs_ans=[]
	@fs_queries=["/position/latitude-deg", "/position/longitude-deg", "/position/altitude-ft", 
		"/orientation/heading-deg", "/velocities/groundspeed-kt"]
	@speed = 0

	@waypoints=Way.new(nil,'user', Time.now, "Blue")
	@mytracks=[]
	@mytrack_current=-1
	@prev_track_node = nil
	@posnode = Node.new(1, Time.now, @lon, @lat)
	@tempposnode = Node.new(1, Time.now, @lon, @lat)

	@node = Node.new(1, Time.now, @lon, @lat, 0, @zoom)
	@rot = 0
	@remainingTiles = 0
	@httpThreads = Array.new
	@currentlyDownloading = Array.new
	@currentlyDownloadingElevation = Array.new
	@tilesToAdd = Array.new
	
	@navs = Navaid.new(arg)
	
	@httpMutex = Mutex.new
	@httpElevationMutex = Mutex.new
	@queryMutex = Mutex.new
	@tilesToAddMutex = Mutex.new
	
	@scene=Qt::GraphicsScene.new()
	@w.gVmap.setScene(@scene)
	resetScene()
	
	@w.lBzoom.setText(@zoom.to_s)
	vorGraphic=Qt::GraphicsSvgItem.new(":/icons/vor.svg")
	vorGraphic.setElementId("VOR")
	boundingrect = vorGraphic.boundingRect
	@vor_offsetx = boundingrect.right / 2
	@vor_offsety = boundingrect.bottom / 2

	begin
		@fs_socket = TCPSocket.open('localhost', FS_PORT)
		@fs_socket.puts "reset"
	rescue
		#swallow all errors
	end
	
	if FileTest.directory?(MAPSDIR) then
		$MAPSHOME = MAPSDIR
	else
		resp = Qt::MessageBox::question(nil, "No local Map Directory found.", "Create one?", Qt::MessageBox::No, Qt::MessageBox::Yes)
		if resp == Qt::MessageBox::Yes then
			Dir.mkdir(MAPSDIR)
			$MAPSHOME = MAPSDIR
		else
			$MAPSHOME = "./"
		end
	end
	puts "Map Directory located here: \"#{$MAPSHOME}\""
	
	readFlightgear()
end

Instance Attribute Details

#flagObject (readonly)

Returns the value of attribute flag.



84
85
86
# File 'lib/main-dlg-impl.rb', line 84

def flag
  @flag
end

Returns the value of attribute menu.



84
85
86
# File 'lib/main-dlg-impl.rb', line 84

def menu
  @menu
end

#metricUnitObject

Returns the value of attribute metricUnit.



87
88
89
# File 'lib/main-dlg-impl.rb', line 87

def metricUnit
  @metricUnit
end

#mytrack_currentObject

Returns the value of attribute mytrack_current.



84
85
86
# File 'lib/main-dlg-impl.rb', line 84

def mytrack_current
  @mytrack_current
end

#mytracksObject (readonly)

Returns the value of attribute mytracks.



84
85
86
# File 'lib/main-dlg-impl.rb', line 84

def mytracks
  @mytracks
end

#nodeObject

Returns the value of attribute node.



84
85
86
# File 'lib/main-dlg-impl.rb', line 84

def node
  @node
end

#offset_x=(value) ⇒ Object (writeonly)

Sets the attribute offset_x

Parameters:

  • value

    the value to set the attribute offset_x to.



86
87
88
# File 'lib/main-dlg-impl.rb', line 86

def offset_x=(value)
  @offset_x = value
end

#offset_yObject

Returns the value of attribute offset_y.



84
85
86
# File 'lib/main-dlg-impl.rb', line 84

def offset_y
  @offset_y
end

#sceneObject (readonly)

Returns the value of attribute scene.



84
85
86
# File 'lib/main-dlg-impl.rb', line 84

def scene
  @scene
end

#scene_tilesObject

Returns the value of attribute scene_tiles.



84
85
86
# File 'lib/main-dlg-impl.rb', line 84

def scene_tiles
  @scene_tiles
end

#toffset_xObject (readonly)

Returns the value of attribute toffset_x.



84
85
86
# File 'lib/main-dlg-impl.rb', line 84

def toffset_x
  @toffset_x
end

#wObject

Returns the value of attribute w.



84
85
86
# File 'lib/main-dlg-impl.rb', line 84

def w
  @w
end

#waypointsObject

Returns the value of attribute waypoints.



84
85
86
# File 'lib/main-dlg-impl.rb', line 84

def waypoints
  @waypoints
end

#zoomObject (readonly)

Returns the value of attribute zoom.



84
85
86
# File 'lib/main-dlg-impl.rb', line 84

def zoom
  @zoom
end

Instance Method Details

#addNavToScene(vor, origin_x, origin_y) ⇒ Object



487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
# File 'lib/main-dlg-impl.rb', line 487

def addNavToScene(vor, origin_x, origin_y)
	vorGraphic = Qt::GraphicsSvgItem.new(":/icons/vor.svg")
	vorGraphic.setElementId(vor.type)
	vorGraphic.setTransform(Qt::Transform.new.translate(-@vor_offsetx, -@vor_offsety))
	vorGraphic.setZValue(Z_VALUE_NAV)
	@scene.addItem(vorGraphic)
	vorNode = Node.new(0, nil, vor.lon.to_f, vor.lat.to_f)
	vorGraphic.setPos((vorNode.toxtile - origin_x) * 256, (vorNode.toytile - origin_y) * 256)
	vorGraphic.baseElement = vor
	vor.sceneItem = vorGraphic
	
	# create text on Navaid
	textString = vor.shortName + " " + vor.freq.to_s
	text=Qt::GraphicsSimpleTextItem.new(textString)
	text.setFont(@graphicsSceneFont)
	bounding = text.boundingRect
	background = Qt::GraphicsRectItem.new(bounding)
	background.setBrush(@graphicsSceneBrush)
	background.setPen(@noPen)
	background.setToolTip(textString + "; " + vor.longName)
	background.setPos(@vor_offsetx - bounding.width / 2, 2*@vor_offsety+3)
	text.setParentItem(background)
	background.setParentItem(vorGraphic)
end

#addRunwayToScene(rw, origin_x, origin_y) ⇒ Object



512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
# File 'lib/main-dlg-impl.rb', line 512

def addRunwayToScene(rw, origin_x, origin_y)
	rwNode = Node.new(0, nil, rw.lon.to_f, rw.lat.to_f)
	
	# create text
	textString = rw.airportName + " " + rw.freq.to_s
	text=Qt::GraphicsSimpleTextItem.new(textString)
	text.setFont(@graphicsSceneFont)
	bounding = text.boundingRect
	background = Qt::GraphicsRectItem.new(bounding)
	background.setTransform(Qt::Transform.new.translate(-bounding.width / 2, ILSTEXTOFFSET))
	background.setZValue(Z_VALUE_NAV)
	background.setBrush(@graphicsSceneBrush)
	background.setPen(@noPen)
	background.setToolTip(textString)
	text.setParentItem(background)
	background.setPos((rwNode.toxtile - origin_x) * 256, (rwNode.toytile - origin_y) * 256)

	rwGraphic = Qt::GraphicsEllipseItem.new(0,0,ILSSIZE,ILSSIZE)
	rwGraphic.setStartAngle(ILSCONEANGLE*8)
	rwGraphic.setSpanAngle(-ILSCONEANGLE*16)
	rwGraphic.setTransform(Qt::Transform.new.translate(bounding.width/ 2, -ILSTEXTOFFSET).rotate(rw.direction + 90).translate(-ILSSIZE / 2, -ILSSIZE / 2))
	rwGraphic.setPen(@noPen)
	rwGraphic.setBrush(@ilsBrush)
	rwGraphic.setFlag(Qt::GraphicsItem::ItemStacksBehindParent)

	rwGraphic.setParentItem(background)
	@scene.addItem(background)
	rw.sceneItem = background
end

#addTileToScene(f, origin_x, origin_y, thread = false) ⇒ Object



420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
# File 'lib/main-dlg-impl.rb', line 420

def addTileToScene(f, origin_x, origin_y, thread=false)
	@scene_tiles << f
	f =~ /\/(\d*)\/(\d*)\/(\d*)/
	x = $2.to_i
	y = $3.to_i

	if thread then
		# we can not add the tiles to the scene within this thread directly. It crosses thread
		# bounderies which crashes QT badly
		@tilesToAddMutex.synchronize {
			@tilesToAdd << [f, (x - origin_x)*256, (y - origin_y)*256, OPENSTREETMAP_TILE]
		}
	else # add immediately, we are not in a different thread
		pmi=Qt::GraphicsPixmapItem.new(Qt::Pixmap.new(f), @openstreetmapLayer)
		pmi.setOffset((x - origin_x)*256, (y - origin_y)*256)
	end

	if @w.cBshadows.isChecked then
		if FileTest.exist?(f + "-elevation.png") then
			if thread then
				# we can not add the tiles to the scene within this thread directly. It crosses thread
				# bounderies which crashes QT badly
				@tilesToAddMutex.synchronize {
					@tilesToAdd << [f, (x - origin_x)*256, (y - origin_y)*256, ELEVATION_TILE]
				}
			else
				pmi = Qt::GraphicsPixmapItem.new(Qt::Pixmap.new(f + "-elevation.png"), @elevationLayer)
				pmi.setOffset((x - origin_x)*256, (y - origin_y)*256)
				pmi.setZValue(Z_VALUE_TILES_ELEVATION)
			end
		else
			@httpThreads << Thread.new(f) {|filename|
				if !@currentlyDownloadingElevation.include?(filename) then
					@currentlyDownloadingElevation << filename
					# try to download elevation profile
					@httpElevationMutex.synchronize {
						h = Net::HTTP.new('toolserver.org')
						h.open_timeout = 10
						filename =~ /\/\d+\/\d+\/\d+$/
						fn = $&
						begin
							resp, data = h.get("/~cmarqu/hill" + fn + ".png", nil)
							if resp.kind_of?(Net::HTTPOK) then
								# check here again as in the meantime another thread might already have added the tile
								if !FileTest.exist?($MAPSHOME + fn + "-elevation.png") then
									File.open($MAPSHOME + fn + "-elevation.png", "w") do |file|
										file.write(data)
									end
									@tilesToAddMutex.synchronize {
										@tilesToAdd << [$MAPSHOME + fn + "-elevation.png", (x - origin_x)*256, (y - origin_y)*256, ELEVATION_TILE]
									}
								end
							else
								puts "No elevation profile found for this tile."
							end
						# NoMethodError because of bug, see http://redmine.ruby-lang.org/issues/show/2708
						rescue NoMethodError, Errno::ECONNREFUSED, SocketError, Timeout::Error
							puts "No connection to elevation profile server."
						end
					} # sync
					@currentlyDownloadingElevation.delete(filename)
				end # if downloading
			} # Thread
		end
	end
end

#autosaveTimerObject



937
938
939
# File 'lib/main-dlg-impl.rb', line 937

def autosaveTimer()
	savetrack(@mytracks, false)
end

#cBndb_clickedObject



985
986
987
# File 'lib/main-dlg-impl.rb', line 985

def cBndb_clicked()
	movemap(@node, true)
end

#cBpointorigin_clickedObject



955
956
957
# File 'lib/main-dlg-impl.rb', line 955

def cBpointorigin_clicked()
	@w.fRcurrentwp.enabled = !@w.cBtoorigin.isChecked()
end

#cBrw_clickedObject



989
990
991
# File 'lib/main-dlg-impl.rb', line 989

def cBrw_clicked()
	movemap(@node, true)
end

#cBshadows_clickedObject



993
994
995
# File 'lib/main-dlg-impl.rb', line 993

def cBshadows_clicked()
	movemap(@node, true)
end

#cBvor_clickedObject



981
982
983
# File 'lib/main-dlg-impl.rb', line 981

def cBvor_clicked()
	movemap(@node, true)
end

#get_data(path) ⇒ Object



202
203
204
205
206
207
208
209
# File 'lib/main-dlg-impl.rb', line 202

def get_data(path)
	# check from end to get most recent position
	r=@fs_ans.reverse.detect do |f|
		f.include?(path)
	end
	r =~ /-?\d+\.\d+/
	return $&.to_f
end

#hSopacity_changed(opacity) ⇒ Object



1015
1016
1017
1018
# File 'lib/main-dlg-impl.rb', line 1015

def hSopacity_changed(opacity)
	@opacity = opacity / 100.0
	@openstreetmapLayer.setOpacity(@opacity)
end

#keyPressEvent(keyevent) ⇒ Object



1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
# File 'lib/main-dlg-impl.rb', line 1002

def keyPressEvent(keyevent)
	case keyevent.text
		when "+"
			zoomplus
		when "-"
			zoomminus
		when " "
			@w.pBrecordTrack.click
		else # case
			super
	end # case
end

#loadtrack(title) ⇒ Object



277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
# File 'lib/main-dlg-impl.rb', line 277

def loadtrack(title)	
	fn=Qt::FileDialog::getOpenFileName(nil, title, $MAPSHOME + "/tracks/", "Track-Data (*.gpx *.log);;All (*)")
	if !fn.nil? then
		success = false
		doc = XML::Document.file(fn)
		doc.find('/ns:gpx/ns:trk', "ns:http://www.topografix.com/GPX/1/1").each{|trk|
			@mytrack_current -= 1
			trk.find("ns:trkseg", "ns:http://www.topografix.com/GPX/1/1").each{|seg|
				ns = XML::Namespace.new(seg, 'ns', 'http://www.topografix.com/GPX/1/1')
				seg.namespaces.namespace=ns
				@mytrack_current += 1
				if @mytracks[@mytrack_current].nil? then
					@mytracks[@mytrack_current] = Way.new(1, 'user', Time.now, nextcolor)
					@prev_track_node = nil
				end
				track=@mytracks[@mytrack_current]
				track.nodes.clear
				xpat_time = XML::XPath::Expression.new("ns:time")
				xpat_time_us = XML::XPath::Expression.new("ns:time_us")
				xpat_elevation = XML::XPath::Expression.new("ns:ele")
				seg.find("ns:trkpt", "ns:http://www.topografix.com/GPX/1/1").each{|tpt|
					usec = tpt.find_first(xpat_time_us)
					usec = (usec.nil? ? "0" : usec.content)
					track << Node.new(nil, tpt.find_first(xpat_time).content + usec, \
							tpt["lon"].to_f, tpt["lat"].to_f, tpt.find_first(xpat_elevation).content.to_f)
					success = true
				}
			}
		}
		if success then
			movemap(@node, true)
		else
			Qt::MessageBox::warning(nil, "Warning", "No data found in file.")
		end
		return success
	end
end

#loadwaypoint(title) ⇒ Object



315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
# File 'lib/main-dlg-impl.rb', line 315

def loadwaypoint(title)	
	fn=Qt::FileDialog::getOpenFileName(nil, title, $MAPSHOME + "/waypoints/", "Waypoint-Data (*.gpx *.log);;All (*)")
	if !fn.nil? then
		success = false
		doc = XML::Document.file(fn)
		@waypoints = Way.new(nil,'user', Time.now, "Blue")
		doc.find("/ns:gpx/ns:wpt", "ns:http://www.topografix.com/GPX/1/1").each{ |wpt|
			ns = XML::Namespace.new(wpt, 'ns', 'http://www.topografix.com/GPX/1/1')
			wpt.namespaces.namespace = ns
			xpat_time = XML::XPath::Expression.new("ns:time")
			xpat_elevation = XML::XPath::Expression.new("ns:ele")
			@waypoints << Node.new(nil, wpt.find_first(xpat_time).content, wpt["lon"].to_f, \
						wpt["lat"].to_f, wpt.find_first(xpat_elevation).content.to_f)
			success = true
		}
		if success then
			movemap(@node, true)
		else
			Qt::MessageBox::warning(nil, "Warning", "No data found in file.")
		end
		return success
	end
end

#movemap(node, repaint = false, downloadTiles = true) ⇒ Object



542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
# File 'lib/main-dlg-impl.rb', line 542

def movemap(node, repaint=false, downloadTiles=true)
	origin_x=node.xtile
	origin_y=node.ytile

	if repaint then
		@scene_tiles = []
		@scene_navs = []
		@scene_rws = []
		resetScene()
		# 8 => 256 = 2**8
		size = 2**(@zoom + 8)
		sceneRect = Qt::RectF.new(0,0,size,size)
		sceneRect.moveCenter(Qt::PointF.new(@node.xtile, @node.ytile))
		@scene.setSceneRect(sceneRect)
	end

	vorsToDisplay = @navs.getVORs(node.getLatLonBox(@w.gVmap.size, @offset_x, @offset_y))
	if vorsToDisplay.length < MAXVORSTODISPLAY then
		vorsToDisplay.each do |vor|
			if !@scene_navs.include?(vor)
				if (@w.cBndb.isChecked and vor.type == "NDB") or
						(@w.cBvor.isChecked and vor.type != "NDB") then
					@scene_navs << vor
					addNavToScene(vor, origin_x, origin_y)
				end
			end
		end
	elsif !@scene_navs.empty? then
		repaint = true
		@scene_tiles = []
		@scene_navs = []
		@scene_rws = []
		resetScene()
	end

	if @w.cBrw.isChecked then
		runwaysToDisplay = @navs.getRunways(node.getLatLonBox(@w.gVmap.size, @offset_x, @offset_y))
		if runwaysToDisplay.length < MAXILSTODISPLAY then
			runwaysToDisplay.each do |runway|
				if !@scene_rws.include?(runway)
					@scene_rws << runway
					addRunwayToScene(runway, origin_x, origin_y)
				end
			end
		end
	elsif !@scene_rws.empty? then
		repaint = true
		@scene_tiles = []
		@scene_navs = []
		@scene_rws = []
		resetScene()
	end

	fn = node.getfilenames(@w.gVmap.size, @offset_x, @offset_y)

	fn.each{|f|
		if !@scene_tiles.include?(f) then
			if FileTest.exist?(f+".png") then
				addTileToScene(f, origin_x, origin_y)
			elsif downloadTiles and (@timeNoInternet.nil? or (Time.now - @timeNoInternet) > 60) then
				@httpThreads << Thread.new(f) {|filename|
					# check if we already download this tile
					if !@currentlyDownloading.include?(filename) then
						@currentlyDownloading << filename
						@remainingTiles += 1
						@httpMutex.synchronize {
							h = Net::HTTP.new('tile.openstreetmap.org')
							h.open_timeout = 10
							filename =~ /\/\d+\/\d+\/\d+$/
							fn = $&
							begin
								resp, data = h.get(fn + ".png", nil)
								if resp.kind_of?(Net::HTTPOK) then
									maindir = Dir.pwd
									Dir.chdir($MAPSHOME)
									fn.split("/")[0..-2].each do |dir|
										if !dir.empty? then
											begin
												Dir.mkdir(dir) 
											rescue Errno::EEXIST
												# just swallow error
											end
											Dir.chdir(dir)
										end
									end
									Dir.chdir(maindir)
									File.open($MAPSHOME + fn + ".png", "w") do |file|
										file.write(data)
									end
									# we call from within a thread, signal this to the subroutine
									addTileToScene($MAPSHOME + fn, origin_x, origin_y, true)
								else
									puts "Could not download tile. Internet connection alive?"
									@timeNoInternet=Time.now
								end
							# NoMethodError because of bug, see http://redmine.ruby-lang.org/issues/show/2708
							rescue NoMethodError, Errno::ECONNREFUSED, SocketError, Timeout::Error
								puts "Could not download tile. Internet connection alive?"
								@timeNoInternet=Time.now
							end
						}
						@remainingTiles -= 1
						@currentlyDownloading.delete(filename)
					end # if
				}
			else
				puts "Internet timeout still running"
			end
		end
	}
	
	if repaint then
		mainnode_x=node.toxtile
		mainnode_y=node.toytile

		# set waypoint flags
		i=1
		@waypoints.nodes.each {|node|
			if !node.nil? then
				putflag((node.toxtile - mainnode_x) * 256, (node.toytile - mainnode_y) * 256, i, node)
			end
			i+=1
		}
		# set origin pin
		pmi=Qt::GraphicsPixmapItem.new(@pin)
		pmi.setOffset(OFFSET_PIN_X, -OFFSET_PIN_Y)
		pmi.setZValue(Z_VALUE_ORIGIN)
		@scene.addItem(pmi)

		# create hud display
		# needs to be embedded in other graphics element to circumvent a bug if the position of
		# the ProxyWidget is above, below 2**15 - 1, bug in QT
		@hud=Qt::GraphicsRectItem.new(0,0,10,10)
		@hud.setPen(@noPen)
		hud=Qt::GraphicsProxyWidget.new(@hud)
		@hud_widget = HudWidget.new()
		hud.setWidget(@hud_widget)
		@hud.setZValue(Z_VALUE_HUD)
		@scene.addItem(@hud)
		@hud.setPos(@w.gVmap.mapToScene(0,0))
		
		# create rose
		@rose=Qt::GraphicsSvgItem.new(":/icons/rose.svg")
		@rose.setElementId("rose")
		boundingrect = @rose.boundingRect
		rose_offsetx = boundingrect.right / 2
		rose_offsety = boundingrect.bottom / 2
		@rose.setTransform(Qt::Transform.new.scale(SCALE_SVG,SCALE_SVG).translate(-rose_offsetx, -rose_offsety))
		@rose.setZValue(Z_VALUE_ROSE)
		@scene.addItem(@rose)
		@rose.setPos((@posnode.toxtile - mainnode_x) * 256, (@posnode.toytile - mainnode_y) * 256)

		# create bearing-pointer
		@pointer=Qt::GraphicsSvgItem.new(":/icons/rose.svg")
		@pointer.setElementId("zeiger")
		boundingrect = @pointer.boundingRect
		@pointer_offsetx = boundingrect.right / 2
		@pointer.setTransform(Qt::Transform.new.scale(SCALE_SVG,SCALE_SVG).rotate(0).translate(-@pointer_offsetx, 0))
		@pointer.setZValue(Z_VALUE_POINTER)
		@scene.addItem(@pointer)
		@pointer.setPos((@posnode.toxtile - mainnode_x) * 256, (@posnode.toytile - mainnode_y) * 256)

		# create pointer to origin
		@pointertoorigin=Qt::GraphicsSvgItem.new(":/icons/rose.svg")
		@pointertoorigin.setElementId("zeigertoorigin")
		boundingrect = @pointertoorigin.boundingRect
		@pointertoorigin_offsetx = boundingrect.right / 2
		@pointertoorigin.setTransform(Qt::Transform.new.scale(SCALE_SVG,SCALE_SVG).rotate(0).translate(-@pointertoorigin_offsetx, 0))
		@pointertoorigin.setZValue(Z_VALUE_POINTERTOORIGIN)
		@scene.addItem(@pointertoorigin)
		@pointertoorigin.setPos((@posnode.toxtile - mainnode_x) * 256, (@posnode.toytile - mainnode_y) * 256)
		
		# paint tracks
		@mytracks.each {|track|
			prev_node = nil
			if !track.nil? then
				@linepen.setColor(Qt::Color.new(track.color))
				tck=nil
				prev_node=false
				if !track.nodes.empty? then
					track.nodes.each{|n|
						if !prev_node then
							tck=Qt::PainterPath.new(Qt::PointF.new((n.toxtile - mainnode_x) * 256, (n.toytile - mainnode_y) * 256))
						else
							tck.lineTo((n.toxtile - mainnode_x) * 256, (n.toytile - mainnode_y) * 256)
						end
						prev_node = true
					}
					track.path=TrackGraphicsPathItem.new(track)
					track.path.setPath(tck)
					track.path.setZValue(Z_VALUE_TRACK)
					track.path.setPen(@linepen)
					@scene.addItem(track.path)
				end
			end
		}
		if @w.pBrecordTrack.isChecked then
			if !@mytracks[@mytrack_current].path.nil?
				@tckpath=@mytracks[@mytrack_current].path.path
			end
		end
	end

	@w.gVmap.centerOn(@offset_x*256,@offset_y*256)
	if !@hud.nil? then
		@hud.setPos(@w.gVmap.mapToScene(0,0))
	end
end

#nextcolorObject



225
226
227
228
229
230
231
232
233
234
# File 'lib/main-dlg-impl.rb', line 225

def nextcolor
	col=@colors[:selection][@colors[:index]]
	if col.nil? then
		col=@colors[:selection][0]
		@colors[:index] = 0
	else
		@colors[:index] += 1
	end
	return col
end

#pBexit_clickedObject



967
968
969
970
971
972
973
974
975
976
977
978
979
# File 'lib/main-dlg-impl.rb', line 967

def pBexit_clicked()
	puts "Syncing data and exiting."
	@cfg.setValue("metricUnit", Qt::Variant.new(@metricUnit))
	@cfg.setValue("zoom", Qt::Variant.new(@zoom))
	@cfg.setValue("lat", Qt::Variant.new(@node.lat))
	@cfg.setValue("lon", Qt::Variant.new(@node.lon))
	@cfg.setValue("rwChecked", Qt::Variant.new(@w.cBrw.isChecked))
	@cfg.setValue("nbdChecked", Qt::Variant.new(@w.cBndb.isChecked))
	@cfg.setValue("vorChecked", Qt::Variant.new(@w.cBvor.isChecked))
	@cfg.setValue("opacity", Qt::Variant.new(@opacity))
	@cfg.sync
	@parent.close
end

#pBminus_clickedObject



959
960
961
# File 'lib/main-dlg-impl.rb', line 959

def pBminus_clicked()
	zoomminus
end

#pBplus_clickedObject



963
964
965
# File 'lib/main-dlg-impl.rb', line 963

def pBplus_clicked()
	zoomplus
end

#pBrecordTrack_toggled(state) ⇒ Object



941
942
943
944
945
946
947
948
949
950
951
952
953
# File 'lib/main-dlg-impl.rb', line 941

def pBrecordTrack_toggled(state)
	if state
		@mytrack_current += 1
		@w.pBrecordTrack.text = "Recording Track #{@mytrack_current + 1}"
		if @mytracks[@mytrack_current].nil? then
			@mytracks[@mytrack_current] = Way.new(1, 'user', Time.now, nextcolor)
			@linepen.setColor(Qt::Color.new(@mytracks[@mytrack_current].color))
			@prev_track_node = false
		end
	else
		@w.pBrecordTrack.text = "Record Track #{@mytrack_current + 2}"
	end
end

#putflag(x, y, i, node) ⇒ Object



211
212
213
214
215
216
217
218
219
220
221
222
223
# File 'lib/main-dlg-impl.rb', line 211

def putflag(x,y,i,node)
	flag=FlagGraphicsPixmapItem.new(@flag)
	flag.setOffset(x - OFFSET_FLAG_X, y - OFFSET_FLAG_Y)
	t=Qt::GraphicsTextItem.new(i.to_s, flag)
	t.setPos(x + OFFSET_FLAG_COUNTER_X, y + OFFSET_FLAG_COUNTER_Y)
	flag.setZValue(Z_VALUE_WAYPOINT)
	tooltip=("Lon: %.3f°"%node.lon)+("\nLat: %.3f°"%node.lat)
	if node.elevation>0 then
		tooltip += ("\nElevation: %.1fm" % node.elevation)
	end
	flag.setToolTip(tooltip)
	@scene.addItem(flag)
end

#readFlightgearObject



751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
# File 'lib/main-dlg-impl.rb', line 751

def readFlightgear
	Thread.new do
		while true
			if @fs_socket.nil? then
				sleep 1
			else
				begin
					@queryMutex.synchronize {
						@fs_queries.each do |q|
							@fs_socket.print("get " + q + "\r\n")
							s=""
							while select([@fs_socket], nil, nil, 0.3) do
								s += @fs_socket.read(1)
								# check for end of line characterized by this string: "\r\n/>"
								# break	if s[-4..-1] == "\r\n/>" and s.include?(q)
							end
							if s.include?(q) then
								@fs_ans << s.split("\n")
								@fs_ans.flatten!
							end
						end
					}
				rescue
					puts "Warning: Can not communicate with Flightsimulator. Is Telnet interface configured?"
					@scene.removeItem(@rose)
					@scene.removeItem(@pointer)
					@fs_socket = nil
					@hud = nil
				end
			end
		end #while
	end # Thread
end

#resetSceneObject



189
190
191
192
193
194
195
196
197
198
199
200
# File 'lib/main-dlg-impl.rb', line 189

def resetScene
	@scene.clear
	@openstreetmapLayer = TileGraphicsItemGroup.new
	@openstreetmapLayer.setZValue(Z_VALUE_TILES)
	@openstreetmapLayer.setOpacity(@opacity)
	@scene.addItem(@openstreetmapLayer)
	@elevationLayer = Qt::GraphicsItemGroup.new
	@elevationLayer.setZValue(Z_VALUE_TILES_ELEVATION)
	@scene.addItem(@elevationLayer)
	
	@w.hSopacity.setValue((@opacity * 100).to_i)
end

#resizeEvent(e) ⇒ Object



997
998
999
1000
# File 'lib/main-dlg-impl.rb', line 997

def resizeEvent(e)
	super
	movemap(@node, true)
end

#savetrack(items, warn = true) ⇒ Object



236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
# File 'lib/main-dlg-impl.rb', line 236

def savetrack(items, warn=true)
	if items[0].nil? or items[0].nodes.length == 0 then
		Qt::MessageBox::warning(nil, "Warning", "No data recorded yet.") if warn
	else
		begin
			Dir.mkdir($MAPSHOME + "/tracks")
		rescue Errno::EEXIST
			# just swallow error
		end
	
		ap "generating xml-doc"
		doc = XML::Document.new()
		doc.root = XML::Node.new('gpx')
		doc.root["xmlns"] = "http://www.topografix.com/GPX/1/1"
		doc.root["creator"] = "ruby-tracker"
		doc.root["version"] = "1.1"
		doc.root["xmlns:xsi"] = "http://www.w3.org/2001/XMLSchema-instance" 
		doc.root["xsi:schemaLocation"] = "http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd"

		tracknode = XML::Node.new("trk")
		doc.root << tracknode
		items.each{|track|
			segnode = XML::Node.new("trkseg")
			tracknode << segnode
			track.nodes.each{|n|
				trackpoint = XML::Node.new("trkpt")
				trackpoint["lat"] = 	n.lat.to_s.gsub(",",".")
				trackpoint["lon"] = 	n.lon.to_s.gsub(",",".")
				trackpoint << XML::Node.new("ele", n.elevation.to_s.gsub(",","."))
				trackpoint << XML::Node.new("time", n.toGPStime)
				trackpoint << XML::Node.new("time_us", n.timestamp.usec.to_s)
				segnode << trackpoint
			}
		}
		File.open($MAPSHOME + "/tracks/" + items.first.nodes.first.toGPStime + ".gpx", "w+"){|f|
			f.puts doc.inspect
		}
		ap "xml-file written"
	end
end

#saveWaypoints(waypoints) ⇒ Object



339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
# File 'lib/main-dlg-impl.rb', line 339

def saveWaypoints(waypoints)
	if waypoints.length == 0 then
		Qt::MessageBox::warning(nil, "Warning", "No waypoints set yet.") if warn
	else
		begin
			Dir.mkdir($MAPSHOME + "/waypoints")
		rescue Errno::EEXIST
			# just swallow error
		end
	
		doc = XML::Document.new()
		doc.root = XML::Node.new('gpx')
		doc.root["xmlns"] = "http://www.topografix.com/GPX/1/1"
		doc.root["creator"] = "ruby-tracker"
		doc.root["version"] = "1.1"
		doc.root["xmlns:xsi"] = "http://www.w3.org/2001/XMLSchema-instance" 
		doc.root["xsi:schemaLocation"] = "http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd"

		waypoints[0].nodes.each{|n|
			if !n.nil? then
				wpnode = XML::Node.new("wpt")
				doc.root << wpnode
				wpnode["lat"] = 	n.lat.to_s.gsub(",",".")
				wpnode["lon"] = 	n.lon.to_s.gsub(",",".")
				wpnode << XML::Node.new("ele", n.elevation.to_s.gsub(",","."))
				wpnode << XML::Node.new("time", n.toGPStime)
			end
		}
		fn=Qt::FileDialog::getSaveFileName(nil, "Save Waypoint File", $MAPSHOME + "/waypoints/", "Waypoint-Data (*.gpx *.log);;All (*)","*.gpx")

		if !fn.nil? then
			if fn !~ /\.gpx$/ then
				fn += ".gpx"
			end
			File.open(fn, "w+"){|f|
				f.puts doc.inspect
			}
		end
	end
end

#wakeupTimerObject



785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
# File 'lib/main-dlg-impl.rb', line 785

def wakeupTimer()
#		p "wakeup in"
	# have to do centering every time as QT will not scroll to scene coordinates which have no elements placed there yet
	begin
		@w.gVmap.centerOn(@offset_x*256,@offset_y*256)
	rescue ArgumentError
		# swallow
	end

	@wakeupCounter += 1
	if @wakeupCounter <= TICKSTOSKIP then
		# trick to prevent threads from getting just tiny slices of time to execute 
		# inside the main event loop of QT
		sleep LOOPSLEEPINTERVAL
		return
	end
	@wakeupCounter = 0

	# add tiles which are awaiting addition				
	@tilesToAddMutex.synchronize {
		@tilesToAdd.each do |tile|
			parent = (tile[3] == OPENSTREETMAP_TILE) ? @openstreetmapLayer : @elevationLayer
			pmi = Qt::GraphicsPixmapItem.new(Qt::Pixmap.new(tile[0]), parent)
			pmi.setOffset(tile[1], tile[2])
		end
		@tilesToAdd.clear
	}

	if @remainingTiles > 0 then
		if @warningText.nil? then
			@warningText = Qt::GraphicsSimpleTextItem.new()
			@warningText.setBrush(Qt::Brush.new(Qt::Color.new("red")))
			@warningText.setZValue(Z_VALUE_WARNING)
			@scene.addItem(@warningText)
		end
		fontInfo = Qt::FontInfo.new(@warningText.font)
		@warningText.setText("#{@remainingTiles} remaining tiles")
		@warningText.setPos(@w.gVmap.mapToScene((@w.gVmap.size.width - @warningText.boundingRect.width)/2, 
					@w.gVmap.size.height - fontInfo.pixelSize - 10))
	elsif !@warningText.nil? then
		@scene.removeItem(@warningText)
		@warningText = nil
	end

	if @fs_socket.nil? then
		begin
			@fs_socket = TCPSocket.open('localhost', FS_PORT)
			movemap(@node, true)
		rescue
			#swallow all errors
			puts "Non-critical socket error: #{$!}"
		end
	else
		#ap @fs_ans
		if @fs_ans.length>0 then # check if any answer has been received yet.
			if !@hud.nil? then
				@tempposnode.lon = get_data("/position/longitude-deg")
				@tempposnode.lat = get_data("/position/latitude-deg")
				@rot = get_data("/orientation/heading-deg")
				@alt = get_data("/position/altitude-ft")
				@speed = get_data("/velocities/groundspeed-kt")
				# protect against invalid data
				if !(@tempposnode.lon and @tempposnode.lat and @rot and @alt and @speed) then
					@fs_ans=[]
					return
				end
				@posnode = @tempposnode.dup
				
				@speed = @speed  * 1.852
				@hud_widget.w.lBlat.setText("%2.3f°" % @posnode.lat)
				@hud_widget.w.lBlon.setText("%2.3f°" % @posnode.lon)
				conversion = @metricUnit ? 1 : 0.54
				@hud_widget.w.lBspeed.setText("%3.1f" % (@speed*conversion) +  (@metricUnit ? " km/h" : "kt"))
				@hud_widget.w.lBheading.setText("%3.1f°" % (@rot))
				conversion = @metricUnit ? 3.281 : 1
				@hud_widget.w.lBalt.setText("%3.1f" % (@alt/conversion) +  (@metricUnit ? "m" : "ft"))
				mainnode_x=@node.toxtile
				mainnode_y=@node.toytile
				@rose.setPos((@posnode.toxtile - mainnode_x) * 256, (@posnode.toytile - mainnode_y) * 256)
				
				@pointer.setTransform(Qt::Transform.new.scale(SCALE_SVG,SCALE_SVG).rotate(@rot+180.0) \
						.translate(-@pointer_offsetx, -@pointer_offsetx))
				@pointer.setPos((@posnode.toxtile - mainnode_x) * 256 ,(@posnode.toytile - mainnode_y) * 256)
				
				to_x = mainnode_x
				to_y = mainnode_y
				to_lon = @node.lon
				to_lat = @node.lat
				if !@w.cBtoorigin.isChecked and !@waypoints.currentwp.nil? then
					if !@waypoints.nodes[@waypoints.currentwp-1].nil? then
						to_x = @waypoints.nodes[@waypoints.currentwp-1].toxtile
						to_y = @waypoints.nodes[@waypoints.currentwp-1].toytile
						to_lon = @waypoints.nodes[@waypoints.currentwp-1].lon
						to_lat = @waypoints.nodes[@waypoints.currentwp-1].lat
					end
				end
				@pointertoorigin.setTransform(Qt::Transform.new.scale(SCALE_SVG,SCALE_SVG).rotateRadians(Math::PI / 2 + \
						Math.atan2((@posnode.toytile - to_y), (@posnode.toxtile - to_x))) \
						.translate(-@pointertoorigin_offsetx, -@pointertoorigin_offsetx))
				@pointertoorigin.setPos((@posnode.toxtile - mainnode_x) * 256 ,(@posnode.toytile - mainnode_y) * 256)
				
				@hud_widget.w.lBdistance.text = @posnode.distanceto_str(to_lon, to_lat)
				
				if @w.cBautocenter.isChecked then
					@offset_x = @posnode.toxtile - mainnode_x
					@offset_y = @posnode.toytile - mainnode_y
					movemap(@node)
				end
				if @mytrack_current >= 0 and @w.pBrecordTrack.isChecked then
					if @mytracks[@mytrack_current].nil? then
						@mytracks[@mytrack_current] = Way.new(1, 'user', Time.now, nextcolor)
						@linepen.setColor(Qt::Color.new(@mytracks[@mytrack_current].color))
						@prev_track_node = false
					end
					@mytracks[@mytrack_current] << Node.new(nil, Time.now, @posnode.lon, @posnode.lat, @alt / 3.281)
					n = @mytracks[@mytrack_current].nodes.last
					n.speed = @speed
					if !@prev_track_node then
						@tckpath = Qt::PainterPath.new(Qt::PointF.new((n.toxtile - mainnode_x) * 256, (n.toytile - mainnode_y) * 256))
						@mytracks[@mytrack_current].path=TrackGraphicsPathItem.new(@mytracks[@mytrack_current])
						@mytracks[@mytrack_current].path.setPath(@tckpath)
						@mytracks[@mytrack_current].path.setZValue(Z_VALUE_TRACK)
						@mytracks[@mytrack_current].path.setPen(@linepen)
						@scene.addItem(@mytracks[@mytrack_current].path)
						@prev_track_node = true
					else
						@tckpath.lineTo((n.toxtile - mainnode_x) * 256, (n.toytile - mainnode_y) * 256)
						@mytracks[@mytrack_current].path.setPath(@tckpath)
					end
				end
				
			end # if [email protected]?
		end # if @fs_ans.length>0
		@fs_ans=[]
	end # socket nil
#		p "wakeupTimer out"
end

#writeFlightsim(element) ⇒ Object



924
925
926
927
928
929
930
931
932
933
934
# File 'lib/main-dlg-impl.rb', line 924

def writeFlightsim(element)
	@queryMutex.synchronize {
		@fs_socket.print(element + "\r\n")
		s = ""
		while select([@fs_socket], nil, nil, 0.3) do
			s += @fs_socket.read(1)
			# check for end of line characterized by this string: "\r\n/>"
			break	if s[-4..-1] == "\r\n/>"
		end
	}
end

#zoomminusObject



400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
# File 'lib/main-dlg-impl.rb', line 400

def zoomminus 
	@httpThreads.each do |th|
		th.kill
	end
	@remainingTiles = 0
	@httpThreads = Array.new
	@currentlyDownloading = Array.new
	@currentlyDownloadingElevation = Array.new
	@scene.removeItem(@warningText)

	@zoom -= 1
	@zoom=17 if @zoom>17
	@zoom=3 if @zoom<3
	@w.lBzoom.setText(@zoom.to_s)
	@node.zoom(@zoom)
	@offset_x /= 2
	@offset_y /= 2
	movemap(@node, true)
end

#zoomplusObject



380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
# File 'lib/main-dlg-impl.rb', line 380

def zoomplus
	@httpThreads.each do |th|
		th.kill
	end
	@httpThreads = Array.new
	@currentlyDownloading = Array.new
	@currentlyDownloadingElevation = Array.new
	@remainingTiles = 0
	@scene.removeItem(@warningText)

	@zoom += 1
	@zoom=17 if @zoom>17
	@zoom=3 if @zoom<3
	@w.lBzoom.setText(@zoom.to_s)
	@node.zoom(@zoom)
	@offset_x *= 2
	@offset_y *= 2
	movemap(@node, true)
end