SketchUp 8 Constants Guide

SketchUp defines constants, some are global, others are defined in classes or 'namespaced'. Many of them are not listed in the SketchUp.com help documentation. This list includes all constants.

While creating this document, I noticed that some constants' values changed from version to version. Hence, it is strongly recommended that the constant names (versus their values) are used in code.

All of the links in this reference refer back to SketchUp.com.

Some of the concepts in this document may be obvious to experienced programmers, but many API users are new to Ruby, or new to programming.

Finally, thanks to Jim Foltz and others for their previous work and help.


Generated with SUMD_Guide v2.0, on 2015-12-21 at 04:27:34 PM GMT, using SketchUp v8.0.16846 & Ruby v1.8.6.


Unless otherwise noted, constants are of class Fixnum.

This document divides the SketchUp defined constants into three categories

1. Namespaced Constants: These are defined on a class. They will often be listed in a form similar to:

Sketchup::Importer::ImporterNotFound

Sketchup::Importer is the class they are defined on. Hence, one can set a variable equal to the class, and refer to them in another way. A short name may make the code more readable.

# cns = constant namespace
cns = Sketchup::Importer
if (t == cns::ImporterNotFound)
  # etc
end

Two things to remember about namespaced constants:

  • One can define the namespace, but one can also use the class method on an instance object.
  • They are inherited. If they are defined on a class (like 'Dimension'). They are also available on its subclasses (like 'DimensionLinear').

2. Global Numeric Constants:

Almost all of these constants are used as parameters or returns in methods. Most are Fixnum.

3. Global Object Constants:

There are a few constants that are SketchUp objects. All are defined in the Geom module, with the exception of Sketchup::Console.

Namespaced Constants

Dimension #arrow_type #arrow_type=

Defined on Sketchup::Dimension. See Dimension#arrow_type. These constants are for use with Sketchup::Dimension subclasses such as DimensionLinear and DimensionRadial.

arrow_type = dim.arrow_type
dim.arrow_type = arrow_type

** Constants not defined in SketchUp 8 **

DimensionLinear #aligned_text_position #aligned_text_position=

Defined on Sketchup::DimensionLinear. See DimensionLinear#aligned_text_position.

at_pos = dim.aligned_text_position
dim.aligned_text_position = at_pos

** Constants not defined in SketchUp 8 **

DimensionLinear #text_position #text_position=

Defined on Sketchup::DimensionLinear. See DimensionLinear#text_position.

text_pos = dim.text_position
dim.text_position = text_pos

** Constants not defined in SketchUp 8 **

Entities #add_faces_from_mesh

Defined on Geom::PolygonMesh. See Entities#add_faces_from_mesh.

ame = Sketchup.active_model.entities
ame.add_faces_from_mesh(pm, smooth_flags, material)

** Constants not defined in SketchUp 8 **

Face #classify_point

Defined on Sketchup::Face. See Face#classify_point.

pt_location = face.classify_point(pt)

The below code sample is in the template_code.rb file. Load, then SUMD_TC.new.face_1.

# must have a model open with at least one face!
cns = Sketchup::Face
face = Sketchup.active_model.entities.grep(cns)[0]
if (face)
  pt_location = face.classify_point(ORIGIN)
  t = case pt_location
    when cns::PointInside      then 'pt is inside'
    when cns::PointNotOnPlane  then 'pt not on plane'
    when cns::PointOnEdge,
         cns::PointOnVertex    then 'pt on perimeter'
    when cns::PointOutside     then 'pt is outside'
    when cns::PointUnknown     then 'pt error?'
    else 'not trapped by case statement'
  end
else
  t = 'no face found'
end
puts t
pt_locationvaluept_locationvalue
PointInside1PointOnVertex2
PointNotOnPlane32PointOutside16
PointOnEdge4PointUnknown0
PointOnFace8

Importer #load_file

Defined on Sketchup::Importer. See Importer#load_file. These are returned to SketchUp when your importer is finished with processing. Note the following is not included --

5 = SketchUp version not supported (no additional dialog shown)

class YourImporter < Sketchup::Importer
  def load_file(file_path, status)
    return status_code
  end
end
status_code returnvalue
ImportCanceled2
ImportFail1
ImportFileNotFound4
ImportSuccess0
ImporterNotFound3

Length 'UnitsOptions' OptionsProvider

Defined on Length. See Model#options, OptionsManager, OptionsManager#[] and OptionsProvider.

First, SketchUp.com does not list all of the keys used in OptionsManager and OptionsProvider. The below table shows all of the keys.

OptionsManager
key
OptionsProvider
key
OptionsProvider
value

class
PageOptionsShowTransitiontrueBoolean
TransitionTime2.0Float
 
PrintOptionsComputeSizeFromScalefalseBoolean
FitToPagetrueBoolean
LineWeight0.5Float
ModelExtentstrueBoolean
NumberOfPages1Fixnum
PixelsPerInch150.0Float
PrintHeight11.0Float
PrintQuality0Fixnum
PrintWidth8.5Float
ScaleAdjustment1.0Float
SectionSlicefalseBoolean
SizeInModel1.0Float
SizeInPrint1.0Float
VectorModefalseBoolean
 
SlideshowOptionsLoopSlideshowtrueBoolean
SlideTime1.0Float
 
UnitsOptionsAnglePrecision1Fixnum
AngleSnapEnabledtrueBoolean
ForceInchDisplayfalseBoolean
LengthFormat1Fixnum
LengthPrecision4Fixnum
LengthSnapEnabledtrueBoolean
LengthSnapLength0.25Float
LengthUnit0Fixnum
SnapAngle15.0Float
SuppressUnitsDisplayfalseBoolean

These constants are used with the 'UnitsOptions' OptionsProvider. In the two following code lines, units and format have constant equivalents.

am = Sketchup.active_model
units  = am.options['UnitsOptions']['LengthUnit']
format = am.options['UnitsOptions']['LengthFormat']

The following code creates two hashes that make use of the Length:: constants, queries the two settings, and outputs to the console. It's in the template_code.rb file. Load, then SUMD_TC.new.len_1.

cns = Length
h_units  = Hash.new('Unit Unknown')
h_format = Hash.new('Format Unknown')

h_units[cns::Centimeter] = 'cm'
h_units[cns::Feet]       = 'ft'
h_units[cns::Inches]     = 'in'
h_units[cns::Meter]      = 'm'
h_units[cns::Millimeter] = 'mm'

h_format[cns::Architectural] = 'Architectural'
h_format[cns::Decimal]       = 'Decimal'
h_format[cns::Engineering]   = 'Engineering'
h_format[cns::Fractional]    = 'Fractional'

om = Sketchup.active_model.options # OptionManager
op = om['UnitsOptions']            # OptionsProvider
units =  h_units[  op['LengthUnit']   ]
format = h_format[ op['LengthFormat'] ]
puts "Current model units are #{units}"
puts "Current model format is #{format}"
constantvalueconstantvalue
Architectural1Fractional3
Centimeter3Inches0
Decimal0Meter4
Engineering2Millimeter2
Feet1

Model #save #save_copy

Defined on Sketchup::Model. See Model#save and Model#save_copy.

# version param +2014, if omitted, saves in current version
status = model.save(filename, version)
status = model.save_copy(filename, version)

** Constants not defined in SketchUp 8 **

RenderingOptionsObserver

Defined on Sketchup::RenderingOptions. These constants are used with a RenderingOptionsObserver instance (fqn Sketchup::RenderingOptionsObserver).

A RenderingOptions instance is essentially a Hash. Its keys can be enumerated, and setting their value will change the rendering options of the model. The constants are used in a callback method in a RenderingOptionsObserver instance as a notification of rendering option changes by the user or other code.

The constants provide some information about the change.

  • They do not map one-to-one to the RenderingOptions keys. Some changes will result in two callbacks firing.
  • Some RenderingOptions keys will fire a callback, but with no constant assigned to the type value.
  • Some RenderingOptions keys will not fire a callback.

The following code lists all of the RenderingOptions constants and values, then creates a hash from all of the RenderingOptions keys. It then adds a RenderingOptionsObserver to the current model. The observer outputs to the console the onRenderingOptionsChanged callback's type parameter and the constant associated with it, along any RenderingOptions changes. One can change RenderingOptions thru the UI and see what's going on, especially if UI operations do not have constants or keys. The code sample is in the template_code.rb file. Load, then SUMD_TC.new.ro_1.

am = Sketchup.active_model
cns = Sketchup::RenderingOptions

# create a hash of ro keys
@@h_ro = {}
am.rendering_options.each { |k,v|
  val = v.kind_of?(Sketchup::Color) ? v.to_s.slice(-20,20) : v
  @@h_ro[k] = val
}

# hash @@roc = RenderingOptions constants
#   key   is constant value
#   value is constant name, with some spacing added by RegEx
@@roc = Hash.new("** No Constant! **")
# get all the constants, parse names, add to hash
cns.constants.each { |c|
  text = c.to_s.dup
  if    ( text =~ /^ROPSet/ ) ; text.sub!(/^ROPSet/, 'ROPSet  ')
  elsif ( text =~ /^ROP/    ) ; text.sub!(/^ROP/   , 'ROP     ')
  end
  @@roc[cns.const_get(c)] = text
}

# dump hash to console
cnsl = '-----------------------------------------'
puts cnsl + '  ro_1()'
prev = -1
@@roc.sort.each { |r|
  num = r[0].to_s.rjust(3) + ((prev + 1 != r[0]) ? "*" : " ")
  puts "#{num} #{r[1]}"
  prev = r[0]
}
puts cnsl

# create a RenderingOptionsObserver instance & add callback method
@obs_ro1 = Sketchup::RenderingOptionsObserver.new
@obs_ro1.instance_eval {
  @tmr_stopped = true
  def onRenderingOptionsChanged(ro, type)
    # timer puts line breaks between ro changes when multiple ocurr
    if (@tmr_stopped)
      @tmr_stopped = false
      UI.start_timer(0.100) { @tmr_stopped = true ; puts }
    end

    # Loop thru ro's and find changes, load into s_val
    s_val = ''
    ro.each { |k,v|
      val =  v.kind_of?(Sketchup::Color) ? v.to_s.slice(-20,20) : v
      if (@@h_ro[k] != val)
        @@h_ro[k] = val
        val = "%e" % v if (v.class == Float)
        s_val << "#{val.to_s.rjust(20)} #{k}"
      end
    }
    # finally put info to console
    puts "#{type.to_s.rjust(2)} #{@@roc[type].ljust(32)}  #{s_val}"
  end
}
# attach the observer
am.rendering_options.add_observer(@obs_ro1)

The above code does not make use of the constants, so the below code shows one way of creating an observer. The callback uses some constants (items in 'view' menu and toolbar) in a case statement. Similar code could be used in a plug-in. This code sample is SUMD_TC.new.ro_2.

# create an observer & add callback method
@obs_ro2 = Sketchup::RenderingOptionsObserver.new
@obs_ro2.instance_eval {
  def onRenderingOptionsChanged(ro, type)
    cns = ro.class
    suffix = case type
      when cns::ROPDrawHidden
                  'DrawHidden'
      when cns::ROPSetDisplayColorByLayer
                     'DisplayColorByLayer'
      when cns::ROPSetDisplaySketchAxes
                     'DisplaySketchAxes'
      when cns::ROPSetHideConstructionGeometry
                     'HideConstructionGeometry'
      when cns::ROPSetModelTransparency
                     'ModelTransparency'
      when cns::ROPSetRenderMode
                     'RenderMode'
      when cns::ROPSetSectionDisplayMode
                     'SectionDisplayMode'
      when cns::ROPSetTexture
                     'Texture'
      else "Not caught by case statement"
      end
    puts suffix
  end
}
# attach it to the Rendering_options of the model
Sketchup.active_model.rendering_options.add_observer(@obs_ro2)

The following table lists RenderingOptions keys which fire callbacks in a RenderingOptionsObserver callback. As mentioned, some keys generate more than one callback, and, any row with '** Missing, type =' in the 'Observer constant (type)' column fired a callback, but there isn't a RenderingOptions constant with that value. It is sorted by RenderingOption value.class, RenderingOption key, and Constant name. Duplicate values are shown bolded. Note that since these seem to have a many-to-many relationship, the testing done may not show all combinations.

RenderingOptions
key
RenderingOptions
value.class

Observer constant (type)
DisplayColorByLayerBooleanROPSetDisplayColorByLayer
DisplayDimsBooleanROPSetDisplayDims
DisplayFogBooleanROPSetDisplayFog
DisplayInstanceAxesBooleanROPSetDisplayInstanceAxes
DisplaySketchAxesBooleanROPSetDisplaySketchAxes
DisplayTextBooleanROPSetDisplayText
DisplayWatermarksBoolean** Missing, type = 54
DrawDepthQueBooleanROPSetDepthQueEdges
DrawGroundBooleanROPSetDrawGround
DrawHiddenBooleanROPDrawHidden
DrawHorizonBooleanROPSetDrawHorizon
DrawLineEndsBooleanROPSetLineEndEdges
DrawProfilesOnlyBooleanROPSetProfilesOnlyEdges
DrawSilhouettesBooleanROPSetProfileEdges
DrawUndergroundBooleanROPSetDrawUnderground
ExtendLinesBooleanROPSetExtendLines
FogUseBkColorBooleanROPSetFogUseBkColor
HideConstructionGeometryBooleanROPSetHideConstructionGeometry
InactiveHiddenBooleanROPEditComponent
InstanceHiddenBooleanROPEditComponent
JitterEdgesBooleanROPSetJitterEdges
MaterialTransparencyBooleanROPSetMaterialTransparency
ModelTransparencyBooleanROPSetModelTransparency
TextureBooleanROPSetTexture
DepthQueWidthFixnumROPSetDepthQueWidth
EdgeColorModeFixnumROPSetEdgeColorMode
EdgeDisplayModeFixnumROPSetEdgeDisplayMode
EdgeTypeFixnumROPSetEdgeType
FaceColorModeFixnumROPSetFaceColorMode
GroundTransparencyFixnumROPSetGroundTransparency
LineEndWidthFixnumROPSetLineEndWidth
LineExtensionFixnumROPSetLineExtension
RenderModeFixnumROPSetEdgeDisplayMode
RenderModeFixnumROPSetRenderMode
SectionCutWidthFixnumROPSetSectionCutWidth
SilhouetteWidthFixnumROPSetProfileWidth
TransparencySortFixnumROPTransparencySortMethod
FogEndDistFloatROPSetFogDist
FogStartDistFloatROPSetFogDist
InactiveFadeFloatROPEditComponent
InstanceFadeFloatROPEditComponent
BackgroundColorSketchup::ColorROPSetBackgroundColor
ConstructionColorSketchup::ColorROPSetConstructionColor
FaceBackColorSketchup::ColorROPSetFaceColor
FaceFrontColorSketchup::ColorROPSetFaceColor
FogColorSketchup::ColorROPSetFogColor
ForegroundColorSketchup::ColorROPSetForegroundColor
GroundColorSketchup::ColorROPSetGroundColor
HighlightColorSketchup::ColorROPSetHighlightColor
LockedColorSketchup::ColorROPSetLockedColor
SectionActiveColorSketchup::ColorROPSetSectionActiveColor
SectionDefaultCutColorSketchup::ColorROPSetSectionDefaultCutColor
SectionInactiveColorSketchup::ColorROPSetSectionInactiveColor
SkyColorSketchup::ColorROPSetSkyColor

The following table lists RenderingOptions keys that do not fire the onRenderingOptionsChanged callback.

R Opts keyR Opts value.class
BandColorSketchup::Color
HorizonColorSketchup::Color
ShowViewNameBoolean

The following RenderingOptions constants are not fired by any keys in RenderingOptions. They may be returned for UI changes that do not have API control.

Observer constant (type)value
ROPAssign0
ROPSetExtendEdges7
ROPSetFogHint24
ROPSetSectionDisplayMode25
ROPSetTransparencyObsolete2

Global Object Constants

Geometry Class constants

These constants can be used anywhere instances of their respective classes are used.

constantvalueclass
IDENTITY#Geom::Transformation
ORIGIN(0", 0", 0")Geom::Point3d
X_AXIS(1.0, 0.0, 0.0)Geom::Vector3d
Y_AXIS(0.0, 1.0, 0.0)Geom::Vector3d
Z_AXIS(0.0, 0.0, 1.0)Geom::Vector3d

Other object constants

The only other object constant defined is Sketchup::Console.

SKETCHUP_CONSOLE.write("this way also")
constantvalue
SKETCHUP_CONSOLE#

Global Numeric Constants

Sketchup.send_action

Sketchup.send_action(action)

See Sketchup.send_action. This method allows for either a string or a number for its parameter. Numbers are officially 'unsupported', and only available under Windows.

The following code produces the same result.

bln = Sketchup.send_action("selectArcTool:") # use a String
bln = Sketchup.send_action(CMD_ARC)          # use a Constant
bln = Sketchup.send_action(21065)            # use a Fixnum
bln = Sketchup.send_action(action)     # action can be either

Some strings are not listed on SketchUp.com. If one needs an unlisted menu item string, one can assign a keyboard shortcut, then either view them with Sketchup.get_shortcuts.sort.join("\n") or by exporting the 'Preferences' from the UI and viewing the .dat file in a text editor. If a string ending in ':' is shown...

The following table shows strings (taken from SketchUp.com Nov-15), and their constant equivalents. Matches were done via RegEx and several lines of case statement.

action Stringaction ConstantFixnum
copy:CMD_COPY57634
cut:CMD_CUT57635
editHide:
editRedo:CMD_REDO57644
editUndo:CMD_UNDO57643
editUnhide:
fixNonPlanarFaces:
getPhotoTexture:
openDocument:CMD_OPEN57601
pageAdd:CMD_PAGE_NEW21067
pageDelete:CMD_PAGE_DELETE21078
pageNext:CMD_PAGE_NEXT10535
pagePrevious:CMD_PAGE_PREVIOUS10536
pageUpdate:CMD_PAGE_UPDATE21068
paste:CMD_PASTE57637
printDocument:CMD_PRINT57607
renderHiddenLine:CMD_HIDDENLINE10511
renderMonochrome:
renderShaded:CMD_SHADED10512
renderTextures:CMD_TEXTURED10539
renderWireframe:CMD_WIREFRAME10510
selectArc3PointPieTool:
selectArc3PointTool:
selectArcTool:CMD_ARC21065
selectAxisTool:
selectCircleTool:CMD_CIRCLE21096
selectDimensionTool:CMD_DIMENSION21410
selectDollyTool:CMD_DOLLY10523
selectEraseTool:CMD_ERASE21019
selectExtrudeTool:CMD_EXTRUDE21525
selectFieldOfViewTool:CMD_DISPLAY_FOV21494
selectFreehandTool:CMD_FREEHAND21031
selectImageIglooTool:
selectLineTool:CMD_LINE21020
selectMeasureTool:CMD_MEASURE21024
selectMoveTool:CMD_MOVE21048
selectNorthTool:
selectOffsetTool:CMD_OFFSET21100
selectOrbitTool:CMD_ORBIT10508
selectPaintTool:CMD_PAINT21074
selectPolygonTool:CMD_POLYGON21095
selectPositionCameraTool:CMD_POSITION_CAMERA21169
selectProtractorTool:CMD_PROTRACTOR21057
selectPushPullTool:CMD_PUSHPULL21041
selectRectangle3PointTool:
selectRectangleTool:CMD_RECTANGLE21094
selectRotateTool:CMD_ROTATE21129
selectScaleTool:CMD_SCALE21236
selectSectionPlaneTool:CMD_SECTION21337
selectSelectionTool:CMD_SELECT21022
selectTextTool:CMD_TEXT21405
selectTurnTool:CMD_PAN10525
selectWalkTool:CMD_WALK10520
selectZoomTool:CMD_ZOOM10509
selectZoomWindowTool:CMD_ZOOM_WINDOW10526
showRubyPanel:CMD_RUBY_CONSOLE21478
viewBack:CMD_VIEW_BACK10505
viewBottom:CMD_VIEW_BOTTOM10506
viewFront:CMD_VIEW_FRONT10502
viewIso:CMD_VIEW_ISO10507
viewLeft:CMD_VIEW_LEFT10504
viewPerspective:CMD_VIEW_PERSPECTIVE10519
viewRight:CMD_VIEW_RIGHT10503
viewShowAxes:CMD_SKETCHAXES10522
viewShowGuides:CMD_SHOWGUIDES21980
viewShowHidden:CMD_SHOWHIDDEN21154
viewTop:CMD_VIEW_TOP10501
viewUndo:
viewZoomExtents:CMD_ZOOM_EXTENTS10527
viewZoomToSelection:CMD_SELECTION_ZOOM_EXT21469

The following constants do not have string equivalents.

action constantvalueaction constantvalue
CMD_CAMERA_UNDO10529CMD_NEW57600
CMD_DELETE21021CMD_SAVE57603
CMD_DRAWCUTS21348CMD_SKETCHCS21126
CMD_DRAWOUTLINES21347CMD_TRANSPARENT10513
CMD_MAKE_COMPONENT21083

Sketchup.set_status_text

See Sketchup.set_status_text. Text can be placed in three different locations. The constants are used as the position parameter and define the location.

result = Sketchup.set_status_text("This is a Test", SB_VCB_VALUE)
result = Sketchup.set_status_text(status, position)
positionvalue
SB_PROMPT0
SB_VCB_LABEL1
SB_VCB_VALUE2

Command #set_validation_proc

See Command#set_validation_proc. The value returned by the block determines the display state of a command, which can be a menu item, a toolbar button, or both.

your_toolbar = UI::Toolbar.new "YourToolbar"
your_submenu = UI.menu("Draw").add_submenu("Yours")

cmd = UI::Command.new("YourCmd") { some method() }
cmd.menu_text  = "My Command"
cmd.small_icon = "YourCmdSmall.png"
cmd.large_icon = "YourCmdLarge.png"

cmd.set_validation_proc {
  # process
  return cmd_status
}

your_toolbar.add_item cmd
your_submenu.add_item cmd
cmd_statusvalue
MF_CHECKED8
MF_DISABLED2
MF_ENABLED0
MF_GRAYED1
MF_UNCHECKED0

Definition #behavior #snapto

See Behavior#snapto. To quote SketchUp.com help, 'The Behavior class is used to control the "behavior" of components'.

model = Sketchup.active_model
definition = model.definitions[0]
behavior = definition.behavior
snap_to = behavior.snapto
behavior.snapto = snap_to
snap_tovalue
SnapTo_Arbitrary0
SnapTo_Horizontal1
SnapTo_Sloped3
SnapTo_Vertical2

Layer #page_behavior #page_behavior=

See Layer#page_behavior. This attribute is a numeric, with somewhat confusing documentation. From the docs, 'The behavior is composed of a combination of these flags'. So default visiblity is bit 0 ('HIDDEN' is set), why does 'NEW_PAGES' have 'VISIBLE' setting bit 4 and 'HIDDEN' setting bit 5? Seems that they should be mutually exclusive.

layers = Sketchup.active_model.layers
layer.page_behavior = page_behavior
page_behavior = layers[0].page_behavior
puts page_behavior[0]   # this is default visiblity
puts page_behavior[4]   # this new pages visible?
puts page_behavior[5]   # this new pages hidden?
constantvalue
LAYER_USES_DEFAULT_VISIBILITY_ON_NEW_PAGES0
LAYER_VISIBLE_BY_DEFAULT0
LAYER_HIDDEN_BY_DEFAULT1
LAYER_IS_VISIBLE_ON_NEW_PAGES16
LAYER_IS_HIDDEN_ON_NEW_PAGES32

Page #update, Pages #add

See Page#update and Pages#add. These bit constants are used for the flag parameter.

am = Sketchup.active_model
status = am.pages.add(name, flags = nil, index = nil)
am.pages['yourPage'].update(flags = nil)
flag parametervalueflag parametervalue
PAGE_NO_CAMERA4094PAGE_USE_RENDERING_OPTIONS2
PAGE_USE_ALL4095PAGE_USE_SECTION_PLANES64
PAGE_USE_CAMERA1PAGE_USE_SHADOWINFO4
PAGE_USE_HIDDEN16PAGE_USE_SKETCHCS8
PAGE_USE_LAYER_VISIBILITY32

Text #leader_type #leader_type=

See Text#leader_type

leader = text.leader_type
text.leader_type = leader
leadervalue
ALeaderModel2
ALeaderNone0
ALeaderView1

TextureWriter #write

See Texturewriter#write

tw = Sketchup.create_texture_writer
status = tw.write(entity, side, filename)
status returnvalue
FILE_WRITE_FAILED_INVALID_TYPE1
FILE_WRITE_FAILED_UNKNOWN2
FILE_WRITE_OK0

Tool #onKeyDown, Tool #onKeyUp

See Tool#onKeyDown. The constants are the key parameter, VK_PRIOR is 'Page Up', VK_NEXT is 'Page Down'.

  • A-Z keys return 65-90
  • qwerty number keys are 48-57
  • keypad number keys are 96-105

I could not get any information from the flags parameter. I would suggest using keyUp and KeyDown to keep track of modifier key state. The next section has code that attaches to mouse and keyboard events.

 def onKeyDown(key, repeat, flags, view)
key cb
parameter

value
key cb
parameter

value
VK_ALT18VK_LEFT37
VK_COMMAND18VK_MENU18
VK_CONTROL17VK_NEXT34
VK_DELETE46VK_PRIOR33
VK_DOWN40VK_RIGHT39
VK_END35VK_SHIFT16
VK_HOME36VK_SPACE32
VK_INSERT45VK_UP38

Tool #onMouse

See Tool #onLButtonDoubleClick. A total of nine mouse button events exist: up, down, and double click, for left, middle, and right buttons. Under Windows:

  • A user can click more than one button at once.
  • The 'flags' bits for which buttons are pressed are not set on the 'Up' events for a single button press.
  • On a double button press and release, a single down event will often fire, the the double. On release, first the wrong button will fire an event, the a 'blank' up event.
  • 'Down' and 'Up' events fire first, then the 'DoubleClick' event fires.

All methods have the following for parameters -

def onLButtonDown(flags, x, y, view)
# your code
end

Below is code that shows use of the constants, also some "doesn't quite work" key code. Located in the template_code.rb file. Load, then SUMD_TC.new.tool_1.

@@mse = Proc.new { |up_down_dbl, flags, x, y, view|
  button  = ''
  key_mod = ''
  if (MK_LBUTTON & flags != 0) then button << ', Left'   end
  if (MK_MBUTTON & flags != 0) then button << ', Middle' end
  if (MK_RBUTTON & flags != 0) then button << ', Right'  end

  if (MK_SHIFT   & flags != 0) then key_mod << ', Shift' end
  if (MK_CONTROL & flags != 0) then key_mod << ', Ctrl'  end
  if (MK_ALT     & flags != 0) then key_mod << ', Alt'   end
  s1 = up_down_dbl.ljust(7)
  s2 =  button.sub(/^, /, '').ljust(20)
  s3 = key_mod.sub(/^, /, '')
  puts "Mouse Button #{s1} button = #{s2} keys = #{s3}"
}
@tool = Object.new
@tool.instance_eval {
  def onLButtonDown(*a)        ; @@mse.call('Down'  , *a) ; end
  def onMButtonDown(*a)        ; @@mse.call('Down'  , *a) ; end
  def onRButtonDown(*a)        ; @@mse.call('Down'  , *a) ; end

  def onLButtonUp(*a)          ; @@mse.call('Up'    , *a) ; end
  def onMButtonUp(*a)          ; @@mse.call('Up'    , *a) ; end
  def onRButtonUp(*a)          ; @@mse.call('Up'    , *a) ; end

  def onLButtonDoubleClick(*a) ; @@mse.call('DblClk', *a) ; end
  def onMButtonDoubleClick(*a) ; @@mse.call('DblClk', *a) ; end
  def onRButtonDoubleClick(*a) ; @@mse.call('DblClk', *a) ; end

  def onKeyDown(key, repeat, flags, view)
    # Some binary fun for testing
    t = flags.to_s(2).rjust(16)
    bin = "#{ t[-16,4]} #{ t[-12,4]} " \
          "#{ t[ -8,4]} #{ t[ -4,4]}".rjust(19)
    puts "#{key.to_s.ljust(4)}\t#{flags.to_s.ljust(5)}\t#{bin}"

    k    = key.to_s.rjust(3)
    alt  = (ALT_MODIFIER_MASK       & key != 0).to_s.ljust(5)
    cons = (CONSTRAIN_MODIFIER_MASK & key != 0).to_s.ljust(5)
    copy = (COPY_MODIFIER_MASK      & key != 0).to_s.ljust(5)
    puts "key = #{k}  alt = #{alt}  cons = #{cons}  copy = #{copy}"
  end
}
Sketchup.active_model.select_tool(@tool)
flags cb
parameter

value
flags cb
parameter

value
MK_ALT32MK_MBUTTON16
MK_COMMAND0MK_RBUTTON2
MK_CONTROL8MK_SHIFT4
MK_LBUTTON1

Toolbar #get_last_state

See Toolbar#get_last_state.

state = toolbar.get_last_state
state returnvalue
TB_HIDDEN0
TB_NEVER_SHOWN-1
TB_VISIBLE1

UI.messagebox

See UI.messagebox. MB_MULTILINE shows a dialog with a scrollable text area and an 'Okay' button.

status = UI.messagebox(message, type)
status returnvaluetype parametervalue
IDABORT3MB_ABORTRETRYIGNORE2
IDCANCEL2MB_MULTILINE16
IDIGNORE5MB_OK0
IDNO7MB_OKCANCEL1
IDOK1MB_RETRYCANCEL5
IDRETRY4MB_YESNO4
IDYES6MB_YESNOCANCEL3

View #draw

See View#draw

view = Sketchup.active_model.active_view
view.draw(mode, pts)
mode parametervaluemode parametervalue
GL_LINES1GL_QUADS7
GL_LINE_LOOP2GL_QUAD_STRIP8
GL_LINE_STRIP3GL_TRIANGLES4
GL_POINTS0GL_TRIANGLE_FAN6
GL_POLYGON9GL_TRIANGLE_STRIP5

View #draw_text

See View#draw_text. These constants are used in SketchUp 2016+ and control the text alignment.

:align valuevalue
TextAlignCenter1
TextAlignLeft0
TextAlignRight2

RUBY_ Constants, SketchUp Platform Constants

The following are RUBY_ and SketchUp constants which vary from version to version.

constantvalueclass
PLATFORMi386-mswin32String
RELEASE_DATE2008-08-11String
RUBY_PATCHLEVEL287Fixnum
RUBY_PLATFORMi386-mswin32String
RUBY_RELEASE_DATE2008-08-11String
RUBY_VERSION1.8.6String
VERSION1.8.6String

Depreciated Constants

I believe the following are depreciated. VK_ constants should be used in their place. I tried the mask constants on both the key and flags parameters, and nothing seemed to work.

constantvalue
ALT_MODIFIER_KEY18
ALT_MODIFIER_MASK32
CONSTRAIN_MODIFIER_KEY16
CONSTRAIN_MODIFIER_MASK4
COPY_MODIFIER_KEY17
COPY_MODIFIER_MASK8

The following have been replaced by namespaced constants.

constantvalue
DimensionArrowClosed3
DimensionArrowDot2
DimensionArrowNone0
DimensionArrowOpen4
DimensionArrowSlash1

Yet to be added to documentation or unknown

constantvalue
Sketchup::Pages::ImageEmbedded0
Sketchup::Pages::ImageEmbeddedAndLinked1
Sketchup::Pages::ImageLinked2
Sketchup::Pages::UnitsNormalizedX2
Sketchup::Pages::UnitsNormalizedY1
Sketchup::Pages::UnitsPixels0