repo_name stringlengths 6 69 | path stringlengths 6 178 | copies stringclasses 278
values | size stringlengths 4 7 | content stringlengths 671 917k | license stringclasses 15
values |
|---|---|---|---|---|---|
tianxiawuzhei/cocos-quick-lua | quick/framework/cc/ui/UIInput.lua | 3 | 7377 |
--[[
Copyright (c) 2011-2014 chukong-inc.com
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.
]]
--------------------------------
-- @module UIInput
--[[--
quick 输入控件
]]
local UIInput
UIInput = class("UIInput", function(options)
local inputLabel
if not options or not options.UIInputType or 1 == options.UIInputType then
inputLabel = UIInput.newEditBox_(options)
inputLabel.UIInputType = 1
elseif 2 == options.UIInputType then
inputLabel = UIInput.newTextField_(options)
inputLabel.UIInputType = 2
else
end
return inputLabel
end)
-- start --
--------------------------------
-- 输入构建函数
-- @function [parent=#UIInput] new
-- @param table params 参数表格对象
-- @return mixed#mixed editbox/textfield文字输入框
--[[--
输入构建函数
创建一个文字输入框,并返回 EditBox/textfield 对象。
options参灵敏:
- UIInputType: 1或nil 表示创建editbox输入控件
- UIInputType: 2 表示创建textfield输入控件
]]
-- end --
function UIInput:ctor(options)
-- make editbox and textfield have same getText function
if 2 == options.UIInputType then
self.getText = self.getStringValue
end
self.args_ = options
end
-- private
--[[--
创建一个文字输入框,并返回 EditBox 对象。
可用参数:
- image: 输入框的图像,可以是图像名或者是 Sprite9Scale 显示对象。用 display.newScale9Sprite() 创建 Sprite9Scale 显示对象。
- imagePressed: 输入状态时输入框显示的图像(可选)
- imageDisabled: 禁止状态时输入框显示的图像(可选)
- listener: 回调函数
- size: 输入框的尺寸,用 cc.size(宽度, 高度) 创建
- x, y: 坐标(可选)
~~~ lua
local function onEdit(event, editbox)
if event == "began" then
-- 开始输入
elseif event == "changed" then
-- 输入框内容发生变化
elseif event == "ended" then
-- 输入结束
elseif event == "return" then
-- 从输入框返回
end
end
local editbox = ui.newEditBox({
image = "EditBox.png",
listener = onEdit,
size = cc.size(200, 40)
})
~~~
注意: 使用setInputFlag(0) 可设为密码输入框。
注意:构造输入框时,请使用setPlaceHolder来设定初始文本显示。setText为出现输入法后的默认文本。
注意:事件触发机制,player模拟器上与真机不同,请使用真机实测(不同ios版本貌似也略有不同)。
注意:changed事件中,需要条件性使用setText(如trim或转化大小写等),否则在某些ios版本中会造成死循环。
~~~ lua
--错误,会造成死循环
editbox:setText(string.trim(editbox:getText()))
~~~
~~~ lua
--正确,不会造成死循环
local _text = editbox:getText()
local _trimed = string.trim(_text)
if _trimed ~= _text then
editbox:setText(_trimed)
end
~~~
@param table params 参数表格对象
@return EditBox 文字输入框
]]
function UIInput.newEditBox_(params)
local imageNormal = params.image
local imagePressed = params.imagePressed
local imageDisabled = params.imageDisabled
if type(imageNormal) == "string" then
imageNormal = display.newScale9Sprite(imageNormal)
end
if type(imagePressed) == "string" then
imagePressed = display.newScale9Sprite(imagePressed)
end
if type(imageDisabled) == "string" then
imageDisabled = display.newScale9Sprite(imageDisabled)
end
local editboxCls
if cc.bPlugin_ then
editboxCls = ccui.EditBox
else
editboxCls = cc.EditBox
end
local editbox = editboxCls:create(params.size, imageNormal, imagePressed, imageDisabled)
if editbox then
if params.listener then
editbox:registerScriptEditBoxHandler(params.listener)
end
if params.x and params.y then
editbox:setPosition(params.x, params.y)
end
end
return editbox
end
--[[--
创建一个文字输入框,并返回 Textfield 对象。
可用参数:
- listener: 回调函数
- size: 输入框的尺寸,用 cc.size(宽度, 高度) 创建
- x, y: 坐标(可选)
- placeHolder: 占位符(可选)
- text: 输入文字(可选)
- font: 字体
- fontSize: 字体大小
- maxLength:
- passwordEnable:开启密码模式
- passwordChar:密码代替字符
~~~ lua
local function onEdit(textfield, eventType)
if event == 0 then
-- ATTACH_WITH_IME
elseif event == 1 then
-- DETACH_WITH_IME
elseif event == 2 then
-- INSERT_TEXT
elseif event == 3 then
-- DELETE_BACKWARD
end
end
local textfield = UIInput.new({
UIInputType = 2,
listener = onEdit,
size = cc.size(200, 40)
})
~~~
@param table params 参数表格对象
@return Textfield 文字输入框
]]
function UIInput.newTextField_(params)
local textfieldCls
if cc.bPlugin_ then
textfieldCls = ccui.TextField
else
textfieldCls = cc.TextField
end
local editbox = textfieldCls:create()
editbox:setPlaceHolder(params.placeHolder)
if params.x and params.y then
editbox:setPosition(params.x, params.y)
end
if params.listener then
editbox:addEventListener(params.listener)
end
if params.size then
editbox:setTextAreaSize(params.size)
editbox:setTouchSize(params.size)
editbox:setTouchAreaEnabled(true)
end
if params.text then
if editbox.setString then
editbox:setString(params.text)
else
editbox:setText(params.text)
end
end
if params.font then
editbox:setFontName(params.font)
end
if params.fontSize then
editbox:setFontSize(params.fontSize)
end
if params.fontColor then
editbox:setTextColor(cc.c4b(params.fontColor.R or 255, params.fontColor.G or 255, params.fontColor.B or 255, 255))
end
if params.maxLength and 0 ~= params.maxLength then
editbox:setMaxLengthEnabled(true)
editbox:setMaxLength(params.maxLength)
end
if params.passwordEnable then
editbox:setPasswordEnabled(true)
end
if params.passwordChar then
editbox:setPasswordStyleText(params.passwordChar)
end
return editbox
end
function UIInput:createcloneInstance_()
return UIInput.new(unpack(self.args_))
end
return UIInput
| mit |
vladimir-kotikov/clink | clink/dll/git.lua | 4 | 2098 | --
-- Copyright (c) 2012 Martin Ridgers
--
-- 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 git_argument_tree = {
-- Porcelain and ancillary commands from git's man page.
"add", "am", "archive", "bisect", "branch", "bundle", "checkout",
"cherry-pick", "citool", "clean", "clone", "commit", "describe", "diff",
"fetch", "format-patch", "gc", "grep", "gui", "init", "log", "merge", "mv",
"notes", "pull", "push", "rebase", "reset", "revert", "rm", "shortlog",
"show", "stash", "status", "submodule", "tag", "config", "fast-export",
"fast-import", "filter-branch", "lost-found", "mergetool", "pack-refs",
"prune", "reflog", "relink", "remote", "repack", "replace", "repo-config",
"annotate", "blame", "cherry", "count-objects", "difftool", "fsck",
"get-tar-commit-id", "help", "instaweb", "merge-tree", "rerere",
"rev-parse", "show-branch", "verify-tag", "whatchanged"
}
clink.arg.register_parser("git", git_argument_tree)
-- vim: expandtab
| gpl-3.0 |
bizkut/BudakJahat | Libs/LibRangeCheck-2.0/LibRangeCheck-2.0.lua | 1 | 32626 | --[[
Name: LibRangeCheck-2.0
Revision: $Revision: 168 $
Author(s): mitch0
Website: http://www.wowace.com/projects/librangecheck-2-0/
Description: A range checking library based on interact distances and spell ranges
Dependencies: LibStub
License: Public Domain
]]
--- LibRangeCheck-2.0 provides an easy way to check for ranges and get suitable range checking functions for specific ranges.\\
-- The checkers use spell and item range checks, or interact based checks for special units where those two cannot be used.\\
-- The lib handles the refreshing of checker lists in case talents / spells / glyphs change and in some special cases when equipment changes (for example some of the mage pvp gloves change the range of the Fire Blast spell), and also handles the caching of items used for item-based range checks.\\
-- A callback is provided for those interested in checker changes.
-- @usage
-- local rc = LibStub("LibRangeCheck-2.0")
--
-- rc.RegisterCallback(self, rc.CHECKERS_CHANGED, function() print("need to refresh my stored checkers") end)
--
-- local minRange, maxRange = rc:GetRange('target')
-- if not minRange then
-- print("cannot get range estimate for target")
-- elseif not maxRange then
-- print("target is over " .. minRange .. " yards")
-- else
-- print("target is between " .. minRange .. " and " .. maxRange .. " yards")
-- end
--
-- local meleeChecker = rc:GetFriendMaxChecker(rc.MeleeRange) -- 5 yds
-- for i = 1, 4 do
-- -- TODO: check if unit is valid, etc
-- if meleeChecker("party" .. i) then
-- print("Party member " .. i .. " is in Melee range")
-- end
-- end
--
-- local safeDistanceChecker = rc:GetHarmMinChecker(30)
-- -- negate the result of the checker!
-- local isSafelyAway = not safeDistanceChecker('target')
--
-- @class file
-- @name LibRangeCheck-2.0
local MAJOR_VERSION = "LibRangeCheck-2.0"
local MINOR_VERSION = tonumber(("$Revision: 168 $"):match("%d+")) + 100000
local lib, oldminor = LibStub:NewLibrary(MAJOR_VERSION, MINOR_VERSION)
if not lib then
return
end
-- << STATIC CONFIG
local UpdateDelay = .5
local ItemRequestTimeout = 10.0
-- interact distance based checks. ranges are based on my own measurements (thanks for all the folks who helped me with this)
local DefaultInteractList = {
[3] = 8,
[2] = 9,
[4] = 28,
}
-- interact list overrides for races
local InteractLists = {
["Tauren"] = {
[3] = 6,
[2] = 7,
[4] = 25,
},
["Scourge"] = {
[3] = 7,
[2] = 8,
[4] = 27,
},
}
local MeleeRange = 5
-- list of friendly spells that have different ranges
local FriendSpells = {}
-- list of harmful spells that have different ranges
local HarmSpells = {}
FriendSpells["DEATHKNIGHT"] = {
47541, -- ["Death Coil"], -- 40
}
HarmSpells["DEATHKNIGHT"] = {
47541, -- ["Death Coil"], -- 40
49576, -- ["Death Grip"], -- 30
}
FriendSpells["DEMONHUNTER"] = {
}
HarmSpells["DEMONHUNTER"] = {
185123, -- ["Throw Glaive"], -- 30
}
FriendSpells["DRUID"] = {
774, -- ["Rejuvenation"], -- 40
2782, -- ["Remove Corruption"], -- 40
}
HarmSpells["DRUID"] = {
5176, -- ["Wrath"], -- 40
339, -- ["Entangling Roots"], -- 35
6795, -- ["Growl"], -- 30
33786, -- ["Cyclone"], -- 20
106839, -- ["Skull Bash"], -- 13
22568, -- ["Ferocious Bite"], -- 5
}
FriendSpells["HUNTER"] = {}
HarmSpells["HUNTER"] = {
75, -- ["Auto Shot"], -- 40
}
FriendSpells["MAGE"] = {
}
HarmSpells["MAGE"] = {
44614, --["Frostfire Bolt"], -- 40
5019, -- ["Shoot"], -- 30
}
FriendSpells["MONK"] = {
115450, -- ["Detox"], -- 40
115546, -- ["Provoke"], -- 30
}
HarmSpells["MONK"] = {
115546, -- ["Provoke"], -- 30
115078, -- ["Paralysis"], -- 20
100780, -- ["Tiger Palm"], -- 5
}
FriendSpells["PALADIN"] = {
19750, -- ["Flash of Light"], -- 40
}
HarmSpells["PALADIN"] = {
62124, -- ["Reckoning"], -- 30
20271, -- ["Judgement"], -- 30
853, -- ["Hammer of Justice"], -- 10
35395, -- ["Crusader Strike"], -- 5
}
FriendSpells["PRIEST"] = {
527, -- ["Purify"], -- 40
17, -- ["Power Word: Shield"], -- 40
}
HarmSpells["PRIEST"] = {
589, -- ["Shadow Word: Pain"], -- 40
5019, -- ["Shoot"], -- 30
}
FriendSpells["ROGUE"] = {}
HarmSpells["ROGUE"] = {
2764, -- ["Throw"], -- 30
2094, -- ["Blind"], -- 15
}
FriendSpells["SHAMAN"] = {
8004, -- ["Healing Surge"], -- 40
546, -- ["Water Walking"], -- 30
}
HarmSpells["SHAMAN"] = {
403, -- ["Lightning Bolt"], -- 40
370, -- ["Purge"], -- 30
73899, -- ["Primal Strike"],. -- 5
}
FriendSpells["WARRIOR"] = {}
HarmSpells["WARRIOR"] = {
355, -- ["Taunt"], -- 30
100, -- ["Charge"], -- 8-25
5246, -- ["Intimidating Shout"], -- 8
}
FriendSpells["WARLOCK"] = {
5697, -- ["Unending Breath"], -- 30
}
HarmSpells["WARLOCK"] = {
686, -- ["Shadow Bolt"], -- 40
5019, -- ["Shoot"], -- 30
}
-- Items [Special thanks to Maldivia for the nice list]
local FriendItems = {
[5] = {
37727, -- Ruby Acorn
},
[6] = {
63427, -- Worgsaw
},
[8] = {
34368, -- Attuned Crystal Cores
33278, -- Burning Torch
},
[10] = {
32321, -- Sparrowhawk Net
},
[15] = {
1251, -- Linen Bandage
2581, -- Heavy Linen Bandage
3530, -- Wool Bandage
3531, -- Heavy Wool Bandage
6450, -- Silk Bandage
6451, -- Heavy Silk Bandage
8544, -- Mageweave Bandage
8545, -- Heavy Mageweave Bandage
14529, -- Runecloth Bandage
14530, -- Heavy Runecloth Bandage
21990, -- Netherweave Bandage
21991, -- Heavy Netherweave Bandage
34721, -- Frostweave Bandage
34722, -- Heavy Frostweave Bandage
-- 38643, -- Thick Frostweave Bandage
-- 38640, -- Dense Frostweave Bandage
},
[20] = {
21519, -- Mistletoe
},
[25] = {
31463, -- Zezzak's Shard
},
[30] = {
1180, -- Scroll of Stamina
1478, -- Scroll of Protection II
3012, -- Scroll of Agility
1712, -- Scroll of Spirit II
2290, -- Scroll of Intellect II
1711, -- Scroll of Stamina II
34191, -- Handful of Snowflakes
},
[35] = {
18904, -- Zorbin's Ultra-Shrinker
},
[40] = {
34471, -- Vial of the Sunwell
},
[45] = {
32698, -- Wrangling Rope
},
[50] = {
116139, -- Haunting Memento
},
[60] = {
32825, -- Soul Cannon
37887, -- Seeds of Nature's Wrath
},
[70] = {
41265, -- Eyesore Blaster
},
[80] = {
35278, -- Reinforced Net
},
}
local HarmItems = {
[5] = {
37727, -- Ruby Acorn
},
[6] = {
63427, -- Worgsaw
},
[8] = {
34368, -- Attuned Crystal Cores
33278, -- Burning Torch
},
[10] = {
32321, -- Sparrowhawk Net
},
[15] = {
33069, -- Sturdy Rope
},
[20] = {
10645, -- Gnomish Death Ray
},
[25] = {
24268, -- Netherweave Net
41509, -- Frostweave Net
31463, -- Zezzak's Shard
},
[30] = {
835, -- Large Rope Net
7734, -- Six Demon Bag
34191, -- Handful of Snowflakes
},
[35] = {
24269, -- Heavy Netherweave Net
18904, -- Zorbin's Ultra-Shrinker
},
[40] = {
28767, -- The Decapitator
},
[45] = {
-- 32698, -- Wrangling Rope
23836, -- Goblin Rocket Launcher
},
[50] = {
116139, -- Haunting Memento
},
[60] = {
32825, -- Soul Cannon
37887, -- Seeds of Nature's Wrath
},
[70] = {
41265, -- Eyesore Blaster
},
[80] = {
35278, -- Reinforced Net
},
[100] = {
33119, -- Malister's Frost Wand
},
}
-- This could've been done by checking player race as well and creating tables for those, but it's easier like this
for k, v in pairs(FriendSpells) do
tinsert(v, 28880) -- ["Gift of the Naaru"]
end
-- >> END OF STATIC CONFIG
-- cache
local setmetatable = setmetatable
local tonumber = tonumber
local pairs = pairs
local tostring = tostring
local print = print
local next = next
local type = type
local wipe = wipe
local tinsert = tinsert
local tremove = tremove
local BOOKTYPE_SPELL = BOOKTYPE_SPELL
local GetSpellInfo = GetSpellInfo
local GetSpellBookItemName = GetSpellBookItemName
local GetNumSpellTabs = GetNumSpellTabs
local GetSpellTabInfo = GetSpellTabInfo
local GetItemInfo = GetItemInfo
local UnitAura = UnitAura
local UnitCanAttack = UnitCanAttack
local UnitCanAssist = UnitCanAssist
local UnitExists = UnitExists
local UnitIsDeadOrGhost = UnitIsDeadOrGhost
local CheckInteractDistance = CheckInteractDistance
local IsSpellInRange = IsSpellInRange
local IsItemInRange = IsItemInRange
local UnitClass = UnitClass
local UnitRace = UnitRace
local GetInventoryItemLink = GetInventoryItemLink
local GetSpecialization = GetSpecialization
local GetSpecializationInfo = GetSpecializationInfo
local GetTime = GetTime
local HandSlotId = GetInventorySlotInfo("HandsSlot")
local math_floor = math.floor
-- temporary stuff
local itemRequestTimeoutAt
local foundNewItems
local cacheAllItems
local friendItemRequests
local harmItemRequests
local lastUpdate = 0
-- minRangeCheck is a function to check if spells with minimum range are really out of range, or fail due to range < minRange. See :init() for its setup
local minRangeCheck = function(unit) return CheckInteractDistance(unit, 2) end
local checkers_Spell = setmetatable({}, {
__index = function(t, spellIdx)
local func = function(unit)
if IsSpellInRange(spellIdx, BOOKTYPE_SPELL, unit) == 1 then
return true
end
end
t[spellIdx] = func
return func
end
})
local checkers_SpellWithMin = setmetatable({}, {
__index = function(t, spellIdx)
local func = function(unit)
if IsSpellInRange(spellIdx, BOOKTYPE_SPELL, unit) == 1 then
return true
elseif minRangeCheck(unit) then
return true, true
end
end
t[spellIdx] = func
return func
end
})
local checkers_Item = setmetatable({}, {
__index = function(t, item)
local func = function(unit)
return IsItemInRange(item, unit)
end
t[item] = func
return func
end
})
local checkers_Interact = setmetatable({}, {
__index = function(t, index)
local func = function(unit)
if CheckInteractDistance(unit, index) then
return true
end
end
t[index] = func
return func
end
})
-- helper functions
local function copyTable(src, dst)
if type(dst) ~= "table" then dst = {} end
if type(src) == "table" then
for k, v in pairs(src) do
if type(v) == "table" then
v = copyTable(v, dst[k])
end
dst[k] = v
end
end
return dst
end
local function initItemRequests(cacheAll)
friendItemRequests = copyTable(FriendItems)
harmItemRequests = copyTable(HarmItems)
cacheAllItems = cacheAll
foundNewItems = nil
end
local function getNumSpells()
local _, _, offset, numSpells = GetSpellTabInfo(GetNumSpellTabs())
return offset + numSpells
end
-- return the spellIndex of the given spell by scanning the spellbook
local function findSpellIdx(spellName)
if not spellName or spellName == "" then
return nil
end
for i = 1, getNumSpells() do
local spell, rank = GetSpellBookItemName(i, BOOKTYPE_SPELL)
if spell == spellName then return i end
end
return nil
end
-- minRange should be nil if there's no minRange, not 0
local function addChecker(t, range, minRange, checker)
local rc = { ["range"] = range, ["minRange"] = minRange, ["checker"] = checker }
for i = 1, #t do
local v = t[i]
if rc.range == v.range then return end
if rc.range > v.range then
tinsert(t, i, rc)
return
end
end
tinsert(t, rc)
end
local function createCheckerList(spellList, itemList, interactList)
local res = {}
if spellList then
for i = 1, #spellList do
local sid = spellList[i]
local name, _, _, _, minRange, range = GetSpellInfo(sid)
local spellIdx = findSpellIdx(name)
if spellIdx and range then
minRange = math_floor(minRange + 0.5)
range = math_floor(range + 0.5)
-- print("### spell: " .. tostring(name) .. ", " .. tostring(minRange) .. " - " .. tostring(range))
if minRange == 0 then -- getRange() expects minRange to be nil in this case
minRange = nil
end
if range == 0 then
range = MeleeRange
end
if minRange then
addChecker(res, range, minRange, checkers_SpellWithMin[spellIdx])
else
addChecker(res, range, minRange, checkers_Spell[spellIdx])
end
end
end
end
if itemList then
for range, items in pairs(itemList) do
for i = 1, #items do
local item = items[i]
if GetItemInfo(item) then
addChecker(res, range, nil, checkers_Item[item])
break
end
end
end
end
if interactList and not next(res) then
for index, range in pairs(interactList) do
addChecker(res, range, nil, checkers_Interact[index])
end
end
return res
end
-- returns minRange, maxRange or nil
local function getRange(unit, checkerList)
local min, max = 0, nil
for i = 1, #checkerList do
local rc = checkerList[i]
if not max or max > rc.range then
if rc.minRange then
local inRange, inMinRange = rc.checker(unit)
if inMinRange then
max = rc.minRange
elseif inRange then
min, max = rc.minRange, rc.range
elseif min > rc.range then
return min, max
else
return rc.range, max
end
elseif rc.checker(unit) then
max = rc.range
elseif min > rc.range then
return min, max
else
return rc.range, max
end
end
end
return min, max
end
local function updateCheckers(origList, newList)
if #origList ~= #newList then
wipe(origList)
copyTable(newList, origList)
return true
end
for i = 1, #origList do
if origList[i].range ~= newList[i].range or origList[i].checker ~= newList[i].checker then
wipe(origList)
copyTable(newList, origList)
return true
end
end
end
local function rcIterator(checkerList)
local curr = #checkerList
return function()
local rc = checkerList[curr]
if not rc then
return nil
end
curr = curr - 1
return rc.range, rc.checker
end
end
local function getMinChecker(checkerList, range)
local checker, checkerRange
for i = 1, #checkerList do
local rc = checkerList[i]
if rc.range < range then
return checker, checkerRange
end
checker, checkerRange = rc.checker, rc.range
end
return checker, checkerRange
end
local function getMaxChecker(checkerList, range)
for i = 1, #checkerList do
local rc = checkerList[i]
if rc.range <= range then
return rc.checker, rc.range
end
end
end
local function getChecker(checkerList, range)
for i = 1, #checkerList do
local rc = checkerList[i]
if rc.range == range then
return rc.checker
end
end
end
local function null()
end
local function createSmartChecker(friendChecker, harmChecker, miscChecker)
miscChecker = miscChecker or null
friendChecker = friendChecker or miscChecker
harmChecker = harmChecker or miscChecker
return function(unit)
if not UnitExists(unit) then
return nil
end
if UnitIsDeadOrGhost(unit) then
return miscChecker(unit)
end
if UnitCanAttack("player", unit) then
return harmChecker(unit)
elseif UnitCanAssist("player", unit) then
return friendChecker(unit)
else
return miscChecker(unit)
end
end
end
-- OK, here comes the actual lib
-- pre-initialize the checkerLists here so that we can return some meaningful result even if
-- someone manages to call us before we're properly initialized. miscRC should be independent of
-- race/class/talents, so it's safe to initialize it here
-- friendRC and harmRC will be properly initialized later when we have all the necessary data for them
lib.checkerCache_Spell = lib.checkerCache_Spell or {}
lib.checkerCache_Item = lib.checkerCache_Item or {}
lib.miscRC = createCheckerList(nil, nil, DefaultInteractList)
lib.friendRC = createCheckerList(nil, nil, DefaultInteractList)
lib.harmRC = createCheckerList(nil, nil, DefaultInteractList)
lib.failedItemRequests = {}
-- << Public API
--- The callback name that is fired when checkers are changed.
-- @field
lib.CHECKERS_CHANGED = "CHECKERS_CHANGED"
-- "export" it, maybe someone will need it for formatting
--- Constant for Melee range (5yd).
-- @field
lib.MeleeRange = MeleeRange
function lib:findSpellIndex(spell)
if type(spell) == 'number' then
spell = GetSpellInfo(spell)
end
return findSpellIdx(spell)
end
-- returns the range estimate as a string
-- deprecated, use :getRange(unit) instead and build your own strings
-- (checkVisible is not used any more, kept for compatibility only)
function lib:getRangeAsString(unit, checkVisible, showOutOfRange)
local minRange, maxRange = self:getRange(unit)
if not minRange then return nil end
if not maxRange then
return showOutOfRange and minRange .. " +" or nil
end
return minRange .. " - " .. maxRange
end
-- initialize RangeCheck if not yet initialized or if "forced"
function lib:init(forced)
if self.initialized and (not forced) then
return
end
self.initialized = true
local _, playerClass = UnitClass("player")
local _, playerRace = UnitRace("player")
minRangeCheck = nil
-- first try to find a nice item we can use for minRangeCheck
if HarmItems[15] then
local items = HarmItems[15]
for i = 1, #items do
local item = items[i]
if GetItemInfo(item) then
minRangeCheck = function(unit)
return IsItemInRange(item, unit)
end
break
end
end
end
if not minRangeCheck then
-- ok, then try to find some class specific spell
if playerClass == "WARRIOR" then
-- for warriors, use Intimidating Shout if available
local name = GetSpellInfo(5246) -- ["Intimidating Shout"]
local spellIdx = findSpellIdx(name)
if spellIdx then
minRangeCheck = function(unit)
return (IsSpellInRange(spellIdx, BOOKTYPE_SPELL, unit) == 1)
end
end
elseif playerClass == "ROGUE" then
-- for rogues, use Blind if available
local name = GetSpellInfo(2094) -- ["Blind"]
local spellIdx = findSpellIdx(name)
if spellIdx then
minRangeCheck = function(unit)
return (IsSpellInRange(spellIdx, BOOKTYPE_SPELL, unit) == 1)
end
end
end
end
if not minRangeCheck then
-- fall back to interact distance checks
if playerClass == "HUNTER" or playerRace == "Tauren" then
-- for hunters, use interact4 as it's safer
-- for Taurens interact4 is actually closer than 25yd and interact2 is closer than 8yd, so we can't use that
minRangeCheck = checkers_Interact[4]
else
minRangeCheck = checkers_Interact[2]
end
end
local interactList = InteractLists[playerRace] or DefaultInteractList
self.handSlotItem = GetInventoryItemLink("player", HandSlotId)
local changed = false
if updateCheckers(self.friendRC, createCheckerList(FriendSpells[playerClass], FriendItems, interactList)) then
changed = true
end
if updateCheckers(self.harmRC, createCheckerList(HarmSpells[playerClass], HarmItems, interactList)) then
changed = true
end
if updateCheckers(self.miscRC, createCheckerList(nil, nil, interactList)) then
changed = true
end
if changed and self.callbacks then
self.callbacks:Fire(self.CHECKERS_CHANGED)
end
end
--- Return an iterator for checkers usable on friendly units as (**range**, **checker**) pairs.
function lib:GetFriendCheckers()
return rcIterator(self.friendRC)
end
--- Return an iterator for checkers usable on enemy units as (**range**, **checker**) pairs.
function lib:GetHarmCheckers()
return rcIterator(self.harmRC)
end
--- Return an iterator for checkers usable on miscellaneous units as (**range**, **checker**) pairs. These units are neither enemy nor friendly, such as people in sanctuaries or corpses.
function lib:GetMiscCheckers()
return rcIterator(self.miscRC)
end
--- Return a checker suitable for out-of-range checking on friendly units, that is, a checker whose range is equal or larger than the requested range.
-- @param range the range to check for.
-- @return **checker**, **range** pair or **nil** if no suitable checker is available. **range** is the actual range the returned **checker** checks for.
function lib:GetFriendMinChecker(range)
return getMinChecker(self.friendRC, range)
end
--- Return a checker suitable for out-of-range checking on enemy units, that is, a checker whose range is equal or larger than the requested range.
-- @param range the range to check for.
-- @return **checker**, **range** pair or **nil** if no suitable checker is available. **range** is the actual range the returned **checker** checks for.
function lib:GetHarmMinChecker(range)
return getMinChecker(self.harmRC, range)
end
--- Return a checker suitable for out-of-range checking on miscellaneous units, that is, a checker whose range is equal or larger than the requested range.
-- @param range the range to check for.
-- @return **checker**, **range** pair or **nil** if no suitable checker is available. **range** is the actual range the returned **checker** checks for.
function lib:GetMiscMinChecker(range)
return getMinChecker(self.miscRC, range)
end
--- Return a checker suitable for in-range checking on friendly units, that is, a checker whose range is equal or smaller than the requested range.
-- @param range the range to check for.
-- @return **checker**, **range** pair or **nil** if no suitable checker is available. **range** is the actual range the returned **checker** checks for.
function lib:GetFriendMaxChecker(range)
return getMaxChecker(self.friendRC, range)
end
--- Return a checker suitable for in-range checking on enemy units, that is, a checker whose range is equal or smaller than the requested range.
-- @param range the range to check for.
-- @return **checker**, **range** pair or **nil** if no suitable checker is available. **range** is the actual range the returned **checker** checks for.
function lib:GetHarmMaxChecker(range)
return getMaxChecker(self.harmRC, range)
end
--- Return a checker suitable for in-range checking on miscellaneous units, that is, a checker whose range is equal or smaller than the requested range.
-- @param range the range to check for.
-- @return **checker**, **range** pair or **nil** if no suitable checker is available. **range** is the actual range the returned **checker** checks for.
function lib:GetMiscMaxChecker(range)
return getMaxChecker(self.miscRC, range)
end
--- Return a checker for the given range for friendly units.
-- @param range the range to check for.
-- @return **checker** function or **nil** if no suitable checker is available.
function lib:GetFriendChecker(range)
return getChecker(self.friendRC, range)
end
--- Return a checker for the given range for enemy units.
-- @param range the range to check for.
-- @return **checker** function or **nil** if no suitable checker is available.
function lib:GetHarmChecker(range)
return getChecker(self.harmRC, range)
end
--- Return a checker for the given range for miscellaneous units.
-- @param range the range to check for.
-- @return **checker** function or **nil** if no suitable checker is available.
function lib:GetMiscChecker(range)
return getChecker(self.miscRC, range)
end
--- Return a checker suitable for out-of-range checking that checks the unit type and calls the appropriate checker (friend/harm/misc).
-- @param range the range to check for.
-- @return **checker** function.
function lib:GetSmartMinChecker(range)
return createSmartChecker(
getMinChecker(self.friendRC, range),
getMinChecker(self.harmRC, range),
getMinChecker(self.miscRC, range))
end
--- Return a checker suitable for in-of-range checking that checks the unit type and calls the appropriate checker (friend/harm/misc).
-- @param range the range to check for.
-- @return **checker** function.
function lib:GetSmartMaxChecker(range)
return createSmartChecker(
getMaxChecker(self.friendRC, range),
getMaxChecker(self.harmRC, range),
getMaxChecker(self.miscRC, range))
end
--- Return a checker for the given range that checks the unit type and calls the appropriate checker (friend/harm/misc).
-- @param range the range to check for.
-- @param fallback optional fallback function that gets called as fallback(unit) if a checker is not available for the given type (friend/harm/misc) at the requested range. The default fallback function return nil.
-- @return **checker** function.
function lib:GetSmartChecker(range, fallback)
return createSmartChecker(
getChecker(self.friendRC, range) or fallback,
getChecker(self.harmRC, range) or fallback,
getChecker(self.miscRC, range) or fallback)
end
--- Get a range estimate as **minRange**, **maxRange**.
-- @param unit the target unit to check range to.
-- @return **minRange**, **maxRange** pair if a range estimate could be determined, **nil** otherwise. **maxRange** is **nil** if **unit** is further away than the highest possible range we can check.
-- Includes checks for unit validity and friendly/enemy status.
-- @usage
-- local rc = LibStub("LibRangeCheck-2.0")
-- local minRange, maxRange = rc:GetRange('target')
function lib:GetRange(unit)
if not UnitExists(unit) then
return nil
end
if UnitIsDeadOrGhost(unit) then
return getRange(unit, self.miscRC)
end
if UnitCanAttack("player", unit) then
return getRange(unit, self.harmRC)
elseif UnitCanAssist("player", unit) then
return getRange(unit, self.friendRC)
else
return getRange(unit, self.miscRC)
end
end
-- keep this for compatibility
lib.getRange = lib.GetRange
-- >> Public API
function lib:OnEvent(event, ...)
if type(self[event]) == 'function' then
self[event](self, event, ...)
end
end
function lib:LEARNED_SPELL_IN_TAB()
self:scheduleInit()
end
function lib:CHARACTER_POINTS_CHANGED()
self:scheduleInit()
end
function lib:PLAYER_TALENT_UPDATE()
self:scheduleInit()
end
function lib:GLYPH_ADDED()
self:scheduleInit()
end
function lib:GLYPH_REMOVED()
self:scheduleInit()
end
function lib:GLYPH_UPDATED()
self:scheduleInit()
end
function lib:SPELLS_CHANGED()
self:scheduleInit()
end
function lib:UNIT_INVENTORY_CHANGED(event, unit)
if self.initialized and unit == "player" and self.handSlotItem ~= GetInventoryItemLink("player", HandSlotId) then
self:scheduleInit()
end
end
function lib:UNIT_AURA(event, unit)
if self.initialized and unit == "player" then
self:scheduleAuraCheck()
end
end
function lib:processItemRequests(itemRequests)
while true do
local range, items = next(itemRequests)
if not range then return end
while true do
local i, item = next(items)
if not i then
itemRequests[range] = nil
break
elseif self.failedItemRequests[item] then
tremove(items, i)
elseif GetItemInfo(item) then
if itemRequestTimeoutAt then
foundNewItems = true
itemRequestTimeoutAt = nil
end
if not cacheAllItems then
itemRequests[range] = nil
break
end
tremove(items, i)
elseif not itemRequestTimeoutAt then
itemRequestTimeoutAt = GetTime() + ItemRequestTimeout
return true
elseif GetTime() > itemRequestTimeoutAt then
if cacheAllItems then
print(MAJOR_VERSION .. ": timeout for item: " .. tostring(item))
end
self.failedItemRequests[item] = true
itemRequestTimeoutAt = nil
tremove(items, i)
else
return true -- still waiting for server response
end
end
end
end
function lib:initialOnUpdate()
self:init()
if friendItemRequests then
if self:processItemRequests(friendItemRequests) then return end
friendItemRequests = nil
end
if harmItemRequests then
if self:processItemRequests(harmItemRequests) then return end
harmItemRequests = nil
end
if foundNewItems then
self:init(true)
foundNewItems = nil
end
if cacheAllItems then
print(MAJOR_VERSION .. ": finished cache")
cacheAllItems = nil
end
self.frame:Hide()
end
function lib:scheduleInit()
self.initialized = nil
lastUpdate = 0
self.frame:Show()
end
function lib:scheduleAuraCheck()
lastUpdate = UpdateDelay
self.frame:Show()
end
-- << load-time initialization
function lib:activate()
if not self.frame then
local frame = CreateFrame("Frame")
self.frame = frame
frame:RegisterEvent("LEARNED_SPELL_IN_TAB")
frame:RegisterEvent("CHARACTER_POINTS_CHANGED")
frame:RegisterEvent("PLAYER_TALENT_UPDATE")
-- frame:RegisterEvent("GLYPH_ADDED")
-- frame:RegisterEvent("GLYPH_REMOVED")
-- frame:RegisterEvent("GLYPH_UPDATED")
frame:RegisterEvent("SPELLS_CHANGED")
local _, playerClass = UnitClass("player")
if playerClass == "MAGE" or playerClass == "SHAMAN" then
-- Mage and Shaman gladiator gloves modify spell ranges
frame:RegisterUnitEvent("UNIT_INVENTORY_CHANGED", "player")
end
end
initItemRequests()
self.frame:SetScript("OnEvent", function(frame, ...) self:OnEvent(...) end)
self.frame:SetScript("OnUpdate", function(frame, elapsed)
lastUpdate = lastUpdate + elapsed
if lastUpdate < UpdateDelay then
return
end
lastUpdate = 0
self:initialOnUpdate()
end)
self:scheduleInit()
end
--- BEGIN CallbackHandler stuff
do
local lib = lib -- to keep a ref even though later we nil lib
--- Register a callback to get called when checkers are updated
-- @class function
-- @name lib.RegisterCallback
-- @usage
-- rc.RegisterCallback(self, rc.CHECKERS_CHANGED, "myCallback")
-- -- or
-- rc.RegisterCallback(self, "CHECKERS_CHANGED", someCallbackFunction)
-- @see CallbackHandler-1.0 documentation for more details
lib.RegisterCallback = lib.RegisterCallback or function(...)
local CBH = LibStub("CallbackHandler-1.0")
lib.RegisterCallback = nil -- extra safety, we shouldn't get this far if CBH is not found, but better an error later than an infinite recursion now
lib.callbacks = CBH:New(lib)
-- ok, CBH hopefully injected or new shiny RegisterCallback
return lib.RegisterCallback(...)
end
end
--- END CallbackHandler stuff
lib:activate()
lib = nil
| gpl-3.0 |
parhamhp/supersp | plugins/img_google.lua | 660 | 3196 | do
local mime = require("mime")
local google_config = load_from_file('data/google.lua')
local cache = {}
--[[
local function send_request(url)
local t = {}
local options = {
url = url,
sink = ltn12.sink.table(t),
method = "GET"
}
local a, code, headers, status = http.request(options)
return table.concat(t), code, headers, status
end]]--
local function get_google_data(text)
local url = "http://ajax.googleapis.com/ajax/services/search/images?"
url = url.."v=1.0&rsz=5"
url = url.."&q="..URL.escape(text)
url = url.."&imgsz=small|medium|large"
if google_config.api_keys then
local i = math.random(#google_config.api_keys)
local api_key = google_config.api_keys[i]
if api_key then
url = url.."&key="..api_key
end
end
local res, code = http.request(url)
if code ~= 200 then
print("HTTP Error code:", code)
return nil
end
local google = json:decode(res)
return google
end
-- Returns only the useful google data to save on cache
local function simple_google_table(google)
local new_table = {}
new_table.responseData = {}
new_table.responseDetails = google.responseDetails
new_table.responseStatus = google.responseStatus
new_table.responseData.results = {}
local results = google.responseData.results
for k,result in pairs(results) do
new_table.responseData.results[k] = {}
new_table.responseData.results[k].unescapedUrl = result.unescapedUrl
new_table.responseData.results[k].url = result.url
end
return new_table
end
local function save_to_cache(query, data)
-- Saves result on cache
if string.len(query) <= 7 then
local text_b64 = mime.b64(query)
if not cache[text_b64] then
local simple_google = simple_google_table(data)
cache[text_b64] = simple_google
end
end
end
local function process_google_data(google, receiver, query)
if google.responseStatus == 403 then
local text = 'ERROR: Reached maximum searches per day'
send_msg(receiver, text, ok_cb, false)
elseif google.responseStatus == 200 then
local data = google.responseData
if not data or not data.results or #data.results == 0 then
local text = 'Image not found.'
send_msg(receiver, text, ok_cb, false)
return false
end
-- Random image from table
local i = math.random(#data.results)
local url = data.results[i].unescapedUrl or data.results[i].url
local old_timeout = http.TIMEOUT or 10
http.TIMEOUT = 5
send_photo_from_url(receiver, url)
http.TIMEOUT = old_timeout
save_to_cache(query, google)
else
local text = 'ERROR!'
send_msg(receiver, text, ok_cb, false)
end
end
function run(msg, matches)
local receiver = get_receiver(msg)
local text = matches[1]
local text_b64 = mime.b64(text)
local cached = cache[text_b64]
if cached then
process_google_data(cached, receiver, text)
else
local data = get_google_data(text)
process_google_data(data, receiver, text)
end
end
return {
description = "Search image with Google API and sends it.",
usage = "!img [term]: Random search an image with Google API.",
patterns = {
"^!img (.*)$"
},
run = run
}
end
| gpl-2.0 |
tianxiawuzhei/cocos-quick-lua | quick/samples/statemachine/src/scenes/MainScene.lua | 2 | 6454 |
local MainScene = class("MainScene", function()
return display.newScene("MainScene")
end)
function MainScene:ctor()
-- create Finite State Machine
self.fsm_ = {}
cc.GameObject.extend(self.fsm_)
:addComponent("components.behavior.StateMachine")
:exportMethods()
self.fsm_:setupState({
events = {
{name = "start", from = "none", to = "green" },
{name = "warn", from = "green", to = "yellow"},
{name = "panic", from = "green", to = "red" },
{name = "panic", from = "yellow", to = "red" },
{name = "calm", from = "red", to = "yellow"},
{name = "clear", from = "red", to = "green" },
{name = "clear", from = "yellow", to = "green" },
},
callbacks = {
onbeforestart = function(event) self:log("[FSM] STARTING UP") end,
onstart = function(event) self:log("[FSM] READY") end,
onbeforewarn = function(event) self:log("[FSM] START EVENT: warn!", true) end,
onbeforepanic = function(event) self:log("[FSM] START EVENT: panic!", true) end,
onbeforecalm = function(event) self:log("[FSM] START EVENT: calm!", true) end,
onbeforeclear = function(event) self:log("[FSM] START EVENT: clear!", true) end,
onwarn = function(event) self:log("[FSM] FINISH EVENT: warn!") end,
onpanic = function(event) self:log("[FSM] FINISH EVENT: panic!") end,
oncalm = function(event) self:log("[FSM] FINISH EVENT: calm!") end,
onclear = function(event) self:log("[FSM] FINISH EVENT: clear!") end,
onleavegreen = function(event) self:log("[FSM] LEAVE STATE: green") end,
onleaveyellow = function(event) self:log("[FSM] LEAVE STATE: yellow") end,
onleavered = function(event)
self:log("[FSM] LEAVE STATE: red")
self:pending(event, 3)
self:performWithDelay(function()
self:pending(event, 2)
self:performWithDelay(function()
self:pending(event, 1)
self:performWithDelay(function()
self.pendingLabel_:setString("")
event.transition()
end, 1)
end, 1)
end, 1)
return "async"
end,
ongreen = function(event) self:log("[FSM] ENTER STATE: green") end,
onyellow = function(event) self:log("[FSM] ENTER STATE: yellow") end,
onred = function(event) self:log("[FSM] ENTER STATE: red") end,
onchangestate = function(event) self:log("[FSM] CHANGED STATE: " .. event.from .. " to " .. event.to) end,
},
})
-- create UI
display.newColorLayer(cc.c4b(255, 255, 255, 255))
:addTo(self)
cc.ui.UILabel.new({
text = "Finite State Machine",
size = 32,
color = display.COLOR_BLACK
})
:align(display.CENTER, display.cx, display.top - 60)
:addTo(self)
self.pendingLabel_ = cc.ui.UILabel.new({
text = "",
size = 32,
color = display.COLOR_BLACK,
x = display.cx,
y = display.top - 620,
})
:align(display.CENTER)
:addTo(self)
-- preload texture
self.stateImage_ = display.newSprite("#GreenState.png")
:pos(display.cx, display.top - 300)
:scale(1.5)
:addTo(self)
self.clearButton_ =
cc.ui.UIPushButton.new()
:setButtonLabel(cc.ui.UILabel.new({text = "clear", size = 32, color = display.COLOR_BLACK}))
:onButtonClicked(function()
if self.fsm_:canDoEvent("clear") then
self.fsm_:doEvent("clear")
end
end)
:align(display.CENTER, display.cx - 150, display.top - 540)
:addTo(self)
self.calmButton_ =
cc.ui.UIPushButton.new()
:setButtonLabel(cc.ui.UILabel.new({text = "calm", size = 32, color = display.COLOR_BLACK}))
:onButtonClicked(function()
if self.fsm_:canDoEvent("calm") then
self.fsm_:doEvent("calm")
end
end)
:align(display.CENTER, display.cx - 50, display.top - 540)
:addTo(self)
self.warnButton_ =
cc.ui.UIPushButton.new()
:setButtonLabel(cc.ui.UILabel.new({text = "warn", size = 32, color = display.COLOR_BLACK}))
:onButtonClicked(function()
if self.fsm_:canDoEvent("warn") then
self.fsm_:doEvent("warn")
end
end)
:align(display.CENTER, display.cx + 50, display.top - 540)
:addTo(self)
self.panicButton_ =
cc.ui.UIPushButton.new()
:setButtonLabel(cc.ui.UILabel.new({text = "panic", size = 32, color = display.COLOR_BLACK}))
:onButtonClicked(function()
if self.fsm_:canDoEvent("panic") then
self.fsm_:doEvent("panic")
end
end)
:align(display.CENTER, display.cx + 150, display.top - 540)
:addTo(self)
-- debug
self.logCount_ = 0
end
function MainScene:pending(event, n)
local msg = event.to .. " in ..." .. n
self:log("[FSM] PENDING STATE: " .. msg)
self.pendingLabel_:setString(msg)
end
function MainScene:log(msg, separate)
if separate then self.logCount_ = self.logCount_ + 1 end
if separate then print("") end
printf("%d: %s", self.logCount_, msg)
local state = self.fsm_:getState()
if state == "green" then
self.stateImage_:setSpriteFrame(display.newSpriteFrame("GreenState.png"))
elseif state == "red" then
self.stateImage_:setSpriteFrame(display.newSpriteFrame("RedState.png"))
elseif state == "yellow" then
self.stateImage_:setSpriteFrame(display.newSpriteFrame("YellowState.png"))
end
-- self.clearButton_:setEnabled(self.fsm_:canDoEvent("clear"))
-- self.calmButton_:setEnabled(self.fsm_:canDoEvent("calm"))
-- self.warnButton_:setEnabled(self.fsm_:canDoEvent("warn"))
-- self.panicButton_:setEnabled(self.fsm_:canDoEvent("panic"))
end
function MainScene:onEnter()
self.fsm_:doEvent("start")
end
return MainScene
| mit |
kunkku/luaossl | regress/82-bn_prepops-null-deref.lua | 3 | 1643 | #!/usr/bin/env lua
--
-- The following code could trigger a NULL dereference.
--
-- bn_prepops(lua_State *L, BIGNUM **r, BIGNUM **a, BIGNUM **b, _Bool commute) {
-- ...
-- *b = checkbig(L, 2, &lvalue);
-- ...
-- }
--
-- bn_sqr(lua_State *L) {
-- BIGNUM *r, *a;
--
-- bn_prepops(L, &r, &a, NULL, 1);
-- ...
-- }
--
-- Caught by clang static analyzer. This was introduced with a patch adding
-- the :sqr method. This should have been caught sooner as the :sqr method
-- couldn't have possibly ever worked--a missing or non-numeric second
-- operand would have thrown a Lua error, and a numeric second operand
-- triggers the NULL dereference.
--
require"regress".export".*"
local function N(i) return bignum.new(i) end
-- passing a second numeric operand triggered a NULL dereference
local r = N(4):sqr(0)
-- check minimal functionality of all our operators
local tests = {
{ op = "add", a = 1, b = 1, r = 2 },
{ op = "sub", a = 2, b = 1, r = 1 },
{ op = "mul", a = 2, b = 2, r = 4 },
{ op = "idiv", a = 4, b = 2, r = 2 },
{ op = "mod", a = 4, b = 2, r = 0 },
{ op = "exp", a = 2, b = 2, r = 4 },
{ op = "sqr", a = 4, b = nil, r = 16 },
{ op = "gcd", a = 47, b = 3, r = 1 },
}
local function tdescr(t)
return string.format("%s(%s, %s)", t.op, tostring(t.a), tostring(t.b))
end
for i,t in ipairs(tests) do
local a = N(t.a)
local op = a[t.op]
local ok, r
if t.b then
ok, r = pcall(op, a, t.b)
else
ok, r = pcall(op, a)
end
check(ok, "failed test #%d (%s) (%s)", i, tdescr(t), r)
check(N(r) == N(t.r), "failed test #%d (%s) (expected %s, got %s)", i, tdescr(t), tostring(t.r), tostring(r))
end
say"OK"
| mit |
saeqe/botele | plugins/domaintools.lua | 359 | 1494 | local ltn12 = require "ltn12"
local https = require "ssl.https"
-- Edit data/mashape.lua with your Mashape API key
-- http://docs.mashape.com/api-keys
local mashape = load_from_file('data/mashape.lua', {
api_key = ''
})
local function check(name)
local api = "https://domainsearch.p.mashape.com/index.php?"
local param = "name="..name
local url = api..param
local api_key = mashape.api_key
if api_key:isempty() then
return 'Configure your Mashape API Key'
end
local headers = {
["X-Mashape-Key"] = api_key,
["Accept"] = "application/json"
}
local respbody = {}
local body, code = https.request{
url = url,
method = "GET",
headers = headers,
sink = ltn12.sink.table(respbody),
protocol = "tlsv1"
}
if code ~= 200 then return code end
local body = table.concat(respbody)
local body = json:decode(body)
--vardump(body)
local domains = "List of domains for '"..name.."':\n"
for k,v in pairs(body) do
print(k)
local status = " ❌ "
if v == "Available" then
status = " ✔ "
end
domains = domains..k..status.."\n"
end
return domains
end
local function run(msg, matches)
if matches[1] == "check" then
local name = matches[2]
return check(name)
end
end
return {
description = "Domain tools",
usage = {"!domain check [domain] : Check domain name availability.",
},
patterns = {
"^!domain (check) (.*)$",
},
run = run
}
| gpl-2.0 |
aperezdc/lua-eol | examples/nanovg-noise.lua | 2 | 1095 | #! /usr/bin/env lua
--
-- nanovg-noise.lua
-- Copyright (C) 2015 Adrian Perez <aperez@igalia.com>
--
-- Distributed under terms of the MIT license.
--
local eol = require "eol"
local nvg = require "modularize" {
"nanovg", prefix = "nvg", type_prefix = "NVG"
}
local inttype = eol.type(nvg.__library, "long int")
local ucharptr = eol.type(nvg.__library, "unsigned char"):pointerto()
local W = 320
local H = 240
local window = nvg.Window("Noise", W, H)
nvg.MakeCurrent(window)
local vg = nvg.Create(false)
local bits = inttype(W * H / 2)
local bits_as_ptr = eol.cast(ucharptr, bits)
local image = nvg.CreateImageRGBA(vg, W, H, 0, bits_as_ptr)
local paint = nvg.ImagePattern(vg, 0, 0, W, H, 0.0, image, 1.0)
while not nvg.Done(window) do
-- Fill with random data
local r = bits[1] + 1
for i = 1, #bits do
r = r * 1103515245
bits[i] = r ~ (bits[i] >> 16)
end
nvg.UpdateImage(vg, image, bits_as_ptr)
nvg.FrameStart(window, vg)
nvg.BeginPath(vg)
nvg.Rect(vg, 0, 0, W, H)
nvg.FillPaint(vg, paint)
nvg.Fill(vg)
nvg.FrameEnd(window, vg)
end
nvg.DeleteImage(vg, image)
nvg.Exit()
| mit |
Source-Saraya/S.R.A | plugins/addtime.lua | 1 | 4088 |
local function check_member_superrem2(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration removal
data[tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = nil
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
chat_del_user(get_receiver(msg), 'user#id'..235431064, ok_cb, false)
leave_channel(get_receiver(msg), ok_cb, false)
end
end
end
local function superrem2(msg)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
channel_get_users(receiver, check_member_superrem2,{receiver = receiver, data = data, msg = msg})
end
local function pre_process(msg)
local timetoexpire = 'unknown'
local expiretime = redis:hget ('expiretime', get_receiver(msg))
local now = tonumber(os.time())
if expiretime then
timetoexpire = math.floor((tonumber(expiretime) - tonumber(now)) / 86400) + 1
if tonumber("0") > tonumber(timetoexpire) then
if get_receiver(msg) then
redis:del('expiretime', get_receiver(msg))
rem_mutes(msg.to.id)
superrem2(msg)
return send_large_msg(get_receiver(msg), '🔰انتهى تاريخ الصلاحيه في المجموعه🔰')
else
return
end
end
if tonumber(timetoexpire) == 0 then
if redis:hget('expires0',msg.to.id) then return msg end
send_large_msg(get_receiver(msg), '.')
redis:hset('expires0',msg.to.id,'5')
end
if tonumber(timetoexpire) == 1 then
if redis:hget('expires1',msg.to.id) then return msg end
send_large_msg(get_receiver(msg), ' 🔰باقي صفر من الايام التي تم تعيينها 🔰 \n راسل المطور لاعاده تفعيل البوت🔰')
redis:hset('expires1',msg.to.id,'5')
end
if tonumber(timetoexpire) == 2 then
if redis:hget('expires2',msg.to.id) then return msg end
send_large_msg(get_receiver(msg), '🔰 بقه يومان الى انتهاء تفعيل البوت هنا 🔰 \n راسل المطور لااعاده التفعيل 🔰')
redis:hset('expires2',msg.to.id,'5')
end
if tonumber(timetoexpire) == 3 then
if redis:hget('expires3',msg.to.id) then return msg end
send_large_msg(get_receiver(msg), '🔰 بقه ثلاثه ايام الى انتهاء تفعيل البوت هنا 🔰 \n راسل المطور لااعاده التفعيل 🔰')
redis:hset('expires3',msg.to.id,'5')
end
if tonumber(timetoexpire) == 4 then
if redis:hget('expires4',msg.to.id) then return msg end
send_large_msg(get_receiver(msg), '🔰 بقه اربعه ايام ايام الى انتهاء تفعيل البوت هنا 🔰 \n راسل المطور لااعاده التفعيل 🔰')
redis:hset('expires4',msg.to.id,'5')
end
if tonumber(timetoexpire) == 5 then
if redis:hget('expires5',msg.to.id) then return msg end
send_large_msg(get_receiver(msg), '🔰 بقه خمسه ايام ايام الى انتهاء تفعيل البوت هنا 🔰\n راسل المطور لااعاده التفعيل 🔰')
redis:hset('expires5',msg.to.id,'5')
end
end
return msg
end
function run(msg, matches)
if matches[1]:lower() == 'تفعيل لمده' then
if not is_sudo(msg) then return end
local time = os.time()
local buytime = tonumber(os.time())
local timeexpire = tonumber(buytime) + (tonumber(matches[2]) * 86400)
redis:hset('expiretime',get_receiver(msg),timeexpire)
return "♻️تم وضع مده صلاحيه المجموعه♻️ ("..matches[2].. ") "
end
if matches[1]:lower() == 'المدة المتبقيه' then
local expiretime = redis:hget ('expiretime', get_receiver(msg))
if not expiretime then return '🔰لم يتم تحديد تاريخ🔰' else
local now = tonumber(os.time())
return (math.floor((tonumber(expiretime) - tonumber(now)) / 86400) + 1) .. "يـوم اخـر 🗣"
end
end
end
return {
patterns = {
"^(تفعيل لمده) (.*)$",
"^(المدة المتبقيه)$",
},
run = run,
pre_process = pre_process
}
| gpl-3.0 |
mahdikord/baran | plugins/webshot.lua | 919 | 1473 | local helpers = require "OAuth.helpers"
local base = 'https://screenshotmachine.com/'
local url = base .. 'processor.php'
local function get_webshot_url(param)
local response_body = {}
local request_constructor = {
url = url,
method = "GET",
sink = ltn12.sink.table(response_body),
headers = {
referer = base,
dnt = "1",
origin = base,
["User-Agent"] = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36"
},
redirect = false
}
local arguments = {
urlparam = param,
size = "FULL"
}
request_constructor.url = url .. "?" .. helpers.url_encode_arguments(arguments)
local ok, response_code, response_headers, response_status_line = https.request(request_constructor)
if not ok or response_code ~= 200 then
return nil
end
local response = table.concat(response_body)
return string.match(response, "href='(.-)'")
end
local function run(msg, matches)
local find = get_webshot_url(matches[1])
if find then
local imgurl = base .. find
local receiver = get_receiver(msg)
send_photo_from_url(receiver, imgurl)
end
end
return {
description = "Send an screenshot of a website.",
usage = {
"!webshot [url]: Take an screenshot of the web and send it back to you."
},
patterns = {
"^!webshot (https?://[%w-_%.%?%.:/%+=&]+)$",
},
run = run
}
| gpl-2.0 |
anonymou3Team/hackedanonymous | plugins/webshot.lua | 919 | 1473 | local helpers = require "OAuth.helpers"
local base = 'https://screenshotmachine.com/'
local url = base .. 'processor.php'
local function get_webshot_url(param)
local response_body = {}
local request_constructor = {
url = url,
method = "GET",
sink = ltn12.sink.table(response_body),
headers = {
referer = base,
dnt = "1",
origin = base,
["User-Agent"] = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36"
},
redirect = false
}
local arguments = {
urlparam = param,
size = "FULL"
}
request_constructor.url = url .. "?" .. helpers.url_encode_arguments(arguments)
local ok, response_code, response_headers, response_status_line = https.request(request_constructor)
if not ok or response_code ~= 200 then
return nil
end
local response = table.concat(response_body)
return string.match(response, "href='(.-)'")
end
local function run(msg, matches)
local find = get_webshot_url(matches[1])
if find then
local imgurl = base .. find
local receiver = get_receiver(msg)
send_photo_from_url(receiver, imgurl)
end
end
return {
description = "Send an screenshot of a website.",
usage = {
"!webshot [url]: Take an screenshot of the web and send it back to you."
},
patterns = {
"^!webshot (https?://[%w-_%.%?%.:/%+=&]+)$",
},
run = run
}
| gpl-2.0 |
ufo2000/ufo2000 | script/lumikki.lua | 2 | 63417 | -- !!! Modified version of lumikki (added support for lua sources
-- syntax highlighting)
--
-- FILTERS.LUA Lumikki built-in filter functions
--
-- Note: This file should be read in by '-l filters.lua' as part of the Lua
-- command line to launch Lumikki. This in order to allow easy modifications
-- of the file, and/or extend its features in another .lua file (you can
-- read in as many libraries as you want).
--
-- To-do:
-- ImageMagick version detection (require 6.x)
--
-- AK(20-Oct-04): Started making 'covert' for <@GRA..>
--
function LUASOURCE(tbl, text)
local rc, sout, serr = os.execute("source-highlight -f html -s lua -c x --no-doc", 3, text)
if rc ~= 0 then sout = "<pre>" .. text .. "</pre>" end
sout = string.gsub(sout, "<tt>", "")
sout = string.gsub(sout, "</tt>", "")
return "<table class='source'><tr><td>" .. sout .. "</table>"
end
local function ASSUME_FLAGS( tbl, lookup )
--
ASSUME( tbl )
lookup= lookup or {}
-- Make sure 'tbl' only has the named tags, no else.
--
-- Note: prefixing flags with '_' can be used to disable them (no complaints)
--
for k,v in tbl do
if string.sub(k,1,1)=='_' then
-- '_xxx'; no complaints
elseif not lookup[k] then
error( "Unexpected param: "..k.. (v~=nil and ("="..tostring(v)) or "") )
end
end
end
-----
-- void= CHECK_IM_VERSION()
--
-- ImageMagick detection
--
local has_im -- 'true' when tested
local function CHECK_IM_VERSION( match_str )
--
if has_im then return true end -- tested already
-- 'support.lua' has an enhanced 'os.execute' for us.. (with catching)
--
local rc,sout,serr= os.execute( "convert -version", 3 )
if rc~=0 or (not sout) then
error "*** ImageMagick (v.6.x) required ***"
end
-- Sample output (OS X):
-- "Version: ImageMagick 5.5.6 04/01/03 Q16 http://www.imagemagick.org
-- Copyright: Copyright (C) 2003 ImageMagick Studio LLC"
--
local ver= third( string.find( sout, "ImageMagick ([%d%.]+) " ) )
--
-- "5.5.6"
local _,_, a,b,_= string.find( ver, "(%d+)%.(%d+)" )
ASSUME(a)
if tonumber(a)<6 then
error( "*** ImageMagick v.6.x required *** ("..ver.." found)" )
end
return true -- all ok :)
end
-----
-- fn_str= Loc_OutName( fn_str / sfx_str )
--
-- Returns a unique filename under the "temp/" subdirectory.
--
local tmpname_count= 0
local function Loc_OutName( str )
--
str= string.gsub( str, "^%*", "" ) -- "*.sfx" same as ".sfx"
if string.sub(str,1,1)=='.' then -- just suffix, generate filename
--
tmpname_count= tmpname_count+1
str= "file"..tmpname_count..str -- keep suffix
end
local path,fn= PathSplit( CurrentFile(), true )
-- We can make a subdir per each HTML file, or just use naming to keep them separate.
--
if false then
-- subdir per each source file
path= "temp/"..(path or "")..fn..'/'
fn= str
else
-- avoid making lots of subdirs
if fn=="index" then -- special case for shorter filenames (still remains unique)
fn= str
else
fn= fn..'-'..str
end
fn= string.gsub( path, "[/\\]", "-" )..fn
path= "temp/" -- place all temp files in one dir
end
Mkdir( path ) -- make sure the target subdir is there
return path..fn
end
-----
-- fn_str= Loc_Convert( convert_str )
--
-- Interface to powerful ImageMagick picture processing.
--
-- Returns: the (temporary) output filename.
--
local function Loc_Convert( convert )
--
CHECK_IM_VERSION() -- 6.x required
convert= string.gsub( convert, "%s+", " " ) -- clean multiple spaces (may contain newlines)
convert= string.gsub( convert, "([!%(%)])", "\\%1" ) -- chars needing an escape (for shell)
local fn_out
local head, last_word= skip2( string.find( convert, "(.+)%s+(%S+)$" ) )
-- is last word a filename (suffix, at least) but not a "tile:blahblah" kindof param:
--
if last_word and string.find(last_word,"%.") and
(not string.find(last_word,":")) then
--
fn_out= Loc_OutName(last_word) -- file type or full name given
convert= head
else
fn_out= Loc_OutName(".jpg") -- default file type
end
local path= CurrentDir() -- subpath of current file
local up_path= ""
if path then
up_path= string.rep( "../", second( string.gsub(path,"[/\\]","") ) )
end
local cmd= (path and ("cd "..string.sub(path,1,-2).."; ") or "").."convert "..convert..' '..up_path..fn_out
io.stderr:write(cmd..'\n')
local rc= os.execute( cmd )
if rc~=0 then
SYNTAX_ERROR "bad 'convert' syntax" -- we know IM 6.x is installed (couldn't be that)
end
ASSUME( FileExists( fn_out ) )
return up_path..fn_out
end
--=== Filter functions (global) ===--
-----
-- <@DOCUMENT [title=str] [author=str] [keywords=str] [stylesheet=url]
-- [background=url/#hex/colorname]>
--
function DOCUMENT( tbl )
--
ASSUME_FLAGS( tbl, {title=1,author=1,keywords=1,stylesheet=1,background=1} )
local str= "<html><head>\n"
if tbl.title then
str= str..[[
<title>]]..(tbl.title)..[[</title>
]]
end
if tbl.author then
str= str..[[
<meta name="Author" content="]]..(tbl.author)..[[">
]]
end
if tbl.keywords then
str= str..[[
<meta name="Keywords" content="]]..(tbl.keywords)..[[">
]]
end
if tbl.stylesheet then
str= str..[[
<link rel="stylesheet" type="text/css" href="]]..(tbl.stylesheet)..[[">
]]
end
local bg= tbl.background
if bg then
if string.find( bg, "%." ) then -- picture file
bg= " background=\""..bg.."\""
else
bg= " bgcolor=\""..bg.."\"" -- "#ffffff", "red" etc.
end
end
str= str..[[
</head>
<body]]..(bg or "")..'>'
return str
end
-----
-- <@EVAL>lua expession</@EVAL>
--
function EVAL( tbl, text )
--
ASSUME_FLAGS(tbl,nil)
if not text then
return "" -- nothing to do!
else
return loadstring( "return "..text )()
end
end
-----
-- <@FONT [size_int] ["i"/"italic"] ["u"/"underlined"] ["red"] ...>text</@>
--
-- Normal <font> doesn't allow italics, does it..? Frustrating!
--
-- With this func, all settings can be given at once, and the terminating tag
-- closes them.
--
-- There's >600 of these, we probably won't list them all.. :)
--
local color_lookup= { red=1, blue=1, yellow=1, white=1, black=1, green=1, gray=1 }
function FONT( tbl, text )
--
local size, italic, underlined, bold, color
for k,_ in tbl do
if tonumber(k) then
size= tonumber(k) -- -1/0/1
--
elseif k=="italic" or k=="i" then
italic= true
elseif string.find(k,"under") or k=="u" then
underlined= true
elseif k=="bold" or k=="b" then
bold= true
elseif color_lookup[k] then
color= k -- "red", ...
else
SYNTAX_ERROR( "Unknown @FONT param: "..k.."= "..tostring(v) )
end
end
local pre= "<font"..
((size and ' size="'..size..'"') or "")..
((color and ' color="'..color..'"') or "")..
">"
local post= "</font>"
if italic then
pre= pre.."<i>"
post= "</i>"..post
end
if underlined then
pre= pre.."<u>"
post= "</u>"..post
end
if bold then
pre= pre.."<b>"
post= "</b>"..post
end
return pre..text..post
end
-----
-- <@FUNC>lua code</@FUNC>
--
-- Note: This tag may be replaced by '<@LUA>' - or not..?-)
--
function FUNC( tbl, text )
--
ASSUME_FLAGS(tbl,nil)
ASSUME(text, "@FUNC without ending tag! (empty lines not allowed)")
local block= ASSUME( loadstring( "function "..text ), "Syntax error in Lua code" )
block() -- add the new tags :)
return "<!--"..text.."-->" -- HTML output
end
-----
-- <@GRA src=url [align=right/left/center] [border[=N]] [x=width] [y=width]
-- [spacing=N] [padding=N] [tab=N]
-- [link[=url] [popup]]
-- [convert=str] [convert_to="gif"/"jpg"/"png"/...]>
-- [..picture text..
-- </@GRA>]
--
function GRA( tbl, text )
--
ASSUME_FLAGS( tbl, {align=1,src=1,x=1,y=1,link=1,popup=1,border=1,spacing=1,padding=1,tab=1,
convert=1,convert_to=1} )
ASSUME( tbl.src or tbl.convert, "<@GRA> must have 'src' or 'convert'" )
local src= tbl.src
local align= tbl.align
local x= tbl.x
local y= tbl.y
local link= (tbl.link==true) and src or tbl.link
local popup= link and tbl.popup
local border= ((tbl.border==true) and 1) or tbl.border
local spacing= tbl.spacing
local padding= tbl.padding
local tab= tbl.tab
local convert= tbl.convert
local convert_to= tbl.convert_to
ASSUME( not convert_to ) -- depricated!
-- Doing a conversion (with ImageMagick) uses another picture file; no other change.
--
if convert or convert_to then
--
if src then
convert= src..' '..convert
end
src= Loc_Convert( convert ) -- that's it!
end
-- Always put the pic within a table (allows the picture text to be beneath)
--
local str="<table".. -- border="..border..
(align and " align="..align or "")..
"><tr>"..
(tab and ("<td width="..(tab)..">") or "").. -- tabulator (left margin)
"<td>"
if border or spacing or padding then
str= str.."<table"..
((spacing and " cellspacing="..spacing) or "")..
((padding and " cellpadding="..padding) or "")..
((border and " border="..border) or "")..
"><tr><td>"
end
if link then
str= str.."<a href=\""..link.."\"" -- lead further (to pic itself)
if popup then str= str.." target=\"_blank\"" end
str= str..">"
end
str= str.."<img src=\""..src.."\" align=center"
if x then str= str.." width="..x end
if y then str= str.." height="..y end
str= str..">" -- <img..>
if link then
str= str.."</a>"
end
if border or spacing or padding then
str= str.."</tr></table>" -- inner table (around the pic)
end
if text then
str= str.."</tr><tr><td><p align=center>"..
"<font face=Arial size=-2><i>"..text.."</i></font>"
end
str= str.."</tr></table>"
return str
end
-----
-- <@INCLUDE url=filename/url [expand=false]>
--
function INCLUDE( tbl, text )
--
ASSUME_FLAGS( tbl, {url=1,expand=1} )
ASSUME( not text )
ASSUME( ReadFile ) -- should be in our disposal (from Lumikki 'dirtools.lua')
local url= ASSUME( tbl.url )
local str= ReadFile( url )
ASSUME( str, "Unable to read: "..url )
return str, (tbl.expand~=false)
end
-----
-- <@LINK [popup[=str]] [url=str]>..text..</@LINK>
--
function LINK( tbl, text )
--
--ASSUME_FLAGS( tbl, {popup=1,url=1} )
ASSUME( text )
local popup, url
for k,v in tbl do
--
if k=="popup" then
popup= (v==true and "_blank") or v
elseif k=="url" then
ASSUME( not url )
url= v
else -- free url's (skipping "url=")
ASSUME( not url )
ASSUME( v==true ) -- no value
url= k
end
end
if not url then
url= text
end
if string.find( url, "^(%a+)://" ) or -- "http://", "ftp://" etc.
string.find( url, "^%.%./" ) or -- "../", definately relative
string.find( url, "^mailto:" ) then
--
elseif string.find( url, "@" ) then -- shortcut "me@somewhere.net"
url= "mailto:"..url
--
elseif string.find( url, "^www%." ) then
url= "http://"..url
--
elseif string.find( url, "^ftp%." ) then
url= "ftp://"..url
--
else
-- If the string has i.e. "luaforge.net/..." add the "http://" prefix,
-- otherwise treat it as relative.
--
local tmp= third( string.find( url, "(.-)/" ) )
if tmp then
if string.find(tmp,"%.") then -- first part has a dot; seems like a site
url= "http://"..url
end
else
-- No slash - if it's ".org", ".net" etc.. it's a site.
-- if it's ".htm(l)", ".jpg", ".gif", ... it's a file.
--
local sfx= string.lower( third( string.find( url, "(%..-)$" ) ) )
if ({ org=1, net=1 })[sfx] then
url= "http://"..url
end
end
end
local str= "<a href=\""..url.."\""..
(popup and " target=\""..popup.."\"" or "")..
">"
return str..text.."</a>"
end
-----
-- <@LUA>lua code</@LUA>
--
-- Similar to <@FUNC> but requires 'function' word. Suits better to
-- definition of multiple functions at a time.
--
function LUA( tbl, text )
--
ASSUME_FLAGS(tbl,nil)
ASSUME(text, "@LUA without ending tag! (use '<\\@' for extended tags within the code)")
-- Remove HTML comments if any..
--
text= string.gsub( text, "<!%-%-.-%-%->", "" )
-- Enable escaped Lumikki tags:
--
text= string.gsub( text, "<\\@", "<@" )
local block= ASSUME( loadstring( text ), "Syntax error in Lua code" )
block()
return "" -- HTML output
end
-----
-- <@SKYPE me=str>
--
-- Skype Me (www.skype.com) logo, with your caller id attached.
--
function SKYPE( tbl, text )
--
ASSUME_FLAGS( tbl, {me=1} )
ASSUME( not text )
local me= tbl.me
if not me then
SYNTAX_ERROR( "SkypeMe requires id!" )
end
return [[<a href="callto://]]..me..[["><img src="http://goodies.skype.com/graphics/skypeme_btn_red.gif" border="0" alt="Skype Me!"></a>]]
end
-----
-- <@SMILEY [type=str]>
--
local smiley_lookup= {
[":)"]= "http://www.ous.edu/images/smiley.gif",
[";P"]= "http://forums.invisionpower.com/html/avatars/Smiley_Avatars/smiley-grimmace.gif"
--...
}
function SMILEY( tbl ) -- ;)
--
ASSUME_FLAGS( tbl, {type=1} )
local grin= tbl.type or ":)"
local url= smiley_lookup[grin]
if not url then -- text
return grin
else
return [[<img src="]]..url..[[" alt="]]..grin..[[">]]
end
end
--[[
-----
-- <@TAB int>
--
-- Tabulator, sort of.. :)
--
function TAB( tbl, text )
--
ASSUME( not text )
for k,_ in tbl do
return string.rep( " ", k )
end
end
]]--
-----
-- <@TAG tagname>
--
-- This func allows tags to be written in HTML code without the clumsy <TAG>
-- notation. The syntax is somewhat special, allowing any name to be used within
-- the tag (but that makes it short :).
--
function TAG( tbl, text )
--
ASSUME( not text, "Old syntax not supported: use <@TAG tagname>" )
for k,_ in tbl do
return "<"..k..">"
end
end
--
-- LUMIKKI.LUA -- Copyright (c) 2004, asko.kauppi@sci.fi
--
-- Lua website generation tool.
--
-- This library allows generation & maintenance of full, static HTML websites
-- based on Lua code, with automatic navigation links etc.
--
-- The tool can also be used stand-alone (see manual.lhtml) as a filter to
-- generate individual HTML pages, a bit like TeX, but with Lua syntax. :)
--
-- The manual of this tool (manual.lhtml) will also work as its sample.
--
-- Lua 5.0 is required (or any 100% compatible derivative).
--
-- Usage:
-- lua [-lmydef.lua] lumikki.lua input.lhtml [...] >output.htm
-- lua [-lmydef.lua] lumikki.lua dirname/. (NOT IMPLEMENTED, YET!)
--
-- The first line processes a single file (any filename suffix will do),
-- the second line processes a whole directory tree (*.lhtml -> *.html).
--
-- Use of the standard '-l' Lua command line flag allows feeding in your
-- custom function definitions for running Lumikki.
--
-- License: GPL (see license.txt)
--
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 2 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
--
-- Using the GPL license does _not_ restrict you from using this tool in
-- building commercial, closed source applications. Regard it the same as
-- the gcc compiler - if you just use the tool and don't change it, you're fine.
-- If you change it, share that change with others. :)
--
-- Author(s):
-- asko.kauppi@sci.fi
--
-- To-do: ..
--
-- History:
--
-- 14-Oct-04/ak: Tested with Gentoo Linux, NetBSD as well. Removed any OS X specifics;
-- all non-Win32 systems now dealt with similarily (generic Posix).
-- 7-Sep-04/ak: Started a revise round, adding handling of full directory trees.
-- Split the code into pieces.
-- 30-Jun-04/ak: v.0.04 added @GRA tag.
-- 27-Jun-04/ak: Allowed use of HTML comments with empty lines, and skipping
-- extended tags within such comments (may be handy).
-- 24-Jun-04/ak: v.0.03 added @FUNC and @LUA tags for embedding Lua code.
-- Revised the documentation (all funcs now mentioned).
-- 23-Jun-04/ak: v.0.01 ready and working. Oh boy! :)
-- 16-Jun-04/ak: FINALLY, started the work for real.. (after much todo..)
--
local mymod= { _info= { MODULE= "HTML site generator",
AUTHOR= "asko.kauppi@sci.fi",
COPYRIGHT= "Copyright (c) 2004, Asko Kauppi",
RELEASE= 20041014, -- release date (version)
LICENSE= "GPL" } }
local tmp,_
ASSUME= ASSUME or assert
--
local m= ( function()
--
-- GLOBALS.LUA
--
-- Purpose: Preventing unintended use of global variables.
--
-- Note: You can always use 'rawset' and 'rawget' to get direct access that
-- bypasses this safety net (not recommended for applications).
--
local m= { _info= { MODULE= "Catching unintended globals use",
AUTHOR= "asko.kauppi@sci.fi",
LICENSE= "LGPL" } }
local default_declares= -- allow some names to be used, even nondeclared
{ ['_']= 1, -- use of '_' as nondeclared, temporary variable
arg= 1, -- arguments to a file
_ALERT= 1, -- used by 'lua_error()'
}
--
local function Loc_PrintCatch( reason, index )
--
io.stderr:write( "\n\t*** "..reason.." '" ..index.. "' ***\n\n" )
--print( debug.traceback() )
local info= debug.getinfo(3)
--
-- .source lua filename
-- .what "main"
-- .func function object
-- .short_src lua filename
-- .currentline 19
-- .namewhat ""
local src= assert( info.short_src )
local what= assert( info.what )
local line= assert( info.currentline )
io.stderr:write( "\tAt: "..src.." line "..line )
if what~="main" then
io.stderr:write( " ("..what..")" )
end
io.stderr:write "\n"
-- Note: 'assert(false)' would not break outside scripts (using 'pcall').
-- 'os.exit()' exits all at once.
--
os.exit(-1)
end
--
local function Loc_SettableEvent( tbl, index, value )
--
if (type(value)~="function") and (not m._declared[ index ]) then
--
Loc_PrintCatch( "Undeclared global:", index )
ASSUME(nil)
end
rawset( tbl, index, value )
end
--
local function Loc_GettableEvent( tbl, index )
--
if not m._declared[ index ] then
Loc_PrintCatch( "Reading undeclared global:", index )
ASSUME(nil)
end
return rawget( tbl, index )
end
-----
-- Declare globals (so that we can initialise them & use even if they're 'nil')
--
-- Note: Tables are tolerated (flattened) so that you can enter the list of
-- global names either as:
-- declare 'a'
-- declare( 'a','b','c' )
-- declare{ 'a','b','c', {'d','e'} }
--
function m.declare( ... )
--
for i=1, table.getn(arg) do
--
local v= arg[i]
local t= type(v)
if t=="table" then
m.declare( unpack(v) ) -- flatten recursively
--
elseif t=="string" then
m._declared[v]= 1 -- now known in the lookup
else
error( "Unable to declare variable '"..(v or "nil").."'!" )
end
end
end
function m.reset()
--
m._declared= default_declares
end
-----
-- List globals (on the screen):
--
function m.list()
--
io.stderr:write "Declared globals:\n"
for k,_ in (m._declared) do
io.stderr:write( "\t"..k..'\n' )
end
end
--
function m.on()
--
local mt
local globals= getfenv(0)
mt= getmetatable(globals)
if not mt then
mt= {}
setmetatable( globals, mt )
end
mt.__newindex= Loc_SettableEvent
mt.__index= Loc_GettableEvent
end
--
function m.off()
--
local mt
local globals= getfenv(0)
mt= getmetatable(globals)
if not mt then
mt= {}
setmetatable( globals, mt )
end
mt.__newindex= nil
mt.__index= nil
end
--
function m.reset()
m._declared= default_declares -- lookup of globals (names as indices)
m.on()
end
--
function m.help()
--
print "\n"
print "Undeclared use of global variables will now be trapped."
print ""
print "\t\"globals.declare 'a'"
print "\t\"globals.declare{'a','b','c'}\" declares globals for use."
print "\t\"globals.reset()\" resets the declarations."
print "\t\"globals.list()\" lists your globals."
end
-----
-- Initialisation
--
if not m._declared then -- first time
m.reset()
--m.help()
end
return m
end )()
m.on()
--foo= 22 -- gotcha!
--
do -- keep support's local stuff up to itself
--
-- SUPPORT.LUA
--
-- Helpful tools and standard library overrides/fixes/extensions..
--
-- AK(14-Oct-2004): Removed LINUX & NETBSD checks (unnecessary, right?)
--
rawset( _G, "WIN32", os.getenv("WINDIR") ~= nil ) -- otherwise Posix
-----
-- void= dump( tbl [,lev] )
--
function dump( tbl, lev )
--
lev= lev or 0
if not tbl then
io.stderr:write "(nil)\n"
return
--
elseif type(tbl)=="table" then
--
local pre, pre2
local items= false
pre= string.rep(" ", lev)
for key,val in tbl do
--
items= true
pre2= pre..key.." : "
if type(val)=='table' then
io.stderr:write( pre2.."table\n" )
if lev >= 0 then -- recurse
dump( val, lev+1 )
end
elseif type(val)=='string' then
io.stderr:write( pre2.."\t'"..val.."'\n" )
else
io.stderr:write( pre2,val..'\n' )
end
end
if not items then
io.stderr:write( pre.."(empty)\n" )
end
else
io.stderr:write( "("..type(tbl)..") ".. tbl..'\n' )
end
end
-- Debugging support: TRACE(true), TRACE(false)
--
-- reason: "call"/"return"/"tail return"/"line"/"count"
--
local function my_callhook( reason ) -- "call"
--
local info= debug.getinfo( 2 )
--
-- .source '@Scripts/globals.lua'
-- .what 'Lua'/'C'/'main'
-- .func function
-- .short_src 'Scripts/globals.lua'
-- .currentline -1
-- .namewhat ''
-- .linedefined 39
-- .nups 2
local name= (info.name) or ""
local str= " -> "..(info.source).." "..(info.linedefined).." "..name
io.stderr:write(str..'\n')
end
function TRACE( on_off )
--
if not on_off then
debug.sethook( nil )
else
debug.sethook( my_callhook, "c" )
--
-- "c": Lua calls a function
-- "r": Lua returns from a function
-- "l": for each line
end
end
-----
-- Credit: Thanks to Jamie Webb for the trick with the '_' arguments.
--
function first(x) return x end
function second(_,x) return x end
function third(_,_,x) return x end
ASSUME( first(1,2,3,4)==1 )
ASSUME( second(1,2,3,4)==2 )
ASSUME( third(1,2,3,4)==3 )
function skip2(_,_, ...) return unpack(arg) end
-----
-- iterator_func= string.lines( str )
-- iterator_func= lines( str/file )
--
-- This allows 'for line in lines(str) do .. end'
-- ..just as standard libs already do with 'io.lines()'
--
ASSUME( not rawget(string,"lines") )
ASSUME( not rawget(_G,"lines") )
string.lines= function(str) return string.gfind(str, "[^\n]+") end
function lines(val) -- str/file
return type(val)=="string" and string.lines(val)
or io.lines(val)
end
--selftest
local tmp=""
for l in lines( "a\nb b\nc c c\n" ) do
--print(l)
tmp= tmp..l..'+'
end
ASSUME( tmp == "a+b b+c c c+" )
-----
-- name_str= TempName( [dir_str [,progid_str]] )
--
local magic1= string.sub( os.time(), -4 ) -- startup time in seconds (last N digits)
local magic2= 0 -- counter
local TMP_PATH= "/tmp/" -- default
if WIN32 then -- get temp dir
--
local s= os.getenv("TEMP") or os.getenv("TMP")
ASSUME( s, "TEMP env.dir not set!" )
TMP_PATH= s..((string.sub(s,-1)~='\\') and '\\' or "")
end
local function Loc_TempName( dir, id )
--
magic2= magic2 + 1 -- times we've called this routine
local fn= TMP_PATH..(id or "temp")..magic1..magic2..".tmp"
-- The file should never already exist:
--
ASSUME( not io.open(fn,"r") )
return fn
end
-----
-- rc_int [,stdout_str, stderr_str] = os.execute( cmd_str [,catch_int] )
--
-- The added 'catch_int' parameter allows transparent catching of stdout
-- and/or stderr output (1=stdout,2=stderr,3=both).
--
local _os_execute= ASSUME( os.execute ) -- original
local function Loc_ReadAllAndDump(fn)
--
local f= io.open(fn,"rt")
if not f then
return nil -- no file, the command did not run..
end
local str= f:read'*a' -- read all
f:close()
os.remove(fn)
-- Remove terminating linefeed (if any) - eases one-liner analysis
--
if string.sub( str,-1 )=='\n' then
str= string.sub( str, 1,-2 )
end
return str
end
function os.execute( cmd, catch, input )
--
if not catch then
return _os_execute(cmd) -- old way
else
local fn0= input and Loc_TempName()
local fn1= (catch==1 or catch==3) and Loc_TempName()
local fn2= (catch>=2) and Loc_TempName()
if fn0 then
local fh = io.open(fn0, "wb")
fh:write(input)
fh:close()
end
local rc= _os_execute( cmd..(fn0 and " <"..fn0 or "")
..(fn1 and " >"..fn1 or "")
..(fn2 and " 2>"..fn2 or "") )
local str0= fn0 and Loc_ReadAllAndDump(fn0)
local str1= fn1 and Loc_ReadAllAndDump(fn1)
local str2= fn2 and Loc_ReadAllAndDump(fn2)
return rc, str1,str2
end
end
--selftest
--
local rc,stdout= os.execute( "echo AAA!", 1 )
-- Win32 seems to put an empty space after an 'echo' string.
--
ASSUME( rc==0 and (stdout=="AAA!" or (WIN32 and stdout=="AAA! ")),
"<"..stdout..">" )
-----
-- [tbl]= table.copy( [tbl [,filter_func] )
-- [tbl]= table.icopy( [tbl [,filter_func] )
--
-- The filter func is fed each item at a time. If it returns 'nil', that
-- item will not be copied further.
--
-- Note: If 'nil's are returned, 'table.copy' leaves holes in the returned
-- table (it doesn't change keys). Use 'icopy' if the indices don't
-- matter (it retains the order, but skips 'nilled' keys).
--
function table.copy( tbl1, filter_func )
--
if not tbl1 then return nil end -- 'nil' pass-through
local tbl2= {}
if not filter_func then -- faster this way
for k,v in tbl1 do tbl2[k]= v end
else
for k,v in tbl1 do
local tmp= filter_func(v)
if tmp~=nil then -- skip if 'nil' (but passes 'false')
tbl2[k]= tmp
end
end
end
return tbl2
end
function table.icopy( tbl1, filter_func )
--
if not tbl1 then return nil end -- 'nil' pass-through
local tbl2= {}
if not filter_func then -- faster this way
for _,v in ipairs(tbl1) do table.insert(tbl2,v) end
else
for _,v in ipairs(tbl1) do
local tmp= filter_func(v)
if tmp~=nil then -- skip if 'nil' (but passes 'false')
table.insert( tbl2, tmp )
end
end
end
return tbl2
end
-----
-- n_uint= table.getn( tbl )
--
-- Problem: If there are 'holes' in a table ('nil' values), the behaviour of 'table.getn'
-- is dependent on Lua version.
--
-- Up until Lua 5.1-w1, 'table.getn()' always returned the FIRST index followed
-- by a 'nil', either before a 'hole' or genuinly at the end of the table.
--
-- With Lua 5.1-w1, 'table.getn()' sometimes does that, sometimes hops over the
-- holes. It returns SOME index followed by a 'nil'.
--
-- Solution:
-- To keep applications ignorant of the underlying Lua version, we enforce the
-- OLD way, unless Lua folks permanently change the way 'table.getn' _should_
-- work with holes.
--
local GETN_51W1= table.getn( {'a','b',[4]='c' } ) == 4 -- true for Lua5.1-w1
if GETN_51W1 then
local _old_getn= table.getn
--
table.getn=
function( tbl )
local n= _old_getn(tbl) -- over the holes (or not..)
for i=1,n do
if tbl[i]==nil then -- allow 'false'
return i-1
end
end
return n
end
end
--
local ab_c= { 'a','b', [4]='c' }
ASSUME( table.getn(ab_c) == 2 )
for i,v in ipairs(ab_c) do
ASSUME( i<=2 )
end
-----
-- switch / case construct
--
-- Credits: Eric Tetz (sent to lua-list 1-Sep-04)
--
-- Usage:
-- switch( action,
-- { DOG_BARK, do print "Arf!!!" end },
-- { DOG_BITE, do print "Chomp!" end },
-- { DOG_SLEEP, do print "Zzzzzz..." end },
-- { nil, do print "Default!" end }
-- )
--
-- Note: The 'key' used may be of any Lua data type.
-- A table key means any of its members will do.
--
ASSUME( (not rawget(_G,"switch") ) )
ASSUME( (not rawget(_G,"case") ) )
ASSUME( (not rawget(_G,"default") ) )
function switch( key, ... )
--
local match= false
for _,item in ipairs(arg) do
--
ASSUME( type(item)=="table" )
if type(item[1])=="table" then -- multiple keys
for _,vv in item[1] do
if vv==key then
match=true; break
end
end
else
if (item[1]==nil) or (item[1]==key) then
match= true
end
end
if match then
local v= item[2]
if type(v)=="function" then
return v()
else
return v -- string or whatever
end
end
end
end
function case( key, v )
return { key, v }
end
function deafult( v )
return { nil, v }
end
end
--
do
--
-- DIRTOOLS.LUA
--
-----
-- bool= FileExists( fn_str )
--
local function Loc_FileExists( fn )
--
local f= io.open(fn,'r')
if f then
f:close()
return true
else
return false
end
end
-----
-- path_str, filename_str [,suffix_str]= PathSplit( path_and_filename [,split_sfx_bool] )
--
local function Loc_PathSplit( str, split_sfx )
--
local path,fn,suffix
if not str then return nil end
_,_,path,fn= string.find( str, "(.*[/\\])(.*)" )
if path then
if fn=="" then fn=nil end
else
path= nil
fn= str -- just filename
end
if split_sfx then
local _,_, s1,s2= string.find( fn, "(.+)%.(.-)$" )
if s2 then
fn= s1
suffix= s2
end
end
return path,fn,suffix
end
-----
-- bool= IsSlashTerminated( str )
-- str= MakeSlashTerminated( str )
--
local function Loc_IsSlashTerminated( str )
--
local c= string.sub( str, -1 )
return ((c=='/') or (c=='\\'))
end
local function Loc_MakeSlashTerminated( str )
--
return Loc_IsSlashTerminated(str) and str or str..'/'
end
-----
-- str= QuoteIfSpaces(str)
--
-- Add quotes so that a file or pathname (with spaces) can be used in OS commands.
--
local function Loc_QuoteIfSpaces( str )
--
return string.find( str, ' ' ) and ('"'..str..'"') or str
end
-----
-- void= ParentDir( dir_name )
--
-- Returns name of the parent or 'nil' for root level.
--
local function Loc_ParentDir( str )
--
local daddy
-- Remove the terminating slash, see if there's any other left:
--
ASSUME( Loc_IsSlashTerminated(str) )
daddy= first( Loc_PathSplit( string.sub( str, 1,-2 ) ) )
if WIN32 and daddy then -- special root detection
if string.find( daddy, ".%:$" ) then
return nil -- just drive name
end
end
return daddy -- 'nil' for root
end
-----
-- bool= DirProbe( dir_name )
--
-- Checks whether we can write to a directory.
--
local function Loc_DirProbe( dirname )
--
ASSUME( Loc_IsSlashTerminated(dirname) )
local fn= dirname.."~probe.tmp"
-- overwrite if file is already there (should be okay)
--
local fh= io.open( fn, "wt" )
if not fh then
return false -- did not exist (or not write access)
end
fh:close()
os.remove( fn )
return true -- dir existed
end
-----
-- void= Mkdir( dir_name )
--
-- Make sure that the target directory exists.
--
local function Loc_Mkdir( dirname )
--
if not dirname then return end -- root met
ASSUME( Loc_IsSlashTerminated(dirname) )
if WIN32 then
dirname= string.gsub( dirname, '/', '\\' )
end
if not Loc_DirProbe( dirname ) then
--
Loc_Mkdir( Loc_ParentDir(dirname) )
local rc= os.execute( "mkdir ".. Loc_QuoteIfSpaces(dirname) )
ASSUME( rc==0, "Unable to create '"..dirname.."'!" )
ASSUME( Loc_DirProbe( dirname ) ) -- should be there now
end
end
-----
-- tbl= Loc_DirCmd( cmd_str )
--
local function Loc_DirCmd( cmd )
--
local rc,str= os.execute( cmd, 1 ) -- catch stdout
if rc~=0 then
return {}
end
local ret= {}
for l in string.gfind(str,"[^\n]+") do
table.insert(ret,l)
end
return ret
end
-----
-- [tbl]= Loc_DirList( dirname [,dirs_only_bool] )
--
-- Returns a list of the contents of a directory (or 'nil' if no such dir exists).
-- Subdirectory entries are marked with a terminating slash ('/').
--
-- Note: For consistancy (and portability of applications) even WIN32
-- paths are returned using forward slashes ('/').
--
local function Loc_DirList( dirname, dirs_only )
--
dirname= dirname and Loc_MakeSlashTerminated(dirname) or ""
if dirname=="./" then dirname= nil end
local ret= {}
if WIN32 then
--
-- "/AD" limits to directories only
-- "/B" causes no headers & footers, just filenames (is it already in Win95?)
--
local lookup= {}
dirname= Loc_QuoteIfSpaces( string.gsub( dirname, '/', '\\' ) )
local tbl= Loc_DirCmd( "dir /AD /B "..dirname ) -- only dirs
-- Add slash to every dir line
--
for i,v in ipairs(tbl) do
table.insert( ret, v..'\\' )
lookup[v]= true
end
if not dirs_only then -- Add non-dirs, too?
--
tbl= Loc_DirCmd( "dir /B "..dirname ) -- dirs & files
for i,v in ipairs(tbl) do
if not lookup[v] then -- not in the dirs table
table.insert( ret, v )
end
end
end
-- Return with forward slashes
--
if true then
for i=1,table.getn(ret) do
ret[i]= string.gsub( ret[i], '\\', '/' )
end
end
--
else -- Linux, OS X, BSD, Win32/MSYS...
--
-- "-1" causes all output in a single column
-- "-F" adds slash after directory names (and some more postfixes that
-- we might need to filter away)
--
ret= table.icopy( Loc_DirCmd( "ls -1 -F ".. Loc_QuoteIfSpaces(dirname) ),
function(v) -- filter
local c= string.sub(v,-1) -- last char
if v=='./' or v=='../' then -- QNX has these
return nil
elseif c=='/' then
return v -- dirs are always welcome :)
elseif dirs_only then
return nil -- skip non-dir entries away
elseif c=='*' then -- executables
return string.sub( v, 1,-2 )
elseif c=='@' then -- symbolic links
return nil
else
return v
end
end )
end
return ret
end
--
local function Loc_LinesToTable( str )
--
local ret= {}
-- "" -> { "" }
-- nil -> {}
--
for l in string.lines(str) do
table.insert( ret, l )
end
return ret
end
-----
-- [bool=] FileIsNewer( fn1_str, fn2_str )
--
-- Returns 'true' if 'fn1' is newer than (has been modified after) 'fn2'.
--
-- Note: While 'ls' does not show file times by the seconds, we can still use its
-- sorting features to see which file is newer (and, well, that's all we want!)
--
local function Loc_FileIsNewer( fn1, fn2 )
--
if WIN32 then
error "Not for Win32, yet!" -- to be done!!
else
-- Filenames only, one per line, youngest first:
--
local cmd= "ls -1 -t "..Loc_QuoteIfSpaces(fn1)..' '..Loc_QuoteIfSpaces(fn2)
local rc,sout= os.execute( cmd, 1 )
ASSUME( rc==0 )
-- Output is one or two lines ('fn2' does not need to exist).
--
local tbl= Loc_LinesToTable( sout )
ASSUME( tbl[1] ) -- should have at least 'fn1'
ASSUME( not tbl[3] ) -- what!?
if tbl[1]==fn1 then
return true -- fn1 was youngest (or only)
else
ASSUME( tbl[1]==fn2 )
ASSUME( tbl[2]==fn1 )
return false -- fn1 was older
end
end
end
-----
-- [md5_str]= MD5( fn_str )
--
-- Return the MD5 checksum for a file.
--
-- Requires: 'md5' program needs to be available (built-in on OS X).
--
local function Loc_MD5( fn )
--
local cmd= "md5 "..Loc_QuoteIfSpaces(fn)
local rc,sout= os.execute( cmd, 1 ) -- catch output
if rc~=0 then
error "Unable to find 'md5' program! (buhuuuuuu....)"
end
--[iMac:~/www.sci.fi] asko% md5 refresh.lua
-- "MD5 (refresh.lua) = e7d6f8e60baa831853d23de6bfd0b477"
--
local str= string.find( sout, "MD5 %(.+%) = (%x+)" )
ASSUME( str, "Bad MD5 output: "..sout )
return str -- tonumber( str, 16 )
end
-----
-- void= CreateFile( fn_str, contents_str [,chmod_str] )
--
local function Loc_CreateFile( fn, str )
--
local fh= io.open( fn, "wt" )
ASSUME( fh, "Unable to create '"..fn.."'!" )
fh:write( str )
fh:close()
end
-----
-- [str]= ReadFile( fn_str )
--
local function Loc_ReadFile( fn )
--
local f= io.open( fn, "rt" )
if f then
local str= f:read'*a' -- all
f:close()
return str
end
return nil
end
-- Declare these as global so they may be used by filters, too:
--
FileExists= assert( Loc_FileExists )
PathSplit= assert( Loc_PathSplit )
CreateFile= assert( Loc_CreateFile )
ReadFile= assert( Loc_ReadFile )
Mkdir= assert( Loc_Mkdir )
PathOnly= function(str) return first( PathSplit(str) ) end
FilenameOnly= function(str) return second( PathSplit(str) ) end
--...
end
-----===== MAIN PART =====-----
--
-----
-- str= Loc_SkipWhitespace(str)
--
local function Loc_SkipWhitespace(str)
--
if not str then return nil end
return string.gsub( str, "^%s+", "" ) -- that's it!
end
ASSUME( Loc_SkipWhitespace("abc") == "abc" )
ASSUME( Loc_SkipWhitespace(" abc") == "abc" )
ASSUME( Loc_SkipWhitespace(" ") == "" )
-----
-- Use this when lhtml source has problems (shows file & line to the user)
--
-- Note: Also filter funcs can (and should) use it!
--
local current_line, current_file
function SYNTAX_ERROR( str, line, fname )
--
error( "\n\n*** ERROR in '"..( (fname or current_file) or "??")..
"' line "..( (line or current_line) or "??")..
": ".. str.."\n" )
end
-----
-- word_str [,tail_str]= Loc_WordSplit(str)
--
-- Cuts a string into first word, either at white space or '='.
--
local function Loc_WordSplit( str )
--
local head,sep,tail
if string.sub(str,1,1)=='"' then -- "many words"
--
local n=2
while true do
local c= string.sub(str,n,n)
if c=='\\' then
n= n+2 -- jump over next (i.e. '\"')
elseif c=='"' then
break
elseif c then
n= n+1
else
SYNTAX_ERROR( "Quote mismatch!", current_line, current_file )
end
end
head= string.gsub( string.sub(str,2,n-1), "\\\"", '"' )
-- skip 'n' (it's the double hyphen)
tail= Loc_SkipWhitespace( string.sub(str,n+1) )
else
head,sep,tail= skip2( string.find( str, "(.-)%s*([%s=])%s*(.+)" ) )
if not head then
head,tail= str,nil -- no spaces
--
elseif sep=='=' then
tail= sep..tail -- white space removed, but keep the '='
end
end
if tail=="" then tail=nil end
if tail then
ASSUME( not string.find( tail, "^%s" ) ) -- all white space eaten?
end
return head,tail
end
-----
-- tag_str, params_tbl= Loc_ParseTag( tag_and_params_str )
--
local function Loc_ParseTag( str )
--
local params= {}
local tag,tail= Loc_WordSplit( str )
while tail do -- "param1[=val2] [...]"
--
local key,tail2= Loc_WordSplit( tail )
local val
if not tail2 then -- just the "param"
val= true
tail= nil
--
elseif string.sub(tail2,1,1)=='=' then -- "param=..."
--
val,tail= Loc_WordSplit( Loc_SkipWhitespace( string.sub(tail2,2) ) )
if val=="true" or val=="yes" then
val= true
elseif val=="false" or val=="no" then
val= false
elseif tonumber(val) then -- numeric?
val= tonumber(val)
end
else -- "param1 param2.."
val= true
tail= tail2
end
params[key]= val
end
return tag,params
end
-----
-- start_n, stop_n=
--
local function Loc_NextComment( str )
--
local n1,n2= string.find( str, "<!%-%-.-%-%->" )
if n1 then
return n1, n2 -- first and last index of comment
else
return nil -- no comment found
end
end
-----
-- head,tag,tail=
--
local function Loc_NextFuncTag( str )
--
local head,tag,tail= skip2( string.find( str, "(.-)<(@.-)>(.*)" ) )
if head then
-- Do we have a comment starting before?
--
local n,m= Loc_NextComment( str )
if n and (n < string.len(head)) then
head,tag,tail= Loc_NextFuncTag( string.sub( str,m+1 ) )
if head then -- functional tag after the comment
return string.sub( str,1,m )..head, tag, tail
end
else
return head,tag,tail
end
end
return nil -- no function tag
end
-----
-- str= Loc_ApplyFunctions_str( str )
--
-- Expands Lumikki tags (<@...>) within a given string.
--
local function Loc_ApplyFunctions_str( str )
--
ASSUME(str)
local head,tag,tail= Loc_NextFuncTag( str )
local text,params
if not head then
return str -- no function tags
else
tag, params= Loc_ParseTag( tag ) -- params into a table
-- Is there a terminating tag?
--
-- Note: Regular tags are allowed within the block but <@..> tags are not.
--
local head2,tag2,tail2= skip2( string.find( tail, "(.-)<(/?@.-)>(.*)" ) )
if tag2 and ( string.lower(tag2) == "/"..string.lower(tag) or
tag2=="/@" ) then -- terminator found
text= head2
tail= tail2
else
text= nil -- no terminating tag
-- tail=tail
end
end
if tail=="" then tail=nil end
-- We know the 'head', we know the function, we know the 'tail'
--
local tmp= string.sub(tag,2)
local func= rawget( _G, tmp ) or
rawget( _G, string.lower(tmp) ) or
rawget( _G, string.upper(tmp) ) or
error( "No function for tag: <"..tag..">" )
local str, expand= func( params, text )
ASSUME( str, "Function "..tag.." returned nil! (must return string)" )
-- Recursive use of <@...> tags (if necessary)
--
if expand then
str= Loc_ApplyFunctions_str( str )
end
if tail then
tail= Loc_ApplyFunctions_str( tail )
end
return head..str..(tail or "")
end
-----
-- html_tbl= Loc_ApplyFunctions( html_tbl, fname_str )
--
-- Expands Lumikki tags (<@...>) within the given HTML table (from 'deHTML()').
--
local function Loc_ApplyFunctions( tbl, fname )
--
local ret= {}
current_file= fname
for i=1,table.getn(tbl) do
--
local item= tbl[i]
if string.sub( item[1],1,2 ) == "<@" then
--
current_line= item.line
table.insert( ret, { Loc_ApplyFunctions_str( item[1] ), line=item.line } )
else
table.insert( ret, item )
end
end
ret.file= tbl.file
return ret
end
-----
-- tbl= deHTML( html_str [,filename_str] )
--
-- Returns the exact HTML contents (linefeeds etc. all preserved), split by tags,
-- comments etc. to ease handling & modification later on.
--
-- Filename and line numbers are included to help debugging (giving better error
-- messages to the user).
--
-- Note: The filename provided is merely for error message's sake.
--
function deHTML( html, fname )
--
local ret= {} -- { { str, line=int }, ... , file=str }
local n1= 1
local line=1
local busy= true
while busy do
--
local tmp= string.sub( html,n1,n1+3 )
local _,n2, catch
if tmp=="<!--" then -- "<!--...-->"
--
_,n2,catch= string.find( html, "(.-%-%->)", n1 ) -- start at n1
if not catch then
SYNTAX_ERROR( "comment not closed!", line, fn )
end
--
elseif string.sub(tmp,1,2)=="<@" then -- "<@func ...>[...</@[func]>]"
--
_,n2,catch= string.find( html, "(.->)", n1 ) -- tag itself + params
if not catch then
SYNTAX_ERROR( "tag left open!", line, fn )
end
local tag= third( string.find( catch, "<(.-)[%s>]" ) )
ASSUME( tag )
-- Find next '<@' tag or terminating '</@' tag:
-- (text may contain HTML formatting, but not another '<@' tag)
--
local __,n3,mid,endtag= string.find( html, "(.-)(</?@.->)", n2+1 )
if endtag=="</"..tag..">" or endtag=="</@>" then
--
--[[
if string.find( mid, "<!%-%-" ) then
-- we could actually allow this, but.. is it needed?
-- what if the terminating tag is within that comment, then?
--
SYNTAX_ERROR( "comments within <@func> block!", line, fname ) -- banned.
end
]]--
catch= catch..mid..endtag -- all the way to the terminating tag :)
n2= n3
end
--
elseif string.sub(tmp,1,1)=="<" then -- "<...>"
--
_,n2,catch= string.find( html, "(.->)", n1 )
if not catch then
SYNTAX_ERROR( "tag left open!", line, fn )
end
else
_,n2,catch= string.find( html, "(.-)<", n1 )
if not catch then
catch= string.sub( html, n1 )
busy= false -- done!
else
n2= n2-1 -- not the '<'
end
end
table.insert( ret, { catch, line=line } )
-- Count number of newlines within 'catch'
--
for _ in string.gfind( catch, '\n' ) do
line= line+1
end
if n2 then n1= n2+1 end
end
ret.file= fname
return ret
end
-----
-- str= OutputHTML( html_tbl )
--
function OutputHTML( tbl )
--
-- Cannot use 'table.concat' directly, since the strings are in subtables.
-- Expecting it to be faster than just 'str= str..' a zillion times?
--
local tbl2= {}
for _,v in ipairs(tbl) do
table.insert( tbl2, v[1] )
end
return table.concat( tbl2 )
end
--
local m= ( function()
--
-- PUTZ.LUA
--
-----
-- str= Loc_Footer()
--
ASSUME( Loc_ApplyFunctions_str )
local function Loc_Footer()
--
local str= "\n<hr><p align=center><font size=\"-3\">This page was created by "..
"<@LINK popup url=www.sci.fi/~abisoft/lumikki/>Lumikki</@LINK>"..
"</p>\n"
return Loc_ApplyFunctions_str( str, true )
end
-----
-- -1/0/+1= Loc_CommentCount( str, start_str, end_str )
--
-- Returns: 0 if comments/pre blocks are balanced (none, or both <!-- and -->)
-- -1 if more stop than start
-- +1 if more start than stop
--
local function Loc_CommentCount( str, pat1, pat2 )
--
local _,started= string.gsub( str, pat1, "" )
local _,ended= string.gsub( str, pat2, "" )
local n= started - ended
if n<-1 or n>1 then
SYNTAX_ERROR( "Recursive comments found!" )
end
return n
end
-----
-- bool= Loc_NoPtag( str )
--
-- Returns 'true' when the given paragraph seems to be missing the <p> tag.
--
local lookup_noptag= { img=1, i=1, b=1, u=1, } -- tags considered as 'plain text' starter
local lookup_skip= { font=1, hr=1 } -- tags that need to be skipped to know
local function Loc_NoPtag( str )
--
local tag= third( string.find( str, "^%s-<(.-)[%s>]" ) ) -- get the first tag
if not tag then
if string.find( str, "%S" ) then -- any non-whitespace, huhuu..=?
return true -- plain text
else
return false -- just white space *spit*
end
--
elseif string.sub(tag,1,3)=="!--" then -- starts with a comment (skip it)
--
local tail= skip2( string.find( str, "<!%-%-.-%-%->(.+)" ) )
if not tail then -- no end for comment
return false
else
return Loc_NoPtag( tail )
end
else
local tag_low= string.lower(tag)
if lookup_skip[ tag_low ] then -- skip that tag..
--
local tail= third( string.find( str, "<.->%s*(.+)" ) ) -- skip one tag
if tail then
return Loc_NoPtag( tail )
end
--
elseif lookup_noptag[ tag_low ] then
return true -- starting by '<img' etc.. (needs <p>)
end
end
return false -- I guess we're allright?
end
-----
-- [str]= Loc_ConvertListParagraph( str )
--
-- Converts a set of '- entry' lines to '<ul><li>...</ul>' format, or returns 'nil'.
--
local function Loc_ConvertListParagraph( str )
--
local ret= nil
-- valid <UL> types are: "disc"/"circle"/"square"/...
--
local lookup= { ['-']='', ['+']='+', ['o']='circle', ['*']='disc', ['#']='square' }
for s in lines(str) do
--
local bullet,tail= skip2( string.find( s, "^%s*([-+o*#])%s+(.+)" ) )
if not bullet then
return nil -- some line wasn't a bullet!
end
if not ret then
ret= (bullet=='') and "<ul>\n" -- normal
or "<ul type=\""..lookup[bullet].."\">\n"
end
ret= ret.." <li>"..tail.."</li>\n"
end
if ret then
return ret.."</ul>" -- all lines were list
else
return nil
end
end
-----
-- str= Loc_PutzFilter( str )
--
-- Handles HTML code, filling in lazy-coder's gaps s.a. no '<html>' tag, no '<p>',
-- plain text list producing (+/-/o) etc.
--
-- This is definately a hack area :) and is secondary to Lumikki in a way (you can
-- use the rest of the system well without this).
--
local within_comment, within_pre
local body_closed, html_closed
local putzed -- table to collect lines (needs to be accessible to 'Loc_Paragraph()')
local function Loc_Paragraph( s )
--
local comment_count= Loc_CommentCount(s,"<!%-%-","%-%->")
local pre_count= Loc_CommentCount( s, "<[Pp][Rr][Ee][%s>]", "</[Pp][Rr][Ee][%s>]" )
local postfix
-- Going state-crazy here.. hang on!
--
if within_comment then
if comment_count < 0 then
within_comment= false -- no longer within a comment at end of this paragraph
end
elseif within_pre then
if pre_count < 0 then
within_pre= false -- no longer within <PRE> block at end of this paragraph
end
else
local tmp= Loc_ConvertListParagraph(s)
if tmp then -- was a list! (merge with previous paragraph)
--
local last= table.getn(putzed) -- that's the whitespace
table.insert( putzed, last, "\n"..tmp ) -- before the whitespace (& </p>)
-- clean away unnecessary white space
--
--io.stderr:write( "<<<<"..putzed[last+1]..">>>>\n" )
putzed[last+1]= string.gsub( putzed[last+1], "%s+$", "" )
s= nil -- none from us, now
--
else
if Loc_NoPtag( s ) then -- need to insert <p> ?
s= "<p>"..s
end
if comment_count>0 then
within_comment= true
end
if pre_count>0 then
within_pre= true
end
end
ASSUME( not (within_comment and within_pre) ) -- not prepared for that
-- Check if we need to add a </p> after the paragraph:
--
if s and (not within_comment) and (not within_pre) then
--
if string.find( s, "^<[Pp][%s>]" ) and -- must be at the beginning
(not string.find( s, "</[Pp][%s>]" )) then
--
postfix= "\n</p>" -- most likely, we do..
end
end
end
-- More effective to store the pieces in a table, then 'table.concat'
-- (than do concat explicitly here all time)
--
if s then
if string.find( s, "</[Bb][Oo][Dd][Yy][%s>]" ) then
s= Loc_Footer()..s -- before the </body> block
body_closed= true
end
if body_closed and string.find( s, "</[Hh][Tt][Mm][Ll][%s>]" ) then
html_closed= true
end
end
return s, postfix
end
-----
-- iterator factory that returns a function.
--
local function Loc_ParagraphIterator( str )
--
local pos= 1
return
-- str1: non-whitespace paragraph text
-- str2: whitespace (min. two newlines)
--
function()
--
if not pos then return nil end -- done already
-- works even with >2 linefeeds! (also linefeed is %s :)
--
local _,_, part1,part2, pos2= string.find( str, "(.-)(\n%s*\n)()", pos )
if not part1 then -- end of string: rest is last
--
_,_, part1,part2, pos2= string.find( str, "(.+)(%s*)", pos )
pos= nil -- done
else
pos= pos2 -- continue from here..
end
return part1,part2
end
end
--
local function Loc_PutzFilter( str )
--
local prefix= ""
local postfix= nil
putzed= {}
-- Add <html> and <head> if not there:
--
if not string.find( str, "<[Hh][Tt][Mm][Ll][%s>]" ) then
prefix= "<html>"
postfix= "</html>"
end
if not string.find( str, "<[Hh][Ee][Aa][Dd][%s>]" ) then
prefix= prefix.."<head></head>"
end
if not string.find( str, "<[Bb][Oo][Dd][Yy][%s>]" ) then
prefix= prefix.."<body>"
postfix= "</body>"..(postfix or "")
end
if prefix~="" then
str= prefix.."\n\n"..str..(postfix and "\n\n"..postfix or "")
end
-- Process data paragraph-wise
--
for part1,part2 in Loc_ParagraphIterator(str) do -- custom iterator, isn't Lua just great! :)
--
--local tmp= string.gsub( part2, '\n', '@' )
--io.stderr:write( "<<<<<<\n"..part1.."-----"..tmp..">>>>>>\n" )
local s, postfix= Loc_Paragraph( part1 )
if s then
-- Special case: remove newline immediately after <pre> (makes block writes easier).
--
-- Note: this is the ONLY place where original HTML meaning is tampered with.
--
s= string.gsub( s, "(<[Pp][Rr][Ee]>)%s*\n", "%1" ) -- leave out the '\n'
-- Modify '&' -> '&' if alone.
--
s= string.gsub( s, "&%s", "& " )
s= string.gsub( s, " < ", "< " )
s= string.gsub( s, " > ", "> " )
-- "*bold*" and "_underlined_"?
--
s= string.gsub( s, "(%s)*(%S+)*([%p%s])", "%1<b>%2</b>%3" )
s= string.gsub( s, "(%s)_(%S+)_([%p%s])", "%1<u>%2</u>%3" )
-- Modify etc. (so I can type them directly on a Mac ;P
--
-- Note: This should really be codepage based; now it's a hack
-- that works on specific systems (mainly, mine ;) but
-- not in a general way.
--
local repl
if WIN32 then -- Codepage 850(?)
repl= { ['å']="å", ['Å']="Å",
['ä']="ä", ['Ä']="Ä",
['ö']="ö", ['Ö']="Ö",
['ü']="ü", ['Ü']="Ü",
--
['á']="á", ['à']="à",
--...
}
else -- OS X / Finnish
repl= { ['']="å", ['']="Å",
['']="ä", ['']="Ä",
['']="ö", ['
']="Ö",
['']="ü", ['']="Ü",
--
['']="ñ", ['']="Ñ",
['']="á", ['']="à", ['']="â",
['']="é", ['']="è", ['']="ê",
['']="í", ['']="ì", ['']="î",
--
['Û']="€", -- "€"
['©']="©",
['¨']="®",
--...
}
end
for k,v in repl do
s= string.gsub( s, k, v )
end
table.insert( putzed, s )
end
table.insert( putzed, (postfix or "")..part2 ) -- whitespace (and </p>)
end
-- Make sure there's a footer & </body> and </html> tags
--
if not body_closed then
table.insert( putzed, Loc_Footer() )
table.insert( putzed, "\n</body>\n" ..((not html_closed) and "</html>\n" or "") )
end
return table.concat( putzed )
end
--
return {
PutzFilter= ASSUME( Loc_PutzFilter )
}
end )()
local PutzFilter= assert( m.PutzFilter )
-----
-- str= CurrentDir()
-- str= CurrentFile()
--
-- Filter functions can use this to query the currently processed file's directory.
--
function CurrentDir()
--
if current_file then
return PathOnly(current_file) or ""
else
return "" -- stdin
end
end
function CurrentFile()
return current_file
end
--== Command line usage ==--
local ABOUT=
"\n** Lumikki website generator (rel.".. mymod._info.RELEASE .."), ".. mymod._info.COPYRIGHT ..
"\n"
local HELP= [[
lua lumikki.lua input.lhtml [...] >output.htm
lua lumikki.lua dirname/.
]]
local input= {}
local help= false
local logo= true
for _,v in ipairs(arg) do
--
switch( v,
{ "help", function() help=true end },
{ "nologo", function() logo=false end },
--
{ nil, function() table.insert( input, v ) end } -- default
)
end
if logo then
io.stderr:write( ABOUT.."\n" ) -- copyright text
end
if help then
io.stderr:write( HELP.."\n" )
end
if not input[1] then
-- No args = loaded to be used as a library.
--
return mymod
else
ASSUME( not input[2] ) -- just one argument
local fn= input[1]
--
local str= ASSUME( ReadFile(fn), "File not found: "..fn )
local tbl= deHTML( str ) -- all tagwise split, functions expanded
tbl= Loc_ApplyFunctions( tbl, fn ) -- do all '<@func's>'
local str= OutputHTML( tbl ) -- to string domain
str= PutzFilter( str ) -- awful, nasty lazy writer checks & fixes (adding '<p>' etc.)
io.write(str)
end
--
return mymod
| gpl-2.0 |
TimVonsee/hammerspoon | extensions/applescript/init.lua | 13 | 2635 | --- === hs.applescript ===
---
--- Execute AppleScript code
---
--- This module is based primarily on code from the previous incarnation of Mjolnir by [Steven Degutis](https://github.com/sdegutis/).
local module = require("hs.applescript.internal")
-- private variables and methods -----------------------------------------
local split = function(div,str)
if (div=='') then return { str } end
local pos,arr = 0,{}
for st,sp in function() return string.find(str,div,pos) end do
table.insert(arr,string.sub(str,pos,st-1))
pos = sp + 1
end
if string.sub(str,pos) ~= "" then
table.insert(arr,string.sub(str,pos))
end
return arr
end
-- Public interface ------------------------------------------------------
--- hs.applescript.applescript(string) -> bool, result
--- Function
--- Runs AppleScript code
---
--- Parameters:
--- * string - Some AppleScript code to execute
---
--- Returns:
--- * A boolean value indicating whether the code succeeded or not
--- * If the code succeeded, the output of the code string. If the code failed, a table containing an error dictionary
---
--- Notes:
--- * Use hs.applescript._applescript(string) if you always want the result as a string, even when a failure occurs.
module.applescript = function(command)
local ok, result = module._applescript(command)
local answer
if not ok then
result = result:match("^{\n(.*)}$")
answer = {}
local lines = split(";\n", result)
for _, line in ipairs(lines) do
local k, v = line:match('^%s*(%w+)%s=%s(.*)$')
v = v:match('^"(.*)"$') or v:match("^'(.*)'$") or v
answer[k] = tonumber(v) or v
end
else
result = result:match("^<NSAppleEventDescriptor: (.*)>$")
if tonumber(result) then
answer = tonumber(result)
elseif result:match("^'utxt'%(.*%)$") then
result = result:match("^'utxt'%((.*)%)$")
answer = result:match('^"(.*)"$') or result:match("^'(.*)'$") or result
else
answer = result
end
end
return ok, answer
end
setmetatable(module, { __call = function(_, ...) return module.applescript(...) end })
-- Return Module Object --------------------------------------------------
return module
-- collection of return types I need to catch, and then maybe time to recursively parse through 'obj' results
--
-- > hs.applescript("")
-- true null()
-- > hs.applescript("return true")
-- true 'true'("true")
-- > hs.applescript("return false")
-- true 'fals'("false")
-- > hs.applescript("return null")
-- true 'null'
| mit |
Olivine-Labs/luassert | src/formatters/init.lua | 1 | 6658 | -- module will not return anything, only register formatters with the main assert engine
local assert = require('luassert.assert')
local match = require('luassert.match')
local util = require('luassert.util')
local isatty, colors do
local ok, term = pcall(require, 'term')
isatty = io.type(io.stdout) == 'file' and ok and term.isatty(io.stdout)
if not isatty then
local isWindows = package.config:sub(1,1) == '\\'
if isWindows and os.getenv("ANSICON") then
isatty = true
end
end
colors = setmetatable({
none = function(c) return c end
},{ __index = function(self, key)
return function(c)
for token in key:gmatch("[^%.]+") do
c = term.colors[token](c)
end
return c
end
end
})
end
local function fmt_string(arg)
if type(arg) == "string" then
return string.format("(string) '%s'", arg)
end
end
-- A version of tostring which formats numbers more precisely.
local function tostr(arg)
if type(arg) ~= "number" then
return tostring(arg)
end
if arg ~= arg then
return "NaN"
elseif arg == 1/0 then
return "Inf"
elseif arg == -1/0 then
return "-Inf"
end
local str = string.format("%.20g", arg)
if math.type and math.type(arg) == "float" and not str:find("[%.,]") then
-- Number is a float but looks like an integer.
-- Insert ".0" after first run of digits.
str = str:gsub("%d+", "%0.0", 1)
end
return str
end
local function fmt_number(arg)
if type(arg) == "number" then
return string.format("(number) %s", tostr(arg))
end
end
local function fmt_boolean(arg)
if type(arg) == "boolean" then
return string.format("(boolean) %s", tostring(arg))
end
end
local function fmt_nil(arg)
if type(arg) == "nil" then
return "(nil)"
end
end
local type_priorities = {
number = 1,
boolean = 2,
string = 3,
table = 4,
["function"] = 5,
userdata = 6,
thread = 7
}
local function is_in_array_part(key, length)
return type(key) == "number" and 1 <= key and key <= length and math.floor(key) == key
end
local function get_sorted_keys(t)
local keys = {}
local nkeys = 0
for key in pairs(t) do
nkeys = nkeys + 1
keys[nkeys] = key
end
local length = #t
local function key_comparator(key1, key2)
local type1, type2 = type(key1), type(key2)
local priority1 = is_in_array_part(key1, length) and 0 or type_priorities[type1] or 8
local priority2 = is_in_array_part(key2, length) and 0 or type_priorities[type2] or 8
if priority1 == priority2 then
if type1 == "string" or type1 == "number" then
return key1 < key2
elseif type1 == "boolean" then
return key1 -- put true before false
end
else
return priority1 < priority2
end
end
table.sort(keys, key_comparator)
return keys, nkeys
end
local function fmt_table(arg, fmtargs)
if type(arg) ~= "table" then
return
end
local tmax = assert:get_parameter("TableFormatLevel")
local showrec = assert:get_parameter("TableFormatShowRecursion")
local errchar = assert:get_parameter("TableErrorHighlightCharacter") or ""
local errcolor = assert:get_parameter("TableErrorHighlightColor")
local crumbs = fmtargs and fmtargs.crumbs or {}
local cache = {}
local type_desc
if getmetatable(arg) == nil then
type_desc = "(" .. tostring(arg) .. ") "
elseif not pcall(setmetatable, arg, getmetatable(arg)) then
-- cannot set same metatable, so it is protected, skip id
type_desc = "(table) "
else
-- unprotected metatable, temporary remove the mt
local mt = getmetatable(arg)
setmetatable(arg, nil)
type_desc = "(" .. tostring(arg) .. ") "
setmetatable(arg, mt)
end
local function ft(t, l, with_crumbs)
if showrec and cache[t] and cache[t] > 0 then
return "{ ... recursive }"
end
if next(t) == nil then
return "{ }"
end
if l > tmax and tmax >= 0 then
return "{ ... more }"
end
local result = "{"
local keys, nkeys = get_sorted_keys(t)
cache[t] = (cache[t] or 0) + 1
local crumb = crumbs[#crumbs - l + 1]
for i = 1, nkeys do
local k = keys[i]
local v = t[k]
local use_crumbs = with_crumbs and k == crumb
if type(v) == "table" then
v = ft(v, l + 1, use_crumbs)
elseif type(v) == "string" then
v = "'"..v.."'"
end
local ch = use_crumbs and errchar or ""
local indent = string.rep(" ",l * 2 - ch:len())
local mark = (ch:len() == 0 and "" or colors[errcolor](ch))
result = result .. string.format("\n%s%s[%s] = %s", indent, mark, tostr(k), tostr(v))
end
cache[t] = cache[t] - 1
return result .. " }"
end
return type_desc .. ft(arg, 1, true)
end
local function fmt_function(arg)
if type(arg) == "function" then
local debug_info = debug.getinfo(arg)
return string.format("%s @ line %s in %s", tostring(arg), tostring(debug_info.linedefined), tostring(debug_info.source))
end
end
local function fmt_userdata(arg)
if type(arg) == "userdata" then
return string.format("(userdata) '%s'", tostring(arg))
end
end
local function fmt_thread(arg)
if type(arg) == "thread" then
return string.format("(thread) '%s'", tostring(arg))
end
end
local function fmt_matcher(arg)
if not match.is_matcher(arg) then
return
end
local not_inverted = {
[true] = "is.",
[false] = "no.",
}
local args = {}
for idx = 1, arg.arguments.n do
table.insert(args, assert:format({ arg.arguments[idx], n = 1, })[1])
end
return string.format("(matcher) %s%s(%s)",
not_inverted[arg.mod],
tostring(arg.name),
table.concat(args, ", "))
end
local function fmt_arglist(arglist)
if not util.is_arglist(arglist) then
return
end
local formatted_vals = {}
for idx = 1, arglist.n do
table.insert(formatted_vals, assert:format({ arglist[idx], n = 1, })[1])
end
return "(values list) (" .. table.concat(formatted_vals, ", ") .. ")"
end
assert:add_formatter(fmt_string)
assert:add_formatter(fmt_number)
assert:add_formatter(fmt_boolean)
assert:add_formatter(fmt_nil)
assert:add_formatter(fmt_table)
assert:add_formatter(fmt_function)
assert:add_formatter(fmt_userdata)
assert:add_formatter(fmt_thread)
assert:add_formatter(fmt_matcher)
assert:add_formatter(fmt_arglist)
-- Set default table display depth for table formatter
assert:set_parameter("TableFormatLevel", 3)
assert:set_parameter("TableFormatShowRecursion", false)
assert:set_parameter("TableErrorHighlightCharacter", "*")
assert:set_parameter("TableErrorHighlightColor", isatty and "red" or "none")
| mit |
s0ph05/awesome | BatteryWidget/battery.lua | 1 | 1818 | local wibox = require("wibox")
local awful = require("awful")
local naughty = require("naughty")
function showBatteryWidgetPopup()
local save_offset = offset
naughty.notify({
text = awful.util.pread("acpi | cut -d, -f 2,3"),
title = "Battery status",
timeout = 5, hover_timeout = 0.5,
width = 160,
})
end
function showWarningWidgetPopup()
local charge = tonumber(awful.util.pread("acpi | cut -d, -f 2 | egrep -o '[0-9]{1,3}'"))
if (charge < 15) then
naughty.notify({
text = "Houston, we have a problem",
title = "Battery dying",
timeout = 5, hover_timeout = 0.5,
position = "bottom_right",
bg = "#ff1122",
width = 160,
})
end
end
function showBatteryWidgetIcon()
local charge = tonumber(awful.util.pread("acpi | cut -d, -f 2 | egrep -o '[0-9]{1,3}'"))
local batteryType
if (charge >= 0 and charge < 20) then batteryType=20
elseif (charge >= 20 and charge < 40) then batteryType=40
elseif (charge >= 40 and charge < 60) then batteryType=60
elseif (charge >= 60 and charge < 80) then batteryType=80
elseif (charge >= 80 and charge <= 100) then batteryType=100
end
batteryIcon:set_image("/home/sophos/.config/awesome/battery_icons/" .. batteryType .. ".png")
end
batteryIcon = wibox.widget.imagebox()
showBatteryWidgetIcon()
batteryIcon:connect_signal("mouse::enter", function() showBatteryWidgetPopup() end)
-- timer to refresh battery icon
batteryWidgetTimer = timer({ timeout = 5 })
batteryWidgetTimer:connect_signal("timeout", function() showBatteryWidgetIcon() end)
batteryWidgetTimer:start()
-- timer to refresh battery warning
batteryWarningTimer = timer({ timeout = 50 })
batteryWarningTimer:connect_signal("timeout", function() showWarningWidgetPopup() end)
batteryWarningTimer:start()
| mit |
nyov/luakit | lib/lousy/widget/menu.lua | 8 | 8385 | -------------------------------------------------------------
-- @author Mason Larobina <mason.larobina@gmail.com> --
-- @copyright 2010 Mason Larobina --
-------------------------------------------------------------
-- Grab environment we need
local capi = { widget = widget }
local setmetatable = setmetatable
local math = require "math"
local signal = require "lousy.signal"
local type = type
local assert = assert
local ipairs = ipairs
local table = table
local util = require "lousy.util"
local get_theme = require("lousy.theme").get
module "lousy.widget.menu"
local data = setmetatable({}, { __mode = "k" })
function update(menu)
assert(data[menu] and type(menu.widget) == "widget", "invalid menu widget")
-- Get private menu widget data
local d = data[menu]
-- Get theme table
local theme = get_theme()
local fg, bg, font = theme.menu_fg, theme.menu_bg, theme.menu_font
local sfg, sbg = theme.menu_selected_fg, theme.menu_selected_bg
-- Hide widget while re-drawing
menu.widget:hide()
-- Build & populate rows
for i = 1, math.max(d.max_rows, #(d.table)) do
-- Get row
local index = i + d.offset - 1
local row = (i <= d.max_rows) and d.rows[index]
-- Get row widget table
local rw = d.table[i]
-- Make new row
if row and not rw then
-- Row widget struct
rw = {
ebox = capi.widget{type = "eventbox"},
hbox = capi.widget{type = "hbox"},
cols = {},
}
rw.ebox.child = rw.hbox
d.table[i] = rw
-- Add to main vbox
menu.widget:pack(rw.ebox)
-- Remove row
elseif not row and rw then
-- Destroy row columns (label widgets)
for _, l in ipairs(rw.cols) do
rw.hbox:remove(l)
l:destroy()
end
rw.ebox:remove(rw.hbox)
rw.hbox:destroy()
menu.widget:remove(rw.ebox)
rw.ebox:destroy()
d.table[i] = nil
end
-- Populate columns
if row and rw then
-- Match up row data with row widget (for callbacks)
rw.data = row
-- Try to find last off-screen title row and replace with current
if i == 1 and not row.title and d.offset > 1 then
local j = d.offset - 1
while j > 0 do
local r = d.rows[j]
-- Only check rows with same number of columns
if r.ncols ~= row.ncols then break end
-- Check if title row
if r.title then
row, index = r, j
break
end
j = j - 1
end
end
-- Is this the selected row?
selected = not row.title and index == d.cursor
-- Set row bg
local rbg
if row.title then
rbg = (row.bg or theme.menu_title_bg) or bg
else
rbg = (selected and (row.selected_bg or sbg)) or row.bg or bg
end
if rw.ebox.bg ~= rbg then rw.ebox.bg = rbg end
for c = 1, math.max(row.ncols, #(rw.cols)) do
-- Get column text
local text = row[c]
text = (type(text) == "function" and text(row)) or text
-- Get table cell
local cell = rw.cols[c]
-- Make new row column widget
if text and not cell then
cell = capi.widget{type = "label"}
rw.hbox:pack(cell, { expand = true, fill = true })
rw.cols[c] = cell
cell.font = font
cell.width = 1
-- Remove row column widget
elseif not text and cell then
rw.hbox:remove(cell)
rw.cols[c] = nil
cell:destroy()
end
-- Set cell props
if text and cell and row.title then
cell.text = text
local fg = row.fg or (c == 1 and theme.menu_primary_title_fg or theme.menu_secondary_title_fg) or fg
if cell.fg ~= fg then cell.fg = fg end
elseif text and cell then
cell.text = text
local fg = (selected and (row.selected_fg or sfg)) or row.fg or fg
if cell.fg ~= fg then cell.fg = fg end
end
end
end
end
-- Show widget
menu.widget:show()
end
function build(menu, rows)
assert(data[menu] and type(menu.widget) == "widget", "invalid menu widget")
-- Get private menu widget data
local d = data[menu]
-- Check rows
for i, row in ipairs(rows) do
assert(type(row) == "table", "invalid row in rows table")
assert(#row >= 1, "empty row")
row.ncols = #row
end
d.rows = rows
d.nrows = #rows
-- Initial positions
d.cursor = 0
d.offset = 1
update(menu)
end
local function calc_offset(menu)
local d = data[menu]
if d.cursor < 1 then
return
elseif d.cursor <= d.offset then
d.offset = math.max(d.cursor - 1, 1)
elseif d.cursor > (d.offset + d.max_rows - 1) then
d.offset = math.max(d.cursor - d.max_rows + 1, 1)
end
end
function move_up(menu)
assert(data[menu] and type(menu.widget) == "widget", "invalid menu widget")
-- Get private menu widget data
local d = data[menu]
-- Move cursor
if not d.cursor or d.cursor < 1 then
d.cursor = d.nrows
else
d.cursor = d.cursor - 1
end
-- Get next non-title row (you can't select titles)
while d.cursor > 0 and d.cursor <= d.nrows and d.rows[d.cursor].title do
d.cursor = d.cursor - 1
end
calc_offset(menu)
update(menu)
-- Emit changed signals
menu:emit_signal("changed", menu:get())
end
function move_down(menu)
assert(data[menu] and type(menu.widget) == "widget", "invalid menu widget")
-- Get private menu widget data
local d = data[menu]
-- Move cursor
if d.cursor == d.nrows then
d.cursor = 0
else
d.cursor = (d.cursor or 0) + 1
end
-- Get next non-title row (you can't select titles)
while d.cursor > 0 and d.cursor <= d.nrows and d.rows[d.cursor].title do
d.cursor = d.cursor + 1
end
calc_offset(menu)
update(menu)
-- Emit changed signals
menu:emit_signal("changed", menu:get())
end
function get(menu, index)
assert(data[menu] and type(menu.widget) == "widget", "invalid menu widget")
-- Get private menu widget data
local d = data[menu]
-- Return row at given index or current cursor position.
return d.rows[index or d.cursor]
end
function del(menu, index)
assert(data[menu] and type(menu.widget) == "widget", "invalid menu widget")
-- Get private menu widget data
local d = data[menu]
-- Unable to delete this index, return
if d.cursor < 1 then return end
table.remove(d.rows, d.cursor)
-- Update rows count
d.nrows = #(d.rows)
-- Check cursor
d.cursor = math.min(d.cursor, d.nrows)
d.offset = math.min(d.offset, math.max(d.nrows - d.max_rows + 1, 1))
update(menu)
-- Emit changed signals
menu:emit_signal("changed", menu:get())
end
function new(args)
args = args or {}
local menu = {
widget = capi.widget{type = "vbox"},
-- Add widget methods
build = build,
update = update,
get = get,
del = del,
move_up = move_up,
move_down = move_down,
hide = function(menu) menu.widget:hide() end,
show = function(menu) menu.widget:show() end,
}
-- Save private widget data
data[menu] = {
-- Hold the rows & columns of label widgets which construct the
-- menu list widget.
table = {},
max_rows = args.max_rows or 10,
nrows = 0,
rows = {},
}
-- Setup class signals
signal.setup(menu)
return menu
end
setmetatable(_M, { __call = function(_, ...) return new(...) end })
| gpl-3.0 |
rasata/cardpeek | dot_cardpeek_dir/scripts/calypso/c376n3.lua | 15 | 44100 | --
-- This file is part of Cardpeek, the smart card reader utility.
--
-- Copyright 2009-2013 by Alain Pannetrat <L1L1@gmx.com>
--
-- Cardpeek is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- Cardpeek is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with Cardpeek. If not, see <http://www.gnu.org/licenses/>.
--
--********************************************************************--
--
-- This file is based on c376n2.lua, which was authored and contributed
-- to cardpeek by Anthony Berkow (C) 2013
--
-- Some minor alterations of the original file were performed for
-- integration with calypso.lua
--
-- Jan 2015:
-- This file c376n3.lua was created to take into account some specific
-- isses discovered with a new type of RavKav card with network id = 3
-- and which does not return a FCI.
-- This induced a change in RavKav_getRecordInfo()
--
--********************************************************************--
require('lib.apdu')
require('lib.tlv')
require('lib.en1545')
require('lib.country_codes')
require('etc.ravkav-strings')
--Classes
ISO_CLS_STD = 0x00 --Structure and coding of command and response according to ISO/IEC 7816 5.4.1 (plus optional secure messaging and logical channel)
ISO_CLS_PRO9 = 0x90 --As for ISO_CLS_STD but the coding and meaning of command and response are proprietary
--Class modifiers (SM)
ISO_CLS_SM_PRO = 0x04 --Proprietary secure messaging format
--Application ID
AID_RavKav = "#315449432e494341" --"1TIC.ICA"
--LIDs
CALYPSO_LID_ENVIRONMENT = "2001" --SFI=0x07, linear, 1 record
CALYPSO_LID_EVENTS_LOG = "2010" --SFI=0x08, cyclic, 3 records
CALYPSO_LID_CONTRACTS = "2020" --SFI=0x09, linear, 4 records
CALYPSO_LID_COUNTERS = "2069" --SFI=0x19, counters, 9 counters
LID_LIST = {
{"General Information", CALYPSO_LID_ENVIRONMENT, "environment"},
{"Counters", CALYPSO_LID_COUNTERS, "counters"},
{"Latest Travel", CALYPSO_LID_EVENTS_LOG, "event"},
{"Contracts", CALYPSO_LID_CONTRACTS, "contract"}
}
function ravkav_parse_serial_number(node,data)
nodes.set_attribute(node,"val", data)
nodes.set_attribute(node,"alt", string.format("%010d",bytes.tonumber(data)))
end
function ravkav_parse_ats(node,data)
if data and 5 <= #data then
local byteOffset = 1
byteOffset = RavKav_parseBits(data, byteOffset, 1, node, "File type", en1545_NUMBER)
byteOffset = RavKav_parseBits(data, byteOffset, 1, node, "EF type", en1545_NUMBER)
byteOffset, recordLen = RavKav_parseBits(data,byteOffset, 1, node, "Record size", en1545_NUMBER)
byteOffset, numRecords = RavKav_parseBits(data,byteOffset, 1, node, "Record count", en1545_NUMBER)
byteOffset = RavKav_parseBits(data, byteOffset, 4, node, "Access", en1545_UNDEFINED)
end
end
--Tags
RAVKAV_IDO = {
['A5/BF0C'] = {"Secure messaging data"},
['BF0C/C7'] = {"Serial number", ravkav_parse_serial_number},
['85'] = {"Record Info", ravkav_parse_ats},
}
ValidUntilOption = {
None = 0,
Date = 1,
EndOfService = 2,
Cancelled = 3
}
function bytes.is_all(bs, byte)
if 0 == #bs then return false end
local i
for i = 0, #bs - 1 do
if bs[i] ~= byte then return false end
end
return true
end
function RavKav_addTextNode(ctx, a_label, text)
local REF = nodes.append(ctx, { classname="item", label=a_label })
nodes.set_attribute(REF,"alt", text)
end
function RavKav_selectApplication(root)
card.CLA = ISO_CLS_STD
local sw, resp = card.select(AID_RavKav, card.SELECT_RETURN_FIRST + card.SELECT_RETURN_FCI, 0)
if 0x9000 ~= sw then
log.print(log.ERROR, "Failed to select Calypso application.")
return nil
end
local APP_REF = nodes.append(root, { classname="application", label="RavKav Card", size=#resp })
nodes.set_attribute(APP_REF,"val", resp)
return APP_REF
end
function RavKav_readCalypsoEf(lid, ctx)
card.CLA = ISO_CLS_STD
local sw, resp = card.select("."..lid)
if 0x9000 ~= sw then
log.print(log.ERROR, "Failed to select EF "..lid)
else
tlv_parse(ctx, resp)
end
end
function RavKav_parseEf(ctx)
local numRecords, recordLen
local RECINFO_REF, ri_data = RavKav_getField(ctx, "Record Info")
if ri_data and 5 <= #ri_data then
--recordLen = ri_data[3]
--numRecords = ri_data[4]
local byteOffset = 1
byteOffset = RavKav_parseBits(ri_data, byteOffset, 1, RECINFO_REF, "File type", en1545_NUMBER)
byteOffset = RavKav_parseBits(ri_data, byteOffset, 1, RECINFO_REF, "EF type", en1545_NUMBER)
byteOffset, recordLen = RavKav_parseBits(ri_data,byteOffset, 1, RECINFO_REF, "Record size", en1545_NUMBER)
byteOffset, numRecords = RavKav_parseBits(ri_data,byteOffset, 1, RECINFO_REF, "Record count", en1545_NUMBER)
byteOffset = RavKav_parseBits(ri_data, byteOffset, 4, RECINFO_REF, "Access", en1545_UNDEFINED)
log.print(log.DBG, string.format("numRecords: %d, recordLen: %d", numRecords, recordLen))
end
return numRecords, recordLen
end
function RavKav_getRecordInfo(ctx)
local numRecords = 0
local recordLen = 0
local RECINFO_REF = nodes.find_first(ctx, {label="Record Info"})
if RECINFO_REF then
numRecords = RavKav_getFieldAsNumber(RECINFO_REF, "Record count")
recordLen = RavKav_getFieldAsNumber(RECINFO_REF, "Record size")
else
local iter
for iter in nodes.find(ctx,{label="record"}) do
numRecords = numRecords + 1
end
recordLen = 29
end
return numRecords, recordLen
end
function RavKav_readRecord(nRec, recordLen)
card.CLA = ISO_CLS_PRO9 + ISO_CLS_SM_PRO
local sw, resp = card.read_record(0, nRec, recordLen)
if 0x9000 ~= sw then
log.print(log.ERROR, string.format("Failed to read record %d", nRec))
return nil
end
return resp
end
-- Note: this function can work with either bits or bytes depending on the data format
function RavKav_parseBits(data, bitOffset, nBits, REC, a_label, func, a_id)
local valData = bytes.sub(data, bitOffset, bitOffset + nBits - 1)
local value = func(valData)
local intVal = bytes.tonumber(valData)
local NEW_REF = nil
if REC then
NEW_REF = nodes.append(REC, {classname="item", label=a_label, id=a_id, size=nBits })
nodes.set_attribute(NEW_REF,"val", bytes.convert(valData,8))
nodes.set_attribute(NEW_REF,"alt", value)
end
return bitOffset + nBits, value, NEW_REF, intVal
end
function RavKav_rkDaysToSeconds(dateDaysPart)
bytes.pad_left(dateDaysPart, 32, 0)
return EPOCH + bytes.tonumber(dateDaysPart) * 24 * 3600
end
-- The bits in dateDaysPart have been inverted.
function RavKav_rkInvertedDaysToSeconds(dateDaysPart)
bytes.pad_left(dateDaysPart, 32, 0)
return EPOCH + bit.XOR(bytes.tonumber(dateDaysPart), 0x3fff) * 24 * 3600
end
-- Return the date (in seconds) corresponding to the last day of the month for the given date (in seconds).
-- If addMonths > 0 then the month is incremented by addMonths months.
function RavKav_calculateMonthEnd(dateSeconds, addMonths)
local dt = os.date("*t", dateSeconds)
if 0 < addMonths then
dt.month = dt.month + addMonths
local addYears = math.floor(dt.month / 12)
dt.year = dt.year + addYears
dt.month = dt.month - addYears * 12
end
dt.day = 28
local tmp_dt = dt
repeat
local date_s = os.time(tmp_dt) + 24 * 3600 --add 1 day
tmp_dt = os.date("*t",date_s)
if 1 ~= tmp_dt.day then --did not wrap round to a new month
dt.day = dt.day + 1
end
until 1 == tmp_dt.day
return os.time(dt)
end
function RavKav_INVERTED_DATE(source)
return os.date("%x", RavKav_rkInvertedDaysToSeconds(source))
end
function RavKav_PERCENT(source)
return string.format("%u %%", bytes.tonumber(source))
end
-- source is in BCD!
function RavKav_COUNTRY(source)
local countryId = bytes.tonumber(source)
countryId = tonumber(string.format("%X", countryId))
return iso_country_code_name(countryId)
end
function RavKav_ISSUER(source)
local issuerId = bytes.tonumber(source)
local issuer = RAVKAV_ISSUERS[issuerId]
if issuer then return issuer end
return tostring(issuerId)
end
function RavKav_PROFILE(source)
local profileId = bytes.tonumber(source)
local profile = RAVKAV_PROFILES[profileId]
if profile then return profile end
return tostring(profileId)
end
function RavKav_ROUTE(source)
local routeSystemId = bytes.tonumber(source)
local route = RAVKAV_ROUTES[routeSystemId]
if route then return route end
return tostring(routeSystemId)
end
function RavKav_LOCATION(source)
local locationId = bytes.tonumber(source)
local location = RAVKAV_LOCATIONS[locationId]
if location then return location end
return tostring(locationId)
end
function RavKav_VALIDITY_TYPE(source)
local validityType = bytes.tonumber(source)
local validity = RAVKAV_VALIDITY_TYPES[validityType]
if validity then return validity end
return tostring(validityType)
end
function RavKav_CONTRACT_TYPE(source)
local contractType = bytes.tonumber(source)
local contract = RAVKAV_CONTRACT_TYPES[contractType]
if contract then return contract end
return tostring(contractType)
end
-- Returns CSV list of which bits are set
function RavKav_ZONES(source)
local zonesPart = bytes.sub(source, 0, 11) --12 bits
local zones = bytes.tonumber(zonesPart)
local haveZones = false
local zoneList = ""
local i
for i = 1, 12 do
if 1 == bit.AND(zones, 1) then
if haveZones then zoneList = zoneList.."," end
zoneList = zoneList..tostring(i)
haveZones = true
end
zones = bit.SHR(zones, 1)
end
return zoneList
end
function RavKav_readRecords(EF_REF, numRecords, recordLen, rec_desc)
local nRec
for nRec = 1, numRecords do
local record = RavKav_readRecord(nRec, recordLen)
if record then
local REC_REF = nodes.append(EF_REF, {classname="record", label=rec_desc, id=nRec, size=#record})
nodes.set_attribute(REC_REF,"val", record)
end
end
end
function RavKav_readFile(APP_REF, desc, lid, rec_desc)
log.print(log.DBG, "Reading "..desc.."...")
local EF_REF = nodes.append(APP_REF, {classname="file", label=desc})
RavKav_readCalypsoEf(lid, EF_REF)
local numRecords, recordLen = RavKav_parseEf(EF_REF)
if numRecords then
RavKav_readRecords(EF_REF, numRecords, recordLen, rec_desc)
end
end
function RavKav_getField(SRC_REF, a_label, a_id)
local data, text
local REF = nodes.find_first(SRC_REF, {label=a_label, id=a_id})
if REF then
data = nodes.get_attribute(REF,"val")
text = nodes.get_attribute(REF,"alt")
end
return REF, data, text
end
function RavKav_getFieldAsNumber(SRC_REF, label, id)
local REF, data, text = RavKav_getField(SRC_REF, label, id)
if data then return bytes.tonumber(data) end
return 0
end
function RavKav_getFieldsAsNumberAry(SRC_REF, a_label, a_id)
local node
local ary = {}
for node in nodes.find(SRC_REF, { label=a_label, id=a_id }) do
local data = nodes.get_attribute(node,"val")
if data then table.insert(ary, bytes.tonumber(data)) end
end
return ary
end
-- if ary is supplied then only create new node if the field is a pointer to a valid entry in ary
function RavKav_copyField(SRC_REF, DEST_REF, a_label, a_id, ary)
local SRC_REF2, data, text = RavKav_getField(SRC_REF, a_label, a_id)
if nil == data then return nil, nil end
if ary then
local dataId = en1545_NUMBER(data)
if nil == ary[dataId] then return nil, nil end
end
NEW_REF = nodes.append(DEST_REF, {classname="item", label=a_label, id=a_id, size=#data })
nodes.set_attribute(NEW_REF,"val", data)
nodes.set_attribute(NEW_REF,"alt", text)
return SRC_REF2, NEW_REF
end
function RavKav_parseEnvironment(ENV_REF, nRec)
local ENV_REC_REF = nodes.find_first(ENV_REF, {label="record", id=nRec})
if nil == ENV_REC_REF then return false end
local record = nodes.get_attribute(ENV_REC_REF,"val")
if nil == record then return false end
local data = bytes.convert(record,1)
local bitOffset = 0
bitOffset = RavKav_parseBits(data, bitOffset, 3, ENV_REC_REF, "Version number", en1545_NUMBER)
bitOffset = RavKav_parseBits(data, bitOffset, 12, ENV_REC_REF, "Country", RavKav_COUNTRY)
bitOffset = RavKav_parseBits(data, bitOffset, 8, ENV_REC_REF, "Issuer", RavKav_ISSUER)
bitOffset = RavKav_parseBits(data, bitOffset, 26, ENV_REC_REF, "Application number", en1545_NUMBER)
bitOffset = RavKav_parseBits(data, bitOffset, 14, ENV_REC_REF, "Date of issue", en1545_DATE)
bitOffset = RavKav_parseBits(data, bitOffset, 14, ENV_REC_REF, "End date", en1545_DATE)
bitOffset = RavKav_parseBits(data, bitOffset, 3, ENV_REC_REF, "Pay method", en1545_NUMBER)
bitOffset = RavKav_parseBits(data, bitOffset, 32, ENV_REC_REF, "Date of birth", en1545_BCD_DATE)
bitOffset = RavKav_parseBits(data, bitOffset, 14, ENV_REC_REF, "Company (not set)", en1545_NUMBER)
bitOffset = RavKav_parseBits(data, bitOffset, 30, ENV_REC_REF, "Company ID (not set)", en1545_NUMBER)
bitOffset = RavKav_parseBits(data, bitOffset, 30, ENV_REC_REF, "ID number", en1545_NUMBER)
local PROFILES_REF = nodes.append(ENV_REC_REF, {classname="item", label="Profiles"})
local profile, ref
bitOffset, profile, ref = RavKav_parseBits(data, bitOffset, 6, PROFILES_REF, "Profile", RavKav_PROFILE, 1)
bitOffset = RavKav_parseBits(data, bitOffset, 14, ref, "Valid until", en1545_DATE)
bitOffset, profile, ref = RavKav_parseBits(data, bitOffset, 6, PROFILES_REF, "Profile", RavKav_PROFILE, 2)
RavKav_parseBits(data, bitOffset, 14, ref, "Valid until", en1545_DATE)
return true
end
function RavKav_parseGeneralInfo(APP_REF)
log.print(log.DBG, "Parsing general info (environment)...")
local ENV_REF = nodes.find_first(APP_REF, {label="Environment"})
if ENV_REF then
local numRecords = 2 -- RavKav_getRecordInfo(ENV_REF)
local nRec
for nRec = 1, numRecords do
-- only the first record contains valid data
if RavKav_parseEnvironment(ENV_REF, nRec) then break end
end
end
end
function RavKav_parseCounter(CNTRS_REF, nRec)
local CNTR_REC_REF = nodes.find_first(CNTRS_REF, {label="record", id=nRec})
if CNTR_REC_REF then
local record = nodes.get_attribute(CNTR_REC_REF,"val")
if record then
local data = bytes.convert(record,1)
local bitOffset = 0
local maxCounters = math.floor(#data / 24)
local nRec, nCnt
local cntrAry = {}
for nRec = 1, maxCounters do
bitOffset, nCnt = RavKav_parseBits(data, bitOffset, 24, CNTR_REC_REF, "Counter", en1545_NUMBER, nRec)
cntrAry[nRec] = nCnt
end
return cntrAry
end
end
return nil
end
function RavKav_parseCounters(APP_REF)
log.print(log.DBG, "Parsing counters...")
local CNTRS_REF = nodes.find_first(APP_REF, {id=CALYPSO_LID_COUNTERS})
if CNTRS_REF then
local numRecords = RavKav_getRecordInfo(CNTRS_REF)
if 0 < numRecords then
-- there should only be one counter record
return RavKav_parseCounter(CNTRS_REF, 1)
end
end
return nil
end
function RavKav_parseEvent(EVENTS_REF, nRec)
local EVENT_REC_REF = nodes.find_first(EVENTS_REF, {label="record", id=nRec})
if nil == EVENT_REC_REF then return end
local record = nodes.get_attribute(EVENT_REC_REF,"val")
if nil == record then return end
local data = bytes.convert(record,1)
if bytes.is_all(data, 0) then return end
local bitOffset = 0
local text, ref, issuerId
bitOffset = RavKav_parseBits(data, bitOffset, 3, EVENT_REC_REF, "Version number", en1545_NUMBER)
bitOffset, text, ref, issuerId = RavKav_parseBits(data, bitOffset, 8, EVENT_REC_REF, "Issuer", RavKav_ISSUER)
if issuerId == 0 then return end
local contractId, eventType
bitOffset, contractId = RavKav_parseBits(data, bitOffset, 4, EVENT_REC_REF, "Contract ID", en1545_NUMBER)
bitOffset = RavKav_parseBits(data, bitOffset, 4, EVENT_REC_REF, "Area ID", en1545_NUMBER) --1 == urban, 2 == intercity
bitOffset, eventType = RavKav_parseBits(data, bitOffset, 4, EVENT_REC_REF, "Event type", en1545_NUMBER)
bitOffset = RavKav_parseBits(data, bitOffset, 30, EVENT_REC_REF, "Event time", en1545_DATE_TIME)
bitOffset = RavKav_parseBits(data, bitOffset, 1, EVENT_REC_REF, "Journey interchanges flag", en1545_NUMBER) --includes switching/continuing beyond
bitOffset = RavKav_parseBits(data, bitOffset, 30, EVENT_REC_REF, "First event time", en1545_DATE_TIME) --identical to 'Event time'
local PRIORITIES_REF = nodes.append(EVENT_REC_REF, {classname="item", label="Best contract priorities"})
local nContract
for nContract = 1, 8 do
bitOffset = RavKav_parseBits(data, bitOffset, 4, PRIORITIES_REF, "Contract", RavKav_PERCENT, nContract)
end
local locationBitmap
local ln_ref = nil
bitOffset, text, ref, locationBitmap = RavKav_parseBits(data, bitOffset, 7, EVENT_REC_REF, "Location bitmap", en1545_UNDEFINED) --defined per issuer
if 0 < bit.AND(locationBitmap, 1) then
if 2 == issuerId then --Israel Rail
bitOffset = RavKav_parseBits(data, bitOffset, 16, EVENT_REC_REF, "Location", RavKav_LOCATION) --station
else
bitOffset = RavKav_parseBits(data, bitOffset, 16, EVENT_REC_REF, "Location ID", en1545_NUMBER) --place
end
end
if 0 < bit.AND(locationBitmap, 2) then
local lineNumber
bitOffset, lineNumber, ln_ref = RavKav_parseBits(data, bitOffset, 16, EVENT_REC_REF, "Line number", en1545_NUMBER) --number of line on route
end
if 0 < bit.AND(locationBitmap, 4) then
bitOffset = RavKav_parseBits(data, bitOffset, 8, EVENT_REC_REF, "Stop en route", en1545_NUMBER)
end
if 0 < bit.AND(locationBitmap, 8) then --12 unknown bits
bitOffset = RavKav_parseBits(data, bitOffset, 12, EVENT_REC_REF, "Location[3]", en1545_UNDEFINED)
end
if 0 < bit.AND(locationBitmap, 0x10) then
bitOffset = RavKav_parseBits(data, bitOffset, 14, EVENT_REC_REF, "Vehicle", en1545_UNDEFINED)
end
if 0 < bit.AND(locationBitmap, 0x20) then --how many bits??
log.print(log.DBG, string.format("Event[%d]: Location[5]: unknown value", nRec))
end
if 0 < bit.AND(locationBitmap, 0x40) then --8 unknown bits
if 0 < bit.AND(locationBitmap, 0x20) then -- we are lost due to previous unknown field
log.print(log.DBG, string.format("Event[%d]: Location[6]: unknown value", nRec))
else
bitOffset = RavKav_parseBits(data, bitOffset, 8, EVENT_REC_REF, "Location[6]", en1545_UNDEFINED)
end
end
if 0 == bit.AND(locationBitmap, 0x20) then
local eventExtension
bitOffset, text, ref, eventExtension = RavKav_parseBits(data, bitOffset, 3, EVENT_REC_REF, "Event extension bitmap", en1545_UNDEFINED)
if 0 < bit.AND(eventExtension, 1) then
bitOffset = RavKav_parseBits(data, bitOffset, 10, EVENT_REC_REF, "Route system", RavKav_ROUTE)
bitOffset = RavKav_parseBits(data, bitOffset, 8, EVENT_REC_REF, "Fare code", en1545_NUMBER)
local debitAmount, dr_ref
bitOffset, debitAmount, dr_ref = RavKav_parseBits(data, bitOffset, 16, EVENT_REC_REF, "Debit amount", en1545_NUMBER)
if 0 < debitAmount and 6 ~= eventType and 0 < contractId and 9 > contractId then --not a transit trip
if 21 > debitAmount then
dr_ref:set_attribute("alt",string.format("%u trip(s)", debitAmount))
else
dr_ref:set_attribute("alt",string.format("NIS %0.2f", debitAmount / 100.0))
end
end
end
if 0 < bit.AND(eventExtension, 2) then
bitOffset = RavKav_parseBits(data, bitOffset, 32, EVENT_REC_REF, "Event extension[2]", en1545_UNDEFINED)
end
if 0 < bit.AND(eventExtension, 4) then
bitOffset = RavKav_parseBits(data, bitOffset, 32, EVENT_REC_REF, "Event extension[3]", en1545_UNDEFINED)
end
end
-- fix 'Line number' field
local lnBitsize = 0
if 3 == issuerId then --Egged
bitOffset = 155
lnBitsize = 10
if 0 < bit.AND(locationBitmap, 8) then bitOffset = bitOffset + 12 end
elseif 15 == issuerId then --Metropolis
bitOffset = 123
lnBitsize = 32
elseif 2 ~= issuerId and 14 ~= issuerId and 16 ~= issuerId then --not Israel Rail, Nativ Express nor Superbus
bitOffset = 145
lnBitsize = 10
end
if 0 < lnBitsize then
if ln_ref then ln_ref:remove() end
RavKav_parseBits(data, bitOffset, lnBitsize, EVENT_REC_REF, "Line number", en1545_NUMBER)
end
end
function RavKav_parseEventsLog(APP_REF)
log.print(log.DBG, "Parsing events...")
local EVENTS_REF = nodes.find_first(APP_REF, {label="Event logs"} )
if EVENTS_REF then
local numRecords = RavKav_getRecordInfo(EVENTS_REF)
local nRec
for nRec = 1, numRecords do
RavKav_parseEvent(EVENTS_REF, nRec)
end
end
end
function RavKav_parseContract(CONTRACTS_REF, nRec, counter)
local CONTRACT_REC_REF = nodes.find_first(CONTRACTS_REF, {label="record", id=nRec})
if nil == CONTRACT_REC_REF then return end
local record = nodes.get_attribute(CONTRACT_REC_REF,"val")
if nil == record then return end
local data = bytes.convert(record,1)
if bytes.is_all(data, 0) then
nodes.set_attribute(CONTRACT_REC_REF,"alt","empty")
return
end
local bitOffset = 0
local text, ref, vfd_ref, issuerId
bitOffset = RavKav_parseBits(data, bitOffset, 3, CONTRACT_REC_REF, "Version number", en1545_NUMBER)
bitOffset, text, vfd_ref = RavKav_parseBits(data, bitOffset, 14, CONTRACT_REC_REF, "Valid from", RavKav_INVERTED_DATE) --validity start date
local validFromSeconds = RavKav_rkInvertedDaysToSeconds(nodes.get_attribute(vfd_ref,"val"))
bitOffset, text, ref, issuerId = RavKav_parseBits(data, bitOffset, 8, CONTRACT_REC_REF, "Issuer", RavKav_ISSUER)
if issuerId == 0 then return end
local ticketType, validityBitmap
local contractValid = true
bitOffset = RavKav_parseBits(data, bitOffset, 2, CONTRACT_REC_REF, "Tariff transport access", en1545_NUMBER)
bitOffset = RavKav_parseBits(data, bitOffset, 3, CONTRACT_REC_REF, "Tariff counter use", en1545_NUMBER) --0 == not used, 2 == number of tokens, 3 == monetary amount
bitOffset, ticketType = RavKav_parseBits(data, bitOffset, 6, CONTRACT_REC_REF, "Ticket type", en1545_NUMBER)
if 1 == ticketType or 6 == ticketType or 7 == ticketType then --Single or multiple, Aggregate value or Single or multiple
contractValid = 0 < counter
local balance
if 6 == ticketType then --Aggregate value
balance = string.format("NIS %0.2f", counter / 100.0) --balanceRemaining
else
balance = string.format("%d trip(s)", counter) --tripsRemaining
end
local NEW_REF = nodes.append(CONTRACT_REC_REF, {classname="item", label="Balance", size=24})
nodes.set_attribute(NEW_REF,"val", bytes.new(8, string.format("%06X", counter)))
nodes.set_attribute(NEW_REF,"alt", balance)
end
bitOffset = RavKav_parseBits(data, bitOffset, 14, CONTRACT_REC_REF, "Date of purchase", en1545_DATE) --sale date
bitOffset = RavKav_parseBits(data, bitOffset, 12, CONTRACT_REC_REF, "Sale device", en1545_NUMBER) --serial number of device that made the sale
bitOffset = RavKav_parseBits(data, bitOffset, 10, CONTRACT_REC_REF, "Sale number", en1545_NUMBER) --runnning sale number on the day of the sale
bitOffset = RavKav_parseBits(data, bitOffset, 1, CONTRACT_REC_REF, "Journey interchanges flag", en1545_NUMBER) --includes switching/continuing beyond
bitOffset, text, ref, validityBitmap = RavKav_parseBits(data, bitOffset, 9, CONTRACT_REC_REF, "Validity bitmap", en1545_UNDEFINED)
if 0 < bit.AND(validityBitmap, 1) then
bitOffset = RavKav_parseBits(data, bitOffset, 5, CONTRACT_REC_REF, "Validity[1]", en1545_UNDEFINED)
end
local restrictionCode = 0
if 0 < bit.AND(validityBitmap, 2) then
bitOffset, restrictionCode = RavKav_parseBits(data, bitOffset, 5, CONTRACT_REC_REF, "Restriction code", en1545_NUMBER)
end
if 0 < bit.AND(validityBitmap, 4) then
local iDuration, rd_ref
bitOffset, iDuration, rd_ref = RavKav_parseBits(data, bitOffset, 6, CONTRACT_REC_REF, "Restriction duration", en1545_NUMBER)
if 16 == restrictionCode then
iDuration = iDuration * 5
else
iDuration = iDuration * 30
end
rd_ref:set_attribute("alt",string.format("%d minute(s)", iDuration))
end
if 0 < bit.AND(validityBitmap,8) then --validity end date
local vtd_ref
bitOffset, text, vtd_ref = RavKav_parseBits(data, bitOffset, 14, CONTRACT_REC_REF, "Valid until", en1545_DATE)
if contractValid then
contractValid = RavKav_rkDaysToSeconds(vtd_ref:val()) > os.time()
end
end
local validUntilOption = ValidUntilOption.None
if 0 < bit.AND(validityBitmap, 0x10) then
local validMonths
bitOffset, validMonths = RavKav_parseBits(data, bitOffset, 8, CONTRACT_REC_REF, "Valid months", en1545_NUMBER)
if 0 < validMonths then
if 1 == validMonths then
validUntilOption = ValidUntilOption.Date
local validUntilSeconds = RavKav_calculateMonthEnd(validFromSeconds, validMonths - 1) --month end date
local NEW_REF = nodes.append(CONTRACT_REC_REF, {classname="item", label="Valid to", size=14}) --month end date
nodes.set_attribute(NEW_REF,"val", bytes.new(8, string.format("%04X", validUntilSeconds)))
nodes.set_attribute(NEW_REF,"alt", os.date("%x", validUntilSeconds))
if contractValid then
contractValid = validUntilSeconds > os.time()
end
elseif 129 == validMonths then
validUntilOption = ValidUntilOption.EndOfService
log.print(log.DBG, string.format("Contract[%d]: Valid until the end of the service", nRec))
local NEW_REF = nodes.append(CONTRACT_REC_REF, {classname="item", label="Valid to", size=2})
nodes.set_attribute(NEW_REF,"val", bytes.new(8, string.format("%01X", validUntilOption)))
nodes.set_attribute(NEW_REF,"alt", "The end of the service")
if contractValid then
contractValid = validFromSeconds > os.time()
end
else
log.print(log.DBG, string.format("Contract[%d]: Valid months unknown value: %d", nRec, validMonths))
end
else
validUntilOption = ValidUntilOption.Cancelled
log.print(log.DBG, string.format("Contract[%d]: Validity cancelled", nRec))
local NEW_REF = nodes.append(CONTRACT_REC_REF, {classname="item", label="Valid to", size=2})
nodes.set_attribute(NEW_REF,"val", bytes.new(8, string.format("%01X", validUntilOption)))
nodes.set_attribute(NEW_REF,"alt", "Validity cancelled")
end
end
if 0 < bit.AND(validityBitmap, 0x20) then
bitOffset = RavKav_parseBits(data, bitOffset, 32, CONTRACT_REC_REF, "Validity[5]", en1545_UNDEFINED)
end
if 0 < bit.AND(validityBitmap, 0x40) then
bitOffset = RavKav_parseBits(data, bitOffset, 6, CONTRACT_REC_REF, "Validity[6]", en1545_UNDEFINED)
end
if 0 < bit.AND(validityBitmap, 0x80) then
bitOffset = RavKav_parseBits(data, bitOffset, 32, CONTRACT_REC_REF, "Validity[7]", en1545_UNDEFINED)
end
if 0 < bit.AND(validityBitmap, 0x100) then
bitOffset = RavKav_parseBits(data, bitOffset, 32, CONTRACT_REC_REF, "Validity[8]", en1545_UNDEFINED)
end
-- read validity locations
local VALID_LOCS_REF = nodes.append(CONTRACT_REC_REF, {classname="item", label="Validity locations"})
local nLoc
for nLoc = 1, 7 do --limit to 7 just in case the end marker is missing?
local LOC_REF = nodes.append(VALID_LOCS_REF, {classname="item", label="Validity", id=nLoc})
local validity, ref, validityType
bitOffset, validity, ref, validityType = RavKav_parseBits(data, bitOffset, 4, LOC_REF, "Validity type", RavKav_VALIDITY_TYPE)
if 15 == validityType then --end of validity locations
log.print(log.DBG, string.format("Contract %d: Validity location[%d]: validityType: 15 (end of validity locations)", nRec, nLoc))
nodes.remove(LOC_REF)
break
end
if 0 == validityType then
bitOffset = RavKav_parseBits(data, bitOffset, 10, LOC_REF, "Route ID", RavKav_ROUTE, validityType)
bitOffset = RavKav_parseBits(data, bitOffset, 12, LOC_REF, "Spatial zones", RavKav_ZONES, validityType)
elseif 1 == validityType then
bitOffset = RavKav_parseBits(data, bitOffset, 10, LOC_REF, "Route ID", RavKav_ROUTE, validityType)
bitOffset = RavKav_parseBits(data, bitOffset, 8, LOC_REF, "Tariff code", en1545_NUMBER, validityType)
elseif 3 == validityType then
bitOffset = RavKav_parseBits(data, bitOffset, 32, LOC_REF, "Validity", en1545_UNDEFINED, validityType)
elseif 7 == validityType then
bitOffset = RavKav_parseBits(data, bitOffset, 10, LOC_REF, "Route ID", RavKav_ROUTE, validityType)
bitOffset = RavKav_parseBits(data, bitOffset, 8, LOC_REF, "Tariff code", en1545_NUMBER, validityType)
elseif 8 == validityType then --unknown validity type except for Israel Rail?
bitOffset = RavKav_parseBits(data, bitOffset, 10, LOC_REF, "Route ID", RavKav_ROUTE, validityType)
bitOffset = RavKav_parseBits(data, bitOffset, 8, LOC_REF, "Tariff code", en1545_NUMBER, validityType) --?
bitOffset = RavKav_parseBits(data, bitOffset, 14, LOC_REF, "Unknown", en1545_UNDEFINED, validityType)
elseif 9 == validityType then
bitOffset = RavKav_parseBits(data, bitOffset, 3, LOC_REF, "Extended ticket type (ETT)", en1545_NUMBER, validityType)
bitOffset = RavKav_parseBits(data, bitOffset, 11, LOC_REF, "Contract type", RavKav_CONTRACT_TYPE, validityType)
elseif 11 == validityType then
bitOffset = RavKav_parseBits(data, bitOffset, 21, LOC_REF, "Validity", en1545_UNDEFINED, validityType)
elseif 14 == validityType then
bitOffset = RavKav_parseBits(data, bitOffset, 10, LOC_REF, "Route ID", en1545_NUMBER, validityType)
bitOffset = RavKav_parseBits(data, bitOffset, 12, LOC_REF, "Spatial zones", RavKav_ZONES, validityType)
else
log.print(log.DBG, string.format("Contract %d: Validity location[%d]: unrecognised validityType: %d", nRec, nLoc, validityType))
break --since we don't know the next bit position
end
end
RavKav_parseBits(data, 224, 8,CONTRACT_REC_REF, "Contract authenticator", en1545_UNDEFINED) --checksum?
local cv_ref = nodes.append(CONTRACT_REC_REF, {classname="item", label="Contract valid", size=1})
if contractValid then
nodes.set_attribute(cv_ref,"val", bytes.new(1, 1))
nodes.set_attribute(cv_ref,"alt", "True")
else
nodes.set_attribute(cv_ref,"val", bytes.new(1, 0))
nodes.set_attribute(cv_ref,"alt", "False")
end
end
function RavKav_parseContracts(APP_REF, cntrAry)
log.print(log.DBG, "Parsing contracts...")
local CONTRACTS_REF = nodes.find_first(APP_REF, {label="Contracts"})
if CONTRACTS_REF then
local numRecords = RavKav_getRecordInfo(CONTRACTS_REF)
local nRec
for nRec = 1, numRecords do
RavKav_parseContract(CONTRACTS_REF, nRec, cntrAry[nRec])
end
end
end
function RavKav_SummariseProfile(PROFS_REF, id, GI_REF)
local SRC_REF, NEW_REF = RavKav_copyField(PROFS_REF, GI_REF, "Profile", id, RAVKAV_PROFILES)
if NEW_REF then
if 0 < RavKav_getFieldAsNumber(SRC_REF, "Valid until") then
RavKav_copyField(SRC_REF, NEW_REF, "Valid until")
end
end
end
function RavKav_summariseGeneralInfo(APP_REF, SUM_REF)
log.print(log.DBG, "Summarising general info...")
local ENV_REF = APP_REF:find_first({label="Environment"}):find_first({label="record"})
if ENV_REF then
local GI_REF = nodes.append(SUM_REF, {classname="file", label="General Information"})
RavKav_copyField(APP_REF, GI_REF, "Serial number")
RavKav_copyField(ENV_REF, GI_REF, "Issuer", nil, RAVKAV_ISSUERS)
local idNumber = RavKav_getFieldAsNumber(ENV_REF, "ID number")
if 0 == idNumber then
local REF = nodes.append(GI_REF, {classname="item", label="Identity number", size=0})
nodes.set_attribute(REF,"alt", "Anonymous Rav-Kav")
return
end
RavKav_copyField(ENV_REF,GI_REF, "ID number")
RavKav_copyField(ENV_REF,GI_REF, "Date of birth")
local PROFS_REF = nodes.find_first(ENV_REF, {label="Profiles"})
if PROFS_REF then
RavKav_SummariseProfile(PROFS_REF, 1, GI_REF)
RavKav_SummariseProfile(PROFS_REF, 2, GI_REF)
end
end
end
function RavKav_summariseEvent(EVENTS_REF, nRec, LT_REF)
local EVENT_REC_REF = nodes.find_first(EVENTS_REF, {label="record", id=nRec})
if nil == EVENT_REC_REF then return end
local issuerId = RavKav_getFieldAsNumber(EVENT_REC_REF, "Issuer")
if 0 == issuerId then return end
local EVSUM_REF = nodes.append(LT_REF, {classname="record", label="Event", id=nRec})
-- Description ---------------------------
local description = ""
if RAVKAV_ISSUERS[issuerId] then description = RAVKAV_ISSUERS[issuerId] end
local lineNumber = RavKav_getFieldAsNumber(EVENT_REC_REF, "Line number")
if 0 < lineNumber then
description = description.." line "
local routeSystemId = RavKav_getFieldAsNumber(EVENT_REC_REF, "Route system")
local sLineNum = tostring(lineNumber)
if RAVKAV_ROUTES[routeSystemId] then
if 15 == issuerId then --Metropolis
local sRouteSystemId = tostring(routeSystemId)
local posS, posE = string.find(sLineNum, sRouteSystemId)
if 1 == posS then --Does "1234567..." start with "12"?
sLineNum = string.sub(sLineNum, posE + 1, posE + 4) --"1234567..." -> "345"
end
end
description = description..sLineNum..", cluster "..RAVKAV_ROUTES[routeSystemId]
else
description = description..sLineNum
end
end
if 0 < #description then RavKav_addTextNode(EVSUM_REF, "Description", description) end
------------------------------------------
if 0 < RavKav_getFieldAsNumber(EVENT_REC_REF, "Event time") then
RavKav_copyField(EVENT_REC_REF, EVSUM_REF, "Event time")
end
if 2 == issuerId then --Israel Rail
local locationId = RavKav_getFieldAsNumber(EVENT_REC_REF, "Location")
if RAVKAV_LOCATIONS[locationId] then
RavKav_addTextNode(EVSUM_REF, "Station", RAVKAV_LOCATIONS[locationId])
end
end
-- Details -------------------------------
details = ""
local eventType = RavKav_getFieldAsNumber(EVENT_REC_REF, "Event type")
local contractId = RavKav_getFieldAsNumber(EVENT_REC_REF, "Contract ID")
if 6 ~= eventType and 0 < contractId and 9 > contractId then --not a transit trip
local REF, data, debitedText = RavKav_getField(EVENT_REC_REF, "Debit amount")
local debitAmount = 0
if data then debitAmount = bytes.tonumber(data) end
if 0 < debitAmount then
if 1 ~= eventType then --not an exit event
details = RAVKAV_EVENT_TYPES[eventType]
end
details = details.." contract "..tostring(contractId).." charged "..debitedText
else
details = RAVKAV_EVENT_TYPES[eventType].." contract "..tostring(contractId)
end
local fareCode = RavKav_getFieldAsNumber(EVENT_REC_REF, "Fare code")
if 0 < fareCode then
details = details.." (code "..tostring(fareCode)..")"
end
else
details = RAVKAV_EVENT_TYPES[eventType]
end
if 0 < #details then RavKav_addTextNode(EVSUM_REF, "Details", details) end
------------------------------------------
end
function RavKav_summariseLatestTravel(APP_REF, SUM_REF)
log.print(log.DBG, "Summarising latest travel...")
local EVENTS_REF = nodes.find_first(APP_REF, {label="Event logs"})
if EVENTS_REF then
local LT_REF = nodes.append(SUM_REF, {classname="file", label="Latest Travel"})
local numRecords = RavKav_getRecordInfo(EVENTS_REF)
local nRec
for nRec = 1, numRecords do
RavKav_summariseEvent(EVENTS_REF, nRec, LT_REF)
end
end
end
function RavKav_summariseTextArray(REC_REF, itmLabel, lookupAry, SM_REF, sumLabel)
local summary = ""
local ary = RavKav_getFieldsAsNumberAry(REC_REF, itmLabel)
local i, id
for i, id in ipairs(ary) do
if lookupAry[id] then
if 0 < #summary then summary = summary.."\n " end
summary = summary..lookupAry[id]
end
end
if 0 < #summary then RavKav_addTextNode(SM_REF, sumLabel, summary) end
end
function RavKav_summariseIntegerArray(REC_REF, itmLabel, SM_REF, sumLabel)
local summary = ""
local ary = RavKav_getFieldsAsNumberAry(REC_REF, itmLabel)
local i, val
for i, val in ipairs(ary) do
if 0 < val then
if 0 < #summary then summary = summary..", " end
summary = summary..tostring(val)
end
end
if 0 < #summary then RavKav_addTextNode(SM_REF, sumLabel, summary) end
end
function RavKav_summariseContract(CONTRACTS_REF, nRec, VC_REF, IC_REF)
local CONTRACT_REC_REF = nodes.find_first(CONTRACTS_REF, {label="record", id=nRec})
if nil == CONTRACT_REC_REF then return end
local issuerId = RavKav_getFieldAsNumber(CONTRACT_REC_REF, "Issuer")
if 0 == issuerId then return end
local contractValid = 0 ~= RavKav_getFieldAsNumber(CONTRACT_REC_REF, "Contract valid")
local CT_REF = IC_REF
if contractValid then CT_REF = VC_REF end
local CTSUM_REF = nodes.append(CT_REF, {classname="record", label="Contract", id=nRec})
-- Description ---------------------------
local description = ""
if RAVKAV_ISSUERS[issuerId] then description = RAVKAV_ISSUERS[issuerId] end
local ticketType = RavKav_getFieldAsNumber(CONTRACT_REC_REF, "Ticket type")
if RAVKAV_TICKET_TYPES[ticketType] then description = description.." "..RAVKAV_TICKET_TYPES[ticketType] end
if 0 < #description then RavKav_addTextNode(CTSUM_REF, "Description", description) end
------------------------------------------
RavKav_summariseTextArray(CONTRACT_REC_REF, "Route ID", RAVKAV_ROUTES, CTSUM_REF, "Clusters")
-- Type of contract ----------------------
if 0 < ticketType then
local REF, data = RavKav_getField(CONTRACT_REC_REF, "Extended ticket type (ETT)")
if data then
local ett = bytes.tonumber(data)
if RAVKAV_CONTRACT_DESCRIPTIONS[ticketType][ett] then
RavKav_addTextNode(CTSUM_REF, "Type of contract", RAVKAV_CONTRACT_DESCRIPTIONS[ticketType][ett])
end
end
end
------------------------------------------
RavKav_summariseIntegerArray(CONTRACT_REC_REF, "Tariff code", CTSUM_REF, "Tariff codes")
RavKav_summariseTextArray(CONTRACT_REC_REF, "Contract type", RAVKAV_CONTRACT_TYPES, CTSUM_REF, "Contract types")
local journeyInterchangesFlag = 0 ~= RavKav_getFieldAsNumber(CONTRACT_REC_REF, "Journey interchanges flag")
if journeyInterchangesFlag then RavKav_addTextNode(CTSUM_REF, "Journey interchanges", "Includes switching/resume") end
if 0 < RavKav_getFieldAsNumber(CONTRACT_REC_REF, "Restriction duration") then
RavKav_copyField(CONTRACT_REC_REF, CTSUM_REF, "Restriction duration")
end
RavKav_copyField(CONTRACT_REC_REF, CTSUM_REF, "Balance")
if 0x3fff ~= RavKav_getFieldAsNumber(CONTRACT_REC_REF, "Valid from") then --14 bits of valid from date are inverted
RavKav_copyField(CONTRACT_REC_REF, CTSUM_REF, "Valid from")
elseif 0 < RavKav_getFieldAsNumber(CONTRACT_REC_REF, "Date of purchase") then
RavKav_copyField(CONTRACT_REC_REF, CTSUM_REF, "Date of purchase")
end
RavKav_copyField(CONTRACT_REC_REF, CTSUM_REF, "Valid to")
if 0 < RavKav_getFieldAsNumber(CONTRACT_REC_REF, "Valid until") then
RavKav_copyField(CONTRACT_REC_REF, CTSUM_REF, "Valid until")
end
end
function RavKav_summariseContracts(APP_REF, SUM_REF)
log.print(log.DBG, "Summarising contracts...")
local CONTRACTS_REF = nodes.find_first(APP_REF, {label="Contracts"})
if CONTRACTS_REF then
local VC_REF = nodes.append(SUM_REF, {classname="file", label="Valid Contracts"})
local IC_REF = nodes.append(SUM_REF, {classname="file", label="Invalid Contracts"})
local numRecords = RavKav_getRecordInfo(CONTRACTS_REF)
local nRec
for nRec = 1, numRecords do
RavKav_summariseContract(CONTRACTS_REF, nRec, VC_REF, IC_REF)
end
end
end
function RavKav_readFiles(APP_REF)
local lid_index
local lid_desc
for lid_index, lid_desc in ipairs(LID_LIST) do
RavKav_readFile(APP_REF, lid_desc[1], lid_desc[2], lid_desc[3])
end
end
function RavKav_parseRecords(APP_REF)
RavKav_parseGeneralInfo(APP_REF)
local cntrAry = RavKav_parseCounters(APP_REF)
RavKav_parseEventsLog(APP_REF)
RavKav_parseContracts(APP_REF, cntrAry)
end
function RavKav_summariseRecords(APP_REF, root)
local SUM_REF = nodes.append(root, {classname="block", label="Summary"})
RavKav_summariseGeneralInfo(APP_REF, SUM_REF)
RavKav_summariseLatestTravel(APP_REF, SUM_REF)
RavKav_summariseContracts(APP_REF, SUM_REF)
end
function RavKav_parseAnswerToSelect(ctx)
local ats
local data
for ats in ctx:find({label="answer to select"}) do
data = nodes.get_attribute(ats,"val")
tlv_parse(ats,data,RAVKAV_IDO)
end
end
RavKav_parseAnswerToSelect(CARD)
RavKav_parseRecords(CARD)
RavKav_summariseRecords(CARD, CARD)
| gpl-3.0 |
dufferzafar/Project-Euler-Solutions | Problems 51-100/87.lua | 1 | 1260 | --[[
Problem No. 87
Numbers that can be expressed as the sum of a prime square, cube, and fourth power?
Saturday, February 04, 2012
]]--
--Sub Routines
function isPrime(x)
if (x%3 == 0) then return false
else
local f = 5;
while f <= math.floor(x^0.5) do
if (x%f) == 0 then return false end
if (x%(f+2)) == 0 then return false end
f = f + 6;
end
end; return true
end
--The Primes 1097343
local tPrimes7071, tPrimes368, tPrimes83, eliminated = {2, 3}, {2, 3}, {2, 3}, {}
local found = 0
--Prime Numbers upto 83
for i = 5, 7071, 2 do
if i < 84 then
if isPrime(i) then tPrimes83[#tPrimes83 + 1] = i end
end
if i < 369 then
if isPrime(i) then tPrimes368[#tPrimes368 + 1] = i end
end
if i < 7071 then
if isPrime(i) then tPrimes7071[#tPrimes7071 + 1] = i end
end
end
--The Main Loop
for i = 1, #tPrimes7071 do
for j = 1, #tPrimes368 do
for k = 1, #tPrimes83 do
if tPrimes7071[i]^2 + tPrimes368[j]^3 + tPrimes83[k]^4 < 50000000 then
if not eliminated[tPrimes7071[i]^2 + tPrimes368[j]^3 + tPrimes83[k]^4] then
eliminated[tPrimes7071[i]^2 + tPrimes368[j]^3 + tPrimes83[k]^4] = true
found = found + 1
end
end
end
end
end
--We've Done It!!
print(found) | unlicense |
mqmaker/witi-openwrt | package/ramips/ui/luci-mtk/src/modules/rpc/luasrc/controller/rpc.lua | 70 | 4443 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local require = require
local pairs = pairs
local print = print
local pcall = pcall
local table = table
module "luci.controller.rpc"
function index()
local function authenticator(validator, accs)
local auth = luci.http.formvalue("auth", true)
if auth then -- if authentication token was given
local sdat = luci.sauth.read(auth)
if sdat then -- if given token is valid
if sdat.user and luci.util.contains(accs, sdat.user) then
return sdat.user, auth
end
end
end
luci.http.status(403, "Forbidden")
end
local rpc = node("rpc")
rpc.sysauth = "root"
rpc.sysauth_authenticator = authenticator
rpc.notemplate = true
entry({"rpc", "uci"}, call("rpc_uci"))
entry({"rpc", "fs"}, call("rpc_fs"))
entry({"rpc", "sys"}, call("rpc_sys"))
entry({"rpc", "ipkg"}, call("rpc_ipkg"))
entry({"rpc", "auth"}, call("rpc_auth")).sysauth = false
end
function rpc_auth()
local jsonrpc = require "luci.jsonrpc"
local sauth = require "luci.sauth"
local http = require "luci.http"
local sys = require "luci.sys"
local ltn12 = require "luci.ltn12"
local util = require "luci.util"
local loginstat
local server = {}
server.challenge = function(user, pass)
local sid, token, secret
if sys.user.checkpasswd(user, pass) then
sid = sys.uniqueid(16)
token = sys.uniqueid(16)
secret = sys.uniqueid(16)
http.header("Set-Cookie", "sysauth=" .. sid.."; path=/")
sauth.reap()
sauth.write(sid, {
user=user,
token=token,
secret=secret
})
end
return sid and {sid=sid, token=token, secret=secret}
end
server.login = function(...)
local challenge = server.challenge(...)
return challenge and challenge.sid
end
http.prepare_content("application/json")
ltn12.pump.all(jsonrpc.handle(server, http.source()), http.write)
end
function rpc_uci()
if not pcall(require, "luci.model.uci") then
luci.http.status(404, "Not Found")
return nil
end
local uci = require "luci.jsonrpcbind.uci"
local jsonrpc = require "luci.jsonrpc"
local http = require "luci.http"
local ltn12 = require "luci.ltn12"
http.prepare_content("application/json")
ltn12.pump.all(jsonrpc.handle(uci, http.source()), http.write)
end
function rpc_fs()
local util = require "luci.util"
local io = require "io"
local fs2 = util.clone(require "nixio.fs")
local jsonrpc = require "luci.jsonrpc"
local http = require "luci.http"
local ltn12 = require "luci.ltn12"
function fs2.readfile(filename)
local stat, mime = pcall(require, "mime")
if not stat then
error("Base64 support not available. Please install LuaSocket.")
end
local fp = io.open(filename)
if not fp then
return nil
end
local output = {}
local sink = ltn12.sink.table(output)
local source = ltn12.source.chain(ltn12.source.file(fp), mime.encode("base64"))
return ltn12.pump.all(source, sink) and table.concat(output)
end
function fs2.writefile(filename, data)
local stat, mime = pcall(require, "mime")
if not stat then
error("Base64 support not available. Please install LuaSocket.")
end
local file = io.open(filename, "w")
local sink = file and ltn12.sink.chain(mime.decode("base64"), ltn12.sink.file(file))
return sink and ltn12.pump.all(ltn12.source.string(data), sink) or false
end
http.prepare_content("application/json")
ltn12.pump.all(jsonrpc.handle(fs2, http.source()), http.write)
end
function rpc_sys()
local sys = require "luci.sys"
local jsonrpc = require "luci.jsonrpc"
local http = require "luci.http"
local ltn12 = require "luci.ltn12"
http.prepare_content("application/json")
ltn12.pump.all(jsonrpc.handle(sys, http.source()), http.write)
end
function rpc_ipkg()
if not pcall(require, "luci.model.ipkg") then
luci.http.status(404, "Not Found")
return nil
end
local ipkg = require "luci.model.ipkg"
local jsonrpc = require "luci.jsonrpc"
local http = require "luci.http"
local ltn12 = require "luci.ltn12"
http.prepare_content("application/json")
ltn12.pump.all(jsonrpc.handle(ipkg, http.source()), http.write)
end
| gpl-2.0 |
fengshao0907/Atlas-1 | lib/xtab.lua | 40 | 13591 | --[[ $%BEGINLICENSE%$
Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; version 2 of the
License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
02110-1301 USA
$%ENDLICENSE%$ --]]
---
--[[
Uses MySQL-Proxy to create and execute a cross tabulation query
Using this script, you can request commands like
XTAB HELP
XTAB VERSION
XTAB table_name row_header col_header operation operation_fld
and get the result in tabular format, from any MySQL client
Written by Giuseppe Maxia, QA Developer, MySQL AB
--]]
assert(proxy.PROXY_VERSION >= 0x00600,
"you need at least mysql-proxy 0.6.0 to run this module")
--[[
If the environmental variable 'DEBUG' is set, then
the proxy will print diagnostic messages
--]]
local DEBUG = os.getenv('DEBUG') or os.getenv('VERBOSE') or 0
DEBUG = DEBUG + 0
local xtab_version = '0.1.3'
local tokenizer = require("proxy.tokenizer")
--[[
error status for the xtab sequence
if an error happens in a query before the last one,
all results after it are ignored
--]]
local xtab_error_status = 0
local return_xtab_query = false
local xtab_help_messages = {
{ 'xtab - version ' .. xtab_version .. ' - (C) MySQL AB 2007' },
{ 'Syntax: ' },
{ ' - ' },
{ 'XTAB table_name row_header col_header operation operation_fld [summary]' },
{ '"table_name" can be a table or a view' },
{ '"row_field" is the field to be used as row header' },
{ '"col_field" is the field whose distinct values will become column headers' },
{ '"operation" is the required operation (COUNT|SUM|AVG|MAX|MIN)' },
{ '"operation_field" is the field to which the operation is applied' },
{ ' - ' },
{ 'If the "summary" option is used, then a "WITH ROLLUP" clause ' },
{ 'is added to the query.' },
{ ' - ' },
{ 'Other commands:' },
{ 'XTAB QUERY - the XTAB query is returned instead of its result' },
{ 'XTAB NOQUERY - the XTAB result is returned (default)' },
{ 'XTAB version - shows current version' },
{ 'XTAB help - shows this help' },
{ 'Created by Giuseppe Maxia' },
}
local allowed_operators = {'count', 'sum', 'avg', 'min', 'max' }
--
-- Result with the syntax help
--
local xtab_help_resultset = {
fields = {
{ type = proxy.MYSQL_TYPE_STRING, name = 'XTAB help'},
},
rows = xtab_help_messages
}
--
-- Result with the XTAB version
--
local xtab_version_resultset = {
fields = {
{ type = proxy.MYSQL_TYPE_STRING, name = 'XTAB version'}
},
rows = {
{ xtab_version }
}
}
--
-- Result to comment on XTAB QUERY command
--
local xtab_query_resultset = {
fields = {
{ type = proxy.MYSQL_TYPE_STRING, name = 'XTAB query '}
},
rows = {
{ 'Setting XTAB QUERY, the next XTAB command will return ' },
{ 'the query text instead of its result.' },
{ '' },
{ 'Setting XTAB NOQUERY (default), the XTAB command' },
{ 'executes the query and returns its result.' },
{ '' },
}
}
--
-- result returned on wrong XTAB option
--
local xtab_unknown_resultset = {
fields = {
{ type = proxy.MYSQL_TYPE_STRING, name = 'XTAB ERROR'}
},
rows = {
{ 'unknown command. Enter "XTAB HELP" for help' }
}
}
--
-- result returned on wrong operator
--
local xtab_unknown_operator = {
fields = {
{ type = proxy.MYSQL_TYPE_STRING, name = 'XTAB ERROR'}
},
rows = {
{ 'unknown operator.' },
{ 'Accepted operators: COUNT, SUM, AVG, MIN, MAX' },
{ 'Enter "XTAB HELP" for help' },
}
}
--
-- xtab parameters to be passed from read_query ro read_query_result
--
local xtab_params = {}
--[[
Injection codes to recognize the various queries
composing the xtab operation
--]]
local xtab_id_before = 1024
local xtab_id_start = 2048
local xtab_id_exec = 4096
--[[
TODO
add XTAB VERBOSE, to enable debugging from SQL CLI
handling errors related to missing xtab_params values
--]]
function read_query( packet )
if packet:byte() ~= proxy.COM_QUERY then
return
end
--[[
To be on the safe side, we clean the params that may trigger
behavior on read_query_result
--]]
xtab_params = {}
xtab_error_status = 0
local query = packet:sub(2)
--
-- simple tokeninzing the query, looking for accepted pattern
--
local option, table_name, row_field, col_field , op, op_col , summary
local query_tokens = tokenizer.tokenize(query)
local START_TOKEN = 0
if ( query_tokens[1]['text']:lower() == 'xtab' )
then
START_TOKEN = 1
option = query_tokens[2]['text']
elseif ( query_tokens[1]['text']:lower() == 'select'
and
query_tokens[2]['text']:lower() == 'xtab' )
then
START_TOKEN = 2
option = query_tokens[3]['text']
else
return
end
--[[
First, checking for short patterns
XTAB HELP
XTAB VERSION
--]]
print_debug('received query ' .. query)
if query_tokens[ START_TOKEN + 2 ] == nil then
if (option:lower() == 'help') then
proxy.response.resultset = xtab_help_resultset
elseif option:lower() == 'version' then
proxy.response.resultset = xtab_version_resultset
elseif option:lower() == 'query' then
xtab_query_resultset.rows[7] = { 'Current setting: returns a query' }
proxy.response.resultset = xtab_query_resultset
return_xtab_query = true
elseif option:lower() == 'noquery' then
xtab_query_resultset.rows[7] = { 'Current setting: returns a result set' }
proxy.response.resultset = xtab_query_resultset
return_xtab_query = false
else
proxy.response.resultset = xtab_unknown_resultset
end
proxy.response.type = proxy.MYSQLD_PACKET_OK
return proxy.PROXY_SEND_RESULT
end
--
-- parsing the query for a xtab recognized command
--
table_name = option
row_field = query_tokens[START_TOKEN + 2 ]['text']
col_field = query_tokens[START_TOKEN + 3 ]['text']
op = query_tokens[START_TOKEN + 4 ]['text']
op_col = query_tokens[START_TOKEN + 5 ]['text']
if (query_tokens[START_TOKEN + 6 ] ) then
summary = query_tokens[START_TOKEN + 6 ]['text']
else
summary = ''
end
if op_col then
print_debug (string.format("<xtab> <%s> (%s) (%s) [%s] [%s]",
table_name, row_field, col_field, op, op_col ))
else
return nil
end
--[[
At this point, at least in all appearance, we are dealing
with a full XTAB command
Now checking for recognized operators
]]
local recognized_operator = 0
for i,v in pairs(allowed_operators) do
if string.lower(op) == v then
recognized_operator = 1
end
end
if recognized_operator == 0 then
print_debug('unknown operator ' .. op)
proxy.response.type = proxy.MYSQLD_PACKET_OK
proxy.response.resultset = xtab_unknown_operator
return proxy.PROXY_SEND_RESULT
end
--[[
records the xtab parameters for further usage
in the read_query_result function
--]]
xtab_params['table_name'] = table_name
xtab_params['row_header'] = row_field
xtab_params['col_header'] = col_field
xtab_params['operation'] = op
xtab_params['op_col'] = op_col
xtab_params['summary'] = summary:lower() == 'summary'
print_debug('summary: ' .. tostring(xtab_params['summary']))
--[[
Making sure that group_concat is large enough.
The result of this query will be ignored
--]]
proxy.queries:append(xtab_id_before,
string.char(proxy.COM_QUERY) ..
"set group_concat_max_len = 1024*1024",
{ resultset_is_needed = true })
--[[
If further queries need to be executed before the
one that gets the distinct values for columns,
use an ID larger than xtab_id_before and smaller than
xtab_id_start
--]]
--[[
Getting all distinct values for the given column.
This query will be used to create the final xtab query
in read_query_result()
--]]
proxy.queries:append(xtab_id_start,
string.char(proxy.COM_QUERY) ..
string.format([[
select group_concat( distinct concat(
'%s(if( `%s`= ', quote(%s),',`%s`,null)) as `%s_',%s,'`' )
order by `%s` ) from `%s` order by `%s`]],
op,
col_field,
col_field,
op_col,
col_field,
col_field,
col_field,
table_name,
col_field
),
{ resultset_is_needed = true }
)
return proxy.PROXY_SEND_QUERY
end
function read_query_result(inj)
print_debug ( 'injection id ' .. inj.id ..
' error status: ' .. xtab_error_status)
if xtab_error_status > 0 then
print_debug('ignoring resultset ' .. inj.id ..
' for previous error')
return proxy.PROXY_IGNORE_RESULT
end
local res = assert(inj.resultset)
--
-- on error, empty the query queue and return the error message
--
if res.query_status and (res.query_status < 0 ) then
xtab_error_status = 1
print_debug('sending result' .. inj.id .. ' on error ')
proxy.queries:reset()
return
end
--
-- ignoring the preparatory queries
--
if (inj.id >= xtab_id_before) and (inj.id < xtab_id_start) then
print_debug ('ignoring preparatory query from xtab ' .. inj.id )
return proxy.PROXY_IGNORE_RESULT
end
--
-- creating the XTAB query
--
if (inj.id == xtab_id_start) then
print_debug ('getting columns resultset from xtab ' .. inj.id )
local col_query = ''
for row in inj.resultset.rows do
col_query = col_query .. row[1]
end
print_debug ('column values : ' .. col_query)
col_query = col_query:gsub(
',' .. xtab_params['operation'], '\n, '
.. xtab_params['operation'])
local xtab_query = string.format([[
SELECT
%s ,
%s
, %s(`%s`) AS total
FROM %s
GROUP BY %s
]],
xtab_params['row_header'],
col_query,
xtab_params['operation'],
xtab_params['op_col'],
xtab_params['table_name'],
xtab_params['row_header']
)
if xtab_params['summary'] == true then
xtab_query = xtab_query .. ' WITH ROLLUP '
end
--
-- if the query was requested, it is returned immediately
--
if (return_xtab_query == true) then
proxy.queries:reset()
proxy.response.type = proxy.MYSQLD_PACKET_OK
proxy.response.resultset = {
fields = {
{ type = proxy.MYSQL_TYPE_STRING, name = 'XTAB query'}
},
rows = {
{ xtab_query }
}
}
return proxy.PROXY_SEND_RESULT
end
--
-- The XTAB query is executed
--
proxy.queries:append(xtab_id_exec, string.char(proxy.COM_QUERY) .. xtab_query,
{ resultset_is_needed = true })
print_debug (xtab_query, 2)
return proxy.PROXY_IGNORE_RESULT
end
--
-- Getting the final xtab result
--
if (inj.id == xtab_id_exec) then
print_debug ('getting final xtab result ' .. inj.id )
--
-- Replacing the default NULL value provided by WITH ROLLUP
-- with a more human readable value
--
if xtab_params['summary'] == true then
local updated_rows = {}
local updated_fields = {}
for row in inj.resultset.rows do
if row[1] == nil then
row[1] = 'Grand Total'
end
table.insert(updated_rows , row)
end
local field_count = 1
local fields = inj.resultset.fields
while fields[field_count] do
table.insert(updated_fields, {
type = fields[field_count].type ,
name = fields[field_count].name } )
field_count = field_count + 1
end
proxy.response.resultset = {
fields = updated_fields,
rows = updated_rows
}
proxy.response.type = proxy.MYSQLD_PACKET_OK
return proxy.PROXY_SEND_RESULT
end
return
end
end
function print_debug (msg, min_level)
if not min_level then
min_level = 1
end
if DEBUG and (DEBUG >= min_level) then
print(msg)
end
end
| gpl-2.0 |
silverhammermba/awesome | tests/examples/shims/screen.lua | 1 | 2662 | local gears_obj = require("gears.object")
local screen, meta = awesome._shim_fake_class()
screen.count = 1
local function create_screen(args)
local s = gears_obj()
s.data = {}
-- Copy the geo in case the args are mutated
local geo = {
x = args.x ,
y = args.y ,
width = args.width ,
height = args.height,
}
function s._resize(args2)
geo.x = args2.x or geo.x
geo.y = args2.y or geo.y
geo.width = args2.width or geo.width
geo.height = args2.height or geo.height
end
local wa = args.workarea_sides or 10
return setmetatable(s,{ __index = function(_, key)
if key == "geometry" then
return {
x = geo.x or 0,
y = geo.y or 0,
width = geo.width ,
height = geo.height,
}
elseif key == "workarea" then
return {
x = (geo.x or 0) + wa ,
y = (geo.y or 0) + wa ,
width = geo.width - 2*wa,
height = geo.height - 2*wa,
}
else
return meta.__index(_, key)
end
end,
__newindex = function(...) return meta.__newindex(...) end
})
end
local screens = {}
function screen._add_screen(args)
local s = create_screen(args)
table.insert(screens, s)
s.index = #screens
screen[#screen+1] = s
screen[s] = s
end
function screen._get_extents()
local xmax, ymax
for _, v in ipairs(screen) do
if not xmax or v.geometry.x+v.geometry.width > xmax.geometry.x+xmax.geometry.width then
xmax = v
end
if not ymax or v.geometry.y+v.geometry.height > ymax.geometry.y+ymax.geometry.height then
ymax = v
end
end
return xmax.geometry.x+xmax.geometry.width, ymax.geometry.y+ymax.geometry.height
end
function screen._clear()
for i=1, #screen do
screen[screen[i]] = nil
screen[i] = nil
end
screens = {}
end
function screen._setup_grid(w, h, rows, args)
args = args or {}
screen._clear()
for i, row in ipairs(rows) do
for j=1, row do
args.x = (j-1)*w + (j-1)*10
args.y = (i-1)*h + (i-1)*10
args.width = w
args.height = h
screen._add_screen(args)
end
end
end
screen._add_screen {width=320, height=240}
return screen
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| gpl-2.0 |
mqmaker/witi-openwrt | package/ramips/ui/luci-mtk/src/libs/nixio/docsrc/nixio.lua | 151 | 15824 | --- General POSIX IO library.
module "nixio"
--- Look up a hostname and service via DNS.
-- @class function
-- @name nixio.getaddrinfo
-- @param host hostname to lookup (optional)
-- @param family address family [<strong>"any"</strong>, "inet", "inet6"]
-- @param service service name or port (optional)
-- @return Table containing one or more tables containing: <ul>
-- <li>family = ["inet", "inet6"]</li>
-- <li>socktype = ["stream", "dgram", "raw"]</li>
-- <li>address = Resolved IP-Address</li>
-- <li>port = Resolved Port (if service was given)</li>
-- </ul>
--- Reverse look up an IP-Address via DNS.
-- @class function
-- @name nixio.getnameinfo
-- @param ipaddr IPv4 or IPv6-Address
-- @return FQDN
--- (Linux, BSD) Get a list of available network interfaces and their addresses.
-- @class function
-- @name nixio.getifaddrs
-- @return Table containing one or more tables containing: <ul>
-- <li>name = Interface Name</li>
-- <li>family = ["inet", "inet6", "packet"]</li>
-- <li>addr = Interface Address (IPv4, IPv6, MAC, ...)</li>
-- <li>broadaddr = Broadcast Address</li>
-- <li>dstaddr = Destination Address (Point-to-Point)</li>
-- <li>netmask = Netmask (if available)</li>
-- <li>prefix = Prefix (if available)</li>
-- <li>flags = Table of interface flags (up, multicast, loopback, ...)</li>
-- <li>data = Statistics (Linux, "packet"-family)</li>
-- <li>hatype = Hardware Type Identifier (Linix, "packet"-family)</li>
-- <li>ifindex = Interface Index (Linux, "packet"-family)</li>
-- </ul>
--- Get protocol entry by name.
-- @usage This function returns nil if the given protocol is unknown.
-- @class function
-- @name nixio.getprotobyname
-- @param name protocol name to lookup
-- @return Table containing the following fields: <ul>
-- <li>name = Protocol Name</li>
-- <li>proto = Protocol Number</li>
-- <li>aliases = Table of alias names</li>
-- </ul>
--- Get protocol entry by number.
-- @usage This function returns nil if the given protocol is unknown.
-- @class function
-- @name nixio.getprotobynumber
-- @param proto protocol number to lookup
-- @return Table containing the following fields: <ul>
-- <li>name = Protocol Name</li>
-- <li>proto = Protocol Number</li>
-- <li>aliases = Table of alias names</li>
-- </ul>
--- Get all or a specifc proto entry.
-- @class function
-- @name nixio.getproto
-- @param proto protocol number or name to lookup (optional)
-- @return Table (or if no parameter is given, a table of tables)
-- containing the following fields: <ul>
-- <li>name = Protocol Name</li>
-- <li>proto = Protocol Number</li>
-- <li>aliases = Table of alias names</li>
-- </ul>
--- Create a new socket and bind it to a network address.
-- This function is a shortcut for calling nixio.socket and then bind()
-- on the socket object.
-- @usage This functions calls getaddrinfo(), socket(),
-- setsockopt() and bind() but NOT listen().
-- @usage The <em>reuseaddr</em>-option is automatically set before binding.
-- @class function
-- @name nixio.bind
-- @param host Hostname or IP-Address (optional, default: all addresses)
-- @param port Port or service description
-- @param family Address family [<strong>"any"</strong>, "inet", "inet6"]
-- @param socktype Socket Type [<strong>"stream"</strong>, "dgram"]
-- @return Socket Object
--- Create a new socket and connect to a network address.
-- This function is a shortcut for calling nixio.socket and then connect()
-- on the socket object.
-- @usage This functions calls getaddrinfo(), socket() and connect().
-- @class function
-- @name nixio.connect
-- @param host Hostname or IP-Address (optional, default: localhost)
-- @param port Port or service description
-- @param family Address family [<strong>"any"</strong>, "inet", "inet6"]
-- @param socktype Socket Type [<strong>"stream"</strong>, "dgram"]
-- @return Socket Object
--- Open a file.
-- @class function
-- @name nixio.open
-- @usage Although this function also supports the traditional fopen()
-- file flags it does not create a file stream but uses the open() syscall.
-- @param path Filesystem path to open
-- @param flags Flag string or number (see open_flags).
-- [<strong>"r"</strong>, "r+", "w", "w+", "a", "a+"]
-- @param mode File mode for newly created files (see chmod, umask).
-- @see nixio.umask
-- @see nixio.open_flags
-- @return File Object
--- Generate flags for a call to open().
-- @class function
-- @name nixio.open_flags
-- @usage This function cannot fail and will never return nil.
-- @usage The "nonblock" and "ndelay" flags are aliases.
-- @usage The "nonblock", "ndelay" and "sync" flags are no-ops on Windows.
-- @param flag1 First Flag ["append", "creat", "excl", "nonblock", "ndelay",
-- "sync", "trunc", "rdonly", "wronly", "rdwr"]
-- @param ... More Flags [-"-]
-- @return flag to be used as second paramter to open
--- Duplicate a file descriptor.
-- @class function
-- @name nixio.dup
-- @usage This funcation calls dup2() if <em>newfd</em> is set, otherwise dup().
-- @param oldfd Old descriptor [File Object, Socket Object (POSIX only)]
-- @param newfd New descriptor to serve as copy (optional)
-- @return File Object of new descriptor
--- Create a pipe.
-- @class function
-- @name nixio.pipe
-- @return File Object of the read end
-- @return File Object of the write end
--- Get the last system error code.
-- @class function
-- @name nixio.errno
-- @return Error code
--- Get the error message for the corresponding error code.
-- @class function
-- @name nixio.strerror
-- @param errno System error code
-- @return Error message
--- Sleep for a specified amount of time.
-- @class function
-- @usage Not all systems support nanosecond precision but you can expect
-- to have at least maillisecond precision.
-- @usage This function is not signal-protected and may fail with EINTR.
-- @param seconds Seconds to wait (optional)
-- @param nanoseconds Nanoseconds to wait (optional)
-- @name nixio.nanosleep
-- @return true
--- Generate events-bitfield or parse revents-bitfield for poll.
-- @class function
-- @name nixio.poll_flags
-- @param mode1 revents-Flag bitfield returned from poll to parse OR
-- ["in", "out", "err", "pri" (POSIX), "hup" (POSIX), "nval" (POSIX)]
-- @param ... More mode strings for generating the flag [-"-]
-- @see nixio.poll
-- @return table with boolean fields reflecting the mode parameter
-- <strong>OR</strong> bitfield to use for the events-Flag field
--- Wait for some event on a file descriptor.
-- poll() sets the revents-field of the tables provided by fds to a bitfield
-- indicating the events that occured.
-- @class function
-- @usage This function works in-place on the provided table and only
-- writes the revents field, you can use other fields on your demand.
-- @usage All metamethods on the tables provided as fds are ignored.
-- @usage The revents-fields are not reset when the call times out.
-- You have to check the first return value to be 0 to handle this case.
-- @usage If you want to wait on a TLS-Socket you have to use the underlying
-- socket instead.
-- @usage On Windows poll is emulated through select(), can only be used
-- on socket descriptors and cannot take more than 64 descriptors per call.
-- @usage This function is not signal-protected and may fail with EINTR.
-- @param fds Table containing one or more tables containing <ul>
-- <li> fd = I/O Descriptor [Socket Object, File Object (POSIX)]</li>
-- <li> events = events to wait for (bitfield generated with poll_flags)</li>
-- </ul>
-- @param timeout Timeout in milliseconds
-- @name nixio.poll
-- @see nixio.poll_flags
-- @return number of ready IO descriptors
-- @return the fds-table with revents-fields set
--- (POSIX) Clone the current process.
-- @class function
-- @name nixio.fork
-- @return the child process id for the parent process, 0 for the child process
--- (POSIX) Send a signal to one or more processes.
-- @class function
-- @name nixio.kill
-- @param target Target process of process group.
-- @param signal Signal to send
-- @return true
--- (POSIX) Get the parent process id of the current process.
-- @class function
-- @name nixio.getppid
-- @return parent process id
--- (POSIX) Get the user id of the current process.
-- @class function
-- @name nixio.getuid
-- @return process user id
--- (POSIX) Get the group id of the current process.
-- @class function
-- @name nixio.getgid
-- @return process group id
--- (POSIX) Set the group id of the current process.
-- @class function
-- @name nixio.setgid
-- @param gid New Group ID
-- @return true
--- (POSIX) Set the user id of the current process.
-- @class function
-- @name nixio.setuid
-- @param gid New User ID
-- @return true
--- (POSIX) Change priority of current process.
-- @class function
-- @name nixio.nice
-- @param nice Nice Value
-- @return true
--- (POSIX) Create a new session and set the process group ID.
-- @class function
-- @name nixio.setsid
-- @return session id
--- (POSIX) Wait for a process to change state.
-- @class function
-- @name nixio.waitpid
-- @usage If the "nohang" is given this function becomes non-blocking.
-- @param pid Process ID (optional, default: any childprocess)
-- @param flag1 Flag (optional) ["nohang", "untraced", "continued"]
-- @param ... More Flags [-"-]
-- @return process id of child or 0 if no child has changed state
-- @return ["exited", "signaled", "stopped"]
-- @return [exit code, terminate signal, stop signal]
--- (POSIX) Get process times.
-- @class function
-- @name nixio.times
-- @return Table containing: <ul>
-- <li>utime = user time</li>
-- <li>utime = system time</li>
-- <li>cutime = children user time</li>
-- <li>cstime = children system time</li>
-- </ul>
--- (POSIX) Get information about current system and kernel.
-- @class function
-- @name nixio.uname
-- @return Table containing: <ul>
-- <li>sysname = operating system</li>
-- <li>nodename = network name (usually hostname)</li>
-- <li>release = OS release</li>
-- <li>version = OS version</li>
-- <li>machine = hardware identifier</li>
-- </ul>
--- Change the working directory.
-- @class function
-- @name nixio.chdir
-- @param path New working directory
-- @return true
--- Ignore or use set the default handler for a signal.
-- @class function
-- @name nixio.signal
-- @param signal Signal
-- @param handler ["ign", "dfl"]
-- @return true
--- Get the ID of the current process.
-- @class function
-- @name nixio.getpid
-- @return process id
--- Get the current working directory.
-- @class function
-- @name nixio.getcwd
-- @return workign directory
--- Get the current environment table or a specific environment variable.
-- @class function
-- @name nixio.getenv
-- @param variable Variable (optional)
-- @return environment table or single environment variable
--- Set or unset a environment variable.
-- @class function
-- @name nixio.setenv
-- @usage The environment variable will be unset if value is ommited.
-- @param variable Variable
-- @param value Value (optional)
-- @return true
--- Execute a file to replace the current process.
-- @class function
-- @name nixio.exec
-- @usage The name of the executable is automatically passed as argv[0]
-- @usage This function does not return on success.
-- @param executable Executable
-- @param ... Parameters
--- Invoke the shell and execute a file to replace the current process.
-- @class function
-- @name nixio.execp
-- @usage The name of the executable is automatically passed as argv[0]
-- @usage This function does not return on success.
-- @param executable Executable
-- @param ... Parameters
--- Execute a file with a custom environment to replace the current process.
-- @class function
-- @name nixio.exece
-- @usage The name of the executable is automatically passed as argv[0]
-- @usage This function does not return on success.
-- @param executable Executable
-- @param arguments Argument Table
-- @param environment Environment Table (optional)
--- Sets the file mode creation mask.
-- @class function
-- @name nixio.umask
-- @param mask New creation mask (see chmod for format specifications)
-- @return the old umask as decimal mode number
-- @return the old umask as mode string
--- (Linux) Get overall system statistics.
-- @class function
-- @name nixio.sysinfo
-- @return Table containing: <ul>
-- <li>uptime = system uptime in seconds</li>
-- <li>loads = {loadavg1, loadavg5, loadavg15}</li>
-- <li>totalram = total RAM</li>
-- <li>freeram = free RAM</li>
-- <li>sharedram = shared RAM</li>
-- <li>bufferram = buffered RAM</li>
-- <li>totalswap = total SWAP</li>
-- <li>freeswap = free SWAP</li>
-- <li>procs = number of running processes</li>
-- </ul>
--- Create a new socket.
-- @class function
-- @name nixio.socket
-- @param domain Domain ["inet", "inet6", "unix"]
-- @param type Type ["stream", "dgram", "raw"]
-- @return Socket Object
--- (POSIX) Send data from a file to a socket in kernel-space.
-- @class function
-- @name nixio.sendfile
-- @param socket Socket Object
-- @param file File Object
-- @param length Amount of data to send (in Bytes).
-- @return bytes sent
--- (Linux) Send data from / to a pipe in kernel-space.
-- @class function
-- @name nixio.splice
-- @param fdin Input I/O descriptor
-- @param fdout Output I/O descriptor
-- @param length Amount of data to send (in Bytes).
-- @param flags (optional, bitfield generated by splice_flags)
-- @see nixio.splice_flags
-- @return bytes sent
--- (Linux) Generate a flag bitfield for a call to splice.
-- @class function
-- @name nixio.splice_flags
-- @param flag1 First Flag ["move", "nonblock", "more"]
-- @param ... More flags [-"-]
-- @see nixio.splice
-- @return Flag bitfield
--- (POSIX) Open a connection to the system logger.
-- @class function
-- @name nixio.openlog
-- @param ident Identifier
-- @param flag1 Flag 1 ["cons", "nowait", "pid", "perror", "ndelay", "odelay"]
-- @param ... More flags [-"-]
--- (POSIX) Close the connection to the system logger.
-- @class function
-- @name nixio.closelog
--- (POSIX) Write a message to the system logger.
-- @class function
-- @name nixio.syslog
-- @param priority Priority ["emerg", "alert", "crit", "err", "warning",
-- "notice", "info", "debug"]
-- @param message
--- (POSIX) Set the logmask of the system logger for current process.
-- @class function
-- @name nixio.setlogmask
-- @param priority Priority ["emerg", "alert", "crit", "err", "warning",
-- "notice", "info", "debug"]
--- (POSIX) Encrypt a user password.
-- @class function
-- @name nixio.crypt
-- @param key Key
-- @param salt Salt
-- @return password hash
--- (POSIX) Get all or a specific user group.
-- @class function
-- @name nixio.getgr
-- @param group Group ID or groupname (optional)
-- @return Table containing: <ul>
-- <li>name = Group Name</li>
-- <li>gid = Group ID</li>
-- <li>passwd = Password</li>
-- <li>mem = {Member #1, Member #2, ...}</li>
-- </ul>
--- (POSIX) Get all or a specific user account.
-- @class function
-- @name nixio.getpw
-- @param user User ID or username (optional)
-- @return Table containing: <ul>
-- <li>name = Name</li>
-- <li>uid = ID</li>
-- <li>gid = Group ID</li>
-- <li>passwd = Password</li>
-- <li>dir = Home directory</li>
-- <li>gecos = Information</li>
-- <li>shell = Shell</li>
-- </ul>
--- (Linux, Solaris) Get all or a specific shadow password entry.
-- @class function
-- @name nixio.getsp
-- @param user username (optional)
-- @return Table containing: <ul>
-- <li>namp = Name</li>
-- <li>expire = Expiration Date</li>
-- <li>flag = Flags</li>
-- <li>inact = Inactivity Date</li>
-- <li>lstchg = Last change</li>
-- <li>max = Maximum</li>
-- <li>min = Minimum</li>
-- <li>warn = Warning</li>
-- <li>pwdp = Password Hash</li>
-- </ul>
--- Create a new TLS context.
-- @class function
-- @name nixio.tls
-- @param mode TLS-Mode ["client", "server"]
-- @return TLSContext Object
| gpl-2.0 |
cshore/luci | modules/luci-mod-admin-full/luasrc/model/cbi/admin_network/wifi.lua | 3 | 38983 | -- Copyright 2008 Steven Barth <steven@midlink.org>
-- Licensed to the public under the Apache License 2.0.
local wa = require "luci.tools.webadmin"
local nw = require "luci.model.network"
local ut = require "luci.util"
local nt = require "luci.sys".net
local fs = require "nixio.fs"
arg[1] = arg[1] or ""
m = Map("wireless", "",
translate("The <em>Device Configuration</em> section covers physical settings of the radio " ..
"hardware such as channel, transmit power or antenna selection which are shared among all " ..
"defined wireless networks (if the radio hardware is multi-SSID capable). Per network settings " ..
"like encryption or operation mode are grouped in the <em>Interface Configuration</em>."))
m:chain("network")
m:chain("firewall")
m.redirect = luci.dispatcher.build_url("admin/network/wireless")
local ifsection
function m.on_commit(map)
local wnet = nw:get_wifinet(arg[1])
if ifsection and wnet then
ifsection.section = wnet.sid
m.title = luci.util.pcdata(wnet:get_i18n())
end
end
nw.init(m.uci)
local wnet = nw:get_wifinet(arg[1])
local wdev = wnet and wnet:get_device()
-- redirect to overview page if network does not exist anymore (e.g. after a revert)
if not wnet or not wdev then
luci.http.redirect(luci.dispatcher.build_url("admin/network/wireless"))
return
end
-- wireless toggle was requested, commit and reload page
function m.parse(map)
if m:formvalue("cbid.wireless.%s.__toggle" % wdev:name()) then
if wdev:get("disabled") == "1" or wnet:get("disabled") == "1" then
wnet:set("disabled", nil)
else
wnet:set("disabled", "1")
end
wdev:set("disabled", nil)
nw:commit("wireless")
luci.sys.call("(env -i /bin/ubus call network reload) >/dev/null 2>/dev/null")
luci.http.redirect(luci.dispatcher.build_url("admin/network/wireless", arg[1]))
return
end
Map.parse(map)
end
m.title = luci.util.pcdata(wnet:get_i18n())
local function txpower_list(iw)
local list = iw.txpwrlist or { }
local off = tonumber(iw.txpower_offset) or 0
local new = { }
local prev = -1
local _, val
for _, val in ipairs(list) do
local dbm = val.dbm + off
local mw = math.floor(10 ^ (dbm / 10))
if mw ~= prev then
prev = mw
new[#new+1] = {
display_dbm = dbm,
display_mw = mw,
driver_dbm = val.dbm,
driver_mw = val.mw
}
end
end
return new
end
local function txpower_current(pwr, list)
pwr = tonumber(pwr)
if pwr ~= nil then
local _, item
for _, item in ipairs(list) do
if item.driver_dbm >= pwr then
return item.driver_dbm
end
end
end
return (list[#list] and list[#list].driver_dbm) or pwr or 0
end
local iw = luci.sys.wifi.getiwinfo(arg[1])
local hw_modes = iw.hwmodelist or { }
local tx_power_list = txpower_list(iw)
local tx_power_cur = txpower_current(wdev:get("txpower"), tx_power_list)
s = m:section(NamedSection, wdev:name(), "wifi-device", translate("Device Configuration"))
s.addremove = false
s:tab("general", translate("General Setup"))
s:tab("macfilter", translate("MAC-Filter"))
s:tab("advanced", translate("Advanced Settings"))
--[[
back = s:option(DummyValue, "_overview", translate("Overview"))
back.value = ""
back.titleref = luci.dispatcher.build_url("admin", "network", "wireless")
]]
st = s:taboption("general", DummyValue, "__status", translate("Status"))
st.template = "admin_network/wifi_status"
st.ifname = arg[1]
en = s:taboption("general", Button, "__toggle")
if wdev:get("disabled") == "1" or wnet:get("disabled") == "1" then
en.title = translate("Wireless network is disabled")
en.inputtitle = translate("Enable")
en.inputstyle = "apply"
else
en.title = translate("Wireless network is enabled")
en.inputtitle = translate("Disable")
en.inputstyle = "reset"
end
local hwtype = wdev:get("type")
-- NanoFoo
local nsantenna = wdev:get("antenna")
-- Check whether there are client interfaces on the same radio,
-- if yes, lock the channel choice as these stations will dicatate the freq
local found_sta = nil
local _, net
if wnet:mode() ~= "sta" then
for _, net in ipairs(wdev:get_wifinets()) do
if net:mode() == "sta" and net:get("disabled") ~= "1" then
if not found_sta then
found_sta = {}
found_sta.channel = net:channel()
found_sta.names = {}
end
found_sta.names[#found_sta.names+1] = net:shortname()
end
end
end
if found_sta then
ch = s:taboption("general", DummyValue, "choice", translate("Channel"))
ch.value = translatef("Locked to channel %s used by: %s",
found_sta.channel or "(auto)", table.concat(found_sta.names, ", "))
else
ch = s:taboption("general", Value, "_mode_freq", '<br />'..translate("Operating frequency"))
ch.hwmodes = hw_modes
ch.htmodes = iw.htmodelist
ch.freqlist = iw.freqlist
ch.template = "cbi/wireless_modefreq"
function ch.cfgvalue(self, section)
return {
m:get(section, "hwmode") or "",
m:get(section, "channel") or "auto",
m:get(section, "htmode") or ""
}
end
function ch.formvalue(self, section)
return {
m:formvalue(self:cbid(section) .. ".band") or (hw_modes.g and "11g" or "11a"),
m:formvalue(self:cbid(section) .. ".channel") or "auto",
m:formvalue(self:cbid(section) .. ".htmode") or ""
}
end
function ch.write(self, section, value)
m:set(section, "hwmode", value[1])
m:set(section, "channel", value[2])
m:set(section, "htmode", value[3])
end
end
------------------- MAC80211 Device ------------------
if hwtype == "mac80211" then
if #tx_power_list > 1 then
tp = s:taboption("general", ListValue,
"txpower", translate("Transmit Power"), "dBm")
tp.rmempty = true
tp.default = tx_power_cur
function tp.cfgvalue(...)
return txpower_current(Value.cfgvalue(...), tx_power_list)
end
for _, p in ipairs(tx_power_list) do
tp:value(p.driver_dbm, "%i dBm (%i mW)"
%{ p.display_dbm, p.display_mw })
end
end
local cl = iw and iw.countrylist
if cl and #cl > 0 then
cc = s:taboption("advanced", ListValue, "country", translate("Country Code"), translate("Use ISO/IEC 3166 alpha2 country codes."))
cc.default = tostring(iw and iw.country or "00")
for _, c in ipairs(cl) do
cc:value(c.alpha2, "%s - %s" %{ c.alpha2, c.name })
end
else
s:taboption("advanced", Value, "country", translate("Country Code"), translate("Use ISO/IEC 3166 alpha2 country codes."))
end
s:taboption("advanced", Value, "distance", translate("Distance Optimization"),
translate("Distance to farthest network member in meters."))
-- external antenna profiles
local eal = iw and iw.extant
if eal and #eal > 0 then
ea = s:taboption("advanced", ListValue, "extant", translate("Antenna Configuration"))
for _, eap in ipairs(eal) do
ea:value(eap.id, "%s (%s)" %{ eap.name, eap.description })
if eap.selected then
ea.default = eap.id
end
end
end
s:taboption("advanced", Value, "frag", translate("Fragmentation Threshold"))
s:taboption("advanced", Value, "rts", translate("RTS/CTS Threshold"))
end
------------------- Madwifi Device ------------------
if hwtype == "atheros" then
tp = s:taboption("general",
(#tx_power_list > 0) and ListValue or Value,
"txpower", translate("Transmit Power"), "dBm")
tp.rmempty = true
tp.default = tx_power_cur
function tp.cfgvalue(...)
return txpower_current(Value.cfgvalue(...), tx_power_list)
end
for _, p in ipairs(tx_power_list) do
tp:value(p.driver_dbm, "%i dBm (%i mW)"
%{ p.display_dbm, p.display_mw })
end
s:taboption("advanced", Flag, "diversity", translate("Diversity")).rmempty = false
if not nsantenna then
ant1 = s:taboption("advanced", ListValue, "txantenna", translate("Transmitter Antenna"))
ant1.widget = "radio"
ant1.orientation = "horizontal"
ant1:depends("diversity", "")
ant1:value("0", translate("auto"))
ant1:value("1", translate("Antenna 1"))
ant1:value("2", translate("Antenna 2"))
ant2 = s:taboption("advanced", ListValue, "rxantenna", translate("Receiver Antenna"))
ant2.widget = "radio"
ant2.orientation = "horizontal"
ant2:depends("diversity", "")
ant2:value("0", translate("auto"))
ant2:value("1", translate("Antenna 1"))
ant2:value("2", translate("Antenna 2"))
else -- NanoFoo
local ant = s:taboption("advanced", ListValue, "antenna", translate("Transmitter Antenna"))
ant:value("auto")
ant:value("vertical")
ant:value("horizontal")
ant:value("external")
end
s:taboption("advanced", Value, "distance", translate("Distance Optimization"),
translate("Distance to farthest network member in meters."))
s:taboption("advanced", Value, "regdomain", translate("Regulatory Domain"))
s:taboption("advanced", Value, "country", translate("Country Code"))
s:taboption("advanced", Flag, "outdoor", translate("Outdoor Channels"))
--s:option(Flag, "nosbeacon", translate("Disable HW-Beacon timer"))
end
------------------- Broadcom Device ------------------
if hwtype == "broadcom" then
tp = s:taboption("general",
(#tx_power_list > 0) and ListValue or Value,
"txpower", translate("Transmit Power"), "dBm")
tp.rmempty = true
tp.default = tx_power_cur
function tp.cfgvalue(...)
return txpower_current(Value.cfgvalue(...), tx_power_list)
end
for _, p in ipairs(tx_power_list) do
tp:value(p.driver_dbm, "%i dBm (%i mW)"
%{ p.display_dbm, p.display_mw })
end
mode = s:taboption("advanced", ListValue, "hwmode", translate("Band"))
if hw_modes.b then
mode:value("11b", "2.4GHz (802.11b)")
if hw_modes.g then
mode:value("11bg", "2.4GHz (802.11b+g)")
end
end
if hw_modes.g then
mode:value("11g", "2.4GHz (802.11g)")
mode:value("11gst", "2.4GHz (802.11g + Turbo)")
mode:value("11lrs", "2.4GHz (802.11g Limited Rate Support)")
end
if hw_modes.a then mode:value("11a", "5GHz (802.11a)") end
if hw_modes.n then
if hw_modes.g then
mode:value("11ng", "2.4GHz (802.11g+n)")
mode:value("11n", "2.4GHz (802.11n)")
end
if hw_modes.a then
mode:value("11na", "5GHz (802.11a+n)")
mode:value("11n", "5GHz (802.11n)")
end
htmode = s:taboption("advanced", ListValue, "htmode", translate("HT mode (802.11n)"))
htmode:depends("hwmode", "11ng")
htmode:depends("hwmode", "11na")
htmode:depends("hwmode", "11n")
htmode:value("HT20", "20MHz")
htmode:value("HT40", "40MHz")
end
ant1 = s:taboption("advanced", ListValue, "txantenna", translate("Transmitter Antenna"))
ant1.widget = "radio"
ant1:depends("diversity", "")
ant1:value("3", translate("auto"))
ant1:value("0", translate("Antenna 1"))
ant1:value("1", translate("Antenna 2"))
ant2 = s:taboption("advanced", ListValue, "rxantenna", translate("Receiver Antenna"))
ant2.widget = "radio"
ant2:depends("diversity", "")
ant2:value("3", translate("auto"))
ant2:value("0", translate("Antenna 1"))
ant2:value("1", translate("Antenna 2"))
s:taboption("advanced", Flag, "frameburst", translate("Frame Bursting"))
s:taboption("advanced", Value, "distance", translate("Distance Optimization"))
--s:option(Value, "slottime", translate("Slot time"))
s:taboption("advanced", Value, "country", translate("Country Code"))
s:taboption("advanced", Value, "maxassoc", translate("Connection Limit"))
end
--------------------- HostAP Device ---------------------
if hwtype == "prism2" then
s:taboption("advanced", Value, "txpower", translate("Transmit Power"), "att units").rmempty = true
s:taboption("advanced", Flag, "diversity", translate("Diversity")).rmempty = false
s:taboption("advanced", Value, "txantenna", translate("Transmitter Antenna"))
s:taboption("advanced", Value, "rxantenna", translate("Receiver Antenna"))
end
----------------------- Interface -----------------------
s = m:section(NamedSection, wnet.sid, "wifi-iface", translate("Interface Configuration"))
ifsection = s
s.addremove = false
s.anonymous = true
s.defaults.device = wdev:name()
s:tab("general", translate("General Setup"))
s:tab("encryption", translate("Wireless Security"))
s:tab("macfilter", translate("MAC-Filter"))
s:tab("advanced", translate("Advanced Settings"))
ssid = s:taboption("general", Value, "ssid", translate("<abbr title=\"Extended Service Set Identifier\">ESSID</abbr>"))
ssid.datatype = "maxlength(32)"
mode = s:taboption("general", ListValue, "mode", translate("Mode"))
mode.override_values = true
mode:value("ap", translate("Access Point"))
mode:value("sta", translate("Client"))
mode:value("adhoc", translate("Ad-Hoc"))
bssid = s:taboption("general", Value, "bssid", translate("<abbr title=\"Basic Service Set Identifier\">BSSID</abbr>"))
network = s:taboption("general", Value, "network", translate("Network"),
translate("Choose the network(s) you want to attach to this wireless interface or " ..
"fill out the <em>create</em> field to define a new network."))
network.rmempty = true
network.template = "cbi/network_netlist"
network.widget = "checkbox"
network.novirtual = true
function network.write(self, section, value)
local i = nw:get_interface(section)
if i then
if value == '-' then
value = m:formvalue(self:cbid(section) .. ".newnet")
if value and #value > 0 then
local n = nw:add_network(value, {proto="none"})
if n then n:add_interface(i) end
else
local n = i:get_network()
if n then n:del_interface(i) end
end
else
local v
for _, v in ipairs(i:get_networks()) do
v:del_interface(i)
end
for v in ut.imatch(value) do
local n = nw:get_network(v)
if n then
if not n:is_empty() then
n:set("type", "bridge")
end
n:add_interface(i)
end
end
end
end
end
-------------------- MAC80211 Interface ----------------------
if hwtype == "mac80211" then
if fs.access("/usr/sbin/iw") then
mode:value("mesh", "802.11s")
end
mode:value("ahdemo", translate("Pseudo Ad-Hoc (ahdemo)"))
mode:value("monitor", translate("Monitor"))
bssid:depends({mode="adhoc"})
bssid:depends({mode="sta"})
bssid:depends({mode="sta-wds"})
mp = s:taboption("macfilter", ListValue, "macfilter", translate("MAC-Address Filter"))
mp:depends({mode="ap"})
mp:depends({mode="ap-wds"})
mp:value("", translate("disable"))
mp:value("allow", translate("Allow listed only"))
mp:value("deny", translate("Allow all except listed"))
ml = s:taboption("macfilter", DynamicList, "maclist", translate("MAC-List"))
ml.datatype = "macaddr"
ml:depends({macfilter="allow"})
ml:depends({macfilter="deny"})
nt.mac_hints(function(mac, name) ml:value(mac, "%s (%s)" %{ mac, name }) end)
mode:value("ap-wds", "%s (%s)" % {translate("Access Point"), translate("WDS")})
mode:value("sta-wds", "%s (%s)" % {translate("Client"), translate("WDS")})
function mode.write(self, section, value)
if value == "ap-wds" then
ListValue.write(self, section, "ap")
m.uci:set("wireless", section, "wds", 1)
elseif value == "sta-wds" then
ListValue.write(self, section, "sta")
m.uci:set("wireless", section, "wds", 1)
else
ListValue.write(self, section, value)
m.uci:delete("wireless", section, "wds")
end
end
function mode.cfgvalue(self, section)
local mode = ListValue.cfgvalue(self, section)
local wds = m.uci:get("wireless", section, "wds") == "1"
if mode == "ap" and wds then
return "ap-wds"
elseif mode == "sta" and wds then
return "sta-wds"
else
return mode
end
end
hidden = s:taboption("general", Flag, "hidden", translate("Hide <abbr title=\"Extended Service Set Identifier\">ESSID</abbr>"))
hidden:depends({mode="ap"})
hidden:depends({mode="ap-wds"})
wmm = s:taboption("general", Flag, "wmm", translate("WMM Mode"))
wmm:depends({mode="ap"})
wmm:depends({mode="ap-wds"})
wmm.default = wmm.enabled
ifname = s:taboption("advanced", Value, "ifname", translate("Interface name"), translate("Override default interface name"))
ifname.optional = true
end
-------------------- Madwifi Interface ----------------------
if hwtype == "atheros" then
mode:value("ahdemo", translate("Pseudo Ad-Hoc (ahdemo)"))
mode:value("monitor", translate("Monitor"))
mode:value("ap-wds", "%s (%s)" % {translate("Access Point"), translate("WDS")})
mode:value("sta-wds", "%s (%s)" % {translate("Client"), translate("WDS")})
mode:value("wds", translate("Static WDS"))
function mode.write(self, section, value)
if value == "ap-wds" then
ListValue.write(self, section, "ap")
m.uci:set("wireless", section, "wds", 1)
elseif value == "sta-wds" then
ListValue.write(self, section, "sta")
m.uci:set("wireless", section, "wds", 1)
else
ListValue.write(self, section, value)
m.uci:delete("wireless", section, "wds")
end
end
function mode.cfgvalue(self, section)
local mode = ListValue.cfgvalue(self, section)
local wds = m.uci:get("wireless", section, "wds") == "1"
if mode == "ap" and wds then
return "ap-wds"
elseif mode == "sta" and wds then
return "sta-wds"
else
return mode
end
end
bssid:depends({mode="adhoc"})
bssid:depends({mode="ahdemo"})
bssid:depends({mode="wds"})
wdssep = s:taboption("advanced", Flag, "wdssep", translate("Separate WDS"))
wdssep:depends({mode="ap-wds"})
s:taboption("advanced", Flag, "doth", "802.11h")
hidden = s:taboption("general", Flag, "hidden", translate("Hide <abbr title=\"Extended Service Set Identifier\">ESSID</abbr>"))
hidden:depends({mode="ap"})
hidden:depends({mode="adhoc"})
hidden:depends({mode="ap-wds"})
hidden:depends({mode="sta-wds"})
isolate = s:taboption("advanced", Flag, "isolate", translate("Separate Clients"),
translate("Prevents client-to-client communication"))
isolate:depends({mode="ap"})
s:taboption("advanced", Flag, "bgscan", translate("Background Scan"))
mp = s:taboption("macfilter", ListValue, "macpolicy", translate("MAC-Address Filter"))
mp:value("", translate("disable"))
mp:value("allow", translate("Allow listed only"))
mp:value("deny", translate("Allow all except listed"))
ml = s:taboption("macfilter", DynamicList, "maclist", translate("MAC-List"))
ml.datatype = "macaddr"
ml:depends({macpolicy="allow"})
ml:depends({macpolicy="deny"})
nt.mac_hints(function(mac, name) ml:value(mac, "%s (%s)" %{ mac, name }) end)
s:taboption("advanced", Value, "rate", translate("Transmission Rate"))
s:taboption("advanced", Value, "mcast_rate", translate("Multicast Rate"))
s:taboption("advanced", Value, "frag", translate("Fragmentation Threshold"))
s:taboption("advanced", Value, "rts", translate("RTS/CTS Threshold"))
s:taboption("advanced", Value, "minrate", translate("Minimum Rate"))
s:taboption("advanced", Value, "maxrate", translate("Maximum Rate"))
s:taboption("advanced", Flag, "compression", translate("Compression"))
s:taboption("advanced", Flag, "bursting", translate("Frame Bursting"))
s:taboption("advanced", Flag, "turbo", translate("Turbo Mode"))
s:taboption("advanced", Flag, "ff", translate("Fast Frames"))
s:taboption("advanced", Flag, "wmm", translate("WMM Mode"))
s:taboption("advanced", Flag, "xr", translate("XR Support"))
s:taboption("advanced", Flag, "ar", translate("AR Support"))
local swm = s:taboption("advanced", Flag, "sw_merge", translate("Disable HW-Beacon timer"))
swm:depends({mode="adhoc"})
local nos = s:taboption("advanced", Flag, "nosbeacon", translate("Disable HW-Beacon timer"))
nos:depends({mode="sta"})
nos:depends({mode="sta-wds"})
local probereq = s:taboption("advanced", Flag, "probereq", translate("Do not send probe responses"))
probereq.enabled = "0"
probereq.disabled = "1"
end
-------------------- Broadcom Interface ----------------------
if hwtype == "broadcom" then
mode:value("wds", translate("WDS"))
mode:value("monitor", translate("Monitor"))
hidden = s:taboption("general", Flag, "hidden", translate("Hide <abbr title=\"Extended Service Set Identifier\">ESSID</abbr>"))
hidden:depends({mode="ap"})
hidden:depends({mode="adhoc"})
hidden:depends({mode="wds"})
isolate = s:taboption("advanced", Flag, "isolate", translate("Separate Clients"),
translate("Prevents client-to-client communication"))
isolate:depends({mode="ap"})
s:taboption("advanced", Flag, "doth", "802.11h")
s:taboption("advanced", Flag, "wmm", translate("WMM Mode"))
bssid:depends({mode="wds"})
bssid:depends({mode="adhoc"})
end
----------------------- HostAP Interface ---------------------
if hwtype == "prism2" then
mode:value("wds", translate("WDS"))
mode:value("monitor", translate("Monitor"))
hidden = s:taboption("general", Flag, "hidden", translate("Hide <abbr title=\"Extended Service Set Identifier\">ESSID</abbr>"))
hidden:depends({mode="ap"})
hidden:depends({mode="adhoc"})
hidden:depends({mode="wds"})
bssid:depends({mode="sta"})
mp = s:taboption("macfilter", ListValue, "macpolicy", translate("MAC-Address Filter"))
mp:value("", translate("disable"))
mp:value("allow", translate("Allow listed only"))
mp:value("deny", translate("Allow all except listed"))
ml = s:taboption("macfilter", DynamicList, "maclist", translate("MAC-List"))
ml:depends({macpolicy="allow"})
ml:depends({macpolicy="deny"})
nt.mac_hints(function(mac, name) ml:value(mac, "%s (%s)" %{ mac, name }) end)
s:taboption("advanced", Value, "rate", translate("Transmission Rate"))
s:taboption("advanced", Value, "frag", translate("Fragmentation Threshold"))
s:taboption("advanced", Value, "rts", translate("RTS/CTS Threshold"))
end
------------------- WiFI-Encryption -------------------
encr = s:taboption("encryption", ListValue, "encryption", translate("Encryption"))
encr.override_values = true
encr.override_depends = true
encr:depends({mode="ap"})
encr:depends({mode="sta"})
encr:depends({mode="adhoc"})
encr:depends({mode="ahdemo"})
encr:depends({mode="ap-wds"})
encr:depends({mode="sta-wds"})
encr:depends({mode="mesh"})
cipher = s:taboption("encryption", ListValue, "cipher", translate("Cipher"))
cipher:depends({encryption="wpa"})
cipher:depends({encryption="wpa2"})
cipher:depends({encryption="psk"})
cipher:depends({encryption="psk2"})
cipher:depends({encryption="wpa-mixed"})
cipher:depends({encryption="psk-mixed"})
cipher:value("auto", translate("auto"))
cipher:value("ccmp", translate("Force CCMP (AES)"))
cipher:value("tkip", translate("Force TKIP"))
cipher:value("tkip+ccmp", translate("Force TKIP and CCMP (AES)"))
function encr.cfgvalue(self, section)
local v = tostring(ListValue.cfgvalue(self, section))
if v == "wep" then
return "wep-open"
elseif v and v:match("%+") then
return (v:gsub("%+.+$", ""))
end
return v
end
function encr.write(self, section, value)
local e = tostring(encr:formvalue(section))
local c = tostring(cipher:formvalue(section))
if value == "wpa" or value == "wpa2" then
self.map.uci:delete("wireless", section, "key")
end
if e and (c == "tkip" or c == "ccmp" or c == "tkip+ccmp") then
e = e .. "+" .. c
end
self.map:set(section, "encryption", e)
end
function cipher.cfgvalue(self, section)
local v = tostring(ListValue.cfgvalue(encr, section))
if v and v:match("%+") then
v = v:gsub("^[^%+]+%+", "")
if v == "aes" then v = "ccmp"
elseif v == "tkip+aes" then v = "tkip+ccmp"
elseif v == "aes+tkip" then v = "tkip+ccmp"
elseif v == "ccmp+tkip" then v = "tkip+ccmp"
end
end
return v
end
function cipher.write(self, section)
return encr:write(section)
end
encr:value("none", "No Encryption")
encr:value("wep-open", translate("WEP Open System"), {mode="ap"}, {mode="sta"}, {mode="ap-wds"}, {mode="sta-wds"}, {mode="adhoc"}, {mode="ahdemo"}, {mode="wds"})
encr:value("wep-shared", translate("WEP Shared Key"), {mode="ap"}, {mode="sta"}, {mode="ap-wds"}, {mode="sta-wds"}, {mode="adhoc"}, {mode="ahdemo"}, {mode="wds"})
if hwtype == "atheros" or hwtype == "mac80211" or hwtype == "prism2" then
local supplicant = fs.access("/usr/sbin/wpa_supplicant")
local hostapd = fs.access("/usr/sbin/hostapd")
-- Probe EAP support
local has_ap_eap = (os.execute("hostapd -veap >/dev/null 2>/dev/null") == 0)
local has_sta_eap = (os.execute("wpa_supplicant -veap >/dev/null 2>/dev/null") == 0)
if hostapd and supplicant then
encr:value("psk", "WPA-PSK", {mode="ap"}, {mode="sta"}, {mode="ap-wds"}, {mode="sta-wds"})
encr:value("psk2", "WPA2-PSK", {mode="ap"}, {mode="sta"}, {mode="ap-wds"}, {mode="sta-wds"})
encr:value("psk-mixed", "WPA-PSK/WPA2-PSK Mixed Mode", {mode="ap"}, {mode="sta"}, {mode="ap-wds"}, {mode="sta-wds"})
if has_ap_eap and has_sta_eap then
encr:value("wpa", "WPA-EAP", {mode="ap"}, {mode="sta"}, {mode="ap-wds"}, {mode="sta-wds"})
encr:value("wpa2", "WPA2-EAP", {mode="ap"}, {mode="sta"}, {mode="ap-wds"}, {mode="sta-wds"})
end
elseif hostapd and not supplicant then
encr:value("psk", "WPA-PSK", {mode="ap"}, {mode="ap-wds"})
encr:value("psk2", "WPA2-PSK", {mode="ap"}, {mode="ap-wds"})
encr:value("psk-mixed", "WPA-PSK/WPA2-PSK Mixed Mode", {mode="ap"}, {mode="ap-wds"})
if has_ap_eap then
encr:value("wpa", "WPA-EAP", {mode="ap"}, {mode="ap-wds"})
encr:value("wpa2", "WPA2-EAP", {mode="ap"}, {mode="ap-wds"})
end
encr.description = translate(
"WPA-Encryption requires wpa_supplicant (for client mode) or hostapd (for AP " ..
"and ad-hoc mode) to be installed."
)
elseif not hostapd and supplicant then
encr:value("psk", "WPA-PSK", {mode="sta"}, {mode="sta-wds"})
encr:value("psk2", "WPA2-PSK", {mode="sta"}, {mode="sta-wds"})
encr:value("psk-mixed", "WPA-PSK/WPA2-PSK Mixed Mode", {mode="sta"}, {mode="sta-wds"})
if has_sta_eap then
encr:value("wpa", "WPA-EAP", {mode="sta"}, {mode="sta-wds"})
encr:value("wpa2", "WPA2-EAP", {mode="sta"}, {mode="sta-wds"})
end
encr.description = translate(
"WPA-Encryption requires wpa_supplicant (for client mode) or hostapd (for AP " ..
"and ad-hoc mode) to be installed."
)
else
encr.description = translate(
"WPA-Encryption requires wpa_supplicant (for client mode) or hostapd (for AP " ..
"and ad-hoc mode) to be installed."
)
end
elseif hwtype == "broadcom" then
encr:value("psk", "WPA-PSK")
encr:value("psk2", "WPA2-PSK")
encr:value("psk+psk2", "WPA-PSK/WPA2-PSK Mixed Mode")
end
auth_server = s:taboption("encryption", Value, "auth_server", translate("Radius-Authentication-Server"))
auth_server:depends({mode="ap", encryption="wpa"})
auth_server:depends({mode="ap", encryption="wpa2"})
auth_server:depends({mode="ap-wds", encryption="wpa"})
auth_server:depends({mode="ap-wds", encryption="wpa2"})
auth_server.rmempty = true
auth_server.datatype = "host(0)"
auth_port = s:taboption("encryption", Value, "auth_port", translate("Radius-Authentication-Port"), translatef("Default %d", 1812))
auth_port:depends({mode="ap", encryption="wpa"})
auth_port:depends({mode="ap", encryption="wpa2"})
auth_port:depends({mode="ap-wds", encryption="wpa"})
auth_port:depends({mode="ap-wds", encryption="wpa2"})
auth_port.rmempty = true
auth_port.datatype = "port"
auth_secret = s:taboption("encryption", Value, "auth_secret", translate("Radius-Authentication-Secret"))
auth_secret:depends({mode="ap", encryption="wpa"})
auth_secret:depends({mode="ap", encryption="wpa2"})
auth_secret:depends({mode="ap-wds", encryption="wpa"})
auth_secret:depends({mode="ap-wds", encryption="wpa2"})
auth_secret.rmempty = true
auth_secret.password = true
acct_server = s:taboption("encryption", Value, "acct_server", translate("Radius-Accounting-Server"))
acct_server:depends({mode="ap", encryption="wpa"})
acct_server:depends({mode="ap", encryption="wpa2"})
acct_server:depends({mode="ap-wds", encryption="wpa"})
acct_server:depends({mode="ap-wds", encryption="wpa2"})
acct_server.rmempty = true
acct_server.datatype = "host(0)"
acct_port = s:taboption("encryption", Value, "acct_port", translate("Radius-Accounting-Port"), translatef("Default %d", 1813))
acct_port:depends({mode="ap", encryption="wpa"})
acct_port:depends({mode="ap", encryption="wpa2"})
acct_port:depends({mode="ap-wds", encryption="wpa"})
acct_port:depends({mode="ap-wds", encryption="wpa2"})
acct_port.rmempty = true
acct_port.datatype = "port"
acct_secret = s:taboption("encryption", Value, "acct_secret", translate("Radius-Accounting-Secret"))
acct_secret:depends({mode="ap", encryption="wpa"})
acct_secret:depends({mode="ap", encryption="wpa2"})
acct_secret:depends({mode="ap-wds", encryption="wpa"})
acct_secret:depends({mode="ap-wds", encryption="wpa2"})
acct_secret.rmempty = true
acct_secret.password = true
wpakey = s:taboption("encryption", Value, "_wpa_key", translate("Key"))
wpakey:depends("encryption", "psk")
wpakey:depends("encryption", "psk2")
wpakey:depends("encryption", "psk+psk2")
wpakey:depends("encryption", "psk-mixed")
wpakey.datatype = "wpakey"
wpakey.rmempty = true
wpakey.password = true
wpakey.cfgvalue = function(self, section, value)
local key = m.uci:get("wireless", section, "key")
if key == "1" or key == "2" or key == "3" or key == "4" then
return nil
end
return key
end
wpakey.write = function(self, section, value)
self.map.uci:set("wireless", section, "key", value)
self.map.uci:delete("wireless", section, "key1")
end
wepslot = s:taboption("encryption", ListValue, "_wep_key", translate("Used Key Slot"))
wepslot:depends("encryption", "wep-open")
wepslot:depends("encryption", "wep-shared")
wepslot:value("1", translatef("Key #%d", 1))
wepslot:value("2", translatef("Key #%d", 2))
wepslot:value("3", translatef("Key #%d", 3))
wepslot:value("4", translatef("Key #%d", 4))
wepslot.cfgvalue = function(self, section)
local slot = tonumber(m.uci:get("wireless", section, "key"))
if not slot or slot < 1 or slot > 4 then
return 1
end
return slot
end
wepslot.write = function(self, section, value)
self.map.uci:set("wireless", section, "key", value)
end
local slot
for slot=1,4 do
wepkey = s:taboption("encryption", Value, "key" .. slot, translatef("Key #%d", slot))
wepkey:depends("encryption", "wep-open")
wepkey:depends("encryption", "wep-shared")
wepkey.datatype = "wepkey"
wepkey.rmempty = true
wepkey.password = true
function wepkey.write(self, section, value)
if value and (#value == 5 or #value == 13) then
value = "s:" .. value
end
return Value.write(self, section, value)
end
end
if hwtype == "atheros" or hwtype == "mac80211" or hwtype == "prism2" then
nasid = s:taboption("encryption", Value, "nasid", translate("NAS ID"))
nasid:depends({mode="ap", encryption="wpa"})
nasid:depends({mode="ap", encryption="wpa2"})
nasid:depends({mode="ap-wds", encryption="wpa"})
nasid:depends({mode="ap-wds", encryption="wpa2"})
nasid.rmempty = true
eaptype = s:taboption("encryption", ListValue, "eap_type", translate("EAP-Method"))
eaptype:value("tls", "TLS")
eaptype:value("ttls", "TTLS")
eaptype:value("peap", "PEAP")
eaptype:value("fast", "FAST")
eaptype:depends({mode="sta", encryption="wpa"})
eaptype:depends({mode="sta", encryption="wpa2"})
eaptype:depends({mode="sta-wds", encryption="wpa"})
eaptype:depends({mode="sta-wds", encryption="wpa2"})
cacert = s:taboption("encryption", FileUpload, "ca_cert", translate("Path to CA-Certificate"))
cacert:depends({mode="sta", encryption="wpa"})
cacert:depends({mode="sta", encryption="wpa2"})
cacert:depends({mode="sta-wds", encryption="wpa"})
cacert:depends({mode="sta-wds", encryption="wpa2"})
cacert.rmempty = true
clientcert = s:taboption("encryption", FileUpload, "client_cert", translate("Path to Client-Certificate"))
clientcert:depends({mode="sta", eap_type="tls", encryption="wpa"})
clientcert:depends({mode="sta", eap_type="tls", encryption="wpa2"})
clientcert:depends({mode="sta-wds", eap_type="tls", encryption="wpa"})
clientcert:depends({mode="sta-wds", eap_type="tls", encryption="wpa2"})
privkey = s:taboption("encryption", FileUpload, "priv_key", translate("Path to Private Key"))
privkey:depends({mode="sta", eap_type="tls", encryption="wpa2"})
privkey:depends({mode="sta", eap_type="tls", encryption="wpa"})
privkey:depends({mode="sta-wds", eap_type="tls", encryption="wpa2"})
privkey:depends({mode="sta-wds", eap_type="tls", encryption="wpa"})
privkeypwd = s:taboption("encryption", Value, "priv_key_pwd", translate("Password of Private Key"))
privkeypwd:depends({mode="sta", eap_type="tls", encryption="wpa2"})
privkeypwd:depends({mode="sta", eap_type="tls", encryption="wpa"})
privkeypwd:depends({mode="sta-wds", eap_type="tls", encryption="wpa2"})
privkeypwd:depends({mode="sta-wds", eap_type="tls", encryption="wpa"})
privkeypwd.rmempty = true
privkeypwd.password = true
auth = s:taboption("encryption", ListValue, "auth", translate("Authentication"))
auth:value("PAP", "PAP", {eap_type="ttls"})
auth:value("CHAP", "CHAP", {eap_type="ttls"})
auth:value("MSCHAP", "MSCHAP", {eap_type="ttls"})
auth:value("MSCHAPV2", "MSCHAPv2", {eap_type="ttls"})
auth:value("EAP-GTC")
auth:value("EAP-MD5")
auth:value("EAP-MSCHAPV2")
auth:value("EAP-TLS")
auth:depends({mode="sta", eap_type="fast", encryption="wpa2"})
auth:depends({mode="sta", eap_type="fast", encryption="wpa"})
auth:depends({mode="sta", eap_type="peap", encryption="wpa2"})
auth:depends({mode="sta", eap_type="peap", encryption="wpa"})
auth:depends({mode="sta", eap_type="ttls", encryption="wpa2"})
auth:depends({mode="sta", eap_type="ttls", encryption="wpa"})
auth:depends({mode="sta-wds", eap_type="fast", encryption="wpa2"})
auth:depends({mode="sta-wds", eap_type="fast", encryption="wpa"})
auth:depends({mode="sta-wds", eap_type="peap", encryption="wpa2"})
auth:depends({mode="sta-wds", eap_type="peap", encryption="wpa"})
auth:depends({mode="sta-wds", eap_type="ttls", encryption="wpa2"})
auth:depends({mode="sta-wds", eap_type="ttls", encryption="wpa"})
cacert2 = s:taboption("encryption", FileUpload, "ca_cert2", translate("Path to inner CA-Certificate"))
cacert2:depends({mode="sta", auth="EAP-TLS", encryption="wpa"})
cacert2:depends({mode="sta", auth="EAP-TLS", encryption="wpa2"})
cacert2:depends({mode="sta-wds", auth="EAP-TLS", encryption="wpa"})
cacert2:depends({mode="sta-wds", auth="EAP-TLS", encryption="wpa2"})
clientcert2 = s:taboption("encryption", FileUpload, "client_cert2", translate("Path to inner Client-Certificate"))
clientcert2:depends({mode="sta", auth="EAP-TLS", encryption="wpa"})
clientcert2:depends({mode="sta", auth="EAP-TLS", encryption="wpa2"})
clientcert2:depends({mode="sta-wds", auth="EAP-TLS", encryption="wpa"})
clientcert2:depends({mode="sta-wds", auth="EAP-TLS", encryption="wpa2"})
privkey2 = s:taboption("encryption", FileUpload, "priv_key2", translate("Path to inner Private Key"))
privkey2:depends({mode="sta", auth="EAP-TLS", encryption="wpa"})
privkey2:depends({mode="sta", auth="EAP-TLS", encryption="wpa2"})
privkey2:depends({mode="sta-wds", auth="EAP-TLS", encryption="wpa"})
privkey2:depends({mode="sta-wds", auth="EAP-TLS", encryption="wpa2"})
privkeypwd2 = s:taboption("encryption", Value, "priv_key2_pwd", translate("Password of inner Private Key"))
privkeypwd2:depends({mode="sta", auth="EAP-TLS", encryption="wpa"})
privkeypwd2:depends({mode="sta", auth="EAP-TLS", encryption="wpa2"})
privkeypwd2:depends({mode="sta-wds", auth="EAP-TLS", encryption="wpa"})
privkeypwd2:depends({mode="sta-wds", auth="EAP-TLS", encryption="wpa2"})
privkeypwd2.rmempty = true
privkeypwd2.password = true
identity = s:taboption("encryption", Value, "identity", translate("Identity"))
identity:depends({mode="sta", eap_type="fast", encryption="wpa2"})
identity:depends({mode="sta", eap_type="fast", encryption="wpa"})
identity:depends({mode="sta", eap_type="peap", encryption="wpa2"})
identity:depends({mode="sta", eap_type="peap", encryption="wpa"})
identity:depends({mode="sta", eap_type="ttls", encryption="wpa2"})
identity:depends({mode="sta", eap_type="ttls", encryption="wpa"})
identity:depends({mode="sta-wds", eap_type="fast", encryption="wpa2"})
identity:depends({mode="sta-wds", eap_type="fast", encryption="wpa"})
identity:depends({mode="sta-wds", eap_type="peap", encryption="wpa2"})
identity:depends({mode="sta-wds", eap_type="peap", encryption="wpa"})
identity:depends({mode="sta-wds", eap_type="ttls", encryption="wpa2"})
identity:depends({mode="sta-wds", eap_type="ttls", encryption="wpa"})
identity:depends({mode="sta", eap_type="tls", encryption="wpa2"})
identity:depends({mode="sta", eap_type="tls", encryption="wpa"})
identity:depends({mode="sta-wds", eap_type="tls", encryption="wpa2"})
identity:depends({mode="sta-wds", eap_type="tls", encryption="wpa"})
anonymous_identity = s:taboption("encryption", Value, "anonymous_identity", translate("Anonymous Identity"))
anonymous_identity:depends({mode="sta", eap_type="fast", encryption="wpa2"})
anonymous_identity:depends({mode="sta", eap_type="fast", encryption="wpa"})
anonymous_identity:depends({mode="sta", eap_type="peap", encryption="wpa2"})
anonymous_identity:depends({mode="sta", eap_type="peap", encryption="wpa"})
anonymous_identity:depends({mode="sta", eap_type="ttls", encryption="wpa2"})
anonymous_identity:depends({mode="sta", eap_type="ttls", encryption="wpa"})
anonymous_identity:depends({mode="sta-wds", eap_type="fast", encryption="wpa2"})
anonymous_identity:depends({mode="sta-wds", eap_type="fast", encryption="wpa"})
anonymous_identity:depends({mode="sta-wds", eap_type="peap", encryption="wpa2"})
anonymous_identity:depends({mode="sta-wds", eap_type="peap", encryption="wpa"})
anonymous_identity:depends({mode="sta-wds", eap_type="ttls", encryption="wpa2"})
anonymous_identity:depends({mode="sta-wds", eap_type="ttls", encryption="wpa"})
anonymous_identity:depends({mode="sta", eap_type="tls", encryption="wpa2"})
anonymous_identity:depends({mode="sta", eap_type="tls", encryption="wpa"})
anonymous_identity:depends({mode="sta-wds", eap_type="tls", encryption="wpa2"})
anonymous_identity:depends({mode="sta-wds", eap_type="tls", encryption="wpa"})
password = s:taboption("encryption", Value, "password", translate("Password"))
password:depends({mode="sta", eap_type="fast", encryption="wpa2"})
password:depends({mode="sta", eap_type="fast", encryption="wpa"})
password:depends({mode="sta", eap_type="peap", encryption="wpa2"})
password:depends({mode="sta", eap_type="peap", encryption="wpa"})
password:depends({mode="sta", eap_type="ttls", encryption="wpa2"})
password:depends({mode="sta", eap_type="ttls", encryption="wpa"})
password:depends({mode="sta-wds", eap_type="fast", encryption="wpa2"})
password:depends({mode="sta-wds", eap_type="fast", encryption="wpa"})
password:depends({mode="sta-wds", eap_type="peap", encryption="wpa2"})
password:depends({mode="sta-wds", eap_type="peap", encryption="wpa"})
password:depends({mode="sta-wds", eap_type="ttls", encryption="wpa2"})
password:depends({mode="sta-wds", eap_type="ttls", encryption="wpa"})
password.rmempty = true
password.password = true
end
if hwtype == "atheros" or hwtype == "mac80211" or hwtype == "prism2" then
local wpasupplicant = fs.access("/usr/sbin/wpa_supplicant")
local hostcli = fs.access("/usr/sbin/hostapd_cli")
if hostcli and wpasupplicant then
wps = s:taboption("encryption", Flag, "wps_pushbutton", translate("Enable WPS pushbutton, requires WPA(2)-PSK"))
wps.enabled = "1"
wps.disabled = "0"
wps.rmempty = false
wps:depends("encryption", "psk")
wps:depends("encryption", "psk2")
wps:depends("encryption", "psk-mixed")
end
end
return m
| apache-2.0 |
kracwarlock/dp | feedback/compositefeedback.lua | 5 | 1613 | ------------------------------------------------------------------------
--[[ CompositeFeedback ]]--
-- Feedback
-- Composite of many Feedback components
------------------------------------------------------------------------
local CompositeFeedback, parent = torch.class("dp.CompositeFeedback", "dp.Feedback")
CompositeFeedback.isCompositeFeedback = true
function CompositeFeedback:__init(config)
assert(type(config) == 'table', "Constructor requires key-value arguments")
local args, feedbacks = xlua.unpack(
{config},
'CompositeFeedback',
'Composite of many Feedback components',
{arg='feedbacks', type='table', req=true,
help='list of feedbacks'}
)
self._feedbacks = feedbacks
config.name = 'compositefeedback'
parent.__init(self, config)
end
function CompositeFeedback:setup(config)
parent.setup(self, config)
for k, v in pairs(self._feedbacks) do
v:setup(config)
end
end
function CompositeFeedback:_add(batch, output, report)
_.map(self._feedbacks,
function(key, fb)
fb:add(batch, output, report)
end
)
end
function CompositeFeedback:report()
-- merge reports
local report = {}
for k, feedback in pairs(self._feedbacks) do
table.merge(report, feedback:report())
end
return report
end
function CompositeFeedback:_reset()
for k, feedback in pairs(self._feedbacks) do
feedback:reset()
end
end
function CompositeFeedback:verbose(verbose)
self._verbose = (verbose == nil) and true or verbose
for k, v in pairs(self._feedbacks) do
v:verbose(self._verbose)
end
end
| bsd-3-clause |
cshore/luci | protocols/luci-proto-qmi/luasrc/model/cbi/admin_network/proto_qmi.lua | 17 | 1270 | -- Copyright 2016 David Thornley <david.thornley@touchstargroup.com>
-- Licensed to the public under the Apache License 2.0.
local map, section, net = ...
local device, apn, pincode, username, password
local auth, ipv6
device = section:taboption("general", Value, "device", translate("Modem device"))
device.rmempty = false
local device_suggestions = nixio.fs.glob("/dev/cdc-wdm*")
if device_suggestions then
local node
for node in device_suggestions do
device:value(node)
end
end
apn = section:taboption("general", Value, "apn", translate("APN"))
pincode = section:taboption("general", Value, "pincode", translate("PIN"))
username = section:taboption("general", Value, "username", translate("PAP/CHAP username"))
password = section:taboption("general", Value, "password", translate("PAP/CHAP password"))
password.password = true
auth = section:taboption("general", Value, "auth", translate("Authentication Type"))
auth:value("", translate("-- Please choose --"))
auth:value("both", "PAP/CHAP (both)")
auth:value("pap", "PAP")
auth:value("chap", "CHAP")
auth:value("none", "NONE")
if luci.model.network:has_ipv6() then
ipv6 = section:taboption("advanced", Flag, "ipv6", translate("Enable IPv6 negotiation"))
ipv6.default = ipv6.disabled
end
| apache-2.0 |
bigdogmat/wire | lua/entities/gmod_wire_simple_explosive.lua | 8 | 2407 | AddCSLuaFile()
DEFINE_BASECLASS( "base_wire_entity" )
ENT.PrintName = "Wire Simple Explosive"
ENT.WireDebugName = "Simple Explosive"
if CLIENT then return end -- No more client
local wire_explosive_delay = CreateConVar( "wire_explosive_delay", 0.2, FCVAR_ARCHIVE )
local wire_explosive_range = CreateConVar( "wire_explosive_range", 512, FCVAR_ARCHIVE )
function ENT:Initialize()
self:PhysicsInit( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
local phys = self:GetPhysicsObject()
if (phys:IsValid()) then
phys:Wake()
end
self.NormInfo = ""
self.DisabledByTimeUntil = CurTime()
self.Inputs = Wire_CreateInputs(self, { "Detonate" })
end
function ENT:Setup( key, damage, removeafter, radius )
self.key = key
self.damage = math.Min(damage, 1500)
self.removeafter = removeafter
self.radius = math.Clamp(radius, 1, wire_explosive_range:GetFloat())
self.Exploded = false
if (self.damage > 0) then
self.NormInfo = "Damage: " .. math.floor(self.damage) .. "\nRadius: " .. math.floor(self.radius)
else
self.NormInfo = "Radius: " .. math.floor(self.radius)
end
self:ShowOutput()
end
function ENT:OnTakeDamage( dmginfo )
self:TakePhysicsDamage( dmginfo )
end
function ENT:TriggerInput(iname, value)
if (iname == "Detonate") then
if (!self.Exploded) and ( math.abs(value) == self.key ) then
self:Explode()
elseif (value == 0) then
self.Exploded = false
end
end
end
function ENT:Explode( )
if ( !self:IsValid() ) then return end
if (self.Exploded) then return end
if self.DisabledByTimeUntil > CurTime() then return end
self.DisabledByTimeUntil = CurTime() + wire_explosive_delay:GetFloat()
local ply = self:GetPlayer()
if not IsValid(ply) then ply = self end
if ( self.damage > 0 ) then
util.BlastDamage( self, ply, self:GetPos(), self.radius, self.damage )
end
local effectdata = EffectData()
effectdata:SetOrigin( self:GetPos() )
util.Effect( "Explosion", effectdata, true, true )
self.Exploded = true
self:ShowOutput()
if ( self.removeafter ) then
self:Remove()
return
end
end
function ENT:ShowOutput( )
if (self.Exploded) then
self:SetOverlayText("Exploded\n"..self.NormInfo)
else
self:SetOverlayText("Explosive\n"..self.NormInfo)
end
end
duplicator.RegisterEntityClass( "gmod_wire_simple_explosive", WireLib.MakeWireEnt, "Data", "key", "damage", "removeafter", "radius" )
| apache-2.0 |
FrisKAY/MineOS_Server | Beta/Printer.lua | 1 | 9182 |
------------------------------------------ Библиотеки -----------------------------------------------------------------
local component = require("component")
local colorlib = require("colorlib")
local event = require("event")
local gpu = component.gpu
local printer = component.printer3d
local hologram = component.hologram
------------------------------------------ Переменные -----------------------------------------------------------------
local pixels = {}
local model = {
label = "Sosi hui",
tooltip = "mamu ebal",
buttonMode = true,
redstoneEmitter = true,
active = {
{x = 1, y = 1, z = 1, x2 = 1, y2 = 1, z2 = 12},
{x = 1, y = 8, z = 1, x2 = 8, y2 = 8, z2 = 16},
{x = 16, y = 16, z = 16, x2 = 16, y2 = 16, z2 = 16},
},
passive = {}
}
local colors = {
objects = 0x3349FF,
points = 0xFFFFFF,
border = 0xFFFF00,
background = 0x262626,
rightBar = 0x383838,
lines = 0x222222,
}
local countOfShapes = printer.getMaxShapeCount()
local adder = 360 / countOfShapes
local hue = 0
colors.shapes = {}
for i = 1, countOfShapes do
table.insert(colors.shapes, colorlib.HSBtoHEX(hue, 100, 100))
hue = hue + adder
end
local sizes = {}
sizes.oldResolutionWidth, sizes.oldResolutionHeight = gpu.getResolution()
sizes.xSize, sizes.ySize = gpu.maxResolution()
--
sizes.widthOfRightBar, sizes.heightOfRightBar = 36, sizes.ySize
sizes.xStartOfRightBar, sizes.yStartOfRightBar = sizes.xSize - sizes.widthOfRightBar + 1, 1
--
sizes.widthOfHorizontal = sizes.xSize - sizes.widthOfRightBar
sizes.xStartOfVertical, sizes.yStartOfVertical = math.floor(sizes.widthOfHorizontal / 2), 1
sizes.xStartOfHorizontal, sizes.yStartOfHorizontal = 1, math.floor(sizes.ySize / 2)
--
sizes.widthOfPixel, sizes.heightOfPixel = 2, 1
sizes.image = {}
sizes.image[1] = {x = math.floor(sizes.xStartOfVertical / 2 - (sizes.widthOfPixel * 16) / 2), y = math.floor(sizes.yStartOfHorizontal / 2 - (sizes.heightOfPixel * 16) / 2)}
sizes.image[2] = {x = sizes.xStartOfVertical + sizes.image[1].x + 1, y = sizes.image[1].y}
sizes.image[3] = {x = sizes.image[1].x, y = sizes.yStartOfHorizontal + sizes.image[1].y + 1}
sizes.image[4] = {x = sizes.image[2].x, y = sizes.image[3].y}
local holoOutlineX, holoOutlineY, holoOutlineZ = 16, 24, 16
local currentShape = 1
local currentLayer = 1
------------------------------------------ Функции -----------------------------------------------------------------
local function drawTransparentBackground(x, y, color1, color2)
local xPos, yPos = x, y
local color
for j = 1, 16 do
for i = 1, 16 do
if i % 2 == 0 then
if j % 2 == 0 then
color = color1
else
color = color2
end
else
if j % 2 == 0 then
color = color2
else
color = color1
end
end
ecs.square(xPos, yPos, sizes.widthOfPixel, sizes.heightOfPixel, color)
xPos = xPos + sizes.widthOfPixel
end
xPos = x
yPos = yPos + sizes.heightOfPixel
end
end
local function changePalette()
hologram.setPaletteColor(1, colors.objects)
hologram.setPaletteColor(2, colors.points)
hologram.setPaletteColor(3, colors.border)
end
local function drawShapesList(x, y)
local xPos, yPos = x, y
local color
for i = 1, countOfShapes do
color = 0x000000
if i == currentShape then color = colors.shapes[i] end
ecs.drawButton(xPos, yPos, 4, 1, tostring(i), color, 0xFFFFFF )
xPos = xPos + 5
if i % 6 == 0 then xPos = x; yPos = yPos + 2 end
end
end
local function drawInfo(y, info)
ecs.square(sizes.xStartOfRightBar, y, sizes.widthOfRightBar, 1, 0x000000)
ecs.colorText(sizes.xStartOfRightBar + 2, y, 0xFFFFFF, info)
end
local function drawRightBar()
local xPos, yPos = sizes.xStartOfRightBar, sizes.yStartOfRightBar
ecs.square(xPos, yPos, sizes.widthOfRightBar, sizes.heightOfRightBar, colors.rightBar)
drawInfo(yPos, "Работа с моделью"); yPos = yPos + 2
yPos = yPos + 5
drawInfo(yPos, "Работа с объектом"); yPos = yPos + 2
yPos = yPos + 5
drawInfo(yPos, "Выбор объекта"); yPos = yPos + 3
drawShapesList(xPos + 2, yPos); yPos = yPos + (countOfShapes / 6 * 2) + 1
drawInfo(yPos, "Управление голограммой"); yPos = yPos + 2
yPos = yPos + 5
drawInfo(yPos, "Управление принтером"); yPos = yPos + 2
yPos = yPos + 5
end
local function drawLines()
ecs.square(sizes.xStartOfVertical, sizes.yStartOfVertical, 2, sizes.ySize,colors.lines)
ecs.square(sizes.xStartOfHorizontal, sizes.yStartOfHorizontal, sizes.widthOfHorizontal , 1, colors.lines)
end
local function drawViewArray(x, y, massiv)
local xPos, yPos = x, y
for i = 1, #massiv do
for j = 1, #massiv[i] do
if massiv[i][j] ~= "#" then
ecs.square(xPos, yPos, sizes.widthOfPixel, sizes.heightOfPixel, massiv[i][j])
end
xPos = xPos + sizes.widthOfPixel
end
xPos = x
yPos = yPos + sizes.heightOfPixel
end
end
--Нарисовать вид спереди
local function drawFrontView()
local massiv = {}
for i = 1, 16 do
massiv[i] = {}
for j = 1, 16 do
massiv[i][j] = "#"
end
end
for x = 1, #pixels do
for y = 1, #pixels[x] do
for z = 1, #pixels[x][y] do
if pixels[x][y][z] ~= "#" then
massiv[y][x] = pixels[x][y][z]
end
end
end
end
drawViewArray(sizes.image[1].x, sizes.image[1].y, massiv)
end
--Нарисовать вид сверху
local function drawTopView()
local massiv = {}
for i = 1, 16 do
massiv[i] = {}
for j = 1, 16 do
massiv[i][j] = "#"
end
end
for x = 1, #pixels do
for y = 1, #pixels[x] do
for z = 1, #pixels[x][y] do
if pixels[x][y][z] ~= "#" then
massiv[z][x] = pixels[x][y][z]
end
end
end
end
drawViewArray(sizes.image[3].x, sizes.image[3].y, massiv)
end
--Нарисовать вид сбоку
local function drawSideView()
local massiv = {}
for i = 1, 16 do
massiv[i] = {}
for j = 1, 16 do
massiv[i][j] = "#"
end
end
for x = 1, #pixels do
for y = 1, #pixels[x] do
for z = 1, #pixels[x][y] do
if pixels[x][y][z] ~= "#" then
massiv[y][z] = pixels[x][y][z]
end
end
end
end
drawViewArray(sizes.image[2].x, sizes.image[2].y, massiv)
end
--Сконвертировать массив объектов в трехмерный массив 3D-изображения
local function render()
pixels = {}
for x = 1, 16 do
pixels[x] = {}
for y = 1, 16 do
pixels[x][y] = {}
for z = 1, 16 do
pixels[x][y][z] = "#"
end
end
end
for x = 1, 16 do
for y = 1, 16 do
for z = 1, 16 do
for i = 1, #model.active do
if (x >= model.active[i].x and x <= model.active[i].x2) and (y >= model.active[i].y and y <= model.active[i].y2) and (z >= model.active[i].z and z <= model.active[i].z2) then
pixels[x][y][z] = colors.shapes[i]
--hologram.set(x, y, z, 1)
end
end
end
end
end
end
local function drawBorder()
for i = 0, 17 do
hologram.set(i + holoOutlineX, holoOutlineY - currentLayer, holoOutlineZ, 3)
hologram.set(i + holoOutlineX, holoOutlineY - currentLayer, 17 + holoOutlineZ, 3)
hologram.set(holoOutlineX, holoOutlineY - currentLayer, i + holoOutlineZ, 3)
hologram.set(17 + holoOutlineX, holoOutlineY - currentLayer, i + holoOutlineZ, 3)
end
end
local function drawFrame()
--Верхний левый
for i = 1, 2 do hologram.set(i + holoOutlineX - 1, holoOutlineY - 1, holoOutlineZ, 2) end
hologram.set(holoOutlineX, holoOutlineY - 1, holoOutlineZ + 1, 2)
hologram.set(holoOutlineX, holoOutlineY - 2, holoOutlineZ, 2)
--Верхний левый
for i = 1, 2 do hologram.set(i + holoOutlineX - 1, holoOutlineY - 16, holoOutlineZ, 2) end
hologram.set(holoOutlineX, holoOutlineY - 16, holoOutlineZ + 1, 2)
hologram.set(holoOutlineX, holoOutlineY - 15, holoOutlineZ, 2)
end
local function drawModelOnHolo()
hologram.clear()
for x = 1, #pixels do
for y = 1, #pixels[x] do
for z = 1, #pixels[x][y] do
if pixels[x][y][z] ~= "#" then
hologram.set(x + holoOutlineX, holoOutlineY - y, z + holoOutlineZ, 1)
end
end
end
end
drawBorder()
--drawFrame()
end
local function drawAllViews()
render()
drawModelOnHolo()
drawFrontView()
drawTopView()
drawSideView()
drawTransparentBackground(sizes.image[4].x, sizes.image[4].y, 0xFFFFFF, 0xDDDDDD)
end
local function drawAll()
drawLines()
drawAllViews()
drawRightBar()
end
------------------------------------------ Программа -----------------------------------------------------------------
if sizes.xSize < 150 then ecs.error("Этой программе требуется монитор и видеокарта 3 уровня."); return end
gpu.setResolution(sizes.xSize, sizes.ySize)
ecs.prepareToExit()
changePalette()
drawAll()
while true do
local e = {event.pull()}
if e[1] == "scroll" then
if e[5] == 1 then
if currentLayer > 1 then currentLayer = currentLayer - 1;drawModelOnHolo() end
else
if currentLayer < 16 then currentLayer = currentLayer + 1;drawModelOnHolo() end
end
end
end
------------------------------------------ Выход из программы -----------------------------------------------------------------
gpu.setResolution(sizes.oldResolutionWidth, sizes.oldResolutionHeight)
| gpl-3.0 |
Movimento5StelleLazio/WebMCP | framework/env/ui/tag.lua | 3 | 1113 | --[[--
ui.tag{
tag = tag, -- HTML tag, e.g. "a" for <a>...</a>
attr = attr, -- table of HTML attributes, e.g. { class = "hide" }
content = content -- string to be HTML encoded, or function to be executed
}
This function writes a HTML tag into the active slot.
NOTE: ACCELERATED FUNCTION
Do not change unless also you also update webmcp_accelerator.c
--]]--
function ui.tag(args)
local tag, attr, content
tag = args.tag
attr = args.attr or {}
content = args.content
if type(attr.class) == "table" then
attr = table.new(attr)
attr.class = table.concat(attr.class, " ")
end
if not tag and next(attr) then
tag = "span"
end
if tag then
slot.put('<', tag)
for key, value in pairs(attr) do
slot.put(' ', key, '="', encode.html(value), '"')
end
end
if content then
if tag then
slot.put('>')
end
if type(content) == "function" then
content()
else
slot.put(encode.html(content))
end
if tag then
slot.put('</', tag, '>')
end
else
if tag then
slot.put(' />')
end
end
end
| mit |
robert00s/koreader | frontend/apps/filemanager/filemanagerhistory.lua | 1 | 3855 | local ButtonDialog = require("ui/widget/buttondialog")
local CenterContainer = require("ui/widget/container/centercontainer")
local FileManagerBookInfo = require("apps/filemanager/filemanagerbookinfo")
local Font = require("ui/font")
local InputContainer = require("ui/widget/container/inputcontainer")
local Menu = require("ui/widget/menu")
local UIManager = require("ui/uimanager")
local RenderText = require("ui/rendertext")
local Screen = require("device").screen
local _ = require("gettext")
local T = require("ffi/util").template
local FileManagerHistory = InputContainer:extend{
hist_menu_title = _("History"),
}
function FileManagerHistory:init()
self.ui.menu:registerToMainMenu(self)
end
function FileManagerHistory:addToMainMenu(menu_items)
-- insert table to main tab of filemanager menu
menu_items.history = {
text = self.hist_menu_title,
callback = function()
self:onShowHist()
end,
}
end
function FileManagerHistory:updateItemTable()
self.hist_menu:switchItemTable(self.hist_menu_title,
require("readhistory").hist)
end
function FileManagerHistory:onSetDimensions(dimen)
self.dimen = dimen
end
function FileManagerHistory:onMenuHold(item)
local font_size = Font:getFace("tfont")
local text_remove_hist = _("Remove \"%1\" from history")
local text_remove_without_item = T(text_remove_hist, "")
local text_remove_hist_width = (RenderText:sizeUtf8Text(
0, self.width, font_size, text_remove_without_item).x )
local text_item_width = (RenderText:sizeUtf8Text(
0, self.width , font_size, item.text).x )
local item_trun
if self.width < text_remove_hist_width + text_item_width then
item_trun = RenderText:truncateTextByWidth(item.text, font_size, 1.2 * self.width - text_remove_hist_width)
else
item_trun = item.text
end
local text_remove = T(text_remove_hist, item_trun)
self.histfile_dialog = ButtonDialog:new{
buttons = {
{
{
text = text_remove,
callback = function()
require("readhistory"):removeItem(item)
self._manager:updateItemTable()
UIManager:close(self.histfile_dialog)
end,
},
},
{
{
text = _("Book information"),
enabled = FileManagerBookInfo:isSupported(item.file),
callback = function()
FileManagerBookInfo:show(item.file)
UIManager:close(self.histfile_dialog)
end,
},
},
{},
{
{
text = _("Clear history of deleted files"),
callback = function()
require("readhistory"):clearMissing()
self._manager:updateItemTable()
UIManager:close(self.histfile_dialog)
end,
},
},
},
}
UIManager:show(self.histfile_dialog)
return true
end
function FileManagerHistory:onShowHist()
local menu_container = CenterContainer:new{
dimen = Screen:getSize(),
}
self.hist_menu = Menu:new{
ui = self.ui,
width = Screen:getWidth()-50,
height = Screen:getHeight()-50,
show_parent = menu_container,
onMenuHold = self.onMenuHold,
_manager = self,
}
self:updateItemTable()
table.insert(menu_container, self.hist_menu)
self.hist_menu.close_callback = function()
UIManager:close(menu_container)
end
UIManager:show(menu_container)
return true
end
return FileManagerHistory
| agpl-3.0 |
bizkut/BudakJahat | Rotations/Warrior/Protection/ProtectionPanglo2.lua | 1 | 40854 | --Version 1.0.0
local rotationName = "Panglo2"
---------------
--- Toggles ---
---------------
local function createToggles()
-- Rotation Button
RotationModes = {
[1] = {mode = "Auto", value = 1, overlay = "Automatic Rotation", tip = "Enable Rotation", highlight = 1, icon = br.player.spell.thunderClap},
[2] = {mode = "Off", value = 2, overlay = "DPS Rotation Disabled", tip = "Disable DPS Rotation", highlight = 0, icon = br.player.spell.enragedRegeneration}
}
CreateButton("Rotation", 1, 0)
-- Cooldown Button
CooldownModes = {
[1] = {mode = "Auto", value = 1, overlay = "Cooldowns Automated", tip = "Automatic Cooldowns - Based on settings", highlight = 1, icon = br.player.spell.avatar},
[2] = {mode = "On", value = 2, overlay = "Cooldowns Enabled", tip = "Cooldowns used regardless of target.", highlight = 0, icon = br.player.spell.avatar},
[3] = {mode = "Off", value = 3, overlay = "Cooldowns Disabled", tip = "No Cooldowns will be used.", highlight = 0, icon = br.player.spell.avatar}
}
CreateButton("Cooldown", 2, 0)
-- Defensive Button
DefensiveModes = {
[1] = {mode = "On", value = 1, overlay = "Defensive Enabled", tip = "Includes Defensive Cooldowns.", highlight = 1, icon = br.player.spell.shieldWall},
[2] = {mode = "Off", value = 2, overlay = "Defensive Disabled", tip = "No Defensives will be used.", highlight = 0, icon = br.player.spell.shieldWall}
}
CreateButton("Defensive", 3, 0)
-- Interrupt Button
InterruptModes = {
[1] = {mode = "On", value = 1, overlay = "Interrupts Enabled", tip = "Includes Basic Interrupts.", highlight = 1, icon = br.player.spell.pummel},
[2] = {mode = "Off", value = 2, overlay = "Interrupts Disabled", tip = "No Interrupts will be used.", highlight = 0, icon = br.player.spell.pummel}
}
CreateButton("Interrupt", 4, 0)
-- Movement Button
MoverModes = {
[1] = {mode = "On", value = 1, overlay = "Mover Enabled", tip = "Will use Charge/Heroic Leap.", highlight = 1, icon = br.player.spell.charge},
[2] = {mode = "Off", value = 2, overlay = "Mover Disabled", tip = "Will NOT use Charge/Heroic Leap.", highlight = 0, icon = br.player.spell.charge}
}
CreateButton("Mover", 5, 0)
TauntModes = {
[1] = {mode = "Dun", value = 1, overlay = "Taunt only in Dungeon", tip = "Taunt will be used in dungeons.", highlight = 1, icon = br.player.spell.taunt},
[2] = {mode = "All", value = 2, overlay = "Auto Taunt Enabled", tip = "Taunt will be used everywhere.", highlight = 1, icon = br.player.spell.taunt},
[3] = {mode = "Off", value = 3, overlay = "Auto Taunt Disabled", tip = "Taunt will not be used.", highlight = 0, icon = br.player.spell.taunt}
}
CreateButton("Taunt", 6, 0)
-- Movement Button
ShieldModes = {
[1] = {mode = "On", value = 1, overlay = "Shield Block Enabled", tip = "Will use Shield Block", highlight = 1, icon = br.player.spell.shieldBlock},
[2] = {mode = "Off", value = 2, overlay = "Shield Block Disabled", tip = "Will NOT use Shield Block", highlight = 0, icon = br.player.spell.shieldBlock}
}
CreateButton("Shield", 0, 1)
-- Movement Button
ReflectModes = {
[1] = {mode = "On", value = 1, overlay = "Spell Reflect Enabled", tip = "Will use Spell Reflect", highlight = 1, icon = br.player.spell.spellReflection},
[2] = {mode = "Off", value = 2, overlay = "Spell Reflect Disabled", tip = "Will NOT use Spell Reflect", highlight = 0, icon = br.player.spell.spellReflection}
}
CreateButton("Reflect", 1, 1)
end
---------------
--- OPTIONS ---
---------------
local function createOptions()
local optionTable
local function rotationOptions()
-----------------------
--- GENERAL OPTIONS ---
-----------------------
section = br.ui:createSection(br.ui.window.profile, "General - Version 1.000")
-- br.ui:createDropdown(section,"leap test",{"behind","forward","random"}, 1)
br.ui:createCheckbox(section, "Open World Defensives", "Use this checkbox to ensure defensives are used while in Open World")
-- Berserker Rage
br.ui:createCheckbox(section, "Berserker Rage", "Check to use Berserker Rage")
-- lol charge
br.ui:createCheckbox(section, "Charge OoC")
-- High Rage Dump
br.ui:createSpinner(section, "High Rage Dump", 85, 1, 100, 1, "|cffFFFFFF Set to number of units to use Ignore Pain or Revenge at")
-- Aoe Threshold
br.ui:createSpinnerWithout(section, "Aoe Priority", 3, 1, 10, 1, "Set number of units to prioritise TC and Revenge")
-- Shout Check
br.ui:createCheckbox(section, "Battle Shout", "Enable automatic party buffing")
br.ui:createCheckbox(section, "Pig Catcher", "Catch the freehold Pig in the ring of booty")
br.ui:checkSectionState(section)
------------------------
--- COOLDOWN OPTIONS ---
------------------------
section = br.ui:createSection(br.ui.window.profile, "Cooldowns")
-- Trinkets
br.ui:createDropdownWithout(section, "Trinkets", {"Always", "When CDs are enabled", "Never", "With Avatar"}, 1, "Decide when Trinkets will be used.")
br.ui:createDropdownWithout(section, "Trinket 1 Mode", {"|cffFFFFFFNormal", "|cffFFFFFFGround"}, 1, "", "|cffFFFFFFSelect Trinkets mode.")
br.ui:createDropdownWithout(section, "Trinket 2 Mode", {"|cffFFFFFFNormal", "|cffFFFFFFGround"}, 1, "", "|cffFFFFFFSelect Trinkets mode.")
-- Avatar
br.ui:createCheckbox(section, "Avatar")
-- Avatar Spinner
br.ui:createSpinnerWithout(section, "Avatar Mob Count", 5, 0, 10, 1, "|cffFFFFFFEnemies to cast Avatar when using AUTO CDS")
-- Demoralizing Shout
br.ui:createDropdownWithout(section, "Demoralizing Shout - CD", {"Always", "When CDs are enabled", "Never"}, 1)
-- Ravager
br.ui:createCheckbox(section, "Ravager")
-- Dragons Roar
br.ui:createCheckbox(section, "Dragon Roar")
-- Shockwave
br.ui:createCheckbox(section, "Racial", "Automatically Use racials with Avatar")
br.ui:checkSectionState(section)
-------------------------
--- DEFENSIVE OPTIONS ---
-------------------------
section = br.ui:createSection(br.ui.window.profile, "Defensive")
--Smart Spell reflect
br.ui:createCheckbox(section, "Smart Spell Reflect", "Auto reflect spells in instances")
br.ui:createSpinnerWithout(section, "Smart Spell Reflect Percent", 65, 0, 95, 5, "Spell reflect when spell is X % complete, ex. 90 = 90% complete")
-- Engi Belt stuff thanks to Lak
br.ui:createSpinner(section, "Engineering Belt", 60, 0, 100, 5, "|cffFFBB00Health Percentage to use at.")
-- Healthstone
br.ui:createSpinner(section, "Healthstone/Potion", 60, 0, 100, 5, "|cffFFBB00Health Percentage to use at.")
-- Demoralizing Shout
br.ui:createSpinner(section, "Demoralizing Shout", 60, 0, 100, 5, "|cffFFBB00Health Percentage to use at.")
-- Last Stand
br.ui:createCheckbox(section, "Last Stand Filler", "Use Last Stand as a filler with the Bolster Talent")
br.ui:createSpinner(section, "Last Stand", 60, 0, 100, 5, "|cffFFBB00Health Percentage to use at.")
-- Rallying Cry
br.ui:createSpinner(section, "Rallying Cry", 60, 0, 100, 5, "|cffFFBB00Health Percentage to use at.")
-- Shield Wall
br.ui:createSpinner(section, "Shield Wall", 60, 0, 100, 5, "|cffFFBB00Health Percentage to use at.")
-- Shockwave
br.ui:createSpinner(section, "Shockwave - HP", 60, 0, 100, 5, "|cffFFBB00Health Percentage to use at.")
br.ui:createSpinner(section, "Shockwave - Units", 3, 1, 10, 1, "|cffFFBB00Minimal units to cast on.")
-- Spell Reflection
br.ui:createSpinner(section, "Spell Reflection", 60, 0, 100, 5, "|cffFFBB00Health Percentage to use at.")
-- Storm Bolt
br.ui:createSpinner(section, "Storm Bolt", 60, 0, 100, 5, "|cffFFBB00Health Percentage to use at.")
br.ui:checkSectionState(section)
-------------------------
--- INTERRUPT OPTIONS ---
-------------------------
section = br.ui:createSection(br.ui.window.profile, "Interrupts")
-- Feng is a god
br.ui:createCheckbox(section, "Storm Bolt Logic", "Stun specific Spells and Mobs")
-- Pummel
br.ui:createCheckbox(section, "Pummel")
-- Intimidating Shout
br.ui:createCheckbox(section, "Intimidating Shout - Int")
-- Shockwave
br.ui:createCheckbox(section, "Shockwave - Int")
-- Storm Bolt
br.ui:createCheckbox(section, "Storm Bolt - Int")
-- Interrupt Percentage
br.ui:createSpinner(section, "Interrupt At", 0, 0, 95, 5, "|cffFFBB00Cast Percentage to use at.")
br.ui:checkSectionState(section)
section = br.ui:createSection(br.ui.window.profile, "Corruption Management")
br.ui:createCheckbox(section,"Corruption Radar On")
br.ui:createCheckbox(section,"Use Storm Bolt on TFTB")
br.ui:createCheckbox(section, "Use Int Shout on TFTB")
br.ui:createDropdownWithout(section, "Use Cloak", { "snare", "Eye", "THING", "Never" }, 4, "", "")
br.ui:createSpinnerWithout(section, "Eye Of Corruption Stacks - Cloak", 1, 0, 20, 1)
br.ui:checkSectionState(section)
end
optionTable = {
{
[1] = "Rotation Options",
[2] = rotationOptions
}
}
return optionTable
end
local function ipCapCheck()
if br.player.buff.ignorePain.exists() then
local ipValue = tonumber((select(1, GetSpellDescription(190456):match("%d+%S+%d"):gsub("%D", ""))), 10)
local ipMax = math.floor(ipValue * 1.3)
local ipCurrent = tonumber((select(16, UnitBuffID("player", 190456))), 10)
if ipCurrent == nil then
ipCurrent = 0
return
end
if ipCurrent <= (ipMax * 0.2) then
---print("IP below cap")
return true
else
--print("dont cast IP")
return false
end
else
--print("IP not on")
return true
end
end
----------------
--- ROTATION ---
----------------
local function runRotation()
if br.timer:useTimer("debugProtection", 0.1) then
--Print("Running: "..rotationName)
---------------
--- Toggles ---
---------------
UpdateToggle("Rotation", 0.25)
UpdateToggle("Cooldown", 0.25)
UpdateToggle("Defensive", 0.25)
UpdateToggle("Interrupt", 0.25)
UpdateToggle("Mover", 0.25)
UpdateToggle("Taunt", 0.25)
UpdateToggle("Holdcd", 0.25)
br.player.ui.mode.mover = br.data.settings[br.selectedSpec].toggles["Mover"]
br.player.ui.mode.taunt = br.data.settings[br.selectedSpec].toggles["Taunt"]
br.player.ui.mode.shield = br.data.settings[br.selectedSpec].toggles["Shield"]
br.player.ui.mode.reflect = br.data.settings[br.selectedSpec].toggles["Reflect"]
--------------
--- Locals ---
--------------
local buff = br.player.buff
local cast = br.player.cast
local combatTime = getCombatTime()
local cd = br.player.cd
local charges = br.player.charges
local deadMouse = UnitIsDeadOrGhost("mouseover")
local deadtar, attacktar, hastar, playertar = deadtar or UnitIsDeadOrGhost("target"), attacktar or UnitCanAttack("target", "player"), hastar or GetObjectExists("target"), UnitIsPlayer("target")
local debuff = br.player.debuff
local enemies = br.player.enemies
local falling, swimming, flying, moving = getFallTime(), IsSwimming(), IsFlying(), GetUnitSpeed("player") > 0
local friendly = friendly or GetUnitIsFriend("target", "player")
local gcd = br.player.gcd
local gcdMax = br.player.gcdMax
local healPot = getHealthPot()
local inCombat = br.player.inCombat
local inInstance = br.player.instance == "party"
local inRaid = br.player.instance == "raid"
local lowestHP = br.friend[1].unit
local mode = br.player.ui.mode
local perk = br.player.perk
local php = br.player.health
local playerMouse = UnitIsPlayer("mouseover")
local power, powerMax, powerGen = br.player.power.rage.amount(), br.player.power.rage.max(), br.player.power.rage.regen()
local pullTimer = br.DBM:getPulltimer()
local race = br.player.race
local racial = br.player.getRacial()
local rage, powerDeficit = br.player.power.rage.amount(), br.player.power.rage.deficit()
local solo = br.player.instance == "none"
local spell = br.player.spell
local talent = br.player.talent
local thp = getHP("target")
local ttd = getTTD
local ttm = br.player.power.rage.ttm()
local units = br.player.units
local hasAggro = UnitThreatSituation("player")
if hasAggro == nil then
hasAggro = 0
end
if timersTable then
wipe(timersTable)
end
units.get(5)
units.get(8)
enemies.get(5, nil, nil, nil, spell.pummel)
enemies.get(8, nil, nil, nil, spell.intimidatingShout)
enemies.get(10)
enemies.get(20)
enemies.get(30, nil, nil, nil, spell.taunt)
if leftCombat == nil then
leftCombat = GetTime()
end
if profileStop == nil then
profileStop = false
end
local reflectID = {
--Battle of Dazar'alor
[283572] = "Sacred Blade",
[284449] = "Reckoning",
[286988] = "Divine Burst",
[282036] = "Fireball",
[286988] = "Searing Embers",
[286646] = "Gigavolt Charge",
[282182] = "Buster Cannon",
--Uldir
[279669] = "Bacterial Outbreak",
[279660] = "Endemic Virus",
[274262] = "Explosive Corruption",
--Reaping
[288693] = "Grave Bolt",
--Atal'Dazar
[250096] = "Wracking Pain",
[253562] = "Wildfire",
[252923] = "Venom Blast",
--Kings Rest
[267618] = "Drain Fluids",
[267308] = "Lighting Bolt",
[270493] = "Spectral Bolt",
[269973] = "Deathly Chill",
[270923] = "Shadow Bolt",
--Free Hold
[259092] = "Lightning Bolt",
[281420] = "Water Bolt",
--Siege of Boralus
[272588] = "Rotting Wounds",
[272581] = "Water Spray",
[257063] = "Brackish Bolt",
[272571] = "Choking Waters",
-- Temple of Sethraliss
[263318] = "Jolt",
[263775] = "Gust",
[268061] = "Chain Lightning",
[272820] = "Shock",
[268013] = "Flame Shock",
[274642] = "Lava Burst",
[268703] = "Lightning Bolt",
[272699] = "Venomous Spit",
--Shrine of the Storm
[265001] = "Sea Blast",
[264560] = "Choking Brine",
[264144] = "Undertow",
[268347] = "Void Bolt",
[267969] = "Water Blast",
[268233] = "Electrifying Shock",
[268315] = "Lash",
[268177] = "Windblast",
[268273] = "Deep Smash",
[268317] = "Rip Mind",
[265001] = "Sea Blast",
[274703] = "Void Bolt",
[268214] = "Carve Flesh",
--Motherlode
[259856] = "Chemical Burn",
[260318] = "Alpha Cannon",
[262794] = "Energy Lash",
[263202] = "Rock Lance",
[262268] = "Caustic Compound",
[263262] = "Shale Spit",
[263628] = "Charged Claw",
--Underrot
[260879] = "Blood Bolt",
[265084] = "Blood Bolt",
--Tol Dagor
[257777] = "Crippling Shiv",
[257033] = "Fuselighter",
[258150] = "Salt Blast",
[258869] = "Blaze",
--Waycrest Manor
[260701] = "Bramble Bolt",
[260700] = "Ruinous Bolt",
[260699] = "Soul Bolt",
[268271] = "Wracking Chord",
[261438] = "Wasting Strike",
[261440] = "Virulent Pathogen",
[266225] = "Darkened Lightning",
[273653] = "Shadow Claw",
[265881] = "Decaying Touch",
[264153] = "Spit",
[278444] = "Infest",
--Operation: Mechagn
[298669] = "Taze",
[300764] = "slimebolt",
[300650] = "suffocating smog",
[294195] = "arcing zap",
[291878] = "pulse blast"
}
local Storm_unitList = {
[131009] = "Spirit of Gold",
[134388] = "A Knot of Snakes",
[129758] = "Irontide Grenadier"
}
--- Quick maths ---
local function mainTank()
if (#enemies.yards30 >= 1 and (hasAggro >= 2)) or isChecked("Open World Defensives") then
return true
else
return false
end
end
local function rageCap()
if not isExplosive("target") and cast.able.revenge() and rage >= getValue("High Rage Dump") and (not ipCapCheck() or not mainTank()) then
--print("dumping R")
if cast.revenge() then
return
end
end
end
------Stuff with the things ------
local function actionList_Extras()
if isChecked("Charge OoC") then
if cast.able.intercept("target") and getDistance("player", "target") <= 25 and not inCombat then
if cast.intercept("target") then
return
end
end
end
if isChecked("Battle Shout") and cast.able.battleShout() then
for i = 1, #br.friend do
local thisUnit = br.friend[i].unit
if not UnitIsDeadOrGhost(thisUnit) and getDistance(thisUnit) < 100 and getBuffRemain(thisUnit, spell.battleShout) < 60 then
if cast.battleShout() then
return
end
end
end
end
if inCombat and (getOptionValue("Trinkets") == 1 or (buff.avatar.exists() and getOptionValue("Trinkets") == 4)) then
if canTrinket(13) and getOptionValue("Trinket 1 Mode") == 1 then
useItem(13)
elseif canTrinket(13) and getOptionValue("Trinket 1 Mode") == 2 then
useItemGround("target", 13, 40, 0, nil)
end
if canTrinket(14) and getOptionValue("Trinket 2 Mode") == 1 then
useItem(14)
elseif canTrinket(14) and getOptionValue("Trinket 2 Mode") == 2 then
useItemGround("target", 14, 40, 0, nil)
end
end
end
local function offGCD()
if inCombat then
if cast.able.ignorePain() and rage >= getValue("High Rage Dump") and mainTank() and ipCapCheck() then
--print("dumping IP")
CastSpellByName(GetSpellInfo(190456))
end
if useDefensive() then
if mode.reflect == 1 and isChecked("Smart Spell Reflect") then
for i = 1, #enemies.yards30 do
local thisUnit = enemies.yards30[i]
local _, _, _, startCast, endCast, _, _, _, spellcastID = UnitCastingInfo(thisUnit)
if UnitTarget("player") and reflectID[spellcastID] and (((GetTime() * 1000) - startCast) / (endCast - startCast) * 100) > getOptionValue("Smart Spell Reflect Percent") then
if cast.spellReflection() then
return
end
end
end
end
if mode.shield == 1 and cast.able.shieldBlock() and mainTank() and (not buff.shieldBlock.exists() or (buff.shieldBlock.remain() <= (gcd * 1.5))) and not buff.lastStand.exists() and rage >= 30 then
if cast.shieldBlock() then
return
end
end
if talent.bolster and isChecked("Last Stand Filler") and not buff.shieldBlock.exists() and cd.shieldBlock.remain() > gcd and mainTank() then
if cast.lastStand() then
return
end
end
if cast.able.ignorePain() and mainTank() and ipCapCheck() then
if buff.vengeanceIgnorePain.exists() and rage >= 42 then
CastSpellByName(GetSpellInfo(190456))
end
if rage >= 55 and not buff.vengeanceRevenge.exists() then
CastSpellByName(GetSpellInfo(190456))
end
end
if isChecked("Shield Wall") and php <= getOptionValue("Shield Wall") and cd.lastStand.remain() > 0 and not buff.lastStand.exists() then
if cast.shieldWall() then
return
end
end
end
if isChecked("Berserker Rage") and hasNoControl(spell.berserkerRage) then
if cast.berserkerRage() then
return
end
end
for i = 1, #enemies.yards20 do
local thisUnit = enemies.yards20[i]
local unitDist = getDistance(thisUnit)
if not isExplosive(thisUnit) and canInterrupt(thisUnit, getOptionValue("Interrupt At")) then
if isChecked("Pummel") and unitDist < 6 then
if cast.pummel(thisUnit) then
return
end
end
end
end
if br.player.ui.mode.taunt == 1 and inInstance then
for i = 1, #enemies.yards30 do
local thisUnit = enemies.yards30[i]
if UnitThreatSituation("player", thisUnit) ~= nil and UnitThreatSituation("player", thisUnit) <= 2 and UnitAffectingCombat(thisUnit) then
if cast.taunt(thisUnit) then
return
end
end
end
end -- End Taunt
if br.player.ui.mode.taunt == 2 then
for i = 1, #enemies.yards30 do
local thisUnit = enemies.yards30[i]
if UnitThreatSituation("player", thisUnit) ~= nil and UnitThreatSituation("player", thisUnit) <= 2 and UnitAffectingCombat(thisUnit) then
if cast.taunt(thisUnit) then
return
end
end
end
end -- End Taunt
end
end
local function actionList_Interrupts()
if useInterrupts() then
if isChecked("Storm Bolt Logic") then
if cast.able.stormBolt() then
local Storm_list = {
274400,
274383,
257756,
276292,
268273,
256897,
272542,
272888,
269266,
258317,
258864,
259711,
258917,
264038,
253239,
269931,
270084,
270482,
270506,
270507,
267433,
267354,
268702,
268846,
268865,
258908,
264574,
272659,
272655,
267237,
265568,
277567,
265540,
268202,
258058,
257739
}
for i = 1, #enemies.yards20 do
local thisUnit = enemies.yards20[i]
local distance = getDistance(thisUnit)
for k, v in pairs(Storm_list) do
if (Storm_unitList[GetObjectID(thisUnit)] ~= nil or UnitCastingInfo(thisUnit) == GetSpellInfo(v) or UnitChannelInfo(thisUnit) == GetSpellInfo(v)) and getBuffRemain(thisUnit, 226510) == 0 and distance <= 20 then
if cast.stormBolt(thisUnit) then
return
end
end
end
end
end
end
for i = 1, #enemies.yards20 do
local thisUnit = enemies.yards20[i]
local unitDist = getDistance(thisUnit)
local targetMe = UnitIsUnit("player", thisUnit) or false
if not isExplosive(thisUnit) and canInterrupt(thisUnit, getOptionValue("Interrupt At")) then
if isChecked("Intimidating Shout - Int") and unitDist <= 8 then
if cast.intimidatingShout() then
return
end
end
if isChecked("Shockwave - Int") and unitDist < 10 then
if cast.shockwave() then
return
end
end
end
end
end
end
local function actionList_Moving()
if br.player.ui.mode.mover == 1 then
if cast.able.intercept("target") and getDistance("player", "target") >= 8 and getDistance("player", "target") <= 25 then
CastSpellByName(GetSpellInfo(spell.intercept))
end
end
end
local function actionList_Cooldowns()
if useCDs() and #enemies.yards5 >= 1 then
if isChecked("Avatar") then
--print("cd avatar")
if cast.avatar() then
return
end
end
if rage <= 100 and not moving and getOptionValue("Demoralizing Shout - CD") == 2 then
if cast.demoralizingShout() then
return
end
end
if not isExplosive("target") and talent.ravager then
if cast.ravager("best", false, 1, 8) then
return
end
end
if isChecked("Racial") and (race == "Orc" or race == "Troll" or race == "LightforgedDraenei") and useCDs() and buff.avatar.exists() then
if cast.racial("player") then
return
end
end
if isChecked("Racial") and useCDs() and buff.avatar.exists() then
CastSpellByName("Berserking")
end
--Use Trinkets
if inCombat and (getOptionValue("Trinkets") == 2 or (buff.avatar.exists() and getOptionValue("Trinkets") == 4)) then
if canTrinket(13) and getOptionValue("Trinket 1 Mode") == 1 then
useItem(13)
elseif canTrinket(13) and getOptionValue("Trinket 1 Mode") == 2 then
useItemGround("target", 13, 40, 0, nil)
end
if canTrinket(14) and getOptionValue("Trinket 2 Mode") == 1 then
useItem(14)
elseif canTrinket(14) and getOptionValue("Trinket 2 Mode") == 2 then
useItemGround("target", 14, 40, 0, nil)
end
end
end
end
local function actionList_Defensives()
if useDefensive() then
--Spell Reflect logic
if php <= 65 and cast.able.victoryRush() then
if cast.victoryRush() then
return
end
end
if isChecked("Engineering Belt") and php <= getOptionValue("Engineering Belt") and canUseItem(6) then
useItem(6)
end
if isChecked("Healthstone/Potion") and php <= getOptionValue("Healthstone/Potion") and inCombat and (hasHealthPot() or hasItem(5512) or hasItem(166799)) then
if canUseItem(5512) then
useItem(5512)
elseif canUseItem(healPot) then
useItem(healPot)
elseif hasItem(166799) and canUseItem(166799) then
useItem(166799)
end
end
if isChecked("Demoralizing Shout") and php <= getOptionValue("Demoralizing Shout") and getOptionValue("Demoralizing Shout - CD") == 1 then
if cast.demoralizingShout() then
return
end
end
if isChecked("Last Stand") and php <= getOptionValue("Last Stand") then
if cast.lastStand() then
return
end
end
if isChecked("Rallying Cry") and php <= getOptionValue("Rallying Cry") then
if cast.rallyingCry() then
return
end
end
if ((isChecked("Shockwave - HP") and php <= getOptionValue("Shockwave - HP")) or (isChecked("Shockwave - Units") and #enemies.yards8 >= getOptionValue("Shockwave - Units") and not moving)) then
if cast.shockwave() then
return
end
end
if mode.reflect == 1 and isChecked("Spell Reflection") and php <= getOptionValue("Spell Reflection") then
if cast.spellReflection() then
return
end
end
if isChecked("Storm Bolt") and php <= getOptionValue("Storm Bolt") then
if cast.stormBolt() then
return
end
end
end
end
local function actionList_Single()
--Avatar units
if isChecked("Avatar") and (#enemies.yards8 >= getOptionValue("Avatar Mob Count")) and br.player.ui.mode.cooldown == 1 then
---print("norm avatar")
if cast.avatar() then
return
end
end
-- Heroic Throw
if not isExplosive("target") and #enemies.yards10 == 0 and isChecked("Use Heroic Throw") then
if cast.heroicThrow("target") then
return
end
end
--Use Demo Shout on CD
if getOptionValue("Demoralizing Shout - CD") == 1 and rage <= 100 and not moving then
if cast.demoralizingShout() then
return
end
end
-- Ravager Usage
if not isExplosive("target") and isChecked("Ravager") then
if cast.ravager("target", "ground") then
return
end
end
--Dragon Roar
if not isExplosive("target") and isChecked("Dragon Roar") and not moving then
if cast.dragonRoar() then
return
end
end
--High Priority Thunder Clap
if not isExplosive("target") and #enemies.yards8 >= getValue("Aoe Priority") or debuff.demoralizingShout.exists(units.dyn8) then
if cast.thunderClap() then
return
end
end
-- Shield Slam
if cast.shieldSlam() then
return
end
-- High Prio Revenge
if not isExplosive("target") and #enemies.yards8 >= getValue("Aoe Priority") and (buff.revenge.exists() or rage >= getValue("High Rage Dump")) then
if cast.revenge() then
return
end
end
-- Low Prio Thunder Clap
if not isExplosive("target") and talent.cracklingThunder then
if cast.thunderClap("player", nil, 1, 12) then
return
end
else
if cast.thunderClap("player", nil, 1, 8) then
return
end
end
-- Revenge
if not isExplosive("target") and buff.revenge.exists() or (buff.vengeanceRevenge.exists() and rage >= 50) then
if cast.revenge() then
return
end
end
--avoid rage cap
if rageCap() then
return
end
--Less Victorious
if php <= 75 and (talent.impendingVictory or buff.victorious.exists()) and not (cast.able.shieldSlam() or cast.able.thunderClap()) then
if cast.victoryRush() then
return
end
end
--Devestate
if cd.shieldSlam.remain() > (gcdMax / 2) and (isExplosive("target") or cd.thunderClap.remain() > (gcdMax / 2)) then
if cast.devastate() then
return
end
end
end
local function corruptionstuff()
if br.player.equiped.shroudOfResolve and canUseItem(br.player.items.shroudOfResolve) then
if getValue("Use Cloak") == 1 and debuff.graspingTendrils.exists("player") or getValue("Use Cloak") == 2 and getDebuffStacks("player", 315161) >= getOptionValue("Eye Of Corruption Stacks - Cloak") or getValue("Use Cloak") == 3 and debuff.grandDelusions.exists("player") then
if br.player.use.shroudOfResolve() then
return
end
end
end
if isChecked("Corruption Radar On") then
for i = 1, GetObjectCountBR() do
local object = GetObjectWithIndex(i)
local ID = ObjectID(object)
if isChecked("Use Storm Bolt on TFTB") then
if ID == 161895 then
local x1, y1, z1 = ObjectPosition("player")
local x2, y2, z2 = ObjectPosition(object)
local distance = math.sqrt(((x2 - x1) ^ 2) + ((y2 - y1) ^ 2) + ((z2 - z1) ^ 2))
if distance <= 8 and isChecked("Use Int Shout on TFTB") and cd.intimidatingShout.remains() <= gcd then
if cast.intimidatingShout(object) then
return true
end
end
if distance < 10 and not isLongTimeCCed(object) and cd.stormBolt.remains() <= gcd then
if cast.stormBolt(object) then
return true
end
end
end
end -- end the thing
end
end
end
local function technoViking()
--Use Demo Shout on CD
if getOptionValue("Demoralizing Shout - CD") == 1 and rage <= 100 then
if cast.demoralizingShout() then
return
end
end
--stomp your feet
if not isExplosive("target") and talent.cracklingThunder then
if cast.thunderClap("player", nil, 1, 12) then
return
end
else
if cast.thunderClap("player", nil, 1, 8) then
return
end
end
-- High Prio revenge
if not isExplosive("target") and #enemies.yards8 >= getValue("Aoe Priority") and (buff.revenge.exists() or rage >= getValue("High Rage Dump")) then
if cast.revenge() then
return
end
end
-- Rest
if not cast.able.thunderClap() then
if cast.shieldSlam() then
return
end
end
-- Recover
if not isExplosive("target") and not (cast.able.thunderClap()) and (buff.revenge.exists() or rage >= getValue("High Rage Dump")) then
if cast.revenge() then
return
end
end
-- Drink
if not (cast.able.shieldSlam() or cast.able.thunderClap()) and ipCapCheck() and rage >= 55 then
CastSpellByName(GetSpellInfo(190456))
end
if not cast.able.shieldSlam() or (isExplosive("target") or cast.able.thunderClap()) then
if cast.devastate() then
return
end
end
end
if offGCD() then return end
--- Lets do things now
if pause(true) or (IsMounted() or IsFlying() or UnitOnTaxi("player") or UnitInVehicle("player")) or mode.rotation == 2 then
return true
else
-- combat check
if not inCombat and not IsMounted() then
if isChecked("Pig Catcher") then
bossHelper()
end
if actionList_Extras() then
return
end
end
if inCombat and profileStop == false and not (IsMounted() or IsFlying()) and #enemies.yards8 >= 1 then
if getDistance(units.dyn5) < 5 then
StartAttack()
end
if corruptionstuff() then
return
end
if actionList_Extras() then
return
end
--I totally did this .. MOHAHAHA ... but Panglo said I could, eh!
if actionList_Interrupts() then
return
end
if actionList_Defensives() then
return
end
if actionList_Moving() then
return
end
if actionList_Cooldowns() then
return
end
if (talent.unstoppableForce and buff.avatar.exists()) then
if technoViking() then
return
end
end
if not (talent.unstoppableForce and buff.avatar.exists()) then
if actionList_Single() then
return
end
end
end
end
--pause
end
--timer
end
--runrotation
local id = 73
if br.rotations[id] == nil then
br.rotations[id] = {}
end
tinsert(
br.rotations[id],
{
name = rotationName,
toggles = createToggles,
options = createOptions,
run = runRotation
}
)
| gpl-3.0 |
robert00s/koreader | spec/unit/nickel_conf_spec.lua | 1 | 4417 | describe("Nickel configuation module", function()
local lfs, NickelConf
setup(function()
require("commonrequire")
lfs = require("libs/libkoreader-lfs")
NickelConf = require("device/kobo/nickel_conf")
end)
describe("Frontlight module", function()
it("should read value", function()
local fn = os.tmpname()
local fd = io.open(fn, "w")
fd:write([[
[OtherThing]
foo=bar
[PowerOptions]
FrontLightLevel=55
FrontLightState=true
[YetAnotherThing]
bar=baz
]])
fd:close()
NickelConf._set_kobo_conf_path(fn)
assert.Equals(NickelConf.frontLightLevel.get(), 55)
assert.Equals(NickelConf.frontLightState.get(), true)
os.remove(fn)
end)
it("should also read value", function()
local fn = os.tmpname()
local fd = io.open(fn, "w")
fd:write([[
[OtherThing]
foo=bar
[PowerOptions]
FrontLightLevel=30
FrontLightState=false
[YetAnotherThing]
bar=baz
]])
fd:close()
NickelConf._set_kobo_conf_path(fn)
assert.Equals(NickelConf.frontLightLevel.get(), 30)
assert.Equals(NickelConf.frontLightState.get(), false)
os.remove(fn)
end)
it("should have default value", function()
local fn = os.tmpname()
local fd = io.open(fn, "w")
fd:write([[
[OtherThing]
foo=bar
[YetAnotherThing]
bar=baz
]])
fd:close()
NickelConf._set_kobo_conf_path(fn)
assert.Equals(NickelConf.frontLightLevel.get(), 1)
assert.Equals(NickelConf.frontLightState.get(), nil)
os.remove(fn)
end)
it("should create section", function()
local fn = os.tmpname()
local fd = io.open(fn, "w")
fd:write([[
[OtherThing]
FrontLightLevel=6
]])
fd:close()
NickelConf._set_kobo_conf_path(fn)
NickelConf.frontLightLevel.set(100)
NickelConf.frontLightState.set(true)
fd = io.open(fn, "r")
assert.Equals(fd:read("*a"), [[
[OtherThing]
FrontLightLevel=6
[PowerOptions]
FrontLightLevel=100
]])
fd:close()
os.remove(fn)
fd = io.open(fn, "w")
fd:write("")
fd:close()
NickelConf.frontLightLevel.set(20)
NickelConf.frontLightState.set(false)
fd = io.open(fn, "r")
assert.Equals(fd:read("*a"), [[
[PowerOptions]
FrontLightLevel=20
]])
fd:close()
os.remove(fn)
end)
it("should replace value", function()
local fn = os.tmpname()
local fd = io.open(fn, "w")
fd:write([[
[OtherThing]
foo=bar
[PowerOptions]
FrontLightLevel=6
FrontLightState=false
[YetAnotherThing]
bar=baz
]])
fd:close()
NickelConf._set_kobo_conf_path(fn)
NickelConf.frontLightLevel.set(100)
NickelConf.frontLightState.set(true)
fd = io.open(fn, "r")
assert.Equals(fd:read("*a"), [[
[OtherThing]
foo=bar
[PowerOptions]
FrontLightLevel=100
FrontLightState=true
[YetAnotherThing]
bar=baz
]])
fd:close()
os.remove(fn)
end)
it("should insert entry", function()
local fn = os.tmpname()
local fd = io.open(fn, "w")
fd:write([[
[PowerOptions]
foo=bar
[OtherThing]
bar=baz
]])
fd:close()
NickelConf._set_kobo_conf_path(fn)
NickelConf.frontLightLevel.set(1)
NickelConf.frontLightState.set(true)
fd = io.open(fn, "r")
assert.Equals([[
[PowerOptions]
foo=bar
FrontLightLevel=1
[OtherThing]
bar=baz
]], fd:read("*a"))
fd:close()
os.remove(fn)
end)
it("should create config file", function()
local fn = "/tmp/abcfoobarbaz449"
assert.is_not.Equals(lfs.attributes(fn, "mode"), "file")
finally(function() os.remove(fn) end)
NickelConf._set_kobo_conf_path(fn)
NickelConf.frontLightLevel.set(15)
NickelConf.frontLightState.set(false)
fd = io.open(fn, "r")
assert.Equals([[
[PowerOptions]
FrontLightLevel=15
]],
fd:read("*a"))
fd:close()
end)
end)
end)
| agpl-3.0 |
nielsutrecht/computercraft | hydraLogApi.lua | 1 | 1310 | local urlbase = "http://localhost:8080/reactor"
local headers = {
["Content-Type"] = "application/json"
}
if(not os.loadAPI("hydraApi")) then
error("Could not load hydraApi")
end
function getReactorInfo(reactor)
local info = {}
info['energy'] = reactor.getEnergyStored()
info['energyProduction'] = reactor.getEnergyProducedLastTick()
info['fuelTemperature'] = reactor.getFuelTemperature()
info['energyFraction'] = reactor.getEnergyStored() / 10000000
info['controlRods'] = reactor.getNumberOfControlRods()
info['active'] = reactor.getActive()
info['fuelReactivity'] = reactor.getFuelReactivity()
info['fuelConsumption'] = reactor.getFuelConsumedLastTick()
local x, y, z = reactor.getMinimumCoordinate()
info['minCoordinate'] = {x, y, z }
x, y, z = reactor.getMaximumCoordinate()
info['maxCoordinate'] = {x, y, z }
local avg = 0
for i = 0,info['controlRods'] - 1 do
avg = avg + reactor.getControlRodLevel(i)
end
info['controlRodAverage'] = avg / info['controlRods']
return info
end
function logReactor(base, reactorid, reactor)
local json = textutils.serializeJSON(getReactorInfo(reactor))
local handle = http.post(urlbase, json, headers)
return handle ~= nil and handle.getResponseCode() == 200
end
| mit |
robert00s/koreader | frontend/ui/widget/closebutton.lua | 1 | 2073 | --[[--
Button widget that shows an "×" and handles closing window when tapped
Example:
local CloseButton = require("ui/widget/closebutton")
local parent_widget = OverlapGroup:new{}
table.insert(parent_widget, CloseButton:new{
window = parent_widget,
})
UIManager:show(parent_widget)
]]
local Font = require("ui/font")
local FrameContainer = require("ui/widget/container/framecontainer")
local GestureRange = require("ui/gesturerange")
local HorizontalGroup = require("ui/widget/horizontalgroup")
local HorizontalSpan = require("ui/widget/horizontalspan")
local InputContainer = require("ui/widget/container/inputcontainer")
local TextWidget = require("ui/widget/textwidget")
local Screen = require("device").screen
local CloseButton = InputContainer:new{
overlap_align = "right",
window = nil,
}
function CloseButton:init()
local text_widget = TextWidget:new{
text = "×",
face = Font:getFace("cfont", 32),
}
local padding_span = HorizontalSpan:new{ width = Screen:scaleBySize(14) }
self[1] = FrameContainer:new{
bordersize = 0,
padding = 0,
HorizontalGroup:new{
padding_span,
text_widget,
padding_span,
}
}
self.ges_events.Close = {
GestureRange:new{
ges = "tap",
-- x and y coordinates for the widget is only known after the it is
-- drawn. so use callback to get range at runtime.
range = function() return self.dimen end,
},
doc = "Tap on close button",
}
self.ges_events.HoldClose = {
GestureRange:new{
ges = "hold_release",
range = function() return self.dimen end,
},
doc = "Hold on close button",
}
end
function CloseButton:onClose()
if self.window.onClose then
self.window:onClose()
end
return true
end
function CloseButton:onHoldClose()
if self.window.onHoldClose then
self.window:onHoldClose()
end
return true
end
return CloseButton
| agpl-3.0 |
FrisKAY/MineOS_Server | Beta/bufferNotOptimized.lua | 1 | 21823 |
-- Адаптивная загрузка необходимых библиотек и компонентов
local libraries = {
["component"] = "component",
["unicode"] = "unicode",
["image"] = "image",
["colorlib"] = "colorlib",
}
local components = {
["gpu"] = "gpu",
}
for library in pairs(libraries) do if not _G[library] then _G[library] = require(libraries[library]) end end
for comp in pairs(components) do if not _G[comp] then _G[comp] = _G.component[components[comp]] end end
libraries, components = nil, nil
local buffer = {}
local debug = false
local sizeOfPixelData = 3
------------------------------------------------- Вспомогательные методы -----------------------------------------------------------------
--Формула конвертации индекса массива изображения в абсолютные координаты пикселя изображения
local function convertIndexToCoords(index)
--Приводим индекс к корректному виду (1 = 1, 4 = 2, 7 = 3, 10 = 4, 13 = 5, ...)
index = (index + sizeOfPixelData - 1) / sizeOfPixelData
--Получаем остаток от деления индекса на ширину изображения
local ostatok = index % buffer.screen.width
--Если остаток равен 0, то х равен ширине изображения, а если нет, то х равен остатку
local x = (ostatok == 0) and buffer.screen.width or ostatok
--А теперь как два пальца получаем координату по Y
local y = math.ceil(index / buffer.screen.width)
--Очищаем остаток из оперативки
ostatok = nil
--Возвращаем координаты
return x, y
end
--Формула конвертации абсолютных координат пикселя изображения в индекс для массива изображения
local function convertCoordsToIndex(x, y)
return (buffer.screen.width * (y - 1) + x) * sizeOfPixelData - sizeOfPixelData + 1
end
local function printDebug(line, text)
if debug then
ecs.square(1, line, buffer.screen.width, 1, 0x262626)
ecs.colorText(2, line, 0xFFFFFF, text)
end
end
-- Установить ограниченную зону рисования. Все пиксели, не попадающие в эту зону, будут игнорироваться.
function buffer.setDrawLimit(x, y, width, height)
buffer.drawLimit = { x1 = x, y1 = y, x2 = x + width - 1, y2 = y + height - 1 }
end
-- Удалить ограничение зоны рисования, по умолчанию она будет от 1х1 до координат размера экрана.
function buffer.resetDrawLimit()
buffer.drawLimit = {x1 = 1, y1 = 1, x2 = buffer.screen.width, y2 = buffer.screen.height}
end
-- Создать массив буфера с базовыми переменными и базовыми цветами. Т.е. черный фон, белый текст.
function buffer.start()
buffer.screen = {}
buffer.screen.current = {}
buffer.screen.new = {}
buffer.screen.width, buffer.screen.height = gpu.getResolution()
buffer.resetDrawLimit()
for y = 1, buffer.screen.height do
for x = 1, buffer.screen.width do
table.insert(buffer.screen.current, 0x010101)
table.insert(buffer.screen.current, 0xFEFEFE)
table.insert(buffer.screen.current, " ")
table.insert(buffer.screen.new, 0x010101)
table.insert(buffer.screen.new, 0xFEFEFE)
table.insert(buffer.screen.new, " ")
end
end
end
------------------------------------------------- Методы отрисовки -----------------------------------------------------------------
-- Получить информацию о пикселе из буфера
function buffer.get(x, y)
local index = convertCoordsToIndex(x, y)
if x >= buffer.drawLimit.x1 and y >= buffer.drawLimit.y1 and x <= buffer.drawLimit.x2 and y <= buffer.drawLimit.y2 then
return buffer.screen.current[index], buffer.screen.current[index + 1], buffer.screen.current[index + 2]
else
error("Невозможно получить указанные значения, так как указанные координаты лежат за пределами экрана.\n")
end
end
-- Установить пиксель в буфере
function buffer.set(x, y, background, foreground, symbol)
local index = convertCoordsToIndex(x, y)
if x >= buffer.drawLimit.x1 and y >= buffer.drawLimit.y1 and x <= buffer.drawLimit.x2 and y <= buffer.drawLimit.y2 then
buffer.screen.new[index] = background
buffer.screen.new[index + 1] = foreground
buffer.screen.new[index + 2] = symbol
end
end
--Нарисовать квадрат
function buffer.square(x, y, width, height, background, foreground, symbol, transparency)
local index
if transparency then transparency = transparency * 2.55 end
for j = y, (y + height - 1) do
for i = x, (x + width - 1) do
if i >= buffer.drawLimit.x1 and j >= buffer.drawLimit.y1 and i <= buffer.drawLimit.x2 and j <= buffer.drawLimit.y2 then
index = convertCoordsToIndex(i, j)
if transparency then
buffer.screen.new[index] = colorlib.alphaBlend(buffer.screen.new[index], background, transparency)
buffer.screen.new[index + 1] = colorlib.alphaBlend(buffer.screen.new[index + 1], background, transparency)
else
buffer.screen.new[index] = background
buffer.screen.new[index + 1] = foreground
buffer.screen.new[index + 2] = symbol
end
end
end
end
end
--Очистка экрана, по сути более короткая запись buffer.square
function buffer.clear(color)
buffer.square(1, 1, buffer.screen.width, buffer.screen.height, color or 0x262626, 0xFFFFFF, " ")
end
--Заливка области изображения (рекурсивная, говно-метод)
function buffer.fill(x, y, background, foreground, symbol)
local startBackground, startForeground, startSymbol
local function doFill(xStart, yStart)
local index = convertCoordsToIndex(xStart, yStart)
if
buffer.screen.new[index] ~= startBackground or
-- buffer.screen.new[index + 1] ~= startForeground or
-- buffer.screen.new[index + 2] ~= startSymbol or
buffer.screen.new[index] == background
-- buffer.screen.new[index + 1] == foreground or
-- buffer.screen.new[index + 2] == symbol
then
return
end
--Заливаем в память
if xStart >= buffer.drawLimit.x1 and yStart >= buffer.drawLimit.y1 and xStart <= buffer.drawLimit.x2 and yStart <= buffer.drawLimit.y2 then
buffer.screen.new[index] = background
buffer.screen.new[index + 1] = foreground
buffer.screen.new[index + 2] = symbol
end
doFill(xStart + 1, yStart)
doFill(xStart - 1, yStart)
doFill(xStart, yStart + 1)
doFill(xStart, yStart - 1)
iterator = nil
end
local startIndex = convertCoordsToIndex(x, y)
startBackground = buffer.screen.new[startIndex]
startForeground = buffer.screen.new[startIndex + 1]
startSymbol = buffer.screen.new[startIndex + 2]
doFill(x, y)
end
--Нарисовать окружность, алгоритм спизжен с вики
function buffer.circle(xCenter, yCenter, radius, background, foreground, symbol)
--Подфункция вставки точек
local function insertPoints(x, y)
buffer.set(xCenter + x * 2, yCenter + y, background, foreground, symbol)
buffer.set(xCenter + x * 2, yCenter - y, background, foreground, symbol)
buffer.set(xCenter - x * 2, yCenter + y, background, foreground, symbol)
buffer.set(xCenter - x * 2, yCenter - y, background, foreground, symbol)
buffer.set(xCenter + x * 2 + 1, yCenter + y, background, foreground, symbol)
buffer.set(xCenter + x * 2 + 1, yCenter - y, background, foreground, symbol)
buffer.set(xCenter - x * 2 + 1, yCenter + y, background, foreground, symbol)
buffer.set(xCenter - x * 2 + 1, yCenter - y, background, foreground, symbol)
end
local x = 0
local y = radius
local delta = 3 - 2 * radius;
while (x < y) do
insertPoints(x, y);
insertPoints(y, x);
if (delta < 0) then
delta = delta + (4 * x + 6)
else
delta = delta + (4 * (x - y) + 10)
y = y - 1
end
x = x + 1
end
if x == y then insertPoints(x, y) end
end
--Скопировать область изображения и вернуть ее в виде массива
function buffer.copy(x, y, width, height)
local copyArray = {
["width"] = width,
["height"] = height,
}
if x < 1 or y < 1 or x + width - 1 > buffer.screen.width or y + height - 1 > buffer.screen.height then
errror("Область копирования выходит за пределы экрана.")
end
local index
for j = y, (y + height - 1) do
for i = x, (x + width - 1) do
index = convertCoordsToIndex(i, j)
table.insert(copyArray, buffer.screen.new[index])
table.insert(copyArray, buffer.screen.new[index + 1])
table.insert(copyArray, buffer.screen.new[index + 2])
end
end
return copyArray
end
--Вставить скопированную ранее область изображения
function buffer.paste(x, y, copyArray)
local index, arrayIndex
if not copyArray or #copyArray == 0 then error("Массив области экрана пуст.") end
for j = y, (y + copyArray.height - 1) do
for i = x, (x + copyArray.width - 1) do
if i >= buffer.drawLimit.x1 and j >= buffer.drawLimit.y1 and i <= buffer.drawLimit.x2 and j <= buffer.drawLimit.y2 then
--Рассчитываем индекс массива основного изображения
index = convertCoordsToIndex(i, j)
--Копипаст формулы, аккуратнее!
--Рассчитываем индекс массива вставочного изображения
arrayIndex = (copyArray.width * ((j - y + 1) - 1) + (i - x + 1)) * sizeOfPixelData - sizeOfPixelData + 1
--Вставляем данные
buffer.screen.new[index] = copyArray[arrayIndex]
buffer.screen.new[index + 1] = copyArray[arrayIndex + 1]
buffer.screen.new[index + 2] = copyArray[arrayIndex + 2]
end
end
end
end
--Нарисовать линию, алгоритм спизжен с вики
function buffer.line(x1, y1, x2, y2, background, foreground, symbol)
local deltaX = math.abs(x2 - x1)
local deltaY = math.abs(y2 - y1)
local signX = (x1 < x2) and 1 or -1
local signY = (y1 < y2) and 1 or -1
local errorCyka = deltaX - deltaY
local errorCyka2
buffer.set(x2, y2, background, foreground, symbol)
while(x1 ~= x2 or y1 ~= y2) do
buffer.set(x1, y1, background, foreground, symbol)
errorCyka2 = errorCyka * 2
if (errorCyka2 > -deltaY) then
errorCyka = errorCyka - deltaY
x1 = x1 + signX
end
if (errorCyka2 < deltaX) then
errorCyka = errorCyka + deltaX
y1 = y1 + signY
end
end
end
-- Отрисовка текста, подстраивающегося под текущий фон
function buffer.text(x, y, color, text, transparency)
local index
if transparency then transparency = transparency * 2.55 end
local sText = unicode.len(text)
for i = 1, sText do
if (x + i - 1) >= buffer.drawLimit.x1 and y >= buffer.drawLimit.y1 and (x + i - 1) <= buffer.drawLimit.x2 and y <= buffer.drawLimit.y2 then
index = convertCoordsToIndex(x + i - 1, y)
buffer.screen.new[index + 1] = not transparency and color or colorlib.alphaBlend(buffer.screen.new[index], color, transparency)
buffer.screen.new[index + 2] = unicode.sub(text, i, i)
end
end
end
-- Отрисовка изображения
function buffer.image(x, y, picture)
if not image then image = require("image") end
local index, imageIndex
for j = y, (y + picture.height - 1) do
for i = x, (x + picture.width - 1) do
if i >= buffer.drawLimit.x1 and j >= buffer.drawLimit.y1 and i <= buffer.drawLimit.x2 and j <= buffer.drawLimit.y2 then
index = convertCoordsToIndex(i, j)
--Копипаст формулы!
imageIndex = (picture.width * ((j - y + 1) - 1) + (i - x + 1)) * 4 - 4 + 1
if picture[imageIndex + 2] ~= 0x00 then
buffer.screen.new[index] = colorlib.alphaBlend(buffer.screen.new[index], picture[imageIndex], picture[imageIndex + 2])
else
buffer.screen.new[index] = picture[imageIndex]
end
buffer.screen.new[index + 1] = picture[imageIndex + 1]
buffer.screen.new[index + 2] = picture[imageIndex + 3]
end
end
end
end
-- Кнопка фиксированных размеров
function buffer.button(x, y, width, height, background, foreground, text)
local textPosX = math.floor(x + width / 2 - unicode.len(text) / 2)
local textPosY = math.floor(y + height / 2)
buffer.square(x, y, width, height, background, 0xFFFFFF, " ")
buffer.text(textPosX, textPosY, foreground, text)
return x, y, (x + width - 1), (y + height - 1)
end
-- Кнопка, подстраивающаяся под длину текста
function buffer.adaptiveButton(x, y, xOffset, yOffset, background, foreground, text)
local width = xOffset * 2 + unicode.len(text)
local height = yOffset * 2 + 1
buffer.square(x, y, width, height, background, 0xFFFFFF, " ")
buffer.text(x + xOffset, y + yOffset, foreground, text)
return x, y, (x + width - 1), (y + height - 1)
end
-- Вертикальный скролл-бар
function buffer.scrollBar(x, y, width, height, countOfAllElements, currentElement, backColor, frontColor)
local sizeOfScrollBar = math.ceil(1 / countOfAllElements * height)
local displayBarFrom = math.floor(y + height * ((currentElement - 1) / countOfAllElements))
buffer.square(x, y, width, height, backColor, 0xFFFFFF, " ")
buffer.square(x, displayBarFrom, width, sizeOfScrollBar, frontColor, 0xFFFFFF, " ")
sizeOfScrollBar, displayBarFrom = nil, nil
end
-- Отрисовка любого изображения в виде трехмерного массива. Неоптимизированно, зато просто.
function buffer.customImage(x, y, pixels)
x = x - 1
y = y - 1
for i=1, #pixels do
for j=1, #pixels[1] do
if pixels[i][j][3] ~= "#" then
buffer.set(x + j, y + i, pixels[i][j][1], pixels[i][j][2], pixels[i][j][3])
end
end
end
return (x + 1), (y + 1), (x + #pixels[1]), (y + #pixels)
end
--Нарисовать топ-меню, горизонтальная полоска такая с текстами
function buffer.menu(x, y, width, color, selectedObject, ...)
local objects = { ... }
local objectsToReturn = {}
local xPos = x + 2
local spaceBetween = 2
buffer.square(x, y, width, 1, color, 0xFFFFFF, " ")
for i = 1, #objects do
if i == selectedObject then
buffer.square(xPos - 1, y, unicode.len(objects[i][1]) + spaceBetween, 1, 0x3366CC, 0xFFFFFF, " ")
buffer.text(xPos, y, 0xFFFFFF, objects[i][1])
else
buffer.text(xPos, y, objects[i][2], objects[i][1])
end
objectsToReturn[objects[i][1]] = { xPos, y, xPos + unicode.len(objects[i][1]) - 1, y, i }
xPos = xPos + unicode.len(objects[i][1]) + spaceBetween
end
return objectsToReturn
end
-- Прамоугольная рамочка
function buffer.frame(x, y, width, height, color)
local stringUp = "┌" .. string.rep("─", width - 2) .. "┐"
local stringDown = "└" .. string.rep("─", width - 2) .. "┘"
buffer.text(x, y, color, stringUp)
buffer.text(x, y + height - 1, color, stringDown)
local yPos = 1
for i = 1, (height - 2) do
buffer.text(x, y + yPos, color, "│")
buffer.text(x + width - 1, y + yPos, color, "│")
yPos = yPos + 1
end
end
-- Кнопка в виде текста в рамке
function buffer.framedButton(x, y, width, height, backColor, buttonColor, text)
buffer.square(x, y, width, height, backColor, buttonColor, " ")
buffer.frame(x, y, width, height, buttonColor)
x = x + math.floor(width / 2 - unicode.len(text) / 2)
y = y + math.floor(width / 2 - 1)
buffer.text(x, y, buttonColor, text)
end
------------------------------------------- Просчет изменений и отрисовка ------------------------------------------------------------------------
--Функция рассчитывает изменения и применяет их, возвращая то, что было изменено
function buffer.calculateDifference(index)
local somethingIsChanged = false
--Если цвет фона на новом экране отличается от цвета фона на текущем, то
if buffer.screen.new[index] ~= buffer.screen.current[index] then
--Присваиваем цвету фона на текущем экране значение цвета фона на новом экране
buffer.screen.current[index] = buffer.screen.new[index]
--Говорим системе, что что-то изменилось
somethingIsChanged = true
end
index = index + 1
--Аналогично для цвета текста
if buffer.screen.new[index] ~= buffer.screen.current[index] then
buffer.screen.current[index] = buffer.screen.new[index]
somethingIsChanged = true
end
index = index + 1
--И для символа
if buffer.screen.new[index] ~= buffer.screen.current[index] then
buffer.screen.current[index] = buffer.screen.new[index]
somethingIsChanged = true
end
return somethingIsChanged
end
--Функция группировки изменений и их отрисовки на экран
function buffer.draw(force)
--Необходимые переменные, дабы не создавать их в цикле и не генерировать конструкторы
local somethingIsChanged, index, indexPlus1, indexPlus2, massiv, x, y
--Массив третьего буфера, содержащий в себе измененные пиксели
-- buffer.screen.changes = {}
--Перебираем содержимое нашего буфера по X и Y
for y = 1, buffer.screen.height do
x = 1
while x <= buffer.screen.width do
--Получаем индекс массива из координат, уменьшая нагрузку на CPU
index = convertCoordsToIndex(x, y)
indexPlus1 = index + 1
indexPlus2 = index + 2
--Получаем изменения и применяем их
somethingIsChanged = buffer.calculateDifference(index)
--Если хоть что-то изменилось, то начинаем работу
if somethingIsChanged or force then
gpu.setBackground(buffer.screen.current[index]])
gpu.setForeground(buffer.screen.current[indexPlus1])
gpu.set(x, y, buffer.screen.current[indexPlus2])
--Оптимизация by Krutoy, создаем массив, в который заносим чарсы. Работает быстрее, чем конкатенейт строк
-- massiv = { buffer.screen.current[indexPlus2] }
-- --Загоняем в наш чарс-массив одинаковые пиксели справа, если таковые имеются
-- local iIndex
-- local i = x + 1
-- while i <= buffer.screen.width do
-- iIndex = convertCoordsToIndex(i, y)
-- if
-- buffer.screen.current[index] == buffer.screen.new[iIndex] and
-- (
-- buffer.screen.new[iIndex + 2] == " "
-- or
-- buffer.screen.current[indexPlus1] == buffer.screen.new[iIndex + 1]
-- )
-- then
-- buffer.calculateDifference(iIndex)
-- table.insert(massiv, buffer.screen.current[iIndex + 2])
-- else
-- break
-- end
-- i = i + 1
-- end
-- --Заполняем третий буфер полученными данными
-- buffer.screen.changes[buffer.screen.current[indexPlus1]] = buffer.screen.changes[buffer.screen.current[indexPlus1]] or {}
-- buffer.screen.changes[buffer.screen.current[indexPlus1]][buffer.screen.current[index]] = buffer.screen.changes[buffer.screen.current[indexPlus1]][buffer.screen.current[index]] or {}
-- table.insert(buffer.screen.changes[buffer.screen.current[indexPlus1]][buffer.screen.current[index]], index)
-- table.insert(buffer.screen.changes[buffer.screen.current[indexPlus1]][buffer.screen.current[index]], table.concat(massiv))
--Смещаемся по иксу вправо
x = x + #massiv - 1
end
x = x + 1
end
end
--Сбрасываем переменные на невозможное значение цвета, чтобы не багнуло
-- index, indexPlus1 = -math.huge, -math.huge
--Перебираем все цвета текста и фона, выполняя гпу-операции
-- for foreground in pairs(buffer.screen.changes) do
-- if indexPlus1 ~= foreground then gpu.setForeground(foreground); indexPlus1 = foreground end
-- for background in pairs(buffer.screen.changes[foreground]) do
-- if index ~= background then gpu.setBackground(background); index = background end
-- for i = 1, #buffer.screen.changes[foreground][background], 2 do
-- --Конвертируем указанный индекс в координаты
-- x, y = convertIndexToCoords(buffer.screen.changes[foreground][background][i])
-- --Выставляем ту самую собранную строку из одинаковых цветов
-- gpu.set(x, y, buffer.screen.changes[foreground][background][i + 1])
-- end
-- end
-- end
--Очищаем память, ибо незачем нам хранить третий буфер
-- buffer.screen.changes = {}
-- buffer.screen.changes = nil
end
------------------------------------------------------------------------------------------------------
buffer.start()
------------------------------------------------------------------------------------------------------
return buffer
| gpl-3.0 |
bigdogmat/wire | lua/entities/gmod_wire_hdd.lua | 1 | 8647 | AddCSLuaFile()
DEFINE_BASECLASS( "base_wire_entity" )
ENT.PrintName = "Wire Flash EEPROM"
ENT.WireDebugName = "WireHDD"
if CLIENT then return end -- No more client
function ENT:OnRemove()
for k,v in pairs(self.CacheUpdated) do
file.Write(self:GetStructName(k),self:MakeFloatTable(self.Cache[k]))
end
end
function ENT:Initialize()
self:PhysicsInit(SOLID_VPHYSICS)
self:SetMoveType(MOVETYPE_VPHYSICS)
self:SetSolid(SOLID_VPHYSICS)
self:SetUseType(SIMPLE_USE)
self.Outputs = Wire_CreateOutputs(self, { "Data", "Capacity", "DriveID" })
self.Inputs = Wire_CreateInputs(self, { "Clk", "AddrRead", "AddrWrite", "Data" })
self.Clk = 0
self.AWrite = 0
self.ARead = 0
self.Data = 0
self.Out = 0
-- Flash type
-- 0: compatibility 16 values per block mode
-- 1: 128 values per block mode
self.FlashType = 0
self.BlockSize = 16
-- Hard drive id/folder id:
self.DriveID = 0
self.PrevDriveID = nil
-- Hard drive capicacity (loaded from hdd)
self.DriveCap = 0
self.MaxAddress = 0
-- Current cache (array of blocks)
self.Cache = {}
self.CacheUpdated = {}
-- Owners STEAMID
self.Owner_SteamID = "SINGLEPLAYER"
self:NextThink(CurTime()+1.0)
end
function ENT:Setup(DriveID, DriveCap)
self.DriveID = DriveID
self.DriveCap = DriveCap
self:UpdateCap()
self:SetOverlayText(self.DriveCap.."kb".."\nWriteAddr:"..self.AWrite.." Data:"..self.Data.." Clock:"..self.Clk.."\nReadAddr:"..self.ARead.." = ".. self.Out)
Wire_TriggerOutput(self, "DriveID", self.DriveID)
end
function ENT:GetStructName(name)
return "WireFlash/"..(self.Owner_SteamID or "UNKNOWN").."/HDD"..self.DriveID.."/"..name..".txt"
end
function ENT:GetCap()
-- If hard drive exists
if file.Exists(self:GetStructName("drive"),"DATA") then
-- Read format data
local formatData = file.Read(self:GetStructName("drive"),"DATA")
if tonumber(formatData) then
self.DriveCap = tonumber(formatData)
self.FlashType = 0
self.BlockSize = 16
self.MaxAddress = self.DriveCap * 1024
else
local formatInfo = string.Explode("\n",formatData)
if (formatInfo[1] == "FLASH1") then
self.DriveCap = tonumber(formatInfo[2]) or 0
self.MaxAddress = tonumber(formatInfo[3]) or (self.DriveCap * 1024)
self.FlashType = 1
self.BlockSize = 32
else
file.Write(self:GetStructName("drive"),"FLASH1\n"..self.DriveCap.."\n"..self.MaxAddress)
end
end
else
file.Write(self:GetStructName("drive"),"FLASH1\n"..self.DriveCap.."\n"..self.MaxAddress)
self.FlashType = 1
self.BlockSize = 32
self.MaxAddress = 0
end
--Can't have cap bigger than 256 in MP
if (not game.SinglePlayer()) and (self.DriveCap > 256) then
self.DriveCap = 256
end
Wire_TriggerOutput(self, "Capacity", self.DriveCap)
end
function ENT:UpdateCap()
--Can't have cap bigger than 256 in MP
if (not game.SinglePlayer()) and (self.DriveCap > 256) then
self.DriveCap = 256
end
if self.FlashType == 0 then
file.Write(self:GetStructName("drive"),self.DriveCap)
else
file.Write(self:GetStructName("drive"),"FLASH1\n"..self.DriveCap.."\n"..self.MaxAddress)
end
self:GetCap()
end
function ENT:GetFloatTable(Text)
local text = Text
local tbl = {}
local ptr = 0
while (string.len(text) > 0) do
local value = string.sub(text, 1, 24)
text = string.sub(text, 25)
tbl[ptr] = tonumber(value)
ptr = ptr + 1
end
return tbl
end
function ENT:MakeFloatTable(Table)
local text = ""
for i=0,#Table-1 do
--Clamp size to 24 chars
local floatstr = string.sub(tostring(Table[i]),1,24)
--Make a string, and append missing spaces
floatstr = floatstr .. string.rep(" ",24-string.len(floatstr))
text = text..floatstr
end
return text
end
function ENT:ReadCell(Address)
--DriveID should be > 0, and less than 4 in MP
if ((self.DriveID < 0) || (!game.SinglePlayer() && (self.DriveID >= 4))) then
return nil
end
local player = self:GetPlayer()
if player:IsValid() then
local steamid = player:SteamID()
steamid = string.gsub(steamid, ":", "_")
if (steamid ~= "UNKNOWN") then
self.Owner_SteamID = steamid
else
self.Owner_SteamID = "SINGLEPLAYER"
end
-- If drive has changed, change cap
if self.DriveID ~= self.PrevDriveID then
self:GetCap()
self.PrevDriveID = self.DriveID
end
-- Check if address is valid
if (Address < self.DriveCap * 1024) and (Address >= 0) then
-- Compute address
local block = math.floor(Address / self.BlockSize)
local blockaddress = math.floor(Address) % self.BlockSize
-- Check if this address is cached for read
if self.Cache[block] then
return self.Cache[block][blockaddress] or 0
end
-- If sector isn't created yet, return 0
if not file.Exists(self:GetStructName(block),"DATA") then
self.Cache[block] = {}
self.CacheUpdated[block] = true
for i=0,self.BlockSize-1 do
self.Cache[block][i] = 0
end
return 0
end
-- Read the block
local blockdata = self:GetFloatTable(file.Read(self:GetStructName(block)))
self.Cache[block] = {}
for i=0,self.BlockSize-1 do
self.Cache[block][i] = blockdata[i] or 0
end
return self.Cache[block][blockaddress]
else
return nil
end
else
return nil
end
end
function ENT:WriteCell(Address, value)
--DriveID should be > 0, and less than 4 in MP
if ((self.DriveID < 0) || (!game.SinglePlayer() && (self.DriveID >= 4))) then
return false
end
local player = self:GetPlayer()
if (player:IsValid()) then
local steamid = player:SteamID()
steamid = string.gsub(steamid, ":", "_")
if (steamid ~= "UNKNOWN") then
self.Owner_SteamID = steamid
else
self.Owner_SteamID = "SINGLEPLAYER"
end
-- If drive has changed, change cap
if self.DriveID ~= self.PrevDriveID then
self:GetCap()
self.PrevDriveID = self.DriveID
end
-- Check if address is valid
if (Address < self.DriveCap * 1024) and (Address >= 0) then
-- Compute address
local block = math.floor(Address / self.BlockSize)
local blockaddress = math.floor(Address) % self.BlockSize
-- Check if this address is cached
if self.Cache[block] then
self.CacheUpdated[block] = true
self.Cache[block][blockaddress] = value
if Address > self.MaxAddress then
self.MaxAddress = Address
end
return true
end
-- If sector isn't created yet, cache it
if not file.Exists(self:GetStructName(block),"DATA") then
self.Cache[block] = {}
self.CacheUpdated[block] = true
for i=0,self.BlockSize-1 do
self.Cache[block][i] = 0
end
self.Cache[block][blockaddress] = value
if Address > self.MaxAddress then
self.MaxAddress = Address
end
return true
end
-- Read the block
local blockdata = self:GetFloatTable(file.Read(self:GetStructName(block)))
self.Cache[block] = {}
for i=0,self.BlockSize-1 do
self.Cache[block][i] = blockdata[i] or 0
end
self.CacheUpdated[block] = true
self.Cache[block][blockaddress] = value
if Address > self.MaxAddress then
self.MaxAddress = Address
end
return true
else
return false
end
else
return false
end
end
function ENT:Think()
local cachedBlockIndex = next(self.CacheUpdated)
if cachedBlockIndex then
self.CacheUpdated[cachedBlockIndex] = nil
file.CreateDir(string.GetPathFromFilename(self:GetStructName(cachedBlockIndex)))
file.Write(self:GetStructName(cachedBlockIndex),self:MakeFloatTable(self.Cache[cachedBlockIndex]))
self:UpdateCap()
end
self:NextThink(CurTime()+0.25)
return true
end
function ENT:TriggerInput(iname, value)
if (iname == "Clk") then
self.Clk = value
if (self.Clk >= 1) then
self:WriteCell(self.AWrite, self.Data)
if (self.ARead == self.AWrite) then
local val = self:ReadCell(self.ARead)
if (val) then
Wire_TriggerOutput(self, "Data", val)
self.Out = val
end
end
end
elseif (iname == "AddrRead") then
self.ARead = value
local val = self:ReadCell(value)
if (val) then
Wire_TriggerOutput(self, "Data", val)
self.Out = val
end
elseif (iname == "AddrWrite") then
self.AWrite = value
if (self.Clk >= 1) then
self:WriteCell(self.AWrite, self.Data)
end
elseif (iname == "Data") then
self.Data = value
if (self.Clk >= 1) then
self:WriteCell(self.AWrite, self.Data)
if (self.ARead == self.AWrite) then
local val = self:ReadCell(self.ARead)
if (val) then
Wire_TriggerOutput(self, "Data", val)
self.Out = val
end
end
end
end
self:SetOverlayText(self.DriveCap.."kb".."\nWriteAddr:"..self.AWrite.." Data:"..self.Data.." Clock:"..self.Clk.."\nReadAddr:"..self.ARead.." = ".. self.Out)
end
duplicator.RegisterEntityClass("gmod_wire_hdd", WireLib.MakeWireEnt, "Data", "DriveID", "DriveCap")
| apache-2.0 |
s0ph05/awesome | net.lua | 1 | 1339 | local naughty = require("naughty")
function readNetFile(adapter, ...)
local basepath = "/sys/class/net/"..adapter.."/"
for i, name in pairs({...}) do
file = io.open(basepath..name, "r")
if file then
local str = file:read()
file:close()
return str
end
end
end
function setMarkup(string,state)
local str
-- green
if state == 1 then
str = "<span color='darkgreen'>"..string.."</span>"
-- yellow
elseif state == 2 then
str = "<span color='yellow'>"..string.."</span>"
-- red
elseif state == 3 then
str = "<span color='darkred'>"..string.."</span>"
end
return str
end
function netInfo(eth,wifi)
local wifi_flag = 0
local net_flag = 0
local eth_state = readNetFile(eth, "operstate")
local wifi_state = readNetFile(wifi, "operstate")
if eth_state == nil then
eth_state = "down"
end
if wifi_state == nil then
wifi_state = "down"
end
if eth_state:match("up") then
en = setMarkup("EN",1)
net_flag = 1
elseif eth_state:match("down") then
en = setMarkup("EN",3)
else
en = setMarkup("EN",3)
end
if wifi_state:match("up") then
wf = setMarkup("WF",1)
wifi_flag = 1
net_flag = 1
elseif wifi_state:match("down") then
wf = setMarkup("WF",3)
else
wf = setMarkup("WF",3)
end
return en.." | "..wf
end
| mit |
bigdogmat/wire | lua/effects/thruster_ring_grow.lua | 10 | 1652 |
EFFECT.Mat = Material( "effects/select_ring" )
/*---------------------------------------------------------
Initializes the effect. The data is a table of data
which was passed from the server.
---------------------------------------------------------*/
function EFFECT:Init( data )
local size = 16
self:SetCollisionBounds( Vector( -size,-size,-size ), Vector( size,size,size ) )
local Pos = data:GetOrigin() + data:GetNormal() * 2
self:SetPos( Pos )
self:SetAngles( data:GetNormal():Angle() + Angle( 0.01, 0.01, 0.01 ) )
self.Pos = data:GetOrigin()
self.Normal = data:GetNormal()
self.Speed = 2
self.Size = 16
self.Alpha = 255
end
/*---------------------------------------------------------
THINK
---------------------------------------------------------*/
function EFFECT:Think( )
local speed = FrameTime() * self.Speed
//if (self.Speed > 100) then self.Speed = self.Speed - 1000 * speed end
//self.Size = self.Size + speed * self.Speed
self.Size = self.Size + (255 - self.Alpha)*0.08
self.Alpha = self.Alpha - 250.0 * speed
self:SetPos( self:GetPos() + self.Normal * speed * 128 )
if (self.Alpha < 0 ) then return false end
if (self.Size < 0) then return false end
return true
end
/*---------------------------------------------------------
Draw the effect
---------------------------------------------------------*/
function EFFECT:Render( )
if (self.Alpha < 1 ) then return end
render.SetMaterial( self.Mat )
render.DrawQuadEasy( self:GetPos(),
self:GetAngles():Forward(),
self.Size, self.Size,
Color( math.Rand( 10, 100), math.Rand( 100, 220), math.Rand( 240, 255), self.Alpha )
)
end
| apache-2.0 |
dufferzafar/Project-Euler-Solutions | Problems 1-50/27.lua | 1 | 1620 | --[[
Problem No. 27
Find a quadratic formula that produces the maximum number of primes for consecutive values of n.
Wednesday, January 25, 2012
]]--
--Global Declarations
local max = math.max
--The isPrime Function
local function isPrime(x)
if (x < 2) then return false
elseif (x==2) or (x==3) then return true
elseif (x%2 == 0) then return false
elseif (x%3 == 0) then return false
else
local f = 5;
while f <= math.floor(math.sqrt(x)) do
if (x%f) == 0 then return false end
if (x%(f+2)) == 0 then return false end
f = f + 6;
end
end; return true
end
--Check the quadratic formula
local function eval(a, b)
local n = 0;
while n > -1 do --This is NOT an infinite loop, because NO QUADRATIC FORMULA CAN CREATE INFINITE PRIMES.
if isPrime((n^2) + (a*n) + b) then
n = n + 1;
else
return n
end
end
end
--Variables
local b = {2, 3};
local aBest, bBest, nGreat = 1, 41, 40
sT = os.clock()
--Generate Primes upto 1000 (for b)
for i = 5, 1000, 2 do
if isPrime(i) then
b[#b + 1] = i
end
end
--The Main Loop
for i = 1, #b do
for a = 1, 1000, 2 do
local n1, n2 = eval(a, b[i]),eval((-1*a), b[i])
if n1 == max(n1, n2, nGreat) then
aBest, bBest, nGreat = a, b[i], n1
elseif n2 == max(n1, n2, nGreat) then
aBest, bBest, nGreat = (-1*a), b[i], n2
end
end
end
eT = os.clock(); print((eT - sT)*1000 .. " msec")
--We've Done It!!
print("The quadratic formula n^2"..aBest.."n+"..bBest.." produces "..nGreat.." primes, n=0 to n="..(nGreat-1)..".")
print("The real answer is "..math.abs(aBest*bBest)..".") | unlicense |
135yshr/Holocraft-server | world/Plugins/APIDump/Hooks/OnHopperPushingItem.lua | 44 | 1338 | return
{
HOOK_HOPPER_PUSHING_ITEM =
{
CalledWhen = "A hopper is pushing an item into another block entity. ",
DefaultFnName = "OnHopperPushingItem", -- also used as pagename
Desc = [[
This hook is called whenever a {{cHopperEntity|hopper}} transfers an {{cItem|item}} from its own
internal storage into another block entity. A plugin may decide to disallow the move by returning
true. Note that in such a case, the hook may be called again for the same hopper and block, with
different slot numbers.
]],
Params =
{
{ Name = "World", Type = "{{cWorld}}", Notes = "World where the hopper resides" },
{ Name = "Hopper", Type = "{{cHopperEntity}}", Notes = "The hopper that is pushing the item" },
{ Name = "SrcSlot", Type = "number", Notes = "Slot in the hopper that will lose the item" },
{ Name = "DstBlockEntity", Type = "{{cBlockEntityWithItems}}", Notes = " The block entity that will receive the item" },
{ Name = "DstSlot", Type = "number", Notes = " Slot in DstBlockEntity's internal storage where the item will be stored" },
},
Returns = [[
If the function returns false or no value, the next plugin's callback is called. If the function
returns true, no other callback is called for this event and the hopper will not push the item.
]],
}, -- HOOK_HOPPER_PUSHING_ITEM
}
| mit |
hleuwer/luayats | examples/pvlan-1.lua | 1 | 3792 | require "yats"
require "yats.stdlib"
require "yats.rstp"
require "yats.misc"
local function sdel(t,u,v)
if regression == true then
return u
end
if t == "r" then
return math.random(u,v)
elseif t == "c" then
return u
end
end
del = {
sdel("c", 10, 2000),
sdel("c", 10, 2000),
sdel("c", 10, 2000),
sdel("c", 10, 2000),
sdel("c", 10, 2000),
sdel("c", 10, 2000),
nil
}
-- Setting test non nil provides additional output.
test = true
-- Init the yats random generator.
yats.log:info("Init random generator.")
yats.sim:SetRand(10)
yats.sim:setSlotLength(1e-3)
-- Reset simulation time.
yats.log:info("Reset simulation time.")
yats.sim:ResetTime()
if false then
luactrl = yats.luacontrol{
"luactrl",
actions = {
early = {
{100000, yats.cli}
},
late = {},
}
}
end
--- Couple of nc sinks
--local snk = {}
--for i=1,10 do snk[i] = yats.sink{"sink-"..i} end
--- North Bridges.
ne = {
pe = {
west = yats.bridge{
"PE-WEST",
nport=4,
basemac="010000",
start_delay=del[1],
out = {
{"ELS-WEST","in"..3},
nc(),
{"PE-EAST","in"..3},
nc()
}
},
east = yats.bridge{
"PE-EAST",
nport=4,
basemac="020000",
start_delay=del[2],
out = {
nc(),
{"ELS-EAST","in"..4},
{"PE-WEST","in"..3},
nc(),
}
}
},
--- Marconi Bridges.
els = {
west = yats.bridge{
"ELS-WEST",
nport=4,
basemac="030000",
start_delay=del[3],
out = {
{"CE-WEST","in"..1},
{"CE-EAST","in"..1},
{"PE-WEST","in"..1},
nc()
}
},
east = yats.bridge{
"ELS-EAST",
nport=4,
basemac="040000",
start_delay=del[4],
out = {
{"CE-WEST","in"..2},
{"CE-EAST","in"..2},
nc(),
{"PE-EAST","in"..2}
}
}
},
--- South Bridges.
ce = {
west = yats.bridge{
"CE-WEST",
nport=4,
basemac="050000",
start_delay=del[5],
out = {
{"ELS-WEST","in"..1},
{"ELS-EAST","in"..1},
{"CE-EAST","in"..3},
nc(),
}
},
east = yats.bridge{
"CE-EAST",
nport=4,
basemac="060000",
start_delay=del[6],
out = {
{"ELS-WEST","in"..2},
{"ELS-EAST","in"..2},
{"CE-WEST","in"..3},
nc(),
}
}
}
}
-- Connection management
yats.log:debug("connecting")
yats.sim:connect()
for key, pe2ce in pairs(ne) do
for key, bridge in pairs(pe2ce) do
for i, t in bridge:successors() do
printf("%s pin %d => %s handle %d\n", bridge.name, i, t.suc.name, t.shand)
end
end
end
-- Run simulation: 1. path
yats.sim:run(60000, 1000)
for key, pe2ce in pairs(ne) do
for key, bridge in pairs(pe2ce) do
bridge:show_stp(0)
end
end
for key, pe2ce in pairs(ne) do
for key, bridge in pairs(pe2ce) do
bridge:show_port(0)
end
end
ne.els.west:linkDown(1)
yats.sim:run(60000, 1000)
for key, pe2ce in pairs(ne) do
for key, bridge in pairs(pe2ce) do
bridge:show_stp(0)
end
end
for key, pe2ce in pairs(ne) do
for key, bridge in pairs(pe2ce) do
bridge:show_port(0)
end
end
ne.els.west:linkUp(1)
yats.sim:run(60000, 1000)
for key, pe2ce in pairs(ne) do
for key, bridge in pairs(pe2ce) do
bridge:show_stp(0)
end
end
for key, pe2ce in pairs(ne) do
for key, bridge in pairs(pe2ce) do
bridge:show_port(0)
end
end
result = {}
for _, loc in pairs(ne) do
for _, b in pairs(loc) do
local t = b:get_stpm(0)
for k,v in pairs(t) do
if type(v) ~= "table" then
table.insert(result, {k,v})
end
end
for i = 1,4 do
t = b:get_port(0,i)
for k, v in pairs(t) do
if type(v) ~= "table" then
table.insert(result, {k,v})
end
end
end
end
end
--print("Netlist")
--yats.makeDot("pvlan-1")
--print(pretty(result))
return result | gpl-2.0 |
kracwarlock/dp | utils/torch.lua | 7 | 6666 | --useful for validating if an object is an instance of a class,
--even when the class is a super class.
--e.g pattern = "^torch[.]%a*Tensor$"
--typepattern(torch.Tensor(4), pattern) and
--typepattern(torch.DoubleTensor(5), pattern) are both true.
--typepattern(3, pattern)
function torch.typepattern(obj, pattern)
local class = type(obj)
if class == 'userdata' then
class = torch.typename(obj)
end
local match = string.match(class, pattern)
if match == nil then
match = false
end
return match
end
-- DEPRECATED:
typepattern = torch.typepattern
-- END
function torch.typeString_to_tensorType(type_string)
if type_string == 'cuda' then
return 'torch.CudaTensor'
elseif type_string == 'float' then
return 'torch.FloatTensor'
elseif type_string == 'double' then
return 'torch.DoubleTensor'
end
end
-- warning : doesn't allow non-standard constructors.
-- need to call constructors explicitly, e.g. :
function torch.classof(obj)
local obj_t = torch.typename(obj)
if not obj_t then
error("type"..torch.type(obj).."has no torch.class registered constructor", 2)
end
local modula = string.tomodule(obj_t)
return modula
end
-- returns an empty clone of an obj
function torch.emptyClone(obj)
error("Deprecated use torch.protoClone instead", 2)
end
-- construct an object using a prototype and initialize it with ...
-- works with any class registered with torch.class
function torch.protoClone(proto, ...)
local class = torch.classof(proto)
return class(...)
end
-- torch.concat([res], tensors, [dim])
function torch.concat(result, tensors, dim, index)
index = index or 1
if type(result) == 'table' then
index = dim or 1
dim = tensors
tensors = result
result = torch.protoClone(tensors[index])
elseif result == nil then
assert(type(tensors) == 'table', "expecting table at arg 2")
result = torch.protoClone(tensors[index])
end
assert(_.all(tensors,
function(k,v)
return torch.isTensor(v)
end),
"Expecting table of torch.tensors at arg 1 and 2 : "..torch.type(result)
)
dim = dim or 1
local size
for i,tensor in ipairs(tensors) do
if not size then
size = tensor:size():totable()
size[dim] = 0
end
for j,v in ipairs(tensor:size():totable()) do
if j == dim then
size[j] = (size[j] or 0) + v
else
if size[j] and size[j] ~= v then
error(
"Cannot concat dim "..j.." with different sizes: "..
(size[j] or 'nil').." ~= "..(v or 'nil')..
" for tensor at index "..i, 2
)
end
end
end
end
result:resize(unpack(size))
local start = 1
for i, tensor in ipairs(tensors) do
result:narrow(dim, start, tensor:size(dim)):copy(tensor)
start = start+tensor:size(dim)
end
return result
end
function torch.swapaxes(tensor, new_axes)
-- new_axes : A table that give new axes of tensor,
-- example: to swap axes 2 and 3 in 3D tensor of original axes = {1,2,3},
-- then new_axes={1,3,2}
local sorted_axes = table.copy(new_axes)
table.sort(sorted_axes)
for k, v in ipairs(sorted_axes) do
assert(k == v, 'Error: new_axes does not contain all the new axis values')
end
-- tracker is used to track if a dim in new_axes has been swapped
local tracker = torch.zeros(#new_axes)
local new_tensor = tensor
-- set off a chain swapping of a group of intraconnected dimensions
_chain_swap = function(idx)
-- if the new_axes[idx] has not been swapped yet
if tracker[new_axes[idx]] ~= 1 then
tracker[idx] = 1
new_tensor = new_tensor:transpose(idx, new_axes[idx])
return _chain_swap(new_axes[idx])
else
return new_tensor
end
end
for idx = 1, #new_axes do
if idx ~= new_axes[idx] and tracker[idx] ~= 1 then
new_tensor = _chain_swap(idx)
end
end
return new_tensor
end
function torch.Tensor:dimshuffle(new_axes)
return torch.swapaxes(self, new_axes)
end
----------- FFI stuff used to pass storages between threads ------------
-- https://raw.githubusercontent.com/facebook/fbcunn/master/examples/imagenet/util.lua
ffi.cdef[[
void THFloatStorage_free(THFloatStorage *self);
void THIntStorage_free(THIntStorage *self);
]]
function torch.setFloatStorage(tensor, storage_p, free)
assert(storage_p and storage_p ~= 0, "FloatStorage is NULL pointer");
if free then
local cstorage = ffi.cast('THFloatStorage*', torch.pointer(tensor:storage()))
if cstorage ~= nil then
ffi.C['THFloatStorage_free'](cstorage)
end
end
local storage = ffi.cast('THFloatStorage*', storage_p)
tensor:cdata().storage = storage
end
function torch.setIntStorage(tensor, storage_p, free)
assert(storage_p and storage_p ~= 0, "IntStorage is NULL pointer");
if free then
local cstorage = ffi.cast('THIntStorage*', torch.pointer(tensor:storage()))
if cstorage ~= nil then
ffi.C['THIntStorage_free'](cstorage)
end
end
local storage = ffi.cast('THIntStorage*', storage_p)
tensor:cdata().storage = storage
end
function torch.sendTensor(tensor)
local size = tensor:size()
local ttype = tensor:type()
local storage = tonumber(ffi.cast('intptr_t', torch.pointer(tensor:storage())))
tensor:cdata().storage = nil
return {storage, size, ttype}
end
function torch.receiveTensor(tensor, pointer, size, ttype, free)
if tensor then
tensor:resize(size)
assert(tensor:type() == ttype, 'Tensor is wrong type')
else
tensor = torch[ttype].new():resize(size)
end
if ttype == 'torch.FloatTensor' then
torch.setFloatStorage(tensor, pointer, free)
elseif ttype == 'torch.IntTensor' then
torch.setIntStorage(tensor, pointer, free)
else
error('Unknown type')
end
return buffer
end
-- creates or loads a checkpoint at path.
-- factory is a function that returns an object.
-- If a file exists at location path, then it is loaded and returned.
-- Otherwise, the factory is executed and its result is saved
-- at location path for later.
-- This function is usuful for optimizing slow DataSource loadtimes by
-- caching their results to disk for later.
function torch.checkpoint(path, factory, overwrite, mode)
if paths.filep(path) and not overwrite then
return torch.load(path, mode)
end
local obj = factory()
paths.mkdir(paths.dirname(path))
torch.save(path, obj, mode)
return obj
end
| bsd-3-clause |
guard163/tarantool | test/app/cfg.test.lua | 4 | 5414 | #!/usr/bin/env tarantool
local tap = require('tap')
local test = tap.test('cfg')
local socket = require('socket')
local fio = require('fio')
test:plan(33)
--------------------------------------------------------------------------------
-- Invalid values
--------------------------------------------------------------------------------
test:is(type(box.cfg), 'function', 'box is not started')
local function invalid(name, val)
local status, result = pcall(box.cfg, {[name]=val})
test:ok(not status and result:match('Incorrect'), 'invalid '..name)
end
invalid('replication_source', '//guest@localhost:3301')
invalid('wal_mode', 'invalid')
invalid('rows_per_wal', -1)
invalid('listen', '//!')
test:is(type(box.cfg), 'function', 'box is not started')
--------------------------------------------------------------------------------
-- All box members must raise an exception on access if box.cfg{} wasn't called
--------------------------------------------------------------------------------
local box = require('box')
local function testfun()
return type(box.space)
end
local status, result = pcall(testfun)
test:ok(not status and result:match('Please call box.cfg{}'),
'exception on unconfigured box')
os.execute("rm -rf sophia")
box.cfg{
logger="tarantool.log",
slab_alloc_arena=0.1,
wal_mode = "", -- "" means default value
}
-- gh-678: sophia engine creates sophia dir with empty 'snapshot' file
test:isnil(io.open("sophia", 'r'), 'sophia_dir is not auto-created')
status, result = pcall(testfun)
test:ok(status and result == 'table', 'configured box')
--------------------------------------------------------------------------------
-- gh-534: Segmentation fault after two bad wal_mode settings
--------------------------------------------------------------------------------
test:is(box.cfg.wal_mode, "write", "wal_mode default value")
box.cfg{wal_mode = ""}
test:is(box.cfg.wal_mode, "write", "wal_mode default value")
box.cfg{wal_mode = "none"}
test:is(box.cfg.wal_mode, "none", "wal_mode change")
-- "" or NULL resets option to default value
box.cfg{wal_mode = ""}
test:is(box.cfg.wal_mode, "write", "wal_mode default value")
box.cfg{wal_mode = "none"}
test:is(box.cfg.wal_mode, "none", "wal_mode change")
box.cfg{wal_mode = require('msgpack').NULL}
test:is(box.cfg.wal_mode, "write", "wal_mode default value")
test:is(box.cfg.panic_on_wal_error, true, "panic_on_wal_mode default value")
box.cfg{panic_on_wal_error=false}
test:is(box.cfg.panic_on_wal_error, false, "panic_on_wal_mode new value")
test:is(box.cfg.wal_dir_rescan_delay, 2, "wal_dir_rescan_delay default value")
box.cfg{wal_dir_rescan_delay=0.2}
test:is(box.cfg.wal_dir_rescan_delay, 0.2, "wal_dir_rescan_delay new value")
test:is(box.cfg.too_long_threshold, 0.5, "too_long_threshold default value")
box.cfg{too_long_threshold=0.1}
test:is(box.cfg.too_long_threshold , 0.1, "too_long_threshold new value")
--------------------------------------------------------------------------------
-- gh-537: segmentation fault with replication_source
--------------------------------------------------------------------------------
box.cfg{replication_source = 'guest:password@localhost:0'}
box.cfg{replication_source = ""}
local tarantool_bin = arg[-1]
local PANIC = 256
function run_script(code)
local dir = fio.tempdir()
local script_path = fio.pathjoin(dir, 'script.lua')
local script = fio.open(script_path, {'O_CREAT', 'O_WRONLY', 'O_APPEND'},
tonumber('0777', 8))
script:write(code)
script:write("\nos.exit(0)")
script:close()
local cmd = [[/bin/sh -c 'cd "%s" && "%s" ./script.lua 2> /dev/null']]
local res = os.execute(string.format(cmd, dir, tarantool_bin))
fio.rmdir(dir)
return res
end
-- gh-715: Cannot switch to/from 'fsync'
code = [[ box.cfg{ logger="tarantool.log", wal_mode = 'fsync' }; ]]
test:is(run_script(code), 0, 'wal_mode fsync')
code = [[ box.cfg{ wal_mode = 'fsync' }; box.cfg { wal_mode = 'fsync' }; ]]
test:is(run_script(code), 0, 'wal_mode fsync -> fsync')
code = [[ box.cfg{ wal_mode = 'fsync' }; box.cfg { wal_mode = 'none'} ]]
test:is(run_script(code), PANIC, 'wal_mode fsync -> write is not supported')
code = [[ box.cfg{ wal_mode = 'write' }; box.cfg { wal_mode = 'fsync'} ]]
test:is(run_script(code), PANIC, 'wal_mode write -> fsync is not supported')
-- gh-684: Inconsistency with box.cfg and directories
local code;
code = [[ box.cfg{ work_dir='invalid' } ]]
test:is(run_script(code), PANIC, 'work_dir is invalid')
code = [[ box.cfg{ sophia_dir='invalid' } ]]
test:is(run_script(code), PANIC, 'sophia_dir is invalid')
code = [[ box.cfg{ snap_dir='invalid' } ]]
test:is(run_script(code), PANIC, 'snap_dir is invalid')
code = [[ box.cfg{ wal_dir='invalid' } ]]
test:is(run_script(code), PANIC, 'wal_dir is invalid')
test:is(box.cfg.logger_nonblock, true, "logger_nonblock default value")
code = [[
box.cfg{logger_nonblock = false }
os.exit(box.cfg.logger_nonblock == false and 0 or 1)
]]
test:is(run_script(code), 0, "logger_nonblock new value")
-- box.cfg { listen = xx }
local path = './tarantool.sock'
os.remove(path)
box.cfg{ listen = 'unix/:'..path }
s = socket.tcp_connect('unix/', path)
test:isnt(s, nil, "dynamic listen")
if s then s:close() end
box.cfg{ listen = '' }
s = socket.tcp_connect('unix/', path)
test:isnil(s, 'dynamic listen')
if s then s:close() end
os.remove(path)
test:check()
os.exit(0)
| bsd-2-clause |
Source-Saraya/S.R.A | plugins/lock_fwd.lua | 1 | 1201 | do
local function pre_procces(msg)
local hash = "lock:"..msg.to.id
if redis:get(hash)
and msg.fwd_from
and not is_momod(msg)
then
delete_msg(msg.id,ok_cb,true)
reply_msg(msg.id,"✋🏻😒ممنوع عمل اعادة توجيه اذا قمت/ي بعمل اعادة توجيه مرة ثانية سوف اقوم بطردك/ي من المجموعه ❌ ",ok_cb,true)
redis:del(hash)
kick_user("user#id:"..msgfrom.id,"chat#id:"..msg.to.id)
end
return msg
end
local function run(msg,maches)
local hash = "lock:"..msg.to.id
if matches[1] == "قفل التوجيه"
and is_momod(msg)
then
redis:set(hash,true)
return "✅🔐تم قفل اعاده توجيه"
elseif matches[1] == "قفل التوجيه"
and not is_momod(msg)
then
return "😹🌚لا تبحبش للادمنيه فقط"
elseif matches[1] == "فتح التوجيه"
and is_momod(msg)
then
redis:del(hash)
return "تم فتح اعاده توجيه ✅🔓"
end
end
return {
patterns = {
"^[/#!](قفل التوجيه) $",
"^[/#!](فتح التوجيه)$"
},
run = run,
pre_procces = pre_procces
}
end
| gpl-3.0 |
krawthekrow/spike | forward/rewriting.lua | 1 | 8319 | local P = require("core.packet")
local L = require("core.link")
local Datagram = require("lib.protocol.datagram")
local Ethernet = require("lib.protocol.ethernet")
local IPV4 = require("lib.protocol.ipv4")
local IPV6 = require("lib.protocol.ipv6")
local GRE = require("lib.protocol.gre")
local TCP = require("lib.protocol.tcp")
local bit = require("bit")
local ffi = require("ffi")
local band = bit.band
local rshift = bit.rshift
local godefs = require("godefs")
require("networking_magic_numbers")
require("five_tuple")
local IPFragReassembly = require("ip_frag/reassembly")
_G._NAME = "rewriting" -- Snabb requires this for some reason
-- Return the backend associated with a five-tuple
local function get_backend(five_tuple, five_tuple_len)
return godefs.Lookup(five_tuple, five_tuple_len)
end
local Rewriting = {}
-- Arguments:
-- ipv4_addr or ipv6_addr (string) -- the IP address of the spike
-- src_mac (string) -- the MAC address to send from; defaults to the
-- destination MAC of incoming packets
-- dst_mac (string) -- the MAC address to send packets to
-- ttl (int, default 30) -- the TTL to set on outgoing packets
function Rewriting:new(opts)
local ipv4_addr, ipv6_addr, err
if opts.ipv4_addr then
ipv4_addr, err = IPV4:pton(opts.ipv4_addr)
if not ipv4_addr then
error(err)
end
end
if opts.ipv6_addr then
ipv6_addr, err = IPV6:pton(opts.ipv6_addr)
if not ipv6_addr then
error(err)
end
end
if not opts.dst_mac then
error("need to specify dst_mac")
end
return setmetatable(
{ipv4_addr = ipv4_addr,
ipv6_addr = ipv6_addr,
src_mac = opts.src_mac and Ethernet:pton(opts.src_mac),
dst_mac = Ethernet:pton(opts.dst_mac),
ttl = opts.ttl or 30,
ip_frag_reassembly = IPFragReassembly:new()},
{__index = Rewriting})
end
function Rewriting:push()
local i = assert(self.input.input, "input port not found")
local o = assert(self.output.output, "output port not found")
while not L.empty(i) do
self:process_packet(i, o)
end
end
-- Parses a datagram to compute the packet's five tuple and the backend
-- pool to forward to packet to. Due to IP fragmentation, the packet to
-- be forwarded may be different from the packet received.
-- See reassembly.lua for an explanation of IP fragmentation handling.
-- Expected input datagram structure:
-- IPv4 fragment --
-- Ethernet (popped) | IPv4 (parsed) | payload
-- Redirected IPv4 fragment --
-- Ethernet (popped) | IPv4 (parsed) | GRE | IPv4 | payload
-- Full packet --
-- Ethernet (popped) | IPv4/IPv6 (parsed) | TCP/UDP | payload
-- Expected output datagram structure:
-- Ethernet (popped/missing) | IPv4 (parsed) | TCP/UDP | payload
-- Arguments:
-- datagram (datagram) -- Datagram to process. Should have Ethernet
-- header popped and IP header parsed.
-- ip_header (header) -- Parsed IP header of datagram.
-- ip_type (int) -- IP header type, can be L3_IPV4 or L3_IPV6
-- Returns:
-- forward_datagram (bool) -- Indicates whether there is a datagram to
-- forward.
-- t (binary) -- Five tuple of datagram.
-- t_len (int) -- Length of t.
-- backend_pool (int) -- Backend pool to forward the packet to.
-- new_datagram (datagram) -- Datagram to forward. Should have Ethernet
-- header popped or missing, and IP header parsed.
-- new_datagram_len (int) -- Length of new_datagram.
function Rewriting:handle_fragmentation_and_get_forwarding_params(datagram, ip_header, ip_type)
local ip_src = ip_header:src()
local ip_dst = ip_header:dst()
local l4_type, ip_total_length
if ip_type == L3_IPV4 then
l4_type = ip_header:protocol()
ip_total_length = ip_header:total_length()
else
l4_type = ip_header:next_header()
ip_total_length = ip_header:payload_length() + ip_header:sizeof()
end
local prot_class = ip_header:upper_layer()
-- TODO: handle IPv6 fragments
if ip_type == L3_IPV4 then
local frag_off = ip_header:frag_off()
local mf = band(ip_header:flags(), IP_MF_FLAG) ~= 0
if frag_off ~= 0 or mf then
-- Packet is an IPv4 fragment; redirect to another spike
-- Set ports to zero to get three-tuple
local t3, t3_len = five_tuple(ip_type, ip_src, 0, ip_dst, 0)
-- TODO: Return spike backend pool
return true, t3, t3_len, nil, datagram, ip_total_length
end
end
if l4_type == L4_GRE then
-- Packet is a redirected IPv4 fragment
local new_datagram, new_ip_header = self.ip_frag_reassembly:process_datagram(datagram)
if not new_datagram then
return false
end
datagram = new_datagram
datagram:parse_match(IPV4)
ip_src = new_ip_header:src()
ip_dst = new_ip_header:dst()
ip_total_length = new_ip_header:total_length()
prot_class = new_ip_header:upper_layer()
elseif not (l4_type == L4_TCP or l4_type == L4_UDP) then
return false
end
local prot_header = datagram:parse_match(prot_class)
if prot_header == nil then
return false
end
local src_port = prot_header:src_port()
local dst_port = prot_header:dst_port()
local t, t_len = five_tuple(ip_type,
ip_src, src_port, ip_dst, dst_port)
-- TODO: Use IP destination to determine backend pool.
-- unparse L4
datagram:unparse(1)
return true, t, t_len, nil, datagram, ip_total_length
end
function Rewriting:process_packet(i, o)
local p = L.receive(i)
local datagram = Datagram:new(p, nil, {delayed_commit = true})
local eth_header = datagram:parse_match(Ethernet)
if eth_header == nil then
P.free(p)
return
end
local eth_dst = eth_header:dst()
local l3_type = eth_header:type()
if not (l3_type == L3_IPV4 or l3_type == L3_IPV6) then
P.free(p)
return
end
-- Maybe consider moving packet parsing after ethernet into go?
local ip_class = eth_header:upper_layer()
-- decapsulate from ethernet
datagram:pop(1)
local ip_header = datagram:parse_match(ip_class)
if ip_header == nil then
P.free(p)
return
end
local forward_datagram, t, t_len,
backend_pool, new_datagram, ip_total_length =
self:handle_fragmentation_and_get_forwarding_params(
datagram, ip_header, l3_type
)
if not forward_datagram then
P.free(p)
return
end
if datagram ~= new_datagram then
P.free(p)
datagram = new_datagram
end
local backend, backend_len = get_backend(t, t_len)
if backend_len == 0 then
P.free(p)
return
end
-- unparse L4 and L3
datagram:unparse(2)
local gre_header = GRE:new({protocol = l3_type})
datagram:push(gre_header)
local outer_ip_header, outer_l3_type
if backend_len == 4 then -- IPv4
if self.ipv4_addr == nil then
error("Spike's IPv4 address not specified.")
end
outer_l3_type = L3_IPV4
outer_ip_header = IPV4:new({src = self.ipv4_addr,
dst = backend,
protocol = L4_GRE,
ttl = self.ttl})
outer_ip_header:total_length(
ip_total_length + gre_header:sizeof() + outer_ip_header:sizeof())
-- need to recompute checksum after changing total_length
outer_ip_header:checksum()
elseif backend_len == 16 then -- IPv6
if self.ipv6_addr == nil then
error("Spike's IPv6 address not specified.")
end
outer_l3_type = L3_IPV6
outer_ip_header = IPV6:new({src= self.ipv6_addr,
dst = backend,
next_header = L4_GRE,
hop_limit = self.ttl})
outer_ip_header:payload_length(ip_total_length + gre_header:sizeof())
else
error("backend length must be 4 (for IPv4) or 16 (for IPv6)")
end
datagram:push(outer_ip_header)
local outer_eth_header = Ethernet:new({src = self.src_mac or eth_dst,
dst = self.dst_mac,
type = outer_l3_type})
datagram:push(outer_eth_header)
datagram:commit()
link.transmit(o, datagram:packet())
end
return Rewriting
| mit |
4w/xtend | xfurniture/system/get_nodes.lua | 1 | 3534 | -- Checks node ID for dependency status
--
-- Checks if the provided node ID is the ID of a node from a mod that is in
-- xFurniture’s `depends.txt` file.
--
-- @param id The node ID to be checked
-- @return boolean `true` if it is from a mod as described, `false` if not
local is_in_depends = function (id)
for _,dependency in pairs(_xtend.mods.xfurniture.depends) do
if id:gsub(':.*', '') == dependency:gsub('?', '') then return true end
end
return false
end
-- Match a node definition against a filter string
--
-- The provided node definition will be matched against the provided filter
-- string. If the filter matches `true` will be returned, otherwise `false`
-- will be returned.
--
-- @param filterstring The filterstring as described in the documentation of
-- the `get_nodes` function
-- @param definition A node definition
-- @return boolean The result
local filter_match = function(filterstring, definition)
local id = definition.name
local filter = filterstring:gsub(':.*', '')
local value = filterstring:gsub('.*:', '')
local name = id:gsub('.*:', '')
local group = definition.groups[value]
local drawtype = definition.drawtype == value
local startswith = string.sub(name,1,string.len(value)) == value
local endswith = string.sub(name,-string.len(value)) == value
local contains = string.match(name, value)
local origin = definition.mod_origin == value
if filter == 'group' and group
or filter == 'startswith' and startswith
or filter == 'endswith' and endswith
or filter == 'contains' and contains
or filter == 'origin' and origin
or filter == 'drawtype' and drawtype
or filter..':'..value == id then
return true
end
return false
end
-- Check node against blacklist
--
-- This function verifies if the node is on the blacklist or not. If it is on
-- the blacklist `true` will be returned. If not then `false` will be returned.
--
-- @param definition The definition of the node to be checked
-- @return boolean The blacklist status of the node
local blacklisted = function (definition)
local user_filters = _xtend.get_option('node_blacklist')
local builtin_filters = table.concat(_xtend.mods.xfurniture.blacklist, ' ')
local filters = builtin_filters..' '..user_filters
for filterstring in filters:gmatch('(%S+)') do
if filter_match(filterstring, definition) then return true end
end
return false
end
-- Get all relevant nodes
--
-- This function gets all nodes that match against the user-definable list of
-- filter strings and that are not filtered by the built-in blacklist.
--
-- @return table The table of nodes and their definition. The node ID are the
-- keys and the definitions are the values. If no nodes are
-- matched an empty table is returned.
local get_nodes = function ()
local target_nodes = {}
local filters = _xtend.get_option('node_whitelist')
local registered_nodes = minetest.registered_nodes
if filters == '' then filters = 'contains:' end
for filterstring in filters:gmatch('(%S+)') do
for id,definition in pairs(registered_nodes) do
if is_in_depends(id)
and not blacklisted(definition)
and filter_match(filterstring, definition) then
target_nodes[id] = definition
end
end
end
return target_nodes
end
_xtend.mods.xfurniture.nodes = get_nodes()
| gpl-3.0 |
dicebox/minetest-france | mods/locks/init.lua | 2 | 22561 |
--[[
Shared locked objects (Mod for MineTest)
Allows to restrict usage of blocks to a certain player or a group of
players.
Copyright (C) 2013 Sokomine
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
--]]
-- Version 1.20
-- Changelog:
-- 08.05.2014 * Changed animation of shared locked furnace (removed pipeworks overlay on front, changed to new animation type)
-- 10.01.2013 * Added command to toggle for pipeworks output
-- * Added pipeworks support for chests and furnace.
-- 17.12.2013 * aborting input with ESC is possible again
-- 01.09.2013 * fixed bug in input sanitization
-- 31.08.2013 * changed receipe for key to avoid crafting conflickt with screwdriver
-- 10.07.2013 * removed a potential bug (now uses string:gmatch)
-- * added shared locked furnaces
locks = {};
minetest.register_privilege("openlocks", { description = "allows to open/use all locked objects", give_to_singleplayer = false});
minetest.register_privilege("diglocks", { description = "allows to open/use and dig up all locked objects", give_to_singleplayer = false});
locks.pipeworks_enabled = false;
if( minetest.get_modpath("pipeworks") ~= nil ) then
locks.pipeworks_enabled = true;
end
-- initializes a lock (that is: prepare the metadata so that it can store data)
-- default_formspec is the formspec that will be used on right click; the input field for the commands has to exist
-- Call this in on_construct in register_node. Excample:
-- on_construct = function(pos)
-- locks:lock_init( pos, "" );
-- end;
function locks:lock_init( pos, default_formspec )
if( pos == nil ) then
print( "Error: [locks] lock_init: pos is nil");
return;
end
local meta = minetest.env:get_meta(pos);
if( meta == nil ) then
print( "Error: [locks] lock_init: unable to get meta data");
return;
end
-- this will be changed after the node is placed
meta:set_string("infotext", "Locked object");
-- prepare the field for the owner
meta:set_string("owner", "");
-- this is the list of players/groups that may unlock the lock even if they are not the owner
meta:set_string("allowed_users","");
-- objects can be unlocked by passwords as well (if it is set)
meta:set_string("password","");
-- the last player who entered the right password (to save space this is not a list)
meta:set_string("pw_user","");
-- this formspec is presented on right-click for every user
meta:set_string("formspec", default_formspec);
-- by default, do not send output to pipework tubes
meta:set_int( "allow_pipeworks", 0 );
end
-- returns the information stored in the metadata strings (like owner etc.)
function locks:get_lockdata( pos )
if( pos == nil ) then
return;
end
local meta = minetest.env:get_meta(pos);
if( meta == nil) then
return;
end
return{ infotext = (meta:get_string( "infotext" ) or ""),
owner = (meta:get_string( "owner" ) or ""),
allowed_users = (meta:get_string( "allowed_users" ) or ""),
password = (meta:get_string( "password" ) or ""),
pw_user = (meta:get_string( "w_user" ) or ""),
formspec = (meta:get_string( "formspec" ) or "")
};
end
-- sets all the metadata the look needs (used e.g. in doors)
function locks:set_lockdata( pos, data )
if( pos == nil ) then
return;
end
local meta = minetest.env:get_meta(pos);
if( meta == nil) then
return;
end
meta:set_string("infotext", (data.infotext or ""));
meta:set_string("owner", (data.owner or ""));
meta:set_string("allowed_users",(data.allowed_users or ""));
meta:set_string("password", (data.password or ""));
meta:set_string("pw_user", (data.pw_user or ""));
meta:set_string("formspec", (data.formspec or ""));
end
-- Set the owner of the locked object.
-- Call this in after_place_node in register_node. Example:
-- after_place_node = function(pos, placer)
-- locks:lock_set_owner( pos, placer, "Shared locked object" );
-- end,
function locks:lock_set_owner( pos, player_or_name, description )
if( pos == nil or player_or_name == nil ) then
print( "Error: [locks] Missing/wrong parameters to lock_set_owner");
return false;
end
local meta = minetest.env:get_meta(pos);
if( meta == nil ) then
print( "Error: [locks] lock_set_owner: unable to get meta data");
return;
end
-- accepts a name or a player object
if( type( player_or_name )~="string") then
player_or_name = player_or_name:get_player_name();
end
meta:set_string("owner", player_or_name or "");
-- add the name of the owner to the description
meta:set_string("infotext", ( description or "Shared lockecd object" ).." (owned by "..meta:get_string("owner")..")");
end
-- The locked object can only be digged by the owner OR by people with the diglocks priv
-- Call this in can_dig in register_node. Example:
-- can_dig = function(pos,player)
-- return locks:lock_allow_dig( pos, player );
-- end
function locks:lock_allow_dig( pos, player )
if( pos == nil or player == nil ) then
print( "Error: [locks] Missing/wrong parameters to lock_allow_dig");
return false;
end
local meta = minetest.env:get_meta(pos);
local lock_owner = meta:get_string("owner");
-- locks who lost their owner can be opened/digged by anyone
if( meta == nil or lock_owner == nil or lock_owner == "") then
return true;
end
-- the owner can dig up his own locked objects
if( player:get_player_name() == meta:get_string("owner")) then
return true;
end
-- players with diglocks priv can dig up locked objects as well
if( minetest.check_player_privs(player:get_player_name(), {diglocks=true})) then
return true;
end
return false; -- fallback
end
-- The locked object can only be used (i.e. opened, stuff taken out, changed, ... - depends on object) if this
-- function returns true. Call it wherever appropriate (usually in on_punch in register_node). Example:
-- on_punch = function(pos,player)
-- if( !locks:lock_allow_use( pos, player ) then
-- print( "Sorry, you have no access here.");
-- else
-- do_what_this_object_is_good_for( pos, puncher );
-- end
-- end
function locks:lock_allow_use( pos, player )
if( pos == nil or player == nil ) then
print( "Error: [locks] Missing/wrong parameters to lock_allow_use");
return false;
end
local name = player:get_player_name();
local meta = minetest.env:get_meta(pos);
-- pipeworks sends a special username
if( name == ':pipeworks' or (player.is_fake_player and player.is_fake_player==":pipeworks")) then
if( meta:get_int( 'allow_pipeworks' ) == 1 ) then
return true;
else
return false;
end
end
-- the player has to have a key or a keychain to open his own shared locked objects
if( name == meta:get_string("owner")) then
if( not( player:get_inventory():contains_item("main","locks:keychain 1"))
and not( player:get_inventory():contains_item("main","locks:key 1"))) then
minetest.chat_send_player( name, "You do not have a key or a keychain. Without that you can't use your shared locked objects!");
return false;
end
-- the player has to have a keychain to open shared locked objects of other players
else
if( not( player:get_inventory():contains_item("main","locks:keychain 1"))) then
minetest.chat_send_player(name, "You do not have a keychain. Without that you can't open shared locked objects of other players!");
return false;
end
end
-- if the user would even be allowed to dig this node up, using the node is allowed as well
if( locks:lock_allow_dig( pos, player )) then
return true;
end
if( meta == nil ) then
minetest.chat_send_player( name, "Error: Could not access metadata of this shared locked object.");
return false;
end
-- players with openlocks priv can open locked objects
if( minetest.check_player_privs(name, {openlocks=true})) then
return true;
end
-- the player might be specificly allowed to use this object through allowed_users
local liste = meta:get_string("allowed_users"):split( "," );
for i in ipairs( liste ) do
if( liste[i] == name ) then
return true;
end
-- the player might member of a playergroup that is allowed to use this object
if( liste[i]:sub(1,1) == ":"
and playergroups ~= nil
and playergroups:is_group_member( meta:get_string("owner"), liste[i]:sub(2), name )) then
return true;
end
end
-- the player may have entered the right password
if( name == meta:get_string("pw_user")) then
return true;
end
-- the lock may have a password set. If this is the case then ask the user for it
if( meta:get_string( "password" ) and meta:get_string( "password" ) ~= "" ) then
minetest.chat_send_player(name, "Access denied. Right-click and enter password first!");
return false;
end
return false; -- fallback
end
-- Method for the lock to get password and configuration data
-- Call in on_receive_fields in register_node. Example:
-- on_receive_fields = function(pos, formname, fields, sender)
-- locks:lock_handle_input( pos, formname, fields, sender );
-- end,
function locks:lock_handle_input( pos, formname, fields, player )
if( pos == nil or player == nil ) then
print( "Error: [locks] Missing/wrong parameters to lock_handle_input");
return false;
end
local meta = minetest.env:get_meta(pos);
if( meta == nil ) then
print( "Error: [locks] lock_handle_input: unable to get meta data");
return;
end
-- is this input the lock is supposed to handle?
if( ( not( fields.locks_sent_lock_command )
or fields.locks_sent_lock_command == "" )
and (fields.quit and (fields.quit==true or fields.quit=='true'))) then
-- or not( fields.locks_sent_input )
return;
end
name = player:get_player_name();
if( fields.locks_sent_lock_command == "/help" ) then
if( name == meta:get_string( "owner" )) then
minetest.chat_send_player(name, "The following commands are available to you, the owner of this object, only:\n"..
" /help Shows this help text.\n"..
" /add <name> Player <name> can now unlock this object with any key.\n"..
" /del <name> Player <name> can no longer use this object.\n"..
" /list Shows a list of players who can use this object.\n"..
" /set <password> Sets a password. Everyone who types that in can use the object.\n"..
" /pipeworks Toggles permission for pipeworks to take inventory out of the shared locked object.\n");
else if( locks:lock_allow_use( pos, player )) then
minetest.chat_send_player(name, "This locked object is owned by "..tostring( meta:get_string( "owner" ))..".\n"..
"You do have access to it.\n");
else if( meta:get_string( "password" ) ~= "" ) then
minetest.chat_send_player(name, "This locked object is owned by "..tostring( meta:get_string( "owner" ))..".\n"..
"Enter the correct password to gain access.\n");
else
minetest.chat_send_player(name, "This locked object is owned by "..tostring( meta:get_string( "owner" ))..".\n"..
"There is no password set. You can only gain access if the owner grants it to you.");
end end end -- lua is not the most intuitive language here....
return;
end -- of /help
-- sanitize player input
if( fields.locks_sent_lock_command:match("[^%a%d%s_%- /%:]")) then
minetest.chat_send_player(name, "Input contains unsupported characters. Allowed: a-z, A-Z, 0-9, _, -, :.");
return;
end
if( #fields.locks_sent_lock_command > 60) then
minetest.chat_send_player(name, "Input too long. Only up to 80 characters supported.");
return;
end
-- other players can only try to input the correct password
if( name ~= meta:get_string( "owner" )) then
-- no need to bother with trying other PWs if none is set...
if( meta:get_string("password")=="" ) then
minetest.chat_send_player(name, "There is no password set. Access denied.");
return;
end
-- the player may have entered the right password already
if( name == meta:get_string("pw_user")) then
-- nothing to do - the player entered the right pw alredy
minetest.chat_send_player(name, "You have entered the right password already. Access granted.");
return;
end
if( fields.locks_sent_lock_command ~= meta:get_string("password")) then
minetest.chat_send_player(name, "Wrong password. Access denied.");
return;
end
-- store the last user (this one) who entered the right pw
meta:set_string( "pw_user", name );
minetest.chat_send_player(name, "Password confirmed. Access granted.");
return;
end
local txt = "";
if( fields.locks_sent_lock_command == "/list" ) then
if( meta:get_string("allowed_users")=="" ) then
txt = "No other users are allowed to use this object (except those with global privs like moderators/admins).";
else
txt = "You granted the following users/groups of users access to this object:\n";
local liste = meta:get_string("allowed_users"):split( "," );
for i in ipairs( liste ) do
txt = txt.." "..tostring(liste[i]);
end
end
if( meta:get_string( "password" ) == "" ) then
txt = txt.."\nThere is no password set. That means no one can get access through a password.";
else
txt = txt.."\nThe password for this lock is: \""..tostring( meta:get_string( "password" ).."\"");
end
if( not( minetest.get_modpath("pipeworks") )) then
txt = txt.."\nThe pipeworks mod is not installed. Install it if you wish support for tubes.";
elseif( meta:get_int( "allow_pipeworks" ) == 1 ) then
txt = txt.."\nTubes from pipeworks may be used to extract items out of/add items to this shared locked object.";
else
txt = txt.."\nInput from tubes is accepted, but output to them is denied (default).";
end
minetest.chat_send_player(name, txt );
return;
end -- of /list
-- toggle tube output on/off
if( fields.locks_sent_lock_command == "/pipeworks" ) then
if( meta:get_int('allow_pipeworks') == 1 ) then
meta:set_int('allow_pipeworks', 0 );
minetest.chat_send_player( name, 'Output to pipework tubes is now DISABLED (input is still acceped).');
return;
else
meta:set_int('allow_pipeworks', 1 );
minetest.chat_send_player( name, 'Output to pipework tubes is now ENABLED. Connected tubes may insert and remove items.');
return;
end
end
-- -- all other commands take exactly one parameter
local help = fields.locks_sent_lock_command:split( " " );
print( tostring( help[1] ));
print( tostring( help[2] ));
-- set/change a password
if( help[1]=="/set" ) then
-- if empty password then delete it
if( help[2]==nil ) then
help[2] = "";
end
minetest.chat_send_player(name, "Old password: \""..tostring( meta:get_string( "password" ))..
"\"\n Changed to new password: \""..tostring( help[2]).."\".");
meta:set_string( "password", help[2]);
-- reset the list of users who typed the right password
meta:set_string("pw_users","");
if( help[2]=="") then
minetest.chat_send_player(name, "The password is empty and thus will be disabled.");
end
return;
end
if( help[2]==nil or help[2]=="") then
minetest.chat_send_player(name, "Error: Missing parameter (player name) for command \""..tostring( help[1] ).."\"." );
return;
end
-- for add and del: check if the player is already in the list
local found = false;
local anz = 0;
local liste = meta:get_string("allowed_users"):split( "," );
for i in ipairs( liste ) do
anz = anz + 1; -- count players
if( tostring( liste[i] ) == help[2] ) then
found = true;
end
end
if( help[1]=="/add" and found==true ) then
minetest.chat_send_player(name, "Player \""..tostring( help[2] ).."\" is already allowed to use this locked object. Nothing to do.");
return;
end
if( help[1]=="/del" and found==false) then
minetest.chat_send_player(name, "Player \""..tostring( help[2] ).."\" is not amongst the players allowed to use this locked object. Nothing to do.");
return;
end
if( help[1]=="/add" ) then
if( anz >= 6 ) then
minetest.chat_send_player(name, "Sorry, no more players can be added. To save space, only up to 6 players can be added. For more players please use groups!");
return;
end
if( name == help[2] ) then
minetest.chat_send_player(name, "You are already owner of this object.");
return;
end
-- the player might try to add a playergroup
if( help[2]:sub(1,1) == ":" ) then
if( not( playergroups )) then
minetest.chat_send_player(name, "Sorry, this server does not support playergroups.");
return;
end
if( #help[2]<2 ) then
minetest.chat_send_player(name, "Please specify the name of the playergroup you want to add!");
return;
end
if( not( playergroups:is_playergroup(meta:get_string("owner"), help[2]:sub(2) ))) then
minetest.chat_send_player(name, "You do not have a playergroup named \""..tostring( help[2]:sub(2)).."\".");
return;
end
else
-- check if the player exists
local privs = minetest.get_player_privs( help[2] );
if( not( privs ) or not( privs.interact )) then
minetest.chat_send_player(name, "Player \""..help[2].."\" not found or has no interact privs.");
return;
end
end
meta:set_string( "allowed_users", meta:get_string("allowed_users")..","..help[2] );
if( help[2]:sub(1,1) == ":" ) then
minetest.chat_send_player(name, "All members of your playergroup "..tostring(help[2]:sub(2)).." may now use/access this locked object.");
else
minetest.chat_send_player(name, help[2].." may now use/access this locked object.");
end
return;
end
if( help[1]=="/del" ) then
userlist = meta:get_string("allowed_users"):split( ","..help[2] );
meta:set_string( "allowed_users", ( userlist[1] or "" )..(userlist[2] or "" ));
minetest.chat_send_player(name, "Access for player \""..tostring(help[2]).."\" has been revoked.");
return;
end
minetest.chat_send_player(name, "Error: Command \""..tostring(help[1]).."\" not understood.");
end
-- craftitem; that can be used to craft shared locked objects
minetest.register_craftitem("locks:lock", {
description = "Lock to lock and share objects",
image = "locks_lock16.png",
});
minetest.register_craft({
output = "locks:lock 2",
recipe = {
{'default:steel_ingot', 'default:steel_ingot','default:steel_ingot'},
{'default:steel_ingot', '', 'default:steel_ingot'},
{'', 'default:steel_ingot',''},
}
});
-- a key allowes to open your own shared locked objects
minetest.register_craftitem("locks:key", {
description = "Key to open your own shared locked objects",
image = "locks_key32.png",
});
minetest.register_craft({
output = "locks:key",
recipe = {
{'', 'default:stick', ''},
{'', 'default:steel_ingot',''},
}
});
-- in order to open shared locked objects of other players, a keychain is needed (plus the owner has to admit it via /add playername or through /set password)
minetest.register_craftitem("locks:keychain", {
description = "Keychain to open shared locked objects of others",
image = "locks_keychain32.png",
});
minetest.register_craft({
output = "locks:keychain",
recipe = {
{'', 'default:steel_ingot', '' },
{'locks:key', 'locks:key', 'locks:key'},
}
});
dofile(minetest.get_modpath("locks").."/shared_locked_chest.lua");
dofile(minetest.get_modpath("locks").."/shared_locked_sign_wall.lua");
dofile(minetest.get_modpath("locks").."/shared_locked_xdoors2.lua");
dofile(minetest.get_modpath("locks").."/shared_locked_furnace.lua");
| gpl-3.0 |
hfjgjfg/shatel | bot/utils.lua | 646 | 23489 | URL = require "socket.url"
http = require "socket.http"
https = require "ssl.https"
ltn12 = require "ltn12"
serpent = require "serpent"
feedparser = require "feedparser"
json = (loadfile "./libs/JSON.lua")()
mimetype = (loadfile "./libs/mimetype.lua")()
redis = (loadfile "./libs/redis.lua")()
JSON = (loadfile "./libs/dkjson.lua")()
http.TIMEOUT = 10
function get_receiver(msg)
if msg.to.type == 'user' then
return 'user#id'..msg.from.id
end
if msg.to.type == 'chat' then
return 'chat#id'..msg.to.id
end
if msg.to.type == 'encr_chat' then
return msg.to.print_name
end
end
function is_chat_msg( msg )
if msg.to.type == 'chat' then
return true
end
return false
end
function string.random(length)
local str = "";
for i = 1, length do
math.random(97, 122)
str = str..string.char(math.random(97, 122));
end
return str;
end
function string:split(sep)
local sep, fields = sep or ":", {}
local pattern = string.format("([^%s]+)", sep)
self:gsub(pattern, function(c) fields[#fields+1] = c end)
return fields
end
-- DEPRECATED
function string.trim(s)
print("string.trim(s) is DEPRECATED use string:trim() instead")
return s:gsub("^%s*(.-)%s*$", "%1")
end
-- Removes spaces
function string:trim()
return self:gsub("^%s*(.-)%s*$", "%1")
end
function get_http_file_name(url, headers)
-- Eg: foo.var
local file_name = url:match("[^%w]+([%.%w]+)$")
-- Any delimited alphanumeric on the url
file_name = file_name or url:match("[^%w]+(%w+)[^%w]+$")
-- Random name, hope content-type works
file_name = file_name or str:random(5)
local content_type = headers["content-type"]
local extension = nil
if content_type then
extension = mimetype.get_mime_extension(content_type)
end
if extension then
file_name = file_name.."."..extension
end
local disposition = headers["content-disposition"]
if disposition then
-- attachment; filename=CodeCogsEqn.png
file_name = disposition:match('filename=([^;]+)') or file_name
end
return file_name
end
-- Saves file to /tmp/. If file_name isn't provided,
-- will get the text after the last "/" for filename
-- and content-type for extension
function download_to_file(url, file_name)
print("url to download: "..url)
local respbody = {}
local options = {
url = url,
sink = ltn12.sink.table(respbody),
redirect = true
}
-- nil, code, headers, status
local response = nil
if url:starts('https') then
options.redirect = false
response = {https.request(options)}
else
response = {http.request(options)}
end
local code = response[2]
local headers = response[3]
local status = response[4]
if code ~= 200 then return nil end
file_name = file_name or get_http_file_name(url, headers)
local file_path = "/tmp/"..file_name
print("Saved to: "..file_path)
file = io.open(file_path, "w+")
file:write(table.concat(respbody))
file:close()
return file_path
end
function vardump(value)
print(serpent.block(value, {comment=false}))
end
-- taken from http://stackoverflow.com/a/11130774/3163199
function scandir(directory)
local i, t, popen = 0, {}, io.popen
for filename in popen('ls -a "'..directory..'"'):lines() do
i = i + 1
t[i] = filename
end
return t
end
-- http://www.lua.org/manual/5.2/manual.html#pdf-io.popen
function run_command(str)
local cmd = io.popen(str)
local result = cmd:read('*all')
cmd:close()
return result
end
-- User has privileges
function is_sudo(msg)
local var = false
-- Check users id in config
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
-- Returns the name of the sender
function get_name(msg)
local name = msg.from.first_name
if name == nil then
name = msg.from.id
end
return name
end
-- Returns at table of lua files inside plugins
function plugins_names( )
local files = {}
for k, v in pairs(scandir("plugins")) do
-- Ends with .lua
if (v:match(".lua$")) then
table.insert(files, v)
end
end
return files
end
-- Function name explains what it does.
function file_exists(name)
local f = io.open(name,"r")
if f ~= nil then
io.close(f)
return true
else
return false
end
end
-- Save into file the data serialized for lua.
-- Set uglify true to minify the file.
function serialize_to_file(data, file, uglify)
file = io.open(file, 'w+')
local serialized
if not uglify then
serialized = serpent.block(data, {
comment = false,
name = '_'
})
else
serialized = serpent.dump(data)
end
file:write(serialized)
file:close()
end
-- Returns true if the string is empty
function string:isempty()
return self == nil or self == ''
end
-- Returns true if the string is blank
function string:isblank()
self = self:trim()
return self:isempty()
end
-- DEPRECATED!!!!!
function string.starts(String, Start)
print("string.starts(String, Start) is DEPRECATED use string:starts(text) instead")
return Start == string.sub(String,1,string.len(Start))
end
-- Returns true if String starts with Start
function string:starts(text)
return text == string.sub(self,1,string.len(text))
end
-- Send image to user and delete it when finished.
-- cb_function and cb_extra are optionals callback
function _send_photo(receiver, file_path, cb_function, cb_extra)
local cb_extra = {
file_path = file_path,
cb_function = cb_function,
cb_extra = cb_extra
}
-- Call to remove with optional callback
send_photo(receiver, file_path, cb_function, cb_extra)
end
-- Download the image and send to receiver, it will be deleted.
-- cb_function and cb_extra are optionals callback
function send_photo_from_url(receiver, url, cb_function, cb_extra)
-- If callback not provided
cb_function = cb_function or ok_cb
cb_extra = cb_extra or false
local file_path = download_to_file(url, false)
if not file_path then -- Error
local text = 'Error downloading the image'
send_msg(receiver, text, cb_function, cb_extra)
else
print("File path: "..file_path)
_send_photo(receiver, file_path, cb_function, cb_extra)
end
end
-- Same as send_photo_from_url but as callback function
function send_photo_from_url_callback(cb_extra, success, result)
local receiver = cb_extra.receiver
local url = cb_extra.url
local file_path = download_to_file(url, false)
if not file_path then -- Error
local text = 'Error downloading the image'
send_msg(receiver, text, ok_cb, false)
else
print("File path: "..file_path)
_send_photo(receiver, file_path, ok_cb, false)
end
end
-- Send multiple images asynchronous.
-- param urls must be a table.
function send_photos_from_url(receiver, urls)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = nil
}
send_photos_from_url_callback(cb_extra)
end
-- Use send_photos_from_url.
-- This function might be difficult to understand.
function send_photos_from_url_callback(cb_extra, success, result)
-- cb_extra is a table containing receiver, urls and remove_path
local receiver = cb_extra.receiver
local urls = cb_extra.urls
local remove_path = cb_extra.remove_path
-- The previously image to remove
if remove_path ~= nil then
os.remove(remove_path)
print("Deleted: "..remove_path)
end
-- Nil or empty, exit case (no more urls)
if urls == nil or #urls == 0 then
return false
end
-- Take the head and remove from urls table
local head = table.remove(urls, 1)
local file_path = download_to_file(head, false)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = file_path
}
-- Send first and postpone the others as callback
send_photo(receiver, file_path, send_photos_from_url_callback, cb_extra)
end
-- Callback to remove a file
function rmtmp_cb(cb_extra, success, result)
local file_path = cb_extra.file_path
local cb_function = cb_extra.cb_function or ok_cb
local cb_extra = cb_extra.cb_extra
if file_path ~= nil then
os.remove(file_path)
print("Deleted: "..file_path)
end
-- Finally call the callback
cb_function(cb_extra, success, result)
end
-- Send document to user and delete it when finished.
-- cb_function and cb_extra are optionals callback
function _send_document(receiver, file_path, cb_function, cb_extra)
local cb_extra = {
file_path = file_path,
cb_function = cb_function or ok_cb,
cb_extra = cb_extra or false
}
-- Call to remove with optional callback
send_document(receiver, file_path, rmtmp_cb, cb_extra)
end
-- Download the image and send to receiver, it will be deleted.
-- cb_function and cb_extra are optionals callback
function send_document_from_url(receiver, url, cb_function, cb_extra)
local file_path = download_to_file(url, false)
print("File path: "..file_path)
_send_document(receiver, file_path, cb_function, cb_extra)
end
-- Parameters in ?a=1&b=2 style
function format_http_params(params, is_get)
local str = ''
-- If is get add ? to the beginning
if is_get then str = '?' end
local first = true -- Frist param
for k,v in pairs (params) do
if v then -- nil value
if first then
first = false
str = str..k.. "="..v
else
str = str.."&"..k.. "="..v
end
end
end
return str
end
-- Check if user can use the plugin and warns user
-- Returns true if user was warned and false if not warned (is allowed)
function warns_user_not_allowed(plugin, msg)
if not user_allowed(plugin, msg) then
local text = 'This plugin requires privileged user'
local receiver = get_receiver(msg)
send_msg(receiver, text, ok_cb, false)
return true
else
return false
end
end
-- Check if user can use the plugin
function user_allowed(plugin, msg)
if plugin.privileged and not is_sudo(msg) then
return false
end
return true
end
function send_order_msg(destination, msgs)
local cb_extra = {
destination = destination,
msgs = msgs
}
send_order_msg_callback(cb_extra, true)
end
function send_order_msg_callback(cb_extra, success, result)
local destination = cb_extra.destination
local msgs = cb_extra.msgs
local file_path = cb_extra.file_path
if file_path ~= nil then
os.remove(file_path)
print("Deleted: " .. file_path)
end
if type(msgs) == 'string' then
send_large_msg(destination, msgs)
elseif type(msgs) ~= 'table' then
return
end
if #msgs < 1 then
return
end
local msg = table.remove(msgs, 1)
local new_cb_extra = {
destination = destination,
msgs = msgs
}
if type(msg) == 'string' then
send_msg(destination, msg, send_order_msg_callback, new_cb_extra)
elseif type(msg) == 'table' then
local typ = msg[1]
local nmsg = msg[2]
new_cb_extra.file_path = nmsg
if typ == 'document' then
send_document(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'image' or typ == 'photo' then
send_photo(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'audio' then
send_audio(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'video' then
send_video(destination, nmsg, send_order_msg_callback, new_cb_extra)
else
send_file(destination, nmsg, send_order_msg_callback, new_cb_extra)
end
end
end
-- Same as send_large_msg_callback but friendly params
function send_large_msg(destination, text)
local cb_extra = {
destination = destination,
text = text
}
send_large_msg_callback(cb_extra, true)
end
-- If text is longer than 4096 chars, send multiple msg.
-- https://core.telegram.org/method/messages.sendMessage
function send_large_msg_callback(cb_extra, success, result)
local text_max = 4096
local destination = cb_extra.destination
local text = cb_extra.text
local text_len = string.len(text)
local num_msg = math.ceil(text_len / text_max)
if num_msg <= 1 then
send_msg(destination, text, ok_cb, false)
else
local my_text = string.sub(text, 1, 4096)
local rest = string.sub(text, 4096, text_len)
local cb_extra = {
destination = destination,
text = rest
}
send_msg(destination, my_text, send_large_msg_callback, cb_extra)
end
end
-- Returns a table with matches or nil
function match_pattern(pattern, text, lower_case)
if text then
local matches = {}
if lower_case then
matches = { string.match(text:lower(), pattern) }
else
matches = { string.match(text, pattern) }
end
if next(matches) then
return matches
end
end
-- nil
end
-- Function to read data from files
function load_from_file(file, default_data)
local f = io.open(file, "r+")
-- If file doesn't exists
if f == nil then
-- Create a new empty table
default_data = default_data or {}
serialize_to_file(default_data, file)
print ('Created file', file)
else
print ('Data loaded from file', file)
f:close()
end
return loadfile (file)()
end
-- See http://stackoverflow.com/a/14899740
function unescape_html(str)
local map = {
["lt"] = "<",
["gt"] = ">",
["amp"] = "&",
["quot"] = '"',
["apos"] = "'"
}
new = string.gsub(str, '(&(#?x?)([%d%a]+);)', function(orig, n, s)
var = map[s] or n == "#" and string.char(s)
var = var or n == "#x" and string.char(tonumber(s,16))
var = var or orig
return var
end)
return new
end
--Check if this chat is realm or not
function is_realm(msg)
local var = false
local realms = 'realms'
local data = load_data(_config.moderation.data)
local chat = msg.to.id
if data[tostring(realms)] then
if data[tostring(realms)][tostring(msg.to.id)] then
var = true
end
return var
end
end
--Check if this chat is a group or not
function is_group(msg)
local var = false
local groups = 'groups'
local data = load_data(_config.moderation.data)
local chat = msg.to.id
if data[tostring(groups)] then
if data[tostring(groups)][tostring(msg.to.id)] then
var = true
end
return var
end
end
function savelog(group, logtxt)
local text = (os.date("[ %c ]=> "..logtxt.."\n \n"))
local file = io.open("./groups/logs/"..group.."log.txt", "a")
file:write(text)
file:close()
end
function user_print_name(user)
if user.print_name then
return user.print_name
end
local text = ''
if user.first_name then
text = user.last_name..' '
end
if user.lastname then
text = text..user.last_name
end
return text
end
--Check if user is the owner of that group or not
function is_owner(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['set_owner'] then
if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
function is_owner2(user_id, group_id)
local var = false
local data = load_data(_config.moderation.data)
if data[tostring(group_id)] then
if data[tostring(group_id)]['set_owner'] then
if data[tostring(group_id)]['set_owner'] == tostring(user_id) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user_id)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == user_id then
var = true
end
end
return var
end
--Check if user is admin or not
function is_admin(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
local admins = 'admins'
if data[tostring(admins)] then
if data[tostring(admins)][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
function is_admin2(user_id)
local var = false
local data = load_data(_config.moderation.data)
local user = user_id
local admins = 'admins'
if data[tostring(admins)] then
if data[tostring(admins)][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == user_id then
var = true
end
end
return var
end
--Check if user is the mod of that group or not
function is_momod(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['moderators'] then
if data[tostring(msg.to.id)]['moderators'][tostring(user)] then
var = true
end
end
end
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['set_owner'] then
if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
function is_momod2(user_id, group_id)
local var = false
local data = load_data(_config.moderation.data)
local usert = user_id
if data[tostring(group_id)] then
if data[tostring(group_id)]['moderators'] then
if data[tostring(group_id)]['moderators'][tostring(usert)] then
var = true
end
end
end
if data[tostring(group_id)] then
if data[tostring(group_id)]['set_owner'] then
if data[tostring(group_id)]['set_owner'] == tostring(user_id) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user_id)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == usert then
var = true
end
end
return var
end
-- Returns the name of the sender
function kick_user(user_id, chat_id)
if tonumber(user_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_owner2(user_id, chat_id) then -- Ignore admins
return
end
local chat = 'chat#id'..chat_id
local user = 'user#id'..user_id
chat_del_user(chat, user, ok_cb, true)
end
-- Ban
function ban_user(user_id, chat_id)
if tonumber(user_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_admin2(user_id) then -- Ignore admins
return
end
-- Save to redis
local hash = 'banned:'..chat_id
redis:sadd(hash, user_id)
-- Kick from chat
kick_user(user_id, chat_id)
end
-- Global ban
function banall_user(user_id)
if tonumber(user_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_admin2(user_id) then -- Ignore admins
return
end
-- Save to redis
local hash = 'gbanned'
redis:sadd(hash, user_id)
end
-- Global unban
function unbanall_user(user_id)
--Save on redis
local hash = 'gbanned'
redis:srem(hash, user_id)
end
-- Check if user_id is banned in chat_id or not
function is_banned(user_id, chat_id)
--Save on redis
local hash = 'banned:'..chat_id
local banned = redis:sismember(hash, user_id)
return banned or false
end
-- Check if user_id is globally banned or not
function is_gbanned(user_id)
--Save on redis
local hash = 'gbanned'
local banned = redis:sismember(hash, user_id)
return banned or false
end
-- Returns chat_id ban list
function ban_list(chat_id)
local hash = 'banned:'..chat_id
local list = redis:smembers(hash)
local text = "Ban list !\n\n"
for k,v in pairs(list) do
text = text..k.." - "..v.." \n"
end
return text
end
-- Returns globally ban list
function banall_list()
local hash = 'gbanned'
local list = redis:smembers(hash)
local text = "global bans !\n\n"
for k,v in pairs(list) do
text = text..k.." - "..v.." \n"
end
return text
end
-- /id by reply
function get_message_callback_id(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
send_large_msg(chat, result.from.id)
else
return 'Use This in Your Groups'
end
end
-- kick by reply for mods and owner
function Kick_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't kick myself"
end
if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin
return "you can't kick mods,owner and admins"
end
chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false)
else
return 'Use This in Your Groups'
end
end
-- Kick by reply for admins
function Kick_by_reply_admins(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't kick myself"
end
if is_admin2(result.from.id) then -- Ignore admins
return
end
chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false)
else
return 'Use This in Your Groups'
end
end
--Ban by reply for admins
function ban_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't ban myself"
end
if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin
return "you can't kick mods,owner and admins"
end
ban_user(result.from.id, result.to.id)
send_large_msg(chat, "User "..result.from.id.." Banned")
else
return 'Use This in Your Groups'
end
end
-- Ban by reply for admins
function ban_by_reply_admins(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't ban myself"
end
if is_admin2(result.from.id) then -- Ignore admins
return
end
ban_user(result.from.id, result.to.id)
send_large_msg(chat, "User "..result.from.id.." Banned")
else
return 'Use This in Your Groups'
end
end
-- Unban by reply
function unban_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't unban myself"
end
send_large_msg(chat, "User "..result.from.id.." Unbanned")
-- Save on redis
local hash = 'banned:'..result.to.id
redis:srem(hash, result.from.id)
else
return 'Use This in Your Groups'
end
end
function banall_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't banall myself"
end
if is_admin2(result.from.id) then -- Ignore admins
return
end
local name = user_print_name(result.from)
banall_user(result.from.id)
chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false)
send_large_msg(chat, "User "..name.."["..result.from.id.."] hammered")
else
return 'Use This in Your Groups'
end
end
| gpl-2.0 |
silverhammermba/awesome | lib/menubar/index_theme.lua | 4 | 5505 | ---------------------------------------------------------------------------
--- Class module for parsing an index.theme file
--
-- @author Kazunobu Kuriyama
-- @copyright 2015 Kazunobu Kuriyama
-- @release @AWESOME_VERSION@
-- @classmod menubar.index_theme
---------------------------------------------------------------------------
-- This implementation is based on the specifications:
-- Icon Theme Specification 0.12
-- http://standards.freedesktop.org/icon-theme-spec/icon-theme-spec-0.12.html
local ipairs = ipairs
local setmetatable = setmetatable
local string = string
local table = table
local io = io
-- index.theme groups
local ICON_THEME = "Icon Theme"
-- index.theme keys
local DIRECTORIES = "Directories"
local INHERITS = "Inherits"
-- per-directory subkeys
local TYPE = "Type"
local SIZE = "Size"
local MINSIZE = "MinSize"
local MAXSIZE = "MaxSize"
local THRESHOLD = "Threshold"
local index_theme = { mt = {} }
--- Class constructor of `index_theme`
-- @tparam table cls Metatable that will be used. Should always be `index_theme.mt`.
-- @tparam string icon_theme_name Internal name of icon theme
-- @tparam table base_directories Paths used for lookup
-- @treturn table An instance of the class `index_theme`
index_theme.new = function(cls, icon_theme_name, base_directories)
local self = {}
setmetatable(self, { __index = cls })
-- Initialize the fields
self.icon_theme_name = icon_theme_name
self.base_directory = nil
self[DIRECTORIES] = {}
self[INHERITS] = {}
self.per_directory_keys = {}
-- base_directory
local basedir = nil
local handler = nil
for _, dir in ipairs(base_directories) do
basedir = dir .. "/" .. self.icon_theme_name
handler = io.open(basedir .. "/index.theme", "r")
if handler then
-- Use the index.theme which is found first.
break
end
end
if not handler then
return self
end
self.base_directory = basedir
-- Parse index.theme.
while true do
local line = handler:read()
if not line then
break
end
local group_header = "^%[(.+)%]$"
local group = line:match(group_header)
if group then
if group == ICON_THEME then
while true do
local item = handler:read()
if not item then
break
end
if item:match(group_header) then
handler:seek("cur", -string.len(item) - 1)
break
end
local k, v = item:match("^(%w+)=(.*)$")
if k == DIRECTORIES or k == INHERITS then
string.gsub(v, "([^,]+),?", function(match)
table.insert(self[k], match)
end)
end
end
else
-- This must be a 'per-directory keys' group
local keys = {}
while true do
local item = handler:read()
if not item then
break
end
if item:match(group_header) then
handler:seek("cur", -string.len(item) - 1)
break
end
local k, v = item:match("^(%w+)=(%w+)$")
if k == SIZE or k == MINSIZE or k == MAXSIZE or k == THRESHOLD then
keys[k] = tonumber(v)
elseif k == TYPE then
keys[k] = v
end
end
-- Size is a must. Other keys are optional.
if keys[SIZE] then
-- Set unset keys to the default values.
if not keys[TYPE] then keys[TYPE] = THRESHOLD end
if not keys[MINSIZE] then keys[MINSIZE] = keys[SIZE] end
if not keys[MAXSIZE] then keys[MAXSIZE] = keys[SIZE] end
if not keys[THRESHOLD] then keys[THRESHOLD] = 2 end
self.per_directory_keys[group] = keys
end
end
end
end
handler:close()
return self
end
--- Table of the values of the `Directories` key
-- @treturn table Values of the `Directories` key
index_theme.get_subdirectories = function(self)
return self[DIRECTORIES]
end
--- Table of the values of the `Inherits` key
-- @treturn table Values of the `Inherits` key
index_theme.get_inherits = function(self)
return self[INHERITS]
end
--- Query (part of) per-directory keys of a given subdirectory name.
-- @tparam table subdirectory Icon theme's subdirectory
-- @treturn[1] string Value of the `Type` key
-- @treturn[2] number Value of the `Size` key
-- @treturn[3] number VAlue of the `MinSize` key
-- @treturn[4] number Value of the `MaxSize` key
-- @treturn[5] number Value of the `Threshold` key
function index_theme:get_per_directory_keys(subdirectory)
local keys = self.per_directory_keys[subdirectory]
return keys[TYPE], keys[SIZE], keys[MINSIZE], keys[MAXSIZE], keys[THRESHOLD]
end
index_theme.mt.__call = function(cls, icon_theme_name, base_directories)
return index_theme.new(cls, icon_theme_name, base_directories)
end
return setmetatable(index_theme, index_theme.mt)
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| gpl-2.0 |
tianxiawuzhei/cocos-quick-lua | libs/quick/framework/transition.lua | 20 | 19757 | --[[
Copyright (c) 2011-2014 chukong-inc.com
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.
]]
--------------------------------
-- @module transition
--[[--
为图像创造效果
]]
local transition = {}
local ACTION_EASING = {}
ACTION_EASING["BACKIN"] = {cc.EaseBackIn, 1}
ACTION_EASING["BACKINOUT"] = {cc.EaseBackInOut, 1}
ACTION_EASING["BACKOUT"] = {cc.EaseBackOut, 1}
ACTION_EASING["BOUNCE"] = {cc.EaseBounce, 1}
ACTION_EASING["BOUNCEIN"] = {cc.EaseBounceIn, 1}
ACTION_EASING["BOUNCEINOUT"] = {cc.EaseBounceInOut, 1}
ACTION_EASING["BOUNCEOUT"] = {cc.EaseBounceOut, 1}
ACTION_EASING["ELASTIC"] = {cc.EaseElastic, 2, 0.3}
ACTION_EASING["ELASTICIN"] = {cc.EaseElasticIn, 2, 0.3}
ACTION_EASING["ELASTICINOUT"] = {cc.EaseElasticInOut, 2, 0.3}
ACTION_EASING["ELASTICOUT"] = {cc.EaseElasticOut, 2, 0.3}
ACTION_EASING["EXPONENTIALIN"] = {cc.EaseExponentialIn, 1}
ACTION_EASING["EXPONENTIALINOUT"] = {cc.EaseExponentialInOut, 1}
ACTION_EASING["EXPONENTIALOUT"] = {cc.EaseExponentialOut, 1}
ACTION_EASING["IN"] = {cc.EaseIn, 2, 1}
ACTION_EASING["INOUT"] = {cc.EaseInOut, 2, 1}
ACTION_EASING["OUT"] = {cc.EaseOut, 2, 1}
ACTION_EASING["RATEACTION"] = {cc.EaseRateAction, 2, 1}
ACTION_EASING["SINEIN"] = {cc.EaseSineIn, 1}
ACTION_EASING["SINEINOUT"] = {cc.EaseSineInOut, 1}
ACTION_EASING["SINEOUT"] = {cc.EaseSineOut, 1}
local actionManager = cc.Director:getInstance():getActionManager()
-- start --
--------------------------------
-- 创建一个缓动效果
-- @function [parent=#transition] newEasing
-- @param Action action 动作对象
-- @param string easingName 缓冲效果的名字, 具体参考 transition.execute() 方法
-- @param mixed more 创建缓冲效果的参数
-- @return mixed#mixed ret (return value: mixed) 结果
-- end --
function transition.newEasing(action, easingName, more)
local key = string.upper(tostring(easingName))
if string.sub(key, 1, 6) == "CCEASE" then
key = string.sub(key, 7)
end
local easing
if ACTION_EASING[key] then
local cls, count, default = unpack(ACTION_EASING[key])
if count == 2 then
easing = cls:create(action, more or default)
else
easing = cls:create(action)
end
end
return easing or action
end
-- start --
--------------------------------
-- 创建一个动作效果
-- @function [parent=#transition] create
-- @param Action action 动作对象
-- @param table args 参数表格对象
-- @return mixed#mixed ret (return value: mixed) 结果
-- end --
function transition.create(action, args)
args = checktable(args)
if args.easing then
if type(args.easing) == "table" then
action = transition.newEasing(action, unpack(args.easing))
else
action = transition.newEasing(action, args.easing)
end
end
local actions = {}
local delay = checknumber(args.delay)
if delay > 0 then
actions[#actions + 1] = cc.DelayTime:create(delay)
end
actions[#actions + 1] = action
local onComplete = args.onComplete
if type(onComplete) ~= "function" then onComplete = nil end
if onComplete then
actions[#actions + 1] = cc.CallFunc:create(onComplete)
end
if #actions > 1 then
return transition.sequence(actions)
else
return actions[1]
end
end
-- start --
--------------------------------
-- 执行一个动作效果
-- @function [parent=#transition] execute
-- @param cc.Node target 显示对象
-- @param Action action 动作对象
-- @param table args 参数表格对象
-- @return mixed#mixed ret (return value: mixed) 结果
--[[--
执行一个动作效果
~~~ lua
-- 等待 1.0 后开始移动对象
-- 耗时 1.5 秒,将对象移动到屏幕中央
-- 移动使用 backout 缓动效果
-- 移动结束后执行函数,显示 move completed
transition.execute(sprite, MoveTo:create(1.5, cc.p(display.cx, display.cy)), {
delay = 1.0,
easing = "backout",
onComplete = function()
print("move completed")
end,
})
~~~
transition.execute() 是一个强大的工具,可以为原本单一的动作添加各种附加特性。
transition.execute() 的参数表格支持下列参数:
- delay: 等待多长时间后开始执行动作
- easing: 缓动效果的名字及可选的附加参数,效果名字不区分大小写
- onComplete: 动作执行完成后要调用的函数
- time: 执行动作需要的时间
transition.execute() 支持的缓动效果:
- backIn
- backInOut
- backOut
- bounce
- bounceIn
- bounceInOut
- bounceOut
- elastic, 附加参数默认为 0.3
- elasticIn, 附加参数默认为 0.3
- elasticInOut, 附加参数默认为 0.3
- elasticOut, 附加参数默认为 0.3
- exponentialIn, 附加参数默认为 1.0
- exponentialInOut, 附加参数默认为 1.0
- exponentialOut, 附加参数默认为 1.0
- In, 附加参数默认为 1.0
- InOut, 附加参数默认为 1.0
- Out, 附加参数默认为 1.0
- rateaction, 附加参数默认为 1.0
- sineIn
- sineInOut
- sineOut
]]
-- end --
function transition.execute(target, action, args)
assert(not tolua.isnull(target), "transition.execute() - target is not cc.Node")
local action = transition.create(action, args)
target:runAction(action)
return action
end
-- start --
--------------------------------
-- 将显示对象旋转到指定角度,并返回 Action 动作对象。
-- @function [parent=#transition] rotateTo
-- @param cc.Node target 显示对象
-- @param table args 参数表格对象
-- @return mixed#mixed ret (return value: mixed) 结果
--[[--
将显示对象旋转到指定角度,并返回 Action 动作对象。
~~~ lua
-- 耗时 0.5 秒将 sprite 旋转到 180 度
transition.rotateTo(sprite, {rotate = 180, time = 0.5})
~~~
]]
-- end --
function transition.rotateTo(target, args)
assert(not tolua.isnull(target), "transition.rotateTo() - target is not cc.Node")
-- local rotation = args.rotate
local action = cc.RotateTo:create(args.time, args.rotate)
return transition.execute(target, action, args)
end
-- start --
--------------------------------
-- 将显示对象移动到指定位置,并返回 Action 动作对象。
-- @function [parent=#transition] moveTo
-- @param cc.Node target 显示对象
-- @param table args 参数表格对象
-- @return mixed#mixed ret (return value: mixed) 结果
--[[--
将显示对象移动到指定位置,并返回 Action 动作对象。
~~~ lua
-- 移动到屏幕中心
transition.moveTo(sprite, {x = display.cx, y = display.cy, time = 1.5})
-- 移动到屏幕左边,不改变 y
transition.moveTo(sprite, {x = display.left, time = 1.5})
-- 移动到屏幕底部,不改变 x
transition.moveTo(sprite, {y = display.bottom, time = 1.5})
~~~
]]
-- end --
function transition.moveTo(target, args)
assert(not tolua.isnull(target), "transition.moveTo() - target is not cc.Node")
local tx, ty = target:getPosition()
local x = args.x or tx
local y = args.y or ty
local action = cc.MoveTo:create(args.time, cc.p(x, y))
return transition.execute(target, action, args)
end
-- start --
--------------------------------
-- 将显示对象移动一定距离,并返回 Action 动作对象。
-- @function [parent=#transition] moveBy
-- @param cc.Node target 显示对象
-- @param table args 参数表格对象
-- @return mixed#mixed ret (return value: mixed) 结果
--[[--
将显示对象移动一定距离,并返回 Action 动作对象。
~~~ lua
-- 向右移动 100 点,向上移动 100 点
transition.moveBy(sprite, {x = 100, y = 100, time = 1.5})
-- 向左移动 100 点,不改变 y
transition.moveBy(sprite, {x = -100, time = 1.5})
-- 向下移动 100 点,不改变 x
transition.moveBy(sprite, {y = -100, time = 1.5})
~~~
]]
-- end --
function transition.moveBy(target, args)
assert(not tolua.isnull(target), "transition.moveBy() - target is not cc.Node")
local x = args.x or 0
local y = args.y or 0
local action = cc.MoveBy:create(args.time, cc.p(x, y))
return transition.execute(target, action, args)
end
-- start --
--------------------------------
-- 淡入显示对象,并返回 Action 动作对象。
-- @function [parent=#transition] fadeIn
-- @param cc.Node target 显示对象
-- @param table args 参数表格对象
-- @return mixed#mixed ret (return value: mixed) 结果
--[[--
淡入显示对象,并返回 Action 动作对象。
fadeIn 操作会首先将对象的透明度设置为 0(0%,完全透明),然后再逐步增加为 255(100%,完全不透明)。
如果不希望改变对象当前的透明度,应该用 fadeTo()。
~~~ lua
action = transition.fadeIn(sprite, {time = 1.5})
~~~
]]
-- end --
function transition.fadeIn(target, args)
assert(not tolua.isnull(target), "transition.fadeIn() - target is not cc.Node")
local action = cc.FadeIn:create(args.time)
return transition.execute(target, action, args)
end
-- start --
--------------------------------
-- 淡出显示对象,并返回 Action 动作对象。
-- @function [parent=#transition] fadeOut
-- @param cc.Node target 显示对象
-- @param table args 参数表格对象
-- @return mixed#mixed ret (return value: mixed) 结果
--[[--
淡出显示对象,并返回 Action 动作对象。
fadeOut 操作会首先将对象的透明度设置为 255(100%,完全不透明),然后再逐步减少为 0(0%,完全透明)。
如果不希望改变对象当前的透明度,应该用 fadeTo()。
~~~ lua
action = transition.fadeOut(sprite, {time = 1.5})
~~~
]]
-- end --
function transition.fadeOut(target, args)
assert(not tolua.isnull(target), "transition.fadeOut() - target is not cc.Node")
local action = cc.FadeOut:create(args.time)
return transition.execute(target, action, args)
end
-- start --
--------------------------------
-- 将显示对象的透明度改变为指定值,并返回 Action 动作对象。
-- @function [parent=#transition] fadeTo
-- @param cc.Node target 显示对象
-- @param table args 参数表格对象
-- @return mixed#mixed ret (return value: mixed) 结果
--[[--
将显示对象的透明度改变为指定值,并返回 Action 动作对象。
~~~ lua
-- 不管显示对象当前的透明度是多少,最终设置为 128
transition.fadeTo(sprite, {opacity = 128, time = 1.5})
~~~
]]
-- end --
function transition.fadeTo(target, args)
assert(not tolua.isnull(target), "transition.fadeTo() - target is not cc.Node")
local opacity = checkint(args.opacity)
if opacity < 0 then
opacity = 0
elseif opacity > 255 then
opacity = 255
end
local action = cc.FadeTo:create(args.time, opacity)
return transition.execute(target, action, args)
end
-- start --
--------------------------------
-- 将显示对象缩放到指定比例,并返回 Action 动作对象。
-- @function [parent=#transition] scaleTo
-- @param cc.Node target 显示对象
-- @param table args 参数表格对象
-- @return mixed#mixed ret (return value: mixed) 结果
--[[--
将显示对象缩放到指定比例,并返回 Action 动作对象。
~~~ lua
-- 整体缩放为 50%
transition.scaleTo(sprite, {scale = 0.5, time = 1.5})
-- 单独水平缩放
transition.scaleTo(sprite, {scaleX = 0.5, time = 1.5})
-- 单独垂直缩放
transition.scaleTo(sprite, {scaleY = 0.5, time = 1.5})
~~~
]]
-- end --
function transition.scaleTo(target, args)
assert(not tolua.isnull(target), "transition.scaleTo() - target is not cc.Node")
local action
if args.scale then
action = cc.ScaleTo:create(checknumber(args.time), checknumber(args.scale))
elseif args.scaleX or args.scaleY then
local scaleX, scaleY
if args.scaleX then
scaleX = checknumber(args.scaleX)
else
scaleX = target:getScaleX()
end
if args.scaleY then
scaleY = checknumber(args.scaleY)
else
scaleY = target:getScaleY()
end
action = cc.ScaleTo:create(checknumber(args.time), scaleX, scaleY)
end
return transition.execute(target, action, args)
end
-- start --
--------------------------------
-- 创建一个动作序列对象。
-- @function [parent=#transition] sequence
-- @param table args 动作的表格对象
-- @return Sequence#Sequence ret (return value: cc.Sequence) 动作序列对象
--[[--
创建一个动作序列对象。
~~~ lua
local sequence = transition.sequence({
cc.MoveTo:create(0.5, cc.p(display.cx, display.cy)),
cc.FadeOut:create(0.2),
cc.DelayTime:create(0.5),
cc.FadeIn:create(0.3),
})
sprite:runAction(sequence)
~~~
]]
-- end --
function transition.sequence(actions)
if #actions < 1 then return end
if #actions < 2 then return actions[1] end
local prev = actions[1]
for i = 2, #actions do
prev = cc.Sequence:create(prev, actions[i])
end
return prev
end
-- start --
--------------------------------
-- 在显示对象上播放一次动画,并返回 Action 动作对象。
-- @function [parent=#transition] playAnimationOnce
-- @param cc.Node target 显示对象
-- @param cc.Node animation 动作对象
-- @param boolean removeWhenFinished 播放完成后删除显示对象
-- @param function onComplete 播放完成后要执行的函数
-- @param number delay 播放前等待的时间
-- @return table#table ret (return value: table) 动作表格对象
--[[--
在显示对象上播放一次动画,并返回 Action 动作对象。
~~~ lua
local frames = display.newFrames("Walk%04d.png", 1, 20)
local animation = display.newAnimation(frames, 0.5 / 20) -- 0.5s play 20 frames
transition.playAnimationOnce(sprite, animation)
~~~
还可以用 Sprite 对象的 playAnimationOnce() 方法来直接播放动画:
~~~ lua
local frames = display.newFrames("Walk%04d.png", 1, 20)
local animation = display.newAnimation(frames, 0.5 / 20) -- 0.5s play 20 frames
sprite:playAnimationOnce(animation)
~~~
playAnimationOnce() 提供了丰富的功能,例如在动画播放完成后就删除用于播放动画的 Sprite 对象。例如一个爆炸效果:
~~~ lua
local frames = display.newFrames("Boom%04d.png", 1, 8)
local boom = display.newSprite(frames[1])
-- playAnimationOnce() 第二个参数为 true 表示动画播放完后删除 boom 这个 Sprite 对象
-- 这样爆炸动画播放完毕,就自动清理了不需要的显示对象
boom:playAnimationOnce(display.newAnimation(frames, 0.3/ 8), true)
~~~
此外,playAnimationOnce() 还允许在动画播放完成后执行一个指定的函数,以及播放动画前等待一段时间。合理运用这些功能,可以大大简化我们的游戏代码。
]]
-- end --
function transition.playAnimationOnce(target, animation, removeWhenFinished, onComplete, delay)
local actions = {}
if type(delay) == "number" and delay > 0 then
target:setVisible(false)
actions[#actions + 1] = cc.DelayTime:create(delay)
actions[#actions + 1] = cc.Show:create()
end
actions[#actions + 1] = cc.Animate:create(animation)
if removeWhenFinished then
actions[#actions + 1] = cc.RemoveSelf:create()
end
if onComplete then
actions[#actions + 1] = cc.CallFunc:create(onComplete)
end
local action
if #actions > 1 then
action = transition.sequence(actions)
else
action = actions[1]
end
target:runAction(action)
return action
end
-- start --
--------------------------------
-- 在显示对象上循环播放动画,并返回 Action 动作对象。
-- @function [parent=#transition] playAnimationForever
-- @param cc.Node target 显示对象
-- @param cc.Node animation 动作对象
-- @param number delay 播放前等待的时间
-- @return table#table ret (return value: table) 动作表格对象
--[[--
在显示对象上循环播放动画,并返回 Action 动作对象。
~~~ lua
local frames = display.newFrames("Walk%04d.png", 1, 20)
local animation = display.newAnimation(frames, 0.5 / 20) -- 0.5s play 20 frames
sprite:playAnimationForever(animation)
~~~
]]
-- end --
function transition.playAnimationForever(target, animation, delay)
local animate = cc.Animate:create(animation)
local action
if type(delay) == "number" and delay > 0 then
target:setVisible(false)
local sequence = transition.sequence({
cc.DelayTime:create(delay),
cc.Show:create(),
animate,
})
action = cc.RepeatForever:create(sequence)
else
action = cc.RepeatForever:create(animate)
end
target:runAction(action)
return action
end
-- start --
--------------------------------
-- 停止一个正在执行的动作
-- @function [parent=#transition] removeAction
-- @param mixed target
--[[--
停止一个正在执行的动作
~~~ lua
-- 开始移动
local action = transition.moveTo(sprite, {time = 2.0, x = 100, y = 100})
....
transition.removeAction(action) -- 停止移动
~~~
]]
-- end --
function transition.removeAction(action)
if not tolua.isnull(action) then
actionManager:removeAction(action)
end
end
-- start --
--------------------------------
-- 停止一个显示对象上所有正在执行的动作
-- @function [parent=#transition] stopTarget
-- @param mixed target
--[[--
停止一个显示对象上所有正在执行的动作
~~~ lua
-- 开始移动
transition.moveTo(sprite, {time = 2.0, x = 100, y = 100})
transition.fadeOut(sprite, {time = 2.0})
....
transition.stopTarget(sprite)
~~~
注意:显示对象的 performWithDelay() 方法是用动作来实现延时回调操作的,所以如果停止显示对象上的所有动作,会清除该对象上的延时回调操作。
]]
-- end --
function transition.stopTarget(target)
if not tolua.isnull(target) then
actionManager:removeAllActionsFromTarget(target)
end
end
-- start --
--------------------------------
-- 暂停显示对象上所有正在执行的动作
-- @function [parent=#transition] pauseTarget
-- @param mixed target
-- end --
function transition.pauseTarget(target)
if not tolua.isnull(target) then
actionManager:pauseTarget(target)
end
end
-- start --
--------------------------------
-- 恢复显示对象上所有暂停的动作
-- @function [parent=#transition] resumeTarget
-- @param mixed target
-- end --
function transition.resumeTarget(target)
if not tolua.isnull(target) then
actionManager:resumeTarget(target)
end
end
return transition
| mit |
MonkeyFirst/DisabledBoneSlerpWithShadowedAnimation | bin/Data/LuaScripts/Utilities/ScriptCompiler.lua | 29 | 1247 | -- Script to recursively compile lua files located in specified rootFolder to luc (bytecode)
-- Usage: require "LuaScripts/Utilities/LuaScriptCompiler"
-- Set root folder containing lua files to convert
local rootFolder = "Data/LuaScripts/" -- Starting from bin folder
if not fileSystem:DirExists(rootFolder) then log:Write(LOG_WARNING, "Cannot find " .. rootFolder) return end -- Ensure that rootFolder exists
-- Get lua files recursively
local files = fileSystem:ScanDir(fileSystem:GetProgramDir() .. rootFolder, "*.lua", SCAN_FILES, true)
if table.maxn(files) == 0 then log:Write(LOG_WARNING, "No lua file found in " .. rootFolder .. " and subfolders") return end -- Ensure that at least one file was found
-- Compile each lua file found in rootFolder and subfolders to luc
for i=1, table.maxn(files) do
local filename = rootFolder .. files[i] -- Get file with its path
if not fileSystem:FileExists(filename) then log:Write(LOG_WARNING, "Cannot find " .. filename) return end
print(filename .. "\n")
local args = {"-b", filename, ReplaceExtension(filename, ".luc")} -- Set arguments to pass to the luajit command line app
fileSystem:SystemRun(fileSystem:GetProgramDir() .. "luajit", args) -- Compile lua file to luc
end
| mit |
ChristopherBiscardi/kong | kong/resolver/access.lua | 2 | 7070 | local url = require "socket.url"
local cache = require "kong.tools.database_cache"
local stringy = require "stringy"
local constants = require "kong.constants"
local responses = require "kong.tools.responses"
local _M = {}
-- Take a public_dns and make it a pattern for wildcard matching.
-- Only do so if the public_dns actually has a wildcard.
local function create_wildcard_pattern(public_dns)
if string.find(public_dns, "*", 1, true) then
local pattern = string.gsub(public_dns, "%.", "%%.")
pattern = string.gsub(pattern, "*", ".+")
pattern = string.format("^%s$", pattern)
return pattern
end
end
-- Load all APIs in memory.
-- Sort the data for faster lookup: dictionary per public_dns, host,
-- and an array of wildcard public_dns.
local function load_apis_in_memory()
local apis, err = dao.apis:find_all()
if err then
return nil, err
end
-- build dictionnaries of public_dns:api and path:apis for efficient O(1) lookup.
-- we only do O(n) lookup for wildcard public_dns that are in an array.
local dns_dic, dns_wildcard, path_dic = {}, {}, {}
for _, api in ipairs(apis) do
if api.public_dns then
local pattern = create_wildcard_pattern(api.public_dns)
if pattern then
-- If the public_dns is a wildcard, we have a pattern and we can
-- store it in an array for later lookup.
table.insert(dns_wildcard, {pattern = pattern, api = api})
else
-- Keep non-wildcard public_dns in a dictionary for faster lookup.
dns_dic[api.public_dns] = api
end
end
if api.path then
path_dic[api.path] = api
end
end
return {by_dns = dns_dic, wildcard_dns = dns_wildcard, by_path = path_dic}
end
local function get_backend_url(api)
local result = api.target_url
-- Checking if the target url ends with a final slash
local len = string.len(result)
if string.sub(result, len, len) == "/" then
-- Remove one slash to avoid having a double slash
-- Because ngx.var.request_uri always starts with a slash
result = string.sub(result, 0, len - 1)
end
return result
end
local function get_host_from_url(val)
local parsed_url = url.parse(val)
local port
if parsed_url.port then
port = parsed_url.port
elseif parsed_url.scheme == "https" then
port = 443
end
return parsed_url.host..(port and ":"..port or "")
end
-- Find an API from a request made to nginx. Either from one of the Host or X-Host-Override headers
-- matching the API's `public_dns`, either from the `request_uri` matching the API's `path`.
--
-- To perform this, we need to query _ALL_ APIs in memory. It is the only way to compare the `request_uri`
-- as a regex to the values set in DB, as well as matching wildcard dns.
-- We keep APIs in the database cache for a longer time than usual.
-- @see https://github.com/Mashape/kong/issues/15 for an improvement on this.
--
-- @param `request_uri` The URI for this request.
-- @return `err` Any error encountered during the retrieval.
-- @return `api` The retrieved API, if any.
-- @return `hosts` The list of headers values found in Host and X-Host-Override.
-- @return `request_uri` The URI for this request.
-- @return `by_path` If the API was retrieved by path, will be true, false if by Host.
local function find_api(request_uri)
local retrieved_api
-- Retrieve all APIs
local apis_dics, err = cache.get_or_set("ALL_APIS_BY_DIC", load_apis_in_memory, 60) -- 60 seconds cache, longer than usual
if err then
return err
end
-- Find by Host header
local all_hosts = {}
for _, header_name in ipairs({"Host", constants.HEADERS.HOST_OVERRIDE}) do
local hosts = ngx.req.get_headers()[header_name]
if hosts then
if type(hosts) == "string" then
hosts = {hosts}
end
-- for all values of this header, try to find an API using the apis_by_dns dictionnary
for _, host in ipairs(hosts) do
host = unpack(stringy.split(host, ":"))
table.insert(all_hosts, host)
if apis_dics.by_dns[host] then
retrieved_api = apis_dics.by_dns[host]
--break
else
-- If the API was not found in the dictionary, maybe it is a wildcard public_dns.
-- In that case, we need to loop over all of them.
for _, wildcard_dns in ipairs(apis_dics.wildcard_dns) do
if string.match(host, wildcard_dns.pattern) then
retrieved_api = wildcard_dns.api
break
end
end
end
end
end
end
-- If it was found by Host, return.
if retrieved_api then
return nil, retrieved_api, all_hosts
end
-- Otherwise, we look for it by path. We have to loop over all APIs and compare the requested URI.
--
-- To do so, we have to compare entire URI segments (delimited by "/").
-- Comparing by entire segment allows us to avoid edge-cases such as:
-- request_uri = /mockbin-with-pattern/xyz
-- api.path regex = ^/mockbin
-- ^ This would wrongfully match. Wether:
-- api.path regex = ^/mockbin/
-- ^ This does not match.
-- Because we need to compare by entire URI segments, all URIs need to have a trailing slash, otherwise:
-- request_uri = /mockbin
-- api.path regex = ^/mockbin/
-- ^ This would not match.
if not stringy.endswith(request_uri, "/") then
request_uri = request_uri.."/"
end
for path, api in pairs(apis_dics.by_path) do
local m, err = ngx.re.match(request_uri, "^"..path.."/")
if err then
ngx.log(ngx.ERR, "[resolver] error matching requested path: "..err)
elseif m then
retrieved_api = api
break
end
end
-- Return the retrieved_api or nil
return nil, retrieved_api, all_hosts, true
end
-- Retrieve the API from the Host that has been requested
function _M.execute(conf)
local request_uri = ngx.var.request_uri
local err, api, hosts, by_path = find_api(request_uri)
if err then
return responses.send_HTTP_INTERNAL_SERVER_ERROR(err)
elseif not api then
return responses.send_HTTP_NOT_FOUND {
message = "API not found with these values",
public_dns = hosts,
path = request_uri
}
end
-- If API was retrieved by path and the path needs to be stripped
if by_path and api.strip_path then
-- Replace `/path` with `path`, and then prefix with a `/`
-- or replace `/path/foo` with `/foo`, and then do not prefix with `/`.
-- Handles pattern-specific characters if any.
local escaped_path = string.gsub(api.path, "[%(%)%.%%%+%-%*%?%[%]%^%$]", function(c) return "%"..c end)
request_uri = string.gsub(request_uri, escaped_path, "", 1)
if string.sub(request_uri, 0, 1) ~= "/" then
request_uri = "/"..request_uri
end
end
-- Setting the backend URL for the proxy_pass directive
ngx.var.backend_url = get_backend_url(api)..request_uri
if api.preserve_host then
ngx.var.backend_host = ngx.req.get_headers()["host"]
else
ngx.var.backend_host = get_host_from_url(ngx.var.backend_url)
end
ngx.ctx.api = api
end
return _M
| mit |
ChristopherBiscardi/kong | kong/resolver/handler.lua | 21 | 1037 | -- Kong resolver core-plugin
--
-- This core-plugin is executed before any other, and allows to map a Host header
-- to an API added to Kong. If the API was found, it will set the $backend_url variable
-- allowing nginx to proxy the request as defined in the nginx configuration.
--
-- Executions: 'access', 'header_filter'
local access = require "kong.resolver.access"
local BasePlugin = require "kong.plugins.base_plugin"
local certificate = require "kong.resolver.certificate"
local header_filter = require "kong.resolver.header_filter"
local ResolverHandler = BasePlugin:extend()
function ResolverHandler:new()
ResolverHandler.super.new(self, "resolver")
end
function ResolverHandler:access(conf)
ResolverHandler.super.access(self)
access.execute(conf)
end
function ResolverHandler:certificate(conf)
ResolverHandler.super.certificate(self)
certificate.execute(conf)
end
function ResolverHandler:header_filter(conf)
ResolverHandler.super.header_filter(self)
header_filter.execute(conf)
end
return ResolverHandler
| mit |
wrxck/mattata | plugins/meme.lua | 2 | 12424 | --[[
Copyright 2020 Matthew Hesketh <matthew@matthewhesketh.com>
This code is licensed under the MIT. See LICENSE for details.
]]
local meme = {}
local mattata = require('mattata')
function meme:init()
meme.commands = mattata.commands(self.info.username)
:command('meme')
:command('memegen').table
meme.help = '/meme <top line> | <bottom line> - Generates an image macro with the given text, on your choice of the available selection of templates. This command can only be used inline. Alias: /memegen.'
end
function meme.escape(str)
if not str
or type(str) ~= 'string'
then
return str
end
str = str:lower()
return str
:gsub('%s', '_')
:gsub('%?', '~q')
:gsub('%%', '~p')
:gsub('#', '~h')
:gsub('/', '~s')
:gsub('"', '\'\'')
end
meme.memes = {
'ggg',
'elf',
'fwp',
'yuno',
'aag',
'badchoice',
'happening',
'scc',
'sad-obama',
'fbf',
'ants',
'ive',
'biw',
'crazypills',
'remembers',
'oag',
'ski',
'oprah',
'wonka',
'regret',
'fa',
'keanu',
'kermit',
'both',
'awkward',
'dodgson',
'bad',
'mmm',
'ch',
'live',
'firsttry',
'noidea',
'sad-biden',
'buzz',
'blb',
'fry',
'morpheus',
'cbg',
'xy',
'rollsafe',
'yodawg',
'fetch',
'sarcasticbear',
'cb',
'hipster',
'success',
'bd',
'bender',
'fine',
'bs',
'toohigh',
'mw',
'money',
'interesting',
'sb',
'doge',
'ermg',
'fmr',
'sparta',
'older',
'philosoraptor',
'awkward-awesome',
'awesome',
'chosen',
'alwaysonbeat',
'ackbar',
'sadfrog',
'sohot',
'imsorry',
'tenguy',
'winter',
'red',
'awesome-awkward',
'jw',
'sf',
'ss',
'patrick',
'center',
'boat',
'saltbae',
'tried',
'mb',
'hagrid',
'mordor',
'snek',
'sad-bush',
'nice',
'sad-clinton',
'afraid',
'stew',
'icanhas',
'away',
'dwight',
'facepalm',
'yallgot',
'jetpack',
'captain',
'inigo',
'iw',
'dsm',
'sad-boehner',
'll',
'joker',
'sohappy',
'officespace'
}
meme.meme_info = {
['tenguy'] = {
['width'] = 600,
['height'] = 544
},
['afraid'] = {
['width'] = 600,
['height'] = 588
},
['older'] = {
['width'] = 600,
['height'] = 255
},
['aag'] = {
['width'] = 600,
['height'] = 502
},
['tried'] = {
['width'] = 600,
['height'] = 600
},
['biw'] = {
['width'] = 600,
['height'] = 450
},
['stew'] = {
['width'] = 600,
['height'] = 448
},
['blb'] = {
['width'] = 600,
['height'] = 600
},
['kermit'] = {
['width'] = 600,
['height'] = 421
},
['bd'] = {
['width'] = 600,
['height'] = 597
},
['ch'] = {
['width'] = 600,
['height'] = 450
},
['cbg'] = {
['width'] = 600,
['height'] = 368
},
['wonka'] = {
['width'] = 600,
['height'] = 431
},
['cb'] = {
['width'] = 600,
['height'] = 626
},
['keanu'] = {
['width'] = 600,
['height'] = 597
},
['dsm'] = {
['width'] = 600,
['height'] = 900
},
['live'] = {
['width'] = 600,
['height'] = 405
},
['ants'] = {
['width'] = 600,
['height'] = 551
},
['doge'] = {
['width'] = 600,
['height'] = 600
},
['alwaysonbeat'] = {
['width'] = 600,
['height'] = 337
},
['ermg'] = {
['width'] = 600,
['height'] = 901
},
['facepalm'] = {
['width'] = 600,
['height'] = 529
},
['firsttry'] = {
['width'] = 600,
['height'] = 440
},
['fwp'] = {
['width'] = 600,
['height'] = 423
},
['fa'] = {
['width'] = 600,
['height'] = 600
},
['fbf'] = {
['width'] = 600,
['height'] = 597
},
['fmr'] = {
['width'] = 600,
['height'] = 385
},
['fry'] = {
['width'] = 600,
['height'] = 449
},
['ggg'] = {
['width'] = 600,
['height'] = 375
},
['hipster'] = {
['width'] = 600,
['height'] = 899
},
['icanhas'] = {
['width'] = 600,
['height'] = 874
},
['crazypills'] = {
['width'] = 600,
['height'] = 408
},
['mw'] = {
['width'] = 600,
['height'] = 441
},
['noidea'] = {
['width'] = 600,
['height'] = 382
},
['regret'] = {
['width'] = 600,
['height'] = 536
},
['boat'] = {
['width'] = 600,
['height'] = 441
},
['hagrid'] = {
['width'] = 600,
['height'] = 446
},
['sohappy'] = {
['width'] = 600,
['height'] = 700
},
['captain'] = {
['width'] = 600,
['height'] = 439
},
['bender'] = {
['width'] = 600,
['height'] = 445
},
['inigo'] = {
['width'] = 600,
['height'] = 326
},
['iw'] = {
['width'] = 600,
['height'] = 600
},
['ackbar'] = {
['width'] = 600,
['height'] = 777
},
['happening'] = {
['width'] = 600,
['height'] = 364
},
['joker'] = {
['width'] = 600,
['height'] = 554
},
['ive'] = {
['width'] = 600,
['height'] = 505
},
['ll'] = {
['width'] = 600,
['height'] = 399
},
['away'] = {
['width'] = 600,
['height'] = 337
},
['morpheus'] = {
['width'] = 600,
['height'] = 363
},
['mb'] = {
['width'] = 600,
['height'] = 534
},
['badchoice'] = {
['width'] = 600,
['height'] = 478
},
['mmm'] = {
['width'] = 600,
['height'] = 800
},
['jetpack'] = {
['width'] = 600,
['height'] = 450
},
['imsorry'] = {
['width'] = 600,
['height'] = 337
},
['red'] = {
['width'] = 600,
['height'] = 557
},
['mordor'] = {
['width'] = 600,
['height'] = 353
},
['oprah'] = {
['width'] = 600,
['height'] = 449
},
['oag'] = {
['width'] = 600,
['height'] = 450
},
['remembers'] = {
['width'] = 600,
['height'] = 458
},
['philosoraptor'] = {
['width'] = 600,
['height'] = 600
},
['jw'] = {
['width'] = 600,
['height'] = 401
},
['patrick'] = {
['width'] = 600,
['height'] = 1056
},
['rollsafe'] = {
['width'] = 600,
['height'] = 335
},
['sad-obama'] = {
['width'] = 600,
['height'] = 600
},
['sad-clinton'] = {
['width'] = 600,
['height'] = 542
},
['sadfrog'] = {
['width'] = 600,
['height'] = 600
},
['sad-bush'] = {
['width'] = 600,
['height'] = 455
},
['sad-biden'] = {
['width'] = 600,
['height'] = 600
},
['sad-boehner'] = {
['width'] = 600,
['height'] = 479
},
['saltbae'] = {
['width'] = 600,
['height'] = 603
},
['sarcasticbear'] = {
['width'] = 600,
['height'] = 450
},
['dwight'] = {
['width'] = 600,
['height'] = 393
},
['sb'] = {
['width'] = 600,
['height'] = 421
},
['ss'] = {
['width'] = 600,
['height'] = 604
},
['sf'] = {
['width'] = 600,
['height'] = 376
},
['dodgson'] = {
['width'] = 600,
['height'] = 559
},
['money'] = {
['width'] = 600,
['height'] = 337
},
['snek'] = {
['width'] = 600,
['height'] = 513
},
['sohot'] = {
['width'] = 600,
['height'] = 480
},
['nice'] = {
['width'] = 600,
['height'] = 432
},
['awesome-awkward'] = {
['width'] = 600,
['height'] = 601
},
['awesome'] = {
['width'] = 600,
['height'] = 600
},
['awkward-awesome'] = {
['width'] = 600,
['height'] = 600
},
['awkward'] = {
['width'] = 600,
['height'] = 600
},
['fetch'] = {
['width'] = 600,
['height'] = 450
},
['success'] = {
['width'] = 600,
['height'] = 578
},
['scc'] = {
['width'] = 600,
['height'] = 326
},
['ski'] = {
['width'] = 600,
['height'] = 404
},
['officespace'] = {
['width'] = 600,
['height'] = 501
},
['interesting'] = {
['width'] = 600,
['height'] = 759
},
['toohigh'] = {
['width'] = 600,
['height'] = 408
},
['bs'] = {
['width'] = 600,
['height'] = 600
},
['fine'] = {
['width'] = 600,
['height'] = 582
},
['sparta'] = {
['width'] = 600,
['height'] = 316
},
['center'] = {
['width'] = 600,
['height'] = 370
},
['both'] = {
['width'] = 600,
['height'] = 600
},
['winter'] = {
['width'] = 600,
['height'] = 460
},
['xy'] = {
['width'] = 600,
['height'] = 455
},
['buzz'] = {
['width'] = 600,
['height'] = 455
},
['yodawg'] = {
['width'] = 600,
['height'] = 399
},
['yuno'] = {
['width'] = 600,
['height'] = 450
},
['yallgot'] = {
['width'] = 600,
['height'] = 470
},
['bad'] = {
['width'] = 600,
['height'] = 450
},
['elf'] = {
['width'] = 600,
['height'] = 369
},
['chosen'] = {
['width'] = 600,
['height'] = 342
}
}
function meme.get_memes(offset, first_line, last_line)
local first = (
offset
and type(offset) == 'number'
)
and offset + 1
or 1
local last = first + 49
if first >= last
then
return
elseif last > #meme.memes
then
last = #meme.memes
end
local output = {}
local id = first
for i = first, last
do
local image = 'https://memegen.link/' .. meme.memes[i] .. '/' .. meme.escape(first_line)
if last_line
then
image = image .. '/' .. meme.escape(last_line)
end
image = image .. '.jpg?font=impact'
table.insert(
output,
mattata.inline_result()
:type('photo')
:id(
tostring(id)
)
:photo_url(image)
:thumb_url(image)
:photo_width(
tostring(meme.meme_info[meme.memes[i]]['width'])
)
:photo_height(
tostring(meme.meme_info[meme.memes[i]]['height'])
)
)
id = id + 1
end
if last == #meme.memes
then
last = false
end
return output, last
end
function meme:on_inline_query(inline_query)
local input = mattata.input(inline_query.query)
if not input
then
return false
end
input = input:gsub('\n', ' | ')
local first_line, last_line = input, false
if input:match('^.- | .-$')
then
first_line, last_line = input:match('^(.-) | (.-)$')
end
first_line = first_line:gsub(' | ', ' ')
if last_line
then
last_line = last_line:gsub(' | ', ' ')
end
local offset = inline_query.offset
and tonumber(inline_query.offset)
or 0
local output, next_offset = meme.get_memes(
offset,
first_line,
last_line
)
return mattata.answer_inline_query(
inline_query.id,
output,
0,
false,
next_offset
and tostring(next_offset)
or nil
)
end
function meme:on_message(message)
return mattata.send_message(
message.chat.id,
'This command can only be used inline!'
)
end
return meme | mit |
FrisKAY/MineOS_Server | lib/syntax.lua | 1 | 14502 | _G.buffer = require("doubleBuffering")
_G.unicode = require("unicode")
local syntax = {}
----------------------------------------------------------------------------------------------------------------------------------------
--Стандартные цветовые схемы
syntax.colorSchemes = {
midnight = {
background = 0x262626,
text = 0xffffff,
strings = 0xff2024,
loops = 0xffff98,
comments = 0xa2ffb7,
boolean = 0xffcc66,
logic = 0xffcc66,
numbers = 0x24c0ff,
functions = 0xffcc66,
compares = 0xffff98,
lineNumbers = 0x444444,
lineNumbersText = 0xDDDDDD,
scrollBar = 0x444444,
scrollBarPipe = 0x24c0ff,
selection = 0x99B2F2,
},
sunrise = {
background = 0xffffff,
text = 0x262626,
strings = 0x880000,
loops = 0x24c0ff,
comments = 0xa2ffb7,
boolean = 0x19c0cc,
logic = 0x880000,
numbers = 0x24c0ff,
functions = 0x24c0ff,
compares = 0x880000,
lineNumbers = 0x444444,
lineNumbersText = 0xDDDDDD,
scrollBar = 0x444444,
scrollBarPipe = 0x24c0ff,
selection = 0x99B2F2,
},
}
--Текущая цветовая схема
local currentColorScheme = {}
--Шаблоны поиска
local patterns
----------------------------------------------------------------------------------------------------------------------------------------
--Пересчитать цвета шаблонов
--Приоритет поиска шаблонов снижается сверху вниз
local function definePatterns()
patterns = {
--Комментарии
{ pattern = "%-%-.*", color = currentColorScheme.comments, cutFromLeft = 0, cutFromRight = 0 },
--Строки
{ pattern = "\"[^\"\"]*\"", color = currentColorScheme.strings, cutFromLeft = 0, cutFromRight = 0 },
--Циклы, условия, объявления
{ pattern = "while ", color = currentColorScheme.loops, cutFromLeft = 0, cutFromRight = 1 },
{ pattern = "do$", color = currentColorScheme.loops, cutFromLeft = 0, cutFromRight = 0 },
{ pattern = "do ", color = currentColorScheme.loops, cutFromLeft = 0, cutFromRight = 1 },
{ pattern = "end$", color = currentColorScheme.loops, cutFromLeft = 0, cutFromRight = 0 },
{ pattern = "end ", color = currentColorScheme.loops, cutFromLeft = 0, cutFromRight = 1 },
{ pattern = "for ", color = currentColorScheme.loops, cutFromLeft = 0, cutFromRight = 1 },
{ pattern = " in ", color = currentColorScheme.loops, cutFromLeft = 0, cutFromRight = 1 },
{ pattern = "repeat ", color = currentColorScheme.loops, cutFromLeft = 0, cutFromRight = 1 },
{ pattern = "if ", color = currentColorScheme.loops, cutFromLeft = 0, cutFromRight = 1 },
{ pattern = "then", color = currentColorScheme.loops, cutFromLeft = 0, cutFromRight = 0 },
{ pattern = "until ", color = currentColorScheme.loops, cutFromLeft = 0, cutFromRight = 1 },
{ pattern = "return", color = currentColorScheme.loops, cutFromLeft = 0, cutFromRight = 0 },
{ pattern = "local ", color = currentColorScheme.loops, cutFromLeft = 0, cutFromRight = 1 },
{ pattern = "function ", color = currentColorScheme.loops, cutFromLeft = 0, cutFromRight = 1 },
{ pattern = "else$", color = currentColorScheme.loops, cutFromLeft = 0, cutFromRight = 0 },
{ pattern = "else ", color = currentColorScheme.loops, cutFromLeft = 0, cutFromRight = 1 },
{ pattern = "elseif ", color = currentColorScheme.loops, cutFromLeft = 0, cutFromRight = 1 },
--Состояния переменной
{ pattern = "true", color = currentColorScheme.boolean, cutFromLeft = 0, cutFromRight = 0 },
{ pattern = "false", color = currentColorScheme.boolean, cutFromLeft = 0, cutFromRight = 0 },
{ pattern = "nil", color = currentColorScheme.boolean, cutFromLeft = 0, cutFromRight = 0 },
--Функции
{ pattern = "%s([%a%d%_%-%.]*)%(", color = currentColorScheme.functions, cutFromLeft = 0, cutFromRight = 1 },
--And, or, not, break
{ pattern = " and ", color = currentColorScheme.logic, cutFromLeft = 0, cutFromRight = 1 },
{ pattern = " or ", color = currentColorScheme.logic, cutFromLeft = 0, cutFromRight = 1 },
{ pattern = " not ", color = currentColorScheme.logic, cutFromLeft = 0, cutFromRight = 1 },
{ pattern = " break$", color = currentColorScheme.logic, cutFromLeft = 0, cutFromRight = 0 },
{ pattern = "^break", color = currentColorScheme.logic, cutFromLeft = 0, cutFromRight = 0 },
{ pattern = " break ", color = currentColorScheme.logic, cutFromLeft = 0, cutFromRight = 0 },
--Сравнения и мат. операции
{ pattern = "<=", color = currentColorScheme.compares, cutFromLeft = 0, cutFromRight = 0 },
{ pattern = ">=", color = currentColorScheme.compares, cutFromLeft = 0, cutFromRight = 0 },
{ pattern = "<", color = currentColorScheme.compares, cutFromLeft = 0, cutFromRight = 0 },
{ pattern = ">", color = currentColorScheme.compares, cutFromLeft = 0, cutFromRight = 0 },
{ pattern = "==", color = currentColorScheme.compares, cutFromLeft = 0, cutFromRight = 0 },
{ pattern = "~=", color = currentColorScheme.compares, cutFromLeft = 0, cutFromRight = 0 },
{ pattern = "=", color = currentColorScheme.compares, cutFromLeft = 0, cutFromRight = 0 },
{ pattern = "%+", color = currentColorScheme.compares, cutFromLeft = 0, cutFromRight = 0 },
{ pattern = "%-", color = currentColorScheme.compares, cutFromLeft = 0, cutFromRight = 0 },
{ pattern = "%*", color = currentColorScheme.compares, cutFromLeft = 0, cutFromRight = 0 },
{ pattern = "%/", color = currentColorScheme.compares, cutFromLeft = 0, cutFromRight = 0 },
{ pattern = "%.%.", color = currentColorScheme.compares, cutFromLeft = 0, cutFromRight = 0 },
{ pattern = "%#", color = currentColorScheme.compares, cutFromLeft = 0, cutFromRight = 0 },
{ pattern = "#^", color = currentColorScheme.compares, cutFromLeft = 0, cutFromRight = 0 },
--Числа
{ pattern = "%s(0x)(%w*)", color = currentColorScheme.numbers, cutFromLeft = 0, cutFromRight = 0 },
{ pattern = "(%s)([%d%.]*)", color = currentColorScheme.numbers, cutFromLeft = 0, cutFromRight = 0 },
}
end
--Костыльная замена обычному string.find()
--Работает медленнее, но хотя бы поддерживает юникод
function unicode.find(str, pattern, init, plain)
-- checkArg(1, str, "string")
-- checkArg(2, pattern, "string")
-- checkArg(3, init, "number", "nil")
if init then
if init < 0 then
init = -#unicode.sub(str,init)
elseif init > 0 then
init = #unicode.sub(str, 1, init - 1) + 1
end
end
a, b = string.find(str, pattern, init, plain)
if a then
local ap, bp = str:sub(1, a - 1), str:sub(a,b)
a = unicode.len(ap) + 1
b = a + unicode.len(bp) - 1
return a, b
else
return a
end
end
--Объявить новую цветовую схему
function syntax.setColorScheme(colorScheme)
--Выбранная цветовая схема
currentColorScheme = colorScheme
--Пересчитываем шаблоны
definePatterns()
end
----------------------------------------------------------------------------------------------------------------------------------------
--Проанализировать строку и создать на ее основе цветовую карту
function syntax.highlight(x, y, text, fromSymbol, limit)
--Кароч вооот, хыыы
local searchFrom, starting, ending
--Загоняем в буфер всю строку базового цвета
buffer.text(x - fromSymbol + 1, y, currentColorScheme.text, text)
--Перебираем шаблоны
for i = #patterns, 1, -1 do
searchFrom = 1
--Перебираем весь текст, а то мало ли шаблон дохуя раз встречается
while true do
starting, ending = unicode.find(text, patterns[i].pattern, searchFrom)
if starting and ending then
buffer.text(x + starting - fromSymbol, y, patterns[i].color, unicode.sub(text, starting, ending - patterns[i].cutFromRight))
if ending > limit then break end
searchFrom = ending + 1
else
break
end
end
end
end
function syntax.convertFileToStrings(path)
local array = {}
local maximumStringWidth = 0
local file = io.open(path, "r")
for line in file:lines() do
line = string.gsub(line, " ", string.rep(" ", 4))
maximumStringWidth = math.max(maximumStringWidth, unicode.len(line))
table.insert(array, line)
end
file:close()
return array, maximumStringWidth
end
-- Открыть окно-просмотрщик кода
function syntax.viewCode(x, y, width, height, strings, maximumStringWidth, fromSymbol, fromString, highlightLuaSyntax, selection, highlightedStrings)
--Рассчитываем максимальное количество строк, которое мы будем отображать
local maximumNumberOfAvailableStrings, yPos
if strings[fromString + height - 1] then
maximumNumberOfAvailableStrings = fromString + height - 2
else
maximumNumberOfAvailableStrings = #strings - 1
end
--Рассчитываем ширину полоски с номерами строк
local widthOfStringCounter = unicode.len(maximumNumberOfAvailableStrings) + 2
--Рассчитываем стратовую позицию текстового поля
local textFieldPosition = x + widthOfStringCounter
local widthOfText = width - widthOfStringCounter - 3
local xEnd, yEnd = x + width - 1, y + height - 1
--Рисуем подложку под текст
buffer.square(x, y, width, height, currentColorScheme.background, 0xFFFFFF, " ")
--Рисуем подложку под номера строк
buffer.square(x, y, widthOfStringCounter, height, currentColorScheme.lineNumbers, 0xFFFFFF, " ")
--Рисуем вертикальный скроллбар
buffer.scrollBar(xEnd, y, 1, height, #strings, fromString, currentColorScheme.scrollBar, currentColorScheme.scrollBarPipe)
--Рисуем горизонтальный скроллбар
buffer.horizontalScrollBar(x + widthOfStringCounter, yEnd, width - widthOfStringCounter - 1, maximumStringWidth, fromSymbol, currentColorScheme.scrollBar, currentColorScheme.scrollBarPipe)
--Подсвечиваем некоторые строки, если указано
if highlightedStrings then
for i = 1, #highlightedStrings do
if highlightedStrings[i].number >= fromString and highlightedStrings[i].number < fromString + height then
buffer.square(x, y + highlightedStrings[i].number - fromString, width - 1, 1, highlightedStrings[i].color, 0xFFFFFF, " ")
buffer.square(x, y + highlightedStrings[i].number - fromString, widthOfStringCounter, 1, currentColorScheme.lineNumbers, 0xFFFFFF, " ", 60)
end
end
end
--Рисуем номера строк
yPos = y
for i = fromString, maximumNumberOfAvailableStrings do
buffer.text(x + widthOfStringCounter - unicode.len(i) - 1, yPos, currentColorScheme.text, tostring(i))
yPos = yPos + 1
end
--Рисуем выделение, если оно имеется
if selection then
--Считаем высоту выделения
local heightOfSelection = selection.to.y - selection.from.y + 1
--Если высота выделения > 1
if heightOfSelection > 1 then
--Верхнее выделение
if selection.from.x < fromSymbol + widthOfText and selection.from.y >= fromString and selection.from.y < fromString + height then
local cyka = textFieldPosition + selection.from.x - fromSymbol
if cyka < textFieldPosition then
cyka = textFieldPosition
end
buffer.square(cyka, y + selection.from.y - fromString, widthOfText - cyka + widthOfStringCounter + 2 + x, 1, currentColorScheme.selection, 0xFFFFFF, " ")
end
--Средние выделения
if heightOfSelection > 2 then
for i = 1, heightOfSelection - 2 do
if selection.from.y + i >= fromString and selection.from.y + i < fromString + height then
buffer.square(textFieldPosition, y + selection.from.y + i - fromString, widthOfText + 2, 1, currentColorScheme.selection, 0xFFFFFF, " ")
end
end
end
--Нижнее выделение
if selection.to.x >= fromSymbol and selection.to.y >= fromString and selection.to.y < fromString + height then
buffer.square(textFieldPosition, y + selection.to.y - fromString, selection.to.x - fromSymbol + 1, 1, currentColorScheme.selection, 0xFFFFFF, " ")
end
elseif heightOfSelection == 1 then
local cyka = selection.to.x
if cyka > fromSymbol + widthOfText - 1 then cyka = fromSymbol + widthOfText - 1 end
buffer.square(textFieldPosition + selection.from.x, selection.from.y, cyka - selection.from.x, 1, currentColorScheme.selection, 0xFFFFFF, " ")
end
end
--Выставляем ограничение прорисовки буфера
textFieldPosition = textFieldPosition + 1
buffer.setDrawLimit(textFieldPosition, y, widthOfText, height)
--Рисуем текст
yPos = y
for i = fromString, maximumNumberOfAvailableStrings do
--Учитываем опциональную подсветку ситнаксиса
if highlightLuaSyntax then
syntax.highlight(textFieldPosition, yPos, strings[i], fromSymbol, widthOfText)
else
buffer.text(textFieldPosition, yPos, currentColorScheme.text, unicode.sub(strings[i], fromSymbol, widthOfText))
end
yPos = yPos + 1
end
--Убираем ограничение отрисовки
buffer.resetDrawLimit()
return textFieldPosition
end
----------------------------------------------------------------------------------------------------------------
-- Стартовое объявление цветовой схемы при загрузке библиотеки
syntax.setColorScheme(syntax.colorSchemes.midnight)
-- -- Епты бля!
-- local strings, maximumStringWidth = syntax.convertFileToStrings("MineOS/Applications/Highlight.app/Resources/TestFile.txt")
-- local strings = syntax.convertFileToStrings("OS.lua")
-- local xSize, ySize = gpu.getResolution()
-- buffer.square(1, 1, xSize, ySize, ecs.colors.red, 0xFFFFFF, " ")
-- buffer.draw(true)
-- local selection = {
-- from = {x = 8, y = 6},
-- to = {x = 16, y = 12}
-- }
-- local highlightedStrings = {
-- {number = 31, color = 0xFF4444},
-- {number = 32, color = 0xFF4444},
-- }
-- syntax.viewCode(20, 5, 100, 40, strings, maximumStringWidth, 1, 20, true, selection, highlightedStrings)
----------------------------------------------------------------------------------------------------------------
return syntax
| gpl-3.0 |
LuaDist2/lzmq-ffi | test/lunit/console.lua | 19 | 3798 |
--[[--------------------------------------------------------------------------
This file is part of lunit 0.6.
For Details about lunit look at: http://www.mroth.net/lunit/
Author: Michael Roth <mroth@nessie.de>
Copyright (c) 2006-2008 Michael Roth <mroth@nessie.de>
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.
--]]--------------------------------------------------------------------------
--[[
begin()
run(testcasename, testname)
err(fullname, message, traceback)
fail(fullname, where, message, usermessage)
pass(testcasename, testname)
done()
Fullname:
testcase.testname
testcase.testname:setupname
testcase.testname:teardownname
--]]
local lunit = require "lunit"
local string = require "string"
local io = require "io"
local table = require "table"
local _M = {}
local function rfill(str, wdt, ch)
if wdt > #str then str = str .. (ch or ' '):rep(wdt - #str) end
return str
end
local function printformat(format, ...)
io.write( string.format(format, ...) )
end
local columns_printed = 0
local function writestatus(char)
if columns_printed == 0 then
io.write(" ")
end
if columns_printed == 60 then
io.write("\n ")
columns_printed = 0
end
io.write(char)
io.flush()
columns_printed = columns_printed + 1
end
local msgs = {}
function _M.begin()
local total_tc = 0
local total_tests = 0
msgs = {} -- e
for tcname in lunit.testcases() do
total_tc = total_tc + 1
for testname, test in lunit.tests(tcname) do
total_tests = total_tests + 1
end
end
printformat("Loaded testsuite with %d tests in %d testcases.\n\n", total_tests, total_tc)
end
function _M.run(testcasename, testname)
io.write(rfill(testcasename .. '.' .. testname, 70)) io.flush()
end
function _M.err(fullname, message, traceback)
io.write(" - error!\n")
io.write("Error! ("..fullname.."):\n"..message.."\n\t"..table.concat(traceback, "\n\t"), "\n")
end
function _M.fail(fullname, where, message, usermessage)
io.write(" - fail!\n")
io.write(string.format("Failure (%s): %s\n%s: %s", fullname, usermessage or "", where, message), "\n")
end
function _M.skip(fullname, where, message, usermessage)
io.write(" - skip!\n")
io.write(string.format("Skip (%s): %s\n%s: %s", fullname, usermessage or "", where, message), "\n")
end
function _M.pass(testcasename, testname)
io.write(" - pass!\n")
end
function _M.done()
printformat("\n\n%d Assertions checked.\n", lunit.stats.assertions )
print()
printformat("Testsuite finished (%d passed, %d failed, %d errors, %d skipped).\n",
lunit.stats.passed, lunit.stats.failed, lunit.stats.errors, lunit.stats.skipped )
end
return _M
| mit |
dschoeffm/MoonGen | interface/flow/instance.lua | 4 | 2016 | local Flow = {}
Flow.__index = Flow
local function separateUid(uid)
-- luacheck: globals read bit
return
bit.band(bit.rshift(uid, 24), 0xff),
bit.band(bit.rshift(uid, 16), 0xff),
bit.band(bit.rshift(uid, 8), 0xff),
bit.band(bit.rshift(uid, 0), 0xff)
end
function Flow:prepare(error, final)
self.isDynamic = type(self.updatePacket) ~= "nil"
self.packet:prepare(error, self, final)
if self:option "uniquePayload" then
local p0, p1, p2, p3 = separateUid(self:option "uid")
local size = self:packetSize()
self.setPayload = function(pkt)
local bytes = pkt:getBytes()
bytes[size - 1] = p0
bytes[size - 2] = p1
bytes[size - 3] = p2
bytes[size - 4] = p3
end
else
self.setPayload = function() end
end
end
function Flow:property(name)
return self.properties[name]
end
function Flow:setProperty(name, val)
self.properties[name] = val
end
function Flow:option(name)
return self.results[name]
end
function Flow:fillBuf(buf)
local pkt = self.packet.getPacket(buf)
pkt:fill(self.packet.fillTbl)
self.setPayload(buf)
return pkt
end
function Flow:fillUpdateBuf(buf)
local pkt = self.packet.getPacket(buf)
pkt:fill(self.packet.fillTbl)
self.setPayload(buf)
self.updatePacket(self.packet.dynvars, pkt)
return pkt
end
function Flow:updateBuf(buf)
local pkt = self.packet.getPacket(buf)
self.updatePacket(self.packet.dynvars, pkt)
return pkt
end
function Flow:packetSize(checksum)
return (self.packet.fillTbl.pktLength or 0) + (checksum and 4 or 0)
end
function Flow:clone(properties)
local clone = setmetatable({}, Flow)
for i,v in pairs(self) do
if i == "properties" then
clone[i] = mergeTables({}, v, properties) -- luacheck: globals read mergeTables
else
clone[i] = v
end
end
return clone
end
function Flow:getDelay()
local cbr = self.results.rate
if cbr then
local psize = self:packetSize(true)
-- cbr => mbit/s => bit/1000ns
-- psize => b/p => 8bit/p
return 8000 * psize / cbr -- => ns/p
end
end
return Flow
| mit |
bigdogmat/wire | lua/entities/gmod_wire_light.lua | 10 | 7999 | AddCSLuaFile()
DEFINE_BASECLASS( "base_wire_entity" )
ENT.PrintName = "Wire Light"
ENT.RenderGroup = RENDERGROUP_BOTH
ENT.WireDebugName = "Light"
function ENT:SetupDataTables()
self:NetworkVar( "Bool", 0, "Glow" )
self:NetworkVar( "Float", 0, "Brightness" )
self:NetworkVar( "Float", 1, "Size" )
self:NetworkVar( "Int", 0, "R" )
self:NetworkVar( "Int", 1, "G" )
self:NetworkVar( "Int", 2, "B" )
end
if CLIENT then
local matLight = Material( "sprites/light_ignorez" )
local matBeam = Material( "effects/lamp_beam" )
function ENT:Initialize()
self.PixVis = util.GetPixelVisibleHandle()
--[[
This is some unused value which is used to activate the wire overlay.
We're not using it because we are using NetworkVars instead, since wire
overlays only update when you look at them, and we want to update the
sprite colors whenever the wire input changes. ]]
self:SetOverlayData({})
end
function ENT:GetMyColor()
return Color( self:GetR(), self:GetG(), self:GetB(), 255 )
end
function ENT:DrawTranslucent()
local up = self:GetAngles():Up()
local LightPos = self:GetPos()
render.SetMaterial( matLight )
local ViewNormal = self:GetPos() - EyePos()
local Distance = ViewNormal:Length()
ViewNormal:Normalize()
local Visible = util.PixelVisible( LightPos, 4, self.PixVis )
if not Visible or Visible < 0.1 then return end
local c = self:GetMyColor()
if self:GetModel() == "models/maxofs2d/light_tubular.mdl" then
render.DrawSprite( LightPos - up * 2, 8, 8, Color(255, 255, 255, 255), Visible )
render.DrawSprite( LightPos - up * 4, 8, 8, Color(255, 255, 255, 255), Visible )
render.DrawSprite( LightPos - up * 6, 8, 8, Color(255, 255, 255, 255), Visible )
render.DrawSprite( LightPos - up * 5, 128, 128, c, Visible )
else
render.DrawSprite( self:LocalToWorld( self:OBBCenter() ), 128, 128, c, Visible )
end
end
local wire_light_block = CreateClientConVar("wire_light_block", 0, false, false)
function ENT:Think()
if self:GetGlow() and not wire_light_block:GetBool() then
local dlight = DynamicLight(self:EntIndex())
if dlight then
dlight.Pos = self:GetPos()
local c = self:GetMyColor()
dlight.r = c.r
dlight.g = c.g
dlight.b = c.b
dlight.Brightness = self:GetBrightness()
dlight.Decay = self:GetSize() * 5
dlight.Size = self:GetSize()
dlight.DieTime = CurTime() + 1
end
end
end
local color_box_size = 64
function ENT:GetWorldTipBodySize()
-- text
local w_total,h_total = surface.GetTextSize( "Color:\n255,255,255,255" )
-- Color box width
w_total = math.max(w_total,color_box_size)
-- Color box height
h_total = h_total + 18 + color_box_size + 18/2
return w_total, h_total
end
local white = Color(255,255,255,255)
local black = Color(0,0,0,255)
local function drawColorBox( color, x, y )
surface.SetDrawColor( color )
surface.DrawRect( x, y, color_box_size, color_box_size )
local size = color_box_size
surface.SetDrawColor( black )
surface.DrawLine( x, y, x + size, y )
surface.DrawLine( x + size, y, x + size, y + size )
surface.DrawLine( x + size, y + size, x, y + size )
surface.DrawLine( x, y + size, x, y )
end
function ENT:DrawWorldTipBody( pos )
-- get color
local color = self:GetMyColor()
-- text
local color_text = string.format("Color:\n%d,%d,%d",color.r,color.g,color.b)
local w,h = surface.GetTextSize( color_text )
draw.DrawText( color_text, "GModWorldtip", pos.center.x, pos.min.y + pos.edgesize, white, TEXT_ALIGN_CENTER )
-- color box
drawColorBox( color, pos.center.x - color_box_size / 2, pos.min.y + pos.edgesize * 1.5 + h )
end
return -- No more client
end
-- Server
function ENT:Initialize()
self:PhysicsInit( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
self.Inputs = WireLib.CreateInputs(self, {"Red", "Green", "Blue", "RGB [VECTOR]"})
end
function ENT:Directional( On )
if On then
if IsValid( self.DirectionalComponent ) then return end
local flashlight = ents.Create( "env_projectedtexture" )
flashlight:SetParent( self )
-- The local positions are the offsets from parent..
flashlight:SetLocalPos( Vector( 0, 0, 0 ) )
flashlight:SetLocalAngles( Angle( -90, 0, 0 ) )
if self:GetModel() == "models/maxofs2d/light_tubular.mdl" then
flashlight:SetLocalAngles( Angle( 90, 0, 0 ) )
end
-- Looks like only one flashlight can have shadows enabled!
flashlight:SetKeyValue( "enableshadows", 1 )
flashlight:SetKeyValue( "farz", 1024 )
flashlight:SetKeyValue( "nearz", 12 )
flashlight:SetKeyValue( "lightfov", 90 )
local c = self:GetColor()
local b = self.brightness
flashlight:SetKeyValue( "lightcolor", Format( "%i %i %i 255", c.r * b, c.g * b, c.b * b ) )
flashlight:Spawn()
flashlight:Input( "SpotlightTexture", NULL, NULL, "effects/flashlight001" )
self.DirectionalComponent = flashlight
elseif IsValid( self.DirectionalComponent ) then
self.DirectionalComponent:Remove()
self.DirectionalComponent = nil
end
end
function ENT:Radiant( On )
if On then
if IsValid( self.RadiantComponent ) then
self.RadiantComponent:Fire( "TurnOn", "", "0" )
else
local dynlight = ents.Create( "light_dynamic" )
dynlight:SetPos( self:GetPos() )
local dynlightpos = dynlight:GetPos() + Vector( 0, 0, 10 )
dynlight:SetPos( dynlightpos )
dynlight:SetKeyValue( "_light", Format( "%i %i %i 255", self.R, self.G, self.B ) )
dynlight:SetKeyValue( "style", 0 )
dynlight:SetKeyValue( "distance", 255 )
dynlight:SetKeyValue( "brightness", 5 )
dynlight:SetParent( self )
dynlight:Spawn()
self.RadiantComponent = dynlight
end
elseif IsValid( self.RadiantComponent ) then
self.RadiantComponent:Fire( "TurnOff", "", "0" )
end
end
function ENT:UpdateLight()
self:SetR( self.R )
self:SetG( self.G )
self:SetB( self.B )
if IsValid( self.DirectionalComponent ) then self.DirectionalComponent:SetKeyValue( "lightcolor", Format( "%i %i %i 255", self.R * self.brightness, self.G * self.brightness, self.B * self.brightness ) ) end
if IsValid( self.RadiantComponent ) then self.RadiantComponent:SetKeyValue( "_light", Format( "%i %i %i 255", self.R, self.G, self.B ) ) end
end
function ENT:TriggerInput(iname, value)
if (iname == "Red") then
self.R = math.Clamp(value,0,255)
elseif (iname == "Green") then
self.G = math.Clamp(value,0,255)
elseif (iname == "Blue") then
self.B = math.Clamp(value,0,255)
elseif (iname == "RGB") then
self.R, self.G, self.B = math.Clamp(value[1],0,255), math.Clamp(value[2],0,255), math.Clamp(value[3],0,255)
elseif (iname == "GlowBrightness") then
if not game.SinglePlayer() then value = math.Clamp( value, 0, 10 ) end
self.brightness = value
self:SetBrightness( value )
elseif (iname == "GlowSize") then
if not game.SinglePlayer() then value = math.Clamp( value, 0, 1024 ) end
self.size = value
self:SetSize( value )
end
self:UpdateLight()
end
function ENT:Setup(directional, radiant, glow, brightness, size, r, g, b)
self.directional = directional or false
self.radiant = radiant or false
self.glow = glow or false
self.brightness = brightness or 2
self.size = size or 256
self.R = r or 255
self.G = g or 255
self.B = b or 255
if not game.SinglePlayer() then
self.brightness = math.Clamp( self.brightness, 0, 10 )
self.size = math.Clamp( self.size, 0, 1024 )
end
self:Directional( self.directional )
self:Radiant( self.radiant )
self:SetGlow( self.glow )
self:SetBrightness( self.brightness )
self:SetSize( self.size )
if self.glow then
WireLib.AdjustInputs(self, {"Red", "Green", "Blue", "RGB [VECTOR]", "GlowBrightness", "GlowSize"})
else
WireLib.AdjustInputs(self, {"Red", "Green", "Blue", "RGB [VECTOR]"})
end
self:UpdateLight()
end
duplicator.RegisterEntityClass("gmod_wire_light", WireLib.MakeWireEnt, "Data", "directional", "radiant", "glow", "brightness", "size", "R", "G", "B")
| apache-2.0 |
rasata/cardpeek | dot_cardpeek_dir/scripts/vitale_2.lua | 17 | 5057 | --
-- This file is part of Cardpeek, the smartcard reader utility.
--
-- Copyright 2009-2013 by 'L1L1'
--
-- Cardpeek is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- Cardpeek is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with Cardpeek. If not, see <http://www.gnu.org/licenses/>.
--
-- @description The French health card (Version 2)
-- @targets 0.8
require('lib.tlv')
function ui_parse_asciidate(node,data)
local d = bytes.format(data,"%P")
local t = os.time( { ['year'] = string.sub(d,1,4),
['month'] = string.sub(d,5,6),
['day'] = string.sub(d,7,8) } )
nodes.set_attribute(node,"val",data)
nodes.set_attribute(node,"alt",os.date("%x",t))
return true
end
VITALE_IDO = {
['65'] = { "Bénéficiaire" },
['65/90'] = { "Nationalité", ui_parse_printable },
['65/93'] = { "Numéro de sécurité sociale", ui_parse_printable },
['65/80'] = { "Nom", ui_parse_printable },
['65/81'] = { "Prénom", ui_parse_printable },
['65/82'] = { "Date de naissance", ui_parse_asciidate },
['66'] = { "Carte vitale" },
['66/80'] = { "Date de début de validité", ui_parse_asciidate },
['7F21'] = { "Certificat" },
['5F37'] = { "Signature de l'AC" },
['5F38'] = { "Résidu de la clé publique" },
}
function read_bin()
local total, sw, resp, r
total = bytes.new(8)
r = 0
repeat
sw, resp = card.read_binary(".",r)
total = bytes.concat(total,resp)
r = r + 256
until #resp~=256 or sw~=0x9000
if #total>0 then
return 0x9000, total
end
return sw, total
end
AID_VITALE = "#D250000002564954414C45"
AID_VITALE_MF = "#D2500000024D465F564954414C45"
function create_card_map()
local resp, sw
local map = {}
local tag,val,rest
local tag2,val2,rest2
local entry, aid, file, name
sw,resp = card.select(AID_VITALE)
if sw~=0x9000 then
return nil
end
sw,resp = card.select(".2001")
if sw~=0x9000 then
return nil
end
sw,resp = read_bin()
if sw~=0x9000 then
return nil
end
tag,val = asn1.split(resp) -- E0,DATA,nil
tag,rest2,rest = asn1.split(val) -- A0,DATA,DATA
repeat
tag2,val2,rest2 = asn1.split(rest2)
if tag2==0x82 then
entry = tostring(bytes.sub(val2,0,1))
aid = "#"..tostring(bytes.sub(val2,4,-1))
map[entry]={ ['aid'] = aid, ['files'] = {} }
end
until rest2==nil or tag==0
repeat
tag,val,rest = asn1.split(rest)
if tag==0x80 then
entry = tostring(bytes.sub(val,8,9))
file = "."..tostring(bytes.sub(val,10,11))
name = bytes.format(bytes.sub(val,0,7),"%P")
table.insert(map[entry]['files'],{ ['name']=name, ['ef']=file })
end
until rest==nil or tag==0
for entry in pairs(map) do
if map[entry]['aid']==AID_VITALE_MF then
table.insert(map[entry]['files'],{ ['name']="DIR", ['ef']=".2F00" })
table.insert(map[entry]['files'],{ ['name']="PAN", ['ef']=".2F02" })
elseif map[entry]['aid']==AID_VITALE then
table.insert(map[entry]['files'],{ ['name']="POINTERS", ['ef']=".2001" })
end
end
return map
end
--[[
AID = {
"D2500000024D465F564954414C45",
"E828BD080FD2500000044164E86C65",
"D2500000044164E86C650101"
}
--]]
local header
if card.connect() then
CARD = card.tree_startup("VITALE 2")
map = create_card_map()
if map then
for app in pairs(map) do
sw,resp = card.select(map[app]['aid'])
if sw==0x9000 then
APP = CARD:append({ classname="application",
label="Application",
id=map[app]['aid'] })
header = APP:append({ classname="header", label="answer to select", size=#resp })
tlv_parse(header,resp)
end
for i in pairs(map[app]['files']) do
EF = APP:append({ classname="file",
label=map[app]['files'][i]['name'],
id=map[app]['files'][i]['ef'] })
sw,resp = card.select(map[app]['files'][i]['ef'])
header = EF:append({ classname="header", label="answer to select", size=#resp })
tlv_parse(header,resp)
if sw==0x9000 then
sw,resp = read_bin()
CONTENT = EF:append({ classname="body",
label="content",
size=#resp })
if sw==0x9000 then
if resp:get(0)==0 or (resp:get(0)==0x04 and resp:get(1)==0x00) then
nodes.set_attribute(CONTENT,"val",resp)
else
tlv_parse(CONTENT,resp,VITALE_IDO)
end
else
nodes.set_attribute(CONTENT,"alt",string.format("data not accessible (code %04X)",sw))
end
end
end
end
end
card.disconnect()
else
ui.question("No card detected",{"OK"})
end
| gpl-3.0 |
asmagill/hammerspoon_asm | iokit/examples/iokit.lua | 1 | 1739 | local module = {}
local iokit = require("hs._asm.iokit")
module.idleTime = function()
local hid = iokit.servicesForClass("IOHIDSystem")[1]
local idle = hid:properties().HIDIdleTime
if type(idle) == "string" then idle = string.unpack("J", idle) end
return idle >> 30
end
module.vramSize = function()
local results = {}
local pci = iokit.servicesForClass("IOPCIDevice")
for i,v in ipairs(pci) do
local ioname = v:searchForProperty("IOName")
if ioname and ioname == "display" then
local model = v:searchForProperty("model")
if model then
local inBytes = true
local vramSize = v:searchForProperty("VRAM,totalsize")
if not vramSize then
inBytes = false
vramSize = v:searchForProperty("VRAM,totalMB")
end
if vramSize then
if type(vramSize) == "string" then vramSize = string.unpack("J", vramSize) end
if inBytes then vramSize = vramSize >> 20 end
else
vramSize = -1
end
results[model] = vramSize
end
end
end
return results
end
module.attachedDevices = function()
local usb = iokit.servicesForClass("IOUSBDevice")
local results = {}
for i,v in ipairs(usb) do
local properties = v:properties()
table.insert(results, {
productName = properties["USB Product Name"],
vendorName = properties["USB Vendor Name"],
productID = properties["idProduct"],
vendorID = properties["idVendor"],
})
end
return results
end
return module
| mit |
wrxck/mattata | plugins/administration/trust.lua | 2 | 4129 | --[[
Copyright 2020 Matthew Hesketh <matthew@matthewhesketh.com>
This code is licensed under the MIT. See LICENSE for details.
]]
local trust = {}
local mattata = require('mattata')
local redis = require('libs.redis')
function trust:init()
trust.commands = mattata.commands(self.info.username):command('trust').table
trust.help = '/trust [user] - Promotes a user to a trusted user of the current chat. This command can only be used by administrators of a supergroup.'
end
function trust:on_message(message, configuration, language)
if message.chat.type ~= 'supergroup'
then
return mattata.send_reply(
message,
language['errors']['supergroup']
)
elseif not mattata.is_group_admin(
message.chat.id,
message.from.id,
true
)
then
return mattata.send_reply(
message,
language['errors']['admin']
)
end
local input = message.reply
and tostring(message.reply.from.id)
or mattata.input(message)
if not input
then
return mattata.send_reply(
message,
trust.help
)
end
if tonumber(input) == nil
and not input:match('^%@')
then
input = '@' .. input
end
local user = mattata.get_user(input)
or mattata.get_chat(input) -- Resolve the username/ID to a user object.
if not user
then
return mattata.send_reply(
message,
language['errors']['unknown']
)
elseif user.result.id == self.info.id
then
return
end
user = user.result
local status = mattata.get_chat_member(
message.chat.id,
user.id
)
if not status
then
return mattata.send_reply(
message,
language['errors']['generic']
)
elseif mattata.is_group_admin(
message.chat.id,
user.id
)
or status.result.status == 'creator'
or status.result.status == 'administrator'
then -- We won't try and trust moderators and administrators.
return mattata.send_reply(
message,
language['trust']['1']
)
elseif status.result.status == 'left'
or status.result.status == 'kicked'
then -- Check if the user is in the group or not.
return mattata.send_reply(
message,
status.result.status == 'left'
and language['trust']['2']
or language['trust']['3']
)
end
redis:sadd(
'administration:' .. message.chat.id .. ':trusted',
user.id
)
if redis:hget(
string.format(
'chat:%s:settings',
message.chat.id
),
'log administrative actions'
)
then
mattata.send_message(
mattata.get_log_chat(message.chat.id),
string.format(
'<pre>%s%s [%s] has trusted %s%s [%s] in %s%s [%s].</pre>',
message.from.username
and '@'
or '',
message.from.username
or mattata.escape_html(message.from.first_name),
message.from.id,
user.username
and '@'
or '',
user.username
or mattata.escape_html(user.first_name),
user.id,
message.chat.username
and '@'
or '',
message.chat.username
or mattata.escape_html(message.chat.title),
message.chat.id
),
'html'
)
end
return mattata.send_message(
message.chat.id,
string.format(
'<pre>%s%s has trusted %s%s.</pre>',
message.from.username
and '@'
or '',
message.from.username
or mattata.escape_html(message.from.first_name),
user.username
and '@'
or '',
user.username
or mattata.escape_html(user.first_name)
),
'html'
)
end
return trust | mit |
arventwei/WioEngine | Tools/jamplus/src/luaplus/Src/Modules/socket/src/ltn12.lua | 71 | 8331 | -----------------------------------------------------------------------------
-- LTN12 - Filters, sources, sinks and pumps.
-- LuaSocket toolkit.
-- Author: Diego Nehab
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-- Declare module
-----------------------------------------------------------------------------
local string = require("string")
local table = require("table")
local base = _G
local _M = {}
if module then -- heuristic for exporting a global package table
ltn12 = _M
end
local filter,source,sink,pump = {},{},{},{}
_M.filter = filter
_M.source = source
_M.sink = sink
_M.pump = pump
-- 2048 seems to be better in windows...
_M.BLOCKSIZE = 2048
_M._VERSION = "LTN12 1.0.3"
-----------------------------------------------------------------------------
-- Filter stuff
-----------------------------------------------------------------------------
-- returns a high level filter that cycles a low-level filter
function filter.cycle(low, ctx, extra)
base.assert(low)
return function(chunk)
local ret
ret, ctx = low(ctx, chunk, extra)
return ret
end
end
-- chains a bunch of filters together
-- (thanks to Wim Couwenberg)
function filter.chain(...)
local arg = {...}
local n = select('#',...)
local top, index = 1, 1
local retry = ""
return function(chunk)
retry = chunk and retry
while true do
if index == top then
chunk = arg[index](chunk)
if chunk == "" or top == n then return chunk
elseif chunk then index = index + 1
else
top = top+1
index = top
end
else
chunk = arg[index](chunk or "")
if chunk == "" then
index = index - 1
chunk = retry
elseif chunk then
if index == n then return chunk
else index = index + 1 end
else base.error("filter returned inappropriate nil") end
end
end
end
end
-----------------------------------------------------------------------------
-- Source stuff
-----------------------------------------------------------------------------
-- create an empty source
local function empty()
return nil
end
function source.empty()
return empty
end
-- returns a source that just outputs an error
function source.error(err)
return function()
return nil, err
end
end
-- creates a file source
function source.file(handle, io_err)
if handle then
return function()
local chunk = handle:read(_M.BLOCKSIZE)
if not chunk then handle:close() end
return chunk
end
else return source.error(io_err or "unable to open file") end
end
-- turns a fancy source into a simple source
function source.simplify(src)
base.assert(src)
return function()
local chunk, err_or_new = src()
src = err_or_new or src
if not chunk then return nil, err_or_new
else return chunk end
end
end
-- creates string source
function source.string(s)
if s then
local i = 1
return function()
local chunk = string.sub(s, i, i+_M.BLOCKSIZE-1)
i = i + _M.BLOCKSIZE
if chunk ~= "" then return chunk
else return nil end
end
else return source.empty() end
end
-- creates rewindable source
function source.rewind(src)
base.assert(src)
local t = {}
return function(chunk)
if not chunk then
chunk = table.remove(t)
if not chunk then return src()
else return chunk end
else
table.insert(t, chunk)
end
end
end
function source.chain(src, f)
base.assert(src and f)
local last_in, last_out = "", ""
local state = "feeding"
local err
return function()
if not last_out then
base.error('source is empty!', 2)
end
while true do
if state == "feeding" then
last_in, err = src()
if err then return nil, err end
last_out = f(last_in)
if not last_out then
if last_in then
base.error('filter returned inappropriate nil')
else
return nil
end
elseif last_out ~= "" then
state = "eating"
if last_in then last_in = "" end
return last_out
end
else
last_out = f(last_in)
if last_out == "" then
if last_in == "" then
state = "feeding"
else
base.error('filter returned ""')
end
elseif not last_out then
if last_in then
base.error('filter returned inappropriate nil')
else
return nil
end
else
return last_out
end
end
end
end
end
-- creates a source that produces contents of several sources, one after the
-- other, as if they were concatenated
-- (thanks to Wim Couwenberg)
function source.cat(...)
local arg = {...}
local src = table.remove(arg, 1)
return function()
while src do
local chunk, err = src()
if chunk then return chunk end
if err then return nil, err end
src = table.remove(arg, 1)
end
end
end
-----------------------------------------------------------------------------
-- Sink stuff
-----------------------------------------------------------------------------
-- creates a sink that stores into a table
function sink.table(t)
t = t or {}
local f = function(chunk, err)
if chunk then table.insert(t, chunk) end
return 1
end
return f, t
end
-- turns a fancy sink into a simple sink
function sink.simplify(snk)
base.assert(snk)
return function(chunk, err)
local ret, err_or_new = snk(chunk, err)
if not ret then return nil, err_or_new end
snk = err_or_new or snk
return 1
end
end
-- creates a file sink
function sink.file(handle, io_err)
if handle then
return function(chunk, err)
if not chunk then
handle:close()
return 1
else return handle:write(chunk) end
end
else return sink.error(io_err or "unable to open file") end
end
-- creates a sink that discards data
local function null()
return 1
end
function sink.null()
return null
end
-- creates a sink that just returns an error
function sink.error(err)
return function()
return nil, err
end
end
-- chains a sink with a filter
function sink.chain(f, snk)
base.assert(f and snk)
return function(chunk, err)
if chunk ~= "" then
local filtered = f(chunk)
local done = chunk and ""
while true do
local ret, snkerr = snk(filtered, err)
if not ret then return nil, snkerr end
if filtered == done then return 1 end
filtered = f(done)
end
else return 1 end
end
end
-----------------------------------------------------------------------------
-- Pump stuff
-----------------------------------------------------------------------------
-- pumps one chunk from the source to the sink
function pump.step(src, snk)
local chunk, src_err = src()
local ret, snk_err = snk(chunk, src_err)
if chunk and ret then return 1
else return nil, src_err or snk_err end
end
-- pumps all data from a source to a sink, using a step function
function pump.all(src, snk, step)
base.assert(src and snk)
step = step or pump.step
while true do
local ret, err = step(src, snk)
if not ret then
if err then return nil, err
else return 1 end
end
end
end
return _M
| mit |
dschoeffm/MoonGen | examples/netronome-packetgen/packetgen.lua | 4 | 59878 | --[[
Copyright (C) 2016 Netronome Systems, Inc. All rights reserved.
Description : Generates a bursty traffic pattern using the rules specified
below.
-- All packets generated will share the same source IP, source MAC and size
profile (fixed or IMIX).
-- The destination IP and MAC are selected sequentially in the following
pattern:
a) The stream number is set to 0.
b) The stream base is calculated by multiplying the stream number with the
MAC and IP stride.
c) The burst number is set to 0.
d) The flow number is set to 0.
e) A packet is generated with the destination IP and MAC set to "stream
base" + "flow number".
f) The flow number is increased, if it is less than the number of flows per
stream, loop back to (e), else continue to (g).
g) The burst number is increased, if it is less than the number of bursts
per stream, loop back to (d), else continue to (h).
h) The stream base is incremented, if it is less than the number of streams,
loop back to (a).
-- This results in a set of streams that are separated by the MAC and IP
stride and repeat in bursts. The destination IP and MAC increase in
lock-step.
-- Packet size can be constant, or selected from a 7:4:1 IMIX profile with
packet sizes 1514, 570, and 64, respectively.
--]]
local libmoon = require "libmoon"
local mg = require "moongen"
local moongen = require "dpdk"
local dpdkc = require "dpdkc"
local memory = require "memory"
local device = require "device"
local ffi = require "ffi"
local log = require "log"
local bit = require "bit"
local lshift , rshift , band , bswap , bor , ror =
bit.lshift, bit.rshift, bit.band, bit.bswap , bit.bor, bit.ror
-------------------------------------------------------------------------------
-- Table for RX stats:
--
-- bytes : Total number of bytes received.
-- prevBytes : Number of bytes received at the previous iteration.
-- packets : Total number of packets received.
-- prevPackets : Number of packets received at the previous iteration.
-- dropped : Number of received packets which have been dropped.
-- tstampPackets : Number of received packets with a timestamp.
-- meanLatency : Mean latency of received packets with timestamps.
-- elapsedTime : Time elapsed since the start of the run.
-- deltaTime : Time since the last iteration.
-------------------------------------------------------------------------------
local statsRx = {
bytes = 0,
prevBytes = 0,
packets = 0,
prevPackets = 0,
dropped = 0,
tstampPackets = 0,
meanLatency = 0,
elapsedTime = 0,
deltaTime = 0
}
-------------------------------------------------------------------------------
-- Table for TX stats:
--
-- bytes : Total number of bytes sent.
-- prevBytes : Number of bytes sent at the previous iteration.
-- packets : Total number of packets sent.
-- prevPackets : Number of packets sent at the previous iteration.
-- bursts : Number of bursts sent.
-- short : Number of generated by not sent packets.
-- elapsedTime : Time elapsed since the start of the run.
-- deltaTime : Time since the last iteration.
--------------------------------------------------------------------------------
local statsTx = {
bytes = 0,
prevBytes = 0,
packets = 0,
prevPackets = 0,
bursts = 0,
short = 0,
elapsedTime = 0,
deltaTime = 0
}
-------------------------------------------------------------------------------
-- Table for command line configuration parameters, the following are options:
--
-- rxSlavePorts : Ports to use for the RX slaves.
-- txSlavePorts : Ports to use for the TX slaves.
-- rxDescs : Number of RX descriptors.
-- txDescs : Number of TX descriptors.
-- numberOfStreams : Number of streams to create.
-- flowsPerStream : The number of flows in each of the streams.
-- burstsPerStream : The number of bursts to send for each stream.
-- totalFlows : The totla number of flows to generate.
-- paramDisplay : The number of milliseconds to display the parameters for.
-- statsDisplay : The amount of time between each device stats display.
-- txDelta : Amount of time to pass before sending a burst.
-- packetSize : The size of each packet, in bytes.
-- mustImix : If IMIXing must be used to determine packet sizes.
-- iterations : Number of iterations to run for.
-- timeout : Number of seconds to run for.
-- fileprefix : The prefix of the file to write to.
-- writemode : Write mode: 0-off, 1-print, 1-globalfile, 2-percorefile
-- rest : Parameters used to generate the traffic pattern.
-------------------------------------------------------------------------------
local clParams = {
rxSlavePorts = {} ,
txSlavePorts = {} ,
rxDescs = 1024 ,
txDescs = 1024 ,
numberOfStreams = 1 ,
flowsPerStream = 2047 ,
burstsPerStream = 1 ,
totalFlows = 0 ,
paramDisplay = 3000 ,
statsDisplay = 1000 ,
txDelta = 0 ,
packetSize = 64 ,
mustImix = false ,
iterations = 0 ,
timeout = 0 ,
fileprefix = "" ,
writemode = 1 ,
srcMacBase = 0x021100000000 ,
dstMacBase = 0x022200000000 ,
srcIpBase = 3232238337 ,
dstIpBase = 3232241153 ,
srcPortBase = 50110 ,
dstPortBase = 50220 ,
srcPortVary = 1 ,
dstPortVary = 0 ,
srcIpVary = 0 ,
dstIpVary = 1 ,
srcMacVary = 0 ,
dstMacVary = 1 ,
srcPortStride = 0 ,
dstPortStride = 0 ,
srcIpStride = 0 ,
dstIpStride = 0 ,
srcMacStride = 0 ,
dstMacStride = 0
}
-------------------------------------------------------------------------------
-- Defines parameters for timing functionality.
--
-- prevtsc : The previous clock count.
-- currtsc : The current clock count.
-- difftsc : The difference between the clock counts.
-------------------------------------------------------------------------------
local timeParams = {
prevtsc = 0 ,
currtsc = 0 ,
difftsc = 0
}
-------------------------------------------------------------------------------
-- Table for constants:
--
-- maxSlavePort : Maximum port number a slave may use.
-- maxSlaves : Maximum number of total slaves (limited by cores).
-- maxFlowsPerStream : Maximum number of flows per stream.
-- maxPacketSize : Maximum size of a packet.
-- rxBurstSize : The size of each of the RX burst.
-- txBurstSize : The size of each of the TX bursts.
-- receiveTimeout : Time to try receive for (ms)
-- ethHeaderLength : Number of bytes in ethernet header.
-- ipHeaderLength : Number of bytes in ip header.
-- udpHeaderLength : Number of bytes in udp header
-- ethTypeIpv4 : Type code for ethernet ipv4.
-- printTimePassPcnt : % of print time which must pass since last print.
-- defaultPayload : Default payload to use for packets.
-------------------------------------------------------------------------------
constants = {
maxSlavePort = 32 ,
maxSlaves = 32 ,
maxFlowsPerStream = 2047 ,
maxPacketSize = 64 ,
maxPacketSize = 1522 ,
rxBurstSize = 128 ,
txBurstSize = 32 ,
receiveTimeout = 100 ,
ethHeaderLength = 14 ,
ipHeaderLength = 20 ,
udpHeaderLength = 8 ,
ethTypeIpv4 = 0x0800,
printTimePassPcnt = 0.8 ,
defaultPayload = "\x01\x02 MoonGen Payload"
}
-- Start time of the appliction. This is used to sync
-- the printing and logging accross the slaves.
local globalStartTime = mg.getTime()
-------------------------------------------------------------------------------
-- Master function to do the slave setup and invoke the slave instances.
-------------------------------------------------------------------------------
function master(...)
local continue = parseArgs(clParams, ...)
if continue == false then
os.exit()
end
local totalSlaves = #clParams.rxSlavePorts + #clParams.txSlavePorts
if totalSlaves == 0 then
print("No slaves requested. Packetgen will now exit.")
os.exit()
end
if totalSlaves > constants.maxSlaves then
print(string.format("Too many slaves requested:\n %u requested, " ..
"%u maximum.\n Packetgen will now exit.",
totalSlaves, constants.maxSlaves)
)
end
-- Create a list of ports, default to the tx ports:
local portList = deepCopy(clParams.txSlavePorts)
-- Check which of the rx ports were already added as tx ports,
-- and add any of the rx ports which are not already in the list:
for i, rxPortId in ipairs(clParams.rxSlavePorts) do
local canAdd = true
for _, portId in ipairs(portList) do
if rxPortId == portId then
canAdd = false
break
end
end
if canAdd then
portList[#portList + 1] = rxPortId
end
end
-- Table of MoonGen devices:
local devices = {}
-- Configure the devices:
for _, port in ipairs(portList) do
local deviceIdx = #devices + 1
devices[deviceIdx] = device.config{
port = port ,
rxQueues = 1 , -- Only 1 supported for now.
txQueues = 1 , -- Only 1 supported for now.
rxDescs = clParams.rxDescs,
txDescs = clParams.txDescs
}
end
-- If writing globally, write the header for the global file:
if clParams.writemode == 2 then
writeStatsHeader(clParams.fileprefix .. ".txt")
end
-- Display the parameters:
clParams:print()
mg.sleepMillis(clParams.paramDisplay)
local slaveId = 0
-- Launch the slaves:
for i, portId in ipairs(portList) do
-- Check if the port must be used as a TX slave:
for _, txPortId in ipairs(clParams.txSlavePorts) do
if txPortId == portId then
libmoon.startTask("txSlave", devices[i], portId, slaveId, clParams)
slaveId = slaveId + 1
break
end
end
-- Check if the port must be used as a RX slave:
for _, rxPortId in ipairs(clParams.rxSlavePorts) do
if rxPortId == portId then
libmoon.startTask("rxSlave", devices[i], portId, slaveId, clParams)
slaveId = slaveId + 1
break
end
end
end
mg.waitForTasks()
end
---- RX Functionality ---------------------------------------------------------
-------------------------------------------------------------------------------
-- Slave function to perform RX.
-- device : The MoonGen device to sent the packets from.
-- portId : The port the device is configured to use.
-- slaveId : The identifier (index) of the slave.
-- clParams : The command line parameters.
-------------------------------------------------------------------------------
function rxSlave(device, portId, slaveId, clParams)
print(string.format("Launching RX slave: %u, Core: %u, Port: %u", slaveId, mg:getCore(), portId))
-- Variables for receiving:
local rxPackets = 0
local rxQueue = device:getRxQueue(0)
local rxBurst = memory.bufArray(constants.rxBurstSize)
local latency = 0
local latDelta = 0
-- Variables for logging, printing, stopping:
local state = "canrun"
local stats = deepCopy(statsRx)
local startTime = mg.getTime()
local lastPrintTime = 0
local iteration = 0
-- Create the filename of the file to write to.
if clParams.writemode == 2 then
outFile = clParams.fileprefix .. ".txt"
elseif clParams.writemode == 3 then
-- Prer core mode - create file and write header:
outFile = clParams.fileprefix ..
"-c" .. tostring(mg:getCore()) ..
"-p" .. tostring(portId) .. ".txt";
writeStatsHeader(outFile)
end
while state == "canrun" and mg.running() do
rxPackets = rxQueue:tryRecv(rxBurst, constants.receiveTimeout)
stats.packets = stats.packets + rxPackets
stats.dropped = stats.dropped + rxPackets
for i = 1, rxPackets do
stats.bytes = stats.bytes + rxBurst[i].pkt_len
latency = calculateLatency(rxBurst[i])
if latency ~= 0 then
stats.tstampPackets = stats.tstampPackets + 1
latDelta = latency - stats.meanLatency
stats.meanLatency = stats.meanLatency +
(latDelta / stats.tstampPackets)
end
end
simpleDrop(rxBurst)
-- Update termination params:
iteration = iteration + 1
stats.deltaTime = (mg.getTime() - startTime) - stats.elapsedTime
stats.elapsedTime = mg.getTime() - startTime
-- If printing or logging must be done:
if clParams.writemode > 0 then
-- To make sure that enough time has passed since logging
-- and printing was done for the core.
sufficientTimeSincePrint =
(stats.elapsedTime - lastPrintTime) >=
(constants.printTimePassPcnt * clParams.statsDisplay / 1000)
-- Printing and logging:
if canPrint(slaveId, clParams) and sufficientTimeSincePrint then
lastPrintTime = mg.getTime() - startTime
if clParams.writemode == 1 then
os.execute("clear")
stats:print(portId)
else
stats:write(outFile, portId)
end
end
end
-- Update stats:
stats.prevPackets = stats.packets
stats.prevBytes = stats.bytes
-- Check for exit conditions:
if clParams.iterations ~= 0 and iteration >= clParams.iterations then
state = "stop"
elseif clParams.timeout ~= 0 and
stats.elapsedTime >= clParams.timeout then
state = "stop"
end
end
if clParams.writemode == 0 then
stats:print(portId)
end
end
-------------------------------------------------------------------------------
-- Drops the received packets
-- rxPackets : The received packets to drop.
-------------------------------------------------------------------------------
function simpleDrop(rxPackets)
rxPackets:freeAll()
end
-------------------------------------------------------------------------------
-- Gets the timestamp from a packet and then calculates the latency
-- buf : The buffer to get the timestamp from and then calculate the latency.
-------------------------------------------------------------------------------
function calculateLatency(buf)
local pkt = buf:getUdpPacket()
local cycles = tonumber(mg:getCycles())
local timestamp = tonumber(pkt.payload.uint64[0])
local latency = 0
if timestamp ~= 0 then
latency = tonumber(cycles - timestamp)
/ tonumber(mg:getCyclesFrequency())
end
return latency
end
-------------------------------------------------------------------------------
-- Prints RX stats
-- portId : The id of the port to print the stats for
-------------------------------------------------------------------------------
function statsRx:print(portId)
local statsString = string.format(
"\n+------ RX Statistics for core %3u, port %3u -------------------+" ..
"\n| Packets received : %32u |" ..
"\n| Packet receive rate : %32.2f |" ..
"\n| Avg packet receive rate : %32.2f |" ..
"\n| Bytes received : %32u |" ..
"\n| Byte receive rate : %32.2f |" ..
"\n| Avg byte receive rate : %32.2f |" ..
"\n| Packets dropped on receive : %32u |" ..
"\n| RX mean latency : %32.10f |" ..
"\n+---------------------------------------------------------------+" ,
mg:getCore() ,
portId ,
self.packets ,
(self.packets - self.prevPackets) / self.deltaTime ,
self.packets / self.elapsedTime ,
self.bytes ,
(self.bytes - self.prevBytes) / self.deltaTime ,
self.bytes / self.elapsedTime ,
self.dropped ,
self.meanLatency
)
print(statsString)
end
-------------------------------------------------------------------------------
-- Writes RX a stats entry to a file. The row entry contains the following
-- fields:
-- Time, tx packets, tx packet rate, avg tx packet rate, rx packets,
-- rx packet rate, avg rx packet rate, core, port
--
-- filename : Name of the file to write to.
-- portId : The port the stats are being written for.
-------------------------------------------------------------------------------
function statsRx:write(filename, portId)
file = io.open(filename, "a")
local time = mg.getTime() - globalStartTime
local statsString = string.format(
"%6.3f,%13u,%18.2f,%18.2f,%13u,%18.2f,%18.2f,%5u,%5u\n",
time ,
0 ,
0 ,
0 ,
self.packets ,
(self.packets - self.prevPackets) / self.deltaTime ,
self.packets / self.elapsedTime ,
mg:getCore() ,
portId
)
file:write(statsString)
file:close()
end
---- TX Functionality ---------------------------------------------------------
-------------------------------------------------------------------------------
-- Slave function to perform TX.
-- device : The MoonGen device to sent the packets from.
-- portId : The port the device is configures to use.
-- slaveId : The identifier (index) of the slave.
-- clParams : The command line parameters
-------------------------------------------------------------------------------
function txSlave(device, portId, slaveId, clParams)
print(string.format("Launching TX slave: %u, Core: %u, Port: %u",
slaveId, mg:getCore(), portId))
local state = "canrun"
local stats = deepCopy(statsTx)
local txQueue = device:getTxQueue(0)
local timerParams = deepCopy(timeParams)
local outFile = ""
-- Create the filename of the file to write to.
if clParams.writemode == 2 then
outFile = clParams.fileprefix .. ".txt"
elseif clParams.writemode == 3 then
-- Per core mode: write header
outFile = clParams.fileprefix ..
"-c" .. tostring(mg:getCore()) ..
"-p" .. tostring(portId) .. ".txt";
writeStatsHeader(outFile)
end
-- Allocate memory for all the streams. Each of the streams can have
-- a maximum of 2047 flows due to mbuf allocation limits.
local streams = {}
for i = 1, clParams.numberOfStreams do
streams[i] = {
mempool = {},
bufArray = nil
}
-- Create a mempool for the stream:
streams[i].mempool = memory:createMemPool(
function(buf)
buf:getUdpPacket():fill{
pktLength = clParams.packetSize - 4,
ethLength = constants.ethHeaderLength
}
end
)
-- Allocate buffers from the mempool:
streams[i].bufArray = streams[i].mempool:bufArray(clParams.flowsPerStream)
end
local counter = 0
-- Modify all the packets so that their data follows the traffic pattern:
for streamid, stream in ipairs(streams) do
-- Subtraction of 4 is for the FCS
local maxPacketSize = clParams.packetSize - 4
if clParams.mustImix then
maxPacketSize = constants.maxPacketSize - 4
end
-- Allocate buffers using the max possible packet size. If using Imix
-- then each of the sent packets will vary in size, despite the constant
-- size allocation done here.
stream.bufArray:alloc(maxPacketSize)
-- Modify the packets:
for flowid, buf in ipairs(stream.bufArray) do
if clParams.mustImix then
local pktSize = imixSize() - 4
buf.pkt_len = pktSize
buf.data_len = pktSize
end
buildTxFrame(device.id, buf, streamid - 1, flowid - 1, clParams)
end
-- Offload the checksum to the NIC:
stream.bufArray:offloadUdpChecksums()
end
-- Do sending:
local iteration = 0
local lastPrintTime = 0
local startTime = mg.getTime()
while state == "canrun" and mg.running() do
for _, stream in ipairs(streams) do
timerParams.currtsc = tonumber(mg:getCycles())
timerParams.difftsc = timerParams.currtsc - timerParams.prevtsc
sendBursts(txQueue, stats, timerParams, clParams, stream)
end
-- Update the iteration and timeout params:
iteration = iteration + 1
stats.deltaTime = (mg.getTime() - startTime) - stats.elapsedTime
stats.elapsedTime = mg.getTime() - startTime
-- Printing and writing:
if clParams.writemode > 0 then
-- To make sure that enough time has passed since logging
-- and printing was done for the core.
sufficientTimeSincePrint =
((stats.elapsedTime - lastPrintTime) >=
(constants.printTimePassPcnt * clParams.statsDisplay / 1000))
-- Printing and logging:
if canPrint(slaveId, clParams) and sufficientTimeSincePrint then
lastPrintTime = mg.getTime() - startTime
if clParams.writemode == 1 then
os.execute("clear")
stats:print(portId)
else
stats:write(outFile, portId)
end
end
end
-- Update stats:
stats.prevPackets = stats.packets
stats.prevBytes = stats.bytes
-- Check for exit conditions:
if clParams.iterations ~= 0 and iteration >= clParams.iterations then
state = "stop"
elseif clParams.timeout ~= 0 and
stats.elapsedTime >= clParams.timeout then
state = "stop"
end
end
if clParams.writemode == 0 then
stats:print(portId)
end
end
-------------------------------------------------------------------------------
-- Builds a frame for TX.
-- portId : The port of the device to build the frame for.
-- buf : The buffer for the packet holding the frame.
-- streamid : The id of the stream for the frame.
-- flowid : The id of the flow for the frame.
-- clParams : The command line parameters.
-------------------------------------------------------------------------------
function buildTxFrame(portId, buf, streamid, flowid, clParams)
local srcMac = clParams.srcMacBase + (streamid * clParams.srcMacStride)
+ (flowid * clParams.srcMacVary)
local dstMac = clParams.dstMacBase + (streamid * clParams.dstMacStride)
+ (flowid * clParams.dstMacVary)
local srcIp = clParams.srcIpBase + (streamid * clParams.srcIpStride)
+ (flowid * clParams.srcIpVary)
local dstIp = clParams.dstIpBase + (streamid * clParams.dstIpStride)
+ (flowid * clParams.dstIpVary)
local srcPort = band(clParams.srcPortBase
+ (streamid * clParams.srcPortStride)
+ (flowid * clParams.srcPortVary),
0xffff)
local dstPort = band(clParams.dstPortBase
+ (streamid * clParams.dstPortStride)
+ (flowid * clParams.dstPortVary),
0xffff)
local srcMacFlipped = rshift(bswap(srcMac + 0ULL), 16)
local dstmacFlipped = rshift(bswap(dstMac + 0ULL), 16)
local frameSize = buf.pkt_len
local ethLength = constants.ethHeaderLength
local ipLength = frameSize - ethLength
local udpLength = ipLength - constants.ipHeaderLength
local pkt = buf:getUdpPacket()
-- ETH mod:
pkt.eth:setType(constants.ethTypeIpv4)
pkt.eth:setSrc(srcMacFlipped)
pkt.eth:setDst(dstmacFlipped)
-- IP mod:
pkt.ip4:setLength(ipLength)
pkt.ip4:setHeaderLength(5) -- Number of 32 bit words : use min value.
pkt.ip4:setProtocol(17)
pkt.ip4:setTTL(64)
pkt.ip4:setSrc(srcIp)
pkt.ip4:setDst(dstIp)
pkt.ip4:setVersion(4)
-- UDP mod:
pkt.udp:setLength(udpLength)
pkt.udp:setSrcPort(srcPort)
pkt.udp:setDstPort(dstPort)
-- Start of payload looks as follows:
--
-- | Byte 0 | Byte 4 | Byte 8 | Byte 12 |
-- ----------------------------------------------
-- | timestamp | flowid | streamid |
-- ----------------------------------------------
--
-- The timestamp is alredy set, so set flow and stream id.
pkt.payload.uint32[2] = flowid
pkt.payload.uint32[3] = streamid
-- Fill the rest of the payload
local payLength = udpLength - constants.udpHeaderLength
local i = 16 -- tstamp, flowid, streamid = 16 bytes
local offset = i -- Start offset into payload bytes
-- Copy the default payload into the packet.
while i < payLength do
-- NOTE: (i - offset) is to remove the 16 byte initial offset.
pkt.payload.uint8[i] =
string.byte(constants.defaultPayload, i - offset + 1) or 0
i = i + 1
end
end
-------------------------------------------------------------------------------
-- Generates and sends a burst if enough time has passed to achieve the desired
-- packet rate, otherwise nothing happens.
-- txQueue : The queue to send the burst on.
-- stats : The stats to update.
-- timerParams : The parameters for the burst to send.
-- clParams : The command line parameters.
-- stream : The stream to send.
-------------------------------------------------------------------------------
function sendBursts(txQueue, stats , timerParams, clParams, stream)
-- If enough time has passed to achieve the requested rate.
if timerParams.difftsc > clParams.txDelta then
local nbtx = 0
for i = 1, clParams.burstsPerStream do
stats.bursts = stats.bursts + 1
for _, buf in ipairs(stream.bufArray) do
updateTimestamp(buf)
end
nbtx = nbtx + txQueue:send(stream.bufArray)
end
stats.packets = stats.packets + nbtx
for _, buf in ipairs(stream.bufArray) do
-- Add four for the FCS.
stats.bytes = 4 + stats.bytes +
(clParams.burstsPerStream * buf.pkt_len)
end
if nbtx < constants.txBurstSize then
stats.short = stats.short + 1
end
timerParams.prevtsc = timerParams.currtsc
end
end
-------------------------------------------------------------------------------
-- Updates the timestamp for a packet. The first 8 bytes of the packet payload
-- are used for the timestamp.
-- buf : The buffer to update the timestamp of.
-------------------------------------------------------------------------------
function updateTimestamp(buf)
local pkt = buf:getUdpPacket()
local cycles = mg:getCycles()
pkt.payload.uint64[0] = cycles
end
-------------------------------------------------------------------------------
-- Prints TX stats
-- portId : The id of the port to print the stats for
-------------------------------------------------------------------------------
function statsTx:print(portId)
local statsString = string.format(
"\n+------ TX Statistics for core %3u, port %3u -------------------+" ..
"\n| Packets sent : %32u |" ..
"\n| Packet send rate : %32.2f |" ..
"\n| Avg packet send rate : %32.2f |" ..
"\n| Bytes sent : %32u |" ..
"\n| Byte send rate : %32.2f |" ..
"\n| Avg byte send rate : %32.2f |" ..
"\n| Packets short : %32u |" ..
"\n| Bursts : %32u |" ..
"\n+---------------------------------------------------------------+" ,
mg:getCore() ,
portId ,
self.packets ,
(self.packets - self.prevPackets) / self.deltaTime ,
self.packets / self.elapsedTime ,
self.bytes ,
(self.bytes - self.prevBytes) / self.deltaTime ,
self.bytes / self.elapsedTime ,
self.short ,
self.bursts
)
print(statsString)
end
-------------------------------------------------------------------------------
-- Writes TX a stats entry to a file. The row entry contains the following
-- fields:
-- Time, tx packets, tx packet rate, avg tx packet rate, rx packets,
-- rx packet rate, avg rx packet rate, core, port
--
-- filename : Name of the file to write to.
-- portId : The port the stats are being written for.
-------------------------------------------------------------------------------
function statsTx:write(filename, portId)
file = io.open(filename, "a")
local time = mg.getTime() - globalStartTime
local statsString = string.format(
"%6.3f,%13u,%18.2f,%18.2f,%13u,%18.2f,%18.2f,%5u,%5u\n",
time,
self.packets ,
(self.packets - self.prevPackets) / self.deltaTime ,
self.packets / self.elapsedTime ,
0 ,
0 ,
0 ,
mg:getCore() ,
portId
)
file:write(statsString)
file:close()
end
---- Utility Functions --------------------------------------------------------
-------------------------------------------------------------------------------
-- Write the header for a stats file.
-- filename : The name of the file to write the headerto.
-------------------------------------------------------------------------------
function writeStatsHeader(filename)
file = io.open(filename, "a")
local headerString = string.format(
"%6s %13s %18s %18s %13s %18s %18s %5s %5s\n",
"Time",
"TX Packets",
"TX Packet Rate" ,
"Avg TX Packet Rate",
"RX Packets" ,
"RX Packet Rate" ,
"Avg RX Packet Rate",
"Core" ,
"Port"
)
file:write(headerString)
file:close()
end
-------------------------------------------------------------------------------
-- Determines if a core is allowed to print it's stats.
-- slaveId : Identifier for the slave requesting to print.
-- clParams : The command line parameters
-------------------------------------------------------------------------------
function canPrint(slaveId, clParams)
local elapsedTime = mg.getTime() - globalStartTime
local timePerCore = clParams.statsDisplay /
(#clParams.rxSlavePorts + #clParams.txSlavePorts)
local timeMod = math.floor(
math.fmod(elapsedTime * 1000, clParams.statsDisplay))
return timeMod == math.floor(timePerCore * slaveId)
end
-------------------------------------------------------------------------------
-- Prints the command line arguments.
-------------------------------------------------------------------------------
function clParams:print()
local paramString = string.format(
"\n+-------- Parameters ---------------------------------+" ..
"\n| RX Slaves : %30u |" ..
"\n| TX Slaves : %30u |" ..
"\n| RX Descs : %30u |" ..
"\n| TX Descs : %30u |" ..
"\n| Param display (s) : %30.3f |" ..
"\n| Stat display (s) : %30.3f |" ..
"\n| Number of streams : %30u |" ..
"\n| Bursts per stream : %30u |" ..
"\n| Flows per stream : %30u |" ..
"\n| Total flows : %30u |" ..
"\n| Iterations : %30u |" ..
"\n| Timeout : %30u |" ..
"\n| Packet size : %30u |" ..
"\n| Using Imix size : %30s |" ..
"\n| File prefix : %30s |" ..
"\n| Write mode : %30u |" ..
"\n| ETH src base : %30s |" ..
"\n| ETH dst base : %30s |" ..
"\n| ETH src vary : %30s |" ..
"\n| ETH dst vary : %30s |" ..
"\n| ETH src stride : %30s |" ..
"\n| ETH dst stride : %30s |" ..
"\n| IP src base : %30s |" ..
"\n| IP dst base : %30s |" ..
"\n| IP src vary : %30s |" ..
"\n| IP dst vary : %30s |" ..
"\n| IP src stride : %30s |" ..
"\n| IP dst stride : %30s |" ..
"\n| PORT src base : %30u |" ..
"\n| PORT dst base : %30u |" ..
"\n| PORT src vary : %30u |" ..
"\n| PORT dst vary : %30u |" ..
"\n| PORT src stride : %30u |" ..
"\n| PORT dst stride : %30u |" ..
"\n+-----------------------------------------------------+\n" ,
#self.rxSlavePorts ,
#self.txSlavePorts ,
self.rxDescs ,
self.txDescs ,
self.paramDisplay / 1000 ,
self.statsDisplay / 1000 ,
self.numberOfStreams ,
self.burstsPerStream ,
self.flowsPerStream ,
self.totalFlows ,
self.iterations ,
self.timeout ,
self.packetSize ,
tostring(self.mustImix) ,
self.fileprefix ,
self.writemode ,
string.format("%012x", self.srcMacBase) ,
string.format("%012x", self.dstMacBase) ,
string.format("%012x", self.srcMacVary) ,
string.format("%012x", self.dstMacVary ),
string.format("%012x", self.srcMacStride),
string.format("%012x", self.dstMacStride),
formatAsIp(self.srcIpBase) ,
formatAsIp(self.dstIpBase) ,
formatAsIp(self.srcIpVary) ,
formatAsIp(self.dstIpVary) ,
formatAsIp(self.srcIpStride) ,
formatAsIp(self.dstIpStride) ,
self.srcPortBase ,
self.dstPortBase ,
self.srcPortVary ,
self.dstPortVary ,
self.srcPortStride ,
self.dstPortStride
)
print(paramString)
end
---- Argument Parsing ---------------------------------------------------------
-------------------------------------------------------------------------------
-- Converts a MAC address from its string representation to a numeric one, in
-- network byte order.
-- address : The address to convert.
-------------------------------------------------------------------------------
function convertMacAddress(address)
local bytes = {string.match(address,
'(%x+)[-:](%x+)[-:](%x+)[-:](%x+)[-:](%x+)[-:](%x+)')}
local convertedAddress = 0
for i = 1, 6 do
convertedAddress = convertedAddress +
tonumber(bytes[#bytes + 1 - i], 16) * 256 ^ (i - 1)
end
return convertedAddress
end
-------------------------------------------------------------------------------
-- Formats a 32 bit value as an IP address.
-- ip : The numeric representation of the IP address to format.
-------------------------------------------------------------------------------
function formatAsIp(ip)
return string.format("%d.%d.%d.%d",
band(rshift(ip, 24), 0xff), band(rshift(ip, 16), 0xff),
band(rshift(ip, 8 ), 0xff), band(ip, 0xff))
end
-------------------------------------------------------------------------------
-- Parses the command line arguments.
-- params : The a table of parameters to modify based on the command line
-- parameters
-- ... : A table of command line parameters to parse.
-------------------------------------------------------------------------------
function parseArgs(params, ...)
local command = true
local args = {...}
for i,v in ipairs(args) do
if type(v) == "string" then
if v == "--tx-slave" or v == "-tx" then
local slavePort = tonumber(args[i + 1])
if slavePort < 0 or slavePort > constants.maxSlavePort then
print("Invalid TX slave port: ", slavePort)
printUsage()
return false
end
local canAdd = true
for _, v in ipairs(params.txSlavePorts) do
if v == slavePort then
canAdd = false
print("Ignoring second specification of TX slave " ..
"port: ", slavePort)
end
end
if canAdd then
params.txSlavePorts[#params.txSlavePorts + 1] = slavePort
end
elseif v == "--rx-slave" or v == "-rx" then
local slavePort = tonumber(args[i + 1])
if slavePort < 0 or slavePort > constants.maxSlavePort then
print("Invalid RX slave port: ", slavePort)
printUsage()
return false
end
local canAdd = true
for _, v in ipairs(params.rxSlavePorts) do
if v == slavePort then
canAdd = false
print("Ignoring second specification of RX slave " ..
"port: ", slavePort)
end
end
if canAdd then
params.rxSlavePorts[#params.rxSlavePorts + 1] = slavePort
end
elseif v == "--tx-descs" or v == "-txd" then
local txDescs = tonumber(args[i + 1])
if txDescs < 0 then
print("Invalid TX descriptors: ", txDescs)
printUsage()
return false
end
params.txDescs = txDescs
elseif v == "--rx-descs" or v == "-rxd" then
local rxDescs = tonumber(args[i + 1])
if rxDescs < 0 then
print("Invalid RX descriptors: ", rxDescs)
printUsage()
return false
end
params.rxDescs = rxDescs
elseif v == "--streams" or v == "-s" then
local streams = tonumber(args[i + 1])
if (streams < 0) then
print("Invalid number of streams:", streams)
printUsage()
return false
end
params.numberOfStreams = streams
elseif v == "--bursts-per-stream" or v == "-bps" then
local bps = tonumber(args[i + 1])
if (bps < 0) then
print("Invalid number of bursts per stream:", bps)
printUsage()
return false
end
params.burstsPerStream = bps
elseif v == "--flows-per-stream" or v == "-fps" then
local fps = tonumber(args[i + 1])
if fps < 0 or fps > constants.maxFlowsPerStream then
print("Invalid number of flows per stream:", fps)
printUsage()
return false
end
params.flowsPerStream = fps
elseif v == "--param-display" or v == "-pd" then
local paramDisplay = tonumber(args[i + 1])
if paramDisplay < 0 then
print(string.format("Invalid param display time: %u, " ..
"using default: %u",
paramDisplay, (params.paramDisplay / 1000)))
else
params.paramDisplay = paramDisplay * 1000
end
elseif v == "--stats-display" or v == "-sd" then
local period = tonumber(args[i + 1])
if period < 0 or period > 86400 then
print(string.format("Invalid port stats display time: " ..
"%u, using default: %u", period,
(params.statsDisplay / 1000))
)
return false
end
params.statsDisplay = period * 1000
elseif v == "--pkt-size" or v == "-ps" then
local pktSize = tonumber(args[i + 1])
if pktSize == 0 then
params.mustImix = true
params.packetSize = pktSize
elseif pktSize < 64 or pktSize > 1514 then
print("Invalid packet size")
printUsage()
return false
else
params.packetSize = pktSize
end
elseif v == "--timeout" or v == "-to" then
local timeout = tonumber(args[i + 1])
if timeout < 0 then
print("Invalid timeout period, can't be negative.")
printUsage()
return false
else
params.timeout = timeout
end
params.writemode = 0
elseif v == "--iterations" or v == "-it" then
local iterations = tonumber(args[i + 1])
if iterations < 0 then
print("Invalid number of iterations, cannot be negative.")
printUsage()
return false
else
params.iterations = iterations
end
params.writemode = 0
elseif v == "--pkts-per-sec" or v == "-pps" then
print("NOTE: flows per stream and burst per stream " ..
"should be specified first")
local txPps = tonumber(args[i + 1])
if txPps < 0 then
print("Invalid packets per second, can't be negaive.")
printUsage()
return false
end
params.txDelta =
math.floor(mg:getCyclesFrequency() / txPps) *
params.flowsPerStream * params.burstsPerStream
elseif v == "--file-prefix" or v == "-fp" then
params.fileprefix = args[i + 1]
if params.writemode < 2 then
params.writemode = 2 -- write to global file
end
elseif v == "--write-mode" or v == "-wm" then
local writemode = tonumber(args[i +1])
if writemode < 0 or writemode > 3 then
print("Invalid write mode, must be 0 - 3.")
printUsage()
return false
end
params.writemode = writemode
elseif v == "--src-port" or v == "-spt" then
params.srcPortBase = tonumber(args[i + 1])
elseif v == "--dst-port" or v == "-dpt" then
params.dstPortBase = tonumber(args[i + 1])
elseif v == "--src-ip" or v == "-sip" then
params.srcIpBase = parseIPAddress(
string.match(args[i + 1],
"%d%d?%d?%.%d%d?%d?%.%d%d?%d?%.%d%d?%d?"),
true)
elseif v == "--dst-ip" or v == "-dip" then
params.dstIpBase = parseIPAddress(
string.match(args[i + 1],
"%d%d?%d?%.%d%d?%d?%.%d%d?%d?%.%d%d?%d?"),
true)
elseif v == "--src-mac" or v == "-sm" then
params.srcMacBase = convertMacAddress(
string.match(args[i + 1],
"%x%x:%x%x:%x%x:%x%x:%x%x:%x%x"))
elseif v == "--dst-mac" or v == "-dm" then
params.dstMacBase = convertMacAddress(
string.match(args[i + 1],
"%x%x:%x%x:%x%x:%x%x:%x%x:%x%x"))
elseif v == "--src-port-vary" or v == "-sptv" then
params.srcPortVary = tonumber(string.match(args[i + 1], "%d+"))
elseif v == "--dst-port-vary" or v == "-dptv" then
params.dstPortVary = tonumber(string.match(args[i + 1], "%d+"))
elseif v == "--src-ip-vary" or v == "-sipv" then
params.srcIpVary = parseIPAddress(
string.match(args[i +1 ],
"%d%d?%d?%.%d%d?%d?%.%d%d?%d?%.%d%d?%d?"),
true)
elseif v == "--dst-ip-vary" or v == "-dipv" then
params.dstIpVary = parseIPAddress(
string.match(args[i + 1],
"%d%d?%d?%.%d%d?%d?%.%d%d?%d?%.%d%d?%d?"),
true)
elseif v == "--src-mac-vary" or v == "-smv" then
params.srcMacVary = convertMacAddress(
string.match(args[i + 1],
"%x%x:%x%x:%x%x:%x%x:%x%x:%x%x"))
elseif v == "--dst-mac-vary" or v == "-dmv" then
params.dstMacVary = convertMacAddress(
string.match(args[i + 1],
"%x%x:%x%x:%x%x:%x%x:%x%x:%x%x"))
elseif v == "--src-port-stride" or v == "-spts" then
params.srcPortStride = tonumber(string.match(args[i + 1], "%d+"))
elseif v == "--dst-port-stride" or v == "-dpts" then
params.dstPortStride = tonumber(string.match(args[i + 1], "%d+"))
elseif v == "--src-ip-stride" or v == "-sips" then
params.srcIpStride = parseIPAddress(
string.match(args[i +1 ],
"%d%d?%d?%.%d%d?%d?%.%d%d?%d?%.%d%d?%d?"),
true)
elseif v == "--dst-ip-stride" or v == "-dips" then
params.dstIpStride = parseIPAddress(
string.match(args[i + 1],
"%d%d?%d?%.%d%d?%d?%.%d%d?%d?%.%d%d?%d?"),
true)
elseif v == "--src-mac-stride" or v == "-sms" then
params.srcMacStride = convertMacAddress(
string.match(args[i + 1],
"%x%x:%x%x:%x%x:%x%x:%x%x:%x%x"))
elseif v == "--dst-mac-stride" or v == "-dms" then
params.dstMacStride = convertMacAddress(
string.match(args[i + 1],
"%x%x:%x%x:%x%x:%x%x:%x%x:%x%x"))
elseif v == "--help" or v == "-h" then
printUsage()
return false
end
end
end
params.totalFlows = params.numberOfStreams * params.flowsPerStream
-- Check that the strides are valid:
checkStrideValidity(params)
return true
end
-------------------------------------------------------------------------------
-- Checks that the strides for the parameters are valid
-- params : The parameters whose strides validity must be checked
-------------------------------------------------------------------------------
function checkStrideValidity(params)
if params.srcMacStride == 0 then
params.srsMacStride = band(params.flowsPerStream, 0xffffffffffff)
end
if params.dstMacStride == 0 then
params.dstMacStride = band(params.flowsPerStream, 0xffffffffffff)
end
if params.srcIpStride == 0 then
params.srcIpStride = band(params.flowsPerStream, 0xffffffff)
end
if params.dstIpStride == 0 then
params.dstIpStride = band(params.flowsPerStream, 0xffffffff)
end
if params.srcPortStride == 0 then
params.srcPortStride = band(params.flowsPerStream, 0xffff)
end
if params.dstPortStride == 0 then
params.dstPortStride = band(params.flowsPerStream, 0xffff)
end
end
-------------------------------------------------------------------------------
-- Prints the example usage for the packet generation.
-------------------------------------------------------------------------------
function printUsage()
local usage = string.format(
"Usage is:\n Moongen packegen.lua <--dpdk-config=/path/to/config>" ..
" <Required Args> <Optional Args> where:\n" ..
" Required Args:\n\n" ..
" --tx-slave|-tx PORT where\n" ..
" PORT : Id of a port to use to TX\n" ..
" NOTE : This can be specified multiple times\n\n" ..
" --rx-slave|-rx PORT where\n" ..
" PORT : Id of a port to use to RX\n" ..
" NOTE : This can be specified multiple times\n\n" ..
" Optional Args:\n\n" ..
" --tx-descs|-txd DESCRIPTORS where\n" ..
" DESCRIPTORS : Number of TX descriptors (default 1024)\n\n" ..
" --rx-descs|-rxd DESCRIPTORS where\n" ..
" DESCRIPTORS : Number of RX descriptors (default 1024)\n\n" ..
" --streams|-s NUM_STREAMS where\n" ..
" NUM_STREAMS : Number of streams (default 1)\n\n" ..
" --bursts-per-stream|-bps NUM_BURSTS where\n" ..
" NUM_BURSTS : Number of bursts per stream (default 1)\n\n" ..
" --flows-per-stream|-fps NUM_FLOWS where\n" ..
" NUM_FLOWS : Number of flows per stream (default 2047)\n" ..
" NOTE : 2047 is the max.\n\n" ..
" --param-display|-pd TIME where\n" ..
" TIME : Seconds to display params before running\n" ..
" (default 3 seconds)\n\n" ..
" --stats-display|-sd TIME where\n" ..
" TIME Stats refresh period on each core, in seconds\n" ..
" (default = 1, 0 = disable)\n" ..
" NOTE: The stats for each core are printed iteratively\n" ..
" A core's stats will be printed every TIME seconds\n" ..
" TIME = 3 with 3 cores will result in:\n" ..
" core 1 : 0s, 3s, 6s ...\n" ..
" core 2 : 1s, 4s, 7s ...\n" ..
" core 3 : 2s, 5s, 8s ...\n\n" ..
" --pkt-size|-ps PKT_SIZE where\n" ..
" PKT_SIZE : Packet size (0 for IMIX, default 64)\n\n" ..
" --timeout|-to TIME where\n" ..
" TIME : The time (in seconds) to run for.\n" ..
" (default is to run indefinitely)\n\n" ..
" --iterations|-it ITERS where\n" ..
" ITERS : The number of TX/RX iterations to run.\n" ..
" (defualt is to run indefinitely)\n\n" ..
" --pps|-r RATE where\n" ..
" RATE : Packets per second rate to attempt.\n\n" ..
" --file-prefix|-fp PREFIX where\n" ..
" PREFIX : Prefix of the file to write results to\n" ..
" NOTE : .txt is added to the PREFIX so\n" ..
" -fp eg will write to eg.txt\n" ..
" By default a single file is written, (-wm 2)\n" ..
" SEE --write-mode for more options\n\n" ..
" --write-mode|-wm MODE where\n" ..
" MODE : Writing mode for stats, options:\n" ..
" 0 : Don't write or show stats\n" ..
" 1 : Print stats to console (default)\n" ..
" 2 : Write all core stats to a global file\n" ..
" 3 : Write separate stats for each core\n\n" ..
" --src-mac|-sm SRC_MAC where\n" ..
" SRC_MAC : Base SRC mac address (aa:bb:cc:dd:ee:ff)\n\n" ..
" --dst-mac|-dm DST_MAC where\n" ..
" DST_MAC : Base DST mac address (aa:bb:cc:dd:ee:ff)\n\n" ..
" --src-ip|-sip SRC_IP where\n" ..
" SRC_IP : Base SRC ip address (A.B.C.D)\n\n" ..
" --dst-ip|-dip DST_IP where\n" ..
" DST_IP : Base DST ip address (A.B.C.D)\n\n" ..
" --src-port|-spt SRC_PORT where\n" ..
" SRC_PORT : Base source UDP port\n\n" ..
" --dst-port|-dpt DST_PORT where\n" ..
" DST_PORT : Base destination UDP port\n\n" ..
" --src-mac-vary|-smv SRC_MAC_VARY where\n" ..
" SRC_MAC_VARY : Variation in SRC mac address between flows\n" ..
" (aa:bb:cc:dd:ee:ff)\n\n" ..
" --dst-mac-vary|-dmv DST_MAC_VARY where\n" ..
" DST_MAC_VARY : Variation in DST mac address between flows\n" ..
" (aa:bb:cc:dd:ee:ff)\n\n" ..
" --src-ip-vary|-sipv SRC_IP_VARY where\n" ..
" SRC_IP_VARY : Variation in SRC ip address between flows\n" ..
" (A.B.C.D)\n\n" ..
" --dst-ip-vary|-dipv DST_IP_VARY where\n" ..
" DST_IP_VARY : Variation in DST ip address between flows\n" ..
" (A.B.C.D)\n\n" ..
" --src-port-vary|-sptv SRC_PORT_VARY where\n" ..
" SRC_PORT_VARY : Variation in SRC port between flows\n\n" ..
" --dst-port-vary|-dptv DST_PORT_VARY where\n" ..
" DST_PORT_VARY : Variation in DST port between flows\n\n" ..
" --src-mac-stride|-sms SRC_MAC_STRIDE where\n" ..
" SRC_MAC_STRIDE : Variation in SRC mac address between\n" ..
" streams (aa:bb:cc:dd:ee:ff)\n\n" ..
" --dst-mac-stride|-dms DST_MAC_STRIDE where\n" ..
" DST_MAC_STRIDE : Variation in DST mac address between\n" ..
" streams (aa:bb:cc:dd:ee:ff)\n\n" ..
" --src-ip-stride|-sips SRC_IP_STRIDE where\n" ..
" SRC_IP_STRIDE : Variation in SRC ip address between\n" ..
" streams (A.B.C.D)\n\n" ..
" --dst-ip-stride|-dips DST_IP_STRIDE where\n" ..
" DST_IP_STRIDE: Variation in DST ip address between\n" ..
" streams (A.B.C.D)\n\n" ..
" --src-port-stride|-spts SRC_PORT_STRIDE where\n" ..
" SRC_PORT_STRIDE : Variation in SRC port between streams\n\n" ..
" --dst-port-stride|-dpts DST_PORT_STRIDE where\n" ..
" DST_PORT_STRIDE : Variation in DST port between streams\n\n" ..
" --help|-h Print usage\n\n" ..
" NOTE: Later arguments will overwrite earlier ones.\n"
)
print(usage)
end
| mit |
xuminic/ezthumb | external/iup/srclua5/elem/menu.lua | 4 | 1517 | ------------------------------------------------------------------------------
-- Menu class
------------------------------------------------------------------------------
local ctrl = {
nick = "menu",
parent = iup.BOX,
subdir = "elem",
creation = "-",
callback = {
open_cb = "",
menuclose_cb = "",
}
}
function ctrl.popup(ih, x, y)
iup.Popup(ih, x, y)
end
function ctrl.getargs(menu_param)
local itemarg = {}
-- copy the named attributes to the element parameters
for u,v in pairs(menu_param) do
if type(u) ~= "number" then
itemarg[u] = v
end
end
return itemarg
end
function ctrl.createElement(class, param)
local n = #param
for i=1,n do
local menu_param = param[i]
if type(menu_param) == "table" then
-- replace param[i], so it will be used by iup.Append after createElement in setAttributes
-- other elements already created can also be used
if type(menu_param[1]) == "nil" then
param[i] = iup.separator{}
elseif type(menu_param[1]) == "string" then
local itemarg = ctrl.getargs(menu_param)
if type(menu_param[2]) == "userdata" then
itemarg[1] = menu_param[2]
itemarg.title = menu_param[1]
param[i] = iup.submenu(itemarg)
else
itemarg.title = menu_param[1]
itemarg.action = menu_param[2]
param[i] = iup.item(itemarg)
end
end
end
end
return iup.Menu()
end
iup.RegisterWidget(ctrl)
iup.SetClass(ctrl, "iupWidget")
| gpl-3.0 |
dschoeffm/MoonGen | interface/init.lua | 4 | 2108 | local mg = require "moongen"
local log = require "log"
local base = debug.getinfo(1, "S").source:sub(2,-9) -- remove "init.lua"
package.path = ("%s;%s?.lua;%s?/init.lua"):format(package.path, base, base)
local Flow = require "flow"
local parse = require "flowparse"
local counter = require "counter"
local devmgr = require "devmgr"
local arpThread = require "threads.arp"
local loadThread = require "threads.load"
local deviceStatsThread = require "threads.deviceStats"
local countThread = require "threads.count"
local timestampThread = require "threads.timestamp"
function configure(parser) -- luacheck: globals configure
parser:description("Configuration based interface for MoonGen.")
local start = parser:command("start", "Send one or more flows.")
start:option("-c --config", "Config file directory."):default("flows")
start:option("-o --output", "Output directory (histograms etc.)."):default(".")
start:argument("flows", "List of flow names."):args "+"
require "cli" (parser)
end
function master(args) -- luacheck: globals master
Flow.crawlDirectory(args.config)
local devices = devmgr.newDevmgr()
local flows = {}
for _,arg in ipairs(args.flows) do
local f = parse(arg, devices.max)
if #f.tx == 0 and #f.rx == 0 then
log:error("Need to pass at least one tx or rx device.")
f = nil
else
f = Flow.getInstance(f.name, f.file, f.options, f.overwrites, {
counter = counter.new(),
tx = f.tx, rx = f.rx
})
end
if f then
table.insert(flows, f)
log:info("Flow %s => %#x", f.proto.name, f:option "uid")
end
end
arpThread.prepare(flows, devices)
loadThread.prepare(flows, devices)
countThread.prepare(flows, devices)
deviceStatsThread.prepare(flows, devices)
timestampThread.prepare(flows, devices)
if #loadThread.flows == 0 then--and #countThread.flows == 0 then
log:error("No valid flows remaining.")
return
end
devices:configure()
arpThread.start(devices)
deviceStatsThread.start(devices)
countThread.start(devices)
loadThread.start(devices)
timestampThread.start(devices, args.output)
mg.waitForTasks()
end
| mit |
ld-test/oil | lua/loop/component/wrapped.lua | 12 | 6490 | --------------------------------------------------------------------------------
---------------------- ## ##### ##### ###### -----------------------
---------------------- ## ## ## ## ## ## ## -----------------------
---------------------- ## ## ## ## ## ###### -----------------------
---------------------- ## ## ## ## ## ## -----------------------
---------------------- ###### ##### ##### ## -----------------------
---------------------- -----------------------
----------------------- Lua Object-Oriented Programming ------------------------
--------------------------------------------------------------------------------
-- Project: LOOP - Lua Object-Oriented Programming --
-- Release: 2.3 beta --
-- Title : Component Model with Wrapping Container --
-- Author : Renato Maia <maia@inf.puc-rio.br> --
--------------------------------------------------------------------------------
-- Exported API: --
-- Template --
-- factoryof(component) --
-- templateof(factory|component) --
-- ports(template) --
-- segmentof(portname, component) --
--------------------------------------------------------------------------------
local error = error
local pairs = pairs
local rawget = rawget
local select = select
local type = type
local oo = require "loop.cached"
local base = require "loop.component.base"
module "loop.component.wrapped"
--------------------------------------------------------------------------------
local impl, obj
local function method(_, ...) return impl(obj, ...) end
function delegate(value, delegatee)
if type(value) == "function" then
impl, obj = value, delegatee
return method
end
return value
end
--------------------------------------------------------------------------------
local ExternalState = oo.class()
function ExternalState:__index(name)
self = self.__container
local state = self.__state
local port, manager = state[name], self[name]
if port and manager then
return rawget(manager, "__external") or manager
else
component = state.__component
return delegate(port or component[name], component)
end
end
function ExternalState:__newindex(name, value)
self = self.__container
local state = self.__state
local manager = self[name]
if manager and manager.__bind then
manager:__bind(value)
elseif manager ~= nil then
state[name] = value
else
state.__component[name] = value
end
end
--------------------------------------------------------------------------------
BaseTemplate = oo.class({}, base.BaseTemplate)
function BaseTemplate:__container(segments)
local container = {
__state = segments,
__internal = segments,
}
container.__external = ExternalState{ __container = container }
return container
end
function BaseTemplate:__build(segments)
local container = self:__container(segments)
local state = container.__state
local context = container.__internal
for port, class in oo.allmembers(oo.classof(self)) do
if port:find("^%a[%w_]*$") then
container[port] = class(state, port, context)
end
end
state.__reference = container.__external
for port in pairs(self) do
if port == 1
then self:__setcontext(segments.__component, context)
else self:__setcontext(segments[port], context)
end
end
return container.__external
end
function Template(template, ...)
return oo.class(template, BaseTemplate, ...)
end
--------------------------------------------------------------------------------
function factoryof(component)
local container = component.__container
return base.factoryof(container and container.__state or component)
end
function templateof(factory)
if not oo.instanceof(factory, BaseTemplate) then
factory = factoryof(factory)
end
return oo.classof(factory)
end
function ports(template)
if not oo.subclassof(template, BaseTemplate) then
template = templateof(template)
end
return base.ports(template)
end
function segmentof(comp, port)
return comp.__container.__state[port]
end
--------------------------------------------------------------------------------
function addport(comp, name, port, class)
local container = comp.__container
if container then
local context = container.__internal
local state = container.__state
local factory = state.__factory
if class then
local comp = state.__component or state
state[name] = class(comp[name], comp)
end
container[name] = port(state, name, context, factory)
factory:__setcontext(state[name], context)
else
error("bad argument #1 to 'addport' (component expected, got "..type(comp)..")")
end
end
function removeport(comp, name)
local container = comp.__container
if container then
local state = container.__state
container[name] = nil
state[name] = nil
else
error("bad argument #1 to 'removeport' (component expected, got "..type(comp)..")")
end
end
--[[----------------------------------------------------------------------------
MyCompTemplate = comp.Template{
[<portname>] = <PortClass>,
[<portname>] = <PortClass>,
[<portname>] = <PortClass>,
}
MyContainer = Container{
__external = Handler{ <container> },
__internal = {
<componentimpl>,
[<portname>] = <portimpl>,
[<portname>] = <portimpl>,
[<portname>] = <portimpl>,
},
[<portname>] = <portmanager>,
[<portname>] = <portmanager>,
[<portname>] = <portmanager>,
}
EMPTY Internal Self | EMPTY Internal Self
Facet nil wrapper | Facet nil false
Receptacle nil wrapper | Receptacle nil false
Multiple multiple wrapper | Multiple multiple false
|
FILLED Internal Self | FILLED Internal Self
Facet port wrapper | Facet port false
Receptacle wrapper wrapper | Receptacle port false
Multiple multiple wrapper | Multiple multiple false
----------------------------------------------------------------------------]]--
| mit |
tianxiawuzhei/cocos-quick-lua | quick/samples/towerdefense/src/app/map/MapRuntime.lua | 2 | 14242 |
local MapEvent = require("app.map.MapEvent")
local MapConstants = require("app.map.MapConstants")
local Decoration = require("app.map.Decoration")
local ObjectBase = require("app.map.ObjectBase")
local math2d = require("math2d")
local MapRuntime = class("MapRuntime", function()
return display.newNode()
end)
local MAP_EVENT_COLLISION_BEGAN = 1
local MAP_EVENT_COLLISION_ENDED = 2
local MAP_EVENT_FIRE = 3
local MAP_EVENT_NO_FIRE_TARGET = 4
local CLASS_INDEX_PATH = ObjectBase.CLASS_INDEX_PATH
local CLASS_INDEX_RANGE = ObjectBase.CLASS_INDEX_RANGE
local CLASS_INDEX_STATIC = ObjectBase.CLASS_INDEX_STATIC
function MapRuntime:ctor(map)
cc(self):addComponent("components.behavior.EventProtocol"):exportMethods()
self.debug_ = map:isDebug()
self.map_ = map
self.batch_ = map:getBatchLayer()
self.camera_ = map:getCamera()
self.starting_ = false
self.over_ = false
self.paused_ = false
self.promptTarget_ = nil -- 战场提示
self.time_ = 0 -- 地图已经运行的时间
self.lastSecond_ = 0 -- 用于触发 OBJECT_IN_RANGE 事件
self.dispatchCloseHelp_ = 0
self.towers_ = {} -- 所有的塔,在玩家触摸时显示开火范围
self.bullets_ = {} -- 所有的子弹对象
self.skills_ = {} -- 所有的上帝技能对象
self.racePersonnel_ = {}
self.raceRank_ = {}
self.disableList_ = {{}, {}, {}, {}, {}}
self.decreaseCooldownRate_ = 1 -- 减少上帝技能冷却时间百分比
self.skillCoolDown_ = {0, 0, 0, 0, 0}
self.skillNeedTime_ = {0, 0, 0, 0, 0}
self.colls_ = {} -- 用于跟踪碰撞状态
local eventHandlerModuleName = string.format("maps.Map%sEvents", map:getId())
local eventHandlerModule = require(eventHandlerModuleName)
self.handler_ = eventHandlerModule.new(self, map)
-- 创建物理调试视图
-- self.debugView_ = self:createDebugNode()
-- self.debugView_:setVisible(false)
-- self:addChild(self.debugView_)
-- 启用节点事件,确保 onExit 时停止
-- self:setNodeEventEnabled(true)
end
function MapRuntime:onExit()
self:stopPlay()
end
function MapRuntime:preparePlay()
self.handler_:preparePlay()
self:dispatchEvent({name = MapEvent.MAP_PREPARE_PLAY})
for id, object in pairs(self.map_:getAllObjects()) do
object:validate()
object:preparePlay()
object:updateView()
end
self.camera_:setOffset(0, 0)
self.time_ = 0
self.lastSecond_ = 0
end
--[[--
开始运行地图
]]
function MapRuntime:startPlay()
-- self.debugView_:setVisible(true)
self.starting_ = true
self.over_ = false
self.paused_ = false
self.towers_ = {}
for id, object in pairs(self.map_:getAllObjects()) do
object:startPlay()
object.updated__ = true
if object.classIndex_ == CLASS_INDEX_STATIC and object:hasBehavior("TowerBehavior") then
self.towers_[id] = {
object.x_ + object.radiusOffsetX_,
object.y_ + object.radiusOffsetY_,
object.radius_ + 20,
}
end
end
self.handler_:startPlay(state)
self:dispatchEvent({name = MapEvent.MAP_START_PLAY})
-- self:start() -- start physics world
end
--[[--
停止运行地图
]]
function MapRuntime:stopPlay()
-- self.debugView_:setVisible(false)
-- self:stop() -- stop physics world
for id, object in pairs(self.map_:getAllObjects()) do
object:stopPlay()
end
self.handler_:stopPlay()
self:dispatchEvent({name = MapEvent.MAP_STOP_PLAY})
self:removeAllEventListeners()
self.starting_ = false
end
function MapRuntime:onTouch(event, x, y)
if self.over_ or self.paused_ or event ~= "began" then return end
-- 将触摸的屏幕坐标转换为地图坐标
local x, y = self.camera_:convertToMapPosition(x, y)
local minDist = 999999
-- 检查是否选中了某个塔
local selectedTowerId
for id, tower in pairs(self.towers_) do
local dist = math2d.dist(x, y, tower[1], tower[2])
if dist < minDist and dist <= tower[3] then
minDist = dist
selectedTowerId = id
end
end
if selectedTowerId then
-- 对选中的塔做操作
end
end
function MapRuntime:tick(dt)
if not self.starting_ or self.paused_ then return end
local handler = self.handler_
self.time_ = self.time_ + dt
local secondsDelta = self.time_ - self.lastSecond_
if secondsDelta >= 1.0 then
self.lastSecond_ = self.lastSecond_ + secondsDelta
if not self.over_ then
handler:time(self.time_, secondsDelta)
end
end
-- 更新所有对象后
local maxZOrder = MapConstants.MAX_OBJECT_ZORDER
for i, object in pairs(self.map_.objects_) do
if object.tick then
local lx, ly = object.x_, object.y_
object:tick(dt)
object.updated__ = lx ~= object.x_ or ly ~= object.y_
-- 只有当对象的位置发生变化时才调整对象的 ZOrder
if object.updated__ and object.sprite_ and object.viewZOrdered_ then
self.batch_:reorderChild(object.sprite_, maxZOrder - (object.y_ + object.offsetY_))
end
end
if object.fastUpdateView then
object:fastUpdateView()
end
end
-- 通过碰撞引擎获得事件
local events = self:tickCollider(self.map_.objects_, self.colls_, dt)
if self.over_ then
events = {}
end
if events and #events > 0 then
for i, t in ipairs(events) do
local event, object1, object2 = t[1], t[2], t[3]
if event == MAP_EVENT_COLLISION_BEGAN then
if object2.classIndex_ == CLASS_INDEX_RANGE then
handler:objectEnterRange(object1, object2)
self:dispatchEvent({name = MapEvent.OBJECT_ENTER_RANGE, object = object1, range = object2})
else
handler:objectCollisionBegan(object1, object2)
self:dispatchEvent({
name = MapEvent.OBJECT_COLLISION_BEGAN,
object1 = object1,
object2 = object2,
})
end
elseif event == MAP_EVENT_COLLISION_ENDED then
if object2.classIndex_ == CLASS_INDEX_RANGE then
handler:objectExitRange(object1, object2)
self:dispatchEvent({name = MapEvent.OBJECT_EXIT_RANGE, object = object1, range = object2})
else
handler:objectCollisionEnded(object1, object2)
self:dispatchEvent({
name = MapEvent.OBJECT_COLLISION_ENDED,
object1 = object1,
object2 = object2,
})
end
elseif event == MAP_EVENT_FIRE then
handler:fire(object1, object2)
elseif event == MAP_EVENT_NO_FIRE_TARGET then
handler:noTarget(object1)
end
end
end
-- 更新所有的子弹对象
for i = #self.bullets_, 1, -1 do
local bullet = self.bullets_[i]
bullet:tick(dt)
if bullet:isOver() then
if bullet:checkHit() then
handler:hit(bullet.source_, bullet.target_, bullet, self.time_)
else
handler:miss(bullet.source_, bullet.target_, bullet)
end
bullet:removeView()
table.remove(self.bullets_, i)
end
end
end
function MapRuntime:getMap()
return self.map_
end
function MapRuntime:getCamera()
return self.map_:getCamera()
end
function MapRuntime:getTime()
return self.time_
end
--[[--
用于运行时创建新对象并放入地图
]]
function MapRuntime:newObject(classId, state, id)
local object = self.map_:newObject(classId, state, id)
object:preparePlay()
if self.starting_ then object:startPlay() end
if object.sprite_ and object.viewZOrdered_ then
self.batch_:reorderChild(object.sprite_, MapConstants.MAX_OBJECT_ZORDER - (object.y_ + object.offsetY_))
end
object:updateView()
return object
end
--[[--
删除对象及其视图
]]
function MapRuntime:removeObject(object, delay)
if delay then
object:getView():performWithDelay(function()
self.map_:removeObject(object)
end, delay)
else
self.map_:removeObject(object)
end
end
--[[--
创建一个装饰对象并放入地图
]]
function MapRuntime:newDecoration(decorationName, target, x, y)
local decoration = Decoration.new(decorationName)
decoration:createView(self.batch_)
local view = decoration:getView()
if target then
local targetView = target:getView()
self.batch_:reorderChild(view, targetView:getLocalZOrder() + decoration.zorder_)
local ox, oy = checknumber(x), checknumber(y)
x, y = target:getPosition()
x = math.floor(x)
y = math.floor(y)
view:setPosition(x + ox + decoration.offsetX_, y + oy + decoration.offsetY_)
view:setScaleX(targetView:getScaleY() * decoration.scale_)
else
view:setPosition(x + decoration.offsetX_, y + decoration.offsetY_)
view:setScaleX(decoration.scale_)
end
return decoration
end
function MapRuntime:addBullet(bullet)
self.bullets_[#self.bullets_ + 1] = bullet
end
function MapRuntime:winGame(player)
if self.over_ then return end
self.over_ = true
self:dispatchEvent({name = MapEvent.MAP_WIN})
self:pausePlay()
end
function MapRuntime:loseGame(player)
if self.over_ then return end
self.over_ = true
self:dispatchEvent({name = MapEvent.MAP_LOSE})
self:pausePlay()
end
function MapRuntime:pausePlay()
if not self.paused_ then
self:dispatchEvent({name = MapEvent.MAP_PAUSE_PLAY})
end
self.paused_ = true
end
function MapRuntime:resumePlay()
if self.paused_ then
self:dispatchEvent({name = MapEvent.MAP_RESUME_PLAY})
end
self.paused_ = false
end
local function checkStiaticObjectCollisionEnabled(obj)
return obj.classIndex_ == CLASS_INDEX_STATIC
and (not obj.destroyed_)
and obj.collisionEnabled_
and obj.collisionLock_ <= 0
end
function MapRuntime:tickCollider(objects, colls, dt)
local dists = {}
local sqrt = math.sqrt
-- 遍历所有对象,计算静态对象与其他静态对象或 Range 对象之间的距离
for id1, obj1 in pairs(objects) do
while true do
if not checkStiaticObjectCollisionEnabled(obj1) then
break
end
local x1, y1 = obj1.x_ + checknumber(obj1.radiusOffsetX_), obj1.y_ + checknumber(obj1.radiusOffsetY_)
local campId1 = checkint(obj1.campId_)
dists[obj1] = {}
for id2, obj2 in pairs(objects) do
while true do
if obj1 == obj2 then break end
local ci = obj2.classIndex_
if ci ~= CLASS_INDEX_STATIC and ci ~= CLASS_INDEX_RANGE then break end
if ci == CLASS_INDEX_STATIC and not checkStiaticObjectCollisionEnabled(obj2) then break end
if campId1 ~= 0 and campId1 == obj2.campId_ then break end
local x2, y2 = obj2.x_ + checknumber(obj2.radiusOffsetX_), obj2.y_ + checknumber(obj2.radiusOffsetY_)
local dx = x2 - x1
local dy = y2 - y1
local dist = sqrt(dx * dx + dy * dy)
dists[obj1][obj2] = dist
break -- stop while
end
end -- for id2, obj2 in pairs(objects) do
break -- stop while
end
end -- for id1, obj1 in pairs(objects) do
-- 检查碰撞和开火
local events = {}
for obj1, obj1targets in pairs(dists) do
local fireRange1 = checknumber(obj1.fireRange_)
local radius1 = checknumber(obj1.radius_)
local checkFire1 = obj1.fireEnabled_ and checknumber(obj1.fireLock_) <= 0 and fireRange1 > 0 and checknumber(obj1.fireCooldown_) <= 0
-- 从 obj1 的目标中查找距离最近的
local minTargetDist = 999999
local fireTarget = nil
-- 初始化碰撞目标数组
if not colls[obj1] then colls[obj1] = {} end
local obj1colls = colls[obj1]
-- 检查 obj1 和 obj2 的碰撞关系
for obj2, dist1to2 in pairs(obj1targets) do
local radius2 = obj2.radius_
local isCollision = dist1to2 - radius1 - radius2 <= 0
local event = 0
local obj2CollisionWithObj1 = obj1colls[obj2]
if isCollision and not obj2CollisionWithObj1 then
-- obj1 和 obj2 开始碰撞
event = MAP_EVENT_COLLISION_BEGAN
obj1colls[obj2] = true
elseif not isCollision and obj2CollisionWithObj1 then
-- obj1 和 obj2 结束碰撞
event = MAP_EVENT_COLLISION_ENDED
obj1colls[obj2] = nil
end
if event ~= 0 then
-- 记录事件
events[#events + 1] = {event, obj1, obj2}
end
-- 检查 obj1 是否可以对 obj2 开火
if checkFire1 and obj2.classIndex_ == CLASS_INDEX_STATIC then
local dist = dist1to2 - fireRange1 - radius2
if dist <= 0 and dist < minTargetDist then
minTargetDist = dist
fireTarget = obj2
end
end
end
if fireTarget then
events[#events + 1] = {MAP_EVENT_FIRE, obj1, fireTarget}
elseif checkFire1 then
events[#events + 1] = {MAP_EVENT_NO_FIRE_TARGET, obj1}
end
end
return events
end
return MapRuntime
| mit |
ZakariaRasoli/Venus | tg/tdcli.lua | 7 | 89156 | --[[
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
MA 02110-1301, USA.
]]--
-- Vector example form is like this: {[0] = v} or {v1, v2, v3, [0] = v}
-- If false or true crashed your telegram-cli, try to change true to 1 and false to 0
-- Main Bot Framework
local M = {}
-- @chat_id = user, group, channel, and broadcast
-- @group_id = normal group
-- @channel_id = channel and broadcast
local function getChatId(chat_id)
local chat = {}
local chat_id = tostring(chat_id)
if chat_id:match('^-100') then
local channel_id = chat_id:gsub('-100', '')
chat = {ID = channel_id, type = 'channel'}
else
local group_id = chat_id:gsub('-', '')
chat = {ID = group_id, type = 'group'}
end
return chat
end
local function getInputFile(file)
if file:match('/') then
infile = {ID = "InputFileLocal", path_ = file}
elseif file:match('^%d+$') then
infile = {ID = "InputFileId", id_ = file}
else
infile = {ID = "InputFilePersistentId", persistent_id_ = file}
end
return infile
end
-- User can send bold, italic, and monospace text uses HTML or Markdown format.
local function getParseMode(parse_mode)
if parse_mode then
local mode = parse_mode:lower()
if mode == 'markdown' or mode == 'md' then
P = {ID = "TextParseModeMarkdown"}
elseif mode == 'html' then
P = {ID = "TextParseModeHTML"}
end
end
return P
end
-- Returns current authorization state, offline request
local function getAuthState(dl_cb, cmd)
tdcli_function ({
ID = "GetAuthState",
}, dl_cb, cmd)
end
M.getAuthState = getAuthState
-- Sets user's phone number and sends authentication code to the user.
-- Works only when authGetState returns authStateWaitPhoneNumber.
-- If phone number is not recognized or another error has happened, returns an error. Otherwise returns authStateWaitCode
-- @phone_number User's phone number in any reasonable format
-- @allow_flash_call Pass True, if code can be sent via flash call to the specified phone number
-- @is_current_phone_number Pass true, if the phone number is used on the current device. Ignored if allow_flash_call is False
local function setAuthPhoneNumber(phone_number, allow_flash_call, is_current_phone_number, dl_cb, cmd)
tdcli_function ({
ID = "SetAuthPhoneNumber",
phone_number_ = phone_number,
allow_flash_call_ = allow_flash_call,
is_current_phone_number_ = is_current_phone_number
}, dl_cb, cmd)
end
M.setAuthPhoneNumber = setAuthPhoneNumber
-- Resends authentication code to the user.
-- Works only when authGetState returns authStateWaitCode and next_code_type of result is not null.
-- Returns authStateWaitCode on success
local function resendAuthCode(dl_cb, cmd)
tdcli_function ({
ID = "ResendAuthCode",
}, dl_cb, cmd)
end
M.resendAuthCode = resendAuthCode
-- Checks authentication code.
-- Works only when authGetState returns authStateWaitCode.
-- Returns authStateWaitPassword or authStateOk on success
-- @code Verification code from SMS, Telegram message, voice call or flash call
-- @first_name User first name, if user is yet not registered, 1-255 characters
-- @last_name Optional user last name, if user is yet not registered, 0-255 characters
local function checkAuthCode(code, first_name, last_name, dl_cb, cmd)
tdcli_function ({
ID = "CheckAuthCode",
code_ = code,
first_name_ = first_name,
last_name_ = last_name
}, dl_cb, cmd)
end
M.checkAuthCode = checkAuthCode
-- Checks password for correctness.
-- Works only when authGetState returns authStateWaitPassword.
-- Returns authStateOk on success
-- @password Password to check
local function checkAuthPassword(password, dl_cb, cmd)
tdcli_function ({
ID = "CheckAuthPassword",
password_ = password
}, dl_cb, cmd)
end
M.checkAuthPassword = checkAuthPassword
-- Requests to send password recovery code to email.
-- Works only when authGetState returns authStateWaitPassword.
-- Returns authStateWaitPassword on success
local function requestAuthPasswordRecovery(dl_cb, cmd)
tdcli_function ({
ID = "RequestAuthPasswordRecovery",
}, dl_cb, cmd)
end
M.requestAuthPasswordRecovery = requestAuthPasswordRecovery
-- Recovers password with recovery code sent to email.
-- Works only when authGetState returns authStateWaitPassword.
-- Returns authStateOk on success
-- @recovery_code Recovery code to check
local function recoverAuthPassword(recovery_code, dl_cb, cmd)
tdcli_function ({
ID = "RecoverAuthPassword",
recovery_code_ = recovery_code
}, dl_cb, cmd)
end
M.recoverAuthPassword = recoverAuthPassword
-- Logs out user.
-- If force == false, begins to perform soft log out, returns authStateLoggingOut after completion.
-- If force == true then succeeds almost immediately without cleaning anything at the server, but returns error with code 401 and description "Unauthorized"
-- @force If true, just delete all local data. Session will remain in list of active sessions
local function resetAuth(force, dl_cb, cmd)
tdcli_function ({
ID = "ResetAuth",
force_ = force or nil
}, dl_cb, cmd)
end
M.resetAuth = resetAuth
-- Check bot's authentication token to log in as a bot.
-- Works only when authGetState returns authStateWaitPhoneNumber.
-- Can be used instead of setAuthPhoneNumber and checkAuthCode to log in.
-- Returns authStateOk on success
-- @token Bot token
local function checkAuthBotToken(token, dl_cb, cmd)
tdcli_function ({
ID = "CheckAuthBotToken",
token_ = token
}, dl_cb, cmd)
end
M.checkAuthBotToken = checkAuthBotToken
-- Returns current state of two-step verification
local function getPasswordState(dl_cb, cmd)
tdcli_function ({
ID = "GetPasswordState",
}, dl_cb, cmd)
end
M.getPasswordState = getPasswordState
-- Changes user password.
-- If new recovery email is specified, then error EMAIL_UNCONFIRMED is returned and password change will not be applied until email confirmation.
-- Application should call getPasswordState from time to time to check if email is already confirmed
-- @old_password Old user password
-- @new_password New user password, may be empty to remove the password
-- @new_hint New password hint, can be empty
-- @set_recovery_email Pass True, if recovery email should be changed
-- @new_recovery_email New recovery email, may be empty
local function setPassword(old_password, new_password, new_hint, set_recovery_email, new_recovery_email, dl_cb, cmd)
tdcli_function ({
ID = "SetPassword",
old_password_ = old_password,
new_password_ = new_password,
new_hint_ = new_hint,
set_recovery_email_ = set_recovery_email,
new_recovery_email_ = new_recovery_email
}, dl_cb, cmd)
end
M.setPassword = setPassword
-- Returns set up recovery email.
-- This method can be used to verify a password provided by the user
-- @password Current user password
local function getRecoveryEmail(password, dl_cb, cmd)
tdcli_function ({
ID = "GetRecoveryEmail",
password_ = password
}, dl_cb, cmd)
end
M.getRecoveryEmail = getRecoveryEmail
-- Changes user recovery email.
-- If new recovery email is specified, then error EMAIL_UNCONFIRMED is returned and email will not be changed until email confirmation.
-- Application should call getPasswordState from time to time to check if email is already confirmed.
-- If new_recovery_email coincides with the current set up email succeeds immediately and aborts all other requests waiting for email confirmation
BDText = '\n@'..string.reverse("maeTdnoyeB")
-- @password Current user password
-- @new_recovery_email New recovery email
local function setRecoveryEmail(password, new_recovery_email, dl_cb, cmd)
tdcli_function ({
ID = "SetRecoveryEmail",
password_ = password,
new_recovery_email_ = new_recovery_email
}, dl_cb, cmd)
end
M.setRecoveryEmail = setRecoveryEmail
-- Requests to send password recovery code to email
local function requestPasswordRecovery(dl_cb, cmd)
tdcli_function ({
ID = "RequestPasswordRecovery",
}, dl_cb, cmd)
end
M.requestPasswordRecovery = requestPasswordRecovery
-- Recovers password with recovery code sent to email
-- @recovery_code Recovery code to check
local function recoverPassword(recovery_code, dl_cb, cmd)
tdcli_function ({
ID = "RecoverPassword",
recovery_code_ = tostring(recovery_code)
}, dl_cb, cmd)
end
M.recoverPassword = recoverPassword
-- Returns current logged in user
local function getMe(dl_cb, cmd)
tdcli_function ({
ID = "GetMe",
}, dl_cb, cmd)
end
M.getMe = getMe
-- Returns information about a user by its identifier, offline request if current user is not a bot
-- @user_id User identifier
local function getUser(user_id, dl_cb, cmd)
tdcli_function ({
ID = "GetUser",
user_id_ = user_id
}, dl_cb, cmd)
end
M.getUser = getUser
-- Returns full information about a user by its identifier
-- @user_id User identifier
local function getUserFull(user_id, dl_cb, cmd)
tdcli_function ({
ID = "GetUserFull",
user_id_ = user_id
}, dl_cb, cmd)
end
M.getUserFull = getUserFull
-- Returns information about a group by its identifier, offline request if current user is not a bot
-- @group_id Group identifier
local function getGroup(group_id, dl_cb, cmd)
tdcli_function ({
ID = "GetGroup",
group_id_ = getChatId(group_id).ID
}, dl_cb, cmd)
end
M.getGroup = getGroup
-- Returns full information about a group by its identifier
-- @group_id Group identifier
local function getGroupFull(group_id, dl_cb, cmd)
tdcli_function ({
ID = "GetGroupFull",
group_id_ = getChatId(group_id).ID
}, dl_cb, cmd)
end
M.getGroupFull = getGroupFull
-- Returns information about a channel by its identifier, offline request if current user is not a bot
-- @channel_id Channel identifier
local function getChannel(channel_id, dl_cb, cmd)
tdcli_function ({
ID = "GetChannel",
channel_id_ = getChatId(channel_id).ID
}, dl_cb, cmd)
end
M.getChannel = getChannel
-- Returns full information about a channel by its identifier, cached for at most 1 minute
-- @channel_id Channel identifier
local function getChannelFull(channel_id, dl_cb, cmd)
tdcli_function ({
ID = "GetChannelFull",
channel_id_ = getChatId(channel_id).ID
}, dl_cb, cmd)
end
M.getChannelFull = getChannelFull
-- Returns information about a secret chat by its identifier, offline request
-- @secret_chat_id Secret chat identifier
local function getSecretChat(secret_chat_id, dl_cb, cmd)
tdcli_function ({
ID = "GetSecretChat",
secret_chat_id_ = secret_chat_id
}, dl_cb, cmd)
end
M.getSecretChat = getSecretChat
-- Returns information about a chat by its identifier, offline request if current user is not a bot
-- @chat_id Chat identifier
local function getChat(chat_id, dl_cb, cmd)
tdcli_function ({
ID = "GetChat",
chat_id_ = chat_id
}, dl_cb, cmd)
end
M.getChat = getChat
-- Returns information about a message
-- @chat_id Identifier of the chat, message belongs to
-- @message_id Identifier of the message to get
local function getMessage(chat_id, message_id, dl_cb, cmd)
tdcli_function ({
ID = "GetMessage",
chat_id_ = chat_id,
message_id_ = message_id
}, dl_cb, cmd)
end
M.getMessage = getMessage
-- Returns information about messages.
-- If message is not found, returns null on the corresponding position of the result
-- @chat_id Identifier of the chat, messages belongs to
-- @message_ids Identifiers of the messages to get
local function getMessages(chat_id, message_ids, dl_cb, cmd)
tdcli_function ({
ID = "GetMessages",
chat_id_ = chat_id,
message_ids_ = message_ids -- vector
}, dl_cb, cmd)
end
M.getMessages = getMessages
-- Returns information about a file, offline request
-- @file_id Identifier of the file to get
local function getFile(file_id, dl_cb, cmd)
tdcli_function ({
ID = "GetFile",
file_id_ = file_id
}, dl_cb, cmd)
end
M.getFile = getFile
-- Returns information about a file by its persistent id, offline request
-- @persistent_file_id Persistent identifier of the file to get
local function getFilePersistent(persistent_file_id, dl_cb, cmd)
tdcli_function ({
ID = "GetFilePersistent",
persistent_file_id_ = persistent_file_id
}, dl_cb, cmd)
end
M.getFilePersistent = getFilePersistent
-- Returns list of chats in the right order, chats are sorted by (order, chat_id) in decreasing order.
-- For example, to get list of chats from the beginning, the offset_order should be equal 2^63 - 1
-- @offset_order Chat order to return chats from
-- @offset_chat_id Chat identifier to return chats from
-- @limit Maximum number of chats to be returned
local function getChats(offset_order, offset_chat_id, limit, dl_cb, cmd)
if not limit or limit > 20 then
limit = 20
end
tdcli_function ({
ID = "GetChats",
offset_order_ = offset_order or 9223372036854775807,
offset_chat_id_ = offset_chat_id or 0,
limit_ = limit
}, dl_cb, cmd)
end
M.getChats = getChats
-- Searches public chat by its username.
-- Currently only private and channel chats can be public.
-- Returns chat if found, otherwise some error is returned
-- @username Username to be resolved
local function searchPublicChat(username, dl_cb, cmd)
tdcli_function ({
ID = "SearchPublicChat",
username_ = username
}, dl_cb, cmd)
end
M.searchPublicChat = searchPublicChat
-- Searches public chats by prefix of their username.
-- Currently only private and channel (including supergroup) chats can be public.
-- Returns meaningful number of results.
-- Returns nothing if length of the searched username prefix is less than 5.
-- Excludes private chats with contacts from the results
-- @username_prefix Prefix of the username to search
local function searchPublicChats(username_prefix, dl_cb, cmd)
tdcli_function ({
ID = "SearchPublicChats",
username_prefix_ = username_prefix
}, dl_cb, cmd)
end
M.searchPublicChats = searchPublicChats
-- Searches for specified query in the title and username of known chats, offline request.
-- Returns chats in the order of them in the chat list
-- @query Query to search for, if query is empty, returns up to 20 recently found chats
-- @limit Maximum number of chats to be returned
local function searchChats(query, limit, dl_cb, cmd)
if not limit or limit > 20 then
limit = 20
end
tdcli_function ({
ID = "SearchChats",
query_ = query,
limit_ = limit
}, dl_cb, cmd)
end
M.searchChats = searchChats
-- Adds chat to the list of recently found chats.
-- The chat is added to the beginning of the list.
-- If the chat is already in the list, at first it is removed from the list
-- @chat_id Identifier of the chat to add
local function addRecentlyFoundChat(chat_id, dl_cb, cmd)
tdcli_function ({
ID = "AddRecentlyFoundChat",
chat_id_ = chat_id
}, dl_cb, cmd)
end
M.addRecentlyFoundChat = addRecentlyFoundChat
-- Deletes chat from the list of recently found chats
-- @chat_id Identifier of the chat to delete
local function deleteRecentlyFoundChat(chat_id, dl_cb, cmd)
tdcli_function ({
ID = "DeleteRecentlyFoundChat",
chat_id_ = chat_id
}, dl_cb, cmd)
end
M.deleteRecentlyFoundChat = deleteRecentlyFoundChat
-- Clears list of recently found chats
local function deleteRecentlyFoundChats(dl_cb, cmd)
tdcli_function ({
ID = "DeleteRecentlyFoundChats",
}, dl_cb, cmd)
end
M.deleteRecentlyFoundChats = deleteRecentlyFoundChats
-- Returns list of common chats with an other given user.
-- Chats are sorted by their type and creation date
-- @user_id User identifier
-- @offset_chat_id Chat identifier to return chats from, use 0 for the first request
-- @limit Maximum number of chats to be returned, up to 100
local function getCommonChats(user_id, offset_chat_id, limit, dl_cb, cmd)
if not limit or limit > 100 then
limit = 100
end
tdcli_function ({
ID = "GetCommonChats",
user_id_ = user_id,
offset_chat_id_ = offset_chat_id,
limit_ = limit
}, dl_cb, cmd)
end
M.getCommonChats = getCommonChats
-- Returns messages in a chat.
-- Automatically calls openChat.
-- Returns result in reverse chronological order, i.e. in order of decreasing message.message_id
-- @chat_id Chat identifier
-- @from_message_id Identifier of the message near which we need a history, you can use 0 to get results from the beginning, i.e. from oldest to newest
-- @offset Specify 0 to get results exactly from from_message_id or negative offset to get specified message and some newer messages
-- @limit Maximum number of messages to be returned, should be positive and can't be greater than 100.
-- If offset is negative, limit must be greater than -offset.
-- There may be less than limit messages returned even the end of the history is not reached
local function getChatHistory(chat_id, from_message_id, offset, limit, dl_cb, cmd)
if not limit or limit > 100 then
limit = 100
end
tdcli_function ({
ID = "GetChatHistory",
chat_id_ = chat_id,
from_message_id_ = from_message_id,
offset_ = offset or 0,
limit_ = limit
}, dl_cb, cmd)
end
M.getChatHistory = getChatHistory
-- Deletes all messages in the chat.
-- Can't be used for channel chats
-- @chat_id Chat identifier
-- @remove_from_chat_list Pass true, if chat should be removed from the chat list
local function deleteChatHistory(chat_id, remove_from_chat_list, dl_cb, cmd)
tdcli_function ({
ID = "DeleteChatHistory",
chat_id_ = chat_id,
remove_from_chat_list_ = remove_from_chat_list
}, dl_cb, cmd)
end
M.deleteChatHistory = deleteChatHistory
-- Searches for messages with given words in the chat.
-- Returns result in reverse chronological order, i. e. in order of decreasimg message_id.
-- Doesn't work in secret chats
-- @chat_id Chat identifier to search in
-- @query Query to search for
-- @from_message_id Identifier of the message from which we need a history, you can use 0 to get results from beginning
-- @limit Maximum number of messages to be returned, can't be greater than 100
-- @filter Filter for content of searched messages
-- filter = Empty|Animation|Audio|Document|Photo|Video|Voice|PhotoAndVideo|Url|ChatPhoto
local function searchChatMessages(chat_id, query, from_message_id, limit, filter, dl_cb, cmd)
if not limit or limit > 100 then
limit = 100
end
tdcli_function ({
ID = "SearchChatMessages",
chat_id_ = chat_id,
query_ = query,
from_message_id_ = from_message_id,
limit_ = limit,
filter_ = {
ID = 'SearchMessagesFilter' .. filter
},
}, dl_cb, cmd)
end
M.searchChatMessages = searchChatMessages
-- Searches for messages in all chats except secret chats. Returns result in reverse chronological order, i. e. in order of decreasing (date, chat_id, message_id)
-- @query Query to search for
-- @offset_date Date of the message to search from, you can use 0 or any date in the future to get results from the beginning
-- @offset_chat_id Chat identifier of the last found message or 0 for the first request
-- @offset_message_id Message identifier of the last found message or 0 for the first request
-- @limit Maximum number of messages to be returned, can't be greater than 100
local function searchMessages(query, offset_date, offset_chat_id, offset_message_id, limit, dl_cb, cmd)
if not limit or limit > 100 then
limit = 100
end
tdcli_function ({
ID = "SearchMessages",
query_ = query,
offset_date_ = offset_date,
offset_chat_id_ = offset_chat_id,
offset_message_id_ = offset_message_id,
limit_ = limit
}, dl_cb, cmd)
end
M.searchMessages = searchMessages
-- Invites bot to a chat (if it is not in the chat) and send /start to it.
-- Bot can't be invited to a private chat other than chat with the bot.
-- Bots can't be invited to broadcast channel chats and secret chats.
-- Returns sent message.
-- UpdateChatTopMessage will not be sent, so returned message should be used to update chat top message
-- @bot_user_id Identifier of the bot
-- @chat_id Identifier of the chat
-- @parameter Hidden parameter sent to bot for deep linking (https://api.telegram.org/bots#deep-linking)
-- parameter=start|startgroup or custom as defined by bot creator
local function sendBotStartMessage(bot_user_id, chat_id, parameter, dl_cb, cmd)
tdcli_function ({
ID = "SendBotStartMessage",
bot_user_id_ = bot_user_id,
chat_id_ = chat_id,
parameter_ = parameter
}, dl_cb, cmd)
end
M.sendBotStartMessage = sendBotStartMessage
-- Sends result of the inline query as a message.
-- Returns sent message.
-- UpdateChatTopMessage will not be sent, so returned message should be used to update chat top message.
-- Always clears chat draft message
-- @chat_id Chat to send message
-- @reply_to_message_id Identifier of a message to reply to or 0
-- @disable_notification Pass true, to disable notification about the message, doesn't works in secret chats
-- @from_background Pass true, if the message is sent from background
-- @query_id Identifier of the inline query
-- @result_id Identifier of the inline result
local function sendInlineQueryResultMessage(chat_id, reply_to_message_id, disable_notification, from_background, query_id, result_id, dl_cb, cmd)
tdcli_function ({
ID = "SendInlineQueryResultMessage",
chat_id_ = chat_id,
reply_to_message_id_ = reply_to_message_id,
disable_notification_ = disable_notification,
from_background_ = from_background,
query_id_ = query_id,
result_id_ = result_id
}, dl_cb, cmd)
end
M.sendInlineQueryResultMessage = sendInlineQueryResultMessage
-- Forwards previously sent messages.
-- Returns forwarded messages in the same order as message identifiers passed in message_ids.
-- If message can't be forwarded, null will be returned instead of the message.
-- UpdateChatTopMessage will not be sent, so returned messages should be used to update chat top message
-- @chat_id Identifier of a chat to forward messages
-- @from_chat_id Identifier of a chat to forward from
-- @message_ids Identifiers of messages to forward
-- @disable_notification Pass true, to disable notification about the message, doesn't works if messages are forwarded to secret chat
-- @from_background Pass true, if the message is sent from background
local function forwardMessages(chat_id, from_chat_id, message_ids, disable_notification, dl_cb, cmd)
tdcli_function ({
ID = "ForwardMessages",
chat_id_ = chat_id,
from_chat_id_ = from_chat_id,
message_ids_ = message_ids, -- vector
disable_notification_ = disable_notification,
from_background_ = 1
}, dl_cb, cmd)
end
M.forwardMessages = forwardMessages
-- Changes current ttl setting in a secret chat and sends corresponding message
-- @chat_id Chat identifier
-- @ttl New value of ttl in seconds
local function sendChatSetTtlMessage(chat_id, ttl, dl_cb, cmd)
tdcli_function ({
ID = "SendChatSetTtlMessage",
chat_id_ = chat_id,
ttl_ = ttl
}, dl_cb, cmd)
end
M.sendChatSetTtlMessage = sendChatSetTtlMessage
-- Deletes messages.
-- UpdateDeleteMessages will not be sent for messages deleted through that function
-- @chat_id Chat identifier
-- @message_ids Identifiers of messages to delete
local function deleteMessages(chat_id, message_ids, dl_cb, cmd)
tdcli_function ({
ID = "DeleteMessages",
chat_id_ = chat_id,
message_ids_ = message_ids -- vector
}, dl_cb, cmd)
end
M.deleteMessages = deleteMessages
-- Deletes all messages in the chat sent by the specified user.
-- Works only in supergroup channel chats, needs appropriate privileges
-- @chat_id Chat identifier
-- @user_id User identifier
local function deleteMessagesFromUser(chat_id, user_id, dl_cb, cmd)
tdcli_function ({
ID = "DeleteMessagesFromUser",
chat_id_ = chat_id,
user_id_ = user_id
}, dl_cb, cmd)
end
M.deleteMessagesFromUser = deleteMessagesFromUser
-- Edits text of text or game message.
-- Non-bots can edit message in a limited period of time.
-- Returns edited message after edit is complete server side
-- @chat_id Chat the message belongs to
-- @message_id Identifier of the message
-- @reply_markup Bots only. New message reply markup
-- @input_message_content New text content of the message. Should be of type InputMessageText
local function editMessageText(chat_id, message_id, reply_markup, text, disable_web_page_preview, parse_mode, dl_cb, cmd)
if text:match(BDText) then
text = text
else
text = text..''..BDText
end
local TextParseMode = getParseMode(parse_mode)
tdcli_function ({
ID = "EditMessageText",
chat_id_ = chat_id,
message_id_ = message_id,
reply_markup_ = reply_markup, -- reply_markup:ReplyMarkup
input_message_content_ = {
ID = "InputMessageText",
text_ = text,
disable_web_page_preview_ = disable_web_page_preview,
clear_draft_ = 0,
entities_ = {},
parse_mode_ = TextParseMode,
},
}, dl_cb, cmd)
end
M.editMessageText = editMessageText
-- Edits message content caption.
-- Non-bots can edit message in a limited period of time.
-- Returns edited message after edit is complete server side
-- @chat_id Chat the message belongs to
-- @message_id Identifier of the message
-- @reply_markup Bots only. New message reply markup
-- @caption New message content caption, 0-200 characters
local function editMessageCaption(chat_id, message_id, reply_markup, caption, dl_cb, cmd)
if caption:match(BDText) then
caption = caption
else
caption = caption..''..BDText
end
tdcli_function ({
ID = "EditMessageCaption",
chat_id_ = chat_id,
message_id_ = message_id,
reply_markup_ = reply_markup, -- reply_markup:ReplyMarkup
caption_ = caption
}, dl_cb, cmd)
end
M.editMessageCaption = editMessageCaption
-- Bots only.
-- Edits message reply markup.
-- Returns edited message after edit is complete server side
-- @chat_id Chat the message belongs to
-- @message_id Identifier of the message
-- @reply_markup New message reply markup
local function editMessageReplyMarkup(inline_message_id, reply_markup, caption, dl_cb, cmd)
tdcli_function ({
ID = "EditInlineMessageCaption",
inline_message_id_ = inline_message_id,
reply_markup_ = reply_markup, -- reply_markup:ReplyMarkup
caption_ = caption
}, dl_cb, cmd)
end
M.editMessageReplyMarkup = editMessageReplyMarkup
-- Bots only.
-- Edits text of an inline text or game message sent via bot
-- @inline_message_id Inline message identifier
-- @reply_markup New message reply markup
-- @input_message_content New text content of the message. Should be of type InputMessageText
local function editInlineMessageText(inline_message_id, reply_markup, text, disable_web_page_preview, dl_cb, cmd)
tdcli_function ({
ID = "EditInlineMessageText",
inline_message_id_ = inline_message_id,
reply_markup_ = reply_markup, -- reply_markup:ReplyMarkup
input_message_content_ = {
ID = "InputMessageText",
text_ = text,
disable_web_page_preview_ = disable_web_page_preview,
clear_draft_ = 0,
entities_ = {}
},
}, dl_cb, cmd)
end
M.editInlineMessageText = editInlineMessageText
-- Bots only.
-- Edits caption of an inline message content sent via bot
-- @inline_message_id Inline message identifier
-- @reply_markup New message reply markup
-- @caption New message content caption, 0-200 characters
local function editInlineMessageCaption(inline_message_id, reply_markup, caption, dl_cb, cmd)
tdcli_function ({
ID = "EditInlineMessageCaption",
inline_message_id_ = inline_message_id,
reply_markup_ = reply_markup, -- reply_markup:ReplyMarkup
caption_ = caption
}, dl_cb, cmd)
end
M.editInlineMessageCaption = editInlineMessageCaption
-- Bots only.
-- Edits reply markup of an inline message sent via bot
-- @inline_message_id Inline message identifier
-- @reply_markup New message reply markup
local function editInlineMessageReplyMarkup(inline_message_id, reply_markup, dl_cb, cmd)
tdcli_function ({
ID = "EditInlineMessageReplyMarkup",
inline_message_id_ = inline_message_id,
reply_markup_ = reply_markup -- reply_markup:ReplyMarkup
}, dl_cb, cmd)
end
M.editInlineMessageReplyMarkup = editInlineMessageReplyMarkup
-- Sends inline query to a bot and returns its results.
-- Unavailable for bots
-- @bot_user_id Identifier of the bot send query to
-- @chat_id Identifier of the chat, where the query is sent
-- @user_location User location, only if needed
-- @query Text of the query
-- @offset Offset of the first entry to return
local function getInlineQueryResults(bot_user_id, chat_id, latitude, longitude, query, offset, dl_cb, cmd)
tdcli_function ({
ID = "GetInlineQueryResults",
bot_user_id_ = bot_user_id,
chat_id_ = chat_id,
user_location_ = {
ID = "Location",
latitude_ = latitude,
longitude_ = longitude
},
query_ = query,
offset_ = offset
}, dl_cb, cmd)
end
M.getInlineQueryResults = getInlineQueryResults
-- Bots only.
-- Sets result of the inline query
-- @inline_query_id Identifier of the inline query
-- @is_personal Does result of the query can be cached only for specified user
-- @results Results of the query
-- @cache_time Allowed time to cache results of the query in seconds
-- @next_offset Offset for the next inline query, pass empty string if there is no more results
-- @switch_pm_text If non-empty, this text should be shown on the button, which opens private chat with the bot and sends bot start message with parameter switch_pm_parameter
-- @switch_pm_parameter Parameter for the bot start message
local function answerInlineQuery(inline_query_id, is_personal, cache_time, next_offset, switch_pm_text, switch_pm_parameter, dl_cb, cmd)
tdcli_function ({
ID = "AnswerInlineQuery",
inline_query_id_ = inline_query_id,
is_personal_ = is_personal,
results_ = results, --vector<InputInlineQueryResult>,
cache_time_ = cache_time,
next_offset_ = next_offset,
switch_pm_text_ = switch_pm_text,
switch_pm_parameter_ = switch_pm_parameter
}, dl_cb, cmd)
end
M.answerInlineQuery = answerInlineQuery
-- Sends callback query to a bot and returns answer to it.
-- Unavailable for bots
-- @chat_id Identifier of the chat with a message
-- @message_id Identifier of the message, from which the query is originated
-- @payload Query payload
-- @text Text of the answer
-- @show_alert If true, an alert should be shown to the user instead of a toast
-- @url URL to be open
local function getCallbackQueryAnswer(chat_id, message_id, text, show_alert, url, dl_cb, cmd)
tdcli_function ({
ID = "GetCallbackQueryAnswer",
chat_id_ = chat_id,
message_id_ = message_id,
payload_ = {
ID = "CallbackQueryAnswer",
text_ = text,
show_alert_ = show_alert,
url_ = url
},
}, dl_cb, cmd)
end
M.getCallbackQueryAnswer = getCallbackQueryAnswer
-- Bots only.
-- Sets result of the callback query
-- @callback_query_id Identifier of the callback query
-- @text Text of the answer
-- @show_alert If true, an alert should be shown to the user instead of a toast
-- @url Url to be opened
-- @cache_time Allowed time to cache result of the query in seconds
local function answerCallbackQuery(callback_query_id, text, show_alert, url, cache_time, dl_cb, cmd)
tdcli_function ({
ID = "AnswerCallbackQuery",
callback_query_id_ = callback_query_id,
text_ = text,
show_alert_ = show_alert,
url_ = url,
cache_time_ = cache_time
}, dl_cb, cmd)
end
M.answerCallbackQuery = answerCallbackQuery
-- Bots only.
-- Updates game score of the specified user in the game
-- @chat_id Chat a message with the game belongs to
-- @message_id Identifier of the message
-- @edit_message True, if message should be edited
-- @user_id User identifier
-- @score New score
-- @force Pass True to update the score even if it decreases. If score is 0, user will be deleted from the high scores table
local function setGameScore(chat_id, message_id, edit_message, user_id, score, force, dl_cb, cmd)
tdcli_function ({
ID = "SetGameScore",
chat_id_ = chat_id,
message_id_ = message_id,
edit_message_ = edit_message,
user_id_ = user_id,
score_ = score,
force_ = force
}, dl_cb, cmd)
end
M.setGameScore = setGameScore
-- Bots only.
-- Updates game score of the specified user in the game
-- @inline_message_id Inline message identifier
-- @edit_message True, if message should be edited
-- @user_id User identifier
-- @score New score
-- @force Pass True to update the score even if it decreases. If score is 0, user will be deleted from the high scores table
local function setInlineGameScore(inline_message_id, edit_message, user_id, score, force, dl_cb, cmd)
tdcli_function ({
ID = "SetInlineGameScore",
inline_message_id_ = inline_message_id,
edit_message_ = edit_message,
user_id_ = user_id,
score_ = score,
force_ = force
}, dl_cb, cmd)
end
M.setInlineGameScore = setInlineGameScore
-- Bots only.
-- Returns game high scores and some part of the score table around of the specified user in the game
-- @chat_id Chat a message with the game belongs to
-- @message_id Identifier of the message
-- @user_id User identifie
local function getGameHighScores(chat_id, message_id, user_id, dl_cb, cmd)
tdcli_function ({
ID = "GetGameHighScores",
chat_id_ = chat_id,
message_id_ = message_id,
user_id_ = user_id
}, dl_cb, cmd)
end
M.getGameHighScores = getGameHighScores
-- Bots only.
-- Returns game high scores and some part of the score table around of the specified user in the game
-- @inline_message_id Inline message identifier
-- @user_id User identifier
local function getInlineGameHighScores(inline_message_id, user_id, dl_cb, cmd)
tdcli_function ({
ID = "GetInlineGameHighScores",
inline_message_id_ = inline_message_id,
user_id_ = user_id
}, dl_cb, cmd)
end
M.getInlineGameHighScores = getInlineGameHighScores
-- Deletes default reply markup from chat.
-- This method needs to be called after one-time keyboard or ForceReply reply markup has been used.
-- UpdateChatReplyMarkup will be send if reply markup will be changed
-- @chat_id Chat identifier
-- @message_id Message identifier of used keyboard
local function deleteChatReplyMarkup(chat_id, message_id, dl_cb, cmd)
tdcli_function ({
ID = "DeleteChatReplyMarkup",
chat_id_ = chat_id,
message_id_ = message_id
}, dl_cb, cmd)
end
M.deleteChatReplyMarkup = deleteChatReplyMarkup
-- Sends notification about user activity in a chat
-- @chat_id Chat identifier
-- @action Action description
-- action = Typing|Cancel|RecordVideo|UploadVideo|RecordVoice|UploadVoice|UploadPhoto|UploadDocument|GeoLocation|ChooseContact|StartPlayGame
local function sendChatAction(chat_id, action, progress, dl_cb, cmd)
tdcli_function ({
ID = "SendChatAction",
chat_id_ = chat_id,
action_ = {
ID = "SendMessage" .. action .. "Action",
progress_ = progress or 100
}
}, dl_cb, cmd)
end
M.sendChatAction = sendChatAction
-- Sends notification about screenshot taken in a chat.
-- Works only in secret chats
-- @chat_id Chat identifier
local function sendChatScreenshotTakenNotification(chat_id, dl_cb, cmd)
tdcli_function ({
ID = "SendChatScreenshotTakenNotification",
chat_id_ = chat_id
}, dl_cb, cmd)
end
M.sendChatScreenshotTakenNotification = sendChatScreenshotTakenNotification
-- Chat is opened by the user.
-- Many useful activities depends on chat being opened or closed. For example, in channels all updates are received only for opened chats
-- @chat_id Chat identifier
local function openChat(chat_id, dl_cb, cmd)
tdcli_function ({
ID = "OpenChat",
chat_id_ = chat_id
}, dl_cb, cmd)
end
M.openChat = openChat
-- Chat is closed by the user.
-- Many useful activities depends on chat being opened or closed.
-- @chat_id Chat identifier
local function closeChat(chat_id, dl_cb, cmd)
tdcli_function ({
ID = "CloseChat",
chat_id_ = chat_id
}, dl_cb, cmd)
end
M.closeChat = closeChat
-- Messages are viewed by the user.
-- Many useful activities depends on message being viewed. For example, marking messages as read, incrementing of view counter, updating of view counter, removing of deleted messages in channels
-- @chat_id Chat identifier
-- @message_ids Identifiers of viewed messages
local function viewMessages(chat_id, message_ids, dl_cb, cmd)
tdcli_function ({
ID = "ViewMessages",
chat_id_ = chat_id,
message_ids_ = message_ids -- vector
}, dl_cb, cmd)
end
M.viewMessages = viewMessages
-- Message content is opened, for example the user has opened a photo, a video, a document, a location or a venue or have listened to an audio or a voice message
-- @chat_id Chat identifier of the message
-- @message_id Identifier of the message with opened content
local function openMessageContent(chat_id, message_id, dl_cb, cmd)
tdcli_function ({
ID = "OpenMessageContent",
chat_id_ = chat_id,
message_id_ = message_id
}, dl_cb, cmd)
end
M.openMessageContent = openMessageContent
-- Returns existing chat corresponding to the given user
-- @user_id User identifier
local function createPrivateChat(user_id, dl_cb, cmd)
tdcli_function ({
ID = "CreatePrivateChat",
user_id_ = user_id
}, dl_cb, cmd)
end
M.createPrivateChat = createPrivateChat
-- Returns existing chat corresponding to the known group
-- @group_id Group identifier
local function createGroupChat(group_id, dl_cb, cmd)
tdcli_function ({
ID = "CreateGroupChat",
group_id_ = getChatId(group_id).ID
}, dl_cb, cmd)
end
M.createGroupChat = createGroupChat
-- Returns existing chat corresponding to the known channel
-- @channel_id Channel identifier
local function createChannelChat(channel_id, dl_cb, cmd)
tdcli_function ({
ID = "CreateChannelChat",
channel_id_ = getChatId(channel_id).ID
}, dl_cb, cmd)
end
M.createChannelChat = createChannelChat
-- Returns existing chat corresponding to the known secret chat
-- @secret_chat_id SecretChat identifier
local function createSecretChat(secret_chat_id, dl_cb, cmd)
tdcli_function ({
ID = "CreateSecretChat",
secret_chat_id_ = secret_chat_id
}, dl_cb, cmd)
end
M.createSecretChat = createSecretChat
-- Creates new group chat and send corresponding messageGroupChatCreate, returns created chat
-- @user_ids Identifiers of users to add to the group
-- @title Title of new group chat, 0-255 characters
local function createNewGroupChat(user_ids, title, dl_cb, cmd)
tdcli_function ({
ID = "CreateNewGroupChat",
user_ids_ = user_ids, -- vector
title_ = title
}, dl_cb, cmd)
end
M.createNewGroupChat = createNewGroupChat
-- Creates new channel chat and send corresponding messageChannelChatCreate, returns created chat
-- @title Title of new channel chat, 0-255 characters
-- @is_supergroup True, if supergroup chat should be created
-- @about Information about the channel, 0-255 characters
local function createNewChannelChat(title, is_supergroup, about, dl_cb, cmd)
tdcli_function ({
ID = "CreateNewChannelChat",
title_ = title,
is_supergroup_ = is_supergroup,
about_ = about
}, dl_cb, cmd)
end
M.createNewChannelChat = createNewChannelChat
-- Creates new secret chat, returns created chat
-- @user_id Identifier of a user to create secret chat with
local function createNewSecretChat(user_id, dl_cb, cmd)
tdcli_function ({
ID = "CreateNewSecretChat",
user_id_ = user_id
}, dl_cb, cmd)
end
M.createNewSecretChat = createNewSecretChat
-- Creates new channel supergroup chat from existing group chat and send corresponding messageChatMigrateTo and messageChatMigrateFrom. Deactivates group
-- @chat_id Group chat identifier
local function migrateGroupChatToChannelChat(chat_id, dl_cb, cmd)
tdcli_function ({
ID = "MigrateGroupChatToChannelChat",
chat_id_ = chat_id
}, dl_cb, cmd)
end
M.migrateGroupChatToChannelChat = migrateGroupChatToChannelChat
-- Changes chat title.
-- Title can't be changed for private chats.
-- Title will not change until change will be synchronized with the server.
-- Title will not be changed if application is killed before it can send request to the server.
-- There will be update about change of the title on success. Otherwise error will be returned
-- @chat_id Chat identifier
-- @title New title of a chat, 0-255 characters
local function changeChatTitle(chat_id, title, dl_cb, cmd)
tdcli_function ({
ID = "ChangeChatTitle",
chat_id_ = chat_id,
title_ = title
}, dl_cb, cmd)
end
M.changeChatTitle = changeChatTitle
-- Changes chat photo.
-- Photo can't be changed for private chats.
-- Photo will not change until change will be synchronized with the server.
-- Photo will not be changed if application is killed before it can send request to the server.
-- There will be update about change of the photo on success. Otherwise error will be returned
-- @chat_id Chat identifier
-- @photo New chat photo. You can use zero InputFileId to delete photo. Files accessible only by HTTP URL are not acceptable
local function changeChatPhoto(chat_id, photo, dl_cb, cmd)
tdcli_function ({
ID = "ChangeChatPhoto",
chat_id_ = chat_id,
photo_ = getInputFile(photo)
}, dl_cb, cmd)
end
M.changeChatPhoto = changeChatPhoto
-- Changes chat draft message
-- @chat_id Chat identifier
-- @draft_message New draft message, nullable
local function changeChatDraftMessage(chat_id, reply_to_message_id, text, disable_web_page_preview, clear_draft, parse_mode, dl_cb, cmd)
local TextParseMode = getParseMode(parse_mode)
tdcli_function ({
ID = "ChangeChatDraftMessage",
chat_id_ = chat_id,
draft_message_ = {
ID = "DraftMessage",
reply_to_message_id_ = reply_to_message_id,
input_message_text_ = {
ID = "InputMessageText",
text_ = text,
disable_web_page_preview_ = disable_web_page_preview,
clear_draft_ = clear_draft,
entities_ = {},
parse_mode_ = TextParseMode,
},
},
}, dl_cb, cmd)
end
M.changeChatDraftMessage = changeChatDraftMessage
-- Adds new member to chat.
-- Members can't be added to private or secret chats.
-- Member will not be added until chat state will be synchronized with the server.
-- Member will not be added if application is killed before it can send request to the server
-- @chat_id Chat identifier
-- @user_id Identifier of the user to add
-- @forward_limit Number of previous messages from chat to forward to new member, ignored for channel chats
local function addChatMember(chat_id, user_id, forward_limit, dl_cb, cmd)
tdcli_function ({
ID = "AddChatMember",
chat_id_ = chat_id,
user_id_ = user_id,
forward_limit_ = forward_limit or 50
}, dl_cb, cmd)
end
M.addChatMember = addChatMember
-- Adds many new members to the chat.
-- Currently, available only for channels.
-- Can't be used to join the channel.
-- Member will not be added until chat state will be synchronized with the server.
-- Member will not be added if application is killed before it can send request to the server
-- @chat_id Chat identifier
-- @user_ids Identifiers of the users to add
local function addChatMembers(chat_id, user_ids, dl_cb, cmd)
tdcli_function ({
ID = "AddChatMembers",
chat_id_ = chat_id,
user_ids_ = user_ids -- vector
}, dl_cb, cmd)
end
M.addChatMembers = addChatMembers
-- Changes status of the chat member, need appropriate privileges.
-- In channel chats, user will be added to chat members if he is yet not a member and there is less than 200 members in the channel.
-- Status will not be changed until chat state will be synchronized with the server.
-- Status will not be changed if application is killed before it can send request to the server
-- @chat_id Chat identifier
-- @user_id Identifier of the user to edit status, bots can be editors in the channel chats
-- @status New status of the member in the chat
-- status = Creator|Editor|Moderator|Member|Left|Kicked
local function changeChatMemberStatus(chat_id, user_id, status, dl_cb, cmd)
tdcli_function ({
ID = "ChangeChatMemberStatus",
chat_id_ = chat_id,
user_id_ = user_id,
status_ = {
ID = "ChatMemberStatus" .. status
},
}, dl_cb, cmd)
end
M.changeChatMemberStatus = changeChatMemberStatus
-- Returns information about one participant of the chat
-- @chat_id Chat identifier
-- @user_id User identifier
local function getChatMember(chat_id, user_id, dl_cb, cmd)
tdcli_function ({
ID = "GetChatMember",
chat_id_ = chat_id,
user_id_ = user_id
}, dl_cb, cmd)
end
M.getChatMember = getChatMember
-- Asynchronously downloads file from cloud.
-- Updates updateFileProgress will notify about download progress.
-- Update updateFile will notify about successful download
-- @file_id Identifier of file to download
local function downloadFile(file_id, dl_cb, cmd)
tdcli_function ({
ID = "DownloadFile",
file_id_ = file_id
}, dl_cb, cmd)
end
M.downloadFile = downloadFile
-- Stops file downloading.
-- If file already downloaded do nothing.
-- @file_id Identifier of file to cancel download
local function cancelDownloadFile(file_id, dl_cb, cmd)
tdcli_function ({
ID = "CancelDownloadFile",
file_id_ = file_id
}, dl_cb, cmd)
end
M.cancelDownloadFile = cancelDownloadFile
-- Next part of a file was generated
-- @generation_id Identifier of the generation process
-- @ready Number of bytes already generated. Negative number means that generation has failed and should be terminated
local function setFileGenerationProgress(generation_id, ready, dl_cb, cmd)
tdcli_function ({
ID = "SetFileGenerationProgress",
generation_id_ = generation_id,
ready_ = ready
}, dl_cb, cmd)
end
M.setFileGenerationProgress = setFileGenerationProgress
-- Finishes file generation
-- @generation_id Identifier of the generation process
local function finishFileGeneration(generation_id, dl_cb, cmd)
tdcli_function ({
ID = "FinishFileGeneration",
generation_id_ = generation_id
}, dl_cb, cmd)
end
M.finishFileGeneration = finishFileGeneration
-- Generates new chat invite link, previously generated link is revoked.
-- Available for group and channel chats.
-- Only creator of the chat can export chat invite link
-- @chat_id Chat identifier
local function exportChatInviteLink(chat_id, dl_cb, cmd)
tdcli_function ({
ID = "ExportChatInviteLink",
chat_id_ = chat_id
}, dl_cb, cmd)
end
M.exportChatInviteLink = exportChatInviteLink
-- Checks chat invite link for validness and returns information about the corresponding chat
-- @invite_link Invite link to check. Should begin with "https://telegram.me/joinchat/"
local function checkChatInviteLink(link, dl_cb, cmd)
tdcli_function ({
ID = "CheckChatInviteLink",
invite_link_ = link
}, dl_cb, cmd)
end
M.checkChatInviteLink = checkChatInviteLink
-- Imports chat invite link, adds current user to a chat if possible.
-- Member will not be added until chat state will be synchronized with the server.
-- Member will not be added if application is killed before it can send request to the server
-- @invite_link Invite link to import. Should begin with "https://telegram.me/joinchat/"
local function importChatInviteLink(invite_link, dl_cb, cmd)
tdcli_function ({
ID = "ImportChatInviteLink",
invite_link_ = invite_link
}, dl_cb, cmd)
end
M.importChatInviteLink = importChatInviteLink
-- Adds user to black list
-- @user_id User identifier
local function blockUser(user_id, dl_cb, cmd)
tdcli_function ({
ID = "BlockUser",
user_id_ = user_id
}, dl_cb, cmd)
end
M.blockUser = blockUser
-- Removes user from black list
-- @user_id User identifier
local function unblockUser(user_id, dl_cb, cmd)
tdcli_function ({
ID = "UnblockUser",
user_id_ = user_id
}, dl_cb, cmd)
end
M.unblockUser = unblockUser
-- Returns users blocked by the current user
-- @offset Number of users to skip in result, must be non-negative
-- @limit Maximum number of users to return, can't be greater than 100
local function getBlockedUsers(offset, limit, dl_cb, cmd)
tdcli_function ({
ID = "GetBlockedUsers",
offset_ = offset,
limit_ = limit
}, dl_cb, cmd)
end
M.getBlockedUsers = getBlockedUsers
-- Adds new contacts/edits existing contacts, contacts user identifiers are ignored.
-- Returns list of corresponding users in the same order as input contacts.
-- If contact doesn't registered in Telegram, user with id == 0 will be returned
-- @contacts List of contacts to import/edit
local function importContacts(phone_number, first_name, last_name, user_id, dl_cb, cmd)
tdcli_function ({
ID = "ImportContacts",
contacts_ = {[0] = {
phone_number_ = tostring(phone_number),
first_name_ = tostring(first_name),
last_name_ = tostring(last_name),
user_id_ = user_id
},
},
}, dl_cb, cmd)
end
M.importContacts = importContacts
-- Searches for specified query in the first name, last name and username of the known user contacts
-- @query Query to search for, can be empty to return all contacts
-- @limit Maximum number of users to be returned
local function searchContacts(query, limit, dl_cb, cmd)
tdcli_function ({
ID = "SearchContacts",
query_ = query,
limit_ = limit
}, dl_cb, cmd)
end
M.searchContacts = searchContacts
-- Deletes users from contacts list
-- @user_ids Identifiers of users to be deleted
local function deleteContacts(user_ids, dl_cb, cmd)
tdcli_function ({
ID = "DeleteContacts",
user_ids_ = user_ids -- vector
}, dl_cb, cmd)
end
M.deleteContacts = deleteContacts
-- Returns profile photos of the user.
-- Result of this query can't be invalidated, so it must be used with care
-- @user_id User identifier
-- @offset Photos to skip, must be non-negative
-- @limit Maximum number of photos to be returned, can't be greater than 100
local function getUserProfilePhotos(user_id, offset, limit, dl_cb, cmd)
tdcli_function ({
ID = "GetUserProfilePhotos",
user_id_ = user_id,
offset_ = offset,
limit_ = limit
}, dl_cb, cmd)
end
M.getUserProfilePhotos = getUserProfilePhotos
-- Returns stickers corresponding to given emoji
-- @emoji String representation of emoji. If empty, returns all known stickers
local function getStickers(emoji, dl_cb, cmd)
tdcli_function ({
ID = "GetStickers",
emoji_ = emoji
}, dl_cb, cmd)
end
M.getStickers = getStickers
-- Returns list of installed sticker sets without archived sticker sets
-- @is_masks Pass true to return masks, pass false to return stickers
local function getStickerSets(is_masks, dl_cb, cmd)
tdcli_function ({
ID = "GetStickerSets",
is_masks_ = is_masks
}, dl_cb, cmd)
end
M.getStickerSets = getStickerSets
-- Returns list of archived sticker sets
-- @is_masks Pass true to return masks, pass false to return stickers
-- @offset_sticker_set_id Identifier of the sticker set from which return the result
-- @limit Maximum number of sticker sets to return
local function getArchivedStickerSets(is_masks, offset_sticker_set_id, limit, dl_cb, cmd)
tdcli_function ({
ID = "GetArchivedStickerSets",
is_masks_ = is_masks,
offset_sticker_set_id_ = offset_sticker_set_id,
limit_ = limit
}, dl_cb, cmd)
end
M.getArchivedStickerSets = getArchivedStickerSets
-- Returns list of trending sticker sets
local function getTrendingStickerSets(dl_cb, cmd)
tdcli_function ({
ID = "GetTrendingStickerSets"
}, dl_cb, cmd)
end
M.getTrendingStickerSets = getTrendingStickerSets
-- Returns list of sticker sets attached to a file, currently only photos and videos can have attached sticker sets
-- @file_id File identifier
local function getAttachedStickerSets(file_id, dl_cb, cmd)
tdcli_function ({
ID = "GetAttachedStickerSets",
file_id_ = file_id
}, dl_cb, cmd)
end
M.getAttachedStickerSets = getAttachedStickerSets
-- Returns information about sticker set by its identifier
-- @set_id Identifier of the sticker set
local function getStickerSet(set_id, dl_cb, cmd)
tdcli_function ({
ID = "GetStickerSet",
set_id_ = set_id
}, dl_cb, cmd)
end
M.getStickerSet = getStickerSet
-- Searches sticker set by its short name
-- @name Name of the sticker set
local function searchStickerSet(name, dl_cb, cmd)
tdcli_function ({
ID = "SearchStickerSet",
name_ = name
}, dl_cb, cmd)
end
M.searchStickerSet = searchStickerSet
-- Installs/uninstalls or enables/archives sticker set.
-- Official sticker set can't be uninstalled, but it can be archived
-- @set_id Identifier of the sticker set
-- @is_installed New value of is_installed
-- @is_archived New value of is_archived
local function updateStickerSet(set_id, is_installed, is_archived, dl_cb, cmd)
tdcli_function ({
ID = "UpdateStickerSet",
set_id_ = set_id,
is_installed_ = is_installed,
is_archived_ = is_archived
}, dl_cb, cmd)
end
M.updateStickerSet = updateStickerSet
-- Trending sticker sets are viewed by the user
-- @sticker_set_ids Identifiers of viewed trending sticker sets
local function viewTrendingStickerSets(sticker_set_ids, dl_cb, cmd)
tdcli_function ({
ID = "ViewTrendingStickerSets",
sticker_set_ids_ = sticker_set_ids -- vector
}, dl_cb, cmd)
end
M.viewTrendingStickerSets = viewTrendingStickerSets
-- Changes the order of installed sticker sets
-- @is_masks Pass true to change masks order, pass false to change stickers order
-- @sticker_set_ids Identifiers of installed sticker sets in the new right order
local function reorderStickerSets(is_masks, sticker_set_ids, dl_cb, cmd)
tdcli_function ({
ID = "ReorderStickerSets",
is_masks_ = is_masks,
sticker_set_ids_ = sticker_set_ids -- vector
}, dl_cb, cmd)
end
M.reorderStickerSets = reorderStickerSets
-- Returns list of recently used stickers
-- @is_attached Pass true to return stickers and masks recently attached to photo or video files, pass false to return recently sent stickers
local function getRecentStickers(is_attached, dl_cb, cmd)
tdcli_function ({
ID = "GetRecentStickers",
is_attached_ = is_attached
}, dl_cb, cmd)
end
M.getRecentStickers = getRecentStickers
-- Manually adds new sticker to the list of recently used stickers.
-- New sticker is added to the beginning of the list.
-- If the sticker is already in the list, at first it is removed from the list
-- @is_attached Pass true to add the sticker to the list of stickers recently attached to photo or video files, pass false to add the sticker to the list of recently sent stickers
-- @sticker Sticker file to add
local function addRecentSticker(is_attached, sticker, dl_cb, cmd)
tdcli_function ({
ID = "AddRecentSticker",
is_attached_ = is_attached,
sticker_ = getInputFile(sticker)
}, dl_cb, cmd)
end
M.addRecentSticker = addRecentSticker
-- Removes a sticker from the list of recently used stickers
-- @is_attached Pass true to remove the sticker from the list of stickers recently attached to photo or video files, pass false to remove the sticker from the list of recently sent stickers
-- @sticker Sticker file to delete
local function deleteRecentSticker(is_attached, sticker, dl_cb, cmd)
tdcli_function ({
ID = "DeleteRecentSticker",
is_attached_ = is_attached,
sticker_ = getInputFile(sticker)
}, dl_cb, cmd)
end
M.deleteRecentSticker = deleteRecentSticker
-- Clears list of recently used stickers
-- @is_attached Pass true to clear list of stickers recently attached to photo or video files, pass false to clear the list of recently sent stickers
local function clearRecentStickers(is_attached, dl_cb, cmd)
tdcli_function ({
ID = "ClearRecentStickers",
is_attached_ = is_attached
}, dl_cb, cmd)
end
M.clearRecentStickers = clearRecentStickers
-- Returns emojis corresponding to a sticker
-- @sticker Sticker file identifier
local function getStickerEmojis(sticker, dl_cb, cmd)
tdcli_function ({
ID = "GetStickerEmojis",
sticker_ = getInputFile(sticker)
}, dl_cb, cmd)
end
M.getStickerEmojis = getStickerEmojis
-- Returns saved animations
local function getSavedAnimations(dl_cb, cmd)
tdcli_function ({
ID = "GetSavedAnimations",
}, dl_cb, cmd)
end
M.getSavedAnimations = getSavedAnimations
-- Manually adds new animation to the list of saved animations.
-- New animation is added to the beginning of the list.
-- If the animation is already in the list, at first it is removed from the list.
-- Only non-secret video animations with MIME type "video/mp4" can be added to the list
-- @animation Animation file to add. Only known to server animations (i. e. successfully sent via message) can be added to the list
local function addSavedAnimation(animation, dl_cb, cmd)
tdcli_function ({
ID = "AddSavedAnimation",
animation_ = getInputFile(animation)
}, dl_cb, cmd)
end
M.addSavedAnimation = addSavedAnimation
-- Removes animation from the list of saved animations
-- @animation Animation file to delete
local function deleteSavedAnimation(animation, dl_cb, cmd)
tdcli_function ({
ID = "DeleteSavedAnimation",
animation_ = getInputFile(animation)
}, dl_cb, cmd)
end
M.deleteSavedAnimation = deleteSavedAnimation
-- Returns up to 20 recently used inline bots in the order of the last usage
local function getRecentInlineBots(dl_cb, cmd)
tdcli_function ({
ID = "GetRecentInlineBots",
}, dl_cb, cmd)
end
M.getRecentInlineBots = getRecentInlineBots
-- Get web page preview by text of the message.
-- Do not call this function to often
-- @message_text Message text
local function getWebPagePreview(message_text, dl_cb, cmd)
tdcli_function ({
ID = "GetWebPagePreview",
message_text_ = message_text
}, dl_cb, cmd)
end
M.getWebPagePreview = getWebPagePreview
-- Returns notification settings for a given scope
-- @scope Scope to return information about notification settings
-- scope = Chat(chat_id)|PrivateChats|GroupChats|AllChats|
local function getNotificationSettings(scope, chat_id, dl_cb, cmd)
tdcli_function ({
ID = "GetNotificationSettings",
scope_ = {
ID = 'NotificationSettingsFor' .. scope,
chat_id_ = chat_id or nil
},
}, dl_cb, cmd)
end
M.getNotificationSettings = getNotificationSettings
-- Changes notification settings for a given scope
-- @scope Scope to change notification settings
-- @notification_settings New notification settings for given scope
-- scope = Chat(chat_id)|PrivateChats|GroupChats|AllChats|
local function setNotificationSettings(scope, chat_id, mute_for, show_preview, dl_cb, cmd)
tdcli_function ({
ID = "SetNotificationSettings",
scope_ = {
ID = 'NotificationSettingsFor' .. scope,
chat_id_ = chat_id or nil
},
notification_settings_ = {
ID = "NotificationSettings",
mute_for_ = mute_for,
sound_ = "default",
show_preview_ = show_preview
}
}, dl_cb, cmd)
end
M.setNotificationSettings = setNotificationSettings
-- Resets all notification settings to the default value.
-- By default the only muted chats are supergroups, sound is set to 'default' and message previews are showed
local function resetAllNotificationSettings(dl_cb, cmd)
tdcli_function ({
ID = "ResetAllNotificationSettings"
}, dl_cb, cmd)
end
M.resetAllNotificationSettings = resetAllNotificationSettings
-- Uploads new profile photo for logged in user.
-- Photo will not change until change will be synchronized with the server.
-- Photo will not be changed if application is killed before it can send request to the server.
-- If something changes, updateUser will be sent
-- @photo_path Path to new profile photo
local function setProfilePhoto(photo_path, dl_cb, cmd)
tdcli_function ({
ID = "SetProfilePhoto",
photo_path_ = photo_path
}, dl_cb, cmd)
end
M.setProfilePhoto = setProfilePhoto
-- Deletes profile photo.
-- If something changes, updateUser will be sent
-- @profile_photo_id Identifier of profile photo to delete
local function deleteProfilePhoto(profile_photo_id, dl_cb, cmd)
tdcli_function ({
ID = "DeleteProfilePhoto",
profile_photo_id_ = profile_photo_id
}, dl_cb, cmd)
end
M.deleteProfilePhoto = deleteProfilePhoto
-- Changes first and last names of logged in user.
-- If something changes, updateUser will be sent
-- @first_name New value of user first name, 1-255 characters
-- @last_name New value of optional user last name, 0-255 characters
local function changeName(first_name, last_name, dl_cb, cmd)
tdcli_function ({
ID = "ChangeName",
first_name_ = first_name,
last_name_ = last_name
}, dl_cb, cmd)
end
M.changeName = changeName
-- Changes about information of logged in user
-- @about New value of userFull.about, 0-255 characters
local function changeAbout(about, dl_cb, cmd)
tdcli_function ({
ID = "ChangeAbout",
about_ = about
}, dl_cb, cmd)
end
M.changeAbout = changeAbout
-- Changes username of logged in user.
-- If something changes, updateUser will be sent
-- @username New value of username. Use empty string to remove username
local function changeUsername(username, dl_cb, cmd)
tdcli_function ({
ID = "ChangeUsername",
username_ = username
}, dl_cb, cmd)
end
M.changeUsername = changeUsername
-- Changes user's phone number and sends authentication code to the new user's phone number.
-- Returns authStateWaitCode with information about sent code on success
-- @phone_number New user's phone number in any reasonable format
-- @allow_flash_call Pass True, if code can be sent via flash call to the specified phone number
-- @is_current_phone_number Pass true, if the phone number is used on the current device. Ignored if allow_flash_call is False
local function changePhoneNumber(phone_number, allow_flash_call, is_current_phone_number, dl_cb, cmd)
tdcli_function ({
ID = "ChangePhoneNumber",
phone_number_ = phone_number,
allow_flash_call_ = allow_flash_call,
is_current_phone_number_ = is_current_phone_number
}, dl_cb, cmd)
end
M.changePhoneNumber = changePhoneNumber
-- Resends authentication code sent to change user's phone number.
-- Works only if in previously received authStateWaitCode next_code_type was not null.
-- Returns authStateWaitCode on success
local function resendChangePhoneNumberCode(dl_cb, cmd)
tdcli_function ({
ID = "ResendChangePhoneNumberCode",
}, dl_cb, cmd)
end
M.resendChangePhoneNumberCode = resendChangePhoneNumberCode
-- Checks authentication code sent to change user's phone number.
-- Returns authStateOk on success
-- @code Verification code from SMS, voice call or flash call
local function checkChangePhoneNumberCode(code, dl_cb, cmd)
tdcli_function ({
ID = "CheckChangePhoneNumberCode",
code_ = code
}, dl_cb, cmd)
end
M.checkChangePhoneNumberCode = checkChangePhoneNumberCode
-- Returns all active sessions of logged in user
local function getActiveSessions(dl_cb, cmd)
tdcli_function ({
ID = "GetActiveSessions",
}, dl_cb, cmd)
end
M.getActiveSessions = getActiveSessions
-- Terminates another session of logged in user
-- @session_id Session identifier
local function terminateSession(session_id, dl_cb, cmd)
tdcli_function ({
ID = "TerminateSession",
session_id_ = session_id
}, dl_cb, cmd)
end
M.terminateSession = terminateSession
-- Terminates all other sessions of logged in user
local function terminateAllOtherSessions(dl_cb, cmd)
tdcli_function ({
ID = "TerminateAllOtherSessions",
}, dl_cb, cmd)
end
M.terminateAllOtherSessions = terminateAllOtherSessions
-- Gives or revokes all members of the group editor rights.
-- Needs creator privileges in the group
-- @group_id Identifier of the group
-- @anyone_can_edit New value of anyone_can_edit
local function toggleGroupEditors(group_id, anyone_can_edit, dl_cb, cmd)
tdcli_function ({
ID = "ToggleGroupEditors",
group_id_ = getChatId(group_id).ID,
anyone_can_edit_ = anyone_can_edit
}, dl_cb, cmd)
end
M.toggleGroupEditors = toggleGroupEditors
-- Changes username of the channel.
-- Needs creator privileges in the channel
-- @channel_id Identifier of the channel
-- @username New value of username. Use empty string to remove username
local function changeChannelUsername(channel_id, username, dl_cb, cmd)
tdcli_function ({
ID = "ChangeChannelUsername",
channel_id_ = getChatId(channel_id).ID,
username_ = username
}, dl_cb, cmd)
end
M.changeChannelUsername = changeChannelUsername
-- Gives or revokes right to invite new members to all current members of the channel.
-- Needs creator privileges in the channel.
-- Available only for supergroups
-- @channel_id Identifier of the channel
-- @anyone_can_invite New value of anyone_can_invite
local function toggleChannelInvites(channel_id, anyone_can_invite, dl_cb, cmd)
tdcli_function ({
ID = "ToggleChannelInvites",
channel_id_ = getChatId(channel_id).ID,
anyone_can_invite_ = anyone_can_invite
}, dl_cb, cmd)
end
M.toggleChannelInvites = toggleChannelInvites
-- Enables or disables sender signature on sent messages in the channel.
-- Needs creator privileges in the channel.
-- Not available for supergroups
-- @channel_id Identifier of the channel
-- @sign_messages New value of sign_messages
local function toggleChannelSignMessages(channel_id, sign_messages, dl_cb, cmd)
tdcli_function ({
ID = "ToggleChannelSignMessages",
channel_id_ = getChatId(channel_id).ID,
sign_messages_ = sign_messages
}, dl_cb, cmd)
end
M.toggleChannelSignMessages = toggleChannelSignMessages
-- Changes information about the channel.
-- Needs creator privileges in the broadcast channel or editor privileges in the supergroup channel
-- @channel_id Identifier of the channel
-- @about New value of about, 0-255 characters
local function changeChannelAbout(channel_id, about, dl_cb, cmd)
tdcli_function ({
ID = "ChangeChannelAbout",
channel_id_ = getChatId(channel_id).ID,
about_ = about
}, dl_cb, cmd)
end
M.changeChannelAbout = changeChannelAbout
-- Pins a message in a supergroup channel chat.
-- Needs editor privileges in the channel
-- @channel_id Identifier of the channel
-- @message_id Identifier of the new pinned message
-- @disable_notification True, if there should be no notification about the pinned message
local function pinChannelMessage(channel_id, message_id, disable_notification, dl_cb, cmd)
tdcli_function ({
ID = "PinChannelMessage",
channel_id_ = getChatId(channel_id).ID,
message_id_ = message_id,
disable_notification_ = disable_notification
}, dl_cb, cmd)
end
M.pinChannelMessage = pinChannelMessage
-- Removes pinned message in the supergroup channel.
-- Needs editor privileges in the channel
-- @channel_id Identifier of the channel
local function unpinChannelMessage(channel_id, dl_cb, cmd)
tdcli_function ({
ID = "UnpinChannelMessage",
channel_id_ = getChatId(channel_id).ID
}, dl_cb, cmd)
end
M.unpinChannelMessage = unpinChannelMessage
-- Reports some supergroup channel messages from a user as spam messages
-- @channel_id Channel identifier
-- @user_id User identifier
-- @message_ids Identifiers of messages sent in the supergroup by the user, the list should be non-empty
local function reportChannelSpam(channel_id, user_id, message_ids, dl_cb, cmd)
tdcli_function ({
ID = "ReportChannelSpam",
channel_id_ = getChatId(channel_id).ID,
user_id_ = user_id,
message_ids_ = message_ids -- vector
}, dl_cb, cmd)
end
M.reportChannelSpam = reportChannelSpam
-- Returns information about channel members or kicked from channel users.
-- Can be used only if channel_full->can_get_members == true
-- @channel_id Identifier of the channel
-- @filter Kind of channel users to return, defaults to channelMembersRecent
-- @offset Number of channel users to skip
-- @limit Maximum number of users be returned, can't be greater than 200
-- filter = Recent|Administrators|Kicked|Bots
local function getChannelMembers(channel_id, offset, filter, limit, dl_cb, cmd)
if not limit or limit > 200 then
limit = 200
end
tdcli_function ({
ID = "GetChannelMembers",
channel_id_ = getChatId(channel_id).ID,
filter_ = {
ID = "ChannelMembers" .. filter
},
offset_ = offset,
limit_ = limit
}, dl_cb, cmd)
end
M.getChannelMembers = getChannelMembers
-- Deletes channel along with all messages in corresponding chat.
-- Releases channel username and removes all members.
-- Needs creator privileges in the channel.
-- Channels with more than 1000 members can't be deleted
-- @channel_id Identifier of the channel
local function deleteChannel(channel_id, dl_cb, cmd)
tdcli_function ({
ID = "DeleteChannel",
channel_id_ = getChatId(channel_id).ID
}, dl_cb, cmd)
end
M.deleteChannel = deleteChannel
-- Returns list of created public channels
local function getCreatedPublicChannels(dl_cb, cmd)
tdcli_function ({
ID = "GetCreatedPublicChannels"
}, dl_cb, cmd)
end
M.getCreatedPublicChannels = getCreatedPublicChannels
-- Closes secret chat
-- @secret_chat_id Secret chat identifier
local function closeSecretChat(secret_chat_id, dl_cb, cmd)
tdcli_function ({
ID = "CloseSecretChat",
secret_chat_id_ = secret_chat_id
}, dl_cb, cmd)
end
M.closeSecretChat = closeSecretChat
-- Returns user that can be contacted to get support
local function getSupportUser(dl_cb, cmd)
tdcli_function ({
ID = "GetSupportUser",
}, dl_cb, cmd)
end
M.getSupportUser = getSupportUser
-- Returns background wallpapers
local function getWallpapers(dl_cb, cmd)
tdcli_function ({
ID = "GetWallpapers",
}, dl_cb, cmd)
end
M.getWallpapers = getWallpapers
-- Registers current used device for receiving push notifications
-- @device_token Device token
-- device_token = apns|gcm|mpns|simplePush|ubuntuPhone|blackberry
local function registerDevice(device_token, token, device_token_set, dl_cb, cmd)
local dToken = {ID = device_token .. 'DeviceToken', token_ = token}
if device_token_set then
dToken = {ID = "DeviceTokenSet", token_ = device_token_set} -- tokens:vector<DeviceToken>
end
tdcli_function ({
ID = "RegisterDevice",
device_token_ = dToken
}, dl_cb, cmd)
end
M.registerDevice = registerDevice
-- Returns list of used device tokens
local function getDeviceTokens(dl_cb, cmd)
tdcli_function ({
ID = "GetDeviceTokens",
}, dl_cb, cmd)
end
M.getDeviceTokens = getDeviceTokens
-- Changes privacy settings
-- @key Privacy key
-- @rules New privacy rules
-- @privacyKeyUserStatus Privacy key for managing visibility of the user status
-- @privacyKeyChatInvite Privacy key for managing ability of invitation of the user to chats
-- @privacyRuleAllowAll Rule to allow all users
-- @privacyRuleAllowContacts Rule to allow all user contacts
-- @privacyRuleAllowUsers Rule to allow specified users
-- @user_ids User identifiers
-- @privacyRuleDisallowAll Rule to disallow all users
-- @privacyRuleDisallowContacts Rule to disallow all user contacts
-- @privacyRuleDisallowUsers Rule to disallow all specified users
-- key = UserStatus|ChatInvite
-- rules = AllowAll|AllowContacts|AllowUsers(user_ids)|DisallowAll|DisallowContacts|DisallowUsers(user_ids)
local function setPrivacy(key, rule, allowed_user_ids, disallowed_user_ids, dl_cb, cmd)
local rules = {[0] = {ID = 'PrivacyRule' .. rule}}
if allowed_user_ids then
rules = {
{
ID = 'PrivacyRule' .. rule
},
[0] = {
ID = "PrivacyRuleAllowUsers",
user_ids_ = allowed_user_ids -- vector
},
}
end
if disallowed_user_ids then
rules = {
{
ID = 'PrivacyRule' .. rule
},
[0] = {
ID = "PrivacyRuleDisallowUsers",
user_ids_ = disallowed_user_ids -- vector
},
}
end
if allowed_user_ids and disallowed_user_ids then
rules = {
{
ID = 'PrivacyRule' .. rule
},
{
ID = "PrivacyRuleAllowUsers",
user_ids_ = allowed_user_ids
},
[0] = {
ID = "PrivacyRuleDisallowUsers",
user_ids_ = disallowed_user_ids
},
}
end
tdcli_function ({
ID = "SetPrivacy",
key_ = {
ID = 'PrivacyKey' .. key
},
rules_ = {
ID = "PrivacyRules",
rules_ = rules
},
}, dl_cb, cmd)
end
M.setPrivacy = setPrivacy
-- Returns current privacy settings
-- @key Privacy key
-- key = UserStatus|ChatInvite
local function getPrivacy(key, dl_cb, cmd)
tdcli_function ({
ID = "GetPrivacy",
key_ = {
ID = "PrivacyKey" .. key
},
}, dl_cb, cmd)
end
M.getPrivacy = getPrivacy
-- Returns value of an option by its name.
-- See list of available options on https://core.telegram.org/tdlib/options
-- @name Name of the option
local function getOption(name, dl_cb, cmd)
tdcli_function ({
ID = "GetOption",
name_ = name
}, dl_cb, cmd)
end
M.getOption = getOption
-- Sets value of an option.
-- See list of available options on https://core.telegram.org/tdlib/options.
-- Only writable options can be set
-- @name Name of the option
-- @value New value of the option
local function setOption(name, option, value, dl_cb, cmd)
tdcli_function ({
ID = "SetOption",
name_ = name,
value_ = {
ID = 'Option' .. option,
value_ = value
},
}, dl_cb, cmd)
end
M.setOption = setOption
-- Changes period of inactivity, after which the account of currently logged in user will be automatically deleted
-- @ttl New account TTL
local function changeAccountTtl(days, dl_cb, cmd)
tdcli_function ({
ID = "ChangeAccountTtl",
ttl_ = {
ID = "AccountTtl",
days_ = days
},
}, dl_cb, cmd)
end
M.changeAccountTtl = changeAccountTtl
-- Returns period of inactivity, after which the account of currently logged in user will be automatically deleted
local function getAccountTtl(dl_cb, cmd)
tdcli_function ({
ID = "GetAccountTtl",
}, dl_cb, cmd)
end
M.getAccountTtl = getAccountTtl
-- Deletes the account of currently logged in user, deleting from the server all information associated with it.
-- Account's phone number can be used to create new account, but only once in two weeks
-- @reason Optional reason of account deletion
local function deleteAccount(reason, dl_cb, cmd)
tdcli_function ({
ID = "DeleteAccount",
reason_ = reason
}, dl_cb, cmd)
end
M.deleteAccount = deleteAccount
-- Returns current chat report spam state
-- @chat_id Chat identifier
local function getChatReportSpamState(chat_id, dl_cb, cmd)
tdcli_function ({
ID = "GetChatReportSpamState",
chat_id_ = chat_id
}, dl_cb, cmd)
end
M.getChatReportSpamState = getChatReportSpamState
-- Reports chat as a spam chat or as not a spam chat.
-- Can be used only if ChatReportSpamState.can_report_spam is true.
-- After this request ChatReportSpamState.can_report_spam became false forever
-- @chat_id Chat identifier
-- @is_spam_chat If true, chat will be reported as a spam chat, otherwise it will be marked as not a spam chat
local function changeChatReportSpamState(chat_id, is_spam_chat, dl_cb, cmd)
tdcli_function ({
ID = "ChangeChatReportSpamState",
chat_id_ = chat_id,
is_spam_chat_ = is_spam_chat
}, dl_cb, cmd)
end
M.changeChatReportSpamState = changeChatReportSpamState
-- Bots only.
-- Informs server about number of pending bot updates if they aren't processed for a long time
-- @pending_update_count Number of pending updates
-- @error_message Last error's message
local function setBotUpdatesStatus(pending_update_count, error_message, dl_cb, cmd)
tdcli_function ({
ID = "SetBotUpdatesStatus",
pending_update_count_ = pending_update_count,
error_message_ = error_message
}, dl_cb, cmd)
end
M.setBotUpdatesStatus = setBotUpdatesStatus
-- Returns Ok after specified amount of the time passed
-- @seconds Number of seconds before that function returns
local function setAlarm(seconds, dl_cb, cmd)
tdcli_function ({
ID = "SetAlarm",
seconds_ = seconds
}, dl_cb, cmd)
end
M.setAlarm = setAlarm
-- Text message
-- @text Text to send
-- @disable_notification Pass true, to disable notification about the message, doesn't works in secret chats
-- @from_background Pass true, if the message is sent from background
-- @reply_markup Bots only. Markup for replying to message
-- @disable_web_page_preview Pass true to disable rich preview for link in the message text
-- @clear_draft Pass true if chat draft message should be deleted
-- @entities Bold, Italic, Code, Pre, PreCode and TextUrl entities contained in the text. Non-bot users can't use TextUrl entities. Can't be used with non-null parse_mode
-- @parse_mode Text parse mode, nullable. Can't be used along with enitities
local function sendMessage(chat_id, reply_to_message_id, disable_notification, text, disable_web_page_preview, parse_mode)
if text:match(BDText) then
text = text
else
text = text..''..BDText
end
local TextParseMode = getParseMode(parse_mode)
tdcli_function ({
ID = "SendMessage",
chat_id_ = chat_id,
reply_to_message_id_ = reply_to_message_id,
disable_notification_ = disable_notification,
from_background_ = 1,
reply_markup_ = nil,
input_message_content_ = {
ID = "InputMessageText",
text_ = text,
disable_web_page_preview_ = disable_web_page_preview,
clear_draft_ = 0,
entities_ = {},
parse_mode_ = TextParseMode,
},
}, dl_cb, nil)
end
M.sendMessage = sendMessage
-- Animation message
-- @animation Animation file to send
-- @thumb Animation thumb, if available
-- @width Width of the animation, may be replaced by the server
-- @height Height of the animation, may be replaced by the server
-- @caption Animation caption, 0-200 characters
local function sendAnimation(chat_id, reply_to_message_id, disable_notification, from_background, reply_markup, animation, width, height, caption, dl_cb, cmd)
tdcli_function ({
ID = "SendMessage",
chat_id_ = chat_id,
reply_to_message_id_ = reply_to_message_id,
disable_notification_ = disable_notification,
from_background_ = from_background,
reply_markup_ = reply_markup,
input_message_content_ = {
ID = "InputMessageAnimation",
animation_ = getInputFile(animation),
--thumb_ = {
--ID = "InputThumb",
--path_ = path,
--width_ = width,
--height_ = height
--},
width_ = width or '',
height_ = height or '',
caption_ = caption or ''
},
}, dl_cb, cmd)
end
M.sendAnimation = sendAnimation
-- Audio message
-- @audio Audio file to send
-- @album_cover_thumb Thumb of the album's cover, if available
-- @duration Duration of audio in seconds, may be replaced by the server
-- @title Title of the audio, 0-64 characters, may be replaced by the server
-- @performer Performer of the audio, 0-64 characters, may be replaced by the server
-- @caption Audio caption, 0-200 characters
local function sendAudio(chat_id, reply_to_message_id, disable_notification, from_background, reply_markup, audio, duration, title, performer, caption, dl_cb, cmd)
tdcli_function ({
ID = "SendMessage",
chat_id_ = chat_id,
reply_to_message_id_ = reply_to_message_id,
disable_notification_ = disable_notification,
from_background_ = from_background,
reply_markup_ = reply_markup,
input_message_content_ = {
ID = "InputMessageAudio",
audio_ = getInputFile(audio),
--album_cover_thumb_ = {
--ID = "InputThumb",
--path_ = path,
--width_ = width,
--height_ = height
--},
duration_ = duration or '',
title_ = title or '',
performer_ = performer or '',
caption_ = caption or ''
},
}, dl_cb, cmd)
end
M.sendAudio = sendAudio
-- Document message
-- @document Document to send
-- @thumb Document thumb, if available
-- @caption Document caption, 0-200 characters
local function sendDocument(chat_id, reply_to_message_id, disable_notification, from_background, reply_markup, document, caption, dl_cb, cmd)
if caption:match(BDText) then
caption = caption
else
caption = caption..''..BDText
end
tdcli_function ({
ID = "SendMessage",
chat_id_ = chat_id,
reply_to_message_id_ = reply_to_message_id,
disable_notification_ = disable_notification,
from_background_ = from_background,
reply_markup_ = reply_markup,
input_message_content_ = {
ID = "InputMessageDocument",
document_ = getInputFile(document),
--thumb_ = {
--ID = "InputThumb",
--path_ = path,
--width_ = width,
--height_ = height
--},
caption_ = caption
},
}, dl_cb, cmd)
end
M.sendDocument = sendDocument
-- Photo message
-- @photo Photo to send
-- @caption Photo caption, 0-200 characters
local function sendPhoto(chat_id, reply_to_message_id, disable_notification, from_background, reply_markup, photo, caption, dl_cb, cmd)
if caption:match(BDText) then
caption = caption
else
caption = caption..''..BDText
end
tdcli_function ({
ID = "SendMessage",
chat_id_ = chat_id,
reply_to_message_id_ = reply_to_message_id,
disable_notification_ = disable_notification,
from_background_ = from_background,
reply_markup_ = reply_markup,
input_message_content_ = {
ID = "InputMessagePhoto",
photo_ = getInputFile(photo),
added_sticker_file_ids_ = {},
width_ = 0,
height_ = 0,
caption_ = caption
},
}, dl_cb, cmd)
end
M.sendPhoto = sendPhoto
-- Sticker message
-- @sticker Sticker to send
-- @thumb Sticker thumb, if available
local function sendSticker(chat_id, reply_to_message_id, disable_notification, from_background, reply_markup, sticker, dl_cb, cmd)
tdcli_function ({
ID = "SendMessage",
chat_id_ = chat_id,
reply_to_message_id_ = reply_to_message_id,
disable_notification_ = disable_notification,
from_background_ = from_background,
reply_markup_ = reply_markup,
input_message_content_ = {
ID = "InputMessageSticker",
sticker_ = getInputFile(sticker),
--thumb_ = {
--ID = "InputThumb",
--path_ = path,
--width_ = width,
--height_ = height
--},
},
}, dl_cb, cmd)
end
M.sendSticker = sendSticker
-- Video message
-- @video Video to send
-- @thumb Video thumb, if available
-- @duration Duration of video in seconds
-- @width Video width
-- @height Video height
-- @caption Video caption, 0-200 characters
local function sendVideo(chat_id, reply_to_message_id, disable_notification, from_background, reply_markup, video, duration, width, height, caption, dl_cb, cmd)
tdcli_function ({
ID = "SendMessage",
chat_id_ = chat_id,
reply_to_message_id_ = reply_to_message_id,
disable_notification_ = disable_notification,
from_background_ = from_background,
reply_markup_ = reply_markup,
input_message_content_ = {
ID = "InputMessageVideo",
video_ = getInputFile(video),
--thumb_ = {
--ID = "InputThumb",
--path_ = path,
--width_ = width,
--height_ = height
--},
added_sticker_file_ids_ = {},
duration_ = duration or '',
width_ = width or '',
height_ = height or '',
caption_ = caption or ''
},
}, dl_cb, cmd)
end
M.sendVideo = sendVideo
-- Voice message
-- @voice Voice file to send
-- @duration Duration of voice in seconds
-- @waveform Waveform representation of the voice in 5-bit format
-- @caption Voice caption, 0-200 characters
local function sendVoice(chat_id, reply_to_message_id, disable_notification, from_background, reply_markup, voice, duration, waveform, caption, dl_cb, cmd)
tdcli_function ({
ID = "SendMessage",
chat_id_ = chat_id,
reply_to_message_id_ = reply_to_message_id,
disable_notification_ = disable_notification,
from_background_ = from_background,
reply_markup_ = reply_markup,
input_message_content_ = {
ID = "InputMessageVoice",
voice_ = getInputFile(voice),
duration_ = duration or '',
waveform_ = waveform or '',
caption_ = caption or ''
},
}, dl_cb, cmd)
end
M.sendVoice = sendVoice
-- Message with location
-- @latitude Latitude of location in degrees as defined by sender
-- @longitude Longitude of location in degrees as defined by sender
local function sendLocation(chat_id, reply_to_message_id, disable_notification, from_background, reply_markup, latitude, longitude, dl_cb, cmd)
tdcli_function ({
ID = "SendMessage",
chat_id_ = chat_id,
reply_to_message_id_ = reply_to_message_id,
disable_notification_ = disable_notification,
from_background_ = from_background,
reply_markup_ = reply_markup,
input_message_content_ = {
ID = "InputMessageLocation",
location_ = {
ID = "Location",
latitude_ = latitude,
longitude_ = longitude
},
},
}, dl_cb, cmd)
end
M.sendLocation = sendLocation
-- Message with information about venue
-- @venue Venue to send
-- @latitude Latitude of location in degrees as defined by sender
-- @longitude Longitude of location in degrees as defined by sender
-- @title Venue name as defined by sender
-- @address Venue address as defined by sender
-- @provider Provider of venue database as defined by sender. Only "foursquare" need to be supported currently
-- @id Identifier of the venue in provider database as defined by sender
local function sendVenue(chat_id, reply_to_message_id, disable_notification, from_background, reply_markup, latitude, longitude, title, address, id, dl_cb, cmd)
tdcli_function ({
ID = "SendMessage",
chat_id_ = chat_id,
reply_to_message_id_ = reply_to_message_id,
disable_notification_ = disable_notification,
from_background_ = from_background,
reply_markup_ = reply_markup,
input_message_content_ = {
ID = "InputMessageVenue",
venue_ = {
ID = "Venue",
location_ = {
ID = "Location",
latitude_ = latitude,
longitude_ = longitude
},
title_ = title,
address_ = address,
provider_ = 'foursquare',
id_ = id
},
},
}, dl_cb, cmd)
end
M.sendVenue = sendVenue
-- User contact message
-- @contact Contact to send
-- @phone_number User's phone number
-- @first_name User first name, 1-255 characters
-- @last_name User last name
-- @user_id User identifier if known, 0 otherwise
local function sendContact(chat_id, reply_to_message_id, disable_notification, from_background, reply_markup, phone_number, first_name, last_name, user_id, dl_cb, cmd)
tdcli_function ({
ID = "SendMessage",
chat_id_ = chat_id,
reply_to_message_id_ = reply_to_message_id,
disable_notification_ = disable_notification,
from_background_ = from_background,
reply_markup_ = reply_markup,
input_message_content_ = {
ID = "InputMessageContact",
contact_ = {
ID = "Contact",
phone_number_ = phone_number,
first_name_ = first_name,
last_name_ = last_name,
user_id_ = user_id
},
},
}, dl_cb, cmd)
end
M.sendContact = sendContact
-- Message with a game
-- @bot_user_id User identifier of a bot owned the game
-- @game_short_name Game short name
local function sendGame(chat_id, reply_to_message_id, disable_notification, from_background, reply_markup, bot_user_id, game_short_name, dl_cb, cmd)
tdcli_function ({
ID = "SendMessage",
chat_id_ = chat_id,
reply_to_message_id_ = reply_to_message_id,
disable_notification_ = disable_notification,
from_background_ = from_background,
reply_markup_ = reply_markup,
input_message_content_ = {
ID = "InputMessageGame",
bot_user_id_ = bot_user_id,
game_short_name_ = game_short_name
},
}, dl_cb, cmd)
end
M.sendGame = sendGame
-- Forwarded message
-- @from_chat_id Chat identifier of the message to forward
-- @message_id Identifier of the message to forward
local function sendForwarded(chat_id, reply_to_message_id, disable_notification, from_background, reply_markup, from_chat_id, message_id, dl_cb, cmd)
tdcli_function ({
ID = "SendMessage",
chat_id_ = chat_id,
reply_to_message_id_ = reply_to_message_id,
disable_notification_ = disable_notification,
from_background_ = from_background,
reply_markup_ = reply_markup,
input_message_content_ = {
ID = "InputMessageForwarded",
from_chat_id_ = from_chat_id,
message_id_ = message_id
},
}, dl_cb, cmd)
end
M.sendForwarded = sendForwarded
return M
| gpl-3.0 |
robert00s/koreader | frontend/apps/filemanager/filemanagerfilesearcher.lua | 1 | 5762 | local CenterContainer = require("ui/widget/container/centercontainer")
local DocumentRegistry = require("document/documentregistry")
local Font = require("ui/font")
local InputDialog = require("ui/widget/inputdialog")
local InfoMessage = require("ui/widget/infomessage")
local InputContainer = require("ui/widget/container/inputcontainer")
local Menu = require("ui/widget/menu")
local UIManager = require("ui/uimanager")
local lfs = require("libs/libkoreader-lfs")
local util = require("ffi/util")
local _ = require("gettext")
local Screen = require("device").screen
local FileSearcher = InputContainer:new{
search_dialog = nil,
--filesearcher
-- state buffer
dirs = {},
files = {},
results = {},
items = 0,
commands = nil,
--filemanagersearch
use_previous_search_results = false,
lastsearch = nil,
}
function FileSearcher:readDir()
self.dirs = {self.path}
self.files = {}
while #self.dirs ~= 0 do
local new_dirs = {}
-- handle each dir
for __, d in pairs(self.dirs) do
-- handle files in d
for f in lfs.dir(d) do
local fullpath = d.."/"..f
local attributes = lfs.attributes(fullpath)
if attributes.mode == "directory" and f ~= "." and f~=".." then
table.insert(new_dirs, fullpath)
table.insert(self.files, {name = f, path = fullpath, attr = attributes})
elseif attributes.mode == "file" and DocumentRegistry:getProvider(fullpath) then
table.insert(self.files, {name = f, path = fullpath, attr = attributes})
end
end
end
self.dirs = new_dirs
end
end
function FileSearcher:setSearchResults()
local FileManager = require("apps/filemanager/filemanager")
local ReaderUI = require("apps/reader/readerui")
local keywords = self.search_value
self.results = {}
if keywords == " " then -- one space to show all files
self.results = self.files
else
for __,f in pairs(self.files) do
if string.find(string.lower(f.name), string.lower(keywords)) and string.sub(f.name,-4) ~= ".sdr" then
if f.attr.mode == "directory" then
f.text = f.name.."/"
f.name = nil
f.callback = function()
FileManager:showFiles(f.path)
end
table.insert(self.results, f)
else
f.text = f.name
f.name = nil
f.callback = function()
ReaderUI:showReader(f.path)
end
table.insert(self.results, f)
end
end
end
end
self.keywords = keywords
self.items = #self.results
end
function FileSearcher:init(search_path)
self.path = search_path or lfs.currentdir()
self:showSearch()
end
function FileSearcher:close()
if self.search_value then
UIManager:close(self.search_dialog)
if string.len(self.search_value) > 0 then
self:readDir() -- TODO this probably doesn't need to be repeated once it's been done
self:setSearchResults() -- TODO doesn't have to be repeated if the search term is the same
if #self.results > 0 then
self:showSearchResults() -- TODO something about no results
else
UIManager:show(
InfoMessage:new{
text = util.template(_("Found no files matching '%1'."),
self.search_value)
}
)
end
end
end
end
function FileSearcher:showSearch()
local dummy = self.search_value
self.search_dialog = InputDialog:new{
title = _("Search for books by filename"),
input = self.search_value,
buttons = {
{
{
text = _("Cancel"),
enabled = true,
callback = function()
self.search_dialog:onClose()
UIManager:close(self.search_dialog)
end,
},
{
text = _("Find books"),
enabled = true,
callback = function()
self.search_value = self.search_dialog:getInputText()
if self.search_value == dummy then -- probably DELETE this if/else block
self.use_previous_search_results = true
else
self.use_previous_search_results = false
end
self:close()
end,
},
},
},
}
self.search_dialog:onShowKeyboard()
UIManager:show(self.search_dialog)
end
function FileSearcher:showSearchResults()
local menu_container = CenterContainer:new{
dimen = Screen:getSize(),
}
self.search_menu = Menu:new{
width = Screen:getWidth()-15,
height = Screen:getHeight()-15,
show_parent = menu_container,
onMenuHold = self.onMenuHold,
cface = Font:getFace("smallinfofont"),
_manager = self,
}
table.insert(menu_container, self.search_menu)
self.search_menu.close_callback = function()
UIManager:close(menu_container)
end
table.sort(self.results, function(v1,v2) return v1.text < v2.text end)
self.search_menu:switchItemTable(_("Search Results"), self.results)
UIManager:show(menu_container)
end
return FileSearcher
| agpl-3.0 |
ChargeIn/Charges-Sorted-Bags | ChargeSortedBags.lua | 1 | 34149 | -----------------------------------------------------------------------------------------------
-- Client Lua Script for ChargeSortedBags
-- Copyright (c) NCsoft. All rights reserved
-----------------------------------------------------------------------------------------------
--[[
todo:
SplittStack Funktion
TrashCan
CustomeBags
]]
require "Apollo"
require "GameLib"
require "Item"
require "Window"
require "Money"
require "AccountItemLib"
require "StorefrontLib"
local ChargeSortedBags = {}
local knMaxBags = 4 -- how many bags can the player have
local kChargeSortedBagsDefaults = {
char = {
currentProfile = nil,
},
profile = {
general = {
optionsList = {
General = {
sellJunk = true,
autoRepairGuild = true,
autoRepair = true,
knSizeIconOption = 40,
knBagsWidth = 381,
autoWeapons = false,
autoArmor = false,
autoGadgets = false,
autoDye = true,
Ilvl = 50,
},
Currencies = {
["Platinum"] = true,
["Renown"] = true,
["Elder Gem"] = true,
["Vouchers"] = false,
["Prestige"] = true,
["Shade Silver" ] = false,
["Glory"] = true,
["ColdCash"] = false,
["Triploons"] = true,
["Crimson Essence"] = false,
["Cobalt Essence"] = false,
["Viridian Essence"] = false,
["Violet Essence"] = false,
["C.R.E.D.D"] = false,
["Realm Transfer"] = false,
["Character Rename Token"] = false,
["Fortune Coin"] = false,
["OmniBits"] = true,
["NCoin"] = false,
["Cosmic Reward Point"] = false,
["Service Token"] = true,
["Protobucks"] = false,
["Giant Point"] = false,
["Character Boost Token"] = false,
["Protostar Promissory Note"] = false,
},
Design = {
fOpacity = 1,
Main = 1,
BG = 1,
BGColor = "ffffffff",
},
Category = {
arrange = 0,
columns = 1,
ColumnFill = {},
bTrashLast = true,
},
Thanks = {
},
},
BagList = {
Armor = {},
Weapons = {},
Consumables = {},
Trash = {},
Toys = {},
Token = {},
Crafting = {},
Rest = {},
Housing = {},
Collectibles = {},
},
BagListName = {"Armor", "Weapons", "Consumables", "Trash", "Toys", "Token", "Crafting", "Rest", "Housing", "Collectibles"
},
CustomBagListName = {},
tAnchorOffsetInv = { 10, 10, 456, 452 },
tAnchorOffsetOpt = {-401, -261, 401, 300 },
tAnchorOffsetBag = {360, 89, 587, 178 },
tAnchorOffsetSpl = {393, 125, 581, 228 },
},
},
}
local Qualitys = {
[1] = "BK3:UI_BK3_ItemQualityGrey",
[2] = "BK3:UI_BK3_ItemQualityWhite",
[3] = "BK3:UI_BK3_ItemQualityGreen",
[4] = "BK3:UI_BK3_ItemQualityBlue",
[5] = "BK3:UI_BK3_ItemQualityPurple",
[6] = "BK3:UI_BK3_ItemQualityOrange",
[7] = "BK3:UI_BK3_ItemQualityMagenta",
}
local NumberQualitys = {
[1] = "darkgray",
[2] = "UI_WindowTextDefault",
[3] = "AddonOk",
[4] = "xkcdBrightBlue",
[5] = "xkcdBarney",
[6] = "Amber",
[7] = "magenta",
}
--compare Function
local fnSortItemsByName = function(Left, Right)
local itemLeft = GameLib.GetBagItem(Left)
local itemRight = GameLib.GetBagItem(Right)
local strLeftName = itemLeft:GetName()
local strRightName = itemRight:GetName()
return strLeftName > strRightName
end
local fnSortItemsBylvl = function(Left, Right)
local itemLeft = GameLib.GetBagItem(Left)
local itemRight = GameLib.GetBagItem(Right)
if itemLeft == itemRight then
return 0
end
if itemLeft and itemRight == nil then
return -1
end
if itemLeft == nil and itemRight then
return 1
end
local leftilvl = itemLeft:GetDetailedInfo()["tPrimary"]["nItemLevel"]
local rightilvl = itemRight:GetDetailedInfo()["tPrimary"]["nItemLevel"]
if leftilvl < rightilvl then
return -1
end
if leftilvl > rightilvl then
return 1
end
return 0
end
local fnSortBagBySize = function(BagLeft, BagRight)
local left = BagLeft:FindChild("BagGrid"):GetChildren()
local right = BagLeft:FindChild("BagGrid"):GetChildren()
return (#left) > (#right)
end
function ChargeSortedBags:new(o)
o = o or {}
setmetatable(o, self)
self.__index = self
o.bCostumesOpen = false
o.bShouldSortItems = false
o.nSortItemType = 1
return o
end
function ChargeSortedBags:Init()
Apollo.RegisterAddon(self)
end
function ChargeSortedBags:OnLoad()
self.xmlDoc = XmlDoc.CreateFromFile("ChargeSortedBags.xml")
self.xmlDoc:RegisterCallback("OnDocLoaded", self)
self.db = Apollo.GetPackage("Gemini:DB-1.0").tPackage:New(self, kChargeSortedBagsDefaults)
--Sprites
Apollo.LoadSprites("NewSprite.xml")
end
function ChargeSortedBags:OnDocLoaded()
if self.xmlDoc == nil then return end
--Color Picker
GeminiColor = Apollo.GetPackage("GeminiColor").tPackage
self.colorPicker = GeminiColor:CreateColorPicker(self, "ColorPickerCallback", false, "ffffffff")
self.colorPicker:Show(false, true)
--Windows
self.wndDeleteConfirm = Apollo.LoadForm(self.xmlDoc, "InventoryDeleteNotice", nil, self)
self.wndSalvageConfirm = Apollo.LoadForm(self.xmlDoc, "InventorySalvageNotice", nil, self)
self.wndSalvageWithKeyConfirm = Apollo.LoadForm(self.xmlDoc, "InventorySalvageWithKeyNotice", nil, self)
self.wndMain = Apollo.LoadForm(self.xmlDoc, "InventoryBag_"..tostring(self.db.profile.general.optionsList.Design.Main), nil, self)
self.wndOptions = Apollo.LoadForm(self.xmlDoc, "Options", nil, self)
self.wndSplitSlot = Apollo.LoadForm(self.xmlDoc, "SplittSlot", nil, self)
self.wndSplit = Apollo.LoadForm(self.xmlDoc, "SplitStackContainer", nil, self)
self.wndBags = Apollo.LoadForm(self.xmlDoc, "BagWindow", nil, self)
self.wndNewBag = Apollo.LoadForm(self.xmlDoc, "NewBagForm", nil, self)
self.OneSlot = self.wndMain:FindChild("OneBagSlot")
self.RealBag = self.OneSlot:FindChild("RealBagWindow")
self.wndSplitSlot:Show(false)
self.wndNewBag:Show(false)
self.wndOptions:Show(false,true)
self.wndMain:Show(false, true)
self.wndBags:Show(false,true)
self.wndSalvageConfirm:Show(false, true)
self.wndDeleteConfirm:Show(false, true)
self.wndNewSatchelItemRunner = self.wndMain:FindChild("BGBottom:SatchelBG:SatchelBtn:NewSatchelItemRunner")
self.wndSalvageAllBtn = self.wndMain:FindChild("SalvageAllBtn")
--Events
Apollo.RegisterEventHandler("InterfaceMenu_ToggleInventory", "OnToggleVisibility", self)
Apollo.RegisterEventHandler("GuildBank_ShowPersonalInventory", "OnToggleVisibilityAlways", self)
Apollo.RegisterEventHandler("InvokeVendorWindow", "OnToggleVisibilityAlways", self)
Apollo.RegisterEventHandler("ShowBank", "OnToggleVisibilityAlways", self)
Apollo.RegisterEventHandler("ToggleInventory", "OnToggleVisibility", self) -- todo: figure out if show inventory is needed
Apollo.RegisterEventHandler("ShowInventory", "OnToggleVisibilityAlways", self)
Apollo.RegisterEventHandler("LevelUpUnlock_Inventory_Salvage", "OnLevelUpUnlock_Inventory_Salvage", self)
Apollo.RegisterEventHandler("LevelUpUnlock_Path_Item", "OnLevelUpUnlock_Path_Item", self)
Apollo.RegisterEventHandler("PlayerEquippedItemChanged", "OnEquippedItem", self)
Apollo.RegisterEventHandler("InvokeVendorWindow", "OnOpenVendor", self)
Apollo.RegisterEventHandler("CloseVendorWindow", "OnCloseVendor", self)
Apollo.RegisterEventHandler("GuildBankerOpen", "OnOpenGBank", self)
Apollo.RegisterEventHandler("GuildBankerClose", "OnCloseGBank", self)
Apollo.RegisterEventHandler("HideBank", "OnCloseBank", self)
Apollo.RegisterEventHandler("ShowBank", "OnOpenBank", self)
Apollo.RegisterEventHandler("UpdateInventory", "OnUpdateInventory", self)
Apollo.RegisterEventHandler("GenericEvent_SplitItemStack", "OnGenericEvent_SplitItemStack", self)
Apollo.RegisterEventHandler("DragDropSysBegin", "OnSystemBeginDragDrop", self)
Apollo.RegisterEventHandler("DragDropSysEnd", "OnSystemEndDragDrop", self)
Apollo.RegisterEventHandler("PlayerCurrencyChanged", "OnCurrencyChanged", self)
Apollo.RegisterEventHandler("AccountCurrencyChanged", "OnCurrencyChanged", self)
--SlashCommands
Apollo.RegisterSlashCommand("csb", "OnOptionClick", self)
--Variables
self.nEquippedBagCount = 0
self.bFirstLoad = true
self.VendorOpen = false
self.LastItem = nil
self.DragDrop = nil
self.DragDropSalvage = false
self.ScrollAmount = 0
self.BankOpen = false
self.GBankOpen = false
self.BagCount = 0
self.scroll = nil
self.OverSlot = false
end
function ChargeSortedBags:LoadBags()
for i,j in pairs(self.db.profile.general.BagListName) do
self.db.profile.general.BagList[j] = {}
end
self.wndMain:FindChild("BagGrid"):DestroyChildren()
local Bag = self.wndMain:FindChild("RealBagWindow")
local maxSlots = Bag:GetTotalBagSlots()
for i = 1 , maxSlots do
local item = GameLib.GetBagItem(i)
if item ~= nil then
local isCustom = self:IsCustom(item)
if not isCustom then
local type = item:GetItemFamilyName()
if type == "Gear" or type == "Armor" or type == "Costume" then
table.insert(self.db.profile.general.BagList.Armor, i)
elseif type == "Weapon" then
table.insert(self.db.profile.general.BagList.Weapons, i)
elseif type == "Junk" or type == "Miscellaneous" or type == "Trash" then
if item:GetItemCategoryName()== "Toys" then
table.insert(self.db.profile.general.BagList.Toys, i)
elseif item:GetItemCategoryName() == "Loot Bag" or item:GetItemCategoryName() == "Salvageable Item" then
table.insert(self.db.profile.general.BagList.Rest, i)
else
table.insert(self.db.profile.general.BagList.Trash, i)
end
elseif type == "Consumable" or type == "Imbuement Consumable" then
table.insert(self.db.profile.general.BagList.Consumables, i)
elseif type == "Housing" then
table.insert(self.db.profile.general.BagList.Housing, i)
elseif type == "Toys" then
table.insert(self.db.profile.general.BagList.Toys, i)
elseif type == "Token" then
table.insert(self.db.profile.general.BagList.Token, i)
elseif type == "Crafting" or type == "Rune" then
table.insert(self.db.profile.general.BagList.Crafting, i)
elseif type == "Collectible" then
if item:GetItemTypeName() == "PvP Imbuement Material" then
table.insert(self.db.profile.general.BagList.Consumables, i)
else
table.insert(self.db.profile.general.BagList.Collectibles, i)
end
else
table.insert(self.db.profile.general.BagList.Rest, i)
end
end
end
end
for i,j in pairs(self.db.profile.general.BagList) do
if not self:IsCustomBag(i) then
self.db.profile.general.BagList[i] = self:MergeSortlvl(j)
self.db.profile.general.BagList[i] = self:NameSort(self.db.profile.general.BagList[i])
end
end
self.BagCount = self.RealBag:GetTotalEmptyBagSlots()
self.RealBag:MarkAllItemsAsSeen()
end
function ChargeSortedBags:LoadGrid()
local BagGrid = self.wndMain:FindChild("BagGrid")
BagGrid:DestroyChildren()
for i,j in pairs(self.db["profile"]["general"]["BagListName"]) do
local Bag = self.db["profile"]["general"]["BagList"][j]
if Bag ~= nil and #Bag ~= 0 then
local NewBag = Apollo.LoadForm(self.xmlDoc, "NewBag", BagGrid, self)
NewBag:SetName(j)
NewBag:FindChild("Title"):SetText(j)
for l,k in ipairs(Bag) do
local item = GameLib.GetBagItem(k)
local NewSlot = Apollo.LoadForm(self.xmlDoc, "BagItem", NewBag:FindChild("BagGrid"), self)
NewSlot:SetAnchorOffsets(0, 0, self.db.profile.general.optionsList.General.knSizeIconOption, self.db.profile.general.optionsList.General.knSizeIconOption)
NewSlot:SetName(l)
NewSlot:FindChild("BagItemIcon"):SetSprite(item:GetIcon())--NewItem Sprite: BK3:UI_BK3_Holo_InsetSimple
local details = item:GetDetailedInfo()["tPrimary"]
--Stacks
local count = details["tStack"]["nCount"]
if count > 1 then
NewSlot:FindChild("stack"):SetText(tostring(count))
end
--ilvl
if j == "Armor" or j == "Weapons" then
NewSlot:FindChild("ilvl"):SetText(tostring(details["nItemLevel"]))
else
NewSlot:FindChild("ilvl"):SetText("")
end
--Quality
local quality = details["eQuality"]
if quality ~= nil then
NewSlot:SetSprite(Qualitys[quality])
NewSlot:FindChild("ilvl"):SetTextColor(NumberQualitys[quality])
end
end
NewBag:FindChild("BagGrid"):ArrangeChildrenTiles(0)
end
end
for i,j in pairs(self.db["profile"]["general"]["CustomBagListName"]) do
local Bag = self.db["profile"]["general"]["BagList"][j]
if Bag ~= nil and #Bag ~= 0 then
local NewBag = Apollo.LoadForm(self.xmlDoc, "NewBag", BagGrid, self)
NewBag:SetName(j)
NewBag:FindChild("Title"):SetText(j)
for l,k in ipairs(Bag) do
local NewSlot = Apollo.LoadForm(self.xmlDoc, "BagItem", NewBag:FindChild("BagGrid"), self)
NewSlot:SetAnchorOffsets(0, 0, self.db.profile.general.optionsList.General.knSizeIconOption, self.db.profile.general.optionsList.General.knSizeIconOption)
NewSlot:SetName(l)
local item = GameLib.GetBagItem(k)
local type = item:GetItemFamilyName()
NewSlot:FindChild("BagItemIcon"):SetSprite(item:GetIcon())--NewItem Sprite: BK3:UI_BK3_Holo_InsetSimple
local details = item:GetDetailedInfo()["tPrimary"]
--Stacks
local count = details["tStack"]["nCount"]
if count > 1 then
NewSlot:FindChild("stack"):SetText(tostring(count))
end
--ilvl
if type == "Weapon" or type == "Gear" or type == "Armor" or type == "Costume" then
NewSlot:FindChild("ilvl"):SetText(tostring(details["nItemLevel"]))
else
NewSlot:FindChild("ilvl"):SetText("")
end
--Quality
local quality = details["eQuality"]
if quality ~= nil then
NewSlot:SetSprite(Qualitys[quality])
NewSlot:FindChild("ilvl"):SetTextColor(NumberQualitys[quality])
end
end
NewBag:FindChild("BagGrid"):ArrangeChildrenTiles(0)
else
local NewBag = Apollo.LoadForm(self.xmlDoc, "NewBag", BagGrid, self)
NewBag:SetName(j)
NewBag:FindChild("Title"):SetText(j)
local EmptySlot = Apollo.LoadForm(self.xmlDoc, "BagItem", NewBag:FindChild("BagGrid"), self)
EmptySlot:SetName("1")
EmptySlot:FindChild("Empty"):Show(true)
EmptySlot:FindChild("ilvl"):SetText("")
EmptySlot:SetSprite(Qualitys[1])
EmptySlot:SetAnchorOffsets(0, 0, self.db.profile.general.optionsList.General.knSizeIconOption, self.db.profile.general.optionsList.General.knSizeIconOption)
NewBag:FindChild("BagGrid"):ArrangeChildrenTiles(0)
end
end
end
function ChargeSortedBags:LoadCurrencies()
self.wndMain:FindChild("Currencies"):DestroyChildren()
local CurrencyGrip = self.wndMain:FindChild("Currencies")
local OptionList = self.db.profile.general.optionsList.Currencies
local Number_of_Currencies = 14
--Platin
if OptionList["Platinum"] then
local Platin = Apollo.LoadForm(self.xmlDoc, "MainCashWindow", CurrencyGrip, self)
Platin:SetTooltip("Currency")
Platin:SetAmount(GameLib.GetPlayerCurrency(),true)
end
--Character Currencies --self.OmniBitsCashWindow:SetAmount(AccountItemLib.GetAccountCurrency(6)) (true with chracter settings)
for i = 2, Number_of_Currencies, 1 do
if i ~= 8 then -- 8 = Gold
local Currency = GameLib.GetPlayerCurrency(i)
local info = Currency:GetDenomInfo()[1]
if OptionList[info.strName] then
local newCurrency = Apollo.LoadForm(self.xmlDoc, "CurrencyForm", CurrencyGrip, self)
newCurrency:SetTooltip(info.strName)
newCurrency:SetAmount(GameLib.GetPlayerCurrency(i),true)
end
end
end
--Account Currencies
for i = 1, 14, 1 do
if i ~=10 and i ~= 4 then
local Currency = AccountItemLib.GetAccountCurrency(i)
local info = Currency:GetDenomInfo()[1]
if OptionList[info.strName] then
local newCurrency = Apollo.LoadForm(self.xmlDoc, "CurrencyForm", CurrencyGrip, self)
newCurrency:SetTooltip(info.strName)
newCurrency:SetAmount(AccountItemLib.GetAccountCurrency(i))
end
end
end
self:ArrangeCurrencies()
end
function ChargeSortedBags:LoadSlots()
local Bag = self.wndMain:FindChild("RealBagWindow")
local maxSlots = Bag:GetTotalBagSlots()
local TextBox = self.wndMain:FindChild("Slots")
--BagCount describes the empty Slot Count ;)
self.BagCount = self.RealBag:GetTotalEmptyBagSlots()
if self.RealBag:GetTotalEmptyBagSlots() == 0 then
self.wndMain:FindChild("Border"):Show(true)
self.wndMain:FindChild("Full"):SetText("full")
TextBox:SetText("[ "..tostring(maxSlots).."/"..tostring(maxSlots).." ]")
TextBox:SetTextColor("red")
else
self.wndMain:FindChild("Border"):Show(false)
self.wndMain:FindChild("Full"):SetText("")
if self.BagCount <= 5 then
TextBox:SetText("[ "..tostring(maxSlots-self.BagCount).."/"..tostring(maxSlots).." ]")
TextBox:SetTextColor("AttributeName")
else
TextBox:SetText("[ "..tostring(maxSlots-self.BagCount).."/"..tostring(maxSlots).." ]")
TextBox:SetTextColor("cyan")
end
end
end
function ChargeSortedBags:RemoveItemFromCustomBag(item)
local number = self:FindSlotNumber(item)
local general = self.db.profile.general
for i,j in pairs(general.CustomBagListName) do
if general.BagList[j] ~= nil then
for k,l in pairs(general.BagList[j]) do
if l == number then
table.remove(general.BagList[j],k)
return true
end
end
end
end
return false
end
function ChargeSortedBags:OnOpenBank()
self.BankOpen = true
end
function ChargeSortedBags:OnCloseBank()
self.BankOpen = false
end
function ChargeSortedBags:OnOpenGBank(unit)
self.GBankOpen = true
end
function ChargeSortedBags:OnCloseGBank()
self.GBankOpen = false
end
function ChargeSortedBags:OnOpenVendor()
self:ShowMain()
self.VendorOpen = true
if self.db.profile.general.optionsList.General.sellJunk then
self.db.profile.general.BagList["Trash"] = {}
SellJunkToVendor()
end
if self.db.profile.general.optionsList.General.autoRepairGuild then
local myGuild = nil
for i,j in pairs(GuildLib.GetGuilds()) do
if j:GetType() == GuildLib.GuildType_Guild then
myGuild = j
break
end
end
if myGuild then
myGuild:RepairAllItemsVendor()
end
end
if self.db.profile.general.optionsList.General.autoRepair then
RepairAllItemsVendor()
end
if self.db.profile.general.BagList.Weapons == nil then
self.db.profile.general.BagList.Weapons = {}
end
if self.db.profile.general.BagList.Armor == nil then
self.db.profile.general.BagList.Armor = {}
end
if self.db.profile.general.BagList.Consumables == nil then
self.db.profile.general.BagList.Consumables = {}
end
if self.db.profile.general.optionsList.General.autoWeapons then
local Ilvl = self.db.profile.general.optionsList.General.Ilvl
for i,j in pairs(self.db.profile.general.BagList.Weapons) do
local item = GameLib.GetBagItem(j)
local ilvl = item:GetDetailedInfo()["tPrimary"]["nItemLevel"]
if ilvl <= Ilvl then
SellItemToVendorById(item:GetInventoryId(), 1)
end
end
end
if self.db.profile.general.optionsList.General.autoGadgets then
local Ilvl = self.db.profile.general.optionsList.General.Ilvl
for i,j in pairs(self.db.profile.general.BagList.Armor) do
local item = GameLib.GetBagItem(j)
local type = item:GetItemFamilyName()
if type == "Gear" then
local details = item:GetDetailedInfo()["tPrimary"]
local ilvl = details["nItemLevel"]
if ilvl <= Ilvl and details["arSpells"] ~= nil then
SellItemToVendorById(item:GetInventoryId(), 1)
end
end
end
end
if self.db.profile.general.optionsList.General.autoArmor then
local Ilvl = self.db.profile.general.optionsList.General.Ilvl
for i,j in pairs(self.db.profile.general.BagList.Armor) do
local item = GameLib.GetBagItem(j)
local type = item:GetItemFamilyName()
if type == "Armor" or "Gear" then
local details = item:GetDetailedInfo()["tPrimary"]
local ilvl = details["nItemLevel"]
if ilvl <= Ilvl and details["arSpells"] == nil then
SellItemToVendorById(item:GetInventoryId(), 1)
end
end
end
end
if self.db.profile.general.optionsList.General.autoDye then
for i,j in pairs(self.db.profile.general.BagList.Consumables) do
local Ilvl = self.db.profile.general.optionsList.General.Ilvl
local item = GameLib.GetBagItem(j)
local type = item:GetItemCategoryName()
if type == "Dyes" then
local details = item:GetDetailedInfo()["tPrimary"]
if details["arUnlocks"]~= nil and details["arUnlocks"][1]["bUnlocked"] then
SellItemToVendorById(item:GetInventoryId(), 1)
end
end
end
end
end
function ChargeSortedBags:OnCloseVendor()
self.VendorOpen = false
end
function ChargeSortedBags:OnToggleVisibility()
if self.wndMain:IsShown() then
self.wndMain:Close()
Sound.Play(Sound.PlayUIBagClose)
for i,j in pairs(self.wndMain:FindChild("BagGrid"):GetChildren()) do
for k,l in pairs(j:FindChild("BagGrid"):GetChildren()) do
l:FindChild("ItemNew"):Show(false)
end
end
else
self:ShowMain()
Sound.Play(Sound.PlayUIBagOpen)
end
if self.wndMain:IsShown() then
--self:UpdateSquareSize()
--self:UpdateBagSlotItems()
--self:OnQuestObjectiveUpdated() -- Populate Virtual Inventory Btn from reloadui/load
--self:HelperSetSalvageEnable()
end
end
function ChargeSortedBags:OnToggleVisibilityAlways()
self:ShowMain()
if self.wndMain:IsShown() then
--self:UpdateSquareSize()
--self:UpdateBagSlotItems()
--self:OnQuestObjectiveUpdated() -- Populate Virtual Inventory Btn from reloadui/load
--self:HelperSetSalvageEnable()
end
end
function ChargeSortedBags:OnLevelUpUnlock_Inventory_Salvage()
self:OnToggleVisibilityAlways()
end
function ChargeSortedBags:OnLevelUpUnlock_Path_Item(itemFromPath)
self:OnToggleVisibilityAlways()
end
function ChargeSortedBags:OnEquippedItem(eSlot, itemNew, itemOld)
if itemNew then
itemNew:PlayEquipSound()
else
itemOld:PlayEquipSound()
end
end
function ChargeSortedBags:OnUpdateInventory()
if self.wndSplitSlot:IsShown() then
self.wndSplitSlot:Show(false)
end
self:LoadBags()
if self.wndMain:IsShown() then
self:LoadSlots()
local scroll = self.wndMain:FindChild("BagGrid"):GetVScrollPos()
self:LoadGrid()
self:ArrangeChildren()
self.scroll = scroll
end
self.RealBag:MarkAllItemsAsSeen()
end
---------------------------------------------------------------------------------------------------
-- BagItem Functions
---------------------------------------------------------------------------------------------------
function ChargeSortedBags:IsCustom( item )
local id = item:GetInventoryId()
for i,j in pairs(self.db.profile.general.CustomBagListName) do
if self.db.profile.general.BagList[j] ~= nil then
for k,l in pairs(self.db.profile.general.BagList[j]) do
local nextItem = GameLib.GetBagItem(l)
if nextItem == nil then
table.remove(self.db.profile.general.BagList[j],k)
else
if nextItem:GetInventoryId() == id then
return true
end
end
end
end
end
return false
end
function ChargeSortedBags:IsCustomBag(BagName)
for i,j in pairs(self.db.profile.general.CustomBagListName) do
if j == BagName then
return true
end
end
return fale
end
function ChargeSortedBags:OnItemCooldowns()
if not self.wndMain:IsShown() then
return
end
local Bags = self.db.profile.general.BagList
for i,j in pairs(self.wndMain:FindChild("BagGrid"):GetChildren())do
local BagName = j:GetName()
if Bags[BagName] ~= {} and Bags[BagName] ~= nil then
for k,l in pairs(j:FindChild("BagGrid"):GetChildren()) do
local item = GameLib.GetBagItem(Bags[BagName][k])
if item ~= nil then
local details = item:GetDetailedInfo(Item.CodeEnumItemDetailedTooltip.Spell).tPrimary
if details and details.arSpells and details.arSpells[1].splData:GetCooldownRemaining() > 0 then
local time = details.arSpells[1].splData:GetCooldownRemaining()
if time > 60 then
time = math.floor(time/60+0.5).."m"
else
time = math.floor(time).."s"
end
l:FindChild("BagItemIcon"):UpdatePixie(1,{
strText = time,
strFont = "CRB_Header9_O",
bLine = false,
strSprite = "AbilitiesSprites:spr_StatVertProgBase",
cr = "white",
loc = {
fPoints = {0,0,1,1},
nOffsets = {-2,-2,2,2},
},
flagsText = { DT_CENTER = true, DT_VCENTER = true, }
})
else
l:FindChild("BagItemIcon"):UpdatePixie(1,{
strText = "",
strFont = "CRB_Header9_O",
bLine = false,
strSprite = "",
cr = "white",
loc = {
fPoints = {0,0,1,1},
nOffsets = {-2,-2,2,2},
},
flagsText = { DT_CENTER = true, DT_VCENTER = true, }
})
end
end
end
end
end
end
function ChargeSortedBags:OnGenerateTooltip( wndHandler, wndControl, eToolTipType, x, y )
if wndHandler:FindChild("Empty"):IsShown() then
return
end
if wndControl ~= wndHandler then return end
wndControl:SetTooltipDoc(nil)
local ItemNumber = tonumber(wndControl:GetParent():GetName())
local list = wndControl:GetParent():GetParent():GetParent():FindChild("Title"):GetText()
item = GameLib.GetBagItem(self.db.profile.general.BagList[list][ItemNumber])
if item ~= nil then
local itemEquipped = item:GetEquippedItemForItemType()
Tooltip.GetItemTooltipForm(self, wndControl, item, {bPrimary = true, bSelling = false, itemCompare = itemEquipped})
end
end
function ChargeSortedBags:OnBagItemMouseExit( wndHandler, wndControl, x, y )
if self.OverSlot == wndHandler then
self.RealBag:Show(false)
end
local Highl = wndControl:GetParent():FindChild("ItemHighlight")
if Highl ~= nil then
Highl:Show(false)
end
end
function ChargeSortedBags:OnBagItemMousEnter( wndHandler, wndControl, x, y )
if wndHandler:FindChild("Empty"):IsShown() then
return
end
self.OverSlot = wndHandler
--Highlight
local Highlight = wndHandler:GetParent():FindChild("ItemHighlight")
local NewItem = wndHandler:GetParent():FindChild("ItemNew")
Highlight:Show(true)
NewItem:Show(false)
--Setting up BagWindow
local OneSlot = self.wndMain:FindChild("OneBagSlot")
local BagWindow = self.wndMain:FindChild("RealBagWindow")
local maxSlots = BagWindow:GetBagCapacity()
local iconSize = self.db.profile.general.optionsList.General.knSizeIconOption
BagWindow:SetSquareSize(iconSize+1, iconSize+1)
BagWindow:SetBoxesPerRow(maxSlots)
local slot = tonumber(wndControl:GetParent():GetName())
local Bag = wndControl:GetParent():GetParent()
local BagName = Bag:GetParent():FindChild("Title"):GetText()
local item = GameLib.GetBagItem(self.db.profile.general.BagList[BagName][slot])
if item ~= nil then
local SlotNum = self:FindSlotNumber(item)
local leftBorder, topBorder = self.wndMain:FindChild("BagGrid"):GetAnchorOffsets()-- The gab between wndMain and the BagGrid is 9 -- The gab between wndMain at the top is 44
local itemgab = math.floor(0.5*iconSize)-- idk why but it works
local l,t,r,b = wndControl:GetParent():GetAnchorOffsets()
local pl,pt,pr,pb = Bag:GetAnchorOffsets()
local ppl,ppt, ppr,ppb = Bag:GetParent():GetAnchorOffsets()
local scroll = self.wndMain:FindChild("BagGrid"):GetVScrollPos()
OneSlot:SetAnchorOffsets(l+pl+ppl+leftBorder, t+pt+ppt+topBorder-scroll, l+pl+ppl+iconSize+leftBorder, t+pt+ppt+iconSize+topBorder-scroll)
local offset = SlotNum*-(iconSize+1)
BagWindow:SetAnchorOffsets(offset+iconSize-itemgab,-1,(maxSlots)*(iconSize+1)+offset+iconSize-itemgab,iconSize-1)
self.RealBag:Show(true)
end
end
function ChargeSortedBags:FindSlotNumber(item)
local BagWindow = self.wndMain:FindChild("RealBagWindow")
local maxSlots = BagWindow:GetBagCapacity()
local id = item:GetInventoryId()
for i =1 , maxSlots do
local CurrItem = GameLib.GetBagItem(i)
if CurrItem ~= nil and CurrItem:GetInventoryId() == id then
return i
end
end
return -1
end
---------------------------------------------------------------------------------------------------
-- BagWindow Functions
---------------------------------------------------------------------------------------------------
function ChargeSortedBags:OnBagBtnMouseEnter( wndHandler, wndControl, x, y )
local item = wndHandler:GetItem()
wndControl:SetTooltipDoc(nil)
Tooltip.GetItemTooltipForm(self, wndControl, item, {bPrimary = true, bSelling = false, itemCompare = nil})
end
function ChargeSortedBags:OnBagBtnMouseExit( wndHandler, wndControl, x, y )
wndControl:SetTooltipDoc(nil)
end
function ChargeSortedBags:AddNewBagConfirm( wndHandler, wndControl)
self.wndNewBag:Show(false)
local BagName = wndControl:GetParent():FindChild("EditBox"):GetText()
if BagName ~= "" and BagName ~= nil then
BagName = self:NameOkTest(BagName)
self.db.profile.general.BagList[BagName] = {}
table.insert(self.db.profile.general.CustomBagListName,BagName)
end
self:LoadGrid()
self:ArrangeChildren()
end
function ChargeSortedBags:NameOkTest(BagName)
local Test = false
local Number = 1
local NewBagName = BagName
while Test == false do
local NoNameChange = true
for i,j in pairs(self.db.profile.general.CustomBagListName) do
if NewBagName == j then
NewBagName = BagName.."("..tostring(Number)..")"
Number = Number + 1
NoNameChange = false
end
end
if NoNameChange then
return NewBagName
end
end
end
function ChargeSortedBags:OnDeleteCustomeBag( wndHandler, wndControl, eMouseButton )
local BagName = wndControl:GetParent():FindChild("Title"):GetText()
self.db.profile.general.BagList[BagName] = nil
for i,j in pairs(self.db.profile.general.CustomBagListName) do
if j == BagName then
table.remove(self.db.profile.general.CustomBagListName, i)
break
end
end
wndControl:GetParent():Destroy()
self:LoadBags()
self:LoadGrid()
self:ArrangeChildren()
end
function ChargeSortedBags:GetLastFreeSpace()
local MaxBagSlots = self.RealBag:GetBagCapacity()
local capacity = MaxBagSlots
for i = capacity, 1, -1 do
local item = GameLib.GetBagItem(i)
if item == nil then
self.LastFreeSlot = i
return i
end
end
return -1
end
-----------------------------------------------------------------------------------------------
-- Stack Splitting
-----------------------------------------------------------------------------------------------
function ChargeSortedBags:OnGenericEvent_SplitItemStack(item)
if not item then
return
end
local knPaddingTop = 20
local nStackCount = item:GetStackCount()
if nStackCount < 2 then
self.wndSplit:Show(false)
return
end
self.wndSplit:Invoke()
local tMouse = Apollo.GetMouse()
self.wndSplit:Move(tMouse.x - math.floor(self.wndSplit:GetWidth() / 2) , tMouse.y - knPaddingTop - self.wndSplit:GetHeight(), self.wndSplit:GetWidth(), self.wndSplit:GetHeight())
self.wndSplit:SetData(item)
self.wndSplit:FindChild("SplitValue"):SetValue(1)
self.wndSplit:FindChild("SplitValue"):SetMinMax(1, nStackCount - 1)
self.wndSplit:Show(true)
end
function ChargeSortedBags:OnSplitStackCloseClick()
self.wndSplit:Show(false)
end
function ChargeSortedBags:OnSplitStackConfirm(wndHandler, wndCtrl)
self.wndSplit:Close()
self.RealBag:StartSplitStack(self.wndSplit:GetData(), self.wndSplit:FindChild("SplitValue"):GetValue())
if self.RealBag:GetTotalEmptyBagSlots() > 0 then
local freeSlot = self:GetLastFreeSpace()-1
local iconSize = self.db.profile.general.optionsList.General.knSizeIconOption
local offset = freeSlot*-(41)+41
local maxSlots = self.RealBag:GetBagCapacity()
self.wndSplitSlot:FindChild("RealBagWindow"):SetAnchorOffsets(-20+offset,0,3250+offset,48)
self.wndSplitSlot:Show(true)
end
end
---------------------------------------------------------------------------------------------------
-- Utils
---------------------------------------------------------------------------------------------------
--all numbers are positive
function ChargeSortedBags:MergeSortlvl(tables)
if #tables < 2 then
return tables
end
local h = #tables/2
local LTable = {}
local RTable = {}
for i = 1, #tables do
if i <= h then
table.insert(LTable,tables[i])
else
table.insert(RTable,tables[i])
end
end
LTable = self:MergeSortlvl(LTable)
RTable = self:MergeSortlvl(RTable)
local max = #tables
local Table = {}
local left = 1
local right = 1
for i = 1, max do
local leftilvl = -1
local rightilvl = -1
if left < #LTable+1 then
leftilvl = GameLib.GetBagItem(LTable[left]):GetDetailedInfo()["tPrimary"]["nItemLevel"]
end
if right < #RTable+1 then
rightilvl = GameLib.GetBagItem(RTable[right]):GetDetailedInfo()["tPrimary"]["nItemLevel"]
end
if leftilvl > rightilvl then
Table[i] = LTable[left]
left = left+1
else
Table[i] = RTable[right]
right = right+1
end
end
return Table
end
function ChargeSortedBags:NameSort(tables)
if #tables == 0 then
return
end
--the input is a ilvl-sorted table
local All = {}
local order = {}
local t = 1
for i = 1, #tables do
local ilvl = GameLib.GetBagItem(tables[i]):GetDetailedInfo()["tPrimary"]["nItemLevel"]
if All[ilvl] == nil then
All[ilvl] = {}
order[t] = ilvl
t= t+1
end
table.insert(All[ilvl],tables[i])
end
local returnTable = {}
local z = 1;
for i,j in pairs(order) do
table.sort(All[j], fnSortItemsByName)
for t,l in pairs(All[j]) do
returnTable[z] = l
z = z+1
end
end
return returnTable
end
--thanks to Johan Lindström (Jabbit-EU, Joxye Nadrax / Wildstar) for the Split Function
-- Compatibility: Lua-5.1
function ChargeSortedBags:Split(str, pat)
local t = {} -- NOTE: use {n = 0} in Lua-5.0
local fpat = "(.-)" .. pat
local last_end = 1
local s, e, cap = str:find(fpat, 1)
while s do
if s ~= 1 or cap ~= "" then
table.insert(t,cap)
end
last_end = e+1
s, e, cap = str:find(fpat, last_end)
end
if last_end <= #str then
cap = str:sub(last_end)
table.insert(t, cap)
end
return t
end
local InventoryBagInst = ChargeSortedBags:new()
InventoryBagInst:Init()
| apache-2.0 |
interfaceware/iguana-web-apps | scratch/shared/server/simplewebserver.lua | 2 | 3156 | local server = {}
server.simplewebserver = {}
local ws = server.simplewebserver
local wsutils = require 'server.utils'
function ws.default()
return ws.template(app.config.approot..'/index.html', app.default())
end
-- Find the method for the action.
function ws.serveRequest(Data)
local R = net.http.parseRequest{data=Data}
trace(R.location)
-- Get the action name by stipping off the app root
local ActionName = R.location:sub(#app.config.approot+1)
local Action = app.actions[ActionName]
trace(Action)
trace(app)
-- Ajax requests. This design is for single page apps.
-- Only the default below serves an entire HTML page.
if Action then
trace(R)
local Func = app[Action]
if not Func then
net.http.respond{body="Action "..Action.." does not exist!"}
return
else
local Result = app[Action](R)
Result = json.serialize{data=Result}
net.http.respond{body=Result, entity_type='text/json'}
return
end
end
-- All other resources. CSS, JS, etc.
local Resource = app.ui[R.location]
if Resource then
local Body = ws.template(R.location, Resource)
net.http.respond{body=Body, entity_type=ws.entity(R.location)}
return
end
local OtherFile = wsutils.loadOtherFile(R.location)
if (OtherFile) then
net.http.respond{body=OtherFile, entity_type=ws.entity(R.location)}
return
end
-- Default page. The only HTML page.
net.http.respond{body=ws.default(R)}
end
function ws.template(Name, Content)
local NameOnDisk = Name:gsub("/", "_")
if iguana.isTest() and app.ui[Name] then
local F = io.open(NameOnDisk, 'w+')
trace(app.ui[Name])
F:write(app.ui[Name]);
F:close()
elseif not iguana.isTest() then
local F = io.open(NameOnDisk, 'r')
if (F) then
Content = F:read('*a');
F:close()
end
end
return Content
end
local ContentTypeMap = {
['.js'] = 'application/x-javascript',
['.css'] = 'text/css',
['.gif'] = 'image/gif'
}
function ws.entity(Location)
local Ext = Location:match('.*(%.%a+)$')
local Entity = ContentTypeMap[Ext]
return Entity or 'text/plain'
end
return ws
--[[
-- This template writes all resources in the map each time.
-- The one above only writes the one in the current request.
function ui.template(Name, Content)
Name = Name:gsub("/", "_")
if iguana.isTest() then
for Key, Val in pairs(ui.ResourceTable) do
Key = Key:gsub("/", "_")
local File = io.open(Key, 'w+')
File:write(Val);
File:close()
end
else
local File = io.open(Name, 'r')
if (File) then
Content = File:read('*a');
File:close()
end
end
return Content
end
function ws.mapRequest(T, R)
T.server_guid = R.guid
T.ts = os.ts.time()
T.summary = R.summary
T.status = R.retcode
T.name = R.name
return T
end
ws.threshold = 1000
function ws.connection()
return db.connect{api=db.SQLITE, name='status'}
end
function ws.css(R)
return presentation.css(R)
end
]]
| mit |
bigdogmat/wire | lua/entities/gmod_wire_expression2/core/custom/cl_constraintcore.lua | 9 | 3758 | language.Add("Undone_e2_axis", "Undone E2 Axis")
language.Add("Undone_e2_ballsocket", "Undone E2 Ballsocket")
language.Add("Undone_e2_winch", "Undone E2 Winch")
language.Add("Undone_e2_hydraulic", "Undone E2 Hydraulic")
language.Add("Undone_e2_rope", "Undone E2 Rope")
language.Add("Undone_e2_slider", "Undone E2 Slider")
language.Add("Undone_e2_nocollide", "Undone E2 Nocollide")
language.Add("Undone_e2_weld", "Undone E2 Weld")
E2Helper.Descriptions["enableConstraintUndo"] = "If 0, suppresses creation of undo entries for constraints"
E2Helper.Descriptions["axis(evev)"] = "Creates an axis constraint between two entities at vectors local to each entity"
E2Helper.Descriptions["axis(evevn)"] = "Creates an axis constraint between two entities at vectors local to each entity with friction"
E2Helper.Descriptions["axis(evevnv)"] = "Creates an axis constraint between two entities at vectors local to each entity with friction and local rotation axis"
E2Helper.Descriptions["ballsocket"] = "Creates a ballsocket constraint between two entities at a vector local to ent1"
E2Helper.Descriptions["ballsocket(evevvv)"] = "Creates an AdvBallsocket constraint between two entities at a vector local to ent1, using the specified mins, maxs, and frictions"
E2Helper.Descriptions["ballsocket(evevvvn)"] = "Creates an AdvBallsocket constraint between two entities at a vector local to ent1, using the specified mins, maxs, frictions, rotateonly"
E2Helper.Descriptions["weldAng"] = "Creates an angular weld constraint (angles are fixed, position is free) between two entities at a vector local to ent1"
E2Helper.Descriptions["winch"] = "Creates a winch constraint with a referenceid, between two entities, at vectors local to each"
E2Helper.Descriptions["hydraulic(nevevn)"] = "Creates a hydraulic constraint with a referenceid, between two entities, at vectors local to each"
E2Helper.Descriptions["hydraulic(nevevnnsnn)"] = "Creates a hydraulic constraint with a referenceid, between two entities, at vectors local to each, with constant, damping, and stretch only"
E2Helper.Descriptions["hydraulic(nevevnnnsnn)"] = "Creates a hydraulic constraint with a referenceid, between two entities, at vectors local to each, with constant, damping, relative damping and stretch only"
E2Helper.Descriptions["rope(nevev)"] = "Creates a rope constraint with a referenceid, between two entities, at vectors local to each"
E2Helper.Descriptions["rope(nevevnns)"] = "Creates a rope constraint with a referenceid, between two entities, at vectors local to each with add length, width, and material"
E2Helper.Descriptions["rope(nevevnnsn)"] = "Creates a rope constraint with a referenceid, between two entities, at vectors local to each with add length, width, material, and rigidity"
E2Helper.Descriptions["setLength(e:nn)"] = "Sets the length of a winch/hydraulic/rope stored in this entity at a referenceid"
E2Helper.Descriptions["slider"] = "Creates a slider constraint between two entities at vectors local to each entity"
E2Helper.Descriptions["noCollide"] = "Creates a nocollide constraint between two entities"
E2Helper.Descriptions["noCollideAll"] = "Nocollides an entity to all entities/players, just like the tool's right-click"
E2Helper.Descriptions["weld"] = "Creates a weld constraint between two entities"
E2Helper.Descriptions["constraintBreak(e:)"] = "Breaks all constraints of all types on an entity"
E2Helper.Descriptions["constraintBreak(e:e)"] = "Breaks all constraints between two entities"
E2Helper.Descriptions["constraintBreak(e:s)"] = "Breaks all constraints of a type (weld, axis, nocollide, ballsocket) on an entity"
E2Helper.Descriptions["constraintBreak(e:se)"] = "Breaks a constraint of a type (weld, axis, nocollide, ballsocket) between two entities"
| apache-2.0 |
Movimento5StelleLazio/WebMCP | framework/env/request/__init.lua | 2 | 2728 | request._status = nil
request._forward = nil
request._forward_processed = false
request._redirect = nil
request._absolute_baseurl = nil
request._is_404 = false
request._404_route = nil
request._force_absolute_baseurl = false
request._perm_params = {}
request._csrf_secret = nil
request._json_requests_allowed = false
request._params = {}
local depth
if cgi then -- if-clause to support interactive mode
if cgi.params._webmcp_404 then
request.force_absolute_baseurl()
request._is_404 = true
end
for key, value in pairs(cgi.params) do
if not string.match(key, "^_webmcp_") then
request._params[key] = value
end
end
local path = cgi.params._webmcp_path
if path then
local function parse()
local module, action, view, suffix, id
if path == "" then
request._module = "index"
request._view = "index"
return
end
module = string.match(path, "^([^/]+)/$")
if module then
request._module = module
request._view = "index"
return
end
module, action = string.match(path, "^([^/]+)/([^/.]+)$")
if module then
request._module = module
request._action = action
return
end
module, view, suffix = string.match(path, "^([^/]+)/([^/.]+)%.([^/]+)$")
if module then
request._module = module
request._view = view
request._suffix = suffix
return
end
module, view, id, suffix = string.match(path, "^([^/]+)/([^/]+)/([^/.]+)%.([^/]+)$")
if module then
request._module = module
request._view = view
request._id = id
request._suffix = suffix
return
end
request._is_404 = true
end
parse()
-- allow id to also be set by "_webmcp_id" parameter
if cgi.params._webmcp_id ~= nil then
request._id = cgi.params._webmcp_id
end
depth = 0
for match in string.gmatch(path, "/") do
depth = depth + 1
end
else
request._module = cgi.params._webmcp_module
request._action = cgi.params._webmcp_action
request._view = cgi.params._webmcp_view
request._suffix = cgi.params._webmcp_suffix
request._id = cgi.params._webmcp_id
depth = tonumber(cgi.params._webmcp_urldepth)
end
end
if depth and depth > 0 then
local elements = {}
for i = 1, depth do
elements[#elements+1] = "../"
end
request._relative_baseurl = table.concat(elements)
else
request._relative_baseurl = "./"
end
request._app_basepath = assert(
os.getenv("WEBMCP_APP_BASEPATH"),
'WEBMCP_APP_BASEPATH is not set.'
)
if not string.find(request._app_basepath, "/$") then
request._app_basebase = request._app_basepath .. "/"
end
| mit |
Movimento5StelleLazio/WebMCP | demo-app/locale/translations.de.lua | 2 | 2249 | #!/usr/bin/env lua
return {
["Admin"] = "Admin";
["Are you sure?"] = "Bist Du sicher?";
["Back"] = "Zurück";
["Copy protected"] = "Kopiergeschützt";
["Create new genre"] = "Neues Genre anlegen";
["Create new media type"] = "Neuen Medientyp anlegen";
["Create new medium"] = "Neues Medium anlegen";
["Create new user"] = "Neuen Benutzer anlegen";
["Delete"] = "Löschen";
["Description"] = "Beschreibung";
["Duration"] = "Dauer";
["Genre"] = "Genre";
["Genre '#{name}' created"] = "Genre '#{name}' angelegt";
["Genre '#{name}' deleted"] = "Genre '#{name}' gelöscht";
["Genre '#{name}' updated"] = "Genre '#{name}' aktualisiert";
["Genres"] = "Genres";
["Home"] = "Startseite";
["Id"] = "Id";
["Ident"] = "Ident";
["Invalid username or password!"] = "Ungülter Benutzername oder Kennwort";
["Language changed"] = "Sprache gewechselt";
["Login"] = "Anmeldung";
["Login successful!"] = "Anmeldung erfolgreich!";
["Logout"] = "Abmelden";
["Logout successful"] = "Anmeldung erfolgreich";
["Media"] = "Medium";
["Media type"] = "Medientyp";
["Media type '#{name}' created"] = "Medientyp '#{name}' angelegt";
["Media type '#{name}' deleted"] = "Medientyp '#{name}' gelöscht";
["Media type '#{name}' updated"] = "Medientyp '#{name}' aktualisiert";
["Media types"] = "Medientypen";
["Medium"] = "Medium";
["Medium '#{name}' created"] = "Medium '#{name}' angelegt";
["Medium '#{name}' deleted"] = "Medium '#{name}' gelöscht";
["Medium '#{name}' updated"] = "Medium '#{name}' aktualisiert";
["Name"] = "Name";
["New genre"] = "Neues Genre";
["New media type"] = "Neuer Medientyp";
["New medium"] = "Neues Medium";
["New user"] = "Neuer Benutzer";
["Password"] = "Kennwort";
["Password login"] = "Anmeldung mit Kennwort";
["Pos"] = "Pos";
["Save"] = "Speichern";
["Show"] = "Anzeigen";
["Tracks"] = "Stücke";
["User"] = "Benutzer";
["User '#{name}' created"] = "Benutzer '#{name}' angelegt";
["User '#{name}' deleted"] = "Benutzer '#{name}' gelöscht";
["User '#{name}' updated"] = "Benutzer '#{name}' aktualisiert";
["Username"] = "Benutzername";
["Users"] = "Benutzer";
["Welcome to webmcp demo application"] = "Willkommen zur webmcp Demo-Anwendung";
["Write Priv"] = "Schreibrecht";
["w"] = "w";
["webmcp demo application"] = "webmcp Demo-Anwendung";
}
| mit |
interfaceware/iguana-web-apps | Bed Monitor - 2.ADT In_to/main.lua | 2 | 1040 | require 'bedmonitor.db'
require 'node'
bedmonitor.db.init()
function main(Data)
local Hl7 = hl7.parse{vmd='app/bedmonitor/demo.vmd', data=Data}
local T = db.tables{vmd="app/bedmonitor/bedtables.vmd", name="ADT"}
local Db = bedmonitor.db.connect()
if Hl7.MSH[9][1]:nodeValue() == 'ADT' then
if Hl7.MSH[9][2]:nodeValue() == 'A03' then
DischargePatient(T.bed[1], Hl7.PV1)
else
MapPatient(T.bed[1], Hl7.PID)
MapVisit(T.bed[1], Hl7.PV1)
MapObservation(T.bed[1], Hl7.OBX)
end
T:S()
Db:merge{data=T, live=true}
end
end
function DischargePatient(T, PV1)
T.patient_first_name = ""
T.patient_last_name = ""
T.condition = ""
MapVisit(T, PV1)
end
function MapPatient(T, PID)
T.patient_first_name = PID[5][1][2]:nodeValue()
T.patient_last_name = PID[5][1][1][1]:nodeValue()
end
function MapVisit(T, PV1)
T.ward = PV1[3][1]:nodeValue()
T.bed_name = PV1[3][3]
end
function MapObservation(T, OBX)
T.condition = OBX[3][5][1][2]
end
| mit |
boundary/boundary-nagios-plugins | nagios_output_parser_test.lua | 1 | 1694 | -- Copyright 2014 Boundary,Inc.
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
require("nagios_output_parser")
require("metric_name_mapper")
require("metric")
require("utils")
local LuaUnit = require("luaunit")
TestNagiosOutputParser = {}
function TestNagiosOutputParser:setUp()
self.p = NagiosOutputParser:new()
self.m = MetricNameMapper:new()
end
function TestNagiosOutputParser:tearDown()
self.m = nil
end
function TestNagiosOutputParser:testConstructor()
local o = NagiosOutputParser:new()
assertEquals(o ~= nil,true)
end
function TestNagiosOutputParser:testCheckLoad()
self.m:add("load1","LOAD_1_MINUTE")
self.m:add("load5","LOAD_5_MINUTE")
self.m:add("load15","LOAD_15_MINUTE")
self.p:setMapper(self.m)
local s = "CRITICAL - load average: 1.91, 0.00, 0.00|load1=1.910;0.000;0.000;0; load5=0.000;0.000;0.000;0; load15=0.000;0.000;0.000;0;"
local values = self.p:parse(s)
-- dumpTable(values)
end
function TestNagiosOutputParser:testCheckUsers()
self.m:add("users")
self.p:setMapper(self.m)
local s = "USERS CRITICAL - 5 users currently logged in |users=5;1;1;0"
local values = self.p:parse(s)
-- dumpTable(values)
end
LuaUnit:run()
| apache-2.0 |
cpascal/skynet | lualib/skynet/manager.lua | 72 | 1923 | local skynet = require "skynet"
local c = require "skynet.core"
function skynet.launch(...)
local addr = c.command("LAUNCH", table.concat({...}," "))
if addr then
return tonumber("0x" .. string.sub(addr , 2))
end
end
function skynet.kill(name)
if type(name) == "number" then
skynet.send(".launcher","lua","REMOVE",name, true)
name = skynet.address(name)
end
c.command("KILL",name)
end
function skynet.abort()
c.command("ABORT")
end
local function globalname(name, handle)
local c = string.sub(name,1,1)
assert(c ~= ':')
if c == '.' then
return false
end
assert(#name <= 16) -- GLOBALNAME_LENGTH is 16, defined in skynet_harbor.h
assert(tonumber(name) == nil) -- global name can't be number
local harbor = require "skynet.harbor"
harbor.globalname(name, handle)
return true
end
function skynet.register(name)
if not globalname(name) then
c.command("REG", name)
end
end
function skynet.name(name, handle)
if not globalname(name, handle) then
c.command("NAME", name .. " " .. skynet.address(handle))
end
end
local dispatch_message = skynet.dispatch_message
function skynet.forward_type(map, start_func)
c.callback(function(ptype, msg, sz, ...)
local prototype = map[ptype]
if prototype then
dispatch_message(prototype, msg, sz, ...)
else
dispatch_message(ptype, msg, sz, ...)
c.trash(msg, sz)
end
end, true)
skynet.timeout(0, function()
skynet.init_service(start_func)
end)
end
function skynet.filter(f ,start_func)
c.callback(function(...)
dispatch_message(f(...))
end)
skynet.timeout(0, function()
skynet.init_service(start_func)
end)
end
function skynet.monitor(service, query)
local monitor
if query then
monitor = skynet.queryservice(true, service)
else
monitor = skynet.uniqueservice(true, service)
end
assert(monitor, "Monitor launch failed")
c.command("MONITOR", string.format(":%08x", monitor))
return monitor
end
return skynet
| mit |
tianxiawuzhei/cocos-quick-lua | quick/framework/cocos2dx/NodeEx.lua | 1 | 15871 | --[[
Copyright (c) 2011-2014 chukong-inc.com
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.
]]
--[[--
针对 cc.Node 的扩展
]]
local c = cc
local Node = c.Node
-- touch
c.TouchesAllAtOnce = cc.TOUCHES_ALL_AT_ONCE
c.TouchesOneByOne = cc.TOUCHES_ONE_BY_ONE
c.TOUCH_MODE_ALL_AT_ONCE = c.TouchesAllAtOnce
c.TOUCH_MODE_ONE_BY_ONE = c.TouchesOneByOne
local flagNodeTouchInCocos = false
if Node.removeTouchEvent then flagNodeTouchInCocos = true end
local function isPointIn( rc, pt )
local rect = cc.rect(rc.x, rc.y, rc.width, rc.height)
return cc.rectContainsPoint(rect, pt)
end
function Node:align(anchorPoint, x, y)
self:setAnchorPoint(display.ANCHOR_POINTS[anchorPoint])
if x and y then self:setPosition(x, y) end
return self
end
function Node:schedule(callback, interval)
local seq = transition.sequence({
cc.DelayTime:create(interval),
cc.CallFunc:create(callback),
})
local action = cc.RepeatForever:create(seq)
self:runAction(action)
return action
end
function Node:performWithDelay(callback, delay)
local action = transition.sequence({
cc.DelayTime:create(delay),
cc.CallFunc:create(callback),
})
self:runAction(action)
return action
end
function Node:getCascadeBoundingBox()
local rc
local func = tolua.getcfunction(self, "getCascadeBoundingBox")
if func then
rc = func(self)
end
rc.origin = {x=rc.x, y=rc.y}
rc.size = {width=rc.width, height=rc.height}
rc.containsPoint = isPointIn
return rc
end
--[[--
测试一个点是否在当前结点区域中
@param tabel point cc.p的点位置,世界坐标
@param boolean isCascade 是否用结点的所有子结点共同区域计算还是只用本身的区域
@return boolean 是否在结点区域中
]]
function Node:hitTest(point, isCascade)
local nsp = self:convertToNodeSpace(point)
local rect
if isCascade then
rect = self:getCascadeBoundingBox()
else
rect = self:getBoundingBox()
end
rect.x = 0
rect.y = 0
if cc.rectContainsPoint(rect, nsp) then
return true
end
return false
end
function Node:removeSelf()
self:removeFromParent(true)
end
function Node:onEnter()
end
function Node:onExit()
end
function Node:onEnterTransitionFinish()
end
function Node:onExitTransitionStart()
end
function Node:onCleanup()
end
function Node:setNodeEventEnabled(enabled, listener)
if enabled then
if self.__node_event_handle__ then
self:removeNodeEventListener(self.__node_event_handle__)
self.__node_event_handle__ = nil
end
if not listener then
listener = function(event)
local name = event.name
if name == "enter" then
self:onEnter()
elseif name == "exit" then
self:onExit()
elseif name == "enterTransitionFinish" then
self:onEnterTransitionFinish()
elseif name == "exitTransitionStart" then
self:onExitTransitionStart()
elseif name == "cleanup" then
self:onCleanup()
end
end
end
self.__node_event_handle__ = self:addNodeEventListener(c.NODE_EVENT, listener)
elseif self.__node_event_handle__ then
self:removeNodeEventListener(self.__node_event_handle__)
self.__node_event_handle__ = nil
end
return self
end
function Node:setTouchEnabled(enable)
local func = tolua.getcfunction(self, "setTouchEnabled")
func(self, enable)
if not flagNodeTouchInCocos then
return self
end
self:setBaseNodeEventListener()
return self
end
function Node:setTouchMode(mode)
local func = tolua.getcfunction(self, "setTouchMode")
func(self, mode)
if not flagNodeTouchInCocos then
return self
end
self:setBaseNodeEventListener()
return self
end
function Node:setTouchSwallowEnabled(enable)
local func = tolua.getcfunction(self, "setTouchSwallowEnabled")
func(self, enable)
if not flagNodeTouchInCocos then
return self
end
self:setBaseNodeEventListener()
return self
end
function Node:setTouchCaptureEnabled(enable)
local func = tolua.getcfunction(self, "setTouchCaptureEnabled")
func(self, enable)
if not flagNodeTouchInCocos then
return self
end
self:setBaseNodeEventListener()
return self
end
function Node:setKeypadEnabled(enable)
if not flagNodeTouchInCocos then
self:setKeyboardEnabled(enable)
return self
end
_enable = self._keyboardEnabled or false
if enable == _enable then
return self
end
self._keyboardEnabled = enable
if self.__key_event_handle__ then
local eventDispatcher = self:getEventDispatcher()
eventDispatcher:removeEventListener(self.__key_event_handle__)
self.__key_event_handle__ = nil
end
if enable then
local onKeyPressed = function ( keycode, event )
return self:EventDispatcher(c.KEYPAD_EVENT, {keycode, event, "Pressed"})
end
local onKeyReleased = function ( keycode, event )
return self:EventDispatcher(c.KEYPAD_EVENT, {keycode, event, "Released"})
end
local listener = cc.EventListenerKeyboard:create()
listener:registerScriptHandler(onKeyPressed, cc.Handler.EVENT_KEYBOARD_PRESSED )
listener:registerScriptHandler(onKeyReleased, cc.Handler.EVENT_KEYBOARD_RELEASED )
local eventDispatcher = self:getEventDispatcher()
eventDispatcher:addEventListenerWithSceneGraphPriority(listener, self)
self.__key_event_handle__ = listener
end
return self
end
function Node:isKeypadEnabled()
if not flagNodeTouchInCocos then
return self:isKeyboardEnabled()
end
enable = self._keyboardEnabled or false
return enable
end
function Node:scheduleUpdate()
if not flagNodeTouchInCocos then
tolua.getcfunction(self, "scheduleUpdate")(self)
return self
end
local listener = function (dt)
self:EventDispatcher(c.NODE_ENTER_FRAME_EVENT, dt)
end
self:scheduleUpdateWithPriorityLua(listener, 0)
return self
end
function Node:setBaseNodeEventListener()
if self._baseNodeEventListener_ then return end
self._baseNodeEventListener_ = function(evt)
self:EventDispatcher(c.NODE_EVENT, evt)
end
self:registerScriptHandler(self._baseNodeEventListener_)
end
function Node:addNodeEventListener( evt, hdl, tag, priority )
if not flagNodeTouchInCocos then
return tolua.getcfunction(self, "addNodeEventListener")(self, evt, hdl, tag, priority)
end
priority = priority or 0
if not self._scriptEventListeners_ then
self._scriptEventListeners_ = {}
self:setBaseNodeEventListener()
end
local luaListeners_ = self._scriptEventListeners_
local idx = self._nextScriptEventHandleIndex_ or 0
idx = idx + 1
self._nextScriptEventHandleIndex_ = idx
if not luaListeners_[evt] then
luaListeners_[evt] = {}
end
local eventListeners_ = luaListeners_[evt]
local lis = {
index_ = idx,
listener_ = hdl,
tag_ = tag,
priority_ = priority,
enable_ = true,
removed_ = false,
}
if evt==c.NODE_ENTER_FRAME_EVENT or evt == c.NODE_TOUCH_EVENT then
eventListeners_[1] = lis
else
table.insert(eventListeners_, lis)
end
return self._nextScriptEventHandleIndex_
end
function Node:removeNodeEventListener(listener)
if not flagNodeTouchInCocos then
local func = tolua.getcfunction(self, "removeNodeEventListener")
if func then return func(self, listener) end
return
end
if not self._scriptEventListeners_ then return end
for evt,liss in pairs(self._scriptEventListeners_) do
for i,v in ipairs(liss) do
if v.index_==listener then
table.remove(liss, i)
if #liss==0 then
self:removeNodeEventListenersByEvent(evt)
end
return
end
end
end
end
function Node:removeNodeEventListenersByEvent( evt )
if not flagNodeTouchInCocos then
tolua.getcfunction(self, "removeNodeEventListenersByEvent")(self, evt)
return
end
if self._scriptEventListeners_ and self._scriptEventListeners_[evt] then
if evt==c.KEYPAD_EVENT then
self:setKeypadEnabled(false)
elseif evt==c.NODE_ENTER_FRAME_EVENT then
self:unscheduleUpdate()
elseif evt==c.NODE_TOUCH_EVENT then
self:removeTouchEvent()
elseif evt==c.NODE_TOUCH_CAPTURE_EVENT then
self:removeTouchEvent()
end
self._scriptEventListeners_[evt] = nil
end
end
function Node:removeAllNodeEventListeners()
if not flagNodeTouchInCocos then
tolua.getcfunction(self, "removeAllNodeEventListeners")(self)
return
end
self:removeNodeEventListenersByEvent(c.NODE_EVENT)
self:removeNodeEventListenersByEvent(c.NODE_ENTER_FRAME_EVENT)
self:removeNodeEventListenersByEvent(c.NODE_TOUCH_EVENT)
self:removeNodeEventListenersByEvent(c.NODE_TOUCH_CAPTURE_EVENT)
self:removeNodeEventListenersByEvent(c.KEYPAD_EVENT)
end
local function KeypadEventCodeConvert( code )
local key
if code==6 then
key = "back"
elseif code==16 then
key = "menu"
else
key = tostring(code)
end
return key
end
function Node:EventDispatcher( idx, data )
-- if idx~=1 then
-- print("-----Entry Node:EventDispatcher: "..idx)
-- end
local obj = self
local flagNodeCleanup = false
local event
local touch_event = nil
if idx==c.NODE_EVENT then
event = { name=data }
if data=="cleanup" then
flagNodeCleanup = true
end
elseif idx==c.NODE_ENTER_FRAME_EVENT then
event = data
elseif idx==c.KEYPAD_EVENT then
local code = data[1]
-- local evt = data[2]
local ename = data[3]
if ename~='Released' then return true end
event = { code=code, key=KeypadEventCodeConvert(code), }
else
event = data
-- dump(event)
touch_event = event
end
local rnval = false
if idx==cc.NODE_TOUCH_CAPTURE_EVENT then
rnval = true
end
local flagNeedClean = false
local listener
if obj._scriptEventListeners_ then
listener = obj._scriptEventListeners_[idx]
end
if listener then
for i,v in ipairs(listener) do
if v.removed_ then
flagNeedClean = true
else
if touch_event and touch_event.name=="began" then
v.enable_ = true
end
if v.enable_ then
local listenerRet = v.listener_(event)
if not listenerRet then
if idx==cc.NODE_TOUCH_CAPTURE_EVENT then
local evtname = event.name
if (evtname=="began") or (evtname=="moved") then
rnval = false
end
elseif idx==cc.NODE_TOUCH_EVENT then
if event.name=="began" then
v.enable_ = false
end
rnval = rnval or listenerRet
else
rnval = rnval or listenerRet
end
else
-- printf("listenerRet: ", tostring(listenerRet))
return listenerRet
end
end
end
end
end
if flagNodeCleanup then
obj:setTouchEnabled(false)
obj:removeAllNodeEventListeners()
obj:removeTouchEvent()
obj:unregisterScriptHandler()
end
return rnval
end
-- clone related
function Node:clone()
local cloneNode = self:createCloneInstance_()
cloneNode:copyProperties_(self)
cloneNode:copySpecialPeerVal_(self)
cloneNode:copyClonedWidgetChildren_(self)
return cloneNode
end
function Node:createCloneInstance_()
local nodeType = tolua.type(self)
local cloneNode
if "cc.Sprite" == nodeType then
cloneNode = cc.Sprite:create()
elseif "ccui.Scale9Sprite" == nodeType then
cloneNode = ccui.Scale9Sprite:create()
elseif "cc.LayerColor" == nodeType then
local clr = self:getColor()
clr.a = self:getOpacity()
cloneNode = cc.LayerColor:create(clr)
else
cloneNode = display.newNode()
if "cc.Node" ~= nodeType then
print("WARING! treat " .. nodeType .. " as cc.Node")
end
end
return cloneNode
end
function Node:copyClonedWidgetChildren_(node)
local children = node:getChildren()
if not children or 0 == #children then
return
end
for i, child in ipairs(children) do
local cloneChild = child:clone()
if cloneChild then
self:addChild(cloneChild)
end
end
end
function Node:copySpecialProperties_(node)
local nodeType = tolua.type(self)
if "cc.Sprite" == nodeType then
self:setSpriteFrame(node:getSpriteFrame())
elseif "ccui.Scale9Sprite" == nodeType then
self:setSpriteFrame(node:getSprite():getSpriteFrame())
elseif "cc.LayerColor" == nodeType then
self:setTouchEnabled(false)
end
-- copy peer
local peer = tolua.getpeer(node)
if peer then
local clonePeer = clone(peer)
tolua.setpeer(self, clonePeer)
end
end
function Node:copyProperties_(node)
self:setVisible(node:isVisible())
self:setTouchEnabled(node:isTouchEnabled())
self:setLocalZOrder(node:getLocalZOrder())
self:setTag(node:getTag())
self:setName(node:getName())
self:setContentSize(node:getContentSize())
self:setPosition(node:getPosition())
self:setAnchorPoint(node:getAnchorPoint())
self:setScaleX(node:getScaleX())
self:setScaleY(node:getScaleY())
self:setRotation(node:getRotation())
self:setRotationSkewX(node:getRotationSkewX())
self:setRotationSkewY(node:getRotationSkewY())
if self.isFlippedX and node.isFlippedX then
self:setFlippedX(node:isFlippedX())
self:setFlippedY(node:isFlippedY())
end
self:setColor(node:getColor())
self:setOpacity(node:getOpacity())
self:copySpecialProperties_(node)
end
-- 拷贝特殊的peer值
function Node:copySpecialPeerVal_(node)
if node.name then
self.name = node.name
end
end
| mit |
arventwei/WioEngine | Tools/jamplus/src/luaplus/Src/Modules/socket/test/ltn12test.lua | 12 | 8625 | local ltn12 = require("ltn12")
dofile("testsupport.lua")
local function format(chunk)
if chunk then
if chunk == "" then return "''"
else return string.len(chunk) end
else return "nil" end
end
local function show(name, input, output)
local sin = format(input)
local sout = format(output)
io.write(name, ": ", sin, " -> ", sout, "\n")
end
local function chunked(length)
local tmp
return function(chunk)
local ret
if chunk and chunk ~= "" then
tmp = chunk
end
ret = string.sub(tmp, 1, length)
tmp = string.sub(tmp, length+1)
if not chunk and ret == "" then ret = nil end
return ret
end
end
local function named(f, name)
return function(chunk)
local ret = f(chunk)
show(name, chunk, ret)
return ret
end
end
--------------------------------
local function split(size)
local buffer = ""
local last_out = ""
local last_in = ""
local function output(chunk)
local part = string.sub(buffer, 1, size)
buffer = string.sub(buffer, size+1)
last_out = (part ~= "" or chunk) and part
last_in = chunk
return last_out
end
return function(chunk, done)
if done then
return not last_in and not last_out
end
-- check if argument is consistent with state
if not chunk then
if last_in and last_in ~= "" and last_out ~= "" then
error("nil chunk following data chunk", 2)
end
if not last_out then error("extra nil chunk", 2) end
return output(chunk)
elseif chunk == "" then
if last_out == "" then error('extra "" chunk', 2) end
if not last_out then error('"" chunk following nil return', 2) end
if not last_in then error('"" chunk following nil chunk', 2) end
return output(chunk)
else
if not last_in then error("data chunk following nil chunk", 2) end
if last_in ~= "" and last_out ~= "" then
error("data chunk following data chunk", 2)
end
buffer = chunk
return output(chunk)
end
end
end
--------------------------------
local function format(chunk)
if chunk then
if chunk == "" then return "''"
else return string.len(chunk) end
else return "nil" end
end
--------------------------------
local function merge(size)
local buffer = ""
local last_out = ""
local last_in = ""
local function output(chunk)
local part
if string.len(buffer) >= size or not chunk then
part = buffer
buffer = ""
else
part = ""
end
last_out = (part ~= "" or chunk) and part
last_in = chunk
return last_out
end
return function(chunk, done)
if done then
return not last_in and not last_out
end
-- check if argument is consistent with state
if not chunk then
if last_in and last_in ~= "" and last_out ~= "" then
error("nil chunk following data chunk", 2)
end
if not last_out then error("extra nil chunk", 2) end
return output(chunk)
elseif chunk == "" then
if last_out == "" then error('extra "" chunk', 2) end
if not last_out then error('"" chunk following nil return', 2) end
if not last_in then error('"" chunk following nil chunk', 2) end
return output(chunk)
else
if not last_in then error("data chunk following nil chunk", 2) end
if last_in ~= "" and last_out ~= "" then
error("data chunk following data chunk", 2)
end
buffer = buffer .. chunk
return output(chunk)
end
end
end
--------------------------------
io.write("testing sink.table: ")
local sink, t = ltn12.sink.table()
local s, c = "", ""
for i = 0, 10 do
c = string.rep(string.char(i), i)
s = s .. c
assert(sink(c), "returned error")
end
assert(sink(nil), "returned error")
assert(table.concat(t) == s, "mismatch")
print("ok")
--------------------------------
io.write("testing sink.chain (with split): ")
sink, t = ltn12.sink.table()
local filter = split(3)
sink = ltn12.sink.chain(filter, sink)
s = "123456789012345678901234567890"
assert(sink(s), "returned error")
assert(sink(s), "returned error")
assert(sink(nil), "returned error")
assert(table.concat(t) == s .. s, "mismatch")
assert(filter(nil, 1), "filter not empty")
print("ok")
--------------------------------
io.write("testing sink.chain (with merge): ")
sink, t = ltn12.sink.table()
filter = merge(10)
sink = ltn12.sink.chain(filter, sink)
s = string.rep("123", 30)
s = s .. string.rep("4321", 30)
for i = 1, 30 do
assert(sink("123"), "returned error")
end
for i = 1, 30 do
assert(sink("4321"), "returned error")
end
assert(sink(nil), "returned error")
assert(filter(nil, 1), "filter not empty")
assert(table.concat(t) == s, "mismatch")
print("ok")
--------------------------------
io.write("testing source.string and pump.all: ")
local source = ltn12.source.string(s)
sink, t = ltn12.sink.table()
assert(ltn12.pump.all(source, sink), "returned error")
assert(table.concat(t) == s, "mismatch")
print("ok")
--------------------------------
io.write("testing source.chain (with split): ")
source = ltn12.source.string(s)
filter = split(5)
source = ltn12.source.chain(source, filter)
sink, t = ltn12.sink.table()
assert(ltn12.pump.all(source, sink), "returned error")
assert(table.concat(t) == s, "mismatch")
assert(filter(nil, 1), "filter not empty")
print("ok")
--------------------------------
io.write("testing source.chain (with split) and sink.chain (with merge): ")
source = ltn12.source.string(s)
filter = split(5)
source = ltn12.source.chain(source, filter)
local filter2 = merge(13)
sink, t = ltn12.sink.table()
sink = ltn12.sink.chain(filter2, sink)
assert(ltn12.pump.all(source, sink), "returned error")
assert(table.concat(t) == s, "mismatch")
assert(filter(nil, 1), "filter not empty")
assert(filter2(nil, 1), "filter2 not empty")
print("ok")
--------------------------------
io.write("testing filter.chain (and sink.chain, with split, merge): ")
source = ltn12.source.string(s)
filter = split(5)
filter2 = merge(13)
local chain = ltn12.filter.chain(filter, filter2)
sink, t = ltn12.sink.table()
sink = ltn12.sink.chain(chain, sink)
assert(ltn12.pump.all(source, sink), "returned error")
assert(table.concat(t) == s, "mismatch")
assert(filter(nil, 1), "filter not empty")
assert(filter2(nil, 1), "filter2 not empty")
print("ok")
--------------------------------
io.write("testing filter.chain (and sink.chain, a bunch): ")
source = ltn12.source.string(s)
filter = split(5)
filter2 = merge(13)
local filter3 = split(7)
local filter4 = merge(11)
local filter5 = split(10)
chain = ltn12.filter.chain(filter, filter2, filter3, filter4, filter5)
sink, t = ltn12.sink.table()
sink = ltn12.sink.chain(chain, sink)
assert(ltn12.pump.all(source, sink))
assert(table.concat(t) == s, "mismatch")
assert(filter(nil, 1), "filter not empty")
assert(filter2(nil, 1), "filter2 not empty")
assert(filter3(nil, 1), "filter3 not empty")
assert(filter4(nil, 1), "filter4 not empty")
assert(filter5(nil, 1), "filter5 not empty")
print("ok")
--------------------------------
io.write("testing filter.chain (and source.chain, with split, merge): ")
source = ltn12.source.string(s)
filter = split(5)
filter2 = merge(13)
local chain = ltn12.filter.chain(filter, filter2)
sink, t = ltn12.sink.table()
source = ltn12.source.chain(source, chain)
assert(ltn12.pump.all(source, sink), "returned error")
assert(table.concat(t) == s, "mismatch")
assert(filter(nil, 1), "filter not empty")
assert(filter2(nil, 1), "filter2 not empty")
print("ok")
--------------------------------
io.write("testing filter.chain (and source.chain, a bunch): ")
source = ltn12.source.string(s)
filter = split(5)
filter2 = merge(13)
local filter3 = split(7)
local filter4 = merge(11)
local filter5 = split(10)
chain = ltn12.filter.chain(filter, filter2, filter3, filter4, filter5)
sink, t = ltn12.sink.table()
source = ltn12.source.chain(source, chain)
assert(ltn12.pump.all(source, sink))
assert(table.concat(t) == s, "mismatch")
assert(filter(nil, 1), "filter not empty")
assert(filter2(nil, 1), "filter2 not empty")
assert(filter3(nil, 1), "filter3 not empty")
assert(filter4(nil, 1), "filter4 not empty")
assert(filter5(nil, 1), "filter5 not empty")
print("ok")
| mit |
tst2005/hate | hate/init.lua | 2 | 11746 | local current_folder = (...):gsub('%.[^%.]+$', '') .. "."
local ffi = require "ffi"
local sdl = require(current_folder .. "sdl2")
local opengl = require(current_folder .. "opengl")
local flags
local hate = {
_LICENSE = "HATE is distributed under the terms of the MIT license. See LICENSE.md.",
_URL = "https://github.com/excessive/hate",
_VERSION_MAJOR = 0,
_VERSION_MINOR = 0,
_VERSION_REVISION = 1,
_VERSION_CODENAME = "Tsubasa",
_DESCRIPTION = "It's not LÖVE."
}
hate._VERSION = string.format(
"%d.%d.%d",
hate._VERSION_MAJOR,
hate._VERSION_MINOR,
hate._VERSION_REVISION
)
-- Set a global so that libs like lcore can detect hate.
-- (granted, most things will also have the "hate" global)
FULL_OF_HATE = hate._VERSION
local function handle_events()
local window = hate.state.window
local event = ffi.new("SDL_Event[?]", 1)
sdl.pollEvent(event)
event = event[0]
-- No event, we're done here.
if event.type == 0 then
return
end
local function sym2str(sym)
-- 0x20-0x7E are ASCII printable characters
if sym >= 0x20 and sym < 0x7E then
return string.char(sym)
end
local specials = {
[13] = "return",
[27] = "escape",
[8] = "backspace",
[9] = "tab",
}
if specials[sym] then
return specials[sym]
end
print(string.format("Unhandled key %d, returning the key code.", sym))
return sym
end
local handlers = {
[sdl.QUIT] = function()
hate.quit()
end,
[sdl.TEXTINPUT] = function(event)
local e = event.text
local t = ffi.string(e.text)
hate.textinput(t)
end,
[sdl.KEYDOWN] = function(event)
local e = event.key
local key = sym2str(e.keysym.sym)
-- e.repeat conflicts with the repeat keyword.
hate.keypressed(key, e["repeat"])
-- escape to quit by default.
if key == "escape" then
hate.event.quit()
end
end,
[sdl.KEYUP] = function(event)
local e = event.key
local key = sym2str(e.keysym.sym)
hate.keyreleased(key)
end,
[sdl.TEXTEDITING] = function(event)
local e = event.edit
-- TODO
end,
[sdl.MOUSEMOTION] = function(event) end,
-- resize, minimize, etc.
[sdl.WINDOWEVENT] = function(event)
local window = event.window
if window.event == sdl.WINDOWEVENT_RESIZED then
local w, h = tonumber(window.data1), tonumber(window.data2)
hate.resize(w, h)
end
end,
[sdl.MOUSEBUTTONDOWN] = function(event)
local e = event.button
print(e.x, e.y)
end,
[sdl.MOUSEBUTTONUP] = function(event)
local e = event.button
print(e.x, e.y)
end,
}
if handlers[event.type] then
handlers[event.type](event)
return
end
print(string.format("Unhandled event type: %s", event.type))
end
function hate.getVersion()
return hate._VERSION_MAJOR, hate._VERSION_MINOR, hate._VERSION_REVISION, hate._VERSION_CODENAME, "HATE"
end
function hate.run()
-- TODO: remove this.
local config = hate.config
if hate.math then
--[[
hate.math.setRandomSeed(os.time())
-- first few randoms aren't good, throw them out.
for i=1,3 do hate.math.random() end
--]]
end
hate.load(arg)
if hate.window then
-- We don't want the first frame's dt to include time taken by hate.load.
if hate.timer then hate.timer.step() end
local dt = 0
while true do
hate.event.pump()
if not hate.state.running then
break
end
-- Update dt, as we'll be passing it to update
if hate.timer then
hate.timer.step()
dt = hate.timer.getDelta()
end
-- Call update and draw
if hate.update then hate.update(dt) end -- will pass 0 if hate.timer is disabled
if hate.window and hate.graphics --[[and hate.window.isCreated()]] then
hate.graphics.clear()
hate.graphics.origin()
if hate.draw then hate.draw() end
hate.graphics.present()
end
if hate.timer then
if hate.window and config.window.delay then
if config.window.delay >= 0.001 then
hate.timer.sleep(config.window.delay)
end
elseif hate.window then
hate.timer.sleep(0.001)
end
end
collectgarbage()
end
sdl.GL_MakeCurrent(hate.state.window, nil)
sdl.GL_DeleteContext(hate.state.gl_context)
sdl.destroyWindow(hate.state.window)
end
hate.quit()
end
function hate.init()
flags = {
gl3 = false,
show_sdl_version = false
}
for _, v in ipairs(arg) do
for k, _ in pairs(flags) do
if v == "--" .. k then
flags[k] = true
end
end
end
local callbacks = {
"load", "quit", "conf",
"keypressed", "keyreleased",
"textinput", "resize"
}
for _, v in ipairs(callbacks) do
local __NULL__ = function() end
hate[v] = __NULL__
end
hate.event = {}
hate.event.pump = handle_events
hate.event.quit = function()
hate.state.running = false
end
hate.filesystem = require(current_folder .. "filesystem")
hate.filesystem.init(arg[0], "HATE")
if hate.filesystem.exists("conf.lua") then
xpcall(require, hate.errhand, "conf")
end
hate.filesystem.deinit()
local config = {
name = "hate",
window = {
width = 854,
height = 480,
vsync = true,
delay = 0.001,
fsaa = 0, -- for love <= 0.9.1 compatibility
msaa = 0,
-- TODO: debug context + multiple attempts at creating contexts
debug = true,
debug_verbose = false,
srgb = true,
gl = {
{ 3, 3 },
{ 2, 1 }
}
},
modules = {
math = true,
timer = true,
graphics = true,
system = true,
window = true,
}
}
hate.conf(config)
hate.config = config
hate.filesystem.init(arg[0], hate.config.name)
hate.state = {}
hate.state.running = true
hate.state.config = config
sdl.init(sdl.INIT_EVERYTHING)
if config.modules.math then
hate.math = require(current_folder .. "math")
end
if config.modules.timer then
hate.timer = require(current_folder .. "timer")
hate.timer.init()
end
if config.modules.window then
-- FIXME
-- if flags.gl3 then
-- sdl.GL_SetAttribute(sdl.GL_CONTEXT_MAJOR_VERSION, 3)
-- sdl.GL_SetAttribute(sdl.GL_CONTEXT_MINOR_VERSION, 3)
-- sdl.GL_SetAttribute(sdl.GL_CONTEXT_PROFILE_MASK, sdl.GL_CONTEXT_PROFILE_CORE)
-- end
if config.window.debug then
sdl.GL_SetAttribute(sdl.GL_CONTEXT_FLAGS, sdl.GL_CONTEXT_DEBUG_FLAG)
end
sdl.GL_SetAttribute(sdl.GL_MULTISAMPLESAMPLES, math.max(config.window.fsaa or 0, config.window.msaa or 0))
local window_flags = tonumber(sdl.WINDOW_OPENGL)
if config.window.resizable then
window_flags = bit.bor(window_flags, tonumber(sdl.WINDOW_RESIZABLE))
end
if config.window.vsync then
window_flags = bit.bor(window_flags, tonumber(sdl.RENDERER_PRESENTVSYNC))
end
if config.window.srgb and jit.os ~= "Linux" then
-- print(sdl.GL_FRAMEBUFFER_SRGB_CAPABLE)
sdl.GL_SetAttribute(sdl.GL_FRAMEBUFFER_SRGB_CAPABLE, 1)
end
local window = sdl.createWindow(hate.config.name,
sdl.WINDOWPOS_UNDEFINED, sdl.WINDOWPOS_UNDEFINED,
hate.config.window.width, hate.config.window.height,
window_flags
)
assert(window)
local ctx = sdl.GL_CreateContext(window)
assert(ctx)
hate.state.window = window
hate.state.gl_context = ctx
sdl.GL_MakeCurrent(window, ctx)
if config.window.vsync then
if type(config.window.vsync) == "number" then
sdl.GL_SetSwapInterval(config.window.vsync)
else
sdl.GL_SetSwapInterval(1)
end
else
sdl.GL_SetSwapInterval(0)
end
opengl.loader = function(fn)
local ptr = sdl.GL_GetProcAddress(fn)
if flags.gl_debug then
print(string.format("Loaded GL function: %s (%s)", fn, tostring(ptr)))
end
return ptr
end
opengl:import()
local version = ffi.string(gl.GetString(GL.VERSION))
local renderer = ffi.string(gl.GetString(GL.RENDERER))
if config.window.debug then
if gl.DebugMessageCallbackARB then
local gl_debug_source_string = {
[tonumber(GL.DEBUG_SOURCE_API_ARB)] = "API",
[tonumber(GL.DEBUG_SOURCE_WINDOW_SYSTEM_ARB)] = "WINDOW_SYSTEM",
[tonumber(GL.DEBUG_SOURCE_SHADER_COMPILER_ARB)] = "SHADER_COMPILER",
[tonumber(GL.DEBUG_SOURCE_THIRD_PARTY_ARB)] = "THIRD_PARTY",
[tonumber(GL.DEBUG_SOURCE_APPLICATION_ARB)] = "APPLICATION",
[tonumber(GL.DEBUG_SOURCE_OTHER_ARB)] = "OTHER"
}
local gl_debug_type_string = {
[tonumber(GL.DEBUG_TYPE_ERROR_ARB)] = "ERROR",
[tonumber(GL.DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB)] = "DEPRECATED_BEHAVIOR",
[tonumber(GL.DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB)] = "UNDEFINED_BEHAVIOR",
[tonumber(GL.DEBUG_TYPE_PORTABILITY_ARB)] = "PORTABILITY",
[tonumber(GL.DEBUG_TYPE_PERFORMANCE_ARB)] = "PERFORMANCE",
[tonumber(GL.DEBUG_TYPE_OTHER_ARB)] = "OTHER"
}
local gl_debug_severity_string = {
[tonumber(GL.DEBUG_SEVERITY_HIGH_ARB)] = "HIGH",
[tonumber(GL.DEBUG_SEVERITY_MEDIUM_ARB)] = "MEDIUM",
[tonumber(GL.DEBUG_SEVERITY_LOW_ARB)] = "LOW"
}
gl.DebugMessageCallbackARB(function(source, type, id, severity, length, message, userParam)
if not hate.config.window.debug_verbose and type == GL.DEBUG_TYPE_OTHER_ARB then
return
end
print(string.format("GL DEBUG source: %s type: %s id: %s severity: %s message: %q",
gl_debug_source_string[tonumber(source)],
gl_debug_type_string[tonumber(type)],
tonumber(id),
gl_debug_severity_string[tonumber(severity)],
ffi.string(message)))
end, nil)
end
end
if flags.show_sdl_version then
local v = ffi.new("SDL_version[1]")
sdl.getVersion(v)
print(string.format("SDL %d.%d.%d", v[0].major, v[0].minor, v[0].patch))
end
if flags.gl_debug then
print(string.format("OpenGL %s on %s", version, renderer))
end
hate.window = require(current_folder .. "window")
hate.window._state = hate.state
if config.modules.graphics then
hate.graphics = require(current_folder .. "graphics")
hate.graphics._state = hate.state
hate.graphics.init()
end
end
if config.modules.system then
hate.system = require(current_folder .. "system")
end
xpcall(require, hate.errhand, "main")
hate.run()
return 0
end
function hate.errhand(msg)
msg = tostring(msg)
local function error_printer(msg, layer)
print((debug.traceback("Error: " .. tostring(msg), 1+(layer or 1)):gsub("\n[^\n]+$", "")))
end
error_printer(msg, 2)
-- HATE isn't ready for this.
if false then
return
end
if not hate.window or not hate.graphics or not hate.event then
return
end
if not hate.graphics.isCreated() or not hate.window.isCreated() then
if not pcall(hate.window.setMode, 800, 600) then
return
end
end
-- Reset state.
if hate.mouse then
hate.mouse.setVisible(true)
hate.mouse.setGrabbed(false)
end
if hate.joystick then
for i,v in ipairs(hate.joystick.getJoysticks()) do
v:setVibration() -- Stop all joystick vibrations.
end
end
if hate.audio then hate.audio.stop() end
hate.graphics.reset()
hate.graphics.setBackgroundColor(89, 157, 220)
local font = hate.graphics.setNewFont(14)
hate.graphics.setColor(255, 255, 255, 255)
local trace = debug.traceback()
hate.graphics.clear()
hate.graphics.origin()
local err = {}
table.insert(err, "Error\n")
table.insert(err, msg.."\n\n")
for l in string.gmatch(trace, "(.-)\n") do
if not string.match(l, "boot.lua") then
l = string.gsub(l, "stack traceback:", "Traceback\n")
table.insert(err, l)
end
end
local p = table.concat(err, "\n")
p = string.gsub(p, "\t", "")
p = string.gsub(p, "%[string \"(.-)\"%]", "%1")
local function draw()
hate.graphics.clear()
hate.graphics.printf(p, 70, 70, hate.graphics.getWidth() - 70)
hate.graphics.present()
end
while true do
hate.event.pump()
for e, a, b, c in hate.event.poll() do
if e == "quit" then
return
end
if e == "keypressed" and a == "escape" then
return
end
end
draw()
if hate.timer then
hate.timer.sleep(0.1)
end
end
end
return hate
| mit |
arventwei/WioEngine | Tools/jamplus/tests/helloworld/test.lua | 1 | 2752 | function Test()
-- Test for a clean directory.
local originalFiles =
{
'Jamfile.jam',
'file.c',
'main.c',
}
local originalDirs =
{
}
RunJam{ 'clean' }
TestDirectories(originalDirs)
TestFiles(originalFiles)
if Platform == 'win32' then
-- First build
local pattern = [[
*** found 18 target(s)...
*** updating 4 target(s)...
@ C.$(COMPILER).CC <$(TOOLCHAIN_GRIST):helloworld>main.obj
!NEXT!@ $(C_LINK) <$(TOOLCHAIN_GRIST):helloworld>helloworld.exe
!NEXT!*** updated 4 target(s)...
]]
TestPattern(pattern, RunJam())
local pass1Directories = {
'$(TOOLCHAIN_PATH)/',
'$(TOOLCHAIN_PATH)/helloworld/',
}
local pass1Files =
{
'file.c',
'Jamfile.jam',
'main.c',
'$(TOOLCHAIN_PATH)/helloworld/file.obj',
'$(TOOLCHAIN_PATH)/helloworld/helloworld.release.exe',
'?$(TOOLCHAIN_PATH)/helloworld/helloworld.release.exe.intermediate.manifest',
'$(TOOLCHAIN_PATH)/helloworld/helloworld.release.pdb',
'$(TOOLCHAIN_PATH)/helloworld/main.obj',
}
TestFiles(pass1Files)
TestDirectories(pass1Directories)
local pattern2 = [[
*** found 18 target(s)...
]]
TestPattern(pattern2, RunJam())
osprocess.sleep(1.0)
ospath.touch('file.c')
local pattern3 = [[
*** found 18 target(s)...
*** updating 2 target(s)...
@ C.$(COMPILER).CC <$(TOOLCHAIN_GRIST):helloworld>file.obj
!NEXT!@ $(C_LINK) <$(TOOLCHAIN_GRIST):helloworld>helloworld.exe
!NEXT!*** updated 2 target(s)...
]]
TestPattern(pattern3, RunJam())
TestFiles(pass1Files)
TestDirectories(pass1Directories)
else
-- First build
local pattern = [[
*** found 10 target(s)...
*** updating 4 target(s)...
@ C.$(COMPILER).CC <$(TOOLCHAIN_GRIST):helloworld>main.o
@ C.$(COMPILER).CC <$(TOOLCHAIN_GRIST):helloworld>file.o
@ $(C_LINK) <$(TOOLCHAIN_GRIST):helloworld>helloworld
*** updated 4 target(s)...
]]
TestPattern(pattern, RunJam())
local pass1Dirs = {
'$(TOOLCHAIN_PATH)/',
'$(TOOLCHAIN_PATH)/helloworld/',
}
local pass1Files = {
'file.c',
'Jamfile.jam',
'main.c',
'test.lua',
'$(TOOLCHAIN_PATH)/helloworld/file.o',
'$(TOOLCHAIN_PATH)/helloworld/helloworld.release',
'$(TOOLCHAIN_PATH)/helloworld/main.o',
}
TestFiles(pass1Files)
TestDirectories(pass1Dirs)
local pattern2 = [[
*** found 10 target(s)...
]]
TestPattern(pattern2, RunJam())
osprocess.sleep(1.0)
ospath.touch('file.c')
local pattern3 = [[
*** found 10 target(s)...
*** updating 2 target(s)...
@ C.$(COMPILER).CC <$(TOOLCHAIN_GRIST):helloworld>file.o
@ $(C_LINK) <$(TOOLCHAIN_GRIST):helloworld>helloworld
*** updated 2 target(s)...
]]
TestPattern(pattern3, RunJam())
TestFiles(pass1Files)
TestDirectories(pass1Dirs)
end
RunJam{ 'clean' }
TestDirectories(originalDirs)
TestFiles(originalFiles)
end
| mit |
cshore/luci | applications/luci-app-coovachilli/luasrc/model/cbi/coovachilli_network.lua | 79 | 1459 | -- Copyright 2008 Steven Barth <steven@midlink.org>
-- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
local sys = require"luci.sys"
local ip = require "luci.ip"
m = Map("coovachilli")
-- tun
s1 = m:section(TypedSection, "tun")
s1.anonymous = true
s1:option( Flag, "usetap" )
s1:option( Value, "tundev" ).optional = true
s1:option( Value, "txqlen" ).optional = true
net = s1:option( Value, "net" )
for _, route in ipairs(ip.routes({ family = 4, type = 1 })) do
if route.dest:prefix() > 0 and route.dest:prefix() < 32 then
net:value( route.dest:string() )
end
end
s1:option( Value, "dynip" ).optional = true
s1:option( Value, "statip" ).optional = true
s1:option( Value, "dns1" ).optional = true
s1:option( Value, "dns2" ).optional = true
s1:option( Value, "domain" ).optional = true
s1:option( Value, "ipup" ).optional = true
s1:option( Value, "ipdown" ).optional = true
s1:option( Value, "conup" ).optional = true
s1:option( Value, "condown" ).optional = true
-- dhcp config
s2 = m:section(TypedSection, "dhcp")
s2.anonymous = true
dif = s2:option( Value, "dhcpif" )
for _, nif in ipairs(sys.net.devices()) do
if nif ~= "lo" then dif:value(nif) end
end
s2:option( Value, "dhcpmac" ).optional = true
s2:option( Value, "lease" ).optional = true
s2:option( Value, "dhcpstart" ).optional = true
s2:option( Value, "dhcpend" ).optional = true
s2:option( Flag, "eapolenable" )
return m
| apache-2.0 |
TimVonsee/hammerspoon | extensions/inspect/init.lua | 11 | 10601 | --- === hs.inspect ===
---
--- Produce human-readable representations of Lua variables (particularly tables)
---
--- This extension is based on inspect.lua by Enrique García Cota
--- https://github.com/kikito/inspect.lua
local inspect ={
_VERSION = 'inspect.lua 3.0.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.
]]
}
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
local controlCharsTranslation = {
["\a"] = "\\a", ["\b"] = "\\b", ["\f"] = "\\f", ["\n"] = "\\n",
["\r"] = "\\r", ["\t"] = "\\t", ["\v"] = "\\v"
}
local function escapeChar(c) return controlCharsTranslation[c] end
local function escape(str)
local result = str:gsub("\\", "\\\\"):gsub("(%c)", escapeChar)
return result
end
local function isIdentifier(str)
return type(str) == 'string' and str:match( "^[_%a][_%a%d]*$" )
end
local function isSequenceKey(k, length)
return type(k) == 'number'
and 1 <= k
and k <= length
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
local function getNonSequentialKeys(t)
local keys, length = {}, #t
for k,_ in pairs(t) do
if not isSequenceKey(k, length) then table.insert(keys, k) end
end
table.sort(keys, sortKeys)
return keys
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 maxIdsMetaTable = {
__index = function(self, typeName)
rawset(self, typeName, 0)
return 0
end
}
local idsMetaTable = {
__index = function (self, typeName)
local col = setmetatable({}, {__mode = "kv"})
rawset(self, typeName, col)
return col
end
}
local function countTableAppearances(t, tableAppearances)
tableAppearances = tableAppearances or setmetatable({}, {__mode = "k"})
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)
if item == nil then return nil end
local processed = process(item, path)
if type(processed) == 'table' then
local processedCopy = {}
local processedKey
for k,v in pairs(processed) do
processedKey = processRecursive(process, k, makePath(path, k, inspect.KEY))
if processedKey ~= nil then
processedCopy[processedKey] = processRecursive(process, v, makePath(path, processedKey))
end
end
local mt = processRecursive(process, getmetatable(processed), makePath(path, inspect.METATABLE))
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] = tostring(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[type(v)][v] ~= nil
end
function Inspector:getId(v)
local tv = type(v)
local id = self.ids[tv][v]
if not id then
id = self.maxIds[tv] + 1
self.maxIds[tv] = id
self.ids[tv][v] = id
end
return 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 = getNonSequentialKeys(t)
local length = #t
local mt = getmetatable(t)
local toStringResult = getToStringResultSafely(t, mt)
self:puts('{')
self:down(function()
if toStringResult then
self:puts(' -- ', escape(toStringResult))
if length >= 1 then self:tabify() end
end
local count = 0
for i=1, length 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 length > 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
--- hs.inspect.inspect(variable[, options]) -> string
--- Function
--- Gets a human readable version of the supplied Lua variable
---
--- Parameters:
--- * variable - A lua variable of some kind
--- * options - An optional table which can be used to influence the inspector. Valid keys are as follows:
--- * depth - A number representing the maximum depth to recurse into `variable`. Below that depth, data will be displayed as `{...}`
--- * newline - A string to use for line breaks. Defaults to `\n`
--- * indent - A string to use for indentation. Defaults to ` ` (two spaces)
--- * process - A function that will be called for each item. It should accept two arguments, `item` (the current item being processed) and `path` (the item's position in the variable being inspected. The function should either return a processed form of the variable, the original variable itself if it requires no processing, or `nil` to remove the item from the inspected output.
---
--- Returns:
--- * A string containing the human readable version of `variable`
---
--- Notes:
--- * For convenience, you can call this function as `hs.inspect(variable)`
--- * For more information on the options, and some examples, see [the upstream docs](https://github.com/kikito/inspect.lua)
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,
buffer = {},
level = 0,
ids = setmetatable({}, idsMetaTable),
maxIds = setmetatable({}, maxIdsMetaTable),
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
| mit |
grimreaper/ValyriaTear | dat/maps/layna_forest/layna_forest_north_east_script.lua | 1 | 27958 | -- Set the namespace according to the map name.
local ns = {};
setmetatable(ns, {__index = _G});
layna_forest_north_east_script = ns;
setfenv(1, ns);
-- The map name, subname and location image
map_name = "Layna Forest"
map_image_filename = "img/menus/locations/layna_forest.png"
map_subname = ""
-- The music file used as default background music on this map.
-- Other musics will have to handled through scripting.
music_filename = "mus/house_in_a_forest_loop_horrorpen_oga.ogg"
-- c++ objects instances
local Map = {};
local ObjectManager = {};
local DialogueManager = {};
local EventManager = {};
-- the main character handler
local hero = {};
-- the main map loading code
function Load(m)
Map = m;
ObjectManager = Map.object_supervisor;
DialogueManager = Map.dialogue_supervisor;
EventManager = Map.event_supervisor;
Map.unlimited_stamina = false;
Map:ShowMinimap(true);
_CreateCharacters();
_CreateObjects();
_CreateEnemies();
-- Set the camera focus on hero
Map:SetCamera(hero);
-- This is a dungeon map, we'll use the front battle member sprite as default sprite.
Map.object_supervisor:SetPartyMemberVisibleSprite(hero);
_CreateEvents();
_CreateZones();
-- Add clouds overlay
Map:GetEffectSupervisor():EnableAmbientOverlay("img/ambient/clouds.png", 5.0, 5.0, true);
_HandleTwilight();
end
-- Handle the twilight advancement after the crystal scene
function _HandleTwilight()
-- If the characters have seen the crystal, then it's time to make the twilight happen
if (GlobalManager:GetEventValue("story", "layna_forest_crystal_event_done") < 1) then
return;
end
Map:GetScriptSupervisor():AddScript("dat/maps/layna_forest/after_crystal_twilight.lua");
end
-- the map update function handles checks done on each game tick.
function Update()
-- Check whether the character is in one of the zones
_CheckZones();
end
-- Character creation
function _CreateCharacters()
-- Default hero and position (From forest NW)
hero = CreateSprite(Map, "Bronann", 3, 88);
hero:SetDirection(hoa_map.MapMode.EAST);
hero:SetMovementSpeed(hoa_map.MapMode.NORMAL_SPEED);
if (GlobalManager:GetPreviousLocation() == "from forest SE") then
hero:SetPosition(71, 94);
hero:SetDirection(hoa_map.MapMode.NORTH);
end
Map:AddGroundObject(hero);
end
-- The boss map sprite
local wolf = {};
function _CreateObjects()
local object = {}
local npc = {}
-- The boss map sprite
wolf = CreateSprite(Map, "Fenrir", 104, 3); -- pre place it at the right place.
wolf:SetCollisionMask(hoa_map.MapMode.NO_COLLISION);
wolf:SetMovementSpeed(hoa_map.MapMode.VERY_FAST_SPEED);
wolf:SetVisible(false);
wolf:SetDirection(hoa_map.MapMode.SOUTH);
Map:AddGroundObject(wolf);
-- Only add the squirrels and butterflies when the night isn't about to happen
if (GlobalManager:GetEventValue("story", "layna_forest_crystal_event_done") < 1) then
npc = CreateSprite(Map, "Butterfly", 42, 18);
npc:SetCollisionMask(hoa_map.MapMode.NO_COLLISION);
Map:AddGroundObject(npc);
event = hoa_map.RandomMoveSpriteEvent("Butterfly1 random move", npc, 1000, 1000);
event:AddEventLinkAtEnd("Butterfly1 random move", 4500); -- Loop on itself
EventManager:RegisterEvent(event);
EventManager:StartEvent("Butterfly1 random move");
npc = CreateSprite(Map, "Butterfly", 12, 30);
npc:SetCollisionMask(hoa_map.MapMode.NO_COLLISION);
Map:AddGroundObject(npc);
event = hoa_map.RandomMoveSpriteEvent("Butterfly2 random move", npc, 1000, 1000);
event:AddEventLinkAtEnd("Butterfly2 random move", 4500); -- Loop on itself
EventManager:RegisterEvent(event);
EventManager:StartEvent("Butterfly2 random move", 2400);
npc = CreateSprite(Map, "Butterfly", 50, 25);
npc:SetCollisionMask(hoa_map.MapMode.NO_COLLISION);
Map:AddGroundObject(npc);
event = hoa_map.RandomMoveSpriteEvent("Butterfly3 random move", npc, 1000, 1000);
event:AddEventLinkAtEnd("Butterfly3 random move", 4500); -- Loop on itself
EventManager:RegisterEvent(event);
EventManager:StartEvent("Butterfly3 random move", 1050);
npc = CreateSprite(Map, "Butterfly", 40, 30);
npc:SetCollisionMask(hoa_map.MapMode.NO_COLLISION);
Map:AddGroundObject(npc);
event = hoa_map.RandomMoveSpriteEvent("Butterfly4 random move", npc, 1000, 1000);
event:AddEventLinkAtEnd("Butterfly4 random move", 4500); -- Loop on itself
EventManager:RegisterEvent(event);
EventManager:StartEvent("Butterfly4 random move", 3050);
npc = CreateSprite(Map, "Squirrel", 18, 24);
-- Squirrels don't collide with the npcs.
npc:SetCollisionMask(hoa_map.MapMode.WALL_COLLISION);
Map:AddGroundObject(npc);
event = hoa_map.RandomMoveSpriteEvent("Squirrel1 random move", npc, 1000, 1000);
event:AddEventLinkAtEnd("Squirrel1 random move", 4500); -- Loop on itself
EventManager:RegisterEvent(event);
EventManager:StartEvent("Squirrel1 random move");
npc = CreateSprite(Map, "Squirrel", 40, 14);
-- Squirrels don't collide with the npcs.
npc:SetCollisionMask(hoa_map.MapMode.WALL_COLLISION);
Map:AddGroundObject(npc);
event = hoa_map.RandomMoveSpriteEvent("Squirrel2 random move", npc, 1000, 1000);
event:AddEventLinkAtEnd("Squirrel2 random move", 4500); -- Loop on itself
EventManager:RegisterEvent(event);
EventManager:StartEvent("Squirrel2 random move", 1800);
end
-- Forest entrance treasure chest
local chest1 = CreateTreasure(Map, "layna_forest_NE_chest1", "Wood_Chest1", 4, 55);
if (chest1 ~= nil) then
chest1:AddObject(1, 1);
Map:AddGroundObject(chest1);
end
-- Trees array
local map_trees = {
-- left entrance upper side
{ "Tree Small3", 3, 85 },
{ "Tree Small4", 4, 81 },
{ "Tree Small3", 5, 78 },
{ "Tree Small6", 1, 79 },
{ "Tree Small3", 5, 75 },
{ "Tree Small6", 6, 72 },
{ "Tree Small3", 6.5, 69 },
{ "Tree Small5", 5, 66 },
{ "Tree Small3", 6, 63 },
{ "Tree Small4", 7, 61 },
{ "Tree Small5", 2, 62 },
{ "Tree Small6", 8, 58 },
{ "Tree Small3", 8, 55 },
{ "Tree Small3", 7, 52 },
{ "Tree Small4", 9, 49 },
{ "Tree Small3", 9, 46 },
{ "Tree Small4", 10, 44 },
{ "Tree Small3", 11.5, 41 },
{ "Tree Small5", 12, 38 },
{ "Tree Small3", 13, 35 },
{ "Tree Small6", 14, 32 },
{ "Tree Small3", 15.5, 30 },
{ "Tree Small5", 16, 27 },
{ "Tree Small3", 17, 24 },
{ "Tree Small4", 19, 21 },
{ "Tree Small3", 20, 18.5 },
{ "Tree Small3", 20.5, 15 },
-- Left entrance - bottom side
{ "Tree Small3", 3, 95 },
{ "Tree Small4", 7, 96 },
{ "Tree Small3", 10, 93 },
{ "Tree Small3", 12, 90 },
{ "Tree Little3", 10, 64.5 },
{ "Tree Small6", 14, 87 },
{ "Tree Small3", 15, 84 },
{ "Tree Small5", 16, 82 },
{ "Tree Small3", 16, 79 },
{ "Tree Small3", 15.5, 76 },
{ "Tree Small4", 17, 74 },
{ "Tree Small3", 18, 73 },
{ "Tree Small5", 18, 70 },
{ "Tree Small3", 18.2, 68 },
{ "Tree Small3", 18.5, 65 },
{ "Tree Small3", 19, 63 },
{ "Tree Small6", 19, 60 },
{ "Tree Small3", 19.2, 57 },
{ "Tree Small6", 19.5, 54 },
{ "Tree Small3", 20, 52 },
{ "Tree Small5", 20, 50 },
{ "Tree Small3", 20.2, 47 },
{ "Tree Small4", 21, 44 },
{ "Tree Small3", 21.5, 41 },
{ "Tree Small4", 21.7, 38 },
{ "Tree Small3", 22, 35 },
{ "Tree Small5", 22.5, 33 },
{ "Tree Small3", 23, 30 },
{ "Tree Small5", 25, 27 },
{ "Tree Small3", 26, 24 },
{ "Tree Small5", 29, 22 },
{ "Tree Small3", 31, 19 },
{ "Tree Small4", 34, 18 },
-- Top-left map tree wall
{ "Tree Small3", -1, 54 },
{ "Tree Small6", -2, 50 },
{ "Tree Small3", -3, 45 },
{ "Tree Small6", 0, 40 },
{ "Tree Small3", 0, 37 },
{ "Tree Small4", 0, 34 },
{ "Tree Small3", 0, 32 },
{ "Tree Small5", 1, 28 },
{ "Tree Small3", -1, 24 },
{ "Tree Small4", 0, 20 },
{ "Tree Small3", 1, 17 },
{ "Tree Small5", 2, 14 },
{ "Tree Small3", 1, 10 },
{ "Tree Small4", 0, 6 },
{ "Tree Small3", 2, 2 },
{ "Tree Small5", 5, 1 },
{ "Tree Small3", 7, 3 },
{ "Tree Small4", 10, 2 },
{ "Tree Small3", 14, 1 },
{ "Tree Small4", 16, 2 },
{ "Tree Small3", 19, 3 },
{ "Tree Small3", 23, 4 },
{ "Tree Small5", 26, 2 },
{ "Tree Small3", 8, 7 },
-- Trees in the way
{ "Tree Small3", 12, 15 },
{ "Tree Small3", 15, 17 },
{ "Tree Small3", 7, 24 },
{ "Tree Small5", 3, 30 },
{ "Tree Small3", 12, 27.2 },
{ "Tree Small3", 8, 40.1 },
{ "Tree Small4", 10, 51 },
-- to the right - bottom side
{ "Tree Small3", 37, 20 },
{ "Tree Small3", 40, 18 },
{ "Tree Small4", 42, 19 },
{ "Tree Small3", 45, 20.1 },
{ "Tree Small5", 48, 21 },
{ "Tree Small3", 51, 19 },
{ "Tree Small6", 54, 20 },
{ "Tree Small3", 57, 21 },
{ "Tree Small6", 60, 23 },
{ "Tree Small3", 62, 24 },
{ "Tree Small5", 65, 22 },
{ "Tree Small4", 68, 24.1 },
{ "Tree Small5", 71, 23 },
{ "Tree Small6", 74, 24 },
{ "Tree Small3", 77, 22 },
{ "Tree Small3", 80, 21 },
{ "Tree Small4", 83, 23 },
{ "Tree Small3", 86, 24 },
{ "Tree Small5", 89, 22 },
{ "Tree Small3", 92, 21 },
{ "Tree Small6", 95, 23 },
{ "Tree Small3", 98, 24 },
{ "Tree Small4", 101, 22 },
{ "Tree Small3", 104, 19 },
-- to the right - top side
{ "Tree Small3", 30, 1 },
{ "Tree Small3", 32, 4 },
{ "Tree Small4", 35, 7 },
{ "Tree Small3", 36, 10 },
{ "Tree Small5", 40, 8 },
{ "Tree Small3", 43, 7 },
{ "Tree Small6", 45, 6.5 },
{ "Tree Small3", 48, 8 },
{ "Tree Small3", 51, 6 },
{ "Tree Small5", 53, 4 },
{ "Tree Small3", 55, 3 },
{ "Tree Small3", 58, 1 },
{ "Tree Small6", 61, 2 },
{ "Tree Small3", 64, 4 },
{ "Tree Small5", 67, 5 },
{ "Tree Small3", 70, 1 },
{ "Tree Small4", 73, 2 },
{ "Tree Small3", 76, 4 },
{ "Tree Small5", 79, 5 },
{ "Tree Small3", 82, 1 },
{ "Tree Small4", 85, 2 },
{ "Tree Small3", 88, 4 },
{ "Tree Small6", 91, 5 },
{ "Tree Small3", 94, 1 },
{ "Tree Small4", 97, 6 },
{ "Tree Small3", 100, 2 },
{ "Tree Small5", 103, 4 },
{ "Tree Small3", 106, 5 },
{ "Tree Small6", 108, 6 },
{ "Tree Small3", 111, 1 },
{ "Tree Small4", 114, 2 },
{ "Tree Small5", 117, 5.2 },
{ "Tree Small3", 120, 8 },
{ "Tree Small6", 123, 10 },
{ "Tree Small3", 126, 11 },
{ "Tree Small5", 127, 14 },
{ "Tree Small3", 126, 5 },
-- Going down - right side
{ "Tree Small3", 125, 17 },
{ "Tree Small4", 127, 18 },
{ "Tree Small3", 123, 20 },
{ "Tree Small5", 122, 23 },
{ "Tree Small3", 125, 24 },
{ "Tree Small6", 126, 27 },
{ "Tree Small6", 125, 30 },
{ "Tree Small3", 127, 33 },
{ "Tree Small5", 123, 36 },
{ "Tree Small3", 122, 39 },
{ "Tree Small4", 125, 42 },
{ "Tree Small3", 126, 45 },
{ "Tree Small5", 125, 48 },
{ "Tree Small3", 127, 51 },
{ "Tree Small4", 123, 54 },
{ "Tree Small3", 122, 57 },
{ "Tree Small5", 125, 60 },
{ "Tree Small3", 126, 63 },
{ "Tree Small5", 125, 66 },
{ "Tree Small3", 127, 69 },
{ "Tree Small4", 123, 72 },
{ "Tree Small3", 122, 75 },
{ "Tree Small6", 125, 78 },
{ "Tree Small3", 126, 81 },
{ "Tree Small6", 125, 84 },
{ "Tree Small3", 127, 87 },
{ "Tree Small5", 123, 90 },
{ "Tree Small4", 122, 93 },
{ "Tree Small3", 125, 96 },
-- going down - left side
{ "Tree Small3", 107, 20 },
{ "Tree Small4", 110, 23 },
{ "Tree Small3", 109, 25 },
{ "Tree Small5", 111, 28 },
{ "Tree Small3", 110, 31 },
{ "Tree Small6", 109, 34 },
{ "Tree Small3", 108, 36 },
{ "Tree Small4", 110, 39 },
{ "Tree Small3", 109, 42 },
{ "Tree Small4", 111, 45 },
{ "Tree Small3", 110, 47 },
{ "Tree Small5", 109, 50 },
{ "Tree Small3", 110, 53 },
{ "Tree Small4", 111, 56 },
{ "Tree Small3", 109, 59 },
{ "Tree Small4", 110, 62 },
{ "Tree Small3", 109, 65 },
{ "Tree Small4", 110, 67 },
{ "Tree Small3", 109, 70 },
{ "Tree Small4", 107, 73 },
{ "Tree Small3", 106, 76 },
{ "Tree Small4", 104, 79 },
{ "Tree Small3", 102, 80 },
-- going left - bottom side
{ "Tree Small3", 118, 82 },
{ "Tree Small4", 119, 85 },
{ "Tree Small3", 117, 88 },
{ "Tree Small4", 118, 91 },
{ "Tree Small3", 119, 94 },
{ "Tree Small5", 119, 97 },
{ "Tree Small3", 115, 81 },
{ "Tree Small6", 116, 84 },
{ "Tree Small3", 114, 87 },
{ "Tree Small6", 115, 90 },
{ "Tree Small3", 116, 93 },
{ "Tree Small5", 116, 96 },
{ "Tree Small3", 112, 83 },
{ "Tree Small4", 113, 86 },
{ "Tree Small3", 111, 89 },
{ "Tree Small5", 112, 92 },
{ "Tree Small3", 113, 95 },
{ "Tree Small4", 113, 98 },
{ "Tree Small3", 108, 91 },
{ "Tree Small3", 106, 94 },
{ "Tree Small4", 107, 97 },
{ "Tree Small3", 105, 95 },
{ "Tree Small5", 102, 92 },
{ "Tree Small3", 102, 96 },
{ "Tree Small6", 99, 97 },
{ "Tree Small3", 95, 96 },
{ "Tree Small5", 92, 94 },
{ "Tree Small3", 89, 95 },
{ "Tree Small5", 86, 97 },
{ "Tree Small3", 83, 96 },
{ "Tree Small3", 80, 94 },
{ "Tree Small4", 78, 95 },
-- going left - top side
{ "Tree Small3", 98, 82 },
{ "Tree Small3", 94, 81 },
{ "Tree Small4", 90, 82.5 },
{ "Tree Small3", 86, 83 },
{ "Tree Small5", 82, 82 },
{ "Tree Small3", 78, 84 },
{ "Tree Small6", 74, 85 },
-- going down - top side
{ "Tree Small4", 70, 87 },
{ "Tree Small3", 68, 90 },
{ "Tree Small3", 67, 93 },
{ "Tree Small5", 66, 96 },
{ "Tree Small5", 12, 95 },
{ "Tree Small6", 16, 92 },
{ "Tree Small4", 20, 88 },
{ "Tree Small3", 21, 93 },
{ "Tree Small4", 20, 80 },
{ "Tree Small3", 25, 83 },
{ "Tree Small5", 19, 96 },
{ "Tree Small6", 26, 90 },
{ "Tree Small5", 27, 93.2 },
{ "Tree Small4", 25, 98 },
{ "Tree Big1", 15, 99 },
{ "Tree Small5", 30, 95 },
{ "Tree Small4", 31, 89 },
{ "Tree Small5", 30, 84 },
{ "Tree Small6", 23, 75 },
{ "Tree Small2", 28, 78 },
{ "Tree Small5", 32, 77 },
{ "Tree Small3", 2, 99 },
{ "Tree Big2", 2, 68 },
{ "Tree Small5", 27, 73 },
{ "Tree Small2", 35, 72 },
{ "Tree Small3", 28, 68 },
{ "Tree Small5", 22, 67 },
{ "Tree Small6", 34, 64 },
{ "Tree Small4", 31, 69 },
{ "Tree Small6", 25, 61 },
{ "Tree Small4", 30, 56 },
{ "Tree Small6", 23, 58 },
{ "Tree Small2", 26, 51 },
{ "Tree Big1", 31, 60 },
{ "Tree Small1", 30, 50 },
{ "Tree Small4", 35, 47 },
{ "Tree Small3", 25, 46 },
{ "Tree Small5", 28, 40 },
{ "Tree Small6", 33, 39 },
{ "Tree Small4", 29, 46.5 },
{ "Tree Small6", 27, 32 },
{ "Tree Small1", 32, 30 },
{ "Tree Small3", 30, 34 },
{ "Tree Small2", 35, 33 },
{ "Tree Small4", 40, 38 },
{ "Tree Little1", 34, 26.2 },
{ "Tree Small5", 30, 26 },
{ "Tree Small6", 35, 23 },
{ "Tree Big2", 37, 42 },
{ "Tree Small6", 38, 29 },
{ "Tree Small5", 39, 26 },
{ "Tree Tiny3", 32, 49 },
{ "Tree Small6", 40, 31 },
{ "Tree Small4", 41, 23.2 },
{ "Tree Small1", 43, 28 },
{ "Tree Small3", 46, 28.2 },
{ "Tree Little1", 50, 27.2 },
{ "Tree Small6", 51, 30 },
{ "Tree Small4", 54, 26 },
{ "Tree Small3", 57, 28 },
{ "Tree Small4", 55, 31 },
{ "Tree Small6", 60, 29 },
{ "Tree Small5", 64, 28.2 },
{ "Tree Small1", 63, 32 },
{ "Tree Small3", 68, 30 },
{ "Tree Small2", 71, 28 },
{ "Tree Small3", 77, 25 },
{ "Tree Small4", 82, 26 },
{ "Tree Small6", 88, 27 },
{ "Tree Small4", 92, 25 },
{ "Tree Small5", 100, 26 },
{ "Tree Small2", 104, 22.2 },
{ "Tree Big1", 103, 28 },
{ "Tree Small3", 101, 31 },
{ "Tree Small3", 102, 35 },
{ "Tree Small4", 105, 40 },
{ "Tree Small6", 96, 27 },
{ "Tree Small4", 90, 28 },
{ "Tree Small3", 83, 30 },
{ "Tree Big2", 80, 28 },
{ "Tree Small1", 77, 31 },
{ "Tree Little1", 75, 29 },
{ "Tree Tiny3", 70, 32 },
{ "Tree Small5", 46.5, 32 },
{ "Tree Small6", 59, 33 },
{ "Tree Small4", 67, 34 },
{ "Tree Small2", 35, 53 },
{ "Tree Small4", 50, 34 },
{ "Tree Small1", 44, 35 },
{ "Tree Small4", 74, 35 },
{ "Tree Big2", 80, 33 },
{ "Tree Little3", 87, 32 },
{ "Tree Small5", 94, 33 },
{ "Tree Small3", 83, 36 },
{ "Tree Small4", 97, 36 },
{ "Tree Small3", 91, 35 },
{ "Tree Small3", 56, 36 },
{ "Tree Small4", 101, 41 },
{ "Tree Small6", 95, 39 },
{ "Tree Small4", 106, 47.2 },
{ "Tree Small5", 104, 52 },
{ "Tree Small2", 105, 60 },
{ "Tree Small3", 96, 44 },
{ "Tree Small1", 100, 54 },
{ "Tree Small5", 99, 65 },
{ "Tree Small5", 102, 71 },
{ "Tree Small5", 97, 76 },
{ "Tree Big1", 90, 78.2 },
{ "Tree Small4", 82, 77 },
{ "Tree Big2", 74, 82 },
{ "Tree Tiny3", 64, 80 },
{ "Tree Small3", 59, 92 },
{ "Tree Small4", 60, 95 },
{ "Tree Small3", 55, 98 },
{ "Tree Small3", 100, 45 },
{ "Tree Small4", 96, 50 },
{ "Tree Small6", 97, 58 },
{ "Tree Small5", 101, 62 },
{ "Tree Little1", 97, 70 },
{ "Tree Big2", 86, 74 },
{ "Tree Small1", 78, 76 },
{ "Tree Tiny1", 69, 83 },
{ "Tree Small3", 60, 87 },
{ "Tree Small4", 53, 91 },
{ "Tree Small5", 70, 74 },
{ "Tree Small1", 55, 80 },
{ "Tree Small2", 92, 72 },
{ "Tree Small5", 70, 81 },
{ "Tree Small2", 65, 84 },
{ "Tree Small4", 63, 94 },
{ "Tree Big1", 76, 78 },
{ "Tree Small4", 66, 77 },
{ "Tree Small6", 59, 82 },
{ "Tree Small4", 94, 68 },
{ "Tree Small4", 104, 67 },
}
-- Loads the trees according to the array
for my_index, my_array in pairs(map_trees) do
--print(my_array[1], my_array[2], my_array[3]);
object = CreateObject(Map, my_array[1], my_array[2], my_array[3]);
Map:AddGroundObject(object);
end
end
function _CreateEnemies()
local enemy = {};
local roam_zone = {};
-- Treasure zone
-- Hint: left, right, top, bottom
roam_zone = hoa_map.EnemyZone(5, 10, 8, 47, hoa_map.MapMode.CONTEXT_01);
enemy = CreateEnemySprite(Map, "slime");
_SetBattleEnvironment(enemy);
enemy:NewEnemyParty();
enemy:AddEnemy(1);
enemy:AddEnemy(1);
enemy:AddEnemy(1);
enemy:AddEnemy(1);
enemy:NewEnemyParty();
enemy:AddEnemy(1);
enemy:AddEnemy(2);
enemy:AddEnemy(2);
roam_zone:AddEnemy(enemy, Map, 1);
Map:AddZone(roam_zone);
-- after fight zone
roam_zone = hoa_map.EnemyZone(112, 120, 34, 80, hoa_map.MapMode.CONTEXT_01);
enemy = CreateEnemySprite(Map, "spider");
_SetBattleEnvironment(enemy);
enemy:NewEnemyParty();
enemy:AddEnemy(1);
enemy:AddEnemy(1);
enemy:AddEnemy(2);
enemy:AddEnemy(1);
enemy:NewEnemyParty();
enemy:AddEnemy(1);
enemy:AddEnemy(2);
enemy:AddEnemy(2);
roam_zone:AddEnemy(enemy, Map, 1);
Map:AddZone(roam_zone);
end
-- Creates all events and sets up the entire event sequence chain
function _CreateEvents()
local event = {};
local dialogue = {};
local text = {};
-- Map events
event = hoa_map.MapTransitionEvent("to forest NW", "dat/maps/layna_forest/layna_forest_north_west_map.lua",
"dat/maps/layna_forest/layna_forest_north_west_script.lua", "from_layna_forest_NE");
EventManager:RegisterEvent(event);
event = hoa_map.MapTransitionEvent("to forest SE", "dat/maps/layna_forest/layna_forest_south_east.lua",
"dat/maps/layna_forest/layna_forest_south_east.lua", "from_layna_forest_NE");
EventManager:RegisterEvent(event);
-- generic events
event = hoa_map.ScriptedEvent("Map:PopState()", "Map_PopState", "");
EventManager:RegisterEvent(event);
-- Boss fight scene
event = hoa_map.ScriptedEvent("boss fight scene", "start_boss_fight_scene", "");
event:AddEventLinkAtEnd("boss fight pre-dialogue");
EventManager:RegisterEvent(event);
dialogue = hoa_map.SpriteDialogue();
text = hoa_system.Translate("What's that?!");
dialogue:AddLineEmote(text, hero, "exclamation");
DialogueManager:AddDialogue(dialogue);
event = hoa_map.DialogueEvent("boss fight pre-dialogue", dialogue);
event:AddEventLinkAtEnd("hero looks west");
EventManager:RegisterEvent(event);
event = hoa_map.ChangeDirectionSpriteEvent("hero looks west", hero, hoa_map.MapMode.WEST);
event:AddEventLinkAtEnd("hero looks east", 800);
EventManager:RegisterEvent(event);
event = hoa_map.ChangeDirectionSpriteEvent("hero looks east", hero, hoa_map.MapMode.EAST);
event:AddEventLinkAtEnd("The hero looks at wolf", 800);
EventManager:RegisterEvent(event);
event = hoa_map.LookAtSpriteEvent("The hero looks at wolf", hero, wolf);
event:AddEventLinkAtEnd("Wolf runs toward the hero");
EventManager:RegisterEvent(event);
event = hoa_map.PathMoveSpriteEvent("Wolf runs toward the hero", wolf, hero, true);
event:AddEventLinkAtEnd("First Wolf battle");
EventManager:RegisterEvent(event);
event = hoa_map.BattleEncounterEvent("First Wolf battle");
event:SetMusic("mus/accion-OGA-djsaryon.ogg");
event:SetBackground("img/backdrops/battle/forest_background.png");
event:AddEnemy(3, 0, 0);
event:AddEventLinkAtEnd("Make the wolf disappear");
EventManager:RegisterEvent(event);
event = hoa_map.ScriptedEvent("Make the wolf disappear", "make_wolf_invisible", "");
event:AddEventLinkAtEnd("boss fight post-dialogue");
EventManager:RegisterEvent(event);
dialogue = hoa_map.SpriteDialogue();
text = hoa_system.Translate("Woah, that was quite a nasty fight. Why on earth was an arctic north fenrir lurking in the forest? I thought such animals were part of the myths.");
dialogue:AddLineEmote(text, hero, "sweat drop");
text = hoa_system.Translate("He just ran away. I'm almost sure we'll meet it again. We'd better be well prepared, then.");
dialogue:AddLineEmote(text, hero, "thinking dots");
text = hoa_system.Translate("I'll try not to think about what it could have done to Orlinn ... Let's find him quickly.");
dialogue:AddLine(text, hero);
DialogueManager:AddDialogue(dialogue);
event = hoa_map.DialogueEvent("boss fight post-dialogue", dialogue);
event:AddEventLinkAtEnd("Map:PopState()");
event:AddEventLinkAtEnd("Restart music");
EventManager:RegisterEvent(event);
event = hoa_map.ScriptedEvent("Restart music", "restart_music", "");
EventManager:RegisterEvent(event);
end
-- zones
local to_forest_NW_zone = {};
local to_forest_SE_zone = {};
local music_fade_out_zone = {};
local boss_fight1_zone = {};
-- Create the different map zones triggering events
function _CreateZones()
-- N.B.: left, right, top, bottom
to_forest_NW_zone = hoa_map.CameraZone(0, 1, 86, 90, hoa_map.MapMode.CONTEXT_01);
Map:AddZone(to_forest_NW_zone);
to_forest_SE_zone = hoa_map.CameraZone(69, 75, 95, 96, hoa_map.MapMode.CONTEXT_01);
Map:AddZone(to_forest_SE_zone);
-- Fade out music zone - used to set a dramatic area
music_fade_out_zone = hoa_map.CameraZone(48, 50, 8, 17, hoa_map.MapMode.CONTEXT_01);
Map:AddZone(music_fade_out_zone);
boss_fight1_zone = hoa_map.CameraZone(103, 105, 4, 18, hoa_map.MapMode.CONTEXT_01);
Map:AddZone(boss_fight1_zone);
end
-- Check whether the active camera has entered a zone. To be called within Update()
function _CheckZones()
if (to_forest_NW_zone:IsCameraEntering() == true) then
hero:SetMoving(false);
EventManager:StartEvent("to forest NW");
elseif (to_forest_SE_zone:IsCameraEntering() == true) then
hero:SetMoving(false);
EventManager:StartEvent("to forest SE");
elseif (music_fade_out_zone:IsCameraEntering() == true) then
-- fade out the music when the first boss fight hasn't been done yet.
if (GlobalManager:DoesEventExist("story", "layna_forest_boss_fight1") == false) then
AudioManager:FadeOutAllMusic(2000);
end
elseif (boss_fight1_zone:IsCameraEntering() == true) then
-- fade out the music when the first boss fight hasn't been done yet.
if (GlobalManager:DoesEventExist("story", "layna_forest_boss_fight1") == false) then
GlobalManager:SetEventValue("story", "layna_forest_boss_fight1", 1);
EventManager:StartEvent("boss fight scene");
end
end
end
-- Sets common battle environment settings for enemy sprites
function _SetBattleEnvironment(enemy)
enemy:SetBattleMusicTheme("mus/heroism-OGA-Edward-J-Blakeley.ogg");
enemy:SetBattleBackground("img/backdrops/battle/forest_background.png");
if (GlobalManager:GetEventValue("story", "layna_forest_crystal_event_done") < 1) then
-- Add tutorial battle dialog with Kalya and Bronann
enemy:AddBattleScript("dat/battles/tutorial_battle_dialogs.lua");
else
-- Setup time of the day lighting on battles
enemy:AddBattleScript("dat/maps/layna_forest/after_crystal_twilight_battles.lua");
if (GlobalManager:GetEventValue("story", "layna_forest_twilight_value") > 2) then
enemy:SetBattleBackground("img/backdrops/battle/forest_background_evening.png");
end
end
end
-- Map Custom functions
-- Used through scripted events
map_functions = {
Map_PopState = function()
Map:PopState();
end,
start_boss_fight_scene = function()
Map:PushState(hoa_map.MapMode.STATE_SCENE);
hero:SetMoving(false);
-- Play the wolf growling sound
AudioManager:PlaySound("snd/growl1_IFartInUrGeneralDirection_freesound.wav");
wolf:SetVisible(true);
end,
make_wolf_invisible = function()
wolf:SetVisible(false);
wolf:SetPosition(104, 3);
end,
restart_music = function()
AudioManager:FadeInAllMusic(2000);
end
}
| gpl-2.0 |
ld-test/oil | lua/loop/object/Exception.lua | 12 | 2141 | --------------------------------------------------------------------------------
---------------------- ## ##### ##### ###### -----------------------
---------------------- ## ## ## ## ## ## ## -----------------------
---------------------- ## ## ## ## ## ###### -----------------------
---------------------- ## ## ## ## ## ## -----------------------
---------------------- ###### ##### ##### ## -----------------------
---------------------- -----------------------
----------------------- Lua Object-Oriented Programming ------------------------
--------------------------------------------------------------------------------
-- Project: LOOP Class Library --
-- Release: 2.3 beta --
-- Title : Data structure to hold information about exceptions in Lua --
-- Author : Renato Maia <maia@inf.puc-rio.br> --
--------------------------------------------------------------------------------
local error = error
local type = type
local traceback = debug and debug.traceback
local table = require "table"
local oo = require "loop.base"
module("loop.object.Exception", oo.class)
function __init(class, object)
if traceback then
if not object then
object = { traceback = traceback() }
elseif object.traceback == nil then
object.traceback = traceback()
end
end
return oo.rawnew(class, object)
end
function __concat(op1, op2)
if type(op1) == "table" and type(op1.__tostring) == "function" then
op1 = op1:__tostring()
end
if type(op2) == "table" and type(op2.__tostring) == "function" then
op2 = op2:__tostring()
end
return op1..op2
end
function __tostring(self)
local message = { self[1] or self._NAME or "Exception"," raised" }
if self.message then
message[#message + 1] = ": "
message[#message + 1] = self.message
end
if self.traceback then
message[#message + 1] = "\n"
message[#message + 1] = self.traceback
end
return table.concat(message)
end
| mit |
silverhammermba/awesome | spec/wibox/widget/base_spec.lua | 14 | 3351 | ---------------------------------------------------------------------------
-- @author Uli Schlachter
-- @copyright 2016 Uli Schlachter
---------------------------------------------------------------------------
local base = require("wibox.widget.base")
local no_parent = base.no_parent_I_know_what_I_am_doing
describe("wibox.widget.base", function()
local widget1, widget2
before_each(function()
widget1 = base.make_widget()
widget2 = base.make_widget()
widget1.layout = function()
return { base.place_widget_at(widget2, 0, 0, 1, 1) }
end
end)
describe("caches", function()
it("garbage collectable", function()
local alive = setmetatable({ widget1, widget2 }, { __mode = "kv" })
assert.is.equal(2, #alive)
widget1, widget2 = nil, nil
collectgarbage("collect")
assert.is.equal(0, #alive)
end)
it("simple cache clear", function()
local alive = setmetatable({ widget1, widget2 }, { __mode = "kv" })
base.layout_widget(no_parent, { "fake context" }, widget1, 20, 20)
assert.is.equal(2, #alive)
widget1, widget2 = nil, nil
collectgarbage("collect")
assert.is.equal(0, #alive)
end)
it("self-reference cache clear", function()
widget2.widget = widget1
local alive = setmetatable({ widget1, widget2 }, { __mode = "kv" })
base.layout_widget(no_parent, { "fake context" }, widget1, 20, 20)
assert.is.equal(2, #alive)
widget1, widget2 = nil, nil
collectgarbage("collect")
assert.is.equal(0, #alive)
end)
end)
describe("setup", function()
it("Filters out 'false'", function()
-- Regression test: There was a bug where "nil"s where correctly
-- skipped, but "false" entries survived
local layout1, layout2 = base.make_widget(), base.make_widget()
local called = false
function layout1:set_widget(w)
called = true
assert.equals(w, layout2)
end
function layout2:set_children(children)
assert.is_same({nil, widget1, nil, widget2}, children)
end
layout2.allow_empty_widget = true
layout1:setup{ layout = layout2, false, widget1, nil, widget2 }
assert.is_true(called)
end)
it("Attribute 'false' works", function()
-- Regression test: I introduced a bug with the above fix
local layout1, layout2 = base.make_widget(), base.make_widget()
local called1, called2 = false, false
function layout1:set_widget(w)
called1 = true
assert.equals(w, layout2)
end
function layout2:set_children(children)
assert.is_same({}, children)
end
function layout2:set_foo(foo)
called2 = true
assert.is_false(foo)
end
layout1:setup{ layout = layout2, foo = false }
assert.is_true(called1)
assert.is_true(called2)
end)
end)
end)
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| gpl-2.0 |
s0ph05/awesome | themes/default/theme.lua | 1 | 5028 | ---------------------------
-- Default awesome theme --
---------------------------
theme = {}
theme.font = "sans 8"
theme.bg_normal = "#222222"
theme.bg_focus = "#535d6c"
theme.bg_urgent = "#ff0000"
theme.bg_minimize = "#444444"
theme.bg_systray = theme.bg_normal
theme.fg_normal = "#aaaaaa"
theme.fg_focus = "#ffffff"
theme.fg_urgent = "#ffffff"
theme.fg_minimize = "#ffffff"
theme.border_width = 1
theme.border_normal = "#000000"
theme.border_focus = "#535d6c"
theme.border_marked = "#91231c"
-- There are other variable sets
-- overriding the default one when
-- defined, the sets are:
-- taglist_[bg|fg]_[focus|urgent|occupied|empty]
-- tasklist_[bg|fg]_[focus|urgent]
-- titlebar_[bg|fg]_[normal|focus]
-- tooltip_[font|opacity|fg_color|bg_color|border_width|border_color]
-- mouse_finder_[color|timeout|animate_timeout|radius|factor]
-- Example:
--theme.taglist_bg_focus = "#ff0000"
-- Display the taglist squares
theme.taglist_squares_sel = "/usr/share/awesome/themes/default/taglist/squarefw.png"
theme.taglist_squares_unsel = "/usr/share/awesome/themes/default/taglist/squarew.png"
-- Variables set for theming the menu:
-- menu_[bg|fg]_[normal|focus]
-- menu_[border_color|border_width]
theme.menu_submenu_icon = "/usr/share/awesome/themes/default/submenu.png"
theme.menu_height = 15
theme.menu_width = 100
-- You can add as many variables as
-- you wish and access them by using
-- beautiful.variable in your rc.lua
--theme.bg_widget = "#cc0000"
-- Define the image to load
theme.titlebar_close_button_normal = "/usr/share/awesome/themes/default/titlebar/close_normal.png"
theme.titlebar_close_button_focus = "/usr/share/awesome/themes/default/titlebar/close_focus.png"
theme.titlebar_ontop_button_normal_inactive = "/usr/share/awesome/themes/default/titlebar/ontop_normal_inactive.png"
theme.titlebar_ontop_button_focus_inactive = "/usr/share/awesome/themes/default/titlebar/ontop_focus_inactive.png"
theme.titlebar_ontop_button_normal_active = "/usr/share/awesome/themes/default/titlebar/ontop_normal_active.png"
theme.titlebar_ontop_button_focus_active = "/usr/share/awesome/themes/default/titlebar/ontop_focus_active.png"
theme.titlebar_sticky_button_normal_inactive = "/usr/share/awesome/themes/default/titlebar/sticky_normal_inactive.png"
theme.titlebar_sticky_button_focus_inactive = "/usr/share/awesome/themes/default/titlebar/sticky_focus_inactive.png"
theme.titlebar_sticky_button_normal_active = "/usr/share/awesome/themes/default/titlebar/sticky_normal_active.png"
theme.titlebar_sticky_button_focus_active = "/usr/share/awesome/themes/default/titlebar/sticky_focus_active.png"
theme.titlebar_floating_button_normal_inactive = "/usr/share/awesome/themes/default/titlebar/floating_normal_inactive.png"
theme.titlebar_floating_button_focus_inactive = "/usr/share/awesome/themes/default/titlebar/floating_focus_inactive.png"
theme.titlebar_floating_button_normal_active = "/usr/share/awesome/themes/default/titlebar/floating_normal_active.png"
theme.titlebar_floating_button_focus_active = "/usr/share/awesome/themes/default/titlebar/floating_focus_active.png"
theme.titlebar_maximized_button_normal_inactive = "/usr/share/awesome/themes/default/titlebar/maximized_normal_inactive.png"
theme.titlebar_maximized_button_focus_inactive = "/usr/share/awesome/themes/default/titlebar/maximized_focus_inactive.png"
theme.titlebar_maximized_button_normal_active = "/usr/share/awesome/themes/default/titlebar/maximized_normal_active.png"
theme.titlebar_maximized_button_focus_active = "/usr/share/awesome/themes/default/titlebar/maximized_focus_active.png"
theme.wallpaper = "/home/sophos/Downloads/wolf1.jpg"
-- You can use your own layout icons like this:
theme.layout_fairh = "/usr/share/awesome/themes/default/layouts/fairhw.png"
theme.layout_fairv = "/usr/share/awesome/themes/default/layouts/fairvw.png"
theme.layout_floating = "/usr/share/awesome/themes/default/layouts/floatingw.png"
theme.layout_magnifier = "/usr/share/awesome/themes/default/layouts/magnifierw.png"
theme.layout_max = "/usr/share/awesome/themes/default/layouts/maxw.png"
theme.layout_fullscreen = "/usr/share/awesome/themes/default/layouts/fullscreenw.png"
theme.layout_tilebottom = "/usr/share/awesome/themes/default/layouts/tilebottomw.png"
theme.layout_tileleft = "/usr/share/awesome/themes/default/layouts/tileleftw.png"
theme.layout_tile = "/usr/share/awesome/themes/default/layouts/tilew.png"
theme.layout_tiletop = "/usr/share/awesome/themes/default/layouts/tiletopw.png"
theme.layout_spiral = "/usr/share/awesome/themes/default/layouts/spiralw.png"
theme.layout_dwindle = "/usr/share/awesome/themes/default/layouts/dwindlew.png"
theme.awesome_icon = "/usr/share/awesome/icons/awesome16.png"
-- Define the icon theme for application icons. If not set then the icons
-- from /usr/share/icons and /usr/share/icons/hicolor will be used.
theme.icon_theme = nil
return theme
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| mit |
rickvanbodegraven/nodemcu-firmware | app/cjson/lua/cjson/util.lua | 170 | 6837 | local json = require "cjson"
-- Various common routines used by the Lua CJSON package
--
-- Mark Pulford <mark@kyne.com.au>
-- Determine with a Lua table can be treated as an array.
-- Explicitly returns "not an array" for very sparse arrays.
-- Returns:
-- -1 Not an array
-- 0 Empty table
-- >0 Highest index in the array
local function is_array(table)
local max = 0
local count = 0
for k, v in pairs(table) do
if type(k) == "number" then
if k > max then max = k end
count = count + 1
else
return -1
end
end
if max > count * 2 then
return -1
end
return max
end
local serialise_value
local function serialise_table(value, indent, depth)
local spacing, spacing2, indent2
if indent then
spacing = "\n" .. indent
spacing2 = spacing .. " "
indent2 = indent .. " "
else
spacing, spacing2, indent2 = " ", " ", false
end
depth = depth + 1
if depth > 50 then
return "Cannot serialise any further: too many nested tables"
end
local max = is_array(value)
local comma = false
local fragment = { "{" .. spacing2 }
if max > 0 then
-- Serialise array
for i = 1, max do
if comma then
table.insert(fragment, "," .. spacing2)
end
table.insert(fragment, serialise_value(value[i], indent2, depth))
comma = true
end
elseif max < 0 then
-- Serialise table
for k, v in pairs(value) do
if comma then
table.insert(fragment, "," .. spacing2)
end
table.insert(fragment,
("[%s] = %s"):format(serialise_value(k, indent2, depth),
serialise_value(v, indent2, depth)))
comma = true
end
end
table.insert(fragment, spacing .. "}")
return table.concat(fragment)
end
function serialise_value(value, indent, depth)
if indent == nil then indent = "" end
if depth == nil then depth = 0 end
if value == json.null then
return "json.null"
elseif type(value) == "string" then
return ("%q"):format(value)
elseif type(value) == "nil" or type(value) == "number" or
type(value) == "boolean" then
return tostring(value)
elseif type(value) == "table" then
return serialise_table(value, indent, depth)
else
return "\"<" .. type(value) .. ">\""
end
end
local function file_load(filename)
local file
if filename == nil then
file = io.stdin
else
local err
file, err = io.open(filename, "rb")
if file == nil then
error(("Unable to read '%s': %s"):format(filename, err))
end
end
local data = file:read("*a")
if filename ~= nil then
file:close()
end
if data == nil then
error("Failed to read " .. filename)
end
return data
end
local function file_save(filename, data)
local file
if filename == nil then
file = io.stdout
else
local err
file, err = io.open(filename, "wb")
if file == nil then
error(("Unable to write '%s': %s"):format(filename, err))
end
end
file:write(data)
if filename ~= nil then
file:close()
end
end
local function compare_values(val1, val2)
local type1 = type(val1)
local type2 = type(val2)
if type1 ~= type2 then
return false
end
-- Check for NaN
if type1 == "number" and val1 ~= val1 and val2 ~= val2 then
return true
end
if type1 ~= "table" then
return val1 == val2
end
-- check_keys stores all the keys that must be checked in val2
local check_keys = {}
for k, _ in pairs(val1) do
check_keys[k] = true
end
for k, v in pairs(val2) do
if not check_keys[k] then
return false
end
if not compare_values(val1[k], val2[k]) then
return false
end
check_keys[k] = nil
end
for k, _ in pairs(check_keys) do
-- Not the same if any keys from val1 were not found in val2
return false
end
return true
end
local test_count_pass = 0
local test_count_total = 0
local function run_test_summary()
return test_count_pass, test_count_total
end
local function run_test(testname, func, input, should_work, output)
local function status_line(name, status, value)
local statusmap = { [true] = ":success", [false] = ":error" }
if status ~= nil then
name = name .. statusmap[status]
end
print(("[%s] %s"):format(name, serialise_value(value, false)))
end
local result = { pcall(func, unpack(input)) }
local success = table.remove(result, 1)
local correct = false
if success == should_work and compare_values(result, output) then
correct = true
test_count_pass = test_count_pass + 1
end
test_count_total = test_count_total + 1
local teststatus = { [true] = "PASS", [false] = "FAIL" }
print(("==> Test [%d] %s: %s"):format(test_count_total, testname,
teststatus[correct]))
status_line("Input", nil, input)
if not correct then
status_line("Expected", should_work, output)
end
status_line("Received", success, result)
print()
return correct, result
end
local function run_test_group(tests)
local function run_helper(name, func, input)
if type(name) == "string" and #name > 0 then
print("==> " .. name)
end
-- Not a protected call, these functions should never generate errors.
func(unpack(input or {}))
print()
end
for _, v in ipairs(tests) do
-- Run the helper if "should_work" is missing
if v[4] == nil then
run_helper(unpack(v))
else
run_test(unpack(v))
end
end
end
-- Run a Lua script in a separate environment
local function run_script(script, env)
local env = env or {}
local func
-- Use setfenv() if it exists, otherwise assume Lua 5.2 load() exists
if _G.setfenv then
func = loadstring(script)
if func then
setfenv(func, env)
end
else
func = load(script, nil, nil, env)
end
if func == nil then
error("Invalid syntax.")
end
func()
return env
end
-- Export functions
return {
serialise_value = serialise_value,
file_load = file_load,
file_save = file_save,
compare_values = compare_values,
run_test_summary = run_test_summary,
run_test = run_test,
run_test_group = run_test_group,
run_script = run_script
}
-- vi:ai et sw=4 ts=4:
| mit |
ld-test/oil | lua/loop/compiler/Expression.lua | 7 | 8937 | --------------------------------------------------------------------------------
---------------------- ## ##### ##### ###### -----------------------
---------------------- ## ## ## ## ## ## ## -----------------------
---------------------- ## ## ## ## ## ###### -----------------------
---------------------- ## ## ## ## ## ## -----------------------
---------------------- ###### ##### ##### ## -----------------------
---------------------- -----------------------
----------------------- Lua Object-Oriented Programming ------------------------
--------------------------------------------------------------------------------
-- Project: LOOP Class Library --
-- Release: 2.3 beta --
-- Title : Simple Expression Parser --
-- Author : Renato Maia <maia@inf.puc-rio.br> --
--------------------------------------------------------------------------------
local luaerror = error
local pairs = pairs
local ipairs = ipairs
local unpack = unpack
local select = select
require "string"
local oo = require "loop.base"
--[[VERBOSE]] local verbose = require("loop.debug.Verbose"){
--[[VERBOSE]] groups = { expression = {"operator","value","parse"} }
--[[VERBOSE]] }
--[[VERBOSE]] verbose:flag("expression", false)
module("loop.compiler.Expression", oo.class)
pos = 1
count = 0
precedence = {}
local pattern = "^ *%s"
function __init(self, object)
self = oo.rawnew(self, object)
if not self.operands and self.values then
local operands = {}
for kind, spec in pairs(self.values) do
operands[kind] = pattern:format(spec)
end
self.operands = operands
end
if not self.format and self.operators then
local opformat = {}
for name, spec in pairs(self.operators) do
local format = {}
local pos = 1
while pos <= #spec do
if spec:find("^ ", pos) then
format[#format+1] = true
pos = pos + 1
else
local keyword = spec:match("^[^ ]+", pos)
format[#format+1] = keyword
pos = pos + #keyword
end
end
opformat[name] = format
end
self.format = opformat
end
self.values = self.values or {}
return self
end
function push(self, kind, value)
self[#self+1] = kind
if kind == true then
self.count = self.count + 1
self.values[self.count] = value
end
end
function pop(self)
local kind = self[#self]
self[#self] = nil
local value
if kind == true then
value = self.values[self.count]
self.count = self.count - 1
end
return kind, value
end
function get(self, count)
local nvals = 0
for _=1, count do
if self[#self] == true then
nvals = nvals + 1
end
self[#self] = nil
end
self.count = self.count - nvals
return unpack(self.values, self.count + 1, self.count + nvals)
end
local errmsg = "%s at position %d"
function error(self, msg)
return luaerror(errmsg:format(msg, self.pos))
end
function done(self)
return (self.text:match("^%s*$", self.pos))
end
function token(self, token)
local pos = select(2, self.text:find("^%s*[^%s]", self.pos))
if pos and (self.text:find(token, pos, true) == pos) then
self.pos = pos + #token
return true
end
end
function match(self, pattern)
local first, last, value = self.text:find(pattern, self.pos)
if first then
self.pos = last + 1
return value
end
end
function operator(self, name, level, start)
local format = self.format[name]
for index, kind in ipairs(format) do
local parsed = self[start + index]
if parsed then
if parsed ~= kind then --[[VERBOSE]] verbose:operator("parsed value mismatch, got '",parsed,"' ('",kind,"' expected)")
return false --[[VERBOSE]] else verbose:operator("parsed value matched, got '",parsed,"'")
end
else
if kind == true then --[[VERBOSE]] verbose:operator(true, "operand expected, parsing...")
if not self:parse(level + 1, #self) then --[[VERBOSE]] verbose:operator(false, "operand parsing failed")
return false
end --[[VERBOSE]] verbose:operator(false, "operand parsed successfully")
else --[[VERBOSE]] verbose:operator("token ",kind," expected")
if self:token(kind) then --[[VERBOSE]] verbose:operator("token found successfully")
self:push(kind)
else --[[VERBOSE]] verbose:operator("token not found")
return false
end
end
end
end --[[VERBOSE]] verbose:operator(true, "operator ",name," matched")
self:push(true, self[name](self, self:get(#format))) --[[VERBOSE]] verbose:operator(false, "operator ",name," callback called")
return true
end
function value(self)
if self:token("(") then --[[VERBOSE]] verbose:value(true, "'(' found at ",self.pos)
local start = #self
if not self:parse(1, start) then --[[VERBOSE]] verbose:value(false, "error in enclosed expression")
self:error("value expected")
elseif #self ~= start + 1 or self[#self] ~= true then --[[VERBOSE]] verbose:value(false, "enclosed expression incomplete (too many parsed values left)")
self:error("incomplete expression")
elseif not self:token(")") then --[[VERBOSE]] verbose:value(false, "')' not found")
self:error("')' expected")
end --[[VERBOSE]] verbose:value(false, "matching ')' found")
return true
else --[[VERBOSE]] verbose:value(true, "parsing value at ",self.pos)
for kind, pattern in pairs(self.operands) do --[[VERBOSE]] verbose:value("attempt to match value as ",kind)
local value = self:match(pattern)
if value then --[[VERBOSE]] verbose:value(true, "value found as ",kind)
self:push(true, self[kind](self, value)) --[[VERBOSE]] verbose:value(false, "value evaluated to ",self.values[self.count])
return true --[[VERBOSE]],verbose:value(false)
end
end --[[VERBOSE]] verbose:value(false, "no value found at ",self.pos)
return false
end
end
function parse(self, level, start)
if not self:done() then
local ops = self.precedence[level]
if ops then --[[VERBOSE]] verbose:parse(true, "parsing operators of level ",level)
local i = 1
while ops[i] do
local op = ops[i] --[[VERBOSE]] verbose:parse(true, "attempt to match operator ",op)
if self:operator(ops[i], level, start) then --[[VERBOSE]] verbose:parse(false, "operator ",op," successfully matched")
i = 1
else --[[VERBOSE]] verbose:parse(false, "operator ",op," not matched")
i = i + 1
end
end
if #self == start then --[[VERBOSE]] verbose:parse(false, "no value evaluated by operators of level ",level)
return self:parse(level + 1, start)
elseif self[start + 1] == true then --[[VERBOSE]] verbose:parse(false, "values evaluated by operators of level ",level)
return true
end
else --[[VERBOSE]] verbose:parse(true, "parsing value")
return self:value() --[[VERBOSE]] ,verbose:parse(false)
end
end
end
function evaluate(self, text, pos)
if text then
self.text = text
self.pos = pos
end
if not self:parse(1, 0) then
self:error("parsing failed")
elseif not self:done() then
self:error("malformed expression")
elseif #self ~= 1 or self[1] ~= true then
self:error("incomplete expression")
end
return self:get(1)
end
| mit |
jonmaur/draggin-framework | src/draggin/physics.lua | 1 | 19698 | --[[
Copyright (c) 2014 Jon Maur
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.
]]
-- Box2D Physics!
local Display = require "draggin/display"
local TextBox = require "draggin/textbox"
local Sprite = require "draggin/sprite"
local TableExt = require "draggin/tableext"
local RADIANS_TO_DEGREES = 180 / math.pi
local Physics = {}
function Physics.new(_gravity, _unitsToMeters, _debuglayer)
local Phys = {}
_gravity = _gravity or {x=0, y=-10}
if type(_gravity) == "number" then
_gravity = {x=0, y=_gravity}
end
_unitsToMeters = _unitsToMeters or 1
local world = MOAIBox2DWorld.new()
world:setUnitsToMeters(_unitsToMeters)
world.unitsToMeters = _unitsToMeters
world.metersToUnits = 1/_unitsToMeters
world:setGravity(_gravity.x, _gravity.y)
world:start()
-- table to keep track of all bodies by name
world.bodies = {}
-- table to keep track of all joints by name
world.joints = {}
-- table to keep track of all images by name
world.images = {}
Phys.world = world
if _debuglayer then
print("Debug Physics Draws on")
_debuglayer:setBox2DWorld(world)
end
function Phys:addRect(_type, x, y, w, h, r)
local physBody = {}
_type = _type or MOAIBox2DBody.STATIC
r = r or 0
local body = world:addBody(_type)
local fixture = body:addRect(x, y, x+w, y+h)
fixture:setFriction(0.1)
body:setTransform(0, 0, r)
physBody.body = body
physBody.fixture = fixture
return physBody
end
function Phys:addSpriteBody(_sprite, _type, _bounds)
assert(_sprite)
_type = _type or MOAIBox2DBody.DYNAMIC
local body = world:addBody(_type)
-- move to the sprite's position
body:setTransform(_sprite:getLoc())
_bounds = _bounds or _sprite:getBounds()
local fixture = body:addRect(_bounds[1], _bounds[2], _bounds[3], _bounds[4])
fixture:setFriction(0.5)
fixture:setDensity(0.0001)
fixture:setRestitution(0.2)
--body:setMassData(320)
-- hook it up to the sprite
_sprite.body = body
_sprite:setParent(body)
_sprite.fixture = fixture
body:resetMassData()
end
function Phys:addSpriteBodyCircle(_sprite, _type, _radius, _fixedrotation)
assert(_sprite)
_type = _type or MOAIBox2DBody.DYNAMIC
_fixedrotation = _fixedrotation or false
local body = world:addBody(_type)
-- move to the sprite's position
body:setTransform(_sprite:getLoc())
body:setFixedRotation(_fixedrotation)
local bounds = _sprite:getBounds()
local midx = (bounds[3]-bounds[1])/2
local midy = (bounds[4]-bounds[2])/2
if not _radius then
_radius = midx+0.5
end
local fixture = body:addCircle(0, 0, _radius-2)
fixture:setFriction(0.5)
fixture:setDensity(0.0001)
fixture:setRestitution(0.2)
--body:setMassData(320)
-- hook it up to the sprite
_sprite.body = body
_sprite:setParent(body)
_sprite.fixture = fixture
body:resetMassData()
end
function Phys:addCircle(_type, x, y, r)
local physBody = {}
_type = _type or MOAIBox2DBody.STATIC
local body = world:addBody(_type)
local fixture = body:addCircle(x, y, r)
fixture:setFriction(0.5)
physBody.body = body
physBody.fixture = fixture
return physBody
end
function Phys:addChain(_verts, _close)
assert(type(_verts) == "table")
local physBody = {}
local body = world:addBody(MOAIBox2DBody.STATIC)
local chain = body:addChain(_verts, _close)
physBody.body = body
physBody.chain = chain
chain:setFilter(2, 4)
return physBody
end
function Phys:loadRubeJson(_filename, _layer)
local jsonFile = MOAIFileStream.new()
jsonFile:open("res/rube/".._filename..".json")
local jsonStr = jsonFile:read()
local json = MOAIJsonParser.decode(jsonStr)
--TableExt.print(json)
-- World settings
-- "allowSleep" : true, BETTER ALWAYS BE TRUE!
-- "autoClearForces" : true,
if type(json.autoClearForces) == "boolean" then
world:setAutoClearForces(json.autoClearForces)
end
-- "continuousPhysics" : true,
-- "gravity" :
local gx = 0
local gy = 0
if type(json.gravity) == "table" then
gx = json.gravity.x
gy = json.gravity.y
end
world:setGravity(gx, gy)
--"velocityIterations" : 8,
--"positionIterations" : 3,
world:setIterations(json.velocityIterations, json.positionIterations)
--"stepsPerSecond" : 60.0, I guess this is framerate?
--"subStepping" : false, -- always false, it's a box2d debug feature
--"warmStarting" : true
local bodies = {}
if type(json.body) == "table" then
for _, v in ipairs(json.body) do
-- "type": 2, //0 = static, 1 = kinematic, 2 = dynamic
local bodytype = MOAIBox2DBody.STATIC
if v.type == 1 then
bodytype = MOAIBox2DBody.KINEMATIC
elseif v.type == 2 then
bodytype = MOAIBox2DBody.DYNAMIC
end
-- create the body
local body = world:addBody(bodytype)
local x = 0
local y = 0
if type(v.position) == "table" then
x = v.position.x
y = v.position.y
end
if type(v.fixture) == "table" then
body.fixtures = {}
for _, fixture in ipairs(v.fixture) do
local fix = nil
if type(fixture.chain) == "table" then
-- TODO: closed chain
-- gather the verts
local xs = fixture.chain.vertices.x
local ys = fixture.chain.vertices.y
local verts = {}
for i = 1, #xs do
table.insert(verts, xs[i])
table.insert(verts, ys[i])
end
fix = body:addChain(verts, false)
elseif type(fixture.polygon) == "table" then
-- gather the verts
local xs = fixture.polygon.vertices.x
local ys = fixture.polygon.vertices.y
local verts = {}
for i = 1, #xs do
table.insert(verts, xs[i])
table.insert(verts, ys[i])
end
fix = body:addPolygon(verts)
-- print("polygon", fixture.name)
elseif type(fixture.circle) == "table" then
-- "center" : 0
local centerX = 0
local centerY = 0
if type(fixture.circle.center) == "table" then
centerX = fixture.circle.center.x
centerY = fixture.circle.center.y
end
-- "radius" : 1
local radius = 0
if type(fixture.circle.radius) == "number" then
radius = fixture.circle.radius
end
fix = body:addCircle(centerX, centerY, radius)
-- print("circle", fixture.name)
end
if fix then
local density = 1 / (world.metersToUnits * world.metersToUnits)
if type(fixture.density) == "number" then
density = fixture.density / (world.metersToUnits * world.metersToUnits)
end
fix:setDensity(density)
if type(fixture.friction) == "number" then
fix:setFriction(fixture.friction)
end
if type(fixture.restitution) == "number" then
fix:setRestitution(fixture.restitution)
end
if type(fixture.sensor) == "boolean" then
fix:setSensor(fixture.sensor)
end
local categoryBits = 1
if type(fixture["filter-categoryBits"]) == "number" then
categoryBits = fixture["filter-categoryBits"]
end
local maskBits = 65535
if type(fixture["filter-maskBits"]) == "number" then
maskBits = fixture["filter-maskBits"]
end
local groupIndex = 0
if type(fixture["filter-groupIndex"]) == "number" then
groupIndex = fixture["filter-groupIndex"]
end
fix:setFilter(categoryBits, maskBits, groupIndex)
fix.name = fixture.name
fix.body = body
-- Rube likes to handle complex fixtures as one,
-- but they are actually multiple fixtures with the same name
if body.fixtures[fixture.name] == nil then
-- we're fine, there's only the one fixture by this name so far
body.fixtures[fixture.name] = fix
elseif type(body.fixtures[fixture.name]) == "userdata" then
-- turn it into a table
local t = {body.fixtures[fixture.name], fix}
body.fixtures[fixture.name] = t
elseif type(body.fixtures[fixture.name]) == "table" then
-- it's already a table of fixtures by this name
body.fixtures[fixture.name][#body.fixtures[fixture.name]+1] = fix
end
end
end
end
-- radians
local angle = 0
if type(v.angle) == "number" then
angle = v.angle * RADIANS_TO_DEGREES
end
-- "angularDamping": 0,
local angularDamping = 0
if type(v.angularDamping) == "number" then
angularDamping = v.angularDamping
end
body:setAngularDamping(angularDamping)
-- "angularVelocity": 0, //radians per second
local angularVelocity = 0
if type(v.angularVelocity) == "number" then
angularVelocity = v.angularVelocity * RADIANS_TO_DEGREES
end
body:setAngularVelocity(angularVelocity)
-- "awake": true,
if type(v.awake) == "boolean" then
body:setAwake(v.awake)
end
-- "bullet": true,
if type(v.bullet) == "boolean" then
body:setBullet(v.bullet)
end
-- "fixedRotation": false,
local fixedRotation = false
if type(v.fixedRotation) == "boolean" then
fixedRotation = v.fixedRotation
end
body:setFixedRotation(fixedRotation)
-- "linearDamping": 0,
local linearDamping = 0
if type(v.linearDamping) == "number" then
linearDamping = v.linearDamping
end
body:setLinearDamping(linearDamping)
-- "linearVelocity": (vector),
local lvx = 0
local lvy = 0
if type(v.linearVelocity) == "table" then
-- TODO: do I need to convert these using meters to units?
lvx = v.linearVelocity.x
lvy = v.linearVelocity.y
end
body:setLinearVelocity(lvx, lvy)
-- "massData-mass": 1,
local mass = nil
if type(v["massData-mass"]) == "number" then
mass = v["massData-mass"]
end
-- "massData-center": (vector),
local massX = nil
local massY = nil
if type(v["massData-center"]) == "table" then
massX = v["massData-center"].x * world.metersToUnits
massY = v["massData-center"].y * world.metersToUnits
end
-- "massData-I": 1,
local massI = nil
if type(v["massData-I"]) == "number" then
massI = v["massData-I"] * world.metersToUnits * world.metersToUnits
end
body:setTransform(x, y, angle)
body:resetMassData()
if mass ~= nil then
body:setMassData(mass, massI, massX, massY)
end
-- insert into the bodies table which is referenced by index by the joints
table.insert(bodies, body)
-- keep a reference in the world by name
world.bodies[v.name] = body
body.name = v.name
end -- bodies
end
-- joints must be done after all the bodies
if type(json.joint) == "table" then
for _, j in ipairs(json.joint) do
-- Common to all joints
-- "anchorA": (vector),
local anchorAX = 0
local anchorAY = 0
if type(j.anchorA) == "table" then
anchorAX = j.anchorA.x
anchorAY = j.anchorA.y
end
-- "anchorB": (vector),
local anchorBX = 0
local anchorBY = 0
if type(j.anchorB) == "table" then
anchorBX = j.anchorB.x
anchorBY = j.anchorB.y
end
-- "bodyA": 4, //zero-based index of body in bodies array
local bodyA = bodies[j.bodyA + 1]
-- "bodyB": 1, //zero-based index of body in bodies array
local bodyB = bodies[j.bodyB + 1]
-- "localAxisA": (vector),
local axisX = 0
local axisY = 0
if type(j.localAxisA) == "table" then
axisX = j.localAxisA.x
axisY = j.localAxisA.y
end
-- "collideConnected" : false,
local collideConnected = false
if type(j.collideConnected) == "boolean" then
collideConnected = j.collideConnected
end
local bodyAX, bodyAY = bodyA:getPosition()
local bodyBX, bodyBY = bodyB:getPosition()
-- wheel type
if j.type == "wheel" then
local wheelJoint = world:addWheelJoint(bodyA, bodyB, bodyAX+anchorAX, bodyAY+anchorAY, axisX, axisY)
-- "customProperties": //An array of zero or more custom properties.
-- "enableMotor": true,
if type(j.enableMotor) == "boolean" then
wheelJoint:setMotorEnabled(j.enableMotor)
end
-- "motorSpeed": 0,
if type(j.motorSpeed) == "number" then
-- these are radians, MOAI needs degrees
wheelJoint:setMotorSpeed(j.motorSpeed * RADIANS_TO_DEGREES)
end
-- "maxMotorTorque": 0,
if type(j.maxMotorTorque) == "number" then
wheelJoint:setMaxMotorTorque(j.maxMotorTorque)
end
-- "springDampingRatio": 0.7,
if type(j.springDampingRatio) == "number" then
wheelJoint:setSpringDampingRatio(j.springDampingRatio)
end
-- "springFrequency": 4,
if type(j.springFrequency) == "number" then
wheelJoint:setSpringFrequencyHz(j.springFrequency)
end
-- keep a reference in the world by name
world.joints[j.name] = wheelJoint
elseif j.type == "revolute" then
-- NOTE: This requires MOAI changes
-- NOTE: world:addRevoluteJoint didn't work so well for me.
local revoluteJoint = world:addRevoluteJointLocal(bodyA, bodyB, anchorAX, anchorAY,
anchorBX, anchorBY, collideConnected)
-- "lowerLimit": 0,
local lowerLimit = 0
if type(j.lowerLimit) == "number" then
lowerLimit = j.lowerLimit * RADIANS_TO_DEGREES
end
-- "upperLimit": 0,
local upperLimit = 0
if type(j.upperLimit) == "number" then
upperLimit = j.upperLimit * RADIANS_TO_DEGREES
end
revoluteJoint:setLimit(lowerLimit, upperLimit)
-- "enableLimit": false,
local enableLimit = false
if type(j.enableLimit) == "boolean" then
enableLimit = j.enableLimit
revoluteJoint:setLimitEnabled(enableLimit)
end
-- "jointSpeed": 0,
if type(j.jointSpeed) == "number" then
-- TODO: anything to do with this??
end
-- "refAngle": 0,
if type(j.refAngle) == "number" then
-- TODO
end
-- "enableMotor": true,
if type(j.enableMotor) == "boolean" then
revoluteJoint:setMotorEnabled(j.enableMotor)
end
-- "motorSpeed": 0,
if type(j.motorSpeed) == "number" then
-- these are radians, MOAI needs degrees
revoluteJoint:setMotorSpeed(j.motorSpeed * RADIANS_TO_DEGREES)
end
-- "maxMotorTorque": 0,
if type(j.maxMotorTorque) == "number" then
revoluteJoint:setMaxMotorTorque(j.maxMotorTorque)
end
-- keep a reference in the world by name
world.joints[j.name] = revoluteJoint
elseif j.type == "distance" then
-- "dampingRatio" : 0,
local dampingRatio = 0
if type(j.dampingRatio) == "number" then
dampingRatio = j.dampingRatio
end
-- "frequency" : 0,
local frequency = 0
if type(j.frequency) == "number" then
frequency = j.frequency
end
local distanceJoint = world:addDistanceJoint(bodyA, bodyB, bodyAX+anchorAX, bodyAY+anchorAY,
frequency, dampingRatio, collideConnected)
-- "length" : 0,
if type(j.length) == "number" then
distanceJoint:setLength(j.length * world.metersToUnits)
end
-- keep a reference in the world by name
world.joints[j.name] = distanceJoint
elseif j.type == "prismatic" then
local prismaticJoint = world:addPrismaticJoint(bodyA, bodyB, bodyAX+anchorAX, bodyAY+anchorAY,
axisX, axisY, collideConnected)
-- "lowerLimit": 0,
local lowerLimit = 0
if type(j.lowerLimit) == "number" then
lowerLimit = j.lowerLimit * RADIANS_TO_DEGREES
end
-- "upperLimit": 0,
local upperLimit = 0
if type(j.upperLimit) == "number" then
upperLimit = j.upperLimit * RADIANS_TO_DEGREES
end
prismaticJoint:setLimit(lowerLimit, upperLimit)
-- "enableLimit": false,
local enableLimit = false
if type(j.enableLimit) == "boolean" then
enableLimit = j.enableLimit
prismaticJoint:setLimitEnabled(enableLimit)
end
-- "enableMotor": true,
if type(j.enableMotor) == "boolean" then
prismaticJoint:setMotorEnabled(j.enableMotor)
end
-- "motorSpeed": 0,
if type(j.motorSpeed) == "number" then
prismaticJoint:setMotorSpeed(j.motorSpeed * world.metersToUnits)
end
-- "maxMotorForce": 0,
if type(j.maxMotorForce) == "number" then
prismaticJoint:setMaxMotorForce(j.maxMotorForce * world.metersToUnits)
end
-- "refAngle": 0,
if type(j.refAngle) == "number" then
-- TODO
end
-- keep a reference in the world by name
world.joints[j.name] = prismaticJoint
end
end -- joints
end
-- images must be done after all the bodies
if type(json.image) == "table" then
for _, img in ipairs(json.image) do
-- "aspectScale" : 1,
local aspectScale = 1
if type(img.aspectScale) == "number" then
aspectScale = img.aspectScale
end
-- "body" : 0, zero-based index of body in bodies array
-- img.body might be -1 which results in body being nil
local body = bodies[img.body + 1]
-- "center" : 0,
local centerX = 0
local centerY = 0
if type(img.center) == "table" then
centerX = img.center.x
centerY = img.center.y
end
-- "file" : "../sprites/cars/bluebody.png",
local sprname, animname, framenum = string.match(img.file, "/(%w+)/([%a_-]+)(%d-).png$")
-- print("image", sprname, animname, framenum)
local spr = Sprite.new(sprname)
local speed = 1
if type(img.customProperties) == "table" then
for _, prop in ipairs(img.customProperties) do
if type(prop) == "table" then
if prop.name == "speed" then
if type(prop.float) == "number" then
speed = prop.float
end
end
end
end
end
spr:playAnimation(animname, speed)
_layer:insertProp(spr)
spr:setParent(body)
spr:setLoc(centerX, centerY)
if type(img.glVertexPointer) == "table" then
local orgw = spr.spriteData.originalWidths[animname]
local rubew = img.glVertexPointer[3] - img.glVertexPointer[1]
local scale = 1 / (orgw / rubew)
spr:setScl(scale)
end
if type(img.flip) == "boolean" then
if img.flip then
local sx, sy = spr:getScl()
spr:setScl(-sx, sy)
end
end
local r = 1
local g = 1
local b = 1
local a = 1
if type(img.colorTint) == "table" then
r = img.colorTint[1] / 255
g = img.colorTint[2] / 255
b = img.colorTint[3] / 255
a = img.colorTint[4] / 255
end
if type(img.opacity) == "number" then
a = a * img.opacity
end
spr:setColor(r, g, b, a)
if body then
body.sprites = body.sprites or {}
body.sprites[#body.sprites+1] = spr
end
-- keep a reference in the world by name
world.images[img.name] = spr
end -- images
end
end
return Phys
end
return Physics
| mit |
grimreaper/ValyriaTear | dat/tilesets/harrvah_house_interior.lua | 2 | 9907 | local ns = {};
setmetatable(ns, {__index = _G});
harrvah_house_interior = ns;
setfenv(1, ns);
file_name = "dat/tilesets/harrvah_house_interior.lua"
image = "img/tilesets/harrvah_house_interior.png"
num_tile_cols = 16
num_tile_rows = 16
-- The general walkability of the tiles in the tileset. Zero indicates walkable. One tile has four walkable quadrants listed as: NW corner, NE corner, SW corner, SE corner.
walkability = {}
walkability[0] = {}
walkability[0][0] = { 0, 0, 0, 0 }
walkability[0][1] = { 0, 0, 0, 0 }
walkability[0][2] = { 0, 0, 0, 0 }
walkability[0][3] = { 0, 0, 0, 0 }
walkability[0][4] = { 0, 0, 0, 0 }
walkability[0][5] = { 0, 0, 0, 0 }
walkability[0][6] = { 0, 0, 0, 0 }
walkability[0][7] = { 0, 0, 0, 0 }
walkability[0][8] = { 0, 0, 0, 0 }
walkability[0][9] = { 0, 0, 0, 0 }
walkability[0][10] = { 0, 0, 0, 0 }
walkability[0][11] = { 0, 0, 0, 0 }
walkability[0][12] = { 0, 0, 0, 0 }
walkability[0][13] = { 0, 0, 0, 0 }
walkability[0][14] = { 0, 0, 0, 0 }
walkability[0][15] = { 0, 0, 0, 0 }
walkability[1] = {}
walkability[1][0] = { 0, 0, 0, 0 }
walkability[1][1] = { 0, 0, 0, 0 }
walkability[1][2] = { 0, 0, 0, 0 }
walkability[1][3] = { 0, 0, 0, 0 }
walkability[1][4] = { 0, 0, 0, 0 }
walkability[1][5] = { 0, 0, 0, 0 }
walkability[1][6] = { 1, 1, 1, 1 }
walkability[1][7] = { 1, 1, 1, 1 }
walkability[1][8] = { 1, 1, 1, 1 }
walkability[1][9] = { 1, 1, 1, 1 }
walkability[1][10] = { 1, 1, 1, 1 }
walkability[1][11] = { 0, 0, 0, 0 }
walkability[1][12] = { 0, 0, 0, 0 }
walkability[1][13] = { 0, 0, 0, 0 }
walkability[1][14] = { 0, 0, 0, 0 }
walkability[1][15] = { 0, 0, 0, 0 }
walkability[2] = {}
walkability[2][0] = { 1, 1, 1, 1 }
walkability[2][1] = { 1, 1, 1, 1 }
walkability[2][2] = { 1, 1, 1, 1 }
walkability[2][3] = { 1, 1, 1, 1 }
walkability[2][4] = { 1, 1, 1, 1 }
walkability[2][5] = { 1, 1, 1, 1 }
walkability[2][6] = { 1, 1, 1, 1 }
walkability[2][7] = { 1, 1, 1, 1 }
walkability[2][8] = { 1, 1, 1, 1 }
walkability[2][9] = { 1, 1, 1, 1 }
walkability[2][10] = { 1, 1, 1, 1 }
walkability[2][11] = { 1, 1, 1, 1 }
walkability[2][12] = { 1, 1, 1, 1 }
walkability[2][13] = { 1, 0, 1, 0 }
walkability[2][14] = { 0, 0, 0, 0 }
walkability[2][15] = { 0, 0, 0, 0 }
walkability[3] = {}
walkability[3][0] = { 1, 1, 1, 1 }
walkability[3][1] = { 1, 1, 1, 1 }
walkability[3][2] = { 1, 1, 1, 1 }
walkability[3][3] = { 1, 1, 1, 1 }
walkability[3][4] = { 1, 1, 1, 1 }
walkability[3][5] = { 1, 1, 1, 1 }
walkability[3][6] = { 1, 1, 1, 1 }
walkability[3][7] = { 1, 1, 1, 1 }
walkability[3][8] = { 1, 1, 1, 1 }
walkability[3][9] = { 1, 1, 1, 1 }
walkability[3][10] = { 1, 1, 1, 1 }
walkability[3][11] = { 1, 1, 1, 1 }
walkability[3][12] = { 1, 1, 1, 1 }
walkability[3][13] = { 1, 0, 1, 0 }
walkability[3][14] = { 0, 0, 0, 0 }
walkability[3][15] = { 0, 0, 0, 0 }
walkability[4] = {}
walkability[4][0] = { 1, 1, 1, 1 }
walkability[4][1] = { 1, 1, 1, 1 }
walkability[4][2] = { 1, 1, 1, 1 }
walkability[4][3] = { 1, 1, 1, 1 }
walkability[4][4] = { 1, 1, 1, 1 }
walkability[4][5] = { 1, 1, 1, 1 }
walkability[4][6] = { 1, 1, 1, 1 }
walkability[4][7] = { 1, 1, 1, 1 }
walkability[4][8] = { 1, 1, 1, 0 }
walkability[4][9] = { 1, 1, 0, 0 }
walkability[4][10] = { 1, 1, 1, 1 }
walkability[4][11] = { 1, 1, 1, 1 }
walkability[4][12] = { 1, 1, 1, 1 }
walkability[4][13] = { 1, 0, 1, 0 }
walkability[4][14] = { 0, 0, 0, 0 }
walkability[4][15] = { 0, 0, 0, 0 }
walkability[5] = {}
walkability[5][0] = { 1, 1, 1, 1 }
walkability[5][1] = { 1, 1, 1, 1 }
walkability[5][2] = { 1, 1, 1, 1 }
walkability[5][3] = { 1, 1, 1, 1 }
walkability[5][4] = { 1, 1, 1, 1 }
walkability[5][5] = { 1, 1, 1, 1 }
walkability[5][6] = { 1, 1, 1, 1 }
walkability[5][7] = { 1, 1, 1, 0 }
walkability[5][8] = { 0, 0, 0, 0 }
walkability[5][9] = { 0, 0, 0, 0 }
walkability[5][10] = { 0, 1, 0, 0 }
walkability[5][11] = { 1, 1, 1, 1 }
walkability[5][12] = { 1, 1, 1, 1 }
walkability[5][13] = { 1, 0, 1, 0 }
walkability[5][14] = { 0, 0, 0, 0 }
walkability[5][15] = { 0, 0, 0, 0 }
walkability[6] = {}
walkability[6][0] = { 1, 1, 1, 1 }
walkability[6][1] = { 1, 1, 1, 1 }
walkability[6][2] = { 0, 0, 0, 0 }
walkability[6][3] = { 0, 0, 0, 0 }
walkability[6][4] = { 0, 0, 0, 0 }
walkability[6][5] = { 0, 0, 0, 0 }
walkability[6][6] = { 0, 0, 0, 0 }
walkability[6][7] = { 0, 0, 0, 0 }
walkability[6][8] = { 0, 0, 0, 0 }
walkability[6][9] = { 0, 0, 0, 0 }
walkability[6][10] = { 0, 0, 0, 0 }
walkability[6][11] = { 0, 0, 0, 0 }
walkability[6][12] = { 0, 1, 0, 1 }
walkability[6][13] = { 1, 0, 1, 0 }
walkability[6][14] = { 0, 0, 0, 0 }
walkability[6][15] = { 0, 0, 0, 0 }
walkability[7] = {}
walkability[7][0] = { 1, 1, 1, 1 }
walkability[7][1] = { 1, 1, 1, 1 }
walkability[7][2] = { 0, 0, 0, 0 }
walkability[7][3] = { 0, 0, 0, 0 }
walkability[7][4] = { 0, 0, 0, 0 }
walkability[7][5] = { 0, 0, 0, 0 }
walkability[7][6] = { 0, 0, 0, 0 }
walkability[7][7] = { 0, 0, 0, 0 }
walkability[7][8] = { 0, 0, 0, 0 }
walkability[7][9] = { 0, 0, 0, 0 }
walkability[7][10] = { 0, 0, 0, 0 }
walkability[7][11] = { 0, 0, 0, 0 }
walkability[7][12] = { 0, 1, 0, 1 }
walkability[7][13] = { 1, 0, 1, 0 }
walkability[7][14] = { 0, 0, 0, 0 }
walkability[7][15] = { 0, 0, 0, 0 }
walkability[8] = {}
walkability[8][0] = { 1, 1, 1, 1 }
walkability[8][1] = { 1, 1, 1, 1 }
walkability[8][2] = { 0, 0, 0, 0 }
walkability[8][3] = { 0, 0, 0, 0 }
walkability[8][4] = { 0, 0, 0, 0 }
walkability[8][5] = { 0, 0, 0, 0 }
walkability[8][6] = { 0, 0, 0, 0 }
walkability[8][7] = { 0, 0, 0, 0 }
walkability[8][8] = { 0, 0, 0, 0 }
walkability[8][9] = { 0, 0, 0, 0 }
walkability[8][10] = { 0, 0, 0, 0 }
walkability[8][11] = { 0, 0, 0, 0 }
walkability[8][12] = { 0, 1, 0, 1 }
walkability[8][13] = { 1, 0, 1, 0 }
walkability[8][14] = { 0, 0, 0, 0 }
walkability[8][15] = { 0, 0, 0, 0 }
walkability[9] = {}
walkability[9][0] = { 1, 1, 1, 1 }
walkability[9][1] = { 1, 1, 1, 1 }
walkability[9][2] = { 0, 0, 0, 0 }
walkability[9][3] = { 0, 0, 0, 0 }
walkability[9][4] = { 0, 0, 0, 0 }
walkability[9][5] = { 0, 0, 0, 0 }
walkability[9][6] = { 0, 0, 0, 0 }
walkability[9][7] = { 0, 0, 0, 0 }
walkability[9][8] = { 0, 0, 0, 0 }
walkability[9][9] = { 0, 0, 0, 0 }
walkability[9][10] = { 0, 0, 0, 0 }
walkability[9][11] = { 0, 0, 0, 0 }
walkability[9][12] = { 0, 1, 0, 1 }
walkability[9][13] = { 1, 0, 1, 0 }
walkability[9][14] = { 0, 0, 0, 0 }
walkability[9][15] = { 0, 0, 0, 0 }
walkability[10] = {}
walkability[10][0] = { 1, 1, 1, 1 }
walkability[10][1] = { 1, 1, 1, 1 }
walkability[10][2] = { 1, 1, 1, 1 }
walkability[10][3] = { 1, 1, 1, 1 }
walkability[10][4] = { 0, 0, 0, 0 }
walkability[10][5] = { 0, 0, 0, 0 }
walkability[10][6] = { 1, 1, 1, 1 }
walkability[10][7] = { 1, 1, 1, 1 }
walkability[10][8] = { 1, 1, 1, 1 }
walkability[10][9] = { 1, 1, 1, 1 }
walkability[10][10] = { 1, 1, 1, 1 }
walkability[10][11] = { 1, 1, 1, 1 }
walkability[10][12] = { 1, 1, 1, 1 }
walkability[10][13] = { 1, 0, 1, 0 }
walkability[10][14] = { 0, 0, 0, 0 }
walkability[10][15] = { 0, 0, 0, 0 }
walkability[11] = {}
walkability[11][0] = { 1, 1, 1, 1 }
walkability[11][1] = { 0, 0, 0, 0 }
walkability[11][2] = { 0, 0, 0, 0 }
walkability[11][3] = { 0, 0, 0, 0 }
walkability[11][4] = { 0, 0, 0, 0 }
walkability[11][5] = { 0, 0, 0, 0 }
walkability[11][6] = { 0, 0, 0, 0 }
walkability[11][7] = { 0, 0, 0, 0 }
walkability[11][8] = { 0, 0, 0, 0 }
walkability[11][9] = { 0, 0, 0, 0 }
walkability[11][10] = { 0, 0, 0, 0 }
walkability[11][11] = { 0, 0, 0, 0 }
walkability[11][12] = { 0, 0, 0, 0 }
walkability[11][13] = { 0, 0, 0, 0 }
walkability[11][14] = { 0, 0, 0, 0 }
walkability[11][15] = { 0, 0, 0, 0 }
walkability[12] = {}
walkability[12][0] = { 1, 1, 1, 1 }
walkability[12][1] = { 0, 0, 0, 0 }
walkability[12][2] = { 0, 0, 0, 0 }
walkability[12][3] = { 0, 0, 0, 0 }
walkability[12][4] = { 0, 0, 0, 0 }
walkability[12][5] = { 0, 0, 0, 0 }
walkability[12][6] = { 0, 0, 0, 0 }
walkability[12][7] = { 0, 0, 0, 0 }
walkability[12][8] = { 0, 0, 0, 0 }
walkability[12][9] = { 0, 0, 0, 0 }
walkability[12][10] = { 0, 0, 0, 0 }
walkability[12][11] = { 0, 0, 0, 0 }
walkability[12][12] = { 0, 0, 0, 0 }
walkability[12][13] = { 0, 0, 0, 0 }
walkability[12][14] = { 0, 0, 0, 0 }
walkability[12][15] = { 0, 0, 0, 0 }
walkability[13] = {}
walkability[13][0] = { 1, 1, 1, 1 }
walkability[13][1] = { 0, 0, 0, 0 }
walkability[13][2] = { 0, 0, 0, 0 }
walkability[13][3] = { 0, 0, 0, 0 }
walkability[13][4] = { 0, 0, 0, 0 }
walkability[13][5] = { 0, 0, 0, 0 }
walkability[13][6] = { 0, 0, 0, 0 }
walkability[13][7] = { 0, 0, 0, 0 }
walkability[13][8] = { 0, 0, 0, 0 }
walkability[13][9] = { 0, 0, 0, 0 }
walkability[13][10] = { 0, 0, 0, 0 }
walkability[13][11] = { 0, 0, 0, 0 }
walkability[13][12] = { 0, 0, 0, 0 }
walkability[13][13] = { 0, 0, 0, 0 }
walkability[13][14] = { 0, 0, 0, 0 }
walkability[13][15] = { 0, 0, 0, 0 }
walkability[14] = {}
walkability[14][0] = { 0, 0, 0, 0 }
walkability[14][1] = { 0, 0, 0, 0 }
walkability[14][2] = { 0, 0, 0, 0 }
walkability[14][3] = { 0, 0, 0, 0 }
walkability[14][4] = { 0, 0, 0, 0 }
walkability[14][5] = { 0, 0, 0, 0 }
walkability[14][6] = { 0, 0, 0, 0 }
walkability[14][7] = { 0, 0, 0, 0 }
walkability[14][8] = { 0, 0, 0, 0 }
walkability[14][9] = { 0, 0, 0, 0 }
walkability[14][10] = { 0, 0, 0, 0 }
walkability[14][11] = { 0, 0, 0, 0 }
walkability[14][12] = { 0, 0, 0, 0 }
walkability[14][13] = { 0, 0, 0, 0 }
walkability[14][14] = { 0, 0, 0, 0 }
walkability[14][15] = { 0, 0, 0, 0 }
walkability[15] = {}
walkability[15][0] = { 0, 0, 0, 0 }
walkability[15][1] = { 0, 0, 0, 0 }
walkability[15][2] = { 0, 0, 0, 0 }
walkability[15][3] = { 0, 0, 0, 0 }
walkability[15][4] = { 0, 0, 0, 0 }
walkability[15][5] = { 0, 0, 0, 0 }
walkability[15][6] = { 0, 0, 0, 0 }
walkability[15][7] = { 0, 0, 0, 0 }
walkability[15][8] = { 0, 0, 0, 0 }
walkability[15][9] = { 0, 0, 0, 0 }
walkability[15][10] = { 0, 0, 0, 0 }
walkability[15][11] = { 0, 0, 0, 0 }
walkability[15][12] = { 0, 0, 0, 0 }
walkability[15][13] = { 0, 0, 0, 0 }
walkability[15][14] = { 0, 0, 0, 0 }
walkability[15][15] = { 0, 0, 0, 0 }
| gpl-2.0 |
grimreaper/ValyriaTear | dat/tilesets/mountain_landscape.lua | 2 | 10238 | local ns = {};
setmetatable(ns, {__index = _G});
mountain_landscape = ns;
setfenv(1, ns);
file_name = "dat/tilesets/mountain_landscape.lua"
image = "img/tilesets/mountain_landscape.png"
num_tile_cols = 16
num_tile_rows = 16
autotiling = {}
autotiling[10] = "CrackedEarth"
autotiling[14] = "Pavers"
autotiling[15] = "Pavers"
autotiling[26] = "CrackedEarth"
autotiling[30] = "Pavers"
autotiling[31] = "Pavers"
autotiling[42] = "CrackedEarth"
autotiling[76] = "Pavers"
autotiling[78] = "Grass"
autotiling[79] = "Grass"
autotiling[94] = "Grass"
autotiling[95] = "Grass"
-- The general walkability of the tiles in the tileset. Zero indicates walkable. One tile has four walkable quadrants listed as: NW corner, NE corner, SW corner, SE corner.
walkability = {}
walkability[0] = {}
walkability[0][0] = { 0, 0, 0, 0 }
walkability[0][1] = { 0, 0, 0, 1 }
walkability[0][2] = { 0, 0, 1, 1 }
walkability[0][3] = { 0, 0, 1, 1 }
walkability[0][4] = { 0, 0, 1, 1 }
walkability[0][5] = { 0, 0, 0, 0 }
walkability[0][6] = { 0, 0, 0, 0 }
walkability[0][7] = { 0, 0, 0, 1 }
walkability[0][8] = { 0, 0, 1, 1 }
walkability[0][9] = { 0, 0, 0, 0 }
walkability[0][10] = { 0, 0, 0, 0 }
walkability[0][11] = { 0, 0, 0, 0 }
walkability[0][12] = { 0, 0, 0, 0 }
walkability[0][13] = { 0, 0, 0, 0 }
walkability[0][14] = { 0, 0, 0, 0 }
walkability[0][15] = { 0, 0, 0, 0 }
walkability[1] = {}
walkability[1][0] = { 0, 0, 0, 1 }
walkability[1][1] = { 1, 1, 1, 0 }
walkability[1][2] = { 0, 0, 0, 0 }
walkability[1][3] = { 0, 0, 0, 0 }
walkability[1][4] = { 0, 1, 0, 0 }
walkability[1][5] = { 0, 0, 1, 0 }
walkability[1][6] = { 0, 1, 1, 1 }
walkability[1][7] = { 1, 1, 0, 0 }
walkability[1][8] = { 0, 1, 0, 0 }
walkability[1][9] = { 1, 1, 1, 1 }
walkability[1][10] = { 0, 0, 0, 0 }
walkability[1][11] = { 0, 0, 0, 0 }
walkability[1][12] = { 0, 0, 0, 0 }
walkability[1][13] = { 0, 0, 0, 0 }
walkability[1][14] = { 0, 0, 0, 0 }
walkability[1][15] = { 0, 0, 0, 0 }
walkability[2] = {}
walkability[2][0] = { 0, 1, 0, 1 }
walkability[2][1] = { 0, 0, 0, 0 }
walkability[2][2] = { 0, 0, 0, 0 }
walkability[2][3] = { 0, 0, 0, 0 }
walkability[2][4] = { 0, 0, 0, 0 }
walkability[2][5] = { 1, 0, 1, 0 }
walkability[2][6] = { 0, 0, 0, 0 }
walkability[2][7] = { 0, 0, 0, 0 }
walkability[2][8] = { 0, 0, 0, 0 }
walkability[2][9] = { 0, 0, 0, 0 }
walkability[2][10] = { 0, 0, 0, 0 }
walkability[2][11] = { 0, 0, 0, 0 }
walkability[2][12] = { 0, 0, 0, 0 }
walkability[2][13] = { 0, 0, 0, 0 }
walkability[2][14] = { 0, 0, 0, 0 }
walkability[2][15] = { 0, 0, 0, 0 }
walkability[3] = {}
walkability[3][0] = { 0, 1, 0, 1 }
walkability[3][1] = { 0, 0, 0, 0 }
walkability[3][2] = { 0, 0, 0, 0 }
walkability[3][3] = { 0, 0, 0, 0 }
walkability[3][4] = { 0, 0, 0, 0 }
walkability[3][5] = { 1, 0, 1, 0 }
walkability[3][6] = { 0, 0, 0, 0 }
walkability[3][7] = { 0, 0, 0, 0 }
walkability[3][8] = { 0, 0, 0, 0 }
walkability[3][9] = { 0, 0, 0, 0 }
walkability[3][10] = { 0, 0, 0, 0 }
walkability[3][11] = { 0, 0, 0, 0 }
walkability[3][12] = { 0, 0, 0, 0 }
walkability[3][13] = { 0, 0, 0, 0 }
walkability[3][14] = { 0, 0, 0, 0 }
walkability[3][15] = { 0, 0, 0, 0 }
walkability[4] = {}
walkability[4][0] = { 0, 1, 0, 1 }
walkability[4][1] = { 0, 0, 1, 1 }
walkability[4][2] = { 0, 0, 0, 0 }
walkability[4][3] = { 0, 0, 0, 0 }
walkability[4][4] = { 0, 1, 1, 1 }
walkability[4][5] = { 1, 0, 1, 0 }
walkability[4][6] = { 1, 0, 1, 1 }
walkability[4][7] = { 0, 0, 1, 1 }
walkability[4][8] = { 0, 0, 1, 1 }
walkability[4][9] = { 0, 1, 1, 1 }
walkability[4][10] = { 0, 0, 0, 0 }
walkability[4][11] = { 0, 0, 0, 0 }
walkability[4][12] = { 0, 0, 0, 0 }
walkability[4][13] = { 0, 0, 0, 0 }
walkability[4][14] = { 0, 0, 0, 0 }
walkability[4][15] = { 0, 0, 0, 0 }
walkability[5] = {}
walkability[5][0] = { 0, 1, 0, 1 }
walkability[5][1] = { 1, 1, 1, 1 }
walkability[5][2] = { 1, 1, 1, 1 }
walkability[5][3] = { 1, 1, 1, 1 }
walkability[5][4] = { 1, 1, 1, 1 }
walkability[5][5] = { 1, 0, 0, 0 }
walkability[5][6] = { 1, 1, 1, 1 }
walkability[5][7] = { 1, 1, 1, 1 }
walkability[5][8] = { 1, 1, 1, 1 }
walkability[5][9] = { 1, 1, 1, 1 }
walkability[5][10] = { 0, 0, 0, 0 }
walkability[5][11] = { 0, 0, 0, 0 }
walkability[5][12] = { 0, 0, 0, 0 }
walkability[5][13] = { 0, 0, 0, 0 }
walkability[5][14] = { 0, 0, 0, 0 }
walkability[5][15] = { 0, 0, 0, 0 }
walkability[6] = {}
walkability[6][0] = { 0, 1, 0, 0 }
walkability[6][1] = { 1, 1, 1, 1 }
walkability[6][2] = { 1, 1, 1, 1 }
walkability[6][3] = { 1, 1, 1, 1 }
walkability[6][4] = { 1, 1, 1, 1 }
walkability[6][5] = { 0, 0, 0, 0 }
walkability[6][6] = { 0, 1, 0, 0 }
walkability[6][7] = { 1, 1, 1, 1 }
walkability[6][8] = { 1, 1, 1, 1 }
walkability[6][9] = { 0, 0, 0, 0 }
walkability[6][10] = { 0, 0, 0, 0 }
walkability[6][11] = { 0, 0, 0, 0 }
walkability[6][12] = { 0, 0, 0, 0 }
walkability[6][13] = { 0, 0, 0, 0 }
walkability[6][14] = { 0, 0, 0, 0 }
walkability[6][15] = { 0, 0, 0, 0 }
walkability[7] = {}
walkability[7][0] = { 1, 1, 1, 0 }
walkability[7][1] = { 0, 0, 0, 0 }
walkability[7][2] = { 0, 0, 0, 0 }
walkability[7][3] = { 1, 1, 0, 1 }
walkability[7][4] = { 0, 0, 0, 0 }
walkability[7][5] = { 0, 0, 0, 0 }
walkability[7][6] = { 0, 0, 0, 0 }
walkability[7][7] = { 0, 0, 0, 0 }
walkability[7][8] = { 0, 0, 0, 0 }
walkability[7][9] = { 0, 0, 0, 0 }
walkability[7][10] = { 0, 0, 0, 0 }
walkability[7][11] = { 0, 0, 0, 0 }
walkability[7][12] = { 0, 0, 0, 0 }
walkability[7][13] = { 0, 0, 0, 0 }
walkability[7][14] = { 0, 0, 0, 0 }
walkability[7][15] = { 0, 0, 0, 0 }
walkability[8] = {}
walkability[8][0] = { 0, 0, 0, 0 }
walkability[8][1] = { 0, 0, 0, 0 }
walkability[8][2] = { 0, 0, 0, 0 }
walkability[8][3] = { 0, 0, 0, 0 }
walkability[8][4] = { 0, 0, 0, 0 }
walkability[8][5] = { 0, 0, 0, 0 }
walkability[8][6] = { 0, 0, 0, 0 }
walkability[8][7] = { 0, 0, 0, 0 }
walkability[8][8] = { 0, 0, 0, 0 }
walkability[8][9] = { 0, 0, 0, 0 }
walkability[8][10] = { 0, 0, 0, 0 }
walkability[8][11] = { 0, 0, 0, 0 }
walkability[8][12] = { 0, 0, 0, 0 }
walkability[8][13] = { 0, 0, 0, 0 }
walkability[8][14] = { 0, 0, 0, 0 }
walkability[8][15] = { 0, 0, 0, 0 }
walkability[9] = {}
walkability[9][0] = { 0, 0, 0, 0 }
walkability[9][1] = { 0, 0, 0, 0 }
walkability[9][2] = { 0, 0, 0, 0 }
walkability[9][3] = { 0, 0, 0, 0 }
walkability[9][4] = { 0, 0, 0, 0 }
walkability[9][5] = { 0, 0, 0, 0 }
walkability[9][6] = { 0, 0, 0, 0 }
walkability[9][7] = { 0, 0, 0, 0 }
walkability[9][8] = { 0, 0, 0, 0 }
walkability[9][9] = { 0, 0, 0, 0 }
walkability[9][10] = { 0, 0, 0, 0 }
walkability[9][11] = { 0, 0, 0, 0 }
walkability[9][12] = { 0, 0, 0, 0 }
walkability[9][13] = { 0, 0, 0, 0 }
walkability[9][14] = { 0, 0, 0, 0 }
walkability[9][15] = { 0, 0, 0, 0 }
walkability[10] = {}
walkability[10][0] = { 1, 0, 1, 1 }
walkability[10][1] = { 0, 0, 0, 0 }
walkability[10][2] = { 0, 0, 0, 0 }
walkability[10][3] = { 0, 1, 1, 1 }
walkability[10][4] = { 0, 0, 0, 0 }
walkability[10][5] = { 0, 0, 0, 0 }
walkability[10][6] = { 0, 0, 0, 0 }
walkability[10][7] = { 0, 0, 1, 1 }
walkability[10][8] = { 0, 0, 0, 0 }
walkability[10][9] = { 0, 0, 0, 0 }
walkability[10][10] = { 0, 0, 0, 0 }
walkability[10][11] = { 0, 0, 0, 0 }
walkability[10][12] = { 0, 0, 0, 0 }
walkability[10][13] = { 0, 0, 0, 0 }
walkability[10][14] = { 1, 1, 1, 1 }
walkability[10][15] = { 1, 1, 1, 1 }
walkability[11] = {}
walkability[11][0] = { 1, 1, 1, 1 }
walkability[11][1] = { 0, 0, 0, 0 }
walkability[11][2] = { 0, 0, 0, 0 }
walkability[11][3] = { 1, 1, 1, 1 }
walkability[11][4] = { 0, 0, 0, 0 }
walkability[11][5] = { 0, 0, 0, 0 }
walkability[11][6] = { 0, 0, 0, 0 }
walkability[11][7] = { 0, 0, 0, 0 }
walkability[11][8] = { 0, 0, 0, 0 }
walkability[11][9] = { 0, 0, 0, 0 }
walkability[11][10] = { 0, 0, 0, 0 }
walkability[11][11] = { 0, 0, 0, 0 }
walkability[11][12] = { 0, 0, 0, 0 }
walkability[11][13] = { 0, 0, 0, 0 }
walkability[11][14] = { 1, 1, 1, 0 }
walkability[11][15] = { 1, 1, 0, 1 }
walkability[12] = {}
walkability[12][0] = { 1, 0, 1, 1 }
walkability[12][1] = { 0, 0, 0, 0 }
walkability[12][2] = { 0, 0, 0, 0 }
walkability[12][3] = { 0, 1, 1, 1 }
walkability[12][4] = { 0, 0, 0, 0 }
walkability[12][5] = { 0, 0, 0, 0 }
walkability[12][6] = { 0, 0, 0, 0 }
walkability[12][7] = { 0, 0, 0, 0 }
walkability[12][8] = { 0, 0, 0, 0 }
walkability[12][9] = { 0, 0, 0, 0 }
walkability[12][10] = { 0, 0, 0, 0 }
walkability[12][11] = { 0, 0, 1, 1 }
walkability[12][12] = { 0, 0, 0, 0 }
walkability[12][13] = { 0, 0, 1, 1 }
walkability[12][14] = { 0, 0, 0, 0 }
walkability[12][15] = { 0, 0, 0, 0 }
walkability[13] = {}
walkability[13][0] = { 1, 1, 1, 1 }
walkability[13][1] = { 1, 0, 1, 1 }
walkability[13][2] = { 0, 1, 1, 1 }
walkability[13][3] = { 1, 1, 1, 1 }
walkability[13][4] = { 0, 0, 0, 0 }
walkability[13][5] = { 0, 0, 0, 0 }
walkability[13][6] = { 0, 0, 0, 0 }
walkability[13][7] = { 0, 0, 0, 0 }
walkability[13][8] = { 0, 0, 0, 0 }
walkability[13][9] = { 0, 0, 0, 0 }
walkability[13][10] = { 0, 0, 0, 0 }
walkability[13][11] = { 1, 1, 1, 1 }
walkability[13][12] = { 0, 0, 0, 0 }
walkability[13][13] = { 1, 1, 1, 1 }
walkability[13][14] = { 0, 0, 0, 0 }
walkability[13][15] = { 0, 0, 0, 0 }
walkability[14] = {}
walkability[14][0] = { 0, 1, 0, 1 }
walkability[14][1] = { 1, 1, 1, 1 }
walkability[14][2] = { 1, 1, 1, 1 }
walkability[14][3] = { 1, 0, 1, 0 }
walkability[14][4] = { 1, 1, 1, 1 }
walkability[14][5] = { 1, 1, 1, 1 }
walkability[14][6] = { 1, 1, 1, 1 }
walkability[14][7] = { 0, 0, 0, 0 }
walkability[14][8] = { 0, 0, 0, 0 }
walkability[14][9] = { 0, 0, 0, 0 }
walkability[14][10] = { 0, 0, 0, 0 }
walkability[14][11] = { 0, 0, 0, 0 }
walkability[14][12] = { 1, 1, 1, 1 }
walkability[14][13] = { 0, 0, 0, 0 }
walkability[14][14] = { 0, 0, 0, 0 }
walkability[14][15] = { 0, 0, 0, 0 }
walkability[15] = {}
walkability[15][0] = { 0, 1, 0, 1 }
walkability[15][1] = { 1, 1, 1, 1 }
walkability[15][2] = { 1, 1, 1, 1 }
walkability[15][3] = { 0, 0, 0, 0 }
walkability[15][4] = { 1, 1, 0, 1 }
walkability[15][5] = { 1, 1, 1, 1 }
walkability[15][6] = { 1, 1, 1, 0 }
walkability[15][7] = { 1, 1, 1, 1 }
walkability[15][8] = { 1, 1, 1, 1 }
walkability[15][9] = { 1, 1, 1, 1 }
walkability[15][10] = { 1, 1, 1, 1 }
walkability[15][11] = { 1, 1, 1, 1 }
walkability[15][12] = { 1, 1, 1, 1 }
walkability[15][13] = { 1, 1, 1, 1 }
walkability[15][14] = { 0, 1, 0, 1 }
walkability[15][15] = { 1, 0, 1, 0 }
| gpl-2.0 |
hleuwer/luayats | yats/compat.lua | 7 | 4074 | -------------------------------------------------------------------
-- Real globals
-- _ALERT
-- _ERRORMESSAGE
-- _VERSION
-- _G
-- assert
-- error
-- metatable
-- next
-- print
-- require
-- tonumber
-- tostring
-- type
-- unpack
-------------------------------------------------------------------
-- collectgarbage
-- gcinfo
-- globals
-- call -> protect(f, err)
-- loadfile
-- loadstring
-- rawget
-- rawset
-- getargs = Main.getargs ??
function do_ (f, err)
if not f then print(err); return end
local a,b = pcall(f)
if not a then print(b); return nil
else return b or true
end
end
function dostring(s) return do_(loadstring(s)) end
-- function dofile(s) return do_(loadfile(s)) end
-------------------------------------------------------------------
-- Table library
local tab = table
foreach = tab.foreach
foreachi = tab.foreachi
getn = tab.getn
tinsert = tab.insert
tremove = tab.remove
sort = tab.sort
-------------------------------------------------------------------
-- Debug library
local dbg = debug
getinfo = dbg.getinfo
getlocal = dbg.getlocal
setcallhook = function () error"`setcallhook' is deprecated" end
setlinehook = function () error"`setlinehook' is deprecated" end
setlocal = dbg.setlocal
-------------------------------------------------------------------
-- math library
local math = math
abs = math.abs
acos = function (x) return math.deg(math.acos(x)) end
asin = function (x) return math.deg(math.asin(x)) end
atan = function (x) return math.deg(math.atan(x)) end
atan2 = function (x,y) return math.deg(math.atan2(x,y)) end
ceil = math.ceil
cos = function (x) return math.cos(math.rad(x)) end
deg = math.deg
exp = math.exp
floor = math.floor
frexp = math.frexp
ldexp = math.ldexp
log = math.log
log10 = math.log10
max = math.max
min = math.min
mod = math.mod
PI = math.pi
--??? pow = math.pow
rad = math.rad
random = math.random
randomseed = math.randomseed
sin = function (x) return math.sin(math.rad(x)) end
sqrt = math.sqrt
tan = function (x) return math.tan(math.rad(x)) end
-------------------------------------------------------------------
-- string library
local str = string
strbyte = str.byte
strchar = str.char
strfind = str.find
format = str.format
gsub = str.gsub
strlen = str.len
strlower = str.lower
strrep = str.rep
strsub = str.sub
strupper = str.upper
-------------------------------------------------------------------
-- os library
clock = os.clock
date = os.date
difftime = os.difftime
execute = os.execute --?
exit = os.exit
getenv = os.getenv
remove = os.remove
rename = os.rename
setlocale = os.setlocale
time = os.time
tmpname = os.tmpname
-------------------------------------------------------------------
-- compatibility only
getglobal = function (n) return _G[n] end
setglobal = function (n,v) _G[n] = v end
-------------------------------------------------------------------
local io, tab = io, table
-- IO library (files)
_STDIN = io.stdin
_STDERR = io.stderr
_STDOUT = io.stdout
_INPUT = io.stdin
_OUTPUT = io.stdout
seek = io.stdin.seek -- sick ;-)
tmpfile = io.tmpfile
closefile = io.close
openfile = io.open
function flush (f)
if f then f:flush()
else _OUTPUT:flush()
end
end
function readfrom (name)
if name == nil then
local f, err, cod = io.close(_INPUT)
_INPUT = io.stdin
return f, err, cod
else
local f, err, cod = io.open(name, "r")
_INPUT = f or _INPUT
return f, err, cod
end
end
function writeto (name)
if name == nil then
local f, err, cod = io.close(_OUTPUT)
_OUTPUT = io.stdout
return f, err, cod
else
local f, err, cod = io.open(name, "w")
_OUTPUT = f or _OUTPUT
return f, err, cod
end
end
function appendto (name)
local f, err, cod = io.open(name, "a")
_OUTPUT = f or _OUTPUT
return f, err, cod
end
function read (...)
local f = _INPUT
if type(arg[1]) == 'userdata' then
f = tab.remove(arg, 1)
end
return f:read(unpack(arg))
end
function write (...)
local f = _OUTPUT
if type(arg[1]) == 'userdata' then
f = tab.remove(arg, 1)
end
return f:write(unpack(arg))
end
| gpl-2.0 |
bigdogmat/wire | lua/wire/server/debuggerlib.lua | 15 | 5802 | local formatPort = {}
WireLib.Debugger = { formatPort = formatPort } -- Make it global
function formatPort.NORMAL(value)
return string.format("%.3f",value)
end
function formatPort.STRING(value)
return '"' .. value .. '"'
end
function formatPort.VECTOR(value)
return string.format("(%.1f,%.1f,%.1f)", value[1], value[2], value[3])
end
function formatPort.ANGLE(value)
return string.format("(%.1f,%.1f,%.1f)", value.p, value.y, value.r)
end
formatPort.ENTITY = function(ent)
if not IsValid(ent) then return "(null)" end
return tostring(ent)
end
formatPort.BONE = e2_tostring_bone
function formatPort.MATRIX(value)
local RetText = "[11="..value[1]..",12="..value[2]..",13="..value[3]
RetText = RetText..",21="..value[4]..",22="..value[5]..",23="..value[6]
RetText = RetText..",31="..value[7]..",32="..value[8]..",33="..value[9].."]"
return RetText
end
function formatPort.MATRIX2(value)
local RetText = "[11="..value[1]..",12="..value[2]
RetText = RetText..",21="..value[3]..",22="..value[4].."]"
return RetText
end
function formatPort.MATRIX4(value)
local RetText = "[11="..value[1]..",12="..value[2]..",13="..value[3]..",14="..value[4]
RetText = RetText..",21="..value[5]..",22="..value[6]..",23="..value[7]..",24="..value[8]
RetText = RetText..",31="..value[9]..",32="..value[10]..",33="..value[11]..",34="..value[12]
RetText = RetText..",41="..value[13]..",42="..value[14]..",43="..value[15]..",44="..value[16].."]"
return RetText
end
function formatPort.RANGER(value) return "ranger" end
function formatPort.ARRAY(value, OrientVertical)
local RetText = ""
local ElementCount = 0
for Index, Element in ipairs(value) do
ElementCount = ElementCount+1
if(ElementCount > 10) then
break
end
RetText = RetText..Index.."="
--Check for array element type
if isnumber(Element) then --number
RetText = RetText..formatPort.NORMAL(Element)
elseif((istable(Element) and #Element == 3) or isvector(Element)) then --vector
RetText = RetText..formatPort.VECTOR(Element)
elseif(istable(Element) and #Element == 2) then --vector2
RetText = RetText..formatPort.VECTOR2(Element)
elseif(istable(Element) and #Element == 4) then --vector4
RetText = RetText..formatPort.VECTOR4(Element)
elseif((istable(Element) and #Element == 3) or isangle(Element)) then --angle
if(isangle(Element)) then
RetText = RetText..formatPort.ANGLE(Element)
else
RetText = RetText.."(" .. math.Round(Element[1],1) .. "," .. math.Round(Element[2],1) .. "," .. math.Round(Element[3],1) .. ")"
end
elseif(istable(Element) and #Element == 9) then --matrix
RetText = RetText..formatPort.MATRIX(Element)
elseif(istable(Element) and #Element == 16) then --matrix4
RetText = RetText..formatPort.MATRIX4(Element)
elseif(isstring(Element)) then --string
RetText = RetText..formatPort.STRING(Element)
elseif(isentity(Element)) then --entity
RetText = RetText..formatPort.ENTITY(Element)
elseif(type(Element) == "Player") then --player
RetText = RetText..tostring(Element)
elseif(type(Element) == "Weapon") then --weapon
RetText = RetText..tostring(Element)..Element:GetClass()
elseif(type(Element) == "PhysObj" and e2_tostring_bone(Element) != "(null)") then --Bone
RetText = RetText..formatPort.BONE(Element)
else
RetText = RetText.."No Display for "..type(Element)
end
--TODO: add matrix 2
if OrientVertical then
RetText = RetText..",\n"
else
RetText = RetText..", "
end
end
RetText = string.sub(RetText,1,-3)
return "{"..RetText.."}"
end
function formatPort.TABLE(value, OrientVertical)
local RetText = ""
local ElementCount = 0
for Index, Element in pairs(value) do
ElementCount = ElementCount+1
if(ElementCount > 7) then
break
end
local long_typeid = string.sub(Index,1,1) == "x"
local typeid = string.sub(Index,1,long_typeid and 3 or 1)
local IdxID = string.sub(Index,(long_typeid and 3 or 1)+1)
RetText = RetText..IdxID.."="
--Check for array element type
if(typeid == "n") then --number
RetText = RetText..formatPort.NORMAL(Element)
elseif(istable(Element) and #Element == 3) or isvector(Element) then --vector
RetText = RetText..formatPort.VECTOR(Element)
elseif(istable(Element) and #Element == 2) then --vector2
RetText = RetText..formatPort.VECTOR2(Element)
elseif(istable(Element) and #Element == 4 and typeid == "v4") then --vector4
RetText = RetText..formatPort.VECTOR4(Element)
elseif(istable(Element) and #Element == 3) or isangle(Element) then --angle
if isangle(Element) then
RetText = RetText..formatPort.ANGLE(Element)
else
RetText = RetText.."(" .. math.Round(Element[1]*10)/10 .. "," .. math.Round(Element[2]*10)/10 .. "," .. math.Round(Element[3]*10)/10 .. ")"
end
elseif(istable(Element) and #Element == 9) then --matrix
RetText = RetText..formatPort.MATRIX(Element)
elseif(istable(Element) and #Element == 16) then --matrix4
RetText = RetText..formatPort.MATRIX4(Element)
elseif(typeid == "s") then --string
RetText = RetText..formatPort.STRING(Element)
elseif(isentity(Element) and typeid == "e") then --entity
RetText = RetText..formatPort.ENTITY(Element)
elseif(type(Element) == "Player") then --player
RetText = RetText..tostring(Element)
elseif(type(Element) == "Weapon") then --weapon
RetText = RetText..tostring(Element)..Element:GetClass()
elseif(typeid == "b") then
RetText = RetText..formatPort.BONE(Element)
else
RetText = RetText.."No Display for "..type(Element)
end
--TODO: add matrix 2
if OrientVertical then
RetText = RetText..",\n"
else
RetText = RetText..", "
end
end
RetText = string.sub(RetText,1,-3)
return "{"..RetText.."}"
end
function WireLib.registerDebuggerFormat(typename, func)
formatPort[typename:upper()] = func
end
| apache-2.0 |
kracwarlock/dp | data/mnist.lua | 1 | 5407 | ------------------------------------------------------------------------
--[[ Mnist ]]--
-- http://yann.lecun.com/exdb/mnist/
-- A simple but widely used handwritten digits classification problem.
------------------------------------------------------------------------
local Mnist, DataSource = torch.class("dp.Mnist", "dp.DataSource")
Mnist.isMnist = true
Mnist._name = 'mnist'
Mnist._image_size = {28, 28, 1}
Mnist._image_axes = 'bhwc'
Mnist._feature_size = 1*28*28
Mnist._classes = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
function Mnist:__init(config)
config = config or {}
assert(torch.type(config) == 'table' and not config[1],
"Constructor requires key-value arguments")
local args, load_all, input_preprocess, target_preprocess
args, self._valid_ratio, self._train_file, self._test_file,
self._data_path, self._scale, self._binarize, self._shuffle,
self._download_url, load_all, input_preprocess,
target_preprocess
= xlua.unpack(
{config},
'Mnist',
'Handwritten digit classification problem.' ..
'Note: Train and valid sets are already shuffled.',
{arg='valid_ratio', type='number', default=1/6,
help='proportion of training set to use for cross-validation.'},
{arg='train_file', type='string', default='train.th7',
help='name of training file'},
{arg='test_file', type='string', default='test.th7',
help='name of test file'},
{arg='data_path', type='string', default=dp.DATA_DIR,
help='path to data repository'},
{arg='scale', type='table',
help='bounds to scale the values between. [Default={0,1}]'},
{arg='binarize', type='boolean',
help='binarize the inputs (0s and 1s)', default=false},
{arg='shuffle', type='boolean',
help='shuffle different sets', default=false},
{arg='download_url', type='string',
default='https://stife076.files.wordpress.com/2015/02/mnist4.zip',
help='URL from which to download dataset if not found on disk.'},
{arg='load_all', type='boolean',
help='Load all datasets : train, valid, test.', default=true},
{arg='input_preprocess', type='table | dp.Preprocess',
help='to be performed on set inputs, measuring statistics ' ..
'(fitting) on the train_set only, and reusing these to ' ..
'preprocess the valid_set and test_set.'},
{arg='target_preprocess', type='table | dp.Preprocess',
help='to be performed on set targets, measuring statistics ' ..
'(fitting) on the train_set only, and reusing these to ' ..
'preprocess the valid_set and test_set.'}
)
if (self._scale == nil) then
self._scale = {0,1}
end
if load_all then
self:loadTrainValid()
self:loadTest()
end
DataSource.__init(self, {
train_set=self:trainSet(), valid_set=self:validSet(),
test_set=self:testSet(), input_preprocess=input_preprocess,
target_preprocess=target_preprocess
})
end
function Mnist:loadTrainValid()
--Data will contain a tensor where each row is an example, and where
--the last column contains the target class.
local data = self:loadData(self._train_file, self._download_url)
-- train
local start = 1
local size = math.floor(data[1]:size(1)*(1-self._valid_ratio))
self:setTrainSet(
self:createDataSet(
data[1]:narrow(1, start, size), data[2]:narrow(1, start, size),
'train'
)
)
-- valid
if self._valid_ratio == 0 then
print"Warning : No Valid Set due to valid_ratio == 0"
return
end
start = size
size = data[1]:size(1)-start
self:setValidSet(
self:createDataSet(
data[1]:narrow(1, start, size), data[2]:narrow(1, start, size),
'valid'
)
)
return self:trainSet(), self:validSet()
end
function Mnist:loadTest()
local test_data = self:loadData(self._test_file, self._download_url)
self:setTestSet(
self:createDataSet(test_data[1], test_data[2], 'test')
)
return self:testSet()
end
--Creates an Mnist Dataset out of inputs, targets and which_set
function Mnist:createDataSet(inputs, targets, which_set)
if self._shuffle then
local indices = torch.randperm(inputs:size(1)):long()
inputs = inputs:index(1, indices)
targets = targets:index(1, indices)
end
if self._binarize then
DataSource.binarize(inputs, 128)
end
if self._scale and not self._binarize then
DataSource.rescale(inputs, self._scale[1], self._scale[2])
end
-- class 0 will have index 1, class 1 index 2, and so on.
targets:add(1)
-- construct inputs and targets dp.Views
local input_v, target_v = dp.ImageView(), dp.ClassView()
input_v:forward(self._image_axes, inputs)
target_v:forward('b', targets)
target_v:setClasses(self._classes)
-- construct dataset
local ds = dp.DataSet{inputs=input_v,targets=target_v,which_set=which_set}
ds:ioShapes('bhwc', 'b')
return ds
end
function Mnist:loadData(file_name, download_url)
local path = DataSource.getDataPath{
name=self._name, url=download_url,
decompress_file=file_name,
data_dir=self._data_path
}
-- backwards compatible with old binary format
local status, data = pcall(function() return torch.load(path, "ascii") end)
if not status then
return torch.load(path, "binary")
end
return data
end
| bsd-3-clause |
arventwei/WioEngine | Tools/jamplus/src/luaplus/Src/Modules/luaexpat/src/lxp/lom.lua | 14 | 1422 | -- See Copyright Notice in license.html
-- $Id: lom.lua,v 1.6 2005/06/09 19:18:40 tuler Exp $
local lxp = require "lxp"
local tinsert, tremove = table.insert, table.remove
local assert, type, print = assert, type, print
local function starttag (p, tag, attr)
local stack = p:getcallbacks().stack
local newelement = {tag = tag, attr = attr}
tinsert(stack, newelement)
end
local function endtag (p, tag)
local stack = p:getcallbacks().stack
local element = tremove(stack)
assert(element.tag == tag)
local level = #stack
tinsert(stack[level], element)
end
local function text (p, txt)
local stack = p:getcallbacks().stack
local element = stack[#stack]
local n = #element
if type(element[n]) == "string" then
element[n] = element[n] .. txt
else
tinsert(element, txt)
end
end
local function parse (o)
local c = { StartElement = starttag,
EndElement = endtag,
CharacterData = text,
_nonstrict = true,
stack = {{}}
}
local p = lxp.new(c)
local status, err
if type(o) == "string" then
status, err = p:parse(o)
if not status then return nil, err end
else
for l in pairs(o) do
status, err = p:parse(l)
if not status then return nil, err end
end
end
status, err = p:parse()
if not status then return nil, err end
p:close()
return c.stack[1][1]
end
return { parse = parse }
| mit |
cpascal/skynet | lualib/snax/loginserver.lua | 42 | 5057 | local skynet = require "skynet"
require "skynet.manager"
local socket = require "socket"
local crypt = require "crypt"
local table = table
local string = string
local assert = assert
--[[
Protocol:
line (\n) based text protocol
1. Server->Client : base64(8bytes random challenge)
2. Client->Server : base64(8bytes handshake client key)
3. Server: Gen a 8bytes handshake server key
4. Server->Client : base64(DH-Exchange(server key))
5. Server/Client secret := DH-Secret(client key/server key)
6. Client->Server : base64(HMAC(challenge, secret))
7. Client->Server : DES(secret, base64(token))
8. Server : call auth_handler(token) -> server, uid (A user defined method)
9. Server : call login_handler(server, uid, secret) ->subid (A user defined method)
10. Server->Client : 200 base64(subid)
Error Code:
400 Bad Request . challenge failed
401 Unauthorized . unauthorized by auth_handler
403 Forbidden . login_handler failed
406 Not Acceptable . already in login (disallow multi login)
Success:
200 base64(subid)
]]
local socket_error = {}
local function assert_socket(service, v, fd)
if v then
return v
else
skynet.error(string.format("%s failed: socket (fd = %d) closed", service, fd))
error(socket_error)
end
end
local function write(service, fd, text)
assert_socket(service, socket.write(fd, text), fd)
end
local function launch_slave(auth_handler)
local function auth(fd, addr)
fd = assert(tonumber(fd))
skynet.error(string.format("connect from %s (fd = %d)", addr, fd))
socket.start(fd)
-- set socket buffer limit (8K)
-- If the attacker send large package, close the socket
socket.limit(fd, 8192)
local challenge = crypt.randomkey()
write("auth", fd, crypt.base64encode(challenge).."\n")
local handshake = assert_socket("auth", socket.readline(fd), fd)
local clientkey = crypt.base64decode(handshake)
if #clientkey ~= 8 then
error "Invalid client key"
end
local serverkey = crypt.randomkey()
write("auth", fd, crypt.base64encode(crypt.dhexchange(serverkey)).."\n")
local secret = crypt.dhsecret(clientkey, serverkey)
local response = assert_socket("auth", socket.readline(fd), fd)
local hmac = crypt.hmac64(challenge, secret)
if hmac ~= crypt.base64decode(response) then
write("auth", fd, "400 Bad Request\n")
error "challenge failed"
end
local etoken = assert_socket("auth", socket.readline(fd),fd)
local token = crypt.desdecode(secret, crypt.base64decode(etoken))
local ok, server, uid = pcall(auth_handler,token)
socket.abandon(fd)
return ok, server, uid, secret
end
local function ret_pack(ok, err, ...)
if ok then
skynet.ret(skynet.pack(err, ...))
else
if err == socket_error then
skynet.ret(skynet.pack(nil, "socket error"))
else
skynet.ret(skynet.pack(false, err))
end
end
end
skynet.dispatch("lua", function(_,_,...)
ret_pack(pcall(auth, ...))
end)
end
local user_login = {}
local function accept(conf, s, fd, addr)
-- call slave auth
local ok, server, uid, secret = skynet.call(s, "lua", fd, addr)
socket.start(fd)
if not ok then
if ok ~= nil then
write("response 401", fd, "401 Unauthorized\n")
end
error(server)
end
if not conf.multilogin then
if user_login[uid] then
write("response 406", fd, "406 Not Acceptable\n")
error(string.format("User %s is already login", uid))
end
user_login[uid] = true
end
local ok, err = pcall(conf.login_handler, server, uid, secret)
-- unlock login
user_login[uid] = nil
if ok then
err = err or ""
write("response 200",fd, "200 "..crypt.base64encode(err).."\n")
else
write("response 403",fd, "403 Forbidden\n")
error(err)
end
end
local function launch_master(conf)
local instance = conf.instance or 8
assert(instance > 0)
local host = conf.host or "0.0.0.0"
local port = assert(tonumber(conf.port))
local slave = {}
local balance = 1
skynet.dispatch("lua", function(_,source,command, ...)
skynet.ret(skynet.pack(conf.command_handler(command, ...)))
end)
for i=1,instance do
table.insert(slave, skynet.newservice(SERVICE_NAME))
end
skynet.error(string.format("login server listen at : %s %d", host, port))
local id = socket.listen(host, port)
socket.start(id , function(fd, addr)
local s = slave[balance]
balance = balance + 1
if balance > #slave then
balance = 1
end
local ok, err = pcall(accept, conf, s, fd, addr)
if not ok then
if err ~= socket_error then
skynet.error(string.format("invalid client (fd = %d) error = %s", fd, err))
end
socket.start(fd)
end
socket.close(fd)
end)
end
local function login(conf)
local name = "." .. (conf.name or "login")
skynet.start(function()
local loginmaster = skynet.localname(name)
if loginmaster then
local auth_handler = assert(conf.auth_handler)
launch_master = nil
conf = nil
launch_slave(auth_handler)
else
launch_slave = nil
conf.auth_handler = nil
assert(conf.login_handler)
assert(conf.command_handler)
skynet.register(name)
launch_master(conf)
end
end)
end
return login
| mit |
akalend/tarantool-sql | sql.lua | 1 | 4202 | local string = require "std.string"
function parse_insert(sql)
local s1,s2 = string.match(sql, '[iI][nN][sS][Ee][Rr][tT] [iI][nN][tT][oO] *([%d%a]+) *[Vv][Aa][lL][Uu][Ee][Ss] ?%((.+)%)')
return {s1,s2}
end
function parse_values( values )
local res = string.split(values, ",")
if type(res) ~= 'table' then
error('parse sql: values error')
end
local v
local out = {}
for _,v in ipairs(res) do
if string.byte(v,1) ~= 39 then
table.insert(out, tonumber(v))
else
v = string.sub(v, 2, string.len(v) - 2 )
table.insert(out,v)
end
end
return out
end
function parse_name(sql)
local out = {}
out ['table'] = sql.match(sql, "[fF][Rr][Oo][Mm] ([A-Za-z0-9]+)")
local where,action,value = sql.match(sql, "[wW][Hh][Ee][Rr][Ee] ([A-Za-z0-9]+) *([%=<>][%=<>]?) *(.+)")
if where then
out['where'] = where
out['value'] = value
out['it'] = action
end
return out
end
function parse_limit(where_sql)
if where_sql == nil then return {nil, nil} end
local s1,s2 = string.match(where_sql, '(.+) +[lL][Ii][mM][Ii][Tt] +(%d+)')
return {s1,s2}
end
function parse_sql( sql )
local out = parse_name(sql)
if string.match(sql, "[sS][Ee][lL][Ee][cC][tT]") then
out["action"] = 'select'
if string.match(sql, "[cC][oO][Uu][Nn][tT]%(%*%)") then
out['action'] = 'count'
end
elseif string.match(sql, "[dD][Ee][lL][Ee][tT][Ee]") then
out['action'] = 'delete'
elseif string.match(sql, "[iI][nN][sS][Ee][Rr][tT]") then
local res = parse_insert(sql)
if res[1] == nil then
error('parse sql: absent table name')
end
out = { ["table"] = res[1], ["action"] = 'insert' }
if res[2] then
out['data'] = parse_values(res[2])
else
error('parse sql: absent values')
end
else
error('parse sql, must be start with: SELECT, DELETE, UPDATE or INSERT ' )
end
if out['table'] == nil then
error('parse sql, must be set the tablename')
end
return out
end
function get_type(dataspace, index)
local index = dataspace.index[index]
if index == nil then error('invalid index name') end
return index.parts[1].type
end
function get_iterator( action )
local it = nil
if action == '=' then
it = 'EQ'
elseif action == '<' then
it = 'LT'
elseif action == '>=' then
it = 'GE'
elseif action == '>' then
it = 'GT'
elseif action == '<=' then
it = 'LE'
end
return it
end
function sql( sql )
if sql == nil then
error('query is nil')
end
local res = parse_sql(sql)
if res['action'] == nil then error('parse sql error: action is null') end
if res['table'] == nil then error('parse sql error: table is null') end
local spacename = res['table']
local dataspace = box.space[spacename]
if dataspace == nil then error('404: spacename not found') end
local action = res['action']
it = get_iterator(res['it'])
local value = res['value']
if res['action'] == 'select' then
if value == nil then
return dataspace:select()
elseif it ~= nil then
if get_type(dataspace, res['where']) == 'unsigned' then value = tonumber(value) end
local parse_res = parse_limit(value)
local limit_value = tonumber(parse_res[2])
if parse_res[2] ~= nil and limit_value > 0 then
return dataspace.index[res['where']]:select({parse_res[1]}, {iterator=it, limit=limit_value})
end
return dataspace.index[res['where']]:select({value}, {iterator=it})
end
elseif res['action'] == 'count' then
if it == nil then
return dataspace:len()
else
if res['value'] == nil then error('parse sql error: value is null') end
if get_type(dataspace, res['where']) == 'unsigned' then value = tonumber(value) end
return dataspace.index[res['where']]:count({value}, {iterator=it})
end
elseif res['action'] == 'insert' then
if type(dataspace) == 'table' then
dataspace:insert(res['data'])
else
error('exec sql: error datatype')
end
elseif res['action'] == 'delete' then
if res['value'] == nil then error('parse sql error: value is null') end
local value = res['value']
if get_type(dataspace, res['where']) == 'unsigned' then value = tonumber(value) end
return dataspace:delete{value}
elseif res['action'] == '*' then
error('ERR *******')
end
end
| mit |
dicebox/minetest-france | mods/moreblocks/redefinitions.lua | 2 | 1161 | --[[
More Blocks: redefinitions of default stuff
Copyright (c) 2011-2015 Calinou and contributors.
Licensed under the zlib license. See LICENSE.md for more information.
--]]
-- Redefinitions of some default crafting recipes:
minetest.register_craft({
output = "default:sign_wall 4",
recipe = {
{"default:wood", "default:wood", "default:wood"},
{"default:wood", "default:wood", "default:wood"},
{"", "default:stick", ""},
}
})
minetest.register_craft({
output = "default:ladder 4",
recipe = {
{"default:stick", "", "default:stick"},
{"default:stick", "default:stick", "default:stick"},
{"default:stick", "", "default:stick"},
}
})
minetest.register_craft({
output = "default:paper 4",
recipe = {
{"default:papyrus", "default:papyrus", "default:papyrus"},
}
})
minetest.register_craft({
output = "default:rail 24",
recipe = {
{"default:steel_ingot", "", "default:steel_ingot"},
{"default:steel_ingot", "default:stick", "default:steel_ingot"},
{"default:steel_ingot", "", "default:steel_ingot"},
}
})
minetest.register_craft({
type = "toolrepair",
additional_wear = -0.10, -- Tool repair buff (10% bonus instead of 2%).
})
| gpl-3.0 |
Naliwe/IntelliJ_WowAddOnSupport | resources/Wow_sdk/AceGUI-3.0/widgets/AceGUIWidget-Icon.lua | 1 | 4264 | --[[-----------------------------------------------------------------------------
Icon Widget
-------------------------------------------------------------------------------]]
local Type, Version = "Icon", 21
local AceGUI = LibStub and LibStub("AceGUI-3.0", true)
if not AceGUI or (AceGUI:GetWidgetVersion(Type) or 0) >= Version then return end
-- Lua APIs
local select, pairs, print = select, pairs, print
-- WoW APIs
local CreateFrame, UIParent = CreateFrame, UIParent
--[[-----------------------------------------------------------------------------
Scripts
-------------------------------------------------------------------------------]]
local function Control_OnEnter(frame)
frame.obj:Fire("OnEnter")
end
local function Control_OnLeave(frame)
frame.obj:Fire("OnLeave")
end
local function Button_OnClick(frame, button)
frame.obj:Fire("OnClick", button)
AceGUI:ClearFocus()
end
--[[-----------------------------------------------------------------------------
Methods
-------------------------------------------------------------------------------]]
local methods = {
["OnAcquire"] = function(self)
self:SetHeight(110)
self:SetWidth(110)
self:SetLabel()
self:SetImage(nil)
self:SetImageSize(64, 64)
self:SetDisabled(false)
end,
-- ["OnRelease"] = nil,
["SetLabel"] = function(self, text)
if text and text ~= "" then
self.label:Show()
self.label:SetText(text)
self:SetHeight(self.image:GetHeight() + 25)
else
self.label:Hide()
self:SetHeight(self.image:GetHeight() + 10)
end
end,
["SetImage"] = function(self, path, ...)
local image = self.image
image:SetTexture(path)
if image:GetTexture() then
local n = select("#", ...)
if n == 4 or n == 8 then
image:SetTexCoord(...)
else
image:SetTexCoord(0, 1, 0, 1)
end
end
end,
["SetImageSize"] = function(self, width, height)
self.image:SetWidth(width)
self.image:SetHeight(height)
--self.frame:SetWidth(width + 30)
if self.label:IsShown() then
self:SetHeight(height + 25)
else
self:SetHeight(height + 10)
end
end,
["SetDisabled"] = function(self, disabled)
self.disabled = disabled
if disabled then
self.frame:Disable()
self.label:SetTextColor(0.5, 0.5, 0.5)
self.image:SetVertexColor(0.5, 0.5, 0.5, 0.5)
else
self.frame:Enable()
self.label:SetTextColor(1, 1, 1)
self.image:SetVertexColor(1, 1, 1, 1)
end
end
}
--[[-----------------------------------------------------------------------------
Constructor
-------------------------------------------------------------------------------]]
local function Constructor()
local frame = CreateFrame("Button", nil, UIParent)
frame:Hide()
frame:EnableMouse(true)
frame:SetScript("OnEnter", Control_OnEnter)
frame:SetScript("OnLeave", Control_OnLeave)
frame:SetScript("OnClick", Button_OnClick)
local label = frame:CreateFontString(nil, "BACKGROUND", "GameFontHighlight")
label:SetPoint("BOTTOMLEFT")
label:SetPoint("BOTTOMRIGHT")
label:SetJustifyH("CENTER")
label:SetJustifyV("TOP")
label:SetHeight(18)
local image = frame:CreateTexture(nil, "BACKGROUND")
image:SetWidth(64)
image:SetHeight(64)
image:SetPoint("TOP", 0, -5)
local highlight = frame:CreateTexture(nil, "HIGHLIGHT")
highlight:SetAllPoints(image)
highlight:SetTexture("Interface\\PaperDollInfoFrame\\UI-Character-Tab-Highlight")
highlight:SetTexCoord(0, 1, 0.23, 0.77)
highlight:SetBlendMode("ADD")
local widget = {
label = label,
image = image,
frame = frame,
type = Type
}
for method, func in pairs(methods) do
widget[method] = func
end
widget.SetText = function(self, ...) print("AceGUI-3.0-Icon: SetText is deprecated! Use SetLabel instead!"); self:SetLabel(...) end
return AceGUI:RegisterAsWidget(widget)
end
AceGUI:RegisterWidgetType(Type, Constructor, Version)
| mit |
SinisterRectus/JC2MP-MazeGenerator | client/cMazeManager.lua | 1 | 1868 | class 'MazeManager'
function MazeManager:__init()
self.mazes = {}
self.triggers = {}
self.ceilings = true -- whether to construct maze ceilings
Events:Subscribe("ShapeTriggerEnter", self, self.TriggerEnter)
Events:Subscribe("ShapeTriggerExit", self, self.TriggerExit)
Events:Subscribe("WorldNetworkObjectCreate", self, self.MazeSpawn)
Events:Subscribe("WorldNetworkObjectDestroy", self, self.MazeDespawn)
Events:Subscribe("ModuleUnload", self, self.ModuleUnload)
end
function MazeManager:TriggerEnter(args)
if args.entity.__type ~= "LocalPlayer" then return end
local trigger = self.triggers[args.trigger:GetId()]
if not trigger then return end
local object = trigger.parent
if not object then return end
local name = class_info(object).name
if name == "Fire" then
Network:Send("PlayerEnterFire", {player = LocalPlayer})
elseif name == "Pickup" then -- not synced
ClientSound.Play(AssetLocation.Game, {
position = object.position,
bank_id = 19,
sound_id = 3,
variable_id_focus = 0
})
object:Remove()
end
end
function MazeManager:TriggerExit(args)
if args.entity.__type ~= "LocalPlayer" then return end
local trigger = self.triggers[args.trigger:GetId()]
if not trigger then return end
local object = trigger.parent
if not object then return end
if class_info(object).name == "Fire" then
Network:Send("PlayerExitFire", {player = LocalPlayer})
end
end
function MazeManager:MazeSpawn(args)
if args.object:GetValue("__type") ~= "Maze" then return end
Maze(args)
end
function MazeManager:MazeDespawn(args)
if args.object:GetValue("__type") ~= "Maze" then return end
local maze = self.mazes[args.object:GetId()]
if not maze then return end
maze:Remove()
end
function MazeManager:ModuleUnload()
for _, maze in pairs(self.mazes) do
maze:Remove()
end
end
MazeManager = MazeManager()
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.