### Rectangle Tool
#
module Tools2D
class RectangleTool2D

def db(string)
  dir=File.dirname(__FILE__) ### adjust folder to suit tool
  toolname="2Dtools"  ### adjust xxx to suit tool...
  locale=Sketchup.get_locale.upcase
  path=File.join(dir, toolname+locale+".lingvo")
  unless File.exist?(path)
     return string
  else
    deBabelizer(string,path)
  end 
end#def

def getExtents
    bbox=Sketchup.active_model.bounds
    bbox.add(@ip.position)if @ip and @ip.valid?
    bbox.add(@ip1.position)if @ip1 and @ip1.valid?
    bbox.add(@ip2.position)if @ip2 and @ip2.valid?
    bbox.add(@ip3.position)if @ip3 and @ip3.valid?
    return bbox
end

@@cursor=nil
def initialize()
    @ip = Sketchup::InputPoint.new
    @ip1 = Sketchup::InputPoint.new
    @@cursor=nil
    curpath=File.join(File.dirname(__FILE__), "Icons", "2Drectangle_cursor.png")
    @@cursor=UI::create_cursor(curpath, 0, 31) if File.exist?(curpath)
end

def reset
    ### get/set reference plane 'z'
    @z=Sketchup.active_model.get_attribute("2Dtools","z",nil)
    Sketchup.active_model.set_attribute("2Dtools","z",0.0.mm)if not @z
    @z=Sketchup.active_model.get_attribute("2Dtools","z",nil)
    @zmsg=" [ Z="+@z.to_s+" ] "
    @points = []
    @state = 0
    @ip1.clear
    @drawn = false
    Sketchup::set_status_text("", SB_VCB_LABEL)
    Sketchup::set_status_text("", SB_VCB_VALUE)
    Sketchup::set_status_text((db("2D Rectangle:"))+@zmsg+(db(" Click 1 on Corner - Toggles: Ctrl=Cline, Alt=Polyline")))
    @shift_down_time = Time.now
end

def activate
    @ctrl=false
    @ctrlmsg=""
    @alt=false
    @altmsg=""
    self.reset()
end

def deactivate(view)
    view.invalidate if @drawn
    Sketchup::set_status_text("",SB_PROMPT)
    Sketchup::set_status_text("",SB_VCB_LABEL)
    Sketchup::set_status_text("",SB_VCB_VALUE)
end

def onSetCursor()
    #return nil if RUBY_PLATFORM =~ /darwin/
	UI::set_cursor(@@cursor)if @@cursor
end

def resume(view)
  view.invalidate
  if @state==0
    Sketchup::set_status_text((db("2D Rectangle:"))+@zmsg+(db(" Click 1 on Corner - Toggles: Ctrl=Cline, Alt=Polyline")))
  elsif @state==1
    Sketchup::set_status_text("", SB_VCB_LABEL)
    Sketchup::set_status_text((db("2D Rectangle:"))+@zmsg+(db(" Click 1 on Corner - Toggles: Ctrl=Cline, Alt=Polyline")))
  else
    Sketchup::set_status_text((db("2D Rectangle:"))+@zmsg+(db(" Click 2 on Corner - Toggles: Ctrl=Cline, Alt=Polyline"))+@ctrlmsg+@altmsg)
    Sketchup::set_status_text((db("Width")), SB_VCB_LABEL)
  end#if
end

def set_current_point(x, y, view)
    if not @ip.pick view, x, y, @ip1
        return false
    end
    need_draw = true
    # Set the tooltip that will be displayed
    view.tooltip = @ip.tooltip   
    # Compute points
    case @state
    when 0
        Sketchup::set_status_text("", SB_VCB_LABEL)
        Sketchup::set_status_text("", SB_VCB_VALUE)
        Sketchup::set_status_text((db("2D Rectangle:"))+@zmsg+(db(" Click 1 on Corner - Toggles: Ctrl=Cline, Alt=Polyline")))
        @points[0] = @ip.position
        @points[0].z=@z
        @points[4] = @points[0]
        @points[4].z=@z
        need_draw = @ip.display? || @drawn
        if @alt
          view.drawing_color = "orange"
        else
          view.drawing_color = "black"
        end#if
    when 1
        Sketchup::set_status_text((db("2D Rectangle:"))+@zmsg+(db(" Click 2 on Corner - Toggles: Ctrl=Cline, Alt=Polyline"))+@ctrlmsg+@altmsg)
        Sketchup::set_status_text((db("Width")), SB_VCB_LABEL)
        @points[1] = @ip.position
        @points[1].z=@z
        @width = @points[0].distance @points[1]
        #Sketchup::set_status_text(@width.to_s, SB_VCB_VALUE)
        if @alt
          view.drawing_color = "orange"
        else
          view.drawing_color = "black"
        end#if
    when 2
        Sketchup::set_status_text((db("2D Rectangle:"))+@zmsg+(db(" Click 3 on Corner - Toggles: Ctrl=Cline, Alt=Polyline"))+@ctrlmsg+@altmsg)
        Sketchup::set_status_text((db("Height")), SB_VCB_LABEL)
        pt1 = @ip.position
        pt1.z=@z
        pt2 = pt1.project_to_line @points
        vec = pt1 - pt2
        @height = vec.length
        if @height > 0 ### test for a square
            square_point = pt2.offset(vec, @width)
            if view.pick_helper.test_point(square_point, x, y)
                @height = @width
                @points[2] = @points[1].offset(vec, @height)
                @points[3] = @points[0].offset(vec, @height)
                view.tooltip = db("=Square")
            else
                @points[2] = @points[1].offset(vec)
                @points[3] = @points[0].offset(vec)
            end
        else
            @points[2] = @points[1]
            @points[3] = @points[0]
            @points[2].z=@z
            @points[3].z=@z
        end
        if @alt
          view.drawing_color = "orange"
        else
          view.drawing_color = "black"
        end#if
        Sketchup::set_status_text(@height.to_s, SB_VCB_VALUE)
    end
    view.invalidate if need_draw
end

def onMouseMove(flags, x, y, view)
    self.set_current_point(x, y, view)
end

def create_rectangle
   # check for zero height
   Sketchup.active_model.start_operation(db("2D Rectangle"))
   if @points[0] != @points[3]
    if @ctrl
      (@points.length-1).times do |i|
          Sketchup.active_model.active_entities.add_cline(@points[i],@points[i+1])
       end#times
    elsif @alt
      Sketchup.active_model.active_entities.add_curve(@points)
    else
      Sketchup.active_model.active_entities.add_line(@points[0],@points[1])
      Sketchup.active_model.active_entities.add_line(@points[1],@points[2])
      Sketchup.active_model.active_entities.add_line(@points[2],@points[3])
      Sketchup.active_model.active_entities.add_line(@points[3],@points[0])
      ### ignore @points[4] to make face-able...
    end
   end#if
   Sketchup.active_model.commit_operation
   self.reset()
end

def increment_state
    @state += 1
    case @state
      when 1
        @ip1.copy! @ip
        Sketchup::set_status_text((db("2D Rectangle:"))+@zmsg+(db(" Click 2 on Corner - Toggles: Ctrl=Cline, Alt=Polyline"))+@ctrlmsg+@altmsg)
        Sketchup::set_status_text((db("Width")), SB_VCB_LABEL)
      when 2
        ###@ip1.clear
        @ip1.copy! @ip
        Sketchup::set_status_text((db("2D Rectangle:"))+@zmsg+(db(" Click 3 on Corner - Toggles: Ctrl=Cline, Alt=Polyline"))+@ctrlmsg+@altmsg)
        Sketchup::set_status_text((db("Height")), SB_VCB_LABEL)
      when 3
        self.create_rectangle
    end
end

def onLButtonDown(flags, x, y, view)
    self.set_current_point(x, y, view)
    self.increment_state
    view.lock_inference
end

def onCancel(flag, view)
    view.invalidate if @drawn
    self.reset()
    if @points[1]
      view.invalidate
      self.reset(view)
    else
      view.invalidate
      Sketchup::set_status_text("",SB_PROMPT)
      Sketchup.send_action("selectSelectionTool:")
    end#if
end

def enableVCB?
   return true
end
 
# This is called when the user types a value into the VCB
def onUserText(text, view)
    # The user may type in something that we can't parse as a length
    # so we set up some exception handling to trap that
    begin
        value = text.to_l
    rescue
        # Error parsing the text
        UI.beep
        value = nil
        Sketchup::set_status_text "", SB_VCB_VALUE
    end
    return if !value
    
    case @state
    when 1
        # update the width
        vec = @points[1] - @points[0]
        if( vec.length > 0.0 )
            vec.length = value
            @points[1] = @points[0].offset(vec)
            view.invalidate
            self.increment_state
        end
    when 2
        # update the height
        vec = @points[3] - @points[0]
        if( vec.length > 0.0 )
            vec.length = value
            @points[2] = @points[1].offset(vec)
            @points[3] = @points[0].offset(vec)
            self.increment_state
        end
    end
end


def draw(view)
    @drawn = false
    # Show the current input point
    if @ip.valid? && @ip.display?
        @ip.draw(view)
        @drawn = true
    end
    if @ctrl
        view.line_stipple="-"
    else
        view.line_stipple=""
    end#if
    if @alt
        view.drawing_color = "orange"
    else
        view.drawing_color = "black"
    end#if
    # show the rectangle
    if @state == 1 # just draw a line from the start to the end point
        view.set_color_from_line(@ip1, @ip)
        inference_locked = view.inference_locked?
        view.line_width = 3 if inference_locked
        view.draw_polyline([@points[0],@points[1]])
        view.line_width = 1 if inference_locked
        @drawn = true
    elsif @state > 1 # draw all
        view.dynamic=true
        view.draw_polyline(@points)
        view.invalidate
        @drawn = true
    end
end

def onKeyDown(key, rpt, flags, view)
    if key == CONSTRAIN_MODIFIER_KEY && rpt == 1
        @shift_down_time = Time.now
        # if we already have an inference lock, then unlock it
        if( view.inference_locked? )
            view.lock_inference
        elsif( @state == 0 )
            view.lock_inference @ip
        elsif( @state == 1 )
            view.lock_inference @ip, @ip1
        end
    end
    if key==VK_CONTROL || key==VK_COMMAND  ### Ctrl toggles lines / clines
      if @ctrl
        @ctrl=false; @ctrlmsg=""
      else
        @ctrl=true; @ctrlmsg=db(" [as Clines]")
        @alt=false; @altmsg=""
      end#if
    end#if
    if key==VK_ALT  ### Alt toggles lines / polylines
      if @alt
        @alt=false; @altmsg=""
      else
        @alt=true; @altmsg=db(" [as PolyLines]")
        @ctrl=false; @ctrlmsg=""
      end#if
    end#if
end

def onKeyUp(key, rpt, flags, view)
    if key == CONSTRAIN_MODIFIER_KEY && view.inference_locked? && (Time.now - @shift_down_time) > 0.5
        view.lock_inference
    end
end

end # class

end#mod
#-----------------------------------------------------------------------------
# shortcut
#def rectangletool2D
    #Sketchup.active_model.select_tool RectangleTool2D.new
#end
######-----------------------------------------------

