Add inspect.lua and spaces module to hammerspoon config

This commit is contained in:
2017-08-10 14:40:26 +01:00
parent 1921478455
commit 240d77cb82
6 changed files with 992 additions and 8 deletions

View File

@@ -1,24 +1,38 @@
.SILENT: .SILENT:
install: ext/grid.lua installSpoons install: \
update: update_ext/grid.lua updateSpoons ext/grid.lua \
inspect.lua \
installSpoons \
hs/_asm/undocumented/spaces
update: \
update_ext/grid.lua \
update_inspect.lua \
updateSpoons \
update_hs/_asm/undocumented/spaces
#
# Config
#
SPOONS = RoundedCorners HeadphoneAutoPause
INSPECT_VERSION = 3.1.0
SPACES_VERSION = 0.5
SPOONS_DIR = Spoons
SPOON_PATHS = $(foreach s,$(SPOONS),$(shell echo $(SPOONS_DIR)/$(s).spoon))
# #
# Spoons # Spoons
# #
SPOONS = RoundedCorners \
HeadphoneAutoPause
SPOONS_DIR = Spoons
SPOON_PATHS = $(foreach s,$(SPOONS),$(shell echo $(SPOONS_DIR)/$(s).spoon))
.PHONY: installSpoons .PHONY: installSpoons
installSpoons: $(SPOON_PATHS) installSpoons: $(SPOON_PATHS)
.PHONY: removeSpoons .PHONY: removeSpoons
removeSpoons: removeSpoons:
$(foreach dir,$(SPOON_PATHS),(test -d "$(dir)" && echo "removing $(dir)" && rm -rf "$(dir)") || exit 0;) $(foreach dir,$(SPOON_PATHS),(test -d "$(dir)" && echo "removing $(dir)" && rm -rf "$(dir)") || exit 0;)
# $(foreach dir,$(SPOON_PATHS),echo "removing $(dir)";)
.PHONY: updateSpoons .PHONY: updateSpoons
updateSpoons: removeSpoons installSpoons updateSpoons: removeSpoons installSpoons
@@ -51,3 +65,48 @@ remove_ext/grid.lua:
.PHONY: update_ext/grid.lua .PHONY: update_ext/grid.lua
update_ext/grid.lua: remove_ext/grid.lua ext/grid.lua update_ext/grid.lua: remove_ext/grid.lua ext/grid.lua
#
# Spaces module
#
hs/_asm/undocumented/spaces:
echo "fetching $@..." && \
curl -s -L -o "spaces-v$(SPACES_VERSION).zip" \
"https://github.com/asmagill/hs._asm.undocumented.spaces/releases/download/v0.5/spaces-v$(SPACES_VERSION).tar.gz" && \
tar -xvzf "spaces-v$(SPACES_VERSION).zip" && \
rm "spaces-v$(SPACES_VERSION).zip"
.PHONY: remove_hs/_asm/undocumented/spaces
remove_hs/_asm/undocumented/spaces:
( \
test -d "hs/_asm/undocumented/spaces" && \
rm -rf "hs/_asm/undocumented/spaces" && \
echo "removed hs/_asm/undocumented/spaces" \
) || exit 0
.PHONY: update_hs/_asm/undocumented/spaces
update_hs/_asm/undocumented/spaces: \
remove_hs/_asm/undocumented/spaces \
hs/_asm/undocumented/spaces
#
# inspect.lua - useful for debugging
#
inspect.lua:
echo "fetching $@..." && \
curl -s -L -o "$@" \
"https://raw.githubusercontent.com/kikito/inspect.lua/v$(INSPECT_VERSION)/inspect.lua"
.PHONY: remove_inspect.lua
remove_inspect.lua:
( \
test -f "inspect.lua" && rm "inspect.lua" && \
echo "removed inspect.lua" \
) || exit 0
.PHONY: update_inspect.lua
update_inspect.lua: remove_inspect.lua inspect.lua

View File

@@ -0,0 +1,564 @@
--- === hs._asm.undocumented.spaces ===
---
--- These functions utilize private API's within the OS X internals, and are known to have unpredictable behavior under Mavericks and Yosemite when "Displays have separate Spaces" is checked under the Mission Control system preferences.
---
-- some of the commands can really get you in a bit of a fix, so this file will be mostly wrappers and
-- predefined, common actions.
local internal = require("hs._asm.undocumented.spaces.internal")
local module = {}
local screen = require("hs.screen")
local window = require("hs.window")
local settings = require("hs.settings")
local inspect = require("hs.inspect")
local application = require("hs.application")
-- private variables and methods -----------------------------------------
-- flag is checked to see if certain functions are called from module or from module.raw to prevent doing
-- dangerous/unexpected/unknown things unless explicitly enabled
local _BE_DANGEROUS_FLAG_ = false
local _kMetaTable = {}
_kMetaTable._k = {}
_kMetaTable.__index = function(obj, key)
if _kMetaTable._k[obj] then
if _kMetaTable._k[obj][key] then
return _kMetaTable._k[obj][key]
else
for k,v in pairs(_kMetaTable._k[obj]) do
if v == key then return k end
end
end
end
return nil
end
_kMetaTable.__newindex = function(obj, key, value)
error("attempt to modify a table of constants",2)
return nil
end
_kMetaTable.__pairs = function(obj) return pairs(_kMetaTable._k[obj]) end
_kMetaTable.__tostring = function(obj)
local result = ""
if _kMetaTable._k[obj] then
local width = 0
for k,v in pairs(_kMetaTable._k[obj]) do width = width < #k and #k or width end
for k,v in pairs(_kMetaTable._k[obj]) do
result = result..string.format("%-"..tostring(width).."s %s\n", k, tostring(v))
end
else
result = "constants table missing"
end
return result
end
_kMetaTable.__metatable = _kMetaTable -- go ahead and look, but don't unset this
local _makeConstantsTable = function(theTable)
local results = setmetatable({}, _kMetaTable)
_kMetaTable._k[results] = theTable
return results
end
local reverseWithoutSystemSpaces = function(list)
local results = {}
for i,v in ipairs(list) do
if internal.spaceType(v) ~= internal.types.system then
table.insert(results, 1, v)
end
end
return results
end
local isSpaceSafe = function(spaceID, func)
func = func or "undocumented.spaces"
if not _BE_DANGEROUS_FLAG_ then
local t = internal.spaceType(spaceID)
if t ~= internal.types.fullscreen and t ~= internal.types.tiled and t ~= internal.types.user then
_BE_DANGEROUS_FLAG_ = false
error(func..":must be user-created or fullscreen application space", 3)
end
end
_BE_DANGEROUS_FLAG_ = false
return spaceID
end
local screenMT = hs.getObjectMetatable("hs.screen")
local windowMT = hs.getObjectMetatable("hs.window")
-- Public interface ------------------------------------------------------
module.types = _makeConstantsTable(internal.types)
module.masks = _makeConstantsTable(internal.masks)
-- replicate legacy functions
--- hs._asm.undocumented.spaces.count() -> number
--- Function
--- LEGACY: The number of spaces you currently have.
---
--- Notes:
--- * this function may go away in a future update
---
--- * this functions is included for backwards compatibility. It is not recommended because it worked by indexing the spaces ignoring that fullscreen applications are included in the list twice, and only worked with one monitor. Use `hs._asm.undocumented.spaces.query` or `hs._asm.undocumented.spaces.spacesByScreenUUID`.
module.count = function()
return #reverseWithoutSystemSpaces(module.query(internal.masks.allSpaces))
end
--- hs._asm.undocumented.spaces.currentSpace() -> number
--- Function
--- LEGACY: The index of the space you're currently on, 1-indexed (as usual).
---
--- Notes:
--- * this function may go away in a future update
---
--- * this functions is included for backwards compatibility. It is not recommended because it worked by indexing the spaces, which can be rearranged by the operating system anyways. Use `hs._asm.undocumented.spaces.query` or `hs._asm.undocumented.spaces.spacesByScreenUUID`.
module.currentSpace = function()
local theSpaces = reverseWithoutSystemSpaces(module.query(internal.masks.allSpaces))
local currentID = internal.query(internal.masks.currentSpaces)[1]
for i,v in ipairs(theSpaces) do
if v == currentID then return i end
end
return nil
end
--- hs._asm.undocumented.spaces.moveToSpace(number)
--- Function
--- LEGACY: Switches to the space at the given index, 1-indexed (as usual).
---
--- Notes:
--- * this function may go away in a future update
---
--- * this functions is included for backwards compatibility. It is not recommended because it was never really reliable and worked by indexing the spaces, which can be rearranged by the operating system anyways. Use `hs._asm.undocumented.spaces.changeToSpace`.
module.moveToSpace = function(whichIndex)
local theID = internal.query(internal.masks.allSpaces)[whichIndex]
if theID then
internal._changeToSpace(theID, false)
return true
else
return false
end
end
--- hs._asm.undocumented.spaces.isAnimating([screen]) -> bool
--- Function
--- Returns the state of space changing animation for the specified monitor, or for any monitor if no parameter is specified.
---
--- Parameters:
--- * screen - an optional hs.screen object specifying the specific monitor to check the animation status for.
---
--- Returns:
--- * a boolean value indicating whether or not a space changing animation is currently active.
---
--- Notes:
--- * This function can be used in `hs.eventtap` based space changing functions to determine when to release the mouse and key events.
---
--- * This function is also added to the `hs.screen` object metatable so that you can check a specific screen's animation status with `hs.screen:spacesAnimating()`.
module.isAnimating = function(...)
local args = table.pack(...)
if args.n == 0 then
local isAnimating = false
for i,v in ipairs(screen.allScreens()) do
isAnimating = isAnimating or internal.screenUUIDisAnimating(internal.UUIDforScreen(v))
end
return isAnimating
elseif args.n == 1 then
return internal.screenUUIDisAnimating(internal.UUIDforScreen(args[1]))
else
error("isAnimating:invalid argument, none or hs.screen object expected", 2)
end
end
module.spacesByScreenUUID = function(...)
local args = table.pack(...)
if args.n == 0 or args.n == 1 then
local masks = args[1] or internal.masks.allSpaces
local theSpaces = module.query(masks)
local holding = {}
for i,v in ipairs(theSpaces) do
local myScreen = internal.spaceScreenUUID(v) or "screenUndefined"
if not holding[myScreen] then holding[myScreen] = {} end
table.insert(holding[myScreen], v)
end
return holding
else
error("spacesByScreenUUID:invalid argument, none or integer expected", 2)
end
end
-- need to make sure its a user accessible space
module.changeToSpace = function(...)
local args = table.pack(...)
if args.n == 1 or args.n == 2 then
local spaceID = isSpaceSafe(args[1], "changeToSpace")
if type(args[2]) == "boolean" then resetDock = args[2] else resetDock = true end
local fromID, uuid = 0, internal.spaceScreenUUID(spaceID)
for i, v in ipairs(module.query(internal.masks.currentSpaces)) do
if uuid == internal.spaceScreenUUID(v) then
fromID = v
break
end
end
if fromID == 0 then
error("changeToSpace:unable to identify screen for space id "..spaceID, 2)
end
-- this is where you could do some sort of animation with the transform functions
-- may add that in the future
internal.disableUpdates()
for i,v in ipairs(module.query(internal.masks.currentOSSpaces)) do
if internal.spaceScreenUUID(v) == targetUUID then
internal.spaceLevel(v, internal.spaceLevel(v) + 1)
end
end
internal.spaceLevel(spaceID, internal.spaceLevel(spaceID) + 1)
-- doesn't seem to be necessary, _changeToSpace does it for us, though you would need
-- it if you did any animation for the switch
-- internal.showSpaces(spaceID)
internal._changeToSpace(spaceID)
internal.hideSpaces(fromID)
internal.spaceLevel(spaceID, internal.spaceLevel(spaceID) - 1)
for i,v in ipairs(module.query(internal.masks.currentOSSpaces)) do
if internal.spaceScreenUUID(v) == targetUUID then
internal.spaceLevel(v, internal.spaceLevel(v) - 1)
end
end
internal.enableUpdates()
if resetDock then hs.execute("killall Dock") end
else
error("changeToSpace:invalid argument, spaceID and optional boolean expected", 2)
end
return internal.query(internal.masks.currentSpaces)
end
module.mainScreenUUID = function(...)
local UUID = internal.mainScreenUUID(...)
if #UUID ~= 36 then -- on one screen machines, it returns "Main" which doesn't work for spaceCreate
UUID = internal.spaceScreenUUID(internal.activeSpace())
end
return UUID
end
-- -need a way to determine/specify which screen
module.createSpace = function(...)
local args = table.pack(...)
if args.n <= 2 then
local uuid, resetDock
if type(args[1]) == "string" then uuid = args[1] else uuid = module.mainScreenUUID() end
if type(args[#args]) == "boolean" then resetDock = args[#args] else resetDock = true end
local newID = internal.createSpace(uuid)
if resetDock then hs.execute("killall Dock") end
return newID
else
error("createSpace:invalid argument, screenUUID and optional boolean expected", 2)
end
end
-- -need to make sure no windows are only there
-- -need to make sure its a user window
-- ?check for how to do tiled/fullscreen?
module.removeSpace = function(...)
local args = table.pack(...)
if args.n == 1 or args.n == 2 then
local _Are_We_Being_Dangerous_ = _BE_DANGEROUS_FLAG_
local spaceID = isSpaceSafe(args[1], "removeSpace")
local resetDock
if type(args[2]) == "boolean" then resetDock = args[2] else resetDock = true end
if internal.spaceType(spaceID) ~= internal.types.user then
error("removeSpace:you can only remove user created spaces", 2)
end
for i,v in ipairs(module.query(internal.masks.currentSpaces)) do
if spaceID == v then
error("removeSpace:you can't remove one of the currently active spaces", 2)
end
end
local targetUUID = internal.spaceScreenUUID(spaceID)
local sameScreenSpaces = module.spacesByScreenUUID()[targetUUID]
local userSpacesCount = 0
for i,v in ipairs(sameScreenSpaces) do
if internal.spaceType(v) == internal.types.user then
userSpacesCount = userSpacesCount + 1
end
end
if userSpacesCount < 2 then
error("removeSpace:there must be at least one user space on each screen", 2)
end
-- Probably not necessary, with above checks, but if I figure out how to safely
-- "remove" fullscreen/tiled spaces, I may remove them for experimenting
_BE_DANGEROUS_FLAG_ = _Are_We_Being_Dangerous_
-- check for windows which need to be moved
local theWindows = {}
for i, v in ipairs(module.allWindowsForSpace(spaceID)) do if v:id() then table.insert(theWindows, v:id()) end end
-- get id of screen to move them to
local baseID = 0
for i,v in ipairs(module.query(internal.masks.currentSpaces)) do
if internal.spaceScreenUUID(v) == targetUUID then
baseID = v
break
end
end
for i,v in ipairs(theWindows) do
-- only add windows that exist in only one place
if #internal.windowsOnSpaces(v) == 1 then
internal.windowsAddTo(v, baseID)
end
end
internal.windowsRemoveFrom(theWindows, spaceID)
internal._removeSpace(spaceID)
if resetDock then hs.execute("killall Dock") end
else
error("removeSpace:invalid argument, spaceID and optional boolean expected", 2)
end
end
module.allWindowsForSpace = function(...)
local args = table.pack(...)
if args.n == 1 then
local ok, spaceID = pcall(isSpaceSafe, args[1], "allWindowsForSpace")
if not ok then
if internal.spaceName(args[1]) == "dashboard" then spaceID = args[1] else error(spaceID, 2) end
end
local isCurrent, windowIDs = false, {}
for i,v in ipairs(module.query(internal.masks.currentSpaces)) do
if v == spaceID then
isCurrent = true
break
end
end
if isCurrent then
windowIDs = window.allWindows()
else
local targetUUID = internal.spaceScreenUUID(spaceID)
local baseID = 0
for i,v in ipairs(module.query(internal.masks.currentSpaces)) do
if internal.spaceScreenUUID(v) == targetUUID then
baseID = v
break
end
end
internal.disableUpdates()
for i,v in ipairs(module.query(internal.masks.currentOSSpaces)) do
if internal.spaceScreenUUID(v) == targetUUID then
internal.spaceLevel(v, internal.spaceLevel(v) + 1)
end
end
internal.spaceLevel(baseID, internal.spaceLevel(baseID) + 1)
internal._changeToSpace(spaceID)
windowIDs = window.allWindows()
internal.hideSpaces(spaceID)
internal._changeToSpace(baseID)
internal.spaceLevel(baseID, internal.spaceLevel(baseID) - 1)
for i,v in ipairs(module.query(internal.masks.currentOSSpaces)) do
if internal.spaceScreenUUID(v) == targetUUID then
internal.spaceLevel(v, internal.spaceLevel(v) - 1)
end
end
internal.enableUpdates()
end
local realWindowIDs = {}
for i,v in ipairs(windowIDs) do
if v:id() then
for j,k in ipairs(internal.windowsOnSpaces(v:id())) do
if k == spaceID then
table.insert(realWindowIDs, v)
end
end
end
end
windowIDs = realWindowIDs
return windowIDs
else
error("allWindowsForSpace:invalid argument, spaceID expected", 2)
end
end
module.windowOnSpaces = function(...)
local args = table.pack(...)
if args.n == 1 then
windowIDs = internal.windowsOnSpaces(args[1])
return windowIDs
else
error("windowOnSpaces:invalid argument, windowID expected", 2)
end
end
module.moveWindowToSpace = function(...)
local args = table.pack(...)
if args.n == 2 then
local windowID = args[1]
local spaceID = isSpaceSafe(args[2], "moveWindowToSpace")
local currentSpaces = internal.windowsOnSpaces(windowID)
if #currentSpaces == 0 then
error("moveWindowToSpace:no spaceID found for window", 2)
elseif #currentSpaces > 1 then
error("moveWindowToSpace:window on multiple spaces", 2)
end
if currentSpaces[1] ~= spaceID then
internal.windowsAddTo(windowID, spaceID)
internal.windowsRemoveFrom(windowID, currentSpaces[1])
end
return internal.windowsOnSpaces(windowID)[1]
else
error("moveWindowToSpace:invalid argument, windowID and spaceID expected", 2)
end
end
module.layout = function()
local results = {}
for i,v in ipairs(internal.details()) do
local screenID = v["Display Identifier"]
if screenID == "Main" then
screenID = module.mainScreenUUID()
end
results[screenID] = {}
for j,k in ipairs(v.Spaces) do
table.insert(results[screenID], k.ManagedSpaceID)
end
end
return results
end
module.query = function(...)
local args = table.pack(...)
if args.n <= 2 then
local mask, flatten = internal.masks.allSpaces, true
if type(args[1]) == "number" then mask = args[1] end
if type(args[#args]) == "boolean" then flatten = args[#args] end
local results = internal.query(mask)
if not flatten then
return results
else
local userWants, seen = {}, {}
for i, v in ipairs(results) do
if not seen[v] then
seen[v] = true
table.insert(userWants, v)
end
end
return userWants
end
else
error("query:invalid argument, mask and optional boolean expected", 2)
end
end
-- map the basic functions to the main module spaceID
module.screensHaveSeparateSpaces = internal.screensHaveSeparateSpaces
module.activeSpace = internal.activeSpace
module.spaceType = internal.spaceType
module.spaceName = internal.spaceName
module.spaceOwners = internal.spaceOwners
module.spaceScreenUUID = internal.spaceScreenUUID
-- generate debugging information
module.debug = {}
module.debug.layout = function(...) return inspect(internal.details(...)) end
module.debug.report = function(...)
local mask = 7 -- user accessible spaces
local _ = table.pack(...)[1]
if type(_) == "boolean" and _ then
mask = 31 -- I think this gets user and "system" spaces like expose, etc.
elseif type(_) == "boolean" then
mask = 917519 -- I think this gets *everything*, but it may change as I dig
elseif type(_) == "number" then
mask = _ -- user specified mask
elseif table.pack(...).n ~= 0 then
error("debugReport:bad mask type provided, expected number", 2)
end
local list, report = module.query(mask), ""
report = "Screens have separate spaces: "..tostring(internal.screensHaveSeparateSpaces()).."\n"..
"Spaces for mask "..string.format("0x%08x", mask)..": "..(inspect(internal.query(mask)):gsub("%s+"," "))..
"\n\n"
for i,v in ipairs(list) do
report = report..module.debug.spaceInfo(v).."\n"
end
-- see if mask included any of the users accessible spaces flag
if (mask & (1 << 2) ~= 0) then report = report.."\nLayout: "..inspect(internal.details()).."\n" end
return report
end
module.debug.spaceInfo = function(v)
local results =
"Space: "..v.." ("..inspect(internal.spaceName(v))..")\n"..
" Type: "..(module.types[internal.spaceType(v)] and module.types[internal.spaceType(v)] or "-- unknown --")
.." ("..internal.spaceType(v)..")\n"..
" Level: ".. internal.spaceLevel(v).."\n"..
" CompatID: ".. internal.spaceCompatID(v).."\n"..
" Screen: ".. inspect(internal.spaceScreenUUID(v)).."\n"..
" Shape: "..(inspect(internal.spaceShape(v)):gsub("%s+"," ")).."\n"..
" MShape: "..(inspect(internal.spaceManagedShape(v)):gsub("%s+"," ")).."\n"..
" Transform: "..(inspect(internal.spaceTransform(v)):gsub("%s+"," ")).."\n"..
" Values: "..(inspect(internal.spaceValues(v)):gsub("%s+"," ")).."\n"..
" Owners: "..(inspect(internal.spaceOwners(v)):gsub("%s+"," ")).."\n"
if #internal.spaceOwners(v) > 0 then
local apps = {}
for i,v in ipairs(internal.spaceOwners(v)) do
table.insert(apps, (application.applicationForPID(v) and
application.applicationForPID(v):title() or "n/a"))
end
results = results.." : "..(inspect(apps):gsub("%s+"," ")).."\n"
end
return results
end
-- extend built in modules
screenMT.__index.spaces = function(obj) return module.spacesByScreenUUID()[internal.UUIDforScreen(obj)] end
screenMT.__index.spacesUUID = internal.UUIDforScreen
screenMT.__index.spacesAnimating = function(obj) return internal.screenUUIDisAnimating(internal.UUIDforScreen(obj)) end
windowMT.__index.spaces = function(obj) return obj:id() and internal.windowsOnSpaces(obj:id()) or nil end
windowMT.__index.spacesMoveTo = function(obj, ...)
if obj:id() then
module.moveWindowToSpace(obj:id(), ...)
return obj
end
return nil
end
-- add raw subtable if the user has enabled it
if settings.get("_ASMundocumentedSpacesRaw") then
module.raw = internal
module.raw.changeToSpace = function(...)
_BE_DANGEROUS_FLAG_ = true
local result = module.changeToSpace(...)
_BE_DANGEROUS_FLAG_ = false -- should be already, but just in case
return result
end
module.raw.removeSpace = function(...)
_BE_DANGEROUS_FLAG_ = true
local result = module.changeToSpace(...)
_BE_DANGEROUS_FLAG_ = false -- should be already, but just in case
return result
end
module.raw.allWindowsForSpace = function(...)
_BE_DANGEROUS_FLAG_ = true
local result = module.allWindowsForSpace(...)
_BE_DANGEROUS_FLAG_ = false -- should be already, but just in case
return result
end
end
-- Return Module Object --------------------------------------------------
return module

Binary file not shown.

View File

@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>English</string>
<key>CFBundleIdentifier</key>
<string>com.apple.xcode.dsym.internal.so</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundlePackageType</key>
<string>dSYM</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
<string>1</string>
</dict>
</plist>

341
hammerspoon/inspect.lua Normal file
View File

@@ -0,0 +1,341 @@
local inspect ={
_VERSION = 'inspect.lua 3.1.0',
_URL = 'http://github.com/kikito/inspect.lua',
_DESCRIPTION = 'human-readable representations of tables',
_LICENSE = [[
MIT LICENSE
Copyright (c) 2013 Enrique García Cota
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
]]
}
local tostring = tostring
inspect.KEY = setmetatable({}, {__tostring = function() return 'inspect.KEY' end})
inspect.METATABLE = setmetatable({}, {__tostring = function() return 'inspect.METATABLE' end})
-- Apostrophizes the string if it has quotes, but not aphostrophes
-- Otherwise, it returns a regular quoted string
local function smartQuote(str)
if str:match('"') and not str:match("'") then
return "'" .. str .. "'"
end
return '"' .. str:gsub('"', '\\"') .. '"'
end
-- \a => '\\a', \0 => '\\0', 31 => '\31'
local shortControlCharEscapes = {
["\a"] = "\\a", ["\b"] = "\\b", ["\f"] = "\\f", ["\n"] = "\\n",
["\r"] = "\\r", ["\t"] = "\\t", ["\v"] = "\\v"
}
local longControlCharEscapes = {} -- \a => nil, \0 => \000, 31 => \031
for i=0, 31 do
local ch = string.char(i)
if not shortControlCharEscapes[ch] then
shortControlCharEscapes[ch] = "\\"..i
longControlCharEscapes[ch] = string.format("\\%03d", i)
end
end
local function escape(str)
return (str:gsub("\\", "\\\\")
:gsub("(%c)%f[0-9]", longControlCharEscapes)
:gsub("%c", shortControlCharEscapes))
end
local function isIdentifier(str)
return type(str) == 'string' and str:match( "^[_%a][_%a%d]*$" )
end
local function isSequenceKey(k, sequenceLength)
return type(k) == 'number'
and 1 <= k
and k <= sequenceLength
and math.floor(k) == k
end
local defaultTypeOrders = {
['number'] = 1, ['boolean'] = 2, ['string'] = 3, ['table'] = 4,
['function'] = 5, ['userdata'] = 6, ['thread'] = 7
}
local function sortKeys(a, b)
local ta, tb = type(a), type(b)
-- strings and numbers are sorted numerically/alphabetically
if ta == tb and (ta == 'string' or ta == 'number') then return a < b end
local dta, dtb = defaultTypeOrders[ta], defaultTypeOrders[tb]
-- Two default types are compared according to the defaultTypeOrders table
if dta and dtb then return defaultTypeOrders[ta] < defaultTypeOrders[tb]
elseif dta then return true -- default types before custom ones
elseif dtb then return false -- custom types after default ones
end
-- custom types are sorted out alphabetically
return ta < tb
end
-- For implementation reasons, the behavior of rawlen & # is "undefined" when
-- tables aren't pure sequences. So we implement our own # operator.
local function getSequenceLength(t)
local len = 1
local v = rawget(t,len)
while v ~= nil do
len = len + 1
v = rawget(t,len)
end
return len - 1
end
local function getNonSequentialKeys(t)
local keys = {}
local sequenceLength = getSequenceLength(t)
for k,_ in pairs(t) do
if not isSequenceKey(k, sequenceLength) then table.insert(keys, k) end
end
table.sort(keys, sortKeys)
return keys, sequenceLength
end
local function getToStringResultSafely(t, mt)
local __tostring = type(mt) == 'table' and rawget(mt, '__tostring')
local str, ok
if type(__tostring) == 'function' then
ok, str = pcall(__tostring, t)
str = ok and str or 'error: ' .. tostring(str)
end
if type(str) == 'string' and #str > 0 then return str end
end
local function countTableAppearances(t, tableAppearances)
tableAppearances = tableAppearances or {}
if type(t) == 'table' then
if not tableAppearances[t] then
tableAppearances[t] = 1
for k,v in pairs(t) do
countTableAppearances(k, tableAppearances)
countTableAppearances(v, tableAppearances)
end
countTableAppearances(getmetatable(t), tableAppearances)
else
tableAppearances[t] = tableAppearances[t] + 1
end
end
return tableAppearances
end
local copySequence = function(s)
local copy, len = {}, #s
for i=1, len do copy[i] = s[i] end
return copy, len
end
local function makePath(path, ...)
local keys = {...}
local newPath, len = copySequence(path)
for i=1, #keys do
newPath[len + i] = keys[i]
end
return newPath
end
local function processRecursive(process, item, path, visited)
if item == nil then return nil end
if visited[item] then return visited[item] end
local processed = process(item, path)
if type(processed) == 'table' then
local processedCopy = {}
visited[item] = processedCopy
local processedKey
for k,v in pairs(processed) do
processedKey = processRecursive(process, k, makePath(path, k, inspect.KEY), visited)
if processedKey ~= nil then
processedCopy[processedKey] = processRecursive(process, v, makePath(path, processedKey), visited)
end
end
local mt = processRecursive(process, getmetatable(processed), makePath(path, inspect.METATABLE), visited)
setmetatable(processedCopy, mt)
processed = processedCopy
end
return processed
end
-------------------------------------------------------------------
local Inspector = {}
local Inspector_mt = {__index = Inspector}
function Inspector:puts(...)
local args = {...}
local buffer = self.buffer
local len = #buffer
for i=1, #args do
len = len + 1
buffer[len] = args[i]
end
end
function Inspector:down(f)
self.level = self.level + 1
f()
self.level = self.level - 1
end
function Inspector:tabify()
self:puts(self.newline, string.rep(self.indent, self.level))
end
function Inspector:alreadyVisited(v)
return self.ids[v] ~= nil
end
function Inspector:getId(v)
local id = self.ids[v]
if not id then
local tv = type(v)
id = (self.maxIds[tv] or 0) + 1
self.maxIds[tv] = id
self.ids[v] = id
end
return tostring(id)
end
function Inspector:putKey(k)
if isIdentifier(k) then return self:puts(k) end
self:puts("[")
self:putValue(k)
self:puts("]")
end
function Inspector:putTable(t)
if t == inspect.KEY or t == inspect.METATABLE then
self:puts(tostring(t))
elseif self:alreadyVisited(t) then
self:puts('<table ', self:getId(t), '>')
elseif self.level >= self.depth then
self:puts('{...}')
else
if self.tableAppearances[t] > 1 then self:puts('<', self:getId(t), '>') end
local nonSequentialKeys, sequenceLength = getNonSequentialKeys(t)
local mt = getmetatable(t)
local toStringResult = getToStringResultSafely(t, mt)
self:puts('{')
self:down(function()
if toStringResult then
self:puts(' -- ', escape(toStringResult))
if sequenceLength >= 1 then self:tabify() end
end
local count = 0
for i=1, sequenceLength do
if count > 0 then self:puts(',') end
self:puts(' ')
self:putValue(t[i])
count = count + 1
end
for _,k in ipairs(nonSequentialKeys) do
if count > 0 then self:puts(',') end
self:tabify()
self:putKey(k)
self:puts(' = ')
self:putValue(t[k])
count = count + 1
end
if mt then
if count > 0 then self:puts(',') end
self:tabify()
self:puts('<metatable> = ')
self:putValue(mt)
end
end)
if #nonSequentialKeys > 0 or mt then -- result is multi-lined. Justify closing }
self:tabify()
elseif sequenceLength > 0 then -- array tables have one extra space before closing }
self:puts(' ')
end
self:puts('}')
end
end
function Inspector:putValue(v)
local tv = type(v)
if tv == 'string' then
self:puts(smartQuote(escape(v)))
elseif tv == 'number' or tv == 'boolean' or tv == 'nil' then
self:puts(tostring(v))
elseif tv == 'table' then
self:putTable(v)
else
self:puts('<',tv,' ',self:getId(v),'>')
end
end
-------------------------------------------------------------------
function inspect.inspect(root, options)
options = options or {}
local depth = options.depth or math.huge
local newline = options.newline or '\n'
local indent = options.indent or ' '
local process = options.process
if process then
root = processRecursive(process, root, {}, {})
end
local inspector = setmetatable({
depth = depth,
level = 0,
buffer = {},
ids = {},
maxIds = {},
newline = newline,
indent = indent,
tableAppearances = countTableAppearances(root)
}, Inspector_mt)
inspector:putValue(root)
return table.concat(inspector.buffer)
end
setmetatable(inspect, { __call = function(_, ...) return inspect.inspect(...) end })
return inspect