[code] Set Layer Colors menu command example

The first example (above) can add a bunch of undo operations to the undo stack.
This example wraps the commands in named undo operations.

set_demo_layer_colors_undoable.rb (1.7 KB)

# encoding: UTF-8
#
# "Set Demo Layer Colors" & "Reset Layer Colors" commands.
#
# A SketchUp menu command example by Dan Rathbun. 2021-07-14
# This edition wraps the commands in undo operation blocks.

module User # <<<---<<<< Change to YOUR unique toplevel namespace

  module DemoLayerColors

    if !defined?(@loaded)

      UI.menu("View").add_separator

      UI.menu("View").add_item("Set Demo Layer Colors") {
        Sketchup.active_model.start_operation("Demo Layer Colors",true)
          #
          for i in Sketchup.active_model.layers.to_a
            if i.name.start_with?("Demo")
              hue = Sketchup::Color.new("Red")
            elsif i.name.start_with?("New")
              hue = Sketchup::Color.new("Gray")
            else
              hue = Sketchup::Color.new("White")
            end
            props = i.attribute_dictionary("Properties")
            ca = i.get_attribute("Properties","Color") rescue nil
            if !props || ca.nil? || ca != hue.to_a
              i.set_attribute("Properties","Color",i.color.to_a)
            end
            i.color = hue
          end
          #
        Sketchup.active_model.commit_operation
      }

      UI.menu("View").add_item("Reset Layer Colors") {
        Sketchup.active_model.start_operation("Reset Layer Colors",true)
          #
          for i in Sketchup.active_model.layers.to_a
            ca = i.get_attribute("Properties","Color") rescue nil
            i.color = Sketchup::Color::new(ca) if ca
          end
          #
        Sketchup.active_model.commit_operation
      }

      @loaded = true
    end # if not already loaded

  end # extension submodule

end # top level namespace module

EDITS:

(click to expand ...)
  1. The above files had a conditional:

    if $LOADED_FEATURES !~ /#{__FILE__}/i
    

    which should be:

    if $LOADED_FEATURES.grep(/\A#{__FILE__}\z/i).empty?
    
  2. [2021-07-14] The $LOADED_FEATURES conditional test was removed and replaced with a internal conditional block using a @loaded variable. (This should be faster loading.)

2 Likes