Class: MainDlg

Inherits:
Qt::Widget
  • Object
show all
Defined in:
lib/fgmapping/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.



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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
# File 'lib/fgmapping/main-dlg-impl.rb', line 110

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.to_s)).toDouble
  @lon = @cfg.value("lon",Qt::Variant.new(LONSTARTUP.to_s)).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).to_s)).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.



101
102
103
# File 'lib/fgmapping/main-dlg-impl.rb', line 101

def flag
  @flag
end

Returns the value of attribute menu.



101
102
103
# File 'lib/fgmapping/main-dlg-impl.rb', line 101

def menu
  @menu
end

#metricUnitObject

Returns the value of attribute metricUnit.



104
105
106
# File 'lib/fgmapping/main-dlg-impl.rb', line 104

def metricUnit
  @metricUnit
end

#mytrack_currentObject

Returns the value of attribute mytrack_current.



101
102
103
# File 'lib/fgmapping/main-dlg-impl.rb', line 101

def mytrack_current
  @mytrack_current
end

#mytracksObject (readonly)

Returns the value of attribute mytracks.



101
102
103
# File 'lib/fgmapping/main-dlg-impl.rb', line 101

def mytracks
  @mytracks
end

#nodeObject

Returns the value of attribute node.



101
102
103
# File 'lib/fgmapping/main-dlg-impl.rb', line 101

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.



103
104
105
# File 'lib/fgmapping/main-dlg-impl.rb', line 103

def offset_x=(value)
  @offset_x = value
end

#offset_yObject

Returns the value of attribute offset_y.



101
102
103
# File 'lib/fgmapping/main-dlg-impl.rb', line 101

def offset_y
  @offset_y
end

#sceneObject (readonly)

Returns the value of attribute scene.



101
102
103
# File 'lib/fgmapping/main-dlg-impl.rb', line 101

def scene
  @scene
end

#scene_tilesObject

Returns the value of attribute scene_tiles.



101
102
103
# File 'lib/fgmapping/main-dlg-impl.rb', line 101

def scene_tiles
  @scene_tiles
end

#toffset_xObject (readonly)

Returns the value of attribute toffset_x.



101
102
103
# File 'lib/fgmapping/main-dlg-impl.rb', line 101

def toffset_x
  @toffset_x
end

#wObject

Returns the value of attribute w.



101
102
103
# File 'lib/fgmapping/main-dlg-impl.rb', line 101

def w
  @w
end

#waypointsObject

Returns the value of attribute waypoints.



101
102
103
# File 'lib/fgmapping/main-dlg-impl.rb', line 101

def waypoints
  @waypoints
end

#zoomObject (readonly)

Returns the value of attribute zoom.



101
102
103
# File 'lib/fgmapping/main-dlg-impl.rb', line 101

def zoom
  @zoom
end

Instance Method Details

#addNavToScene(vor, origin_x, origin_y) ⇒ Object



522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
# File 'lib/fgmapping/main-dlg-impl.rb', line 522

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



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
# File 'lib/fgmapping/main-dlg-impl.rb', line 547

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



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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
# File 'lib/fgmapping/main-dlg-impl.rb', line 455

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+".png", (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+".png"), @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.request_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.syswrite(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



972
973
974
# File 'lib/fgmapping/main-dlg-impl.rb', line 972

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

#cBndb_clickedObject



1020
1021
1022
# File 'lib/fgmapping/main-dlg-impl.rb', line 1020

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

#cBpointorigin_clickedObject



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

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

#cBrw_clickedObject



1024
1025
1026
# File 'lib/fgmapping/main-dlg-impl.rb', line 1024

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

#cBshadows_clickedObject



1028
1029
1030
# File 'lib/fgmapping/main-dlg-impl.rb', line 1028

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

#cBvor_clickedObject



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

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

#get_data(path) ⇒ Object



219
220
221
222
223
224
225
226
# File 'lib/fgmapping/main-dlg-impl.rb', line 219

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+)' \(double\)/
  return $1.to_f
end

#hSopacity_changed(opacity) ⇒ Object



1050
1051
1052
1053
# File 'lib/fgmapping/main-dlg-impl.rb', line 1050

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

#keyPressEvent(keyevent) ⇒ Object



1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
# File 'lib/fgmapping/main-dlg-impl.rb', line 1037

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

#loadtrack(title) ⇒ Object



299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
# File 'lib/fgmapping/main-dlg-impl.rb', line 299

def loadtrack(title)  
  fn=Qt::FileDialog::getOpenFileName(nil, title, $MAPSHOME + "/tracks/", "Track-Data (*.gpx *.log);;All (*)")
  if !fn.nil? then
    success = false
    file=File.new(fn)
    begin
      doc = REXML::Document.new(file)

      doc.elements.each("/gpx/trk") do |trk|
        @mytrack_current -= 1
        trk.elements.each("trkseg") do |seg|
          @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
          seg.elements.each("trkpt") do |tpt|
            usec = tpt.elements["time_us"].text.strip
            usec = (usec.nil? ? "0" : usec)
            loc = tpt.attributes # lon and lat as a hash
            track << Node.new(nil, tpt.elements["time"].text.strip + usec, \
                loc["lon"].to_f, loc["lat"].to_f, \
                tpt.elements["ele"].text.to_f)
            success = true
          end
        end
      end
    rescue Errno::EISDIR
      # swallow error, "success" is false anyway
    end

    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



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
# File 'lib/fgmapping/main-dlg-impl.rb', line 341

def loadwaypoint(title) 
  fn=Qt::FileDialog::getOpenFileName(nil, title, $MAPSHOME + "/waypoints/", "Waypoint-Data (*.gpx *.log);;All (*)")
  if !fn.nil? then
    success = false
    file=File.new(fn)
    begin
      doc = REXML::Document.new(file)
      @waypoints = Way.new(nil,'user', Time.now, "Blue")
      doc.elements.each("/gpx/wpt") do |wpt|
        loc = wpt.attributes # lon and lat as a hash
        @waypoints << Node.new(nil, wpt.elements["time"].text.strip,
              loc["lon"].to_f, loc["lat"].to_f, \
              wpt.elements["ele"].text.to_f)
        success = true
      end
      file.close
      if success then
        movemap(@node, true)
      else
        Qt::MessageBox::warning(nil, "Warning", "No data found in file.")
      end
      return success
    rescue Errno::EISDIR
      Qt::MessageBox::warning(nil, "Warning", "You selected a directory, not a file. Nothing loaded.")
      return success
    end
  end
end

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



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
750
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
784
# File 'lib/fgmapping/main-dlg-impl.rb', line 577

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.request_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.syswrite(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



242
243
244
245
246
247
248
249
250
251
# File 'lib/fgmapping/main-dlg-impl.rb', line 242

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



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

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



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

def pBminus_clicked()
  zoomminus
end

#pBplus_clickedObject



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

def pBplus_clicked()
  zoomplus
end

#pBrecordTrack_toggled(state) ⇒ Object



976
977
978
979
980
981
982
983
984
985
986
987
988
# File 'lib/fgmapping/main-dlg-impl.rb', line 976

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



228
229
230
231
232
233
234
235
236
237
238
239
240
# File 'lib/fgmapping/main-dlg-impl.rb', line 228

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



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
# File 'lib/fgmapping/main-dlg-impl.rb', line 786

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.8) 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



206
207
208
209
210
211
212
213
214
215
216
217
# File 'lib/fgmapping/main-dlg-impl.rb', line 206

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



1032
1033
1034
1035
# File 'lib/fgmapping/main-dlg-impl.rb', line 1032

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

#savetrack(items, warn = true) ⇒ Object



253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
# File 'lib/fgmapping/main-dlg-impl.rb', line 253

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 = REXML::Document.new 
    doc << REXML::XMLDecl.new(REXML::XMLDecl::DEFAULT_VERSION, REXML::XMLDecl::DEFAULT_ENCODING)

    doc.add_element('gpx')

    node=REXML::XPath.first(doc, "//gpx")
    node.add_namespace("http://www.topografix.com/GPX/1/1")
    node.add_attributes({'creator'=>"ruby-tracker", "version"=>"1.1"} )
    node.add_namespace("xsi", "http://www.w3.org/2001/XMLSchema-instance")

    tracknode = REXML::Element.new("trk")
    node.add_element(tracknode)
    items.each{|track|
      segnode = REXML::Element.new("trkseg")
      tracknode.add_element(segnode)
      track.nodes.each{|n|
        trackpoint = REXML::Element.new("trkpt")
        trackpoint.add_attributes({"lat" => n.lat.to_s.gsub(",","."), "lon" => n.lon.to_s.gsub(",",".")})
        trackpoint.add_text_element("ele", n.elevation.to_s.gsub(",","."))
        trackpoint.add_text_element("time", n.toGPStime)
        trackpoint.add_text_element("time_us", n.timestamp.usec.to_s)
        segnode.add_element(trackpoint)
      }
    }
    File.open($MAPSHOME + "/tracks/" + items.first.nodes.first.toGPStime + ".gpx", "w+"){|f|
      begin
        doc.write(f, 2)
      rescue Errno::EISDIR
        Qt::MessageBox::warning(nil, "Warning", "You selected a directory, not a file. Nothing saved.")
      end
    }
    ap "xml-file written"
  end
end

#saveWaypoints(waypoints) ⇒ Object



370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
# File 'lib/fgmapping/main-dlg-impl.rb', line 370

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 = REXML::Document.new 
    doc << REXML::XMLDecl.new(REXML::XMLDecl::DEFAULT_VERSION, REXML::XMLDecl::DEFAULT_ENCODING)

    doc.add_element('gpx')
    root=REXML::XPath.first(doc, "//gpx")
    root.add_namespace("http://www.topografix.com/GPX/1/1")
    root.add_attributes({'creator'=>"ruby-tracker", "version"=>"1.1"} )
    root.add_namespace("xsi", "http://www.w3.org/2001/XMLSchema-instance")

    waypoints[0].nodes.each{|n|
      if !n.nil? then
        wpnode = REXML::Element.new("wpt")
        root.add_element(wpnode)
        wpnode.add_attributes({"lat" => n.lat.to_s.gsub(",","."), "lon" => n.lon.to_s.gsub(",",".")})
        wpnode.add_text_element("ele", n.elevation.to_s.gsub(",","."))
        wpnode.add_text_element("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|
        begin
          doc.write(f, 2)
        rescue Errno::EISDIR
          Qt::MessageBox::warning(nil, "Warning", "You selected a directory, not a file. Nothing saved.")
        end
      }
    end
  end
end

#wakeupTimerObject



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
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
# File 'lib/fgmapping/main-dlg-impl.rb', line 820

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



959
960
961
962
963
964
965
966
967
968
969
# File 'lib/fgmapping/main-dlg-impl.rb', line 959

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



435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
# File 'lib/fgmapping/main-dlg-impl.rb', line 435

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



415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
# File 'lib/fgmapping/main-dlg-impl.rb', line 415

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