### Text Tool
#
module Tools2D
class TextTool2D

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 TextTool2D::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 = nil
    @ip1 = nil
    @xdown = 0
    @ydown = 0
	@@cursor=nil
    curpath=File.join(File.dirname(__FILE__), "Icons", "2Dtext_cursor.png")
    @@cursor=UI::create_cursor(curpath, 0, 31) if File.exist?(curpath)
end

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

def activate
    @component=nil
    @instance=nil
    @fontlist=TextTool2D::fontlist
    ### 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)
    ###
    @ip1 = Sketchup::InputPoint.new
    @ip = Sketchup::InputPoint.new
    @drawn = false
    model=Sketchup.active_model
    model.start_operation(db("2D Text"))
    entities=model.active_entities
    definitions=model.definitions
### see if model is tagged
ht=4.inch if model.options["UnitsOptions"]["LengthUnit"]<2
ht=100.mm if model.options["UnitsOptions"]["LengthUnit"]>1
@height=model.get_attribute("2DText","height",ht)
@align=model.get_attribute("2DText","align",(db("Center")))
@font=model.get_attribute("2DText","font","Arial")
@bold=model.get_attribute("2DText","bold",(db("No")))
@italic=model.get_attribute("2DText","italic",(db("No")))
@filled=model.get_attribute("2DText","filled",(db("Yes")))
@color=model.get_attribute("2DText","color","Black")
@snap=model.get_attribute("2DText","snap",(db("Z-plane")))
### NOW set text and other
@other=model.get_attribute("2DText","other",(db("Yes")))
@text=model.get_attribute("2DText","text",nil)
@text=(db("2DText                                                  ")) if not @text
### +64 trailing spaces
### set VCB
    Sketchup::set_status_text((db("2D Text...")), SB_PROMPT)
    if @snap!="Z-plane"
        Sketchup::set_status_text((db("Snap-Mode")),SB_VCB_LABEL)
        Sketchup::set_status_text((db("Any Face...")), SB_VCB_VALUE)
    else ###==Any
        Sketchup::set_status_text((db("Snap-Mode")),SB_VCB_LABEL)
        Sketchup::set_status_text("Z=#{@z.to_l}", SB_VCB_VALUE)
    end#if
### do dialog... ###<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
 if not self.dialog
    self.onCancel(nil,nil)
 else ### dialog gave result...
###
@text=@text.strip+"                                                  "### 64 spaces
  text=@text.strip.gsub(/\\n/,"\n")### removes trailing/leading spaces
### align 0/1/2
  align=0 if @align==(db("Left"))
  align=1 if @align==(db("Center"))
  align=2 if @align==(db("Right"))
### other settings Y/N = True/False
  bold=true;bold=false if @bold==(db("No"))
  italic=true;italic=false if @italic==(db("No"))
  filled=true
  filled=false if @filled==(db("No"))
###
if @snap==(db("Z-plane"))
  @component=definitions.add("~2DText#1")
  definitions.unique_name("~2DText#1")
  @component.description=db("2D Text Snaps to Horizontal Faces")
else ### All-Faces
  @component=definitions.add("~2DText[3D]#1")
  definitions.unique_name("~2DText[3D]#1")
  @component.description=db("2D Text Snaps to All Faces")
end#if
ents=@component.entities
### lift @component up standoff 1mm so can be seen above faces
pt=Geom::Point3d.new(0,0,1.mm)
t=Geom::Transformation.new(pt)
g=ents.add_group()
g.entities.add_3d_text(text,align,@font,bold,italic,@height,1.mm,0,filled,0)
g.move!(t); g.explode
### sort out edges and faces of text
edges=[];ents.each{|e|edges<<e if e.class==Sketchup::Edge}
faces=[];ents.each{|e|faces<<e if e.class==Sketchup::Face}
edges.each{|e|e.hidden=true if e.valid? and @filled==(db("Yes"))}
faces.each{|e|
  e.material=@color
  e.back_material=@color
  e.reverse! if e.normal.z<0 ### so faces up
  e.erase! if filled==(db("No"))
}
faces.each{|e|e.erase! if e.valid? and @filled==(db("No"))}
### catches left over faces
### fix colors
@color=(db("<Default>")) if @color==nil
@component.behavior.always_face_camera=false ###
###
@component.behavior.is2d=true
@component.behavior.snapto=1 if @snap==(db("Z-plane")) ### snaps to horizontal faces
@component.behavior.snapto=0 if @snap!=(db("Z-plane")) ### snaps to any face
###
ents.each{|e|e.casts_shadows=false; e.receives_shadows=false}
### set text @component attributes
@component.set_attribute("2DText","text",@text)
@component.set_attribute("2DText","height",@height)
@component.set_attribute("2DText","align",@align)
@component.set_attribute("2DText","font",@font)
@component.set_attribute("2DText","bold",@bold)
@component.set_attribute("2DText","italic",@italic)
@component.set_attribute("2DText","filled",@filled)
@component.set_attribute("2DText","color",@color)
@component.set_attribute("2DText","snap",@snap)
### give model current settings as attributes
model.set_attribute("2DText","height",@height)
model.set_attribute("2DText","align",@align)
model.set_attribute("2DText","font",@font)
model.set_attribute("2DText","bold",@bold)
model.set_attribute("2DText","italic",@italic)
model.set_attribute("2DText","filled",@filled)
model.set_attribute("2DText","color",@color)
model.set_attribute("2DText","snap",@snap)
model.set_attribute("2DText","other",@other)
model.set_attribute("2DText","text",@text)
###
### place 2Dtext compo ### v3.5
#@component.refresh_thumbnail if Sketchup.version.split('.')[0].to_i >= 7
@instance=nil
if @snap==(db("Z-plane"))
  tr=Geom::Transformation.new(ORIGIN)###
  @instance=entities.add_instance(@component,tr)
  @wait=true
else ### snap to any face
  model.place_component(@component)
  @wait=false
end#if
### made component
 end#if dialog
 model.commit_operation if not @wait
 #self.onCancel(nil,nil)
 ###
end

# onCancel is called when the user hits the escape key
def onCancel(flag, view)
    @instance.erase! if @instance and @instance.valid?
    if @component
      view.model.start_operation(db("Delete 2D Text Component"))
        @component.entities.erase_entities(@component.entities.to_a)
      view.model.commit_operation
    end#if
    view.invalidate if view
    Sketchup::set_status_text("",SB_PROMPT)
    Sketchup::set_status_text("",SB_VCB_LABEL)
    Sketchup::set_status_text("",SB_VCB_VALUE)
    Sketchup.send_action("selectSelectionTool:")
    return nil
end

def onMouseMove(flags, x, y, view)
    view.lock_inference
    @ip.pick view, x, y
    if @ip.valid?
        @ip1.copy! @ip
        view.tooltip=(db("2Dtext: "))+@ip1.tooltip
        if @snap==(db("Z-plane"))
          pt=@ip1.position
          pt=[pt.x,pt.y,@z]
          tr=Geom::Transformation.new(pt)### @ cursor
          @instance.transformation=(tr)if @instance
        end#if
        view.invalidate if @ip.display?
    end
end

def onLButtonDown(flags, x, y, view)
    @wait=false
    @ip1.pick view, x, y
    if @ip1.valid?
      Sketchup::set_status_text("",SB_PROMPT)
      Sketchup::set_status_text("",SB_VCB_LABEL)
      Sketchup::set_status_text("",SB_VCB_VALUE)
      ### finally place instance
      if @snap==(db("Z-plane"))
        pt=@ip1.position
        pt=[pt.x,pt.y,@z]
        tr=Geom::Transformation.new(pt)### @ cursor
        @instance.transformation=(tr)if @instance
        ###
        Sketchup::set_status_text("",SB_PROMPT)
        Sketchup::set_status_text("",SB_VCB_LABEL)
        Sketchup::set_status_text("",SB_VCB_VALUE)
        Sketchup.send_action("selectSelectionTool:")
        ###
        view.model.commit_operation
        #self.activate
      end#if
      return nil
    end
    view.invalidate
end

def dialog()
model=Sketchup.active_model
  ### get text and if other settings
  prompts=[(db("Enter Text: ")),(db("Edit Settings: "))]
  values=[@text,@other]
  popups=["",(db("Yes|No"))]
  title=db("2D Text")
  results=inputbox(prompts,values,popups,title)
  return nil if not results
  @text,@other=results
  ### do 'other' dialog
  if @other!=(db("No"))
	aligns=db("Left|Center|Right")
	fonts=@fontlist
	fonts.sort!; fonts=fonts.join("|")
	### colors
    materials=model.materials
	colors=[]; materials.each{|m|colors.push(m.display_name)}
	colors=colors+[db("<Default>")]+(Sketchup::Color.names.sort!)
	colors.uniq!; colors=colors.join("|")
	### dialog...
    prompts=[(db("Height: ")),(db("Alignment: ")),(db("Font: ")),(db("Bold: ")),(db("Italic: ")),(db("Filled: ")),(db("Color: ")),(db("Snap: "))]
    values=[@height,@align,@font,@bold,@italic,@filled,@color,@snap]
    popups=["",aligns,fonts,(db("Yes|No")),(db("Yes|No")),(db("Yes|Yes+Edges|No")),colors,(db("Z-plane|All-Faces"))]
    title=db("2D Text Settings")
    results=inputbox(prompts,values,popups,title)
    return nil if not results
    @height,@align,@font,@bold,@italic,@filled,@color,@snap=results
	### sort out colors
	@color=nil if @color==(db("<Default>"))
  end#if
  return true
end#dialog

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

def reset(view)
    Sketchup::set_status_text((db("2D Text...")), SB_PROMPT)
    if @snap!=(db("Z-plane"))
        Sketchup::set_status_text((db("Snap-Mode")),SB_VCB_LABEL)
        Sketchup::set_status_text((db("Any Face...")), SB_VCB_VALUE)
    else ###==Any
        Sketchup::set_status_text((db("Snap-Mode")),SB_VCB_LABEL)
        Sketchup::set_status_text("Z=#{@z.to_l}", SB_VCB_VALUE)
    end#if
    @ip.clear
    @ip1.clear
    if view 
      view.tooltip=nil
      view.invalidate if @drawn
    end
    @drawn = false
    @component=nil
    @instance=nil
end

def resume(view)
    view.invalidate
    Sketchup::set_status_text((db("2D Text...")), SB_PROMPT)
    if @snap!=(db("Z-plane"))
        Sketchup::set_status_text((db("Snap-Mode")),SB_VCB_LABEL)
        Sketchup::set_status_text((db("Any Face...")), SB_VCB_VALUE)
    else ###==Any
        Sketchup::set_status_text((db("Snap-Mode")),SB_VCB_LABEL)
        Sketchup::set_status_text("Z=#{@z.to_l}", SB_VCB_VALUE)
    end#if
end


def TextTool2D::edit()
  @fontlist=TextTool2D::fontlist
  ###
 def TextTool2D::sdialog()
  model=Sketchup.active_model
  @sother=model.get_attribute("2DText","other","Yes")
  ### get text and if other settings
  prompts=[(db("Enter Text: ")),(db("Edit Settings: "))]
  values=[@stext,@sother]
  popups=["",(db("Yes|No"))]
  title=db("Edit 2D Text")
  results=inputbox(prompts,values,popups,title)
  return nil if not results
  @stext,@sother=results
  model.set_attribute("2DText","other",@sother)
  ### do 'other' dialog
  if @sother!=(db("No"))
	aligns=db("Left|Center|Right")
	fonts=@fontlist
	fonts.sort!; fonts=fonts.join("|")
	### colors
    materials=model.materials
	colors=[]; materials.each{|m|colors.push(m.display_name)}
	colors=colors+[db("<Default>")]+(Sketchup::Color.names.sort!)
	colors.uniq!; colors=colors.join("|")
	### dialog...
    prompts=[(db("Height: ")),(db("Alignment: ")),(db("Font: ")),(db("Bold: ")),(db("Italic: ")),(db("Filled: ")),(db("Color: "))]
    values=[@sheight,@salign,@sfont,@sbold,@sitalic,@sfilled,@scolor]
    popups=["",aligns,fonts,(db("Yes|No")),(db("Yes|No")),(db("Yes|Yes+Edges|No")),colors]
    title=db("Edit 2D Text Settings")
    results=inputbox(prompts,values,popups,title)
    return nil if not results
    @sheight,@salign,@sfont,@sbold,@sitalic,@sfilled,@scolor=results
    ### sort out colors
	@scolor=nil if @scolor==(db("<Default>"))
  end#if
  return true
 end#sdialog
  model=Sketchup.active_model
entities=model.active_entities
selectedCompoInstance=model.selection[0]
selectedCompoInstance=selectedCompoInstance.definition
definitions=model.definitions
txt= db("Edit 2D Text")
model.start_operation(txt)
### get def's tags
ht=4.inch if model.options["UnitsOptions"]["LengthUnit"]<2
ht=100.mm if model.options["UnitsOptions"]["LengthUnit"]>1
@sheight=selectedCompoInstance.get_attribute("2DText","height",ht)
@salign=selectedCompoInstance.get_attribute("2DText","align",(db("Center")))
@sfont=selectedCompoInstance.get_attribute("2DText","font","Arial")
@sbold=selectedCompoInstance.get_attribute("2DText","bold",(db("No")))
@sitalic=selectedCompoInstance.get_attribute("2DText","italic",(db("No")))
@sfilled=selectedCompoInstance.get_attribute("2DText","filled",(db("Yes")))
@scolor=selectedCompoInstance.get_attribute("2DText","color","Black")
@ssnap=selectedCompoInstance.get_attribute("2DText","snap",(db("Z-plane")))
### NOW get text and other
@stext=selectedCompoInstance.get_attribute("2DText","text","????")
###
### dialog
### show VCB and status info
  Sketchup::set_status_text((db("Edit 2D Text...")), SB_PROMPT)
  Sketchup::set_status_text(" ", SB_VCB_LABEL)
  Sketchup::set_status_text(" ", SB_VCB_VALUE)
 if not TextTool2D::sdialog() ### do dialog...
  return nil
 else
### sort results
### ensure \n becomes a line break in text
  @stext=@stext.strip+"                                                  "
  ### 64 spaces
  text=@stext.strip.gsub(/\\n/,"\n")### removes trailing/leading spaces
### align 0/1/2
  align=0 if @salign==(db("Left"))
  align=1 if @salign==(db("Center"))
  align=2 if @salign==(db("Right"))
### other settings Y/N = True/False
  bold=true;bold=false if @sbold==(db("No"))
  italic=true;italic=false if @sitalic==(db("No"))
  filled=true
  filled=false if @sfilled==(db("No"))
### get component
@component=selectedCompoInstance ### @component is selectedCompoInstance = the selected intance's definintion
ents=@component.entities
xents=ents.to_a ###***
### lift @component up @standoff so can be seen above faces
pt=Geom::Point3d.new(0,0,1.mm)
t=Geom::Transformation.new(pt)
g=ents.add_group()
g.entities.add_3d_text(text,align,@sfont,bold,italic,@sheight,1.mm,0,filled,0.0)
g.move!(t)
xents.each{|e|e.erase! if e.valid?}### remove old stuff***
g.explode
### sort out edges and faces of text
edges=[];ents.each{|e|edges<<e if e.class==Sketchup::Edge}
faces=[];ents.each{|e|faces<<e if e.class==Sketchup::Face}
edges.each{|e|e.hidden=true if e.valid? and @sfilled==(db("Yes"))}
faces.each{|e|
  e.material=@scolor
  e.back_material=@scolor
  e.reverse! if e.normal.z<0 ### so faces up
  e.erase! if filled==(db("No"))
}
faces.each{|e|e.erase! if e.valid? and filled==(db("No"))}
### catches left over faces
### fix colors
@scolor=db("<Default>") if @scolor==nil
@component.behavior.always_face_camera=false
@component.behavior.is2d=true
@component.behavior.snapto=0  ### snaps to Any surface
ents.each{|e|e.casts_shadows=false; e.receives_shadows=false}
### set tag @component attributes
@component.set_attribute("2DText","text",@stext)
@component.set_attribute("2DText","height",@sheight)
@component.set_attribute("2DText","align",@salign)
@component.set_attribute("2DText","font",@sfont)
@component.set_attribute("2DText","bold",@sbold)
@component.set_attribute("2DText","italic",@sitalic)
@component.set_attribute("2DText","filled",@sfilled)
@component.set_attribute("2DText","color",@scolor)
@component.set_attribute("2DText","snap",@ssnap)
@component.refresh_thumbnail if Sketchup.version.split('.')[0].to_i >= 7
###
end#if sdialog
### end undo
  model.commit_operation
###
end#edit

def TextTool2D::ok
  if Sketchup.active_model.selection[0] and Sketchup.active_model.selection[0].class==Sketchup::ComponentInstance and Sketchup.active_model.selection[0].definition.get_attribute("2DText","text",false)
    return true
  else
    return false
  end#if
end#

def TextTool2D::fontlist
  ### FONTLIST...
  @fontlist=[]
  font_txt=File.dirname(__FILE__)+"/2DtextTool_Fonts.txt"###
  IO.readlines(font_txt).each{|font|@fontlist<<font.chomp}if font_txt
  @fontlist=["Arial"] if not @fontlist[0]
  return @fontlist
end#

end # class

end#mod
#-----------------------------------------------------------------------------
# shortcut
#def texttool2D
    #Sketchup.active_model.select_tool TextTool2D.new
#end
######-----------------------------------------------

