Skip to content

Instantly share code, notes, and snippets.

@domq
Last active January 3, 2016 17:23
Show Gist options
  • Save domq/4e466a7c4a5d366b00f1 to your computer and use it in GitHub Desktop.
Save domq/4e466a7c4a5d366b00f1 to your computer and use it in GitHub Desktop.
Update SketchUp measurements that are marked up with a pair of brackets
# coding: utf-8
require 'Logger'
# To turn on debugging, open Window → Ruby Console and say
#
# UpdateMeasurements.log.level = Logger::DEBUG
module UpdateMeasurements
# http://stackoverflow.com/a/6768164/435004
def log
UpdateMeasurements.log
end
def self.log
# There is not really a STDOUT in SketchUp's Ruby:
logWithPuts = Class.new do
def write(*args)
puts(*args)
end
def close
end
end
u = logWithPuts.new
@logger ||= Logger.new(u)
end
end
class Sketchup::DimensionLinear
include UpdateMeasurements
def initialize
# For debugging using the Ruby console:
Sketchup::DimensionLinear::last_created = self
end
def measurement
text_orig = self.text
begin
self.text = ""
return self.text
ensure
self.text = text_orig
end
end
def update_text_with_measurement
log.debug("update_text_with_measurement " + self.to_s)
matched = self.text.match('^(.*)\[.*?\](.*)$')
return if (!matched)
self.text = matched[1] + "[" + self.measurement + "]" + matched[2]
end
end
class MeasurementsUpdater < Sketchup::EntitiesObserver
include UpdateMeasurements
def initialize
super
@pending = false
@active = true
end
def toggle_active
@active = ! @active
end
def active?
@active
end
def onElementModified(entities, entity)
if @active
schedule
end
end
# Idea borrowed from https://github.com/SketchUp/sketchup-safe-observer-events
def schedule
return if @pending
timer_id = UI.start_timer(0, false) {
break if ! @pending
self.do_update
@pending = false
}
@pending = true
end
def do_update
log.debug "MeasurementsUpdater#do_update"
Sketchup.active_model.entities.grep(Sketchup::DimensionLinear) {|dim|
begin
dim.update_text_with_measurement
end
}
end
end
updater = MeasurementsUpdater.new
Sketchup.active_model.entities.add_observer(updater)
tools_menu = UI.menu("Tools")
item = tools_menu.add_item("Update measurements automatically") do
updater.toggle_active
end
tools_menu.set_validation_proc(item) do
if updater.active?
MF_CHECKED
else
MF_UNCHECKED
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment