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.



87
88
89
90
91
92
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
# File 'lib/main-dlg-impl.rb', line 87

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)

  @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)

  @node = Node.new(1, Time.now, @lon, @lat, 0, @zoom)
  @rot = 0
  @remainingTiles = 0
  @httpThreads = Array.new
  
  @navs = Navaid.new(arg)
  
  @httpMutex = Mutex.new
  @queryMutex = Mutex.new
    
  @scene=Qt::GraphicsScene.new()
  @w.gVmap.setScene(@scene)
  @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}\""
end

Instance Attribute Details

#flagObject (readonly)

Returns the value of attribute flag.



78
79
80
# File 'lib/main-dlg-impl.rb', line 78

def flag
  @flag
end

Returns the value of attribute menu.



78
79
80
# File 'lib/main-dlg-impl.rb', line 78

def menu
  @menu
end

#metricUnitObject

Returns the value of attribute metricUnit.



81
82
83
# File 'lib/main-dlg-impl.rb', line 81

def metricUnit
  @metricUnit
end

#mytrack_currentObject

Returns the value of attribute mytrack_current.



78
79
80
# File 'lib/main-dlg-impl.rb', line 78

def mytrack_current
  @mytrack_current
end

#mytracksObject (readonly)

Returns the value of attribute mytracks.



78
79
80
# File 'lib/main-dlg-impl.rb', line 78

def mytracks
  @mytracks
end

#nodeObject

Returns the value of attribute node.



78
79
80
# File 'lib/main-dlg-impl.rb', line 78

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.



80
81
82
# File 'lib/main-dlg-impl.rb', line 80

def offset_x=(value)
  @offset_x = value
end

#offset_yObject

Returns the value of attribute offset_y.



78
79
80
# File 'lib/main-dlg-impl.rb', line 78

def offset_y
  @offset_y
end

#sceneObject (readonly)

Returns the value of attribute scene.



78
79
80
# File 'lib/main-dlg-impl.rb', line 78

def scene
  @scene
end

#scene_tilesObject

Returns the value of attribute scene_tiles.



78
79
80
# File 'lib/main-dlg-impl.rb', line 78

def scene_tiles
  @scene_tiles
end

#toffset_xObject (readonly)

Returns the value of attribute toffset_x.



78
79
80
# File 'lib/main-dlg-impl.rb', line 78

def toffset_x
  @toffset_x
end

#wObject

Returns the value of attribute w.



78
79
80
# File 'lib/main-dlg-impl.rb', line 78

def w
  @w
end

#waypointsObject

Returns the value of attribute waypoints.



78
79
80
# File 'lib/main-dlg-impl.rb', line 78

def waypoints
  @waypoints
end

#zoomObject (readonly)

Returns the value of attribute zoom.



78
79
80
# File 'lib/main-dlg-impl.rb', line 78

def zoom
  @zoom
end

Instance Method Details

#addNavToScene(vor, origin_x, origin_y) ⇒ Object



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

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



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

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) ⇒ Object



385
386
387
388
389
390
391
392
393
394
395
# File 'lib/main-dlg-impl.rb', line 385

def addTileToScene(f, origin_x, origin_y)
  pmi=TileGraphicsPixmapItem.new(Qt::Pixmap.new(f))
  @scene_tiles << f
  f =~ /\/(\d*)\/(\d*)\/(\d*)/
  x = $2.to_i
  y = $3.to_i
#   p x - origin_x,y - origin_y
  pmi.setOffset((x - origin_x)*256, (y - origin_y)*256)
  pmi.setZValue(Z_VALUE_TILES)
  @scene.addItem(pmi)
end

#autosaveTimerObject



802
803
804
# File 'lib/main-dlg-impl.rb', line 802

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

#cBndb_clickedObject



849
850
851
# File 'lib/main-dlg-impl.rb', line 849

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

#cBpointorigin_clickedObject



820
821
822
# File 'lib/main-dlg-impl.rb', line 820

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

#cBrw_clickedObject



853
854
855
# File 'lib/main-dlg-impl.rb', line 853

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

#cBvor_clickedObject



845
846
847
# File 'lib/main-dlg-impl.rb', line 845

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

#get_data(path) ⇒ Object



172
173
174
175
176
177
178
# File 'lib/main-dlg-impl.rb', line 172

def get_data(path)
  r=@fs_ans.detect do |f|
    f.include?(path)
  end
  r =~ /-?\d+\.\d+/
  return $&.to_f
end

#keyPressEvent(keyevent) ⇒ Object



862
863
864
865
866
867
868
869
870
871
872
873
# File 'lib/main-dlg-impl.rb', line 862

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

#loadtrack(title) ⇒ Object



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
276
277
278
279
280
281
282
# File 'lib/main-dlg-impl.rb', line 246

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



284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
# File 'lib/main-dlg-impl.rb', line 284

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



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
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
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
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
# File 'lib/main-dlg-impl.rb', line 452

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

  if repaint then
    @scene_tiles = []
    @scene_navs = []
    @scene_rws = []
    @scene.clear
    # 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 = []
    @scene.clear
  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 = []
    @scene.clear
  end

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

  fn.each{|f|
    if !@scene_tiles.include?(f)
      if FileTest.exist?(f+".png") then
        addTileToScene(f, origin_x, origin_y)
      elsif downloadTiles and (@timeNoInternet.nil? or (Time.now - @timeNoInternet) > 60) then
#         Thread.abort_on_exception = true
        @httpThreads << Thread.new {
          @remainingTiles += 1
          @httpMutex.synchronize {
            h = Net::HTTP.new('tile.openstreetmap.org')
            h.open_timeout = 10
            @warningText = Qt::GraphicsSimpleTextItem.new("#{@remainingTiles} remaining tiles")
            @warningText.setBrush(Qt::Brush.new(Qt::Color.new("red")))
            @scene.addItem(@warningText)
            fontInfo = Qt::FontInfo.new(@warningText.font)
            @warningText.setPos(@w.gVmap.mapToScene((@w.gVmap.size.width - @warningText.boundingRect.width)/2, 
                  @w.gVmap.size.height - fontInfo.pixelSize - 10))

            f =~ /\/\d+\/\d+\/\d+$/
            f = $&
            begin
              resp, data = h.get(f + ".png", nil)
              if resp.kind_of?(Net::HTTPOK) then
                maindir = Dir.pwd
                Dir.chdir($MAPSHOME)
                f.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 + f + ".png", "w") do |file|
                  file.write(data)
                end
                addTileToScene($MAPSHOME + f, origin_x, origin_y)
              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
            @scene.removeItem(@warningText)
          }
          @remainingTiles -= 1
        }
      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



194
195
196
197
198
199
200
201
202
203
# File 'lib/main-dlg-impl.rb', line 194

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



832
833
834
835
836
837
838
839
840
841
842
843
# File 'lib/main-dlg-impl.rb', line 832

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.sync
  @parent.close
end

#pBminus_clickedObject



824
825
826
# File 'lib/main-dlg-impl.rb', line 824

def pBminus_clicked()
  zoomminus
end

#pBplus_clickedObject



828
829
830
# File 'lib/main-dlg-impl.rb', line 828

def pBplus_clicked()
  zoomplus
end

#pBrecordTrack_toggled(state) ⇒ Object



806
807
808
809
810
811
812
813
814
815
816
817
818
# File 'lib/main-dlg-impl.rb', line 806

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



180
181
182
183
184
185
186
187
188
189
190
191
192
# File 'lib/main-dlg-impl.rb', line 180

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

#resize(*k) ⇒ Object



857
858
859
860
# File 'lib/main-dlg-impl.rb', line 857

def resize(*k)
  super
  @hud.setPos(@w.gVmap.mapToScene(0,0)) if !@hud.nil?
end

#savetrack(items, warn = true) ⇒ Object



205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
# File 'lib/main-dlg-impl.rb', line 205

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



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
340
341
342
343
344
345
346
347
# File 'lib/main-dlg-impl.rb', line 308

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



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

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
  return if @wakeupCounter <= TICKSTOSKIP
  @wakeupCounter = 0

  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
    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
    else # rescue
      #ap @fs_ans
      if @fs_ans.length>0 then # check if any answer has been received yet.
        if !@hud.nil? then
          @posnode.lon = get_data("/position/longitude-deg")
          @posnode.lat = get_data("/position/latitude-deg")
          @rot = get_data("/orientation/heading-deg")
          @alt = get_data("/position/altitude-ft")
          speed = get_data("/velocities/groundspeed-kt") * 1.852
          # protect against bug in Flightsim, speed ofter zero if returned
          @speed = speed if speed > 0
          @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)
            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
    end # rescue
    @fs_ans=[]
  end # socket nil
end

#writeFlightsim(element) ⇒ Object



789
790
791
792
793
794
795
796
797
798
799
# File 'lib/main-dlg-impl.rb', line 789

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



367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
# File 'lib/main-dlg-impl.rb', line 367

def zoomminus 
  @httpThreads.each do |th|
    th.kill
  end
  @remainingTiles = 0
  @httpThreads = 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



349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
# File 'lib/main-dlg-impl.rb', line 349

def zoomplus
  @httpThreads.each do |th|
    th.kill
  end
  @httpThreads = 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