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 |
|---|---|---|---|---|---|
sajjad94/ASD_KARBALA | plugins/ar-banhammer.lua | 13 | 13810 | --[[
▀▄ ▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀
▀▄ ▄▀ ▀▄ ▄▀
▀▄ ▄▀ BY SAJJAD NOORI ▀▄ ▄▀
▀▄ ▄▀ BY SAJAD NOORI (@SAJJADNOORI) ▀▄ ▄▀
▀▄ ▄▀ JUST WRITED BY SAJJAD NOORI ▀▄ ▄▀
▀▄ ▄▀ ban hammer : الطرد والحظر ▀▄ ▄▀
▀▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀
--]]
local function pre_process(msg)
local data = load_data(_config.moderation.data)
-- SERVICE MESSAGE
if msg.action and msg.action.type then
local action = msg.action.type
-- Check if banned user joins chat by link
if action == 'chat_add_user_link' then
local user_id = msg.from.id
print('Checking invited user '..user_id)
local banned = is_banned(user_id, msg.to.id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('User is banned!')
local print_name = user_print_name(msg.from):gsub("", "")
local name = print_name:gsub("_", "")
savelog(msg.to.id, name.." ["..msg.from.id.."] is banned and kicked ! ")-- Save to logs
kick_user(user_id, msg.to.id)
end
end
-- Check if banned user joins chat
if action == 'chat_add_user' then
local user_id = msg.action.user.id
print('Checking invited user '..user_id)
local banned = is_banned(user_id, msg.to.id)
if banned and not is_momod2(msg.from.id, msg.to.id) or is_gbanned(user_id) and not is_admin2(msg.from.id) then -- Check it with redis
print('User is banned!')
local print_name = user_print_name(msg.from):gsub("", "")
local name = print_name:gsub("_", "")
savelog(msg.to.id, name.." ["..msg.from.id.."] added a banned user >"..msg.action.user.id)-- Save to logs
kick_user(user_id, msg.to.id)
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
redis:incr(banhash)
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
local banaddredis = redis:get(banhash)
if banaddredis then
if tonumber(banaddredis) >= 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 3 times
end
if tonumber(banaddredis) >= 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 7 times
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
redis:set(banhash, 0)-- Reset the Counter
end
end
end
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings'] then
if data[tostring(msg.to.id)]['settings']['lock_bots'] then
bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots']
end
end
end
if msg.action.user.username ~= nil then
if string.sub(msg.action.user.username:lower(), -3) == 'bot' and not is_momod(msg) and bots_protection == "yes" then --- Will kick bots added by normal users
local print_name = user_print_name(msg.from):gsub("", "")
local name = print_name:gsub("_", "")
savelog(msg.to.id, name.." ["..msg.from.id.."] added a bot > @".. msg.action.user.username)-- Save to logs
kick_user(msg.action.user.id, msg.to.id)
end
end
end
-- No further checks
return msg
end
-- banned user is talking !
if msg.to.type == 'chat' or msg.to.type == 'channel' then
local group = msg.to.id
local texttext = 'groups'
--if not data[tostring(texttext)][tostring(msg.to.id)] and not is_realm(msg) then -- Check if this group is one of my groups or not
--chat_del_user('chat#id'..msg.to.id,'user#id'..our_id,ok_cb,false)
--return
--end
local user_id = msg.from.id
local chat_id = msg.to.id
local banned = is_banned(user_id, chat_id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('Banned user talking!')
local print_name = user_print_name(msg.from):gsub("", "")
local name = print_name:gsub("_", "")
savelog(msg.to.id, name.." ["..msg.from.id.."] banned user is talking !")-- Save to logs
kick_user(user_id, chat_id)
msg.text = ''
end
end
return msg
end
local function kick_ban_res(extra, success, result)
local chat_id = extra.chat_id
local chat_type = extra.chat_type
if chat_type == "chat" then
receiver = 'chat#id'..chat_id
else
receiver = 'channel#id'..chat_id
end
if success == 0 then
return send_large_msg(receiver, "Cannot find user by that username!")
end
local member_id = result.peer_id
local user_id = member_id
local member = result.username
local from_id = extra.from_id
local get_cmd = extra.get_cmd
if get_cmd == "دي" then
if member_id == from_id then
send_large_msg(receiver, "لا تستطيع طرد نفسك")
return
end
if is_momod2(member_id, chat_id) and not is_admin2(sender) then
send_large_msg(receiver, "لا تستطيع طرد الادمنية او المدراء")
return
end
kick_user(member_id, chat_id)
elseif get_cmd == 'حظر' then
if is_momod2(member_id, chat_id) and not is_admin2(sender) then
send_large_msg(receiver, "لا تسطيع حضر الادمنية او المدراء")
return
end
send_large_msg(receiver, 'العضو @'..member..' ['..member_id..'] تم حضره')
ban_user(member_id, chat_id)
elseif get_cmd == 'الغاء الحظر' then
send_large_msg(receiver, 'العضو @'..member..' ['..member_id..'] راح الحضر منة')
local hash = 'banned:'..chat_id
redis:srem(hash, member_id)
return 'العضو '..user_id..' راح الحضر منة'
elseif get_cmd == 'حظر عام' then
send_large_msg(receiver, 'العضو @'..member..' ['..member_id..'] تم حضره عام ')
banall_user(member_id)
elseif get_cmd == 'الغاء العام' then
send_large_msg(receiver, 'العضو @'..member..' ['..member_id..'] راح العام منة')
unbanall_user(member_id)
end
end
local function run(msg, matches)
local support_id = msg.from.id
if matches[1]:lower() == 'ايدي' and msg.to.type == "chat" or msg.to.type == "user" then
if msg.to.type == "user" then
return "❣ ايدي البوت : "..msg.to.id.. "\n\n❣ ايدي حسابك : "..msg.from.id.. "\n\n❣ #المطور @SAJJADNOORI"
end
if type(msg.reply_id) ~= "nil" then
local print_name = user_print_name(msg.from):gsub("", "")
local name = print_name:gsub("_", "")
savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ")
id = get_message(msg.reply_id,get_message_callback_id, false)
elseif matches[1]:lower() == 'ايدي' then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ")
return "ايدي المجموعه" ..string.gsub(msg.to.print_name, "_", " ").. ":\n\n"..msg.to.id
end
end
if matches[1]:lower() == 'مغادره' and msg.to.type == "chat" then-- /kickme
local receiver = get_receiver(msg)
if msg.to.type == 'chat' then
local print_name = user_print_name(msg.from):gsub("", "")
local name = print_name:gsub("_", "")
savelog(msg.to.id, name.." ["..msg.from.id.."] left using kickme ")-- Save to logs
chat_del_user("chat#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false)
end
end
if not is_momod(msg) then -- Ignore normal users
return
end
if matches[1]:lower() == "قائمه المحظورين" then -- Ban list !
local chat_id = msg.to.id
if matches[2] and is_admin1(msg) then
chat_id = matches[2]
end
return ban_list(chat_id)
end
if matches[1]:lower() == 'حظر' then-- /ban
if type(msg.reply_id)~="nil" and is_momod(msg) then
if is_admin1(msg) then
msgr = get_message(msg.reply_id,ban_by_reply_admins, false)
else
msgr = get_message(msg.reply_id,ban_by_reply, false)
end
local user_id = matches[2]
local chat_id = msg.to.id
elseif string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return
end
if not is_admin1(msg) and is_momod2(matches[2], msg.to.id) then
return "لا تستطيع حضر الادمنية او المدراء"
end
if tonumber(matches[2]) == tonumber(msg.from.id) then
return "لا تستطيع حضر نفسك"
end
local print_name = user_print_name(msg.from):gsub("", "")
local name = print_name:gsub("_", "")
local receiver = get_receiver(msg)
savelog(msg.to.id, name.." ["..msg.from.id.."] baned user ".. matches[2])
ban_user(matches[2], msg.to.id)
send_large_msg(receiver, 'العضو ['..matches[2]..'] تم حضره')
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'حظر',
from_id = msg.from.id,
chat_type = msg.to.type
}
local username = string.gsub(matches[2], '@', '')
resolve_username(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'الغاء الحظر' then -- /unban
if type(msg.reply_id)~="nil" and is_momod(msg) then
local msgr = get_message(msg.reply_id,unban_by_reply, false)
end
local user_id = matches[2]
local chat_id = msg.to.id
local targetuser = matches[2]
if string.match(targetuser, '^%d+$') then
local user_id = targetuser
local hash = 'banned:'..chat_id
redis:srem(hash, user_id)
local print_name = user_print_name(msg.from):gsub("", "")
local name = print_name:gsub("_", "")
savelog(msg.to.id, name.." ["..msg.from.id.."] unbaned user ".. matches[2])
return 'العضو '..user_id..' راح الحضر منة'
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'الغاء الحظر',
from_id = msg.from.id,
chat_type = msg.to.type
}
local username = string.gsub(matches[2], '@', '')
resolve_username(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'دي' then
if type(msg.reply_id)~="nil" and is_momod(msg) then
if is_admin1(msg) then
msgr = get_message(msg.reply_id,Kick_by_reply_admins, false)
else
msgr = get_message(msg.reply_id,Kick_by_reply, false)
end
elseif string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return
end
if not is_admin1(msg) and is_momod2(matches[2], msg.to.id) then
return "لا تستطيع طرد الادمنية او المدراء"
end
if tonumber(matches[2]) == tonumber(msg.from.id) then
return "لا تستطيع طرد نفسك"
end
local user_id = matches[2]
local chat_id = msg.to.id
print("sexy")
local print_name = user_print_name(msg.from):gsub("", "")
local name = print_name:gsub("_", "")
savelog(msg.to.id, name.." ["..msg.from.id.."] kicked user ".. matches[2])
kick_user(user_id, chat_id)
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'دي',
from_id = msg.from.id,
chat_type = msg.to.type
}
local username = string.gsub(matches[2], '@', '')
resolve_username(username, kick_ban_res, cbres_extra)
end
end
if not is_admin1(msg) and not is_support(support_id) then
return
end
if matches[1]:lower() == 'حظر عام' and is_admin1(msg) then -- Global ban
if type(msg.reply_id) ~="nil" and is_admin1(msg) then
banall = get_message(msg.reply_id,banall_by_reply, false)
end
local user_id = matches[2]
local chat_id = msg.to.id
local targetuser = matches[2]
if string.match(targetuser, '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return false
end
banall_user(targetuser)
return 'العضو ['..user_id..' ] تم حضره عام'
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'حظر عام',
from_id = msg.from.id,
chat_type = msg.to.type
}
local username = string.gsub(matches[2], '@', '')
resolve_username(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'الغاء العام' then -- Global unban
local user_id = matches[2]
local chat_id = msg.to.id
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return false
end
unbanall_user(user_id)
return 'العضو ['..user_id..' ] راح العام منة'
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'الغاء العام',
from_id = msg.from.id,
chat_type = msg.to.type
}
local username = string.gsub(matches[2], '@', '')
resolve_username(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == "قائمه العام" then -- Global ban list
return banall_list()
end
end
return {
patterns = {
"^(حظر عام) (.*)$",
"^(حظر عام)$",
"^(قائمه المحظورين) (.*)$",
"^(قائمه المحظورين)$",
"^(قائمه العام)$",
"^(مغادره)",
"^(دي)$",
"^(حظر)$",
"^(حظر) (.*)$",
"^(الغاء الحظر) (.*)$",
"^(الغاء العام) (.*)$",
"^(الغاء الغام)$",
"^(دي) (.*)$",
"^(الغاء الحظر)$",
"^(ايدي)$",
"^!!tgservice (.+)$"
},
run = run,
pre_process = pre_process
} | gpl-2.0 |
allwenandashi/1 | plugins/activeuser.lua | 7 | 11811 | local function checktodaygr(cb_extra, success, result)
local hash = ''
local thash=''
for k,user in pairs(result.members) do
thash = 'today:'..user.peer_id
if redis:get(thash) then
if redis:get(thash) < os.date("%x",os.time() + 16200) then
hash = 'utmsgst:'..user.peer_id..':'..cb_extra
redis:set(hash,0)
hash = 'utmsgph:'..user.peer_id..':'..cb_extra
redis:set(hash,0)
hash = 'utmsgtex:'..user.peer_id..':'..cb_extra
redis:set(hash,0)
hash = 'utmsgoth:'..user.peer_id..':'..cb_extra
redis:set(hash,0)
redis:set(thash,os.date("%x",os.time() + 16200))
end
else
redis:set(thash,os.date("%x",os.time() + 16200))
end
end
end
local function checktodaych(cb_extra, success, result)
local hash = ''
local thash=''
for k,user in pairs(result) do
thash = 'today:'..user.peer_id
if redis:get(thash) then
if redis:get(thash) < os.date("%x",os.time() + 16200) then
hash = 'utmsgst:'..user.peer_id..':'..cb_extra
redis:set(hash,0)
hash = 'utmsgph:'..user.peer_id..':'..cb_extra
redis:set(hash,0)
hash = 'utmsgtex:'..user.peer_id..':'..cb_extra
redis:set(hash,0)
hash = 'utmsgoth:'..user.peer_id..':'..cb_extra
redis:set(hash,0)
redis:set(thash,os.date("%x",os.time() + 16200))
end
else
redis:set(thash,os.date("%x",os.time() + 16200))
end
end
end
local function cron()
for v,chat in pairs(_chats.chats) do
channel_get_users('channel#id'..chat[1], checktodaych, chat[1])
chat_info('chat#id'..chat[1], checktodaygr, chat[1])
end
end
local function pre_process(msg)
if not msg.service then
if msg.media then
if msg.media.caption == 'sticker.webp' then
local hash = 'utmsgst:'..msg.from.id..':'..msg.to.id
redis:incr(hash)
elseif msg.media.type == 'photo' then
local hash = 'utmsgph:'..msg.from.id..':'..msg.to.id
redis:incr(hash)
end
else
if msg.text then
local hash = 'utmsgtex:'..msg.from.id..':'..msg.to.id
redis:incr(hash)
else
local hash = 'utmsgoth:'..msg.from.id..':'..msg.to.id
redis:incr(hash)
end
end
end
return msg
end
local function getactivegr(cb_extra, success, result)
local maxst = {}
local maxph = {}
local maxtex = {}
local maxoth = {}
local maxname = {}
local maxuser = {}
local maxid = {}
local maxstat = {}
maxstat[1] = 0
maxstat[2] = 0
maxstat[3] = 0
maxname[1] = ''
maxname[2] = ''
maxname[3] = ''
maxuser[1] = ''
maxuser[2] = ''
maxuser[3] = ''
for k,user in pairs(result.members) do
local shash = 'utmsgst:'..user.peer_id..':'..cb_extra
local phash = 'utmsgph:'..user.peer_id..':'..cb_extra
local thash = 'utmsgtex:'..user.peer_id..':'..cb_extra
local ohash = 'utmsgoth:'..user.peer_id..':'..cb_extra
if not redis:get(shash) then
redis:set(shash,0)
end
if not redis:get(phash) then
redis:set(phash,0)
end
if not redis:get(thash) then
redis:set(thash,0)
end
if not redis:get(ohash) then
redis:set(ohash,0)
end
if tonumber(redis:get(shash)) + tonumber(redis:get(phash)) + tonumber(redis:get(thash)) + tonumber(redis:get(ohash)) > maxstat[1] then
maxname[3] = maxname[2]
maxuser[3] = maxuser[2]
maxstat[3] = maxstat[2]
maxid[3] = maxid[2]
maxname[2] = maxname[1]
maxuser[2] = maxuser[1]
maxstat[2] = maxstat[1]
maxid[2] = maxid[1]
maxname[1] = user.print_name
maxuser[1] = user.username
maxid[1] = user.peer_id
maxstat[1] = tonumber(redis:get(shash)) + tonumber(redis:get(phash)) + tonumber(redis:get(thash)) + tonumber(redis:get(ohash))
elseif tonumber(redis:get(shash)) + tonumber(redis:get(phash)) + tonumber(redis:get(thash)) + tonumber(redis:get(ohash)) > maxstat[2] then
maxname[3] = maxname[2]
maxuser[3] = maxuser[2]
maxstat[3] = maxstat[2]
maxid[3] = maxid[2]
maxname[2] = user.print_name
maxuser[2] = user.username
maxid[2] = user.peer_id
maxstat[2] = tonumber(redis:get(shash)) + tonumber(redis:get(phash)) + tonumber(redis:get(thash)) + tonumber(redis:get(ohash))
elseif tonumber(redis:get(shash)) + tonumber(redis:get(phash)) + tonumber(redis:get(thash)) + tonumber(redis:get(ohash)) > maxstat[3] then
maxname[3] = user.print_name
maxuser[3] = user.username
maxid[3] = user.peer_id
maxstat[3] = tonumber(redis:get(shash)) + tonumber(redis:get(phash)) + tonumber(redis:get(thash)) + tonumber(redis:get(ohash))
end
end
maxst[1] = redis:get('utmsgst:'..maxid[1]..':'..cb_extra)
maxph[1] = redis:get('utmsgph:'..maxid[1]..':'..cb_extra)
maxtex[1] = redis:get('utmsgtex:'..maxid[1]..':'..cb_extra)
maxoth[1] = redis:get('utmsgoth:'..maxid[1]..':'..cb_extra)
if maxid[2] then
maxst[2] = redis:get('utmsgst:'..maxid[2]..':'..cb_extra)
maxph[2] = redis:get('utmsgph:'..maxid[2]..':'..cb_extra)
maxtex[2] = redis:get('utmsgtex:'..maxid[2]..':'..cb_extra)
maxoth[2] = redis:get('utmsgoth:'..maxid[2]..':'..cb_extra)
end
if maxid[3] then
maxst[3] = redis:get('utmsgst:'..maxid[3]..':'..cb_extra)
maxph[3] = redis:get('utmsgph:'..maxid[3]..':'..cb_extra)
maxtex[3] = redis:get('utmsgtex:'..maxid[3]..':'..cb_extra)
maxoth[3] = redis:get('utmsgoth:'..maxid[3]..':'..cb_extra)
end
if not maxuser[1] or maxuser[1] == '' then
maxuser[1] = 'ندارد'
else
maxuser[1] = '@'..maxuser[1]
end
if not maxuser[2] or maxuser[2] == '' then
maxuser[2] = 'ندارد'
else
maxuser[2] = '@'..maxuser[2]
end
if not maxuser[3] or maxuser[3] == '' then
maxuser[3] = 'ندارد'
else
maxuser[3] = '@'..maxuser[3]
end
local text = '♨️فعالان امروز گروه\n1⃣ '..maxname[1]..'〖'..maxuser[1]..'〗\n\n📨تعداد پیام های ارسالی: '..maxtex[1] + maxph[1] + maxst[1] + maxoth[1]..'\n\n👾استیکر: '..maxst[1]..'\n\n📷تصویر: '..maxph[1]..'\n\n📃 متن: '..maxtex[1]..'\n\n📦 سایر: '..maxoth[1]
if maxid[2] then
if not maxid[3] then
text = text..'\n\n 2⃣ '..maxname[2]..' 〖'..maxuser[2]..'〗\n\n📨تعداد پیام های ارسالی: '..maxtex[2] + maxph[2] + maxst[2] + maxoth[2]..'\n\n👾استیکر: '..maxst[2]..'\n\n📷تصویر: '..maxph[2]..'\n\n📃 متن: '..maxtex[2]..'\n\n📦 سایر: '..maxoth[2]
else
text = text..'\n\n 2⃣ '..maxname[2]..' 〖'..maxuser[2]..'〗\n\n📨تعداد پیام های ارسالی: '..maxtex[2] + maxph[2] + maxst[2] + maxoth[2]..'\n\n👾استیکر: '..maxst[2]..'\n\n📷تصویر: '..maxph[2]..'\n\n📃 متن: '..maxtex[2]..'\n\n📦 سایر: '..maxoth[2]..'\n\n 3⃣ '..maxname[3]..' 〖'..maxuser[3]..'〗\n\n📨تعداد پیام های ارسالی: '..maxtex[3] + maxph[3] + maxst[3] + maxoth[3]..'\n\n👾استیکر: '..maxst[3]..'\n\n📷تصویر: '..maxph[3]..'\n\n📃 متن: '..maxtex[3]..'\n\n📦 سایر: '..maxoth[3]
end
end
send_msg('chat#id'..cb_extra, text, ok_cb, true)
end
local function getactivech(cb_extra, success, result)
local maxst = {}
local maxph = {}
local maxtex = {}
local maxoth = {}
local maxname = {}
local maxuser = {}
local maxid = {}
local maxstat = {}
maxstat[1] = 0
maxstat[2] = 0
maxstat[3] = 0
maxname[1] = ''
maxname[2] = ''
maxname[3] = ''
maxuser[1] = ''
maxuser[2] = ''
maxuser[3] = ''
for k,user in pairs(result) do
local shash = 'utmsgst:'..user.peer_id..':'..cb_extra
local phash = 'utmsgph:'..user.peer_id..':'..cb_extra
local thash = 'utmsgtex:'..user.peer_id..':'..cb_extra
local ohash = 'utmsgoth:'..user.peer_id..':'..cb_extra
if not redis:get(shash) then
redis:set(shash,0)
end
if not redis:get(phash) then
redis:set(phash,0)
end
if not redis:get(thash) then
redis:set(thash,0)
end
if not redis:get(ohash) then
redis:set(ohash,0)
end
if tonumber(redis:get(shash)) + tonumber(redis:get(phash)) + tonumber(redis:get(thash)) + tonumber(redis:get(ohash)) > maxstat[1] then
maxname[3] = maxname[2]
maxuser[3] = maxuser[2]
maxstat[3] = maxstat[2]
maxid[3] = maxid[2]
maxname[2] = maxname[1]
maxuser[2] = maxuser[1]
maxstat[2] = maxstat[1]
maxid[2] = maxid[1]
maxname[1] = user.print_name
maxuser[1] = user.username
maxid[1] = user.peer_id
maxstat[1] = tonumber(redis:get(shash)) + tonumber(redis:get(phash)) + tonumber(redis:get(thash)) + tonumber(redis:get(ohash))
elseif tonumber(redis:get(shash)) + tonumber(redis:get(phash)) + tonumber(redis:get(thash)) + tonumber(redis:get(ohash)) > maxstat[2] then
maxname[3] = maxname[2]
maxuser[3] = maxuser[2]
maxstat[3] = maxstat[2]
maxid[3] = maxid[2]
maxname[2] = user.print_name
maxuser[2] = user.username
maxid[2] = user.peer_id
maxstat[2] = tonumber(redis:get(shash)) + tonumber(redis:get(phash)) + tonumber(redis:get(thash)) + tonumber(redis:get(ohash))
elseif tonumber(redis:get(shash)) + tonumber(redis:get(phash)) + tonumber(redis:get(thash)) + tonumber(redis:get(ohash)) > maxstat[3] then
maxname[3] = user.print_name
maxuser[3] = user.username
maxid[3] = user.peer_id
maxstat[3] = tonumber(redis:get(shash)) + tonumber(redis:get(phash)) + tonumber(redis:get(thash)) + tonumber(redis:get(ohash))
end
end
maxst[1] = redis:get('utmsgst:'..maxid[1]..':'..cb_extra)
maxph[1] = redis:get('utmsgph:'..maxid[1]..':'..cb_extra)
maxtex[1] = redis:get('utmsgtex:'..maxid[1]..':'..cb_extra)
maxoth[1] = redis:get('utmsgoth:'..maxid[1]..':'..cb_extra)
if maxid[2] then
maxst[2] = redis:get('utmsgst:'..maxid[2]..':'..cb_extra)
maxph[2] = redis:get('utmsgph:'..maxid[2]..':'..cb_extra)
maxtex[2] = redis:get('utmsgtex:'..maxid[2]..':'..cb_extra)
maxoth[2] = redis:get('utmsgoth:'..maxid[2]..':'..cb_extra)
end
if maxid[3] then
maxst[3] = redis:get('utmsgst:'..maxid[3]..':'..cb_extra)
maxph[3] = redis:get('utmsgph:'..maxid[3]..':'..cb_extra)
maxtex[3] = redis:get('utmsgtex:'..maxid[3]..':'..cb_extra)
maxoth[3] = redis:get('utmsgoth:'..maxid[3]..':'..cb_extra)
end
if not maxuser[1] or maxuser[1] == '' then
maxuser[1] = 'ندارد'
else
maxuser[1] = '@'..maxuser[1]
end
if not maxuser[2] or maxuser[2] == '' then
maxuser[2] = 'ندارد'
else
maxuser[2] = '@'..maxuser[2]
end
if not maxuser[3] or maxuser[3] == '' then
maxuser[3] = 'ندارد'
else
maxuser[3] = '@'..maxuser[3]
end
local text = '♨️فعالان امروز گروه\n1⃣ '..maxname[1]..'〖'..maxuser[1]..'〗\n\n📨تعداد پیام های ارسالی: '..maxtex[1] + maxph[1] + maxst[1] + maxoth[1]..'\n\n👾استیکر: '..maxst[1]..'\n\n📷تصویر: '..maxph[1]..'\n\n📃 متن: '..maxtex[1]..'\n\n📦 سایر: '..maxoth[1]
if maxid[2] then
if not maxid[3] then
text = text..'\n\n 2⃣ '..maxname[2]..' 〖'..maxuser[2]..'〗\n\n📨تعداد پیام های ارسالی: '..maxtex[2] + maxph[2] + maxst[2] + maxoth[2]..'\n\n👾استیکر: '..maxst[2]..'\n\n📷تصویر: '..maxph[2]..'\n\n📃 متن: '..maxtex[2]..'\n\n📦 سایر: '..maxoth[2]
else
text = text..'\n\n 2⃣ '..maxname[2]..' 〖'..maxuser[2]..'〗\n\n📨تعداد پیام های ارسالی: '..maxtex[2] + maxph[2] + maxst[2] + maxoth[2]..'\n\n👾استیکر: '..maxst[2]..'\n\n📷تصویر: '..maxph[2]..'\n\n📃 متن: '..maxtex[2]..'\n\n📦 سایر: '..maxoth[2]..'\n\n 3⃣ '..maxname[3]..' 〖'..maxuser[3]..'〗\n\n📨تعداد پیام های ارسالی: '..maxtex[3] + maxph[3] + maxst[3] + maxoth[3]..'\n\n👾استیکر: '..maxst[3]..'\n\n📷تصویر: '..maxph[3]..'\n\n📃 متن: '..maxtex[3]..'\n\n📦 سایر: '..maxoth[3]
end
end
send_msg('channel#id'..cb_extra, text, ok_cb, true)
end
local function run(msg,matches)
if msg.to.type == 'channel' then
channel_get_users('channel#id'..msg.to.id, getactivech, msg.to.id)
elseif msg.to.type == 'chat' then
chat_info('chat#id'..msg.to.id, getactivegr, msg.to.id)
end
end
return {
patterns = {
"^[!/#]active$",
"^active$",
},
pre_process = pre_process,
cron = cron,
run = run
} | gpl-2.0 |
sajjad94/ASD_KARBALA | plugins/ar-getlink.lua | 7 | 28100 | --[[
▀▄ ▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀
▀▄ ▄▀ ▀▄ ▄▀
▀▄ ▄▀ BY SAJJAD NOORI ▀▄ ▄▀
▀▄ ▄▀ BY SAJAD NOORI (@SAJJADNOORI) ▀▄ ▄▀
▀▄ ▄▀ JUST WRITED BY SAJJAD NOORI ▀▄ ▄▀
▀▄ ▄▀ A SPECiAL LINK : الرابط خاص ▀▄ ▄▀
▀▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀
--]]
do
local function check_member(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.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
moderators = {},
set_owner = member_id ,
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes'
}
}
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'You have been promoted as the owner.')
end
end
end
local function check_member_modadd(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.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
moderators = {},
set_owner = member_id ,
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes'
}
}
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Group is added and you have been promoted as the owner ')
end
end
end
local function automodadd(msg)
local data = load_data(_config.moderation.data)
if msg.action.type == 'chat_created' then
receiver = get_receiver(msg)
chat_info(receiver, check_member,{receiver=receiver, data=data, msg = msg})
end
end
local function check_member_modrem(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.members) 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)
return send_large_msg(receiver, 'Group has been removed')
end
end
end
local function show_group_settingsmod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
local bots_protection = "Yes"
if data[tostring(msg.to.id)]['settings']['lock_bots'] then
bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots']
end
local settings = data[tostring(target)]['settings']
local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX.."\nBot protection : "..bots_protection
return text
end
local function set_descriptionmod(msg, data, target, about)
if not is_momod(msg) then
return "For moderators only!"
end
local data_cat = 'description'
data[tostring(target)][data_cat] = about
save_data(_config.moderation.data, data)
return 'Set group description to:\n'..about
end
local function get_description(msg, data)
local data_cat = 'description'
if not data[tostring(msg.to.id)][data_cat] then
return 'No description available.'
end
local about = data[tostring(msg.to.id)][data_cat]
local about = string.gsub(msg.to.print_name, "_", " ")..':\n\n'..about
return 'About '..about
end
local function lock_group_arabic(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'yes' then
return 'Arabic is already locked'
else
data[tostring(target)]['settings']['lock_arabic'] = 'yes'
save_data(_config.moderation.data, data)
return 'Arabic has been locked'
end
end
local function unlock_group_arabic(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'no' then
return 'Arabic is already unlocked'
else
data[tostring(target)]['settings']['lock_arabic'] = 'no'
save_data(_config.moderation.data, data)
return 'Arabic has been unlocked'
end
end
local function lock_group_bots(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_bots_lock = data[tostring(target)]['settings']['lock_bots']
if group_bots_lock == 'yes' then
return 'Bots protection is already enabled'
else
data[tostring(target)]['settings']['lock_bots'] = 'yes'
save_data(_config.moderation.data, data)
return 'Bots protection has been enabled'
end
end
local function unlock_group_bots(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_bots_lock = data[tostring(target)]['settings']['lock_bots']
if group_bots_lock == 'no' then
return 'Bots protection is already disabled'
else
data[tostring(target)]['settings']['lock_bots'] = 'no'
save_data(_config.moderation.data, data)
return 'Bots protection has been disabled'
end
end
local function lock_group_namemod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'yes' then
return 'Group name is already locked'
else
data[tostring(target)]['settings']['lock_name'] = 'yes'
save_data(_config.moderation.data, data)
rename_chat('chat#id'..target, group_name_set, ok_cb, false)
return 'Group name has been locked'
end
end
local function unlock_group_namemod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'no' then
return 'Group name is already unlocked'
else
data[tostring(target)]['settings']['lock_name'] = 'no'
save_data(_config.moderation.data, data)
return 'Group name has been unlocked'
end
end
local function lock_group_floodmod(msg, data, target)
if not is_owner(msg) then
return "Only admins can do it for now"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'yes' then
return 'Group flood is locked'
else
data[tostring(target)]['settings']['flood'] = 'yes'
save_data(_config.moderation.data, data)
return 'Group flood has been locked'
end
end
local function unlock_group_floodmod(msg, data, target)
if not is_owner(msg) then
return "Only admins can do it for now"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'no' then
return 'Group flood is not locked'
else
data[tostring(target)]['settings']['flood'] = 'no'
save_data(_config.moderation.data, data)
return 'Group flood has been unlocked'
end
end
local function lock_group_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'yes' then
return 'Group members are already locked'
else
data[tostring(target)]['settings']['lock_member'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group members has been locked'
end
local function unlock_group_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'no' then
return 'Group members are not locked'
else
data[tostring(target)]['settings']['lock_member'] = 'no'
save_data(_config.moderation.data, data)
return 'Group members has been unlocked'
end
end
local function unlock_group_photomod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'no' then
return 'Group photo is not locked'
else
data[tostring(target)]['settings']['lock_photo'] = 'no'
save_data(_config.moderation.data, data)
return 'Group photo has been unlocked'
end
end
local function set_rulesmod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local data_cat = 'rules'
data[tostring(target)][data_cat] = rules
save_data(_config.moderation.data, data)
return 'Set group rules to:\n'..rules
end
local function modadd(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
return 'Group is already added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_modadd,{receiver=receiver, data=data, msg = msg})
end
local function modrem(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
if not data[tostring(msg.to.id)] then
return 'Group is not added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_modrem,{receiver=receiver, data=data, msg = msg})
end
local function get_rules(msg, data)
local data_cat = 'rules'
if not data[tostring(msg.to.id)][data_cat] then
return 'No rules available.'
end
local rules = data[tostring(msg.to.id)][data_cat]
local rules = 'Chat rules:\n'..rules
return rules
end
local function set_group_photo(msg, success, result)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
if success then
local file = 'data/photos/chat_photo_'..msg.to.id..'.jpg'
print('File downloaded to:', result)
os.rename(result, file)
print('File moved to:', file)
chat_set_photo (receiver, file, ok_cb, false)
data[tostring(msg.to.id)]['settings']['set_photo'] = file
save_data(_config.moderation.data, data)
data[tostring(msg.to.id)]['settings']['lock_photo'] = 'yes'
save_data(_config.moderation.data, data)
send_large_msg(receiver, 'Photo saved!', ok_cb, false)
else
print('Error downloading: '..msg.id)
send_large_msg(receiver, 'Failed, please try again!', ok_cb, false)
end
end
local function promote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'chat#id', '')
if not data[group] then
return send_large_msg(receiver, 'Group is not added.')
end
if data[group]['moderators'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is already a moderator.')
end
data[group]['moderators'][tostring(member_id)] = member_username
save_data(_config.moderation.data, data)
return send_large_msg(receiver, '@'..member_username..' has been promoted.')
end
local function demote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'chat#id', '')
if not data[group] then
return send_large_msg(receiver, 'Group is not added.')
end
if not data[group]['moderators'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is not a moderator.')
end
data[group]['moderators'][tostring(member_id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, '@'..member_username..' has been demoted.')
end
local function username_id(cb_extra, success, result)
local mod_cmd = cb_extra.mod_cmd
local receiver = cb_extra.receiver
local member = cb_extra.member
local text = 'No user @'..member..' in this group.'
for k,v in pairs(result.members) do
vusername = v.username
if vusername == member then
member_username = member
member_id = v.id
if mod_cmd == 'promote' then
return promote(receiver, member_username, member_id)
elseif mod_cmd == 'demote' then
return demote(receiver, member_username, member_id)
end
end
end
send_large_msg(receiver, text)
end
local function modlist(msg)
local data = load_data(_config.moderation.data)
if not data[tostring(msg.to.id)] then
return 'Group is not added.'
end
-- determine if table is empty
if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way
return 'No moderator in this group.'
end
local i = 1
local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n'
for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do
message = message ..i..' - @'..v..' [' ..k.. '] \n'
i = i + 1
end
return message
end
local function callbackres(extra, success, result)
local user = result.id
local name = string.gsub(result.print_name, "_", " ")
local chat = 'chat#id'..extra.chatid
send_large_msg(chat, user..'\n'..name)
return user
end
local function help()
local help_text = tostring(_config.help_text)
return help_text
end
local function cleanmember(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
if success == -1 then
return send_large_msg(receiver, '*Error: Invite link failed* \nReason: Not creator.')
end
for k,v in pairs(result.members) do
kick_user(v.id, result.id)
end
end
local function run(msg, matches)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
local name_log = user_print_name(msg.from)
local group = msg.to.id
if msg.media then
if msg.media.type == 'photo' and data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' and is_chat_msg(msg) and is_momod(msg) then
load_photo(msg.id, set_group_photo, msg)
end
end
if matches[1] == 'add' then
print("group "..msg.to.print_name.."("..msg.to.id..") added")
return modadd(msg)
end
if matches[1] == 'rem' then
print("group "..msg.to.print_name.."("..msg.to.id..") removed")
return modrem(msg)
end
if matches[1] == 'chat_created' and msg.from.id == 0 then
return automodadd(msg)
end
if msg.to.id and data[tostring(msg.to.id)] then
local settings = data[tostring(msg.to.id)]['settings']
if matches[1] == 'chat_add_user' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_member_lock = settings.lock_member
local user = 'user#id'..msg.action.user.id
local chat = 'chat#id'..msg.to.id
if group_member_lock == 'yes' and not is_owner2(msg.action.user.id, msg.to.id) then
chat_del_user(chat, user, ok_cb, true)
elseif group_member_lock == 'yes' and tonumber(msg.from.id) == tonumber(our_id) then
return nil
elseif group_member_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_add_user' then
if not msg.service then
return "Are you trying to troll me?"
end
local receiver = 'user#id'..msg.action.user.id
local data_cat = 'rules'
if not data[tostring(msg.to.id)][data_cat] then
return false
end
local rules = data[tostring(msg.to.id)][data_cat]
local rules = 'Welcome to "' .. string.gsub(msg.to.print_name, '_', ' ') ..'" this group has rules that you should follow:\n'..rules
savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted user "..msg.action.user.id)
send_large_msg(receiver, rules)
end
if matches[1] == 'chat_del_user' then
if not msg.service then
return "Are you trying to troll me?"
end
local user = 'user#id'..msg.action.user.id
local chat = 'chat#id'..msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted user "..user)
end
if matches[1] == 'chat_delete_photo' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_photo_lock = settings.lock_photo
if group_photo_lock == 'yes' then
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:incr(picturehash)
---
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
local picprotectionredis = redis:get(picturehash)
if picprotectionredis then
if tonumber(picprotectionredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)
end
if tonumber(picprotectionredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:set(picturehash, 0)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to deleted picture but failed ")
chat_set_photo(receiver, settings.set_photo, ok_cb, false)
elseif group_photo_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_change_photo' and msg.from.id ~= 0 then
if not msg.service then
return "Are you trying to troll me?"
end
local group_photo_lock = settings.lock_photo
if group_photo_lock == 'yes' then
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:incr(picturehash)
---
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
local picprotectionredis = redis:get(picturehash)
if picprotectionredis then
if tonumber(picprotectionredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)
end
if tonumber(picprotectionredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:set(picturehash, 0)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change picture but failed ")
chat_set_photo(receiver, settings.set_photo, ok_cb, false)
elseif group_photo_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_rename' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_name_set = settings.set_name
local group_name_lock = settings.lock_name
local to_rename = 'chat#id'..msg.to.id
if group_name_lock == 'yes' then
if group_name_set ~= tostring(msg.to.print_name) then
local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id
redis:incr(namehash)
local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id
local nameprotectionredis = redis:get(namehash)
if nameprotectionredis then
if tonumber(nameprotectionredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)
end
if tonumber(nameprotectionredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)
local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id
redis:set(namehash, 0)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change name but failed ")
rename_chat(to_rename, group_name_set, ok_cb, false)
end
elseif group_name_lock == 'no' then
return nil
end
end
if matches[1] == 'setname' and is_momod(msg) then
local new_name = string.gsub(matches[2], '_', ' ')
data[tostring(msg.to.id)]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local to_rename = 'chat#id'..msg.to.id
rename_chat(to_rename, group_name_set, ok_cb, false)
savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]")
end
if matches[1] == 'setphoto' and is_momod(msg) then
data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting'
save_data(_config.moderation.data, data)
return 'Please send me new group photo now'
end
if matches[1] == 'promote' and matches[2] then
if not is_owner(msg) then
return "Only owner can promote"
end
local member = string.gsub(matches[2], "@", "")
local mod_cmd = 'promote'
savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @".. member)
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
if matches[1] == 'demote' and matches[2] then
if not is_owner(msg) then
return "Only owner can demote"
end
if string.gsub(matches[2], "@", "") == msg.from.username then
return "You can't demote yourself"
end
local member = string.gsub(matches[2], "@", "")
local mod_cmd = 'demote'
savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @".. member)
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
if matches[1] == 'modlist' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group modlist")
return modlist(msg)
end
if matches[1] == 'about' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group description")
return get_description(msg, data)
end
if matches[1] == 'rules' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group rules")
return get_rules(msg, data)
end
if matches[1] == 'set' then
if matches[2] == 'rules' then
rules = matches[3]
local target = msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]")
return set_rulesmod(msg, data, target)
end
if matches[2] == 'about' then
local data = load_data(_config.moderation.data)
local target = msg.to.id
local about = matches[3]
savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]")
return set_descriptionmod(msg, data, target, about)
end
end
if matches[1] == 'lock' then
local target = msg.to.id
if matches[2] == 'name' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked name ")
return lock_group_namemod(msg, data, target)
end
if matches[2] == 'member' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked member ")
return lock_group_membermod(msg, data, target)
end
if matches[2] == 'flood' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked flood ")
return lock_group_floodmod(msg, data, target)
end
if matches[2] == 'arabic' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked arabic ")
return lock_group_arabic(msg, data, target)
end
if matches[2] == 'bots' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked bots ")
return lock_group_bots(msg, data, target)
end
end
if matches[1] == 'unlock' then
local target = msg.to.id
if matches[2] == 'name' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked name ")
return unlock_group_namemod(msg, data, target)
end
if matches[2] == 'member' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked member ")
return unlock_group_membermod(msg, data, target)
end
if matches[2] == 'photo' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked photo ")
return unlock_group_photomod(msg, data, target)
end
if matches[2] == 'flood' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked flood ")
return unlock_group_floodmod(msg, data, target)
end
if matches[2] == 'arabic' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked arabic ")
return unlock_group_arabic(msg, data, target)
end
if matches[2] == 'bots' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked bots ")
return unlock_group_bots(msg, data, target)
end
end
if matches[1] == 'settings' then
local target = msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group settings ")
return show_group_settingsmod(msg, data, target)
end
if matches[1] == 'newlink' then
if not is_momod(msg) then
return "For moderators only!"
end
local function callback (extra , success, result)
local receiver = 'chat#'..msg.to.id
if success == 0 then
return send_large_msg(receiver, '*Error: Invite link failed* \nReason: Not creator.')
end
send_large_msg(receiver, "Created a new link")
data[tostring(msg.to.id)]['settings']['set_link'] = result
save_data(_config.moderation.data, data)
end
local receiver = 'chat#'..msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] revoked group link ")
return export_chat_link(receiver, callback, true)
end
if matches[1] == 'الرابط خاص' then
if not is_momod(msg) then
return "👌🏻لتلعَب بكَيفك فقَطَ المدير او الاداري يحَق لهَ✔️"
end
local group_link = data[tostring(msg.to.id)]['settings']['set_link']
if not group_link then
return "❓يرجئ ارسال [/تغير الرابط] لانشاء رابط المجموعه👍🏻✔️"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]")
send_large_msg('user#id'..msg.from.id, "⁉️ رابط مجموعة 👥 "..msg.to.title..'\n'..group_link)
return "تم ارسال الرابط الى الخاص 😚👍"
end
if matches[1] == 'setowner' then
if not is_owner(msg) then
return "For owner only!"
end
data[tostring(msg.to.id)]['set_owner'] = matches[2]
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set ["..matches[2].."] as owner")
local text = matches[2].." added as owner"
return text
end
if matches[1] == 'owner' then
local group_owner = data[tostring(msg.to.id)]['set_owner']
if not group_owner then
return "no owner,ask admins in support groups to set owner for your group"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] used /owner")
return "Group owner is ["..group_owner..']'
end
if matches[1] == 'setgpowner' then
local receiver = "chat#id"..matches[2]
if not is_admin(msg) then
return "For admins only!"
end
data[tostring(matches[2])]['set_owner'] = matches[3]
save_data(_config.moderation.data, data)
local text = matches[3].." added as owner"
send_large_msg(receiver, text)
return
end
if matches[1] == 'setflood' then
if not is_momod(msg) then
return "For moderators only!"
end
if tonumber(matches[2]) < 5 or tonumber(matches[2]) > 20 then
return "Wrong number,range is [5-20]"
end
local flood_max = matches[2]
data[tostring(msg.to.id)]['settings']['flood_msg_max'] = flood_max
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set flood to ["..matches[2].."]")
return 'Group flood has been set to '..matches[2]
end
if matches[1] == 'clean' then
if not is_owner(msg) then
return "Only owner can clean"
end
if matches[2] == 'member' then
if not is_owner(msg) then
return "Only admins can clean members"
end
local receiver = get_receiver(msg)
chat_info(receiver, cleanmember, {receiver=receiver})
end
if matches[2] == 'modlist' then
if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way
return 'No moderator in this group.'
end
local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n'
for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do
data[tostring(msg.to.id)]['moderators'][tostring(k)] = nil
save_data(_config.moderation.data, data)
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned modlist")
end
if matches[2] == 'rules' then
local data_cat = 'rules'
data[tostring(msg.to.id)][data_cat] = nil
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned rules")
end
if matches[2] == 'about' then
local data_cat = 'description'
data[tostring(msg.to.id)][data_cat] = nil
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned about")
end
end
if matches[1] == 'help' then
if not is_momod(msg) then
return
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help")
return help()
end
if matches[1] == 'res' and is_momod(msg) then
local cbres_extra = {
chatid = msg.to.id
}
local username = matches[2]
local username = username:gsub("@","")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username)
return res_user(username, callbackres, cbres_extra)
end
end
end
return {
patterns = {
"^(الرابط خاص)$",
"%[(photo)%]",
"^!!tgservice (.+)$",
},
run = run
}
end
-- arabic : @SAJJADNOORI
| gpl-2.0 |
MmxBoy/mmxanti2 | plugins/plugins.lua | 325 | 6164 | do
-- Returns the key (index) in the config.enabled_plugins table
local function plugin_enabled( name )
for k,v in pairs(_config.enabled_plugins) do
if name == v then
return k
end
end
-- If not found
return false
end
-- Returns true if file exists in plugins folder
local function plugin_exists( name )
for k,v in pairs(plugins_names()) do
if name..'.lua' == v then
return true
end
end
return false
end
local function list_all_plugins(only_enabled)
local text = ''
local nsum = 0
for k, v in pairs( plugins_names( )) do
-- ✔ enabled, ❌ disabled
local status = '❌'
nsum = nsum+1
nact = 0
-- Check if is enabled
for k2, v2 in pairs(_config.enabled_plugins) do
if v == v2..'.lua' then
status = '✔'
end
nact = nact+1
end
if not only_enabled or status == '✔' then
-- get the name
v = string.match (v, "(.*)%.lua")
text = text..nsum..'. '..v..' '..status..'\n'
end
end
local text = text..'\nThere are '..nsum..' plugins installed.\n'..nact..' plugins enabled and '..nsum-nact..' disabled'
return text
end
local function list_plugins(only_enabled)
local text = ''
local nsum = 0
for k, v in pairs( plugins_names( )) do
-- ✔ enabled, ❌ disabled
local status = '❌'
nsum = nsum+1
nact = 0
-- Check if is enabled
for k2, v2 in pairs(_config.enabled_plugins) do
if v == v2..'.lua' then
status = '✔'
end
nact = nact+1
end
if not only_enabled or status == '✔' then
-- get the name
v = string.match (v, "(.*)%.lua")
text = text..v..' '..status..'\n'
end
end
local text = text..'\n'..nact..' plugins enabled from '..nsum..' plugins installed.'
return text
end
local function reload_plugins( )
plugins = {}
load_plugins()
return list_plugins(true)
end
local function enable_plugin( plugin_name )
print('checking if '..plugin_name..' exists')
-- Check if plugin is enabled
if plugin_enabled(plugin_name) then
return 'Plugin '..plugin_name..' is enabled'
end
-- Checks if plugin exists
if plugin_exists(plugin_name) then
-- Add to the config table
table.insert(_config.enabled_plugins, plugin_name)
print(plugin_name..' added to _config table')
save_config()
-- Reload the plugins
return reload_plugins( )
else
return 'Plugin '..plugin_name..' does not exists'
end
end
local function disable_plugin( name, chat )
-- Check if plugins exists
if not plugin_exists(name) then
return 'Plugin '..name..' does not exists'
end
local k = plugin_enabled(name)
-- Check if plugin is enabled
if not k then
return 'Plugin '..name..' not enabled'
end
-- Disable and reload
table.remove(_config.enabled_plugins, k)
save_config( )
return reload_plugins(true)
end
local function disable_plugin_on_chat(receiver, plugin)
if not plugin_exists(plugin) then
return "Plugin doesn't exists"
end
if not _config.disabled_plugin_on_chat then
_config.disabled_plugin_on_chat = {}
end
if not _config.disabled_plugin_on_chat[receiver] then
_config.disabled_plugin_on_chat[receiver] = {}
end
_config.disabled_plugin_on_chat[receiver][plugin] = true
save_config()
return 'Plugin '..plugin..' disabled on this chat'
end
local function reenable_plugin_on_chat(receiver, plugin)
if not _config.disabled_plugin_on_chat then
return 'There aren\'t any disabled plugins'
end
if not _config.disabled_plugin_on_chat[receiver] then
return 'There aren\'t any disabled plugins for this chat'
end
if not _config.disabled_plugin_on_chat[receiver][plugin] then
return 'This plugin is not disabled'
end
_config.disabled_plugin_on_chat[receiver][plugin] = false
save_config()
return 'Plugin '..plugin..' is enabled again'
end
local function run(msg, matches)
-- Show the available plugins
if matches[1] == '!plugins' and is_sudo(msg) then --after changed to moderator mode, set only sudo
return list_all_plugins()
end
-- Re-enable a plugin for this chat
if matches[1] == 'enable' and matches[3] == 'chat' then
local receiver = get_receiver(msg)
local plugin = matches[2]
print("enable "..plugin..' on this chat')
return reenable_plugin_on_chat(receiver, plugin)
end
-- Enable a plugin
if matches[1] == 'enable' and is_sudo(msg) then --after changed to moderator mode, set only sudo
local plugin_name = matches[2]
print("enable: "..matches[2])
return enable_plugin(plugin_name)
end
-- Disable a plugin on a chat
if matches[1] == 'disable' and matches[3] == 'chat' then
local plugin = matches[2]
local receiver = get_receiver(msg)
print("disable "..plugin..' on this chat')
return disable_plugin_on_chat(receiver, plugin)
end
-- Disable a plugin
if matches[1] == 'disable' and is_sudo(msg) then --after changed to moderator mode, set only sudo
if matches[2] == 'plugins' then
return 'This plugin can\'t be disabled'
end
print("disable: "..matches[2])
return disable_plugin(matches[2])
end
-- Reload all the plugins!
if matches[1] == 'reload' and is_sudo(msg) then --after changed to moderator mode, set only sudo
return reload_plugins(true)
end
end
return {
description = "Plugin to manage other plugins. Enable, disable or reload.",
usage = {
moderator = {
"!plugins disable [plugin] chat : disable plugin only this chat.",
"!plugins enable [plugin] chat : enable plugin only this chat.",
},
sudo = {
"!plugins : list all plugins.",
"!plugins enable [plugin] : enable plugin.",
"!plugins disable [plugin] : disable plugin.",
"!plugins reload : reloads all plugins." },
},
patterns = {
"^!plugins$",
"^!plugins? (enable) ([%w_%.%-]+)$",
"^!plugins? (disable) ([%w_%.%-]+)$",
"^!plugins? (enable) ([%w_%.%-]+) (chat)",
"^!plugins? (disable) ([%w_%.%-]+) (chat)",
"^!plugins? (reload)$" },
run = run,
moderated = true, -- set to moderator mode
--privileged = true
}
end | gpl-2.0 |
m-creations/openwrt | feeds/routing/luci-app-bmx6/files/usr/lib/lua/luci/model/cbi/bmx6/tunnels.lua | 18 | 2336 | --[[
Copyright (C) 2011 Pau Escrich <pau@dabax.net>
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.
The full GNU General Public License is included in this distribution in
the file called "COPYING".
--]]
local sys = require("luci.sys")
local bmx6json = require("luci.model.bmx6json")
m = Map("bmx6", "bmx6")
-- tunOut
local tunnelsOut = m:section(TypedSection,"tunOut",translate("Networks to fetch"),translate("Gateways announcements to fetch"))
tunnelsOut.addremove = true
tunnelsOut.anonymous = true
tunnelsOut:option(Value,"tunOut","Name")
tunnelsOut:option(Value,"network", translate("Network to fetch"))
local tunoptions = bmx6json.getOptions("tunOut")
local _,o
for _,o in ipairs(tunoptions) do
if o.name ~= nil and o.name ~= "network" then
help = bmx6json.getHtmlHelp(o)
value = tunnelsOut:option(Value,o.name,o.name,help)
value.optional = true
end
end
-- tunOut
local tunnelsIn = m:section(TypedSection,"tunIn",translate("Networks to offer"),translate("Gateways to announce in the network"))
tunnelsIn.addremove = true
tunnelsIn.anonymous = true
tunnelsIn:option(Value,"tunIn","Name")
tunnelsIn:option(Value,"network", translate("Network to offer"))
local tunInoptions = bmx6json.getOptions("tunIn")
local _,o
for _,o in ipairs(tunInoptions) do
if o.name ~= nil and o.name ~= "network" then
help = bmx6json.getHtmlHelp(o)
value = tunnelsIn:option(Value,o.name,o.name,help)
value.optional = true
end
end
function m.on_commit(self,map)
--Not working. If test returns error the changes are still commited
local msg = bmx6json.testandreload()
if msg ~= nil then
m.message = msg
end
end
return m
| gpl-2.0 |
ziz/solarus | quests/zsxd/data/enemies/chain_and_ball.lua | 2 | 2671 | -- A ball and its chain, usually controlled by another enemy.
-- The ball is controlled by a circular movement and
-- the chain is a sprite that automatically fits the space between the other enemy and the ball.
-- They usually disappear when the enemy is killed.
nb_links = 10
link_sprite = nil
link_xy = {
{x = 0, y = 0},
{x = 0, y = 0},
{x = 0, y = 0},
{x = 0, y = 0},
{x = 0, y = 0},
{x = 0, y = 0},
{x = 0, y = 0},
{x = 0, y = 0},
{x = 0, y = 0},
{x = 0, y = 0}
}
father_name = "" -- name of the enemy the chain and ball is attached to if any
center_xy = {x = 0, y = 0} -- center point of the circles, relative to the father enemy if any, absolute otherwise
function event_appear()
-- set the properties
sol.enemy.set_life(1)
sol.enemy.set_damage(2)
sol.enemy.create_sprite("enemies/chain_and_ball")
sol.enemy.set_size(16, 16)
sol.enemy.set_origin(8, 8)
sol.enemy.set_invincible()
sol.enemy.set_displayed_in_y_order(true)
-- create a second sprite that stays in the script
link_sprite = sol.main.sprite_create("enemies/chain_and_ball")
sol.main.sprite_set_animation(link_sprite, "chain")
-- initialize the links of the chain
for i = 1, nb_links do
link_xy[i].x = 0
link_xy[i].y = 0
end
-- get the difference of coordinates between me and my father
father_name = sol.enemy.get_father()
if father_name ~= "" then
x, y = sol.enemy.get_position()
father_x, father_y = sol.map.enemy_get_position(father_name)
center_xy.x, center_xy.y = x - father_x, y - father_y
end
end
function event_pre_display()
for i = 1, nb_links do
sol.map.sprite_display(link_sprite, link_xy[i].x, link_xy[i].y)
end
end
function event_position_changed(x, y)
-- recalculate the chain position
if father_name ~= "" then
-- the center is relative to the father
x, y = sol.map.enemy_get_position(father_name)
x1, y1 = x + center_xy.x, y + center_xy.y;
else
-- the center is absolute
x1, y1 = center_xy
end
x2, y2 = sol.enemy.get_position();
for i = 1, nb_links do
link_xy[i].x = x1 + (x2 - x1) * (i - 1) / nb_links;
link_xy[i].y = y1 + (y2 - y1) * (i - 1) / nb_links;
end
end
function event_enabled()
m = sol.main.circle_movement_create(7, father_name, 56)
sol.main.movement_set_property(m, "center_dx", center_xy.x)
sol.main.movement_set_property(m, "center_dy", center_xy.y)
sol.main.movement_set_property(m, "radius_speed", 50)
sol.main.movement_set_property(m, "max_rotations", 4)
sol.main.movement_set_property(m, "loop", 2000)
sol.main.movement_set_property(m, "angle_speed", 360)
sol.enemy.start_movement(m)
end
| gpl-3.0 |
jozadaquebatista/textadept | core/iface.lua | 1 | 23223 | -- Copyright 2007-2015 Mitchell mitchell.att.foicica.com. See LICENSE.
local M = {}
--[[ This comment is for LuaDoc.
---
-- Scintilla constants, functions, and properties.
-- Do not modify anything in this module. Doing so will have unpredictable
-- consequences.
module('_SCINTILLA')]]
---
-- Map of Scintilla constant names to their numeric values.
-- @class table
-- @name constants
-- @see _G.buffer
M.constants = {ALPHA_NOALPHA=256,ALPHA_OPAQUE=255,ALPHA_TRANSPARENT=0,ANNOTATION_BOXED=2,ANNOTATION_HIDDEN=0,ANNOTATION_INDENTED=3,ANNOTATION_STANDARD=1,AUTOMATICFOLD_CHANGE=0x0004,AUTOMATICFOLD_CLICK=0x0002,AUTOMATICFOLD_SHOW=0x0001,CARETSTICKY_OFF=0,CARETSTICKY_ON=1,CARETSTICKY_WHITESPACE=2,CARETSTYLE_BLOCK=2,CARETSTYLE_INVISIBLE=0,CARETSTYLE_LINE=1,CARET_EVEN=0x08,CARET_JUMPS=0x10,CARET_SLOP=0x01,CARET_STRICT=0x04,CASEINSENSITIVEBEHAVIOUR_IGNORECASE=1,CASEINSENSITIVEBEHAVIOUR_RESPECTCASE=0,CASE_LOWER=2,CASE_MIXED=0,CASE_UPPER=1,CP_UTF8=65001,CURSORARROW=2,CURSORNORMAL=-1,CURSORREVERSEARROW=7,CURSORWAIT=4,EDGE_BACKGROUND=2,EDGE_LINE=1,EDGE_NONE=0,EOL_CR=1,EOL_CRLF=0,EOL_LF=2,FIND_CXX11REGEX=0x00800000,FIND_MATCHCASE=0x4,FIND_REGEXP=6291456,FIND_WHOLEWORD=0x2,FIND_WORDSTART=0x00100000,FOLDACTION_CONTRACT=0,FOLDACTION_EXPAND=1,FOLDACTION_TOGGLE=2,FOLDFLAG_LEVELNUMBERS=0x0040,FOLDFLAG_LINEAFTER_CONTRACTED=0x0010,FOLDFLAG_LINEAFTER_EXPANDED=0x0008,FOLDFLAG_LINEBEFORE_CONTRACTED=0x0004,FOLDFLAG_LINEBEFORE_EXPANDED=0x0002,FOLDFLAG_LINESTATE=0x0080,FOLDLEVELBASE=0x400,FOLDLEVELHEADERFLAG=0x2000,FOLDLEVELNUMBERMASK=0x0FFF,FOLDLEVELWHITEFLAG=0x1000,IME_INLINE=1,IME_WINDOWED=0,INDIC_BOX=6,INDIC_COMPOSITIONTHICK=14,INDIC_COMPOSITIONTHIN=15,INDIC_CONTAINER=8,INDIC_DASH=9,INDIC_DIAGONAL=3,INDIC_DOTBOX=12,INDIC_DOTS=10,INDIC_FULLBOX=16,INDIC_HIDDEN=5,INDIC_IME=32,INDIC_IME_MAX=35,INDIC_MAX=35,INDIC_PLAIN=0,INDIC_ROUNDBOX=7,INDIC_SQUIGGLE=1,INDIC_SQUIGGLELOW=11,INDIC_SQUIGGLEPIXMAP=13,INDIC_STRAIGHTBOX=8,INDIC_STRIKE=4,INDIC_TEXTFORE=17,INDIC_TT=2,IV_LOOKBOTH=3,IV_LOOKFORWARD=2,IV_NONE=0,IV_REAL=1,LASTSTEPINUNDOREDO=0x100,MARGINOPTION_NONE=0,MARGINOPTION_SUBLINESELECT=1,MARGIN_BACK=2,MARGIN_FORE=3,MARGIN_NUMBER=1,MARGIN_RTEXT=5,MARGIN_SYMBOL=0,MARGIN_TEXT=4,MARKER_MAX=31,MARKNUM_FOLDER=30,MARKNUM_FOLDEREND=25,MARKNUM_FOLDERMIDTAIL=27,MARKNUM_FOLDEROPEN=31,MARKNUM_FOLDEROPENMID=26,MARKNUM_FOLDERSUB=29,MARKNUM_FOLDERTAIL=28,MARK_ARROW=2,MARK_ARROWDOWN=6,MARK_ARROWS=24,MARK_AVAILABLE=28,MARK_BACKGROUND=22,MARK_BOOKMARK=31,MARK_BOXMINUS=14,MARK_BOXMINUSCONNECTED=15,MARK_BOXPLUS=12,MARK_BOXPLUSCONNECTED=13,MARK_CHARACTER=10000,MARK_CIRCLE=0,MARK_CIRCLEMINUS=20,MARK_CIRCLEMINUSCONNECTED=21,MARK_CIRCLEPLUS=18,MARK_CIRCLEPLUSCONNECTED=19,MARK_DOTDOTDOT=23,MARK_EMPTY=5,MARK_FULLRECT=26,MARK_LCORNER=10,MARK_LCORNERCURVE=16,MARK_LEFTRECT=27,MARK_MINUS=7,MARK_PIXMAP=25,MARK_PLUS=8,MARK_RGBAIMAGE=30,MARK_ROUNDRECT=1,MARK_SHORTARROW=4,MARK_SMALLRECT=3,MARK_TCORNER=11,MARK_TCORNERCURVE=17,MARK_UNDERLINE=29,MARK_VLINE=9,MASK_FOLDERS=-33554432,MAX_MARGIN=4,MODEVENTMASKALL=0x3FFFFF,MOD_ALT=4,MOD_BEFOREDELETE=0x800,MOD_BEFOREINSERT=0x400,MOD_CHANGEANNOTATION=0x20000,MOD_CHANGEFOLD=0x8,MOD_CHANGEINDICATOR=0x4000,MOD_CHANGELINESTATE=0x8000,MOD_CHANGEMARGIN=0x10000,MOD_CHANGEMARKER=0x200,MOD_CHANGESTYLE=0x4,MOD_CHANGETABSTOPS=0x200000,MOD_CONTAINER=0x40000,MOD_CTRL=2,MOD_DELETETEXT=0x2,MOD_INSERTCHECK=0x100000,MOD_INSERTTEXT=0x1,MOD_LEXERSTATE=0x80000,MOD_META=16,MOD_NORM=0,MOD_SHIFT=1,MOD_SUPER=8,MOUSE_DRAG=2,MOUSE_PRESS=1,MOUSE_RELEASE=3,MULTIAUTOC_EACH=1,MULTIAUTOC_ONCE=0,MULTILINEUNDOREDO=0x1000,MULTIPASTE_EACH=1,MULTIPASTE_ONCE=0,MULTISTEPUNDOREDO=0x80,ORDER_CUSTOM=2,ORDER_PERFORMSORT=1,ORDER_PRESORTED=0,PERFORMED_REDO=0x40,PERFORMED_UNDO=0x20,PERFORMED_USER=0x10,SCN_AUTOCCANCELLED=2025,SCN_AUTOCCHARDELETED=2026,SCN_AUTOCSELECTION=2022,SCN_CALLTIPCLICK=2021,SCN_CHARADDED=2001,SCN_DOUBLECLICK=2006,SCN_DWELLEND=2017,SCN_DWELLSTART=2016,SCN_FOCUSIN=2028,SCN_FOCUSOUT=2029,SCN_HOTSPOTCLICK=2019,SCN_HOTSPOTDOUBLECLICK=2020,SCN_HOTSPOTRELEASECLICK=2027,SCN_INDICATORCLICK=2023,SCN_INDICATORRELEASE=2024,SCN_KEY=2005,SCN_MACRORECORD=2009,SCN_MARGINCLICK=2010,SCN_MODIFIED=2008,SCN_MODIFYATTEMPTRO=2004,SCN_NEEDSHOWN=2011,SCN_PAINTED=2013,SCN_SAVEPOINTLEFT=2003,SCN_SAVEPOINTREACHED=2002,SCN_STYLENEEDED=2000,SCN_UPDATEUI=2007,SCN_URIDROPPED=2015,SCN_USERLISTSELECTION=2014,SCN_ZOOM=2018,SEL_LINES=2,SEL_RECTANGLE=1,SEL_STREAM=0,SEL_THIN=3,STARTACTION=0x2000,STYLE_BRACEBAD=35,STYLE_BRACELIGHT=34,STYLE_CALLTIP=38,STYLE_CONTROLCHAR=36,STYLE_DEFAULT=32,STYLE_INDENTGUIDE=37,STYLE_LASTPREDEFINED=39,STYLE_LINENUMBER=33,STYLE_MAX=255,TIME_FOREVER=10000000,UPDATE_CONTENT=0x1,UPDATE_H_SCROLL=0x8,UPDATE_SELECTION=0x2,UPDATE_V_SCROLL=0x4,VISIBLE_SLOP=0x01,VISIBLE_STRICT=0x04,VS_NONE=0,VS_RECTANGULARSELECTION=1,VS_USERACCESSIBLE=2,WRAPINDENT_FIXED=0,WRAPINDENT_INDENT=2,WRAPINDENT_SAME=1,WRAPVISUALFLAGLOC_DEFAULT=0x0000,WRAPVISUALFLAGLOC_END_BY_TEXT=0x0001,WRAPVISUALFLAGLOC_START_BY_TEXT=0x0002,WRAPVISUALFLAG_END=0x0001,WRAPVISUALFLAG_MARGIN=0x0004,WRAPVISUALFLAG_NONE=0x0000,WRAPVISUALFLAG_START=0x0002,WRAP_CHAR=2,WRAP_NONE=0,WRAP_WHITESPACE=3,WRAP_WORD=1,WS_INVISIBLE=0,WS_VISIBLEAFTERINDENT=2,WS_VISIBLEALWAYS=1}
---
-- Map of Scintilla function names to tables containing their IDs, return types,
-- wParam types, and lParam types. Types are as follows:
--
-- + `0`: Void.
-- + `1`: Integer.
-- + `2`: Length of the given lParam string.
-- + `3`: Integer position.
-- + `4`: Color, in "0xBBGGRR" format.
-- + `5`: Boolean `true` or `false`.
-- + `6`: Bitmask of Scintilla key modifiers and a key value.
-- + `7`: String parameter.
-- + `8`: String return value.
-- @class table
-- @name functions
M.functions = {add_ref_document={2376,0,0,1},add_selection={2573,1,1,1},add_styled_text={2002,0,2,9},add_tab_stop={2676,0,1,1},add_text={2001,0,2,7},add_undo_action={2560,0,1,1},allocate={2446,0,1,0},allocate_extended_styles={2553,1,1,0},allocate_sub_styles={4020,1,1,1},annotation_clear_all={2547,0,0,0},append_text={2282,0,2,7},assign_cmd_key={2070,0,6,1},auto_c_active={2102,5,0,0},auto_c_cancel={2101,0,0,0},auto_c_complete={2104,0,0,0},auto_c_pos_start={2103,3,0,0},auto_c_select={2108,0,0,7},auto_c_show={2100,0,1,7},auto_c_stops={2105,0,0,7},back_tab={2328,0,0,0},begin_undo_action={2078,0,0,0},brace_bad_light={2352,0,3,0},brace_bad_light_indicator={2499,0,5,1},brace_highlight={2351,0,3,3},brace_highlight_indicator={2498,0,5,1},brace_match={2353,3,3,0},call_tip_active={2202,5,0,0},call_tip_cancel={2201,0,0,0},call_tip_pos_start={2203,3,0,0},call_tip_set_hlt={2204,0,1,1},call_tip_show={2200,0,3,7},can_paste={2173,5,0,0},can_redo={2016,5,0,0},can_undo={2174,5,0,0},cancel={2325,0,0,0},change_insertion={2672,0,2,7},change_lexer_state={2617,1,3,3},char_left={2304,0,0,0},char_left_extend={2305,0,0,0},char_left_rect_extend={2428,0,0,0},char_position_from_point={2561,3,1,1},char_position_from_point_close={2562,3,1,1},char_right={2306,0,0,0},char_right_extend={2307,0,0,0},char_right_rect_extend={2429,0,0,0},choose_caret_x={2399,0,0,0},clear={2180,0,0,0},clear_all={2004,0,0,0},clear_all_cmd_keys={2072,0,0,0},clear_cmd_key={2071,0,6,0},clear_document_style={2005,0,0,0},clear_registered_images={2408,0,0,0},clear_representation={2667,0,7,0},clear_selections={2571,0,0,0},clear_tab_stops={2675,0,1,0},colourise={4003,0,3,3},contracted_fold_next={2618,1,1,0},convert_eols={2029,0,1,0},copy={2178,0,0,0},copy_allow_line={2519,0,0,0},copy_range={2419,0,3,3},copy_text={2420,0,2,7},count_characters={2633,1,1,1},create_document={2375,1,0,0},create_loader={2632,1,1,0},cut={2177,0,0,0},del_line_left={2395,0,0,0},del_line_right={2396,0,0,0},del_word_left={2335,0,0,0},del_word_right={2336,0,0,0},del_word_right_end={2518,0,0,0},delete_back={2326,0,0,0},delete_back_not_line={2344,0,0,0},delete_range={2645,0,3,1},describe_key_word_sets={4017,1,0,8},describe_property={4016,1,7,8},doc_line_from_visible={2221,1,1,0},document_end={2318,0,0,0},document_end_extend={2319,0,0,0},document_start={2316,0,0,0},document_start_extend={2317,0,0,0},drop_selection_n={2671,0,1,0},edit_toggle_overtype={2324,0,0,0},empty_undo_buffer={2175,0,0,0},encoded_from_utf8={2449,1,7,8},end_undo_action={2079,0,0,0},ensure_visible={2232,0,1,0},ensure_visible_enforce_policy={2234,0,1,0},expand_children={2239,0,1,1},find_column={2456,1,1,1},find_indicator_flash={2641,0,3,3},find_indicator_hide={2642,0,0,0},find_indicator_show={2640,0,3,3},find_text={2150,3,1,11},fold_all={2662,0,1,0},fold_children={2238,0,1,1},fold_line={2237,0,1,1},form_feed={2330,0,0,0},format_range={2151,3,5,12},free_sub_styles={4023,0,0,0},get_cur_line={2027,1,2,8},get_hotspot_active_back={2495,4,0,0},get_hotspot_active_fore={2494,4,0,0},get_last_child={2224,1,1,1},get_line={2153,1,1,8},get_line_sel_end_position={2425,3,1,0},get_line_sel_start_position={2424,3,1,0},get_next_tab_stop={2677,1,1,1},get_range_pointer={2643,1,1,1},get_sel_text={2161,1,0,8},get_styled_text={2015,1,0,10},get_text={2182,1,2,8},get_text_range={2162,1,0,10},goto_line={2024,0,1,0},goto_pos={2025,0,3,0},grab_focus={2400,0,0,0},hide_lines={2227,0,1,1},hide_selection={2163,0,5,0},home={2312,0,0,0},home_display={2345,0,0,0},home_display_extend={2346,0,0,0},home_extend={2313,0,0,0},home_rect_extend={2430,0,0,0},home_wrap={2349,0,0,0},home_wrap_extend={2450,0,0,0},indicator_all_on_for={2506,1,1,0},indicator_clear_range={2505,0,1,1},indicator_end={2509,1,1,1},indicator_fill_range={2504,0,1,1},indicator_start={2508,1,1,1},indicator_value_at={2507,1,1,1},insert_text={2003,0,3,7},is_range_word={2691,5,3,3},line_copy={2455,0,0,0},line_cut={2337,0,0,0},line_delete={2338,0,0,0},line_down={2300,0,0,0},line_down_extend={2301,0,0,0},line_down_rect_extend={2426,0,0,0},line_duplicate={2404,0,0,0},line_end={2314,0,0,0},line_end_display={2347,0,0,0},line_end_display_extend={2348,0,0,0},line_end_extend={2315,0,0,0},line_end_rect_extend={2432,0,0,0},line_end_wrap={2451,0,0,0},line_end_wrap_extend={2452,0,0,0},line_from_position={2166,1,3,0},line_length={2350,1,1,0},line_scroll={2168,0,1,1},line_scroll_down={2342,0,0,0},line_scroll_up={2343,0,0,0},line_transpose={2339,0,0,0},line_up={2302,0,0,0},line_up_extend={2303,0,0,0},line_up_rect_extend={2427,0,0,0},lines_join={2288,0,0,0},lines_split={2289,0,1,0},load_lexer_library={4007,0,0,7},lower_case={2340,0,0,0},margin_text_clear_all={2536,0,0,0},marker_add={2043,1,1,1},marker_add_set={2466,0,1,1},marker_define={2040,0,1,1},marker_define_pixmap={2049,0,1,7},marker_define_rgba_image={2626,0,1,7},marker_delete={2044,0,1,1},marker_delete_all={2045,0,1,0},marker_delete_handle={2018,0,1,0},marker_enable_highlight={2293,0,5,0},marker_get={2046,1,1,0},marker_line_from_handle={2017,1,1,0},marker_next={2047,1,1,1},marker_previous={2048,1,1,1},marker_symbol_defined={2529,1,1,0},move_caret_inside_view={2401,0,0,0},move_selected_lines_down={2621,0,0,0},move_selected_lines_up={2620,0,0,0},multiple_select_add_each={2689,0,0,0},multiple_select_add_next={2688,0,0,0},new_line={2329,0,0,0},null={2172,0,0,0},page_down={2322,0,0,0},page_down_extend={2323,0,0,0},page_down_rect_extend={2434,0,0,0},page_up={2320,0,0,0},page_up_extend={2321,0,0,0},page_up_rect_extend={2433,0,0,0},para_down={2413,0,0,0},para_down_extend={2414,0,0,0},para_up={2415,0,0,0},para_up_extend={2416,0,0,0},paste={2179,0,0,0},point_x_from_position={2164,1,0,3},point_y_from_position={2165,1,0,3},position_after={2418,3,3,0},position_before={2417,3,3,0},position_from_line={2167,3,1,0},position_from_point={2022,3,1,1},position_from_point_close={2023,3,1,1},position_relative={2670,3,3,1},private_lexer_call={4013,1,1,1},property_names={4014,1,0,8},property_type={4015,1,7,0},redo={2011,0,0,0},register_image={2405,0,1,7},register_rgba_image={2627,0,1,7},release_all_extended_styles={2552,0,0,0},release_document={2377,0,0,1},replace_sel={2170,0,0,7},replace_target={2194,1,2,7},replace_target_re={2195,1,2,7},rotate_selection={2606,0,0,0},scroll_caret={2169,0,0,0},scroll_range={2569,0,3,3},scroll_to_end={2629,0,0,0},scroll_to_start={2628,0,0,0},search_anchor={2366,0,0,0},search_in_target={2197,1,2,7},search_next={2367,1,1,7},search_prev={2368,1,1,7},select_all={2013,0,0,0},selection_duplicate={2469,0,0,0},set_chars_default={2444,0,0,0},set_empty_selection={2556,0,3,0},set_fold_margin_colour={2290,0,5,4},set_fold_margin_hi_colour={2291,0,5,4},set_hotspot_active_back={2411,0,5,4},set_hotspot_active_fore={2410,0,5,4},set_length_for_encode={2448,0,1,0},set_save_point={2014,0,0,0},set_sel={2160,0,3,3},set_sel_back={2068,0,5,4},set_sel_fore={2067,0,5,4},set_selection={2572,1,1,1},set_styling={2033,0,2,1},set_styling_ex={2073,0,2,7},set_target_range={2686,0,3,3},set_text={2181,0,0,7},set_visible_policy={2394,0,1,1},set_whitespace_back={2085,0,5,4},set_whitespace_fore={2084,0,5,4},set_x_caret_policy={2402,0,1,1},set_y_caret_policy={2403,0,1,1},show_lines={2226,0,1,1},start_record={3001,0,0,0},start_styling={2032,0,3,1},stop_record={3002,0,0,0},stuttered_page_down={2437,0,0,0},stuttered_page_down_extend={2438,0,0,0},stuttered_page_up={2435,0,0,0},stuttered_page_up_extend={2436,0,0,0},style_clear_all={2050,0,0,0},style_reset_default={2058,0,0,0},swap_main_anchor_caret={2607,0,0,0},tab={2327,0,0,0},target_as_utf8={2447,1,0,8},target_from_selection={2287,0,0,0},target_whole_document={2690,0,0,0},text_height={2279,1,1,0},text_width={2276,1,1,7},toggle_caret_sticky={2459,0,0,0},toggle_fold={2231,0,1,0},undo={2176,0,0,0},upper_case={2341,0,0,0},use_pop_up={2371,0,5,0},user_list_show={2117,0,1,7},vc_home={2331,0,0,0},vc_home_display={2652,0,0,0},vc_home_display_extend={2653,0,0,0},vc_home_extend={2332,0,0,0},vc_home_rect_extend={2431,0,0,0},vc_home_wrap={2453,0,0,0},vc_home_wrap_extend={2454,0,0,0},vertical_centre_caret={2619,0,0,0},visible_from_doc_line={2220,1,1,0},word_end_position={2267,1,3,5},word_left={2308,0,0,0},word_left_end={2439,0,0,0},word_left_end_extend={2440,0,0,0},word_left_extend={2309,0,0,0},word_part_left={2390,0,0,0},word_part_left_extend={2391,0,0,0},word_part_right={2392,0,0,0},word_part_right_extend={2393,0,0,0},word_right={2310,0,0,0},word_right_end={2441,0,0,0},word_right_end_extend={2442,0,0,0},word_right_extend={2311,0,0,0},word_start_position={2266,1,3,5},wrap_count={2235,1,1,0},zoom_in={2333,0,0,0},zoom_out={2334,0,0,0},}
---
-- Map of Scintilla property names to table values containing their "get"
-- function IDs, "set" function IDs, return types, and wParam types.
-- The wParam type will be non-zero if the property is indexable.
-- Types are the same as in the `functions` table.
-- @see functions
-- @class table
-- @name properties
M.properties = {additional_caret_fore={2605,2604,4,0},additional_carets_blink={2568,2567,5,0},additional_carets_visible={2609,2608,5,0},additional_sel_alpha={2603,2602,1,0},additional_sel_back={0,2601,4,0},additional_sel_fore={0,2600,4,0},additional_selection_typing={2566,2565,5,0},all_lines_visible={2236,0,5,0},anchor={2009,2026,3,0},annotation_lines={2546,0,1,1},annotation_style={2543,2542,1,1},annotation_style_offset={2551,2550,1,0},annotation_styles={2545,2544,8,1},annotation_text={2541,2540,8,1},annotation_visible={2549,2548,1,0},auto_c_auto_hide={2119,2118,5,0},auto_c_cancel_at_start={2111,2110,5,0},auto_c_case_insensitive_behaviour={2635,2634,1,0},auto_c_choose_single={2114,2113,5,0},auto_c_current={2445,0,1,0},auto_c_current_text={2610,0,8,0},auto_c_drop_rest_of_word={2271,2270,5,0},auto_c_fill_ups={0,2112,7,0},auto_c_ignore_case={2116,2115,5,0},auto_c_max_height={2211,2210,1,0},auto_c_max_width={2209,2208,1,0},auto_c_multi={2637,2636,1,0},auto_c_order={2661,2660,1,0},auto_c_separator={2107,2106,1,0},auto_c_type_separator={2285,2286,1,0},automatic_fold={2664,2663,1,0},back_space_un_indents={2263,2262,5,0},buffered_draw={2034,2035,5,0},call_tip_back={0,2205,4,0},call_tip_fore={0,2206,4,0},call_tip_fore_hlt={0,2207,4,0},call_tip_pos_start={0,2214,1,0},call_tip_position={0,2213,5,0},call_tip_use_style={0,2212,1,0},caret_fore={2138,2069,4,0},caret_line_back={2097,2098,4,0},caret_line_back_alpha={2471,2470,1,0},caret_line_visible={2095,2096,5,0},caret_line_visible_always={2654,2655,5,0},caret_period={2075,2076,1,0},caret_sticky={2457,2458,1,0},caret_style={2513,2512,1,0},caret_width={2189,2188,1,0},char_at={2007,0,1,3},character_pointer={2520,0,1,0},code_page={2137,2037,1,0},column={2129,0,1,3},control_char_symbol={2389,2388,1,0},current_pos={2008,2141,3,0},cursor={2387,2386,1,0},direct_function={2184,0,1,0},direct_pointer={2185,0,1,0},distance_to_secondary_styles={4025,0,1,0},doc_pointer={2357,2358,1,0},edge_colour={2364,2365,4,0},edge_column={2360,2361,1,0},edge_mode={2362,2363,1,0},end_at_last_line={2278,2277,5,0},end_styled={2028,0,3,0},eol_mode={2030,2031,1,0},extra_ascent={2526,2525,1,0},extra_descent={2528,2527,1,0},first_visible_line={2152,2613,1,0},focus={2381,2380,5,0},fold_expanded={2230,2229,5,1},fold_flags={0,2233,1,0},fold_level={2223,2222,1,1},fold_parent={2225,0,1,1},font_quality={2612,2611,1,0},gap_position={2644,0,3,0},h_scroll_bar={2131,2130,5,0},highlight_guide={2135,2134,1,0},hotspot_active_underline={2496,2412,5,0},hotspot_single_line={2497,2421,5,0},identifier={2623,2622,1,0},identifiers={0,4024,7,1},ime_interaction={2678,2679,1,0},indent={2123,2122,1,0},indentation_guides={2133,2132,1,0},indic_alpha={2524,2523,1,1},indic_flags={2685,2684,1,1},indic_fore={2083,2082,4,1},indic_hover_fore={2683,2682,4,1},indic_hover_style={2681,2680,1,1},indic_outline_alpha={2559,2558,1,1},indic_style={2081,2080,1,1},indic_under={2511,2510,5,1},indicator_current={2501,2500,1,0},indicator_value={2503,2502,1,0},key_words={0,4005,7,1},layout_cache={2273,2272,1,0},length={2006,0,1,0},lexer={4002,4001,1,0},lexer_language={4012,4006,8,0},line_count={2154,0,1,0},line_end_position={2136,0,3,1},line_end_types_active={2658,0,1,0},line_end_types_allowed={2657,2656,1,0},line_end_types_supported={4018,0,1,0},line_indent_position={2128,0,3,1},line_indentation={2127,2126,1,1},line_state={2093,2092,1,1},line_visible={2228,0,5,1},lines_on_screen={2370,0,1,0},main_selection={2575,2574,1,0},margin_cursor_n={2249,2248,1,1},margin_left={2156,2155,1,0},margin_mask_n={2245,2244,1,1},margin_options={2557,2539,1,0},margin_right={2158,2157,1,0},margin_sensitive_n={2247,2246,5,1},margin_style={2533,2532,1,1},margin_style_offset={2538,2537,1,0},margin_styles={2535,2534,8,1},margin_text={2531,2530,8,1},margin_type_n={2241,2240,1,1},margin_width_n={2243,2242,1,1},marker_alpha={0,2476,1,1},marker_back={0,2042,4,1},marker_back_selected={0,2292,4,1},marker_fore={0,2041,4,1},max_line_state={2094,0,1,0},mod_event_mask={2378,2359,1,0},modify={2159,0,5,0},mouse_down_captures={2385,2384,5,0},mouse_dwell_time={2265,2264,1,0},mouse_selection_rectangular_switch={2669,2668,5,0},multi_paste={2615,2614,1,0},multiple_selection={2564,2563,5,0},overtype={2187,2186,5,0},paste_convert_endings={2468,2467,5,0},phases_draw={2673,2674,1,0},position_cache={2515,2514,1,0},primary_style_from_style={4028,0,1,1},print_colour_mode={2149,2148,1,0},print_magnification={2147,2146,1,0},print_wrap_mode={2407,2406,1,0},property={4008,4004,8,7},property_expanded={4009,0,8,7},property_int={4010,0,1,7},punctuation_chars={2649,2648,8,0},read_only={2140,2171,5,0},rectangular_selection_anchor={2591,2590,3,0},rectangular_selection_anchor_virtual_space={2595,2594,1,0},rectangular_selection_caret={2589,2588,3,0},rectangular_selection_caret_virtual_space={2593,2592,1,0},rectangular_selection_modifier={2599,2598,1,0},representation={2666,2665,8,7},rgba_image_height={0,2625,1,0},rgba_image_scale={0,2651,1,0},rgba_image_width={0,2624,1,0},scroll_width={2275,2274,1,0},scroll_width_tracking={2517,2516,5,0},search_flags={2199,2198,1,0},sel_alpha={2477,2478,1,0},sel_eol_filled={2479,2480,5,0},selection_empty={2650,0,5,0},selection_end={2145,2144,3,0},selection_is_rectangle={2372,0,5,0},selection_mode={2423,2422,1,0},selection_n_anchor={2579,2578,3,1},selection_n_anchor_virtual_space={2583,2582,1,1},selection_n_caret={2577,2576,3,1},selection_n_caret_virtual_space={2581,2580,1,1},selection_n_end={2587,2586,3,1},selection_n_start={2585,2584,3,1},selection_start={2143,2142,3,0},selections={2570,0,1,0},status={2383,2382,1,0},style_at={2010,0,1,3},style_back={2482,2052,4,1},style_bits={2091,2090,1,0},style_bits_needed={4011,0,1,0},style_bold={2483,2053,5,1},style_case={2489,2060,1,1},style_changeable={2492,2099,5,1},style_character_set={2490,2066,1,1},style_eol_filled={2487,2057,5,1},style_font={2486,2056,8,1},style_fore={2481,2051,4,1},style_from_sub_style={4027,0,1,1},style_hot_spot={2493,2409,5,1},style_italic={2484,2054,5,1},style_size={2485,2055,1,1},style_size_fractional={2062,2061,1,1},style_underline={2488,2059,5,1},style_visible={2491,2074,5,1},style_weight={2064,2063,1,1},sub_style_bases={4026,0,8,0},sub_styles_length={4022,0,1,1},sub_styles_start={4021,0,1,1},tab_indents={2261,2260,5,0},tab_width={2121,2036,1,0},tag={2616,0,8,1},target_end={2193,2192,3,0},target_start={2191,2190,3,0},target_text={2687,0,8,0},technology={2631,2630,1,0},text_length={2183,0,1,0},two_phase_draw={2283,2284,5,0},undo_collection={2019,2012,5,0},use_tabs={2125,2124,5,0},v_scroll_bar={2281,2280,5,0},view_eol={2355,2356,5,0},view_ws={2020,2021,1,0},virtual_space_options={2597,2596,1,0},whitespace_chars={2647,2443,8,0},whitespace_size={2087,2086,1,0},word_chars={2646,2077,8,0},wrap_indent_mode={2473,2472,1,0},wrap_mode={2269,2268,1,0},wrap_start_indent={2465,2464,1,0},wrap_visual_flags={2461,2460,1,0},wrap_visual_flags_location={2463,2462,1,0},x_offset={2398,2397,1,0},zoom={2374,2373,1,0},}
local marker_number, indic_number, list_type, image_type = -1, -1, 0, 0
---
-- Returns a unique marker number for use with `buffer.marker_define()`.
-- Use this function for custom markers in order to prevent clashes with
-- identifiers of other custom markers.
-- @usage local marknum = _SCINTILLA.next_marker_number()
-- @see buffer.marker_define
-- @name next_marker_number
function M.next_marker_number()
marker_number = marker_number + 1
return marker_number
end
---
-- Returns a unique indicator number for use with custom indicators.
-- Use this function for custom indicators in order to prevent clashes with
-- identifiers of other custom indicators.
-- @usage local indic_num = _SCINTILLA.next_indic_number()
-- @see buffer.indic_style
-- @name next_indic_number
function M.next_indic_number()
indic_number = indic_number + 1
return indic_number
end
---
-- Returns a unique user list identier number for use with
-- `buffer.user_list_show()`.
-- Use this function for custom user lists in order to prevent clashes with
-- list identifiers of other custom user lists.
-- @usage local list_type = _SCINTILLA.next_user_list_type()
-- @see buffer.user_list_show
-- @name next_user_list_type
function M.next_user_list_type()
list_type = list_type + 1
return list_type
end
---
-- Returns a unique image type identier number for use with
-- `buffer.register_image()` and `buffer.register_rgba_image()`.
-- Use this function for custom image types in order to prevent clashes with
-- identifiers of other custom image types.
-- @usage local image_type = _SCINTILLA.next_image_type()
-- @see buffer.register_image
-- @see buffer.register_rgba_image
-- @name next_image_type
function M.next_image_type()
image_type = image_type + 1
return image_type
end
return M
| mit |
lukw00/shogun | examples/undocumented/lua_modular/serialization_complex_example.lua | 21 | 2932 | require 'os'
require 'modshogun'
require 'load'
parameter_list={{5,1,10, 2.0, 10}, {10,0.3,2, 1.0, 0.1}}
function check_status(status)
assert(status == true)
-- if status:
-- print "OK reading/writing .h5\n"
--else:
-- print "ERROR reading/writing .h5\n"
end
function concatenate(...)
local result = ...
for _,t in ipairs{select(2, ...)} do
for row,rowdata in ipairs(t) do
for col,coldata in ipairs(rowdata) do
table.insert(result[row], coldata)
end
end
end
return result
end
function rand_matrix(rows, cols, dist)
local matrix = {}
for i = 1, rows do
matrix[i] = {}
for j = 1, cols do
matrix[i][j] = math.random() + dist
end
end
return matrix
end
function generate_lab(num)
lab={}
for i=1,num do
lab[i]=0
end
for i=num+1,2*num do
lab[i]=1
end
for i=2*num+1,3*num do
lab[i]=2
end
for i=3*num+1,4*num do
lab[i]=3
end
return lab
end
function serialization_complex_example(num, dist, dim, C, width)
math.randomseed(17)
data=concatenate(rand_matrix(dim, num, 0), rand_matrix(dim, num, dist), rand_matrix(dim, num, 2 * dist), rand_matrix(dim, num, 3 * dist))
lab=generate_lab(num)
feats=modshogun.RealFeatures(data)
kernel=modshogun.GaussianKernel(feats, feats, width)
labels=modshogun.MulticlassLabels(lab)
svm = modshogun.GMNPSVM(C, kernel, labels)
feats:add_preprocessor(modshogun.NormOne())
feats:add_preprocessor(modshogun.LogPlusOne())
feats:set_preprocessed(1)
svm:train(feats)
fstream = modshogun.SerializableHdf5File("blaah.h5", "w")
status = svm:save_serializable(fstream)
check_status(status)
fstream = modshogun.SerializableAsciiFile("blaah.asc", "w")
status = svm:save_serializable(fstream)
check_status(status)
-- fstream = modshogun.SerializableJsonFile("blaah.json", "w")
-- status = svm:save_serializable(fstream)
-- check_status(status)
fstream = modshogun.SerializableXmlFile("blaah.xml", "w")
status = svm:save_serializable(fstream)
check_status(status)
fstream = modshogun.SerializableHdf5File("blaah.h5", "r")
new_svm=modshogun.GMNPSVM()
status = new_svm:load_serializable(fstream)
check_status(status)
new_svm:train()
fstream = modshogun.SerializableAsciiFile("blaah.asc", "r")
new_svm=modshogun.GMNPSVM()
status = new_svm:load_serializable(fstream)
check_status(status)
new_svm:train()
-- fstream = modshogun.SerializableJsonFile("blaah.json", "r")
-- new_svm=modshogun.GMNPSVM()
-- status = new_svm:load_serializable(fstream)
-- check_status(status)
-- new_svm:train()
fstream = modshogun.SerializableXmlFile("blaah.xml", "r")
new_svm=modshogun.GMNPSVM()
status = new_svm:load_serializable(fstream)
check_status(status)
new_svm:train()
os.remove("blaah.h5")
os.remove("blaah.asc")
-- os.remove("blaah.json")
os.remove("blaah.xml")
return svm,new_svm
end
if debug.getinfo(3) == nill then
print 'Serialization SVMLight'
serialization_complex_example(unpack(parameter_list[1]))
end
| gpl-3.0 |
anoutsider/advanced-logistics-system | gui/widgets.lua | 1 | 21761 | --- Add items search frame
function addSearchWidget(player, index)
local guiPos = global.settings[index].guiPos
local contentFrame = player.gui[guiPos].logisticsFrame.contentFrame
local searchFlow = contentFrame["searchFlow"]
local currentTab = global.currentTab[index]
local searchText = global.searchText[index][currentTab]
searchText = searchText and searchText or ""
if searchFlow == nil then
searchFlow = contentFrame.add({type = "flow", name = "searchFlow", style = "als_info_flow", direction = "horizontal"})
-- remove old search frame
local oldSearchFrame = contentFrame[currentTab .. "SearchFrame"]
if oldSearchFrame ~= nil then
oldSearchFrame.destroy()
end
end
for _,tab in pairs(global.guiTabs) do
if tab ~= currentTab and searchFlow[tab .. "SearchFrame"] ~= nil then
searchFlow[tab .. "SearchFrame"].style = "als_search_frame_hidden"
-- remove old search frame
local oldSearchFrame = contentFrame[tab .. "SearchFrame"]
if oldSearchFrame ~= nil then
oldSearchFrame.destroy()
end
end
end
--add search frame
local searchFrame = searchFlow[currentTab .. "SearchFrame"]
if searchFrame == nil then
searchFrame = searchFlow.add({type = "frame", name = currentTab .. "SearchFrame", style = "als_search_frame", direction = "horizontal"})
searchFrame.add({type = "label", name = currentTab .. "SearchFrameLabel", style = "als_search_label", caption = {"search-label"}})
end
searchFrame.style = "als_search_frame"
--add search field
local searchField = searchFlow[currentTab .. "SearchFrame"][currentTab .. "-search-field"]
if searchField == nil then
searchField = searchFrame.add({type = "textfield", name = currentTab .. "-search-field", style = "als_searchfield_style", text = searchText })
end
end
--- Add networks search frame
function addNetworkSearchWidget(player, index)
local guiPos = global.settings[index].guiPos
local contentFrame = player.gui[guiPos].logisticsFrame.contentFrame
local searchFlow = contentFrame["searchFlow"]
local searchText = global.searchText[index]["networks"]
searchText = searchText and searchText or ""
if searchFlow == nil then
searchFlow = contentFrame.add({type = "flow", name = "searchFlow", style = "als_info_flow", direction = "horizontal"})
end
--add search frame
local searchFrame = searchFlow["networksSearchFrame"]
if searchFrame == nil then
searchFrame = searchFlow.add({type = "frame", name = "networksSearchFrame", style = "als_search_frame", direction = "horizontal"})
searchFrame.add({type = "label", name = "networksSearchFrameLabel", style = "als_search_label", caption = {"search-label"}})
end
--add search field
local searchField = searchFlow["networksSearchFrame"]["networks-search-field"]
if searchField == nil then
searchField = searchFrame.add({type = "textfield", name = "networks-search-field", style = "als_searchfield_style", text = searchText })
end
end
--- Show items info frame
function addItemsInfoWidget(player, index)
local guiPos = global.settings[index].guiPos
local force = player.force.name
local contentFrame = player.gui[guiPos].logisticsFrame.contentFrame
local infoFlow = contentFrame["infoFlow"]
local currentTab = global.currentTab[index]
local total = currentTab == "logistics" and global.logisticsItemsTotal[force] or global.normalItemsTotal[force]
if infoFlow == nil then
infoFlow = contentFrame.add({type = "flow", name = "infoFlow", style = "als_info_flow", direction = "horizontal"})
end
for _,tab in pairs(global.guiTabs) do
if tab ~= currentTab and infoFlow[tab .. "InfoFrame"] ~= nil then
infoFlow[tab .. "InfoFrame"].style = "als_frame_hidden"
end
end
--add info frame
local infoFrame = infoFlow[currentTab .. "InfoFrame"]
if infoFrame ~= nil then
infoFrame.destroy()
end
infoFrame = infoFlow.add({type = "frame", name = currentTab .. "InfoFrame", style = "als_info_frame", direction = "horizontal"})
infoFrame.add({type = "label", name = currentTab .. "InfoFrameTotalLabel", style = "als_info_label", caption = {"info-total"}})
infoFrame.add({type = "label", name = currentTab .. "InfoFrameTotal", style = "label_style", caption = ": " .. number_format(total)})
end
--- Show disconnected chests info frame
function addDisconnectedInfoWidget(player, index)
local guiPos = global.settings[index].guiPos
local force = player.force.name
local contentFrame = player.gui[guiPos].logisticsFrame.contentFrame
local infoFlow = contentFrame["infoFlow"]
local currentTab = global.currentTab[index]
local disconnected = global.disconnectedChests[force]
local disconnectedCount = count(disconnected)
if infoFlow == nil then
infoFlow = contentFrame.add({type = "flow", name = "infoFlow", style = "als_info_flow", direction = "horizontal"})
end
-- remove old disconnected frames
for _,tab in pairs(global.guiTabs) do
if tab ~= currentTab and infoFlow[tab .. "DisconnectedFrame"] ~= nil then
infoFlow[tab .. "DisconnectedFrame"].destroy()
end
end
-- remove disconnected chests info frame
local disconnectedFrame = infoFlow["disconnectedFrame"]
if disconnectedFrame ~= nil then
disconnectedFrame.destroy()
end
-- add disconnected chests info frame
if currentTab == "logistics" or currentTab == "disconnected" and disconnectedCount > 0 then
disconnectedFrame = infoFlow.add({type = "frame", name = "disconnectedFrame", style = "als_info_frame", direction = "horizontal"})
disconnectedFrame.add({type = "label", name = "disconnectedFrameLabel", style = "als_info_label", caption = {"disconnected-chests"}})
disconnectedFrame.add({type = "label", name = "disconnectedFrameTotal", style = "label_style", caption = ": " .. disconnectedCount})
if currentTab == "logistics" then
disconnectedFrame.add({type = "button", name = "disconnectedFrameView", caption = {"view"}, style = "als_button_small"})
end
end
end
--- Show networks info frame
function addNetwroksInfoWidget(player, index, network)
local guiPos = global.settings[index].guiPos
local force = player.force.name
local contentFrame = player.gui[guiPos].logisticsFrame.contentFrame
local infoFlow = contentFrame["infoFlow"]
local currentTab = global.currentTab[index]
local networks = global.networks[force]
local networksCount = global.networksCount[force]
if infoFlow == nil then
infoFlow = contentFrame.add({type = "flow", name = "infoFlow", style = "als_info_flow", direction = "horizontal"})
end
-- remove networks info frame
local netwroksFrame = infoFlow["netwroksFrame"]
if netwroksFrame ~= nil then
netwroksFrame.destroy()
end
-- add networks info frame - logistics
if currentTab == "logistics" and networksCount > 0 then
netwroksFrame = infoFlow.add({type = "frame", name = "netwroksFrame", style = "als_info_frame", direction = "horizontal"})
netwroksFrame.add({type = "label", name = "netwroksFrameLabel", style = "als_info_label", caption = {"networks"}})
netwroksFrame.add({type = "label", name = "netwroksFrameTotal", style = "label_style", caption = ": " .. networksCount})
netwroksFrame.add({type = "button", name = "netwroksFrameView", caption = {"view"}, style = "als_button_small"})
end
-- add networks info frame - networks
if (currentTab == "networks" or currentTab == "networkInfo") and networksCount > 0 then
netwroksFrame = infoFlow.add({type = "frame", name = "netwroksFrame", style = "als_info_frame", direction = "horizontal"})
if currentTab == "networks" then
netwroksFrame.add({type = "label", name = "netwroksFrameLabel", style = "als_info_label", caption = {"networks"}})
netwroksFrame.add({type = "label", name = "netwroksFrameTotal", style = "label_style", caption = ": " .. networksCount})
elseif currentTab == "networkInfo" and network then
netwroksFrame.add({type = "label", name = "netwroksFrameLabel", style = "als_info_label", caption = {"network-name"}})
netwroksFrame.add({type = "label", name = "netwroksFrameTotal", style = "label_style", caption = ": " .. network.name})
end
local logFrame = infoFlow["logFrame"]
if logFrame ~= nil then
logFrame.destroy()
end
local conFrame = infoFlow["conFrame"]
if conFrame ~= nil then
conFrame.destroy()
end
local chargingFrame = infoFlow["chargingFrame"]
if chargingFrame ~= nil then
chargingFrame.destroy()
end
local waitingFrame = infoFlow["waitingFrame"]
if waitingFrame ~= nil then
waitingFrame.destroy()
end
local log_total = 0
local log_av = 0
local con_total = 0
local con_av = 0
local charging = 0
local waiting = 0
if currentTab == "networks" then
for key,network in pairs(networks) do
log_total = log_total + network.bots.log.total
log_av = log_av + network.bots.log.available
con_total = con_total + network.bots.con.total
con_av = con_av + network.bots.con.available
charging = charging + network.charging
waiting = waiting + network.waiting
end
else
if network then
log_total = network.bots.log.total
log_av = network.bots.log.available
con_total = network.bots.con.total
con_av = network.bots.con.available
charging = network.charging
waiting = network.waiting
end
end
log_total = number_format(log_total)
log_av = number_format(log_av)
con_total = number_format(con_total)
con_av = number_format(con_av)
charging = number_format(charging)
waiting = number_format(waiting)
logFrame = infoFlow.add({type = "frame", name = "logFrame", style = "als_info_frame", direction = "horizontal"})
logFrame.add({type = "label", name = "robotsFrameLabelLog", style = "als_info_label", caption = {"network-log"}, tooltip = {"tooltips.net-log-total"}})
logFrame.add({type = "label", name = "robotsFrameTotalLog", style = "label_style", caption = ": " .. log_av .. "/" .. log_total})
conFrame = infoFlow.add({type = "frame", name = "conFrame", style = "als_info_frame", direction = "horizontal"})
conFrame.add({type = "label", name = "robotsFrameLabelCon", style = "als_info_label", caption = {"network-con"}, tooltip = {"tooltips.net-con-total"}})
conFrame.add({type = "label", name = "robotsFrameTotalCon", style = "label_style", caption = ": " .. con_av .. "/" .. con_total})
chargingFrame = infoFlow.add({type = "frame", name = "chargingFrame", style = "als_info_frame", direction = "horizontal"})
chargingFrame.add({type = "label", name = "robotsFrameLabelCharging", style = "als_info_label", caption = {"network-charging"}, tooltip = {"tooltips.net-charging-total"}})
chargingFrame.add({type = "label", name = "robotsFrameTotalCharging", style = "label_style", caption = ": " .. charging})
waitingFrame = infoFlow.add({type = "frame", name = "waitingFrame", style = "als_info_frame", direction = "horizontal"})
waitingFrame.add({type = "label", name = "robotsFrameLabelWaiting", style = "als_info_label", caption = {"network-waiting"}, tooltip = {"tooltips.net-waiting-total"}})
waitingFrame.add({type = "label", name = "robotsFrameTotalWaiting", style = "label_style", caption = ": " .. waiting})
end
end
--- Show item totals info frame
function addItemTotalsInfoWidget(info, player, index)
local guiPos = global.settings[index].guiPos
local contentFrame = player.gui[guiPos].logisticsFrame.contentFrame
local infoFlow = contentFrame["infoFlow"]
local currentTab = global.currentTab[index]
local currentItem = global.currentItem[index]
local total = info["total"]
local orderfunc = function(t,a,b) return t[b] < t[a] end
if infoFlow == nil then
infoFlow = contentFrame.add({type = "flow", name = "infoFlow", style = "als_info_flow", direction = "horizontal"})
end
--add item name info frame
local infoFrameName = infoFlow[currentTab .. "infoFrameName"]
if infoFrameName ~= nil then
infoFrameName.destroy()
end
-- name
infoFrameName = infoFlow.add({type = "frame", name = currentTab .. "infoFrameName", style = "als_info_frame", direction = "horizontal"})
infoFrameName.add({type = "label", name = currentTab .. "infoFrameNameLabel", style = "als_info_label", caption = {"name"}})
infoFrameName.add({type = "label", name = currentTab .. "infoFrameNameValue", style = "label_style", caption = getLocalisedName(currentItem)})
--add "all" total info frame
local infoFrameAll = infoFlow[currentTab .. "InfoFrameAll"]
if infoFrameAll ~= nil then
infoFrameAll.destroy()
end
-- all
infoFrameAll = infoFlow.add({type = "frame", name = currentTab .. "InfoFrameAll", style = "als_info_frame", direction = "horizontal"})
infoFrameAll.add({type = "label", name = currentTab .. "InfoFrameTotalLabel", style = "als_info_label", caption = {"info-total"}})
infoFrameAll.add({type = "label", name = currentTab .. "InfoFrameTotalValue", style = "label_style", caption = ": " .. number_format(total.all)})
for k,v in spairs(total, orderfunc) do
if k ~= "all" then
local key = k:gsub("^%l", string.upper)
local infoFrame = infoFlow[currentTab .. "InfoFrame" .. key]
if infoFrame ~= nil then
infoFrame.destroy()
end
if v > 0 then
infoFrame = infoFlow.add({type = "frame", name = currentTab .. "InfoFrame" .. key, style = "als_info_frame", direction = "horizontal"})
infoFrame.add({type = "label", name = currentTab .. "InfoFrameTotalLabel" .. key, style = "als_info_label", caption = {"info-" .. k}})
infoFrame.add({type = "label", name = currentTab .. "InfoFrameValue" .. key, style = "label_style", caption = ": " .. number_format(v)})
end
end
end
end
--- Show item info filters
function addItemFiltersWidget(player, index)
local guiPos = global.settings[index].guiPos
local contentFrame = player.gui[guiPos].logisticsFrame.contentFrame
local filtersFlow = contentFrame["filtersFlow"]
local currentTab = global.currentTab[index]
local filters = global.itemInfoFilters[index]
if filtersFlow == nil then
filtersFlow = contentFrame.add({type = "flow", name = "filtersFlow", style = "als_info_flow", direction = "horizontal"})
end
local typeFilterFrame = filtersFlow["typeFilterFrame"]
if typeFilterFrame ~= nil then
typeFilterFrame.destroy()
end
local logisticsState = filters["group"]["logistics"] ~= nil
local normalState = filters["group"]["normal"] ~= nil
typeFilterFrame = filtersFlow.add({type = "frame", name = "typeFilterFrame", style = "als_filters_frame", direction = "horizontal"})
typeFilterFrame.add({type = "label", name = "typeFilterFrameLabel", style = "als_info_label", caption = {"filters"}})
typeFilterFrame.add({type = "checkbox", name = "itemInfoFilter_logistics", style = "checkbox_style", caption = {"info-logistics"}, state = logisticsState, tooltip = {"tooltips.filter-by-log"}})
typeFilterFrame.add({type = "checkbox", name = "itemInfoFilter_normal", style = "checkbox_style", caption = {"info-normal"}, state = normalState, tooltip = {"tooltips.filter-by-norm"}})
local chestsFilterFrame = filtersFlow["chestsFilterFrame"]
if chestsFilterFrame ~= nil then
chestsFilterFrame.destroy()
end
local buttonStyle = filters["chests"]["all"] ~= nil and "_selected" or ""
chestsFilterFrame = filtersFlow.add({type = "frame", name = "chestsFilterFrame", style = "als_filters_frame", direction = "horizontal"})
chestsFilterFrame.add({type = "button", name = "itemInfoFilter_all", caption = {"all"}, style = "als_button_all" .. buttonStyle})
for type,codes in pairs(global.codeToName) do
for code,name in pairs(codes) do
if code ~= "name" and code ~= "total" then
local spritePath = getItemSprite(player, name)
if spritePath then
local buttonStyle = filters["chests"][code] ~= nil and "_selected" or ""
chestsFilterFrame.add({type = "sprite-button", name = "itemInfoFilter_" .. code, style = "als_item_icon_small" .. buttonStyle, sprite = spritePath, tooltip = {"tooltips.filter-by", getLocalisedName(name)}})
end
end
end
end
end
--- Show disconnected info filters
function addDisconnectedFiltersWidget(player, index)
local guiPos = global.settings[index].guiPos
local contentFrame = player.gui[guiPos].logisticsFrame.contentFrame
local filtersFlow = contentFrame["filtersFlow"]
local currentTab = global.currentTab[index]
local filters = global.disconnectedFilters[index]
if filtersFlow == nil then
filtersFlow = contentFrame.add({type = "flow", name = "filtersFlow", style = "als_info_flow", direction = "horizontal"})
end
local chestsFilterFrame = filtersFlow["chestsFilterFrame"]
if chestsFilterFrame ~= nil then
chestsFilterFrame.destroy()
end
local buttonStyle = filters["chests"]["all"] ~= nil and "_selected" or ""
chestsFilterFrame = filtersFlow.add({type = "frame", name = "chestsFilterFrame", style = "als_filters_frame", direction = "horizontal"})
chestsFilterFrame.add({type = "label", name = "chestsFilterFrameLabel", style = "als_info_label", caption = {"filters"}})
chestsFilterFrame.add({type = "button", name = "disconnectedFilter_all", caption = {"all"}, style = "als_button_all" .. buttonStyle})
for code,name in pairs(global.codeToName.logistics) do
if code ~= "name" and code ~= "total" then
local spritePath = getItemSprite(player, name)
if spritePath then
local buttonStyle = filters["chests"][code] ~= nil and "_selected" or ""
chestsFilterFrame.add({type = "sprite-button", name = "disconnectedFilter_" .. code, style = "als_item_icon_small" .. buttonStyle, sprite = spritePath, tooltip = {"tooltips.filter-by", getLocalisedName(name)}})
end
end
end
end
--- Show network filters info
function addNetworkFiltersWidget(player, index)
local guiPos = global.settings[index].guiPos
local force = player.force.name
local contentFrame = player.gui[guiPos].logisticsFrame.contentFrame
local filtersFlow = contentFrame["filtersFlow"]
local searchFlow = contentFrame["searchFlow"]
local currentTab = global.currentTab[index]
local filters = global.networksFilter[index]
local filtersCount = count(filters)
local names = global.networksNames[force]
local maxFiltersList = math.min(filtersCount, 2)
if searchFlow == nil then
searchFlow = contentFrame.add({type = "flow", name = "searchFlow", style = "als_info_flow", direction = "horizontal"})
end
-- remove network filters info frame
local networkFiltersFrame = searchFlow["networkFiltersFrame"]
if currentTab == "itemInfo" then
networkFiltersFrame = filtersFlow["networkFiltersFrame"]
end
if networkFiltersFrame ~= nil then
networkFiltersFrame.destroy()
end
-- add network filters info frame
if currentTab == "logistics" then
-- remove old search frame
local oldnetworkFiltersFrame = contentFrame["networkFiltersFrame"]
if oldnetworkFiltersFrame ~= nil then
oldnetworkFiltersFrame.destroy()
end
networkFiltersFrame = searchFlow.add({type = "frame", name = "networkFiltersFrame", style = "als_info_frame", direction = "horizontal"})
networkFiltersFrame.add({type = "label", name = "networkFiltersFrameLabel", style = "als_info_label", caption = {"network-filters"}})
if filtersCount == 0 then
networkFiltersFrame.add({type = "label", name = "networkFiltersFrameValueAll", style = "label_style", caption = {"network-all"}})
networkFiltersFrame.add({type = "button", name = "networkFiltersFrameView", caption = {"filter"}, style = "als_button_small"})
else
networkFiltersFrame.add({type = "label", name = "networkFiltersFrameCount", style = "als_info_label", caption = "(" .. filtersCount .. ")"})
networkFiltersFrame.add({type = "button", name = "networkFiltersFrameView", caption = {"view-filters"}, style = "als_button_small"})
end
elseif currentTab == "itemInfo" then
local itemFilters = global.itemInfoFilters[index]
if itemFilters["group"]["logistics"] ~= nil then
networkFiltersFrame = filtersFlow.add({type = "frame", name = "networkFiltersFrame", style = "als_info_frame", direction = "horizontal"})
networkFiltersFrame.add({type = "label", name = "networkFiltersFrameLabel", style = "als_info_label", caption = {"networks"}})
if filtersCount > 0 then
networkFiltersFrame.add({type = "label", name = "networkFiltersFrameCount", style = "als_info_label", caption = "(" .. filtersCount .. ")"})
end
networkFiltersFrame.add({type = "button", name = "networkFiltersFrameView", caption = {"filter"}, style = "als_button_small"})
end
end
end | mit |
vanjikumaran/wrk | deps/luajit/src/jit/bcsave.lua | 87 | 18141 | ----------------------------------------------------------------------------
-- LuaJIT module to save/list bytecode.
--
-- Copyright (C) 2005-2015 Mike Pall. All rights reserved.
-- Released under the MIT license. See Copyright Notice in luajit.h
----------------------------------------------------------------------------
--
-- This module saves or lists the bytecode for an input file.
-- It's run by the -b command line option.
--
------------------------------------------------------------------------------
local jit = require("jit")
assert(jit.version_num == 20004, "LuaJIT core/library version mismatch")
local bit = require("bit")
-- Symbol name prefix for LuaJIT bytecode.
local LJBC_PREFIX = "luaJIT_BC_"
------------------------------------------------------------------------------
local function usage()
io.stderr:write[[
Save LuaJIT bytecode: luajit -b[options] input output
-l Only list bytecode.
-s Strip debug info (default).
-g Keep debug info.
-n name Set module name (default: auto-detect from input name).
-t type Set output file type (default: auto-detect from output name).
-a arch Override architecture for object files (default: native).
-o os Override OS for object files (default: native).
-e chunk Use chunk string as input.
-- Stop handling options.
- Use stdin as input and/or stdout as output.
File types: c h obj o raw (default)
]]
os.exit(1)
end
local function check(ok, ...)
if ok then return ok, ... end
io.stderr:write("luajit: ", ...)
io.stderr:write("\n")
os.exit(1)
end
local function readfile(input)
if type(input) == "function" then return input end
if input == "-" then input = nil end
return check(loadfile(input))
end
local function savefile(name, mode)
if name == "-" then return io.stdout end
return check(io.open(name, mode))
end
------------------------------------------------------------------------------
local map_type = {
raw = "raw", c = "c", h = "h", o = "obj", obj = "obj",
}
local map_arch = {
x86 = true, x64 = true, arm = true, ppc = true, ppcspe = true,
mips = true, mipsel = true,
}
local map_os = {
linux = true, windows = true, osx = true, freebsd = true, netbsd = true,
openbsd = true, dragonfly = true, solaris = true,
}
local function checkarg(str, map, err)
str = string.lower(str)
local s = check(map[str], "unknown ", err)
return s == true and str or s
end
local function detecttype(str)
local ext = string.match(string.lower(str), "%.(%a+)$")
return map_type[ext] or "raw"
end
local function checkmodname(str)
check(string.match(str, "^[%w_.%-]+$"), "bad module name")
return string.gsub(str, "[%.%-]", "_")
end
local function detectmodname(str)
if type(str) == "string" then
local tail = string.match(str, "[^/\\]+$")
if tail then str = tail end
local head = string.match(str, "^(.*)%.[^.]*$")
if head then str = head end
str = string.match(str, "^[%w_.%-]+")
else
str = nil
end
check(str, "cannot derive module name, use -n name")
return string.gsub(str, "[%.%-]", "_")
end
------------------------------------------------------------------------------
local function bcsave_tail(fp, output, s)
local ok, err = fp:write(s)
if ok and output ~= "-" then ok, err = fp:close() end
check(ok, "cannot write ", output, ": ", err)
end
local function bcsave_raw(output, s)
local fp = savefile(output, "wb")
bcsave_tail(fp, output, s)
end
local function bcsave_c(ctx, output, s)
local fp = savefile(output, "w")
if ctx.type == "c" then
fp:write(string.format([[
#ifdef _cplusplus
extern "C"
#endif
#ifdef _WIN32
__declspec(dllexport)
#endif
const char %s%s[] = {
]], LJBC_PREFIX, ctx.modname))
else
fp:write(string.format([[
#define %s%s_SIZE %d
static const char %s%s[] = {
]], LJBC_PREFIX, ctx.modname, #s, LJBC_PREFIX, ctx.modname))
end
local t, n, m = {}, 0, 0
for i=1,#s do
local b = tostring(string.byte(s, i))
m = m + #b + 1
if m > 78 then
fp:write(table.concat(t, ",", 1, n), ",\n")
n, m = 0, #b + 1
end
n = n + 1
t[n] = b
end
bcsave_tail(fp, output, table.concat(t, ",", 1, n).."\n};\n")
end
local function bcsave_elfobj(ctx, output, s, ffi)
ffi.cdef[[
typedef struct {
uint8_t emagic[4], eclass, eendian, eversion, eosabi, eabiversion, epad[7];
uint16_t type, machine;
uint32_t version;
uint32_t entry, phofs, shofs;
uint32_t flags;
uint16_t ehsize, phentsize, phnum, shentsize, shnum, shstridx;
} ELF32header;
typedef struct {
uint8_t emagic[4], eclass, eendian, eversion, eosabi, eabiversion, epad[7];
uint16_t type, machine;
uint32_t version;
uint64_t entry, phofs, shofs;
uint32_t flags;
uint16_t ehsize, phentsize, phnum, shentsize, shnum, shstridx;
} ELF64header;
typedef struct {
uint32_t name, type, flags, addr, ofs, size, link, info, align, entsize;
} ELF32sectheader;
typedef struct {
uint32_t name, type;
uint64_t flags, addr, ofs, size;
uint32_t link, info;
uint64_t align, entsize;
} ELF64sectheader;
typedef struct {
uint32_t name, value, size;
uint8_t info, other;
uint16_t sectidx;
} ELF32symbol;
typedef struct {
uint32_t name;
uint8_t info, other;
uint16_t sectidx;
uint64_t value, size;
} ELF64symbol;
typedef struct {
ELF32header hdr;
ELF32sectheader sect[6];
ELF32symbol sym[2];
uint8_t space[4096];
} ELF32obj;
typedef struct {
ELF64header hdr;
ELF64sectheader sect[6];
ELF64symbol sym[2];
uint8_t space[4096];
} ELF64obj;
]]
local symname = LJBC_PREFIX..ctx.modname
local is64, isbe = false, false
if ctx.arch == "x64" then
is64 = true
elseif ctx.arch == "ppc" or ctx.arch == "ppcspe" or ctx.arch == "mips" then
isbe = true
end
-- Handle different host/target endianess.
local function f32(x) return x end
local f16, fofs = f32, f32
if ffi.abi("be") ~= isbe then
f32 = bit.bswap
function f16(x) return bit.rshift(bit.bswap(x), 16) end
if is64 then
local two32 = ffi.cast("int64_t", 2^32)
function fofs(x) return bit.bswap(x)*two32 end
else
fofs = f32
end
end
-- Create ELF object and fill in header.
local o = ffi.new(is64 and "ELF64obj" or "ELF32obj")
local hdr = o.hdr
if ctx.os == "bsd" or ctx.os == "other" then -- Determine native hdr.eosabi.
local bf = assert(io.open("/bin/ls", "rb"))
local bs = bf:read(9)
bf:close()
ffi.copy(o, bs, 9)
check(hdr.emagic[0] == 127, "no support for writing native object files")
else
hdr.emagic = "\127ELF"
hdr.eosabi = ({ freebsd=9, netbsd=2, openbsd=12, solaris=6 })[ctx.os] or 0
end
hdr.eclass = is64 and 2 or 1
hdr.eendian = isbe and 2 or 1
hdr.eversion = 1
hdr.type = f16(1)
hdr.machine = f16(({ x86=3, x64=62, arm=40, ppc=20, ppcspe=20, mips=8, mipsel=8 })[ctx.arch])
if ctx.arch == "mips" or ctx.arch == "mipsel" then
hdr.flags = 0x50001006
end
hdr.version = f32(1)
hdr.shofs = fofs(ffi.offsetof(o, "sect"))
hdr.ehsize = f16(ffi.sizeof(hdr))
hdr.shentsize = f16(ffi.sizeof(o.sect[0]))
hdr.shnum = f16(6)
hdr.shstridx = f16(2)
-- Fill in sections and symbols.
local sofs, ofs = ffi.offsetof(o, "space"), 1
for i,name in ipairs{
".symtab", ".shstrtab", ".strtab", ".rodata", ".note.GNU-stack",
} do
local sect = o.sect[i]
sect.align = fofs(1)
sect.name = f32(ofs)
ffi.copy(o.space+ofs, name)
ofs = ofs + #name+1
end
o.sect[1].type = f32(2) -- .symtab
o.sect[1].link = f32(3)
o.sect[1].info = f32(1)
o.sect[1].align = fofs(8)
o.sect[1].ofs = fofs(ffi.offsetof(o, "sym"))
o.sect[1].entsize = fofs(ffi.sizeof(o.sym[0]))
o.sect[1].size = fofs(ffi.sizeof(o.sym))
o.sym[1].name = f32(1)
o.sym[1].sectidx = f16(4)
o.sym[1].size = fofs(#s)
o.sym[1].info = 17
o.sect[2].type = f32(3) -- .shstrtab
o.sect[2].ofs = fofs(sofs)
o.sect[2].size = fofs(ofs)
o.sect[3].type = f32(3) -- .strtab
o.sect[3].ofs = fofs(sofs + ofs)
o.sect[3].size = fofs(#symname+1)
ffi.copy(o.space+ofs+1, symname)
ofs = ofs + #symname + 2
o.sect[4].type = f32(1) -- .rodata
o.sect[4].flags = fofs(2)
o.sect[4].ofs = fofs(sofs + ofs)
o.sect[4].size = fofs(#s)
o.sect[5].type = f32(1) -- .note.GNU-stack
o.sect[5].ofs = fofs(sofs + ofs + #s)
-- Write ELF object file.
local fp = savefile(output, "wb")
fp:write(ffi.string(o, ffi.sizeof(o)-4096+ofs))
bcsave_tail(fp, output, s)
end
local function bcsave_peobj(ctx, output, s, ffi)
ffi.cdef[[
typedef struct {
uint16_t arch, nsects;
uint32_t time, symtabofs, nsyms;
uint16_t opthdrsz, flags;
} PEheader;
typedef struct {
char name[8];
uint32_t vsize, vaddr, size, ofs, relocofs, lineofs;
uint16_t nreloc, nline;
uint32_t flags;
} PEsection;
typedef struct __attribute((packed)) {
union {
char name[8];
uint32_t nameref[2];
};
uint32_t value;
int16_t sect;
uint16_t type;
uint8_t scl, naux;
} PEsym;
typedef struct __attribute((packed)) {
uint32_t size;
uint16_t nreloc, nline;
uint32_t cksum;
uint16_t assoc;
uint8_t comdatsel, unused[3];
} PEsymaux;
typedef struct {
PEheader hdr;
PEsection sect[2];
// Must be an even number of symbol structs.
PEsym sym0;
PEsymaux sym0aux;
PEsym sym1;
PEsymaux sym1aux;
PEsym sym2;
PEsym sym3;
uint32_t strtabsize;
uint8_t space[4096];
} PEobj;
]]
local symname = LJBC_PREFIX..ctx.modname
local is64 = false
if ctx.arch == "x86" then
symname = "_"..symname
elseif ctx.arch == "x64" then
is64 = true
end
local symexport = " /EXPORT:"..symname..",DATA "
-- The file format is always little-endian. Swap if the host is big-endian.
local function f32(x) return x end
local f16 = f32
if ffi.abi("be") then
f32 = bit.bswap
function f16(x) return bit.rshift(bit.bswap(x), 16) end
end
-- Create PE object and fill in header.
local o = ffi.new("PEobj")
local hdr = o.hdr
hdr.arch = f16(({ x86=0x14c, x64=0x8664, arm=0x1c0, ppc=0x1f2, mips=0x366, mipsel=0x366 })[ctx.arch])
hdr.nsects = f16(2)
hdr.symtabofs = f32(ffi.offsetof(o, "sym0"))
hdr.nsyms = f32(6)
-- Fill in sections and symbols.
o.sect[0].name = ".drectve"
o.sect[0].size = f32(#symexport)
o.sect[0].flags = f32(0x00100a00)
o.sym0.sect = f16(1)
o.sym0.scl = 3
o.sym0.name = ".drectve"
o.sym0.naux = 1
o.sym0aux.size = f32(#symexport)
o.sect[1].name = ".rdata"
o.sect[1].size = f32(#s)
o.sect[1].flags = f32(0x40300040)
o.sym1.sect = f16(2)
o.sym1.scl = 3
o.sym1.name = ".rdata"
o.sym1.naux = 1
o.sym1aux.size = f32(#s)
o.sym2.sect = f16(2)
o.sym2.scl = 2
o.sym2.nameref[1] = f32(4)
o.sym3.sect = f16(-1)
o.sym3.scl = 2
o.sym3.value = f32(1)
o.sym3.name = "@feat.00" -- Mark as SafeSEH compliant.
ffi.copy(o.space, symname)
local ofs = #symname + 1
o.strtabsize = f32(ofs + 4)
o.sect[0].ofs = f32(ffi.offsetof(o, "space") + ofs)
ffi.copy(o.space + ofs, symexport)
ofs = ofs + #symexport
o.sect[1].ofs = f32(ffi.offsetof(o, "space") + ofs)
-- Write PE object file.
local fp = savefile(output, "wb")
fp:write(ffi.string(o, ffi.sizeof(o)-4096+ofs))
bcsave_tail(fp, output, s)
end
local function bcsave_machobj(ctx, output, s, ffi)
ffi.cdef[[
typedef struct
{
uint32_t magic, cputype, cpusubtype, filetype, ncmds, sizeofcmds, flags;
} mach_header;
typedef struct
{
mach_header; uint32_t reserved;
} mach_header_64;
typedef struct {
uint32_t cmd, cmdsize;
char segname[16];
uint32_t vmaddr, vmsize, fileoff, filesize;
uint32_t maxprot, initprot, nsects, flags;
} mach_segment_command;
typedef struct {
uint32_t cmd, cmdsize;
char segname[16];
uint64_t vmaddr, vmsize, fileoff, filesize;
uint32_t maxprot, initprot, nsects, flags;
} mach_segment_command_64;
typedef struct {
char sectname[16], segname[16];
uint32_t addr, size;
uint32_t offset, align, reloff, nreloc, flags;
uint32_t reserved1, reserved2;
} mach_section;
typedef struct {
char sectname[16], segname[16];
uint64_t addr, size;
uint32_t offset, align, reloff, nreloc, flags;
uint32_t reserved1, reserved2, reserved3;
} mach_section_64;
typedef struct {
uint32_t cmd, cmdsize, symoff, nsyms, stroff, strsize;
} mach_symtab_command;
typedef struct {
int32_t strx;
uint8_t type, sect;
int16_t desc;
uint32_t value;
} mach_nlist;
typedef struct {
uint32_t strx;
uint8_t type, sect;
uint16_t desc;
uint64_t value;
} mach_nlist_64;
typedef struct
{
uint32_t magic, nfat_arch;
} mach_fat_header;
typedef struct
{
uint32_t cputype, cpusubtype, offset, size, align;
} mach_fat_arch;
typedef struct {
struct {
mach_header hdr;
mach_segment_command seg;
mach_section sec;
mach_symtab_command sym;
} arch[1];
mach_nlist sym_entry;
uint8_t space[4096];
} mach_obj;
typedef struct {
struct {
mach_header_64 hdr;
mach_segment_command_64 seg;
mach_section_64 sec;
mach_symtab_command sym;
} arch[1];
mach_nlist_64 sym_entry;
uint8_t space[4096];
} mach_obj_64;
typedef struct {
mach_fat_header fat;
mach_fat_arch fat_arch[4];
struct {
mach_header hdr;
mach_segment_command seg;
mach_section sec;
mach_symtab_command sym;
} arch[4];
mach_nlist sym_entry;
uint8_t space[4096];
} mach_fat_obj;
]]
local symname = '_'..LJBC_PREFIX..ctx.modname
local isfat, is64, align, mobj = false, false, 4, "mach_obj"
if ctx.arch == "x64" then
is64, align, mobj = true, 8, "mach_obj_64"
elseif ctx.arch == "arm" then
isfat, mobj = true, "mach_fat_obj"
else
check(ctx.arch == "x86", "unsupported architecture for OSX")
end
local function aligned(v, a) return bit.band(v+a-1, -a) end
local be32 = bit.bswap -- Mach-O FAT is BE, supported archs are LE.
-- Create Mach-O object and fill in header.
local o = ffi.new(mobj)
local mach_size = aligned(ffi.offsetof(o, "space")+#symname+2, align)
local cputype = ({ x86={7}, x64={0x01000007}, arm={7,12,12,12} })[ctx.arch]
local cpusubtype = ({ x86={3}, x64={3}, arm={3,6,9,11} })[ctx.arch]
if isfat then
o.fat.magic = be32(0xcafebabe)
o.fat.nfat_arch = be32(#cpusubtype)
end
-- Fill in sections and symbols.
for i=0,#cpusubtype-1 do
local ofs = 0
if isfat then
local a = o.fat_arch[i]
a.cputype = be32(cputype[i+1])
a.cpusubtype = be32(cpusubtype[i+1])
-- Subsequent slices overlap each other to share data.
ofs = ffi.offsetof(o, "arch") + i*ffi.sizeof(o.arch[0])
a.offset = be32(ofs)
a.size = be32(mach_size-ofs+#s)
end
local a = o.arch[i]
a.hdr.magic = is64 and 0xfeedfacf or 0xfeedface
a.hdr.cputype = cputype[i+1]
a.hdr.cpusubtype = cpusubtype[i+1]
a.hdr.filetype = 1
a.hdr.ncmds = 2
a.hdr.sizeofcmds = ffi.sizeof(a.seg)+ffi.sizeof(a.sec)+ffi.sizeof(a.sym)
a.seg.cmd = is64 and 0x19 or 0x1
a.seg.cmdsize = ffi.sizeof(a.seg)+ffi.sizeof(a.sec)
a.seg.vmsize = #s
a.seg.fileoff = mach_size-ofs
a.seg.filesize = #s
a.seg.maxprot = 1
a.seg.initprot = 1
a.seg.nsects = 1
ffi.copy(a.sec.sectname, "__data")
ffi.copy(a.sec.segname, "__DATA")
a.sec.size = #s
a.sec.offset = mach_size-ofs
a.sym.cmd = 2
a.sym.cmdsize = ffi.sizeof(a.sym)
a.sym.symoff = ffi.offsetof(o, "sym_entry")-ofs
a.sym.nsyms = 1
a.sym.stroff = ffi.offsetof(o, "sym_entry")+ffi.sizeof(o.sym_entry)-ofs
a.sym.strsize = aligned(#symname+2, align)
end
o.sym_entry.type = 0xf
o.sym_entry.sect = 1
o.sym_entry.strx = 1
ffi.copy(o.space+1, symname)
-- Write Macho-O object file.
local fp = savefile(output, "wb")
fp:write(ffi.string(o, mach_size))
bcsave_tail(fp, output, s)
end
local function bcsave_obj(ctx, output, s)
local ok, ffi = pcall(require, "ffi")
check(ok, "FFI library required to write this file type")
if ctx.os == "windows" then
return bcsave_peobj(ctx, output, s, ffi)
elseif ctx.os == "osx" then
return bcsave_machobj(ctx, output, s, ffi)
else
return bcsave_elfobj(ctx, output, s, ffi)
end
end
------------------------------------------------------------------------------
local function bclist(input, output)
local f = readfile(input)
require("jit.bc").dump(f, savefile(output, "w"), true)
end
local function bcsave(ctx, input, output)
local f = readfile(input)
local s = string.dump(f, ctx.strip)
local t = ctx.type
if not t then
t = detecttype(output)
ctx.type = t
end
if t == "raw" then
bcsave_raw(output, s)
else
if not ctx.modname then ctx.modname = detectmodname(input) end
if t == "obj" then
bcsave_obj(ctx, output, s)
else
bcsave_c(ctx, output, s)
end
end
end
local function docmd(...)
local arg = {...}
local n = 1
local list = false
local ctx = {
strip = true, arch = jit.arch, os = string.lower(jit.os),
type = false, modname = false,
}
while n <= #arg do
local a = arg[n]
if type(a) == "string" and string.sub(a, 1, 1) == "-" and a ~= "-" then
table.remove(arg, n)
if a == "--" then break end
for m=2,#a do
local opt = string.sub(a, m, m)
if opt == "l" then
list = true
elseif opt == "s" then
ctx.strip = true
elseif opt == "g" then
ctx.strip = false
else
if arg[n] == nil or m ~= #a then usage() end
if opt == "e" then
if n ~= 1 then usage() end
arg[1] = check(loadstring(arg[1]))
elseif opt == "n" then
ctx.modname = checkmodname(table.remove(arg, n))
elseif opt == "t" then
ctx.type = checkarg(table.remove(arg, n), map_type, "file type")
elseif opt == "a" then
ctx.arch = checkarg(table.remove(arg, n), map_arch, "architecture")
elseif opt == "o" then
ctx.os = checkarg(table.remove(arg, n), map_os, "OS name")
else
usage()
end
end
end
else
n = n + 1
end
end
if list then
if #arg == 0 or #arg > 2 then usage() end
bclist(arg[1], arg[2] or "-")
else
if #arg ~= 2 then usage() end
bcsave(ctx, arg[1], arg[2])
end
end
------------------------------------------------------------------------------
-- Public module functions.
module(...)
start = docmd -- Process -b command line option.
| apache-2.0 |
aryajur/luarocks | src/luarocks/pack.lua | 20 | 7450 |
--- Module implementing the LuaRocks "pack" command.
-- Creates a rock, packing sources or binaries.
--module("luarocks.pack", package.seeall)
local pack = {}
package.loaded["luarocks.pack"] = pack
local unpack = unpack or table.unpack
local path = require("luarocks.path")
local repos = require("luarocks.repos")
local fetch = require("luarocks.fetch")
local fs = require("luarocks.fs")
local cfg = require("luarocks.cfg")
local util = require("luarocks.util")
local dir = require("luarocks.dir")
local manif = require("luarocks.manif")
local search = require("luarocks.search")
pack.help_summary = "Create a rock, packing sources or binaries."
pack.help_arguments = "{<rockspec>|<name> [<version>]}"
pack.help = [[
Argument may be a rockspec file, for creating a source rock,
or the name of an installed package, for creating a binary rock.
In the latter case, the app version may be given as a second
argument.
]]
--- Create a source rock.
-- Packages a rockspec and its required source files in a rock
-- file with the .src.rock extension, which can later be built and
-- installed with the "build" command.
-- @param rockspec_file string: An URL or pathname for a rockspec file.
-- @return string or (nil, string): The filename of the resulting
-- .src.rock file; or nil and an error message.
function pack.pack_source_rock(rockspec_file)
assert(type(rockspec_file) == "string")
local rockspec, err = fetch.load_rockspec(rockspec_file)
if err then
return nil, "Error loading rockspec: "..err
end
rockspec_file = rockspec.local_filename
local name_version = rockspec.name .. "-" .. rockspec.version
local rock_file = fs.absolute_name(name_version .. ".src.rock")
local source_file, source_dir = fetch.fetch_sources(rockspec, false)
if not source_file then
return nil, source_dir
end
local ok, err = fs.change_dir(source_dir)
if not ok then return nil, err end
fs.delete(rock_file)
fs.copy(rockspec_file, source_dir)
if not fs.zip(rock_file, dir.base_name(rockspec_file), dir.base_name(source_file)) then
return nil, "Failed packing "..rock_file
end
fs.pop_dir()
return rock_file
end
local function copy_back_files(name, version, file_tree, deploy_dir, pack_dir)
local ok, err = fs.make_dir(pack_dir)
if not ok then return nil, err end
for file, sub in pairs(file_tree) do
local source = dir.path(deploy_dir, file)
local target = dir.path(pack_dir, file)
if type(sub) == "table" then
local ok, err = copy_back_files(name, version, sub, source, target)
if not ok then return nil, err end
else
local versioned = path.versioned_name(source, deploy_dir, name, version)
if fs.exists(versioned) then
fs.copy(versioned, target)
else
fs.copy(source, target)
end
end
end
return true
end
-- @param name string: Name of package to pack.
-- @param version string or nil: A version number may also be passed.
-- @return string or (nil, string): The filename of the resulting
-- .src.rock file; or nil and an error message.
local function do_pack_binary_rock(name, version)
assert(type(name) == "string")
assert(type(version) == "string" or not version)
local query = search.make_query(name, version)
query.exact_name = true
local results = {}
search.manifest_search(results, cfg.rocks_dir, query)
if not next(results) then
return nil, "'"..name.."' does not seem to be an installed rock."
end
local versions = results[name]
if not version then
local first = next(versions)
if next(versions, first) then
return nil, "Please specify which version of '"..name.."' to pack."
end
version = first
end
if not version:match("[^-]+%-%d+") then
return nil, "Expected version "..version.." in version-revision format."
end
local info = versions[version][1]
local root = path.root_dir(info.repo)
local prefix = path.install_dir(name, version, root)
if not fs.exists(prefix) then
return nil, "'"..name.." "..version.."' does not seem to be an installed rock."
end
local rock_manifest = manif.load_rock_manifest(name, version, root)
if not rock_manifest then
return nil, "rock_manifest file not found for "..name.." "..version.." - not a LuaRocks 2 tree?"
end
local name_version = name .. "-" .. version
local rock_file = fs.absolute_name(name_version .. "."..cfg.arch..".rock")
local temp_dir = fs.make_temp_dir("pack")
fs.copy_contents(prefix, temp_dir)
local is_binary = false
if rock_manifest.lib then
local ok, err = copy_back_files(name, version, rock_manifest.lib, path.deploy_lib_dir(root), dir.path(temp_dir, "lib"))
if not ok then return nil, "Failed copying back files: " .. err end
is_binary = true
end
if rock_manifest.lua then
local ok, err = copy_back_files(name, version, rock_manifest.lua, path.deploy_lua_dir(root), dir.path(temp_dir, "lua"))
if not ok then return nil, "Failed copying back files: " .. err end
end
local ok, err = fs.change_dir(temp_dir)
if not ok then return nil, err end
if not is_binary and not repos.has_binaries(name, version) then
rock_file = rock_file:gsub("%."..cfg.arch:gsub("%-","%%-").."%.", ".all.")
end
fs.delete(rock_file)
if not fs.zip(rock_file, unpack(fs.list_dir())) then
return nil, "Failed packing "..rock_file
end
fs.pop_dir()
fs.delete(temp_dir)
return rock_file
end
function pack.pack_binary_rock(name, version, cmd, ...)
-- The --pack-binary-rock option for "luarocks build" basically performs
-- "luarocks build" on a temporary tree and then "luarocks pack". The
-- alternative would require refactoring parts of luarocks.build and
-- luarocks.pack, which would save a few file operations: the idea would be
-- to shave off the final deploy steps from the build phase and the initial
-- collect steps from the pack phase.
local temp_dir, err = fs.make_temp_dir("luarocks-build-pack-"..dir.base_name(name))
if not temp_dir then
return nil, "Failed creating temporary directory: "..err
end
util.schedule_function(fs.delete, temp_dir)
path.use_tree(temp_dir)
local ok, err = cmd(...)
if not ok then
return nil, err
end
local rname, rversion = path.parse_name(name)
if not rname then
rname, rversion = name, version
end
return do_pack_binary_rock(rname, rversion)
end
--- Driver function for the "pack" command.
-- @param arg string: may be a rockspec file, for creating a source rock,
-- or the name of an installed package, for creating a binary rock.
-- @param version string or nil: if the name of a package is given, a
-- version may also be passed.
-- @return boolean or (nil, string): true if successful or nil followed
-- by an error message.
function pack.run(...)
local flags, arg, version = util.parse_flags(...)
assert(type(version) == "string" or not version)
if type(arg) ~= "string" then
return nil, "Argument missing. "..util.see_help("pack")
end
local file, err
if arg:match(".*%.rockspec") then
file, err = pack.pack_source_rock(arg)
else
file, err = do_pack_binary_rock(arg, version)
end
if err then
return nil, err
else
util.printout("Packed: "..file)
return true
end
end
return pack
| mit |
vzaramel/kong | kong/dao/postgres/base_dao.lua | 1 | 10944 | local query_builder = require "kong.dao.postgres.query_builder"
local validations = require "kong.dao.schemas_validation"
local constants = require "kong.constants"
local pgmoon = require "pgmoon"
local DaoError = require "kong.dao.error"
local Object = require "classic"
local utils = require "kong.tools.utils"
local uuid = require "uuid"
local error_types = constants.DATABASE_ERROR_TYPES
local BaseDao = Object:extend()
--for dbnull values
local dbnull = pgmoon.new().null
-- This is important to seed the UUID generator
uuid.seed()
function BaseDao:new(properties)
if self._schema then
self._primary_key = self._schema.primary_key
self._clustering_key = self._schema.clustering_key
local indexes = {}
for field_k, field_v in pairs(self._schema.fields) do
if field_v.queryable then
indexes[field_k] = true
end
end
end
self._properties = properties
self._statements_cache = {}
end
-- Marshall an entity. Does nothing by default,
-- must be overriden for entities where marshalling applies.
function BaseDao:_marshall(t)
return t
end
-- Unmarshall an entity. Does nothing by default,
-- must be overriden for entities where marshalling applies.
function BaseDao:_unmarshall(t)
return t
end
-- Open a connection to the postgres database.
-- @return `pg` Opened postgres connection
-- @return `error` Error if any
function BaseDao:_open_session()
local ok, err
-- Start postgres session
local pg = pgmoon.new({
host = self._properties.hosts,
port = self._properties.port,
database = self._properties.keyspace,
user = self._properties.username,
password = self._properties.password
})
ok, err = pg:connect()
if not ok then
return nil, DaoError(err, error_types.DATABASE)
end
return pg
end
-- Close the given opened session.
-- Will try to put the session in the socket pool if supported.
-- @param `pg` postgres session to close
-- @return `error` Error if any
function BaseDao:_close_session(pg)
-- Back to the pool or close if using luasocket
local ok, err
-- if ngx and ngx.get_phase ~= nil and ngx.get_phase() ~= "init" and ngx.socket.tcp ~= nil and ngx.socket.tcp().setkeepalive ~= nil then
-- -- openresty
-- -- something here ain't working within lapis? sock.setkeepalive is nil although we're in an ngx context
-- ok, err = pg:keepalive()
-- if not ok then
-- return DaoError(err, error_types.DATABASE)
-- end
-- else
ok, err = pg:disconnect()
if not ok then
return DaoError(err, error_types.DATABASE)
end
-- end
if not ok then
return DaoError(err, error_types.DATABASE)
end
end
-- Execute a sql query.
-- Opens a socket, executes the query, puts the socket back into the
-- socket pool and returns a parsed result.
-- @param `query` plain string query.
-- @return `results` If results set are ROWS, a table with an array of unmarshalled rows
-- @return `error` An error if any during the whole execution (sockets/query execution)
function BaseDao:_execute(query)
local pg, err = self:_open_session()
if err then
return nil, err
end
local results, errorOrRows = pg:query(query)
if string.find(errorOrRows, 'ERROR') then
err = errorOrRows
end
if err then
err = DaoError(err, error_types.DATABASE)
end
local socket_err = self:_close_session(pg)
if socket_err then
return nil, socket_err
end
if results and type(results) == 'table' then
for i, row in ipairs(results) do
results[i] = self:_unmarshall(row)
end
end
return results, err
end
-- Execute a sql query.
-- @param `query` The query to execute
-- @return :_execute()
function BaseDao:execute(query)
-- Execute statement
local results, err = self:_execute(query)
return results, err
end
-- Insert a row in the DAO's table.
-- Perform schema validation, UNIQUE checks, FOREIGN checks.
-- @param `t` A table representing the entity to insert
-- @return `result` Inserted entity or nil
-- @return `error` Error if any during the execution
function BaseDao:insert(t)
assert(t ~= nil, "Cannot insert a nil element")
assert(type(t) == "table", "Entity to insert must be a table")
local ok, errors, self_err
-- Populate the entity with any default/overriden values and validate it
ok, errors, self_err = validations.validate_entity(t, self._schema, {
dao = self._factory,
dao_insert = function(field)
if field.type == "id" then
return uuid()
-- default handled in postgres
-- otherwise explicility set a timestamp
-- elseif field.type == "timestamp" then
-- return os.date("!%c")
end
end
})
if self_err then
return nil, self_err
elseif not ok then
return nil, DaoError(errors, error_types.SCHEMA)
end
local insert_q = query_builder.insert(self._table, self:_marshall(t))
local _, query_err = self:execute(insert_q)
if query_err then
return nil, query_err
else
return self:_unmarshall(t)
end
end
local function extract_primary_key(t, primary_key, clustering_key)
local t_no_primary_key = utils.deep_copy(t)
local t_primary_key = {}
for _, key in ipairs(primary_key) do
t_primary_key[key] = t[key]
t_no_primary_key[key] = nil
end
if clustering_key then
for _, key in ipairs(clustering_key) do
t_primary_key[key] = t[key]
t_no_primary_key[key] = nil
end
end
return t_primary_key, t_no_primary_key
end
-- When updating a row that has a json-as-text column (ex: plugin_configuration.value),
-- we want to avoid overriding it with a partial value.
-- Ex: value.key_name + value.hide_credential, if we update only one field,
-- the other should be preserved. Of course this only applies in partial update.
local function fix_tables(t, old_t, schema)
for k, v in pairs(schema.fields) do
if t[k] ~= nil and v.schema then
local s = type(v.schema) == "function" and v.schema(t) or v.schema
for s_k, s_v in pairs(s.fields) do
if not t[k][s_k] and old_t[k] then
t[k][s_k] = old_t[k][s_k]
end
end
fix_tables(t[k], old_t[k], s)
end
end
end
-- Update a row: find the row with the given PRIMARY KEY and update the other values
-- If `full`, sets to NULL values that are not included in the schema.
-- Performs schema validation, UNIQUE and FOREIGN checks.
-- @param `t` A table representing the entity to insert
-- @param `full` If `true`, set to NULL any column not in the `t` parameter
-- @return `result` Updated entity or nil
-- @return `error` Error if any during the execution
function BaseDao:update(t, full)
assert(t ~= nil, "Cannot update a nil element")
assert(type(t) == "table", "Entity to update must be a table")
local ok, errors, self_err
-- Check if exists to prevent upsert
local res, err = self:find_by_primary_key(t)
if err then
return false, err
elseif not res then
return false
end
if not full then
fix_tables(t, res, self._schema)
end
-- Validate schema
ok, errors, self_err = validations.validate_entity(t, self._schema, {
partial_update = not full,
full_update = full,
dao = self._factory
})
if self_err then
return nil, self_err
elseif not ok then
return nil, DaoError(errors, error_types.SCHEMA)
end
-- Extract primary key from the entity
local t_primary_key, t_no_primary_key = extract_primary_key(t, self._primary_key, self._clustering_key)
-- If full, add `null` values to the SET part of the query for nil columns
if full then
for k, v in pairs(self._schema.fields) do
if not t[k] and not v.immutable then
t_no_primary_key[k] = dbnull
end
end
end
local update_q, columns = query_builder.update(self._table, self:_marshall(t_no_primary_key), t_primary_key)
local _, stmt_err = self:execute(update_q, columns, self:_marshall(t))
if stmt_err then
return nil, stmt_err
else
return self:_unmarshall(t)
end
end
-- Retrieve a row at given PRIMARY KEY.
-- @param `where_t` A table containing the PRIMARY KEY (columns/values) of the row to retrieve.
-- @return `row` The first row of the result.
-- @return `error`
function BaseDao:find_by_primary_key(where_t)
assert(self._primary_key ~= nil and type(self._primary_key) == "table" , "Entity does not have a primary_key")
assert(where_t ~= nil and type(where_t) == "table", "where_t must be a table")
local t_primary_key = extract_primary_key(where_t, self._primary_key)
if next(t_primary_key) == nil then
return nil
end
local select_q, where_columns = query_builder.select(self._table, t_primary_key, nil)
local data, err = self:execute(select_q, where_columns, t_primary_key)
-- Return the 1st and only element of the result set
if data and utils.table_size(data) > 0 then
data = table.remove(data, 1)
else
data = nil
end
return data, err
end
-- Retrieve a set of rows from the given columns/value table.
-- @param `where_t` (Optional) columns/values table by which to find an entity.
-- @param `page_size` Size of the page to retrieve (number of rows).
-- @param `paging_state` Start page from given offset. See lua-resty-postgres's :execute() option.
-- @return `res`
-- @return `err`
function BaseDao:find_by_keys(where_t, page_size, paging_state)
local select_q = query_builder.select(self._table, where_t, nil, {
page_size = page_size,
paging_state = paging_state
})
local res = self:execute(select_q)
return res
end
-- Retrieve a page of the table attached to the DAO.
-- @param `page_size` Size of the page to retrieve (number of rows).
-- @param `paging_state` Start page from given offset. See lua-resty-postgres's :execute() option.
-- @return `find_by_keys()`
function BaseDao:find(page_size, paging_state)
return self:find_by_keys(nil, page_size, paging_state)
end
-- Delete the row at a given PRIMARY KEY.
-- @param `where_t` A table containing the PRIMARY KEY (columns/values) of the row to delete
-- @return `success` True if deleted, false if otherwise or not found
-- @return `error` Error if any during the query execution
function BaseDao:delete(where_t)
assert(self._primary_key ~= nil and type(self._primary_key) == "table" , "Entity does not have a primary_key")
assert(where_t ~= nil and type(where_t) == "table", "where_t must be a table")
-- don't need to test if exists first, this was necessary in cassandra?
local t_primary_key = extract_primary_key(where_t, self._primary_key, self._clustering_key)
local delete_q, where_columns = query_builder.delete(self._table, t_primary_key)
local rows = self:execute(delete_q, where_columns, where_t)
-- did we delete anything
return rows.affected_rows > 0
end
-- Truncate the table of this DAO
-- @return `:execute()`
function BaseDao:drop()
local truncate_q = query_builder.truncate(self._table)
return self:execute(truncate_q)
end
return BaseDao
| apache-2.0 |
MmxBoy/Metal-bot | plugins/wiki.lua | 735 | 4364 | -- http://git.io/vUA4M
local socket = require "socket"
local JSON = require "cjson"
local wikiusage = {
"!wiki [text]: Read extract from default Wikipedia (EN)",
"!wiki(lang) [text]: Read extract from 'lang' Wikipedia. Example: !wikies hola",
"!wiki search [text]: Search articles on default Wikipedia (EN)",
"!wiki(lang) search [text]: Search articles on 'lang' Wikipedia. Example: !wikies search hola",
}
local Wikipedia = {
-- http://meta.wikimedia.org/wiki/List_of_Wikipedias
wiki_server = "https://%s.wikipedia.org",
wiki_path = "/w/api.php",
wiki_load_params = {
action = "query",
prop = "extracts",
format = "json",
exchars = 300,
exsectionformat = "plain",
explaintext = "",
redirects = ""
},
wiki_search_params = {
action = "query",
list = "search",
srlimit = 20,
format = "json",
},
default_lang = "en",
}
function Wikipedia:getWikiServer(lang)
return string.format(self.wiki_server, lang or self.default_lang)
end
--[[
-- return decoded JSON table from Wikipedia
--]]
function Wikipedia:loadPage(text, lang, intro, plain, is_search)
local request, sink = {}, {}
local query = ""
local parsed
if is_search then
for k,v in pairs(self.wiki_search_params) do
query = query .. k .. '=' .. v .. '&'
end
parsed = URL.parse(self:getWikiServer(lang))
parsed.path = self.wiki_path
parsed.query = query .. "srsearch=" .. URL.escape(text)
else
self.wiki_load_params.explaintext = plain and "" or nil
for k,v in pairs(self.wiki_load_params) do
query = query .. k .. '=' .. v .. '&'
end
parsed = URL.parse(self:getWikiServer(lang))
parsed.path = self.wiki_path
parsed.query = query .. "titles=" .. URL.escape(text)
end
-- HTTP request
request['url'] = URL.build(parsed)
print(request['url'])
request['method'] = 'GET'
request['sink'] = ltn12.sink.table(sink)
local httpRequest = parsed.scheme == 'http' and http.request or https.request
local code, headers, status = socket.skip(1, httpRequest(request))
if not headers or not sink then
return nil
end
local content = table.concat(sink)
if content ~= "" then
local ok, result = pcall(JSON.decode, content)
if ok and result then
return result
else
return nil
end
else
return nil
end
end
-- extract intro passage in wiki page
function Wikipedia:wikintro(text, lang)
local result = self:loadPage(text, lang, true, true)
if result and result.query then
local query = result.query
if query and query.normalized then
text = query.normalized[1].to or text
end
local page = query.pages[next(query.pages)]
if page and page.extract then
return text..": "..page.extract
else
local text = "Extract not found for "..text
text = text..'\n'..table.concat(wikiusage, '\n')
return text
end
else
return "Sorry an error happened"
end
end
-- search for term in wiki
function Wikipedia:wikisearch(text, lang)
local result = self:loadPage(text, lang, true, true, true)
if result and result.query then
local titles = ""
for i,item in pairs(result.query.search) do
titles = titles .. "\n" .. item["title"]
end
titles = titles ~= "" and titles or "No results found"
return titles
else
return "Sorry, an error occurred"
end
end
local function run(msg, matches)
-- TODO: Remember language (i18 on future version)
-- TODO: Support for non Wikipedias but Mediawikis
local search, term, lang
if matches[1] == "search" then
search = true
term = matches[2]
lang = nil
elseif matches[2] == "search" then
search = true
term = matches[3]
lang = matches[1]
else
term = matches[2]
lang = matches[1]
end
if not term then
term = lang
lang = nil
end
if term == "" then
local text = "Usage:\n"
text = text..table.concat(wikiusage, '\n')
return text
end
local result
if search then
result = Wikipedia:wikisearch(term, lang)
else
-- TODO: Show the link
result = Wikipedia:wikintro(term, lang)
end
return result
end
return {
description = "Searches Wikipedia and send results",
usage = wikiusage,
patterns = {
"^![Ww]iki(%w+) (search) (.+)$",
"^![Ww]iki (search) ?(.*)$",
"^![Ww]iki(%w+) (.+)$",
"^![Ww]iki ?(.*)$"
},
run = run
}
| gpl-2.0 |
mamaddeveloper/uzz | plugins/wiki.lua | 735 | 4364 | -- http://git.io/vUA4M
local socket = require "socket"
local JSON = require "cjson"
local wikiusage = {
"!wiki [text]: Read extract from default Wikipedia (EN)",
"!wiki(lang) [text]: Read extract from 'lang' Wikipedia. Example: !wikies hola",
"!wiki search [text]: Search articles on default Wikipedia (EN)",
"!wiki(lang) search [text]: Search articles on 'lang' Wikipedia. Example: !wikies search hola",
}
local Wikipedia = {
-- http://meta.wikimedia.org/wiki/List_of_Wikipedias
wiki_server = "https://%s.wikipedia.org",
wiki_path = "/w/api.php",
wiki_load_params = {
action = "query",
prop = "extracts",
format = "json",
exchars = 300,
exsectionformat = "plain",
explaintext = "",
redirects = ""
},
wiki_search_params = {
action = "query",
list = "search",
srlimit = 20,
format = "json",
},
default_lang = "en",
}
function Wikipedia:getWikiServer(lang)
return string.format(self.wiki_server, lang or self.default_lang)
end
--[[
-- return decoded JSON table from Wikipedia
--]]
function Wikipedia:loadPage(text, lang, intro, plain, is_search)
local request, sink = {}, {}
local query = ""
local parsed
if is_search then
for k,v in pairs(self.wiki_search_params) do
query = query .. k .. '=' .. v .. '&'
end
parsed = URL.parse(self:getWikiServer(lang))
parsed.path = self.wiki_path
parsed.query = query .. "srsearch=" .. URL.escape(text)
else
self.wiki_load_params.explaintext = plain and "" or nil
for k,v in pairs(self.wiki_load_params) do
query = query .. k .. '=' .. v .. '&'
end
parsed = URL.parse(self:getWikiServer(lang))
parsed.path = self.wiki_path
parsed.query = query .. "titles=" .. URL.escape(text)
end
-- HTTP request
request['url'] = URL.build(parsed)
print(request['url'])
request['method'] = 'GET'
request['sink'] = ltn12.sink.table(sink)
local httpRequest = parsed.scheme == 'http' and http.request or https.request
local code, headers, status = socket.skip(1, httpRequest(request))
if not headers or not sink then
return nil
end
local content = table.concat(sink)
if content ~= "" then
local ok, result = pcall(JSON.decode, content)
if ok and result then
return result
else
return nil
end
else
return nil
end
end
-- extract intro passage in wiki page
function Wikipedia:wikintro(text, lang)
local result = self:loadPage(text, lang, true, true)
if result and result.query then
local query = result.query
if query and query.normalized then
text = query.normalized[1].to or text
end
local page = query.pages[next(query.pages)]
if page and page.extract then
return text..": "..page.extract
else
local text = "Extract not found for "..text
text = text..'\n'..table.concat(wikiusage, '\n')
return text
end
else
return "Sorry an error happened"
end
end
-- search for term in wiki
function Wikipedia:wikisearch(text, lang)
local result = self:loadPage(text, lang, true, true, true)
if result and result.query then
local titles = ""
for i,item in pairs(result.query.search) do
titles = titles .. "\n" .. item["title"]
end
titles = titles ~= "" and titles or "No results found"
return titles
else
return "Sorry, an error occurred"
end
end
local function run(msg, matches)
-- TODO: Remember language (i18 on future version)
-- TODO: Support for non Wikipedias but Mediawikis
local search, term, lang
if matches[1] == "search" then
search = true
term = matches[2]
lang = nil
elseif matches[2] == "search" then
search = true
term = matches[3]
lang = matches[1]
else
term = matches[2]
lang = matches[1]
end
if not term then
term = lang
lang = nil
end
if term == "" then
local text = "Usage:\n"
text = text..table.concat(wikiusage, '\n')
return text
end
local result
if search then
result = Wikipedia:wikisearch(term, lang)
else
-- TODO: Show the link
result = Wikipedia:wikintro(term, lang)
end
return result
end
return {
description = "Searches Wikipedia and send results",
usage = wikiusage,
patterns = {
"^![Ww]iki(%w+) (search) (.+)$",
"^![Ww]iki (search) ?(.*)$",
"^![Ww]iki(%w+) (.+)$",
"^![Ww]iki ?(.*)$"
},
run = run
}
| gpl-2.0 |
rigeirani/sg1 | plugins/wiki.lua | 735 | 4364 | -- http://git.io/vUA4M
local socket = require "socket"
local JSON = require "cjson"
local wikiusage = {
"!wiki [text]: Read extract from default Wikipedia (EN)",
"!wiki(lang) [text]: Read extract from 'lang' Wikipedia. Example: !wikies hola",
"!wiki search [text]: Search articles on default Wikipedia (EN)",
"!wiki(lang) search [text]: Search articles on 'lang' Wikipedia. Example: !wikies search hola",
}
local Wikipedia = {
-- http://meta.wikimedia.org/wiki/List_of_Wikipedias
wiki_server = "https://%s.wikipedia.org",
wiki_path = "/w/api.php",
wiki_load_params = {
action = "query",
prop = "extracts",
format = "json",
exchars = 300,
exsectionformat = "plain",
explaintext = "",
redirects = ""
},
wiki_search_params = {
action = "query",
list = "search",
srlimit = 20,
format = "json",
},
default_lang = "en",
}
function Wikipedia:getWikiServer(lang)
return string.format(self.wiki_server, lang or self.default_lang)
end
--[[
-- return decoded JSON table from Wikipedia
--]]
function Wikipedia:loadPage(text, lang, intro, plain, is_search)
local request, sink = {}, {}
local query = ""
local parsed
if is_search then
for k,v in pairs(self.wiki_search_params) do
query = query .. k .. '=' .. v .. '&'
end
parsed = URL.parse(self:getWikiServer(lang))
parsed.path = self.wiki_path
parsed.query = query .. "srsearch=" .. URL.escape(text)
else
self.wiki_load_params.explaintext = plain and "" or nil
for k,v in pairs(self.wiki_load_params) do
query = query .. k .. '=' .. v .. '&'
end
parsed = URL.parse(self:getWikiServer(lang))
parsed.path = self.wiki_path
parsed.query = query .. "titles=" .. URL.escape(text)
end
-- HTTP request
request['url'] = URL.build(parsed)
print(request['url'])
request['method'] = 'GET'
request['sink'] = ltn12.sink.table(sink)
local httpRequest = parsed.scheme == 'http' and http.request or https.request
local code, headers, status = socket.skip(1, httpRequest(request))
if not headers or not sink then
return nil
end
local content = table.concat(sink)
if content ~= "" then
local ok, result = pcall(JSON.decode, content)
if ok and result then
return result
else
return nil
end
else
return nil
end
end
-- extract intro passage in wiki page
function Wikipedia:wikintro(text, lang)
local result = self:loadPage(text, lang, true, true)
if result and result.query then
local query = result.query
if query and query.normalized then
text = query.normalized[1].to or text
end
local page = query.pages[next(query.pages)]
if page and page.extract then
return text..": "..page.extract
else
local text = "Extract not found for "..text
text = text..'\n'..table.concat(wikiusage, '\n')
return text
end
else
return "Sorry an error happened"
end
end
-- search for term in wiki
function Wikipedia:wikisearch(text, lang)
local result = self:loadPage(text, lang, true, true, true)
if result and result.query then
local titles = ""
for i,item in pairs(result.query.search) do
titles = titles .. "\n" .. item["title"]
end
titles = titles ~= "" and titles or "No results found"
return titles
else
return "Sorry, an error occurred"
end
end
local function run(msg, matches)
-- TODO: Remember language (i18 on future version)
-- TODO: Support for non Wikipedias but Mediawikis
local search, term, lang
if matches[1] == "search" then
search = true
term = matches[2]
lang = nil
elseif matches[2] == "search" then
search = true
term = matches[3]
lang = matches[1]
else
term = matches[2]
lang = matches[1]
end
if not term then
term = lang
lang = nil
end
if term == "" then
local text = "Usage:\n"
text = text..table.concat(wikiusage, '\n')
return text
end
local result
if search then
result = Wikipedia:wikisearch(term, lang)
else
-- TODO: Show the link
result = Wikipedia:wikintro(term, lang)
end
return result
end
return {
description = "Searches Wikipedia and send results",
usage = wikiusage,
patterns = {
"^![Ww]iki(%w+) (search) (.+)$",
"^![Ww]iki (search) ?(.*)$",
"^![Ww]iki(%w+) (.+)$",
"^![Ww]iki ?(.*)$"
},
run = run
}
| gpl-2.0 |
deepak78/new-luci | applications/luci-app-diag-devinfo/luasrc/model/cbi/luci_diag/netdiscover_devinfo_mini.lua | 141 | 1054 | --[[
netdiscover_devinfo - SIP Device Information
(c) 2009 Daniel Dickinson
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$
]]--
require("luci.i18n")
require("luci.util")
require("luci.sys")
require("luci.model.uci")
require("luci.controller.luci_diag.netdiscover_common")
require("luci.controller.luci_diag.devinfo_common")
local debug = false
m = SimpleForm("luci_devinfo", translate("Network Device Scan"), translate("Scan for devices on specified networks."))
m.reset = false
m.submit = false
local outnets = luci.controller.luci_diag.netdiscover_common.get_params()
luci.controller.luci_diag.devinfo_common.run_processes(outnets, luci.controller.luci_diag.netdiscover_common.command_function)
luci.controller.luci_diag.devinfo_common.parse_output(m, outnets, false, "netdiscover", true, debug)
luci.controller.luci_diag.netdiscover_common.action_links(m, true)
return m
| apache-2.0 |
plinkopenguin/wire-extras | lua/weapons/gmod_tool/stools/wire_simulate_data.lua | 2 | 12336 | TOOL.Category = "Wire Extras/Tools"
TOOL.Name = "Simulate Data"
TOOL.Tab = "Wire"
TOOL.Command = nil
TOOL.ConfigName = ""
if ( CLIENT ) then
language.Add( "Tool.wire_simulate_data.name", "Simulate Data Tool" )
language.Add( "Tool.wire_simulate_data.desc", "Used to debug circuits by simulating data." )
language.Add( "Tool.wire_simulate_data.0", "Primary: Attach to selected input.\nSecondary: Next input." )
end
TOOL.ClientConVar[ "type" ] = "NORMAL"
TOOL.ClientConVar[ "auto" ] = "1"
TOOL.ClientConVar[ "number" ] = "0"
TOOL.ClientConVar[ "string" ] = ""
TOOL.ClientConVar[ "vec1" ] = "0"
TOOL.ClientConVar[ "vec2" ] = "0"
TOOL.ClientConVar[ "vec3" ] = "0"
TOOL.ClientConVar[ "entity" ] = "0"
TOOL.ClientConVar[ "table" ] = ""
TOOL.ClientConVar[ "texp2" ] = "1"
TOOL.ClientConVar[ "array" ] = ""
TOOL.CurrentComponent = nil
TOOL.CurrentInput = nil
TOOL.Inputs = nil
TOOL.CurrentOutput = nil
TOOL.Outputs = nil
local function PrintError( player, arg1, arg2, arg3, arg4 )
player:SendLua("GAMEMODE:AddNotify('Item "..arg1.." : "..arg2..arg3..arg4.."', NOTIFY_GENERIC ,5); surface.PlaySound('ambient/water/drip3.wav');")
end
function TOOL:LeftClick( trace )
if !trace.Entity:IsValid() || trace.Entity:IsPlayer() || trace.Entity:IsWorld() then return false end
if (self.CurrentInput && trace.Entity.Inputs[self.CurrentInput].Type) then
local player = self:GetOwner()
local type = self:GetClientInfo("type")
local data = nil
if self:GetClientNumber("auto")==1 then type=trace.Entity.Inputs[self.CurrentInput].Type end
if type!=trace.Entity.Inputs[self.CurrentInput].Type then return false end
if type=="NORMAL" then data = self:GetClientNumber("number")
elseif type=="STRING" then data = self:GetClientInfo("string")
elseif type=="VECTOR" || type=="ANGLE" then data = Vector(self:GetClientNumber("vec1"), self:GetClientNumber("vec2"), self:GetClientNumber("vec3"))
elseif type=="ENTITY" then data = ents.GetByIndex(self:GetClientNumber("entity")) if !data:IsValid() then return false end
elseif type=="TABLE" || type=="ARRAY" then
if type=="TABLE" then data = self:GetClientInfo("table") else
data = self:GetClientInfo("array") end
local texp2 = self:GetClientNumber("texp2")
local datatable = string.Explode( "|",data)
local explode = {}
local vtype = ""
data = {}
for a, b in pairs(datatable) do
datatable[a] = string.gsub(datatable[a]," ", "")
explode = string.Explode("=",datatable[a])
if table.getn(explode)!=2 then PrintError(player,a,"Wrong number of arguments","","") return false end
for k, v in pairs(explode) do
if string.Left(v,1)=="(" && string.Right(v,1)==")" then
if k==1 && type=="ARRAY" then PrintError(player,a,"Array only takes integer indexes, not vector","","") return false end
vtype = string.sub(v, 2, string.len(v)-1)
vtype = string.Explode(",",vtype)
if table.getn(vtype)!=3 then PrintError(player,a,"Vector requires 3 components","","") return false end
for i=1, 3 do
if _G.type(tonumber(vtype[i]))!="number" then PrintError(player,a,"Vector only takes numbers as arguments","","") return false end
end
explode[k] = Vector(vtype[1],vtype[2],vtype[3])
vtype="v"
elseif _G.type(tonumber(v))=="number" then vtype="n" explode[k]=tonumber(v) if k==1 && type=="ARRAY" && explode[k]>E2_MAX_ARRAY_SIZE then PrintError(player,a,"Array max limit of ",E2_MAX_ARRAY_SIZE," exceeded","","") return false end
else if k==1 && type=="ARRAY" then PrintError(player,a,"Array only takes integer indexes, not string","","") return false end
vtype="s" explode[k]=string.gsub(v,"\'","")
end
end
if texp2==1 && type!="ARRAY" then
if _G.type(explode[1])=="Vector" then explode[1] = vtype..explode[1][1]
else explode[1] = vtype..explode[1]
end
end
data[explode[1]] = explode[2]
end
end
if (trace.Entity.Inputs) then
Wire_Link_Clear(self.CurrentComponent, self.CurrentInput)
trace.Entity:TriggerInput( self.CurrentInput, data)
trace.Entity.Inputs[self.CurrentInput].Value = data
return true
end
end
return false
end
function TOOL:RightClick( trace )
local stage = self:GetStage()
if (stage < 2) then
if (not trace.Entity:IsValid()) or (trace.Entity:IsPlayer()) then return end
end
if (stage == 0) then
if (CLIENT) then return end
if (trace.Entity:IsValid()) then
self:SelectComponent(trace.Entity)
else
self:SelectComponent(nil)
end
if (not self.Inputs) or (not self.CurrentInput) then return end
local iNextInput
for k,v in pairs(self.Inputs) do
if (v == self.CurrentInput) then iNextInput = k+1 end
end
if (iNextInput) then
self:GetOwner():EmitSound("weapons/pistol/pistol_empty.wav")
if (iNextInput > table.getn(self.Inputs)) then iNextInput = 1 end
self.CurrentInput = self.Inputs[iNextInput]
if (self.CurrentInput) then self.LastValidInput = self.CurrentInput end
local txt = ""
if (self.CurrentComponent) and (self.CurrentComponent:IsValid()) and (self.CurrentInput)
and (self.CurrentComponent.Inputs) and (self.CurrentComponent.Inputs[self.CurrentInput])
and (self.CurrentComponent.Inputs[self.CurrentInput].Src) then
txt = "%"..(self.CurrentInput or "")
else
txt = self.CurrentInput or ""
end
if (self.InputsDesc) and (self.InputsDesc[self.CurrentInput]) then
txt = txt.." ("..self.InputsDesc[self.CurrentInput]..")"
end
if (self.InputsType) and (self.InputsType[self.CurrentInput])
and (self.InputsType[self.CurrentInput] != "NORMAL") then
txt = txt.." ["..self.InputsType[self.CurrentInput].."]"
end
self:GetWeapon():SetNetworkedString("WireCurrentInput", txt)
if (self.CurrentComponent) and (self.CurrentComponent:IsValid()) then
self.CurrentComponent:SetNetworkedBeamString("BlinkWire", self.CurrentInput)
end
end
elseif (self.Outputs) then
if (CLIENT) then return end
local iNextOutput
for k,v in pairs(self.Outputs) do
if (v == self.CurrentOutput) then iNextOutput = k+1 end
end
if (iNextOutput) then
self:GetOwner():EmitSound("weapons/pistol/pistol_empty.wav")
if (iNextOutput > table.getn(self.Outputs)) then iNextOutput = 1 end
self.CurrentOutput = self.Outputs[iNextOutput] or "" --if that's nil then somethis is wrong with the ent
local txt = "Output: "..self.CurrentOutput
if (self.OutputsDesc) and (self.OutputsDesc[self.CurrentOutput]) then
txt = txt.." ("..self.OutputsDesc[self.CurrentOutput]..")"
end
if (self.OutputsType) and (self.OutputsType[self.CurrentOutput])
and (self.OutputsType[self.CurrentOutput] != "NORMAL") then
txt = txt.." ["..self.OutputsType[self.CurrentOutput].."]"
end
self:GetWeapon():SetNetworkedString("WireCurrentInput", txt)
end
end
end
function TOOL:Reload(trace)
return false
end
function TOOL:Holster()
self:SelectComponent(nil)
end
if (CLIENT) then
function TOOL:DrawHUD()
local current_input = self:GetWeapon():GetNetworkedString("WireCurrentInput") or ""
if (current_input ~= "") then
if (string.sub(current_input, 1, 1) == "%") then
draw.WordBox(8, ScrW()/2+10, ScrH()/2+10, string.sub(current_input, 2), "Default", Color(150,50,50,192), Color(255,255,255,255) )
else
draw.WordBox(8, ScrW()/2+10, ScrH()/2+10, current_input, "Default", Color(50,50,75,192), Color(255,255,255,255) )
end
end
end
end
function TOOL:Think()
if (self:GetStage() == 0) then
local player = self:GetOwner()
local tr = util.GetPlayerTrace(player, player:GetAimVector())
local trace = util.TraceLine(tr)
if (trace.Hit) and (trace.Entity:IsValid()) then
self:SelectComponent(trace.Entity)
else
self:SelectComponent(nil)
end
end
end
function TOOL.BuildCPanel(panel)
panel:AddControl("Header", { Text = "#Tool.wire_simulate_data.name", Description = "#Tool.wire_simulate_data.desc" })
panel:AddControl("ComboBox", {
Label = "Data Type",
MenuButton = "0",
Folder = "wire_simulate_data",
Options = {
Number = {wire_simulate_data_type = "NORMAL"},
String = {wire_simulate_data_type = "STRING"},
Vector = {wire_simulate_data_type = "VECTOR"},
Entity = {wire_simulate_data_type = "ENTITY"},
Angle = {wire_simulate_data_type = "ANGLE"},
Table = {wire_simulate_data_type = "TABLE"},
Array = {wire_simulate_data_type = "ARRAY"},
},
CVars = {
[0] = "wire_simulate_data_type",
}
})
panel:AddControl("CheckBox", {
Label = "Automatically Choose Type",
Command = "wire_simulate_data_auto"
})
panel:AddControl("Slider", {
Label = "Number Value:",
Type = "Float",
Min = "-10",
Max = "10",
Command = "wire_simulate_data_number",
})
panel:AddControl( "TextBox", {
Label = "String Value:",
Description = "Output String",
MaxLength = "64",
Text = "yeps",
WaitForEnter = "true",
Command = "wire_simulate_data_string",
} )
panel:AddControl("Label", {
Text = "Vector and Angle value:",
Description = "Output Vector"
} )
panel:AddControl("Color", {
Label = "Vector value:",
Red = "wire_simulate_data_vec1",
Green = "wire_simulate_data_vec2",
Blue = "wire_simulate_data_vec3",
ShowAlpha = 0,
ShowHSV = 1,
ShowRGB = 1,
Multiplier = "1",
})
panel:AddControl("Slider", {
Label = "EntityID value:",
Type = "Integer",
Min = "0",
Max = "100",
Command = "wire_simulate_data_entity",
})
panel:AddControl( "TextBox", {
Label = "Table:",
Description = "Output Table",
MaxLength = "64",
Text = "",
WaitForEnter = false,
Command = "wire_simulate_data_table",
} )
panel:AddControl("CheckBox", {
Label = "Expression2 Compatible Table",
Command = "wire_simulate_data_texp2"
})
panel:AddControl( "TextBox", {
Label = "Arrays:",
Description = "Output Array",
MaxLength = "64",
Text = "",
WaitForEnter = false,
Command = "wire_simulate_data_array",
} )
panel:AddControl("Label", {
Text = "Arrays currently fail to transfer",
Description = "Disclaimer"
} )
end
function TOOL:SelectComponent(ent)
if (CLIENT) then return end
if (self.CurrentComponent == ent) then return end
if (self.CurrentComponent) and (self.CurrentComponent:IsValid()) then
self.CurrentComponent:SetNetworkedBeamString("BlinkWire", "")
end
self.CurrentComponent = ent
self.CurrentInput = nil
self.Inputs = {}
self.InputsDesc = {}
self.InputsType = {}
local best = nil
local first = nil
if (ent) and (ent.Inputs) then
for k,v in pairs(ent.Inputs) do
if (not first) then first = k end
if (k == self.LastValidInput) then best = k end
if v.Num then
self.Inputs[v.Num] = k
else
table.insert(self.Inputs, k)
end
if (v.Desc) then
self.InputsDesc[k] = v.Desc
end
if (v.Type) then
self.InputsType[k] = v.Type
end
end
end
first = self.Inputs[1] or first
self.CurrentInput = best or first
if (self.CurrentInput) and (self.CurrentInput ~= "") then self.LastValidInput = self.CurrentInput end
local txt = ""
if (self.CurrentComponent) and (self.CurrentComponent:IsValid()) and (self.CurrentInput)
and (self.CurrentComponent.Inputs) and (self.CurrentComponent.Inputs[self.CurrentInput])
and (self.CurrentComponent.Inputs[self.CurrentInput].Src) then
txt = "%"..(self.CurrentInput or "")
else
txt = self.CurrentInput or ""
end
if (self.InputsDesc) and (self.InputsDesc[self.CurrentInput]) then
txt = txt.." ("..self.InputsDesc[self.CurrentInput]..")"
end
if (self.InputsType) and (self.InputsType[self.CurrentInput])
and (self.InputsType[self.CurrentInput] != "NORMAL") then
txt = txt.." ["..self.InputsType[self.CurrentInput].."]"
end
self:GetWeapon():SetNetworkedString("WireCurrentInput", txt)
if (self.CurrentComponent) and (self.CurrentComponent:IsValid()) then
self.CurrentComponent:SetNetworkedBeamString("BlinkWire", self.CurrentInput)
end
end
| gpl-3.0 |
ferstar/openwrt-dreambox | feeds/luci/luci/luci/applications/luci-statistics/luasrc/model/cbi/luci_statistics/email.lua | 4 | 1890 | --[[
Luci configuration model for statistics - collectd email plugin configuration
(c) 2008 Freifunk Leipzig / 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: email.lua 6060 2010-04-13 20:42:26Z jow $
]]--
m = Map("luci_statistics",
translate("E-Mail Plugin Configuration"),
translate(
"The email plugin creates a unix socket which can be used " ..
"to transmit email-statistics to a running collectd daemon. " ..
"This plugin is primarily intended to be used in conjunction " ..
"with Mail::SpamAssasin::Plugin::Collectd but can be used in " ..
"other ways as well."
))
-- collectd_email config section
s = m:section( NamedSection, "collectd_email", "luci_statistics" )
-- collectd_email.enable
enable = s:option( Flag, "enable", translate("Enable this plugin") )
enable.default = 0
-- collectd_email.socketfile (SocketFile)
socketfile = s:option( Value, "SocketFile" )
socketfile.default = "/var/run/collect-email.sock"
socketfile:depends( "enable", 1 )
-- collectd_email.socketgroup (SocketGroup)
socketgroup = s:option( Value, "SocketGroup" )
socketgroup.default = "nobody"
socketgroup.rmempty = true
socketgroup.optional = true
socketgroup:depends( "enable", 1 )
-- collectd_email.socketperms (SocketPerms)
socketperms = s:option( Value, "SocketPerms" )
socketperms.default = "0770"
socketperms.rmempty = true
socketperms.optional = true
socketperms:depends( "enable", 1 )
-- collectd_email.maxconns (MaxConns)
maxconns = s:option( Value, "MaxConns", translate("Maximum allowed connections") )
maxconns.default = 5
maxconns.isinteger = true
maxconns.rmempty = true
maxconns.optional = true
maxconns:depends( "enable", 1 )
return m
| gpl-2.0 |
Dadido3/D3classic | Lua/Buildmodes/Stickphysic.lua | 2 | 2764 | -- ############################ Build Line #############################
function Command_Build_Mode_Stick(Client_ID, Command, Text_0, Text_1, Arg_0, Arg_1, Arg_2, Arg_3, Arg_4)
System_Message_Network_Send(Client_ID, Lang_Get("", "Buildmode: Stick started"))
Build_Mode_Set(Client_ID, "Stick")
Build_Mode_State_Set(Client_ID, 0)
local Segments = 1
local Length = -1
if tonumber(Arg_0) ~= nil then
Segments = tonumber(Arg_0)
end
if tonumber(Arg_1) ~= nil then
Length = tonumber(Arg_1)
end
if Segments < 1 then
Segments = 1
end
Build_Mode_Long_Set(Client_ID, 0, Segments)
Build_Mode_Float_Set(Client_ID, 0, Length)
end
function Build_Mode_Stick(Client_ID, Map_ID, X, Y, Z, Mode, Block_Type)
if Mode == 1 then
local State = Build_Mode_State_Get(Client_ID)
if State == 0 then -- Ersten Punkt wählen
Build_Mode_Coordinate_Set(Client_ID, 0, X, Y, Z)
Build_Mode_State_Set(Client_ID, 1)
elseif State == 1 then -- Zweiten Punkt wählen und bauen
local Segment_Size_Max = 50
local X_0, Y_0, Z_0, X_1, Y_1, Z_1 = X, Y, Z, Build_Mode_Coordinate_Get(Client_ID, 0)
local D_X = X_1 - X_0
local D_Y = Y_1 - Y_0
local D_Z = Z_1 - Z_0
local Distance = math.sqrt(math.pow(D_X,2)+math.pow(D_Y,2)+math.pow(D_Z,2))
local Segments = Build_Mode_Long_Get(Client_ID, 0)--math.ceil(Distance / Segment_Size_Max)
local Length = Build_Mode_Float_Get(Client_ID, 0) / Segments
local M_X = D_X / Segments
local M_Y = D_Y / Segments
local M_Z = D_Z / Segments
local P_1 = Stickphysic_Entity_Add_Point(-1, Map_ID, X_0+0.5, Y_0+0.5, Z_0+0.5, 1)
local i
for i = 1, Segments do
local P_2 = Stickphysic_Entity_Add_Point(-1, Map_ID, X_0+M_X*i+0.5, Y_0+M_Y*i+0.5, Z_0+M_Z*i+0.5, 1)
Stickphysic_Entity_Add_Line(-1, Map_ID, P_1, P_2, Block_Type, Length)
P_1 = P_2
end
System_Message_Network_Send(Client_ID, Lang_Get("", "Buildmode: Stick created"))
--Build_Mode_Set(Client_ID, "Normal")
Build_Mode_Set(Client_ID, Build_Mode_Get(Client_ID))
Build_Mode_State_Set(Client_ID, 0)
end
end
end
-- ############################ Build Anchor #############################
function Command_Build_Mode_Anchor(Client_ID, Command, Text_0, Text_1, Arg_0, Arg_1, Arg_2, Arg_3, Arg_4)
System_Message_Network_Send(Client_ID, Lang_Get("", "Buildmode: Anchor started"))
Build_Mode_Set(Client_ID, "Anchor")
Build_Mode_State_Set(Client_ID, 0)
end
function Build_Mode_Anchor(Client_ID, Map_ID, X, Y, Z, Mode, Block_Type)
if Mode == 1 then
Stickphysic_Entity_Add_Anchor(-1, Map_ID, X+0.5, Y+0.5, Z+0.5, Block_Type)
System_Message_Network_Send(Client_ID, Lang_Get("", "Buildmode: Anchor created"))
Build_Mode_Set(Client_ID, Build_Mode_Get(Client_ID))
end
end | mit |
osgcc/ryzom | ryzom/common/data_common/r2/r2_features_timer.lua | 3 | 24324 | -- In Transalation file
-- Category : uiR2EdTimer --
-- CreationFrom : uiR2EdTimerParameters
-- uiR2EDtooltipCreateFeatureTimer -> tooltip
r2.Features.TimerFeature = {}
local feature = r2.Features.TimerFeature
feature.Name="TimerFeature"
feature.BanditCount = 0
feature.Description="A Timer"
feature.Components = {}
feature.Components.Timer =
{
PropertySheetHeader = r2.getDisplayButtonHeader("r2.events:openEditor()", "uiR2EdEditEventsButton"),
BaseClass="LogicEntity",
Name="Timer",
InEventUI = true,
Menu="ui:interface:r2ed_feature_menu",
DisplayerUI = "R2::CDisplayerLua",
DisplayerUIParams = "defaultUIDisplayer",
DisplayerVisual = "R2::CDisplayerVisualEntity",
-----------------------------------------------------------------------------------------------
Parameters = {},
ApplicableActions = {
"Activate", "Deactivate", "Pause", "Resume", "Trigger",
"add seconds", "sub seconds",
-- "Add 10 Seconds", "Add 1 minute", "Sub 10 seconds", "Sub 1 minute"
},
Events = {
"On Trigger",
"On Activation", "On Desactivation",
"On Pause", "On Resume"
},
Conditions = {
"is active", "is inactive", "is paused",
"is running", "is finished"
},
TextContexts = {},
TextParameters = {},
LiveParameters = {},
-----------------------------------------------------------------------------------------------
-- Category="uiR2EDRollout_Timer",
Prop =
{
{Name="InstanceId", Type="String", WidgetStyle="StaticText", Visible = false},
{Name="Name", Type="String", MaxNumChar="32"},
{Name="Components", Type="Table"},
{Name="Minutes", Type="Number", Min="0", Max="120", DefaultValue="0"},
{Name="Secondes",Type="Number", Min="0", Max="999", DefaultValue="30"},
{Name="Cyclic", Type="Number", WidgetStyle="Boolean", Min="0", Max="1", DefaultValue="0"},
{Name="Active", Type="Number", WidgetStyle="Boolean", DefaultValue="1"},
},
-----------------------------------------------------------------------------------------------
-- from base class
getParentTreeNode = function(this)
return this:getFeatureParentTreeNode()
end,
---------------------------------------------------------------------------------------------------------
getAvailableCommands = function(this, dest)
r2.Classes.LogicEntity.getAvailableCommands(this, dest) -- fill by ancestor
this:getAvailableDisplayModeCommands(dest)
end,
---------------------------------------------------------------------------------------------------------
-- from base class
appendInstancesByType = function(this, destTable, kind)
assert(type(kind) == "string")
--this:delegate():appendInstancesByType(destTable, kind)
r2.Classes.LogicEntity.appendInstancesByType(this, destTable, kind)
for k, component in specPairs(this.Components) do
component:appendInstancesByType(destTable, kind)
end
end,
---------------------------------------------------------------------------------------------------------
-- from base class
getSelectBarSons = function(this)
return Components
end,
---------------------------------------------------------------------------------------------------------
-- from base class
canHaveSelectBarSons = function(this)
return false;
end,
onPostCreate = function(this)
--this:createGhostComponents()
if this.User.DisplayProp and this.User.DisplayProp == 1 then
r2:setSelectedInstanceId(this.InstanceId)
r2:showProperties(this)
this.User.DisplayProp = nil
end
end,
pretranslate = function(this, context)
r2.Translator.createAiGroup(this, context)
end,
translate = function(this, context)
r2.Translator.translateAiGroup(this, context)
local time = this.Secondes + this.Minutes * 60
--local time = secs + min * 60
local rtNpcGrp = r2.Translator.getRtGroup(context, this.InstanceId)
if this.Active == 1 then
local action1 = r2.Translator.createAction("timer_set", rtNpcGrp.Id, 0, time)
local action2 = r2.Translator.createAction("generic_event_trigger", rtNpcGrp.Id, 0)
local action3 = r2.Translator.createAction("set_value", rtNpcGrp.Id, "v2", 0)
local action4 = r2.Translator.createAction("set_value", rtNpcGrp.Id, "Active", 1)
local action = r2.Translator.createAction("multi_actions", {action1, action2, action3, action4})
r2.Translator.translateAiGroupInitialState(this, context, action)
else
local action1 = r2.Translator.createAction("set_value", rtNpcGrp.Id, "v2", 0)
local action2 = r2.Translator.createAction("set_value", rtNpcGrp.Id, "Active", 0)
local action = r2.Translator.createAction("multi_actions", {action1, action2})
r2.Translator.translateAiGroupInitialState(this, context, action)
end
do
local actionTrigger = r2.Translator.createAction("set_value", rtNpcGrp.Id, "v2", 1)
r2.Translator.translateAiGroupEvent("timer_t0_triggered", this, context, actionTrigger)
end
--TODO: gestion v2 pour trigger
if this.Cyclic == 1 then
local states = r2.Translator.getRtStatesNames(context, this.InstanceId)
local eventHandler = r2.Translator.createEvent("timer_t0_triggered", states, rtNpcGrp.Id)
local action1 = r2.Translator.createAction("timer_set", rtNpcGrp.Id, 0, time)
local action2 = r2.Translator.createAction("generic_event_trigger", rtNpcGrp.Id, 0)
local action = r2.Translator.createAction("multi_actions", {action1, action2})
table.insert(context.RtAct.Events, eventHandler)
-- insert a npc_event_handler_action
table.insert(eventHandler.ActionsId, action.Id)
table.insert(context.RtAct.Actions, action)
else
local states = r2.Translator.getRtStatesNames(context, this.InstanceId)
local eventHandler = r2.Translator.createEvent("timer_t0_triggered", states, rtNpcGrp.Id)
local actionEmit = r2.Translator.createAction("generic_event_trigger", rtNpcGrp.Id, 1)
table.insert(context.RtAct.Events, eventHandler)
-- insert a npc_event_handler_action
table.insert(eventHandler.ActionsId, actionEmit.Id)
table.insert(context.RtAct.Actions, actionEmit)
end
end,
}
-- Specific to the component Timer
local component = feature.Components.Timer
function component.getLogicActionActivate(entity, context, action, rtNpcGrp)
local time = entity.Secondes + entity.Minutes * 60
local action1 = r2.Translator.createAction("timer_set", rtNpcGrp.Id, 0, time)
-- local action1 = r2.Translator.createAction("timer_enable", rtNpcGrp.Id, 0)
local action2 = r2.Translator.createAction("generic_event_trigger", rtNpcGrp.Id, 0)
local actionIfInactive = r2.Translator.createAction("if_value_equal", rtNpcGrp.Id, "Active", 0,
r2.Translator.createAction("multi_actions", {action1, action2}))
return actionIfInactive, actionIfInactive
end
function component.getLogicActionDeactivate(entity, context, action, rtNpcGrp)
local action2 = r2.Translator.createAction("timer_disable", rtNpcGrp.Id, 0)
local action1 = r2.Translator.createAction("generic_event_trigger", rtNpcGrp.Id, 1)
local retAction = r2.Translator.createAction("multi_actions", {action1, action2})
local actionIfActive = r2.Translator.createAction("if_value_equal", rtNpcGrp.Id, "Active", 1, retAction)
return actionIfActive, actionIfActive
end
function component.getLogicActionPause(entity, context, action, rtNpcGrp)
local action1 = r2.Translator.createAction("timer_suspend", rtNpcGrp.Id, 0)
local action2 = r2.Translator.createAction("generic_event_trigger", rtNpcGrp.Id, 2)
local multiAction = r2.Translator.createAction("multi_actions", {action1, action2})
local actionIsEnable = r2.Translator.createAction("timer_is_enable", rtNpcGrp.Id, 0);
local actionIf = r2.Translator.createAction("if_value_equal", rtNpcGrp.Id, "is_enable", 1, multiAction)
local retAction = r2.Translator.createAction("multi_actions", {actionIsEnable, actionIf})
assert(retAction)
return retAction, retAction
end
function component.getLogicActionResume(entity, context, action, rtNpcGrp)
local action1 = r2.Translator.createAction("timer_resume", rtNpcGrp.Id, 0)
local action2 = r2.Translator.createAction("generic_event_trigger", rtNpcGrp.Id, 3)
local multiAction = r2.Translator.createAction("multi_actions", {action1, action2})
local actionIsEnable = r2.Translator.createAction("timer_is_enable", rtNpcGrp.Id, 0);
local actionIf = r2.Translator.createAction("if_value_equal", rtNpcGrp.Id, "is_enable", 1, multiAction)
local retAction = r2.Translator.createAction("multi_actions", {actionIsEnable, actionIf})
assert(retAction)
return retAction, retAction
end
function component.getLogicActionTrigger(entity, context, action, rtNpcGrp)
local multiAction = r2.Translator.createAction("multi_actions", {
r2.Translator.createAction("set_value", rtNpcGrp.Id, "v2", 1),
r2.Translator.createAction("timer_trigger", rtNpcGrp.Id, 0)})
local actionIsEnable = r2.Translator.createAction("timer_is_enable", rtNpcGrp.Id, 0);
local actionIf = r2.Translator.createAction("if_value_equal", rtNpcGrp.Id, "is_enable", 1, multiAction)
local retAction = r2.Translator.createAction("multi_actions", {actionIsEnable, actionIf})
assert(retAction)
return retAction, retAction
end
function component.getLogicActionAddSeconds(entity, context, action, rtNpcGrp)
local value = 0
if action.Action.ValueString then value = tonumber(action.Action.ValueString) end
local timerAdd = r2.Translator.createAction("timer_add", rtNpcGrp.Id, 0, value)
local actionIsEnable = r2.Translator.createAction("timer_is_enable", rtNpcGrp.Id, 0);
local actionIf = r2.Translator.createAction("if_value_equal", rtNpcGrp.Id, "is_enable", 1, timerAdd)
local retAction = r2.Translator.createAction("multi_actions", {actionIsEnable, actionIf})
assert(retAction)
return retAction, retAction
end
function component.getLogicActionSubSeconds(entity, context, action, rtNpcGrp)
local value = 0
if action.Action.ValueString then value = tonumber(action.Action.ValueString) end
local actionSub = r2.Translator.createAction("timer_sub", rtNpcGrp.Id, 0, value)
local actionIsEnable = r2.Translator.createAction("timer_is_enable", rtNpcGrp.Id, 0);
local actionIf = r2.Translator.createAction("if_value_equal", rtNpcGrp.Id, "is_enable", 1, actionSub)
local retAction = r2.Translator.createAction("multi_actions", {actionIsEnable, actionIf})
assert(retAction)
return retAction, retAction
end
component.getLogicAction = function(entity, context, action)
assert( action.Class == "ActionStep")
local component = r2:getInstanceFromId(action.Entity)
assert(component)
local rtNpcGrp = r2.Translator.getRtGroup(context, component.InstanceId)
assert(rtNpcGrp)
local funs = {
["Activate"] = component.getLogicActionActivate,
["Deactivate"] = component.getLogicActionDeactivate,
["Pause"] = component.getLogicActionPause,
["Resume"] = component.getLogicActionResume,
["Trigger"] = component.getLogicActionTrigger,
["Add 10 Seconds"] = component.getLogicActionAdd10Seconds,
["Add 1 minute"] = component.getLogicActionAdd1Minute,
["Sub 10 seconds"] = component.getLogicActionSub0Seconds,
["Sub 1 minute"] = component.getLogicActionSub1Minute,
["sub seconds"] = component.getLogicActionSubSeconds,
["add seconds"] = component.getLogicActionAddSeconds,
}
local fun = funs[ action.Action.Type ]
if fun then
firstAction, lastAction = fun(entity, context, action, rtNpcGrp)
end
assert(firstAction)
return firstAction, lastAction
end
component.getLogicCondition = function(this, context, condition)
assert( condition.Class == "ConditionStep")
local component = r2:getInstanceFromId(condition.Entity)
assert(component)
local rtNpcGrp = r2.Translator.getRtGroup(context, component.InstanceId)
assert(rtNpcGrp)
local prefix = ""
if rtNpcGrp.Id and rtNpcGrp.Id ~= "" then
prefix = r2:getNamespace() .. rtNpcGrp.Id.."."
end
if condition.Condition.Type == "is active" then
local action1 = r2.Translator.createAction("timer_is_enable", rtNpcGrp.Id, 0);
local action2 = r2.Translator.createAction("condition_if", prefix.."is_enable == 1" );
local multiactions= r2.Translator.createAction("multi_actions", {action1, action2});
return multiactions, action2
elseif condition.Condition.Type == "is inactive" then
local action1 = r2.Translator.createAction("timer_is_enable", rtNpcGrp.Id, 0)
local action2 = r2.Translator.createAction("condition_if", prefix.."is_enable == 0")
local multiActions = r2.Translator.createAction("multi_actions", {action1, action2})
return multiActions, action2
elseif condition.Condition.Type == "is paused" then
local action1 = r2.Translator.createAction("timer_is_enable", rtNpcGrp.Id, 0);
local action2 = r2.Translator.createAction("timer_is_suspended", rtNpcGrp.Id, 0);
local actionSuspended = r2.Translator.createAction("condition_if", prefix.."is_suspended == 1");
local action3 = r2.Translator.createAction("condition_if", prefix.."is_enable == 1", actionSuspended);
local multiactions = r2.Translator.createAction("multi_actions", {action1, action2, action3});
return multiactions, actionSuspended
elseif condition.Condition.Type == "is running" then
local action1 = r2.Translator.createAction("timer_is_enable", rtNpcGrp.Id, 0);
local action2 = r2.Translator.createAction("timer_is_suspended", rtNpcGrp.Id, 0);
local actionSuspended = r2.Translator.createAction("condition_if", prefix.."is_suspended == 0");
local action3 = r2.Translator.createAction("condition_if", prefix.."is_enable == 1", actionSuspended);
local multiactions = r2.Translator.createAction("multi_actions", {action1, action2, action3});
return multiactions, actionSuspended
elseif condition.Condition.Type == "is finished" then
local action1 = r2.Translator.createAction("timer_is_enable", rtNpcGrp.Id, 0);
local action2 = r2.Translator.createAction("condition_if", prefix.."is_enable == 0");
local action3 = r2.Translator.createAction("condition_if", prefix.."v2 == 1", action2);
local multiactions= r2.Translator.createAction("multi_actions", {action1, action3});
return multiactions, action2
else
assert(nil)
end
return nil,nil
end
component.getLogicEvent = function(this, context, event)
assert( event.Class == "LogicEntityAction")
local component = this -- r2:getInstanceFromId(event.Entity)
assert(component)
local rtNpcGrp = r2.Translator.getRtGroup(context, component.InstanceId)
assert(rtNpcGrp)
local eventType = tostring(event.Event.Type)
local eventHandler, lastCondition = nil, nil
if eventType == "On Trigger" then
eventHandler, firstCondition, lastCondition = r2.Translator.createEvent("timer_t0_triggered", "", rtNpcGrp.Id)
--return r2.Translator.getComponentUserEvent(rtNpcGrp, 6)
elseif eventType == "On Activation" then
return r2.Translator.getComponentGenericEvent(rtNpcGrp, 0)
elseif eventType == "On Desactivation" then
return r2.Translator.getComponentGenericEvent(rtNpcGrp, 1)
elseif eventType == "On Pause" then
return r2.Translator.getComponentGenericEvent(rtNpcGrp, 2)
elseif eventType == "On Resume" then
return r2.Translator.getComponentGenericEvent(rtNpcGrp, 3)
end
return eventHandler, firstCondition, lastCondition
end
component.createComponent = function(x, y, secondes, minutes, cyclic)
local comp = r2.newComponent("Timer")
assert(comp)
comp.Base = r2.Translator.getDebugBase("palette.entities.botobjects.timer")
comp.Name = r2:genInstanceName(i18n.get("uiR2EdNameTimerFeature")):toUtf8()
comp.Position.x = x
comp.Position.y = y
comp.Position.z = r2:snapZToGround(x, y)
if minutes then comp.Minutes = minutes end
if secondes then comp.Secondes = secondes end
if cyclic then comp.Cyclic = cyclic end
return comp
end
component.create = function()
if not r2:checkAiQuota() then return end
local function paramsOk(resultTable)
local x = tonumber( resultTable["X"] )
local y = tonumber( resultTable["Y"] )
local minutes = tonumber( resultTable["Minutes"] )
local secondes = tonumber( resultTable["Secondes"] )
local cyclic = tonumber( resultTable["Cyclic"] )
local showAgain = tonumber(resultTable["Display"])
if not x or not y
then
debugInfo("Can't create Component")
return
end
local component = feature.Components.Timer.createComponent( x, y, secondes, minutes, cyclic)
r2:setCookie(component.InstanceId, "DisplayProp", 1)
r2.requestInsertNode(r2:getCurrentAct().InstanceId, "Features", -1, "", component)
end
local function paramsCancel()
debugInfo("Cancel form for 'Timer' creation")
end
local function posOk(x, y, z)
debugInfo(string.format("Validate creation of 'Timer' at pos (%d, %d, %d)", x, y, z))
if r2.mustDisplayInfo("Timer") == 1 then
r2.displayFeatureHelp("Timer")
end
r2.requestNewAction(i18n.get("uiR2EDNewTimerFeatureAction"))
local component = feature.Components.Timer.createComponent( x, y)
r2:setCookie(component.InstanceId, "DisplayProp", 1)
r2.requestInsertNode(r2:getCurrentAct().InstanceId, "Features", -1, "", component)
end
local function posCancel()
debugInfo("Cancel choice 'Timer' position")
end
local creature = r2.Translator.getDebugCreature("object_component_timer.creature")
r2:choosePos(creature, posOk, posCancel, "createFeatureTimer")
end
function feature.registerForms()
r2.Forms.TimerForm =
{
Caption = "uiR2EdTimerParameters",
PropertySheetHeader =
[[
<view type="text" id="t" multi_line="true" sizeref="w" w="-36" x="4" y="-2" posref="TL TL" global_color="true" fontsize="14" shadow="true" hardtext="uiR2EDTimerDescription"/>
]],
Prop =
{
{Name="Display", Type="Number", WidgetStyle="Boolean", DefaultValue="0", Translation="uiR2showMessageAgain", InvertWidget=true, CaptionWidth=5 },
-- following field are tmp for property sheet building testing
-- {Name="Minutes", Type="Number", Category="uiR2EDRollout_Timer", Min="0", Max="59", Default="0"},
-- {Name="Secondes", Type="Number", Category="uiR2EDRollout_Timer", Min="0", Max="59", Default="10"},
-- {Name="Cyclic", Type="Number", Category="uiR2EDRollout_Timer", WidgetStyle="Boolean", Min="0", Max="1", Default="0"},
-- {Name="Active", Type="Number", WidgetStyle="Boolean", Category="uiR2EDRollout_Default", DefaultValue="1"},
}
}
end
function component:getLogicTranslations()
-- register trad
local logicTranslations = {
["ApplicableActions"] = {
["Activate"] = { menu=i18n.get( "uiR2AA0Activate" ):toUtf8(),
text=i18n.get( "uiR2AA1Activate" ):toUtf8()},
["Deactivate"] = { menu=i18n.get( "uiR2AA0Deactivate" ):toUtf8(),
text=i18n.get( "uiR2AA1Deactivate" ):toUtf8()},
["Trigger"] = { menu=i18n.get( "uiR2AA0Trigger" ):toUtf8(),
text=i18n.get( "uiR2AA1Trigger" ):toUtf8()},
["Pause"] = { menu=i18n.get( "uiR2AA0TimerPause" ):toUtf8(),
text=i18n.get( "uiR2AA1TimerPause" ):toUtf8()},
["Resume"] = { menu=i18n.get( "uiR2AA0TimerResume" ):toUtf8(),
text=i18n.get( "uiR2AA1TimerResume" ):toUtf8()},
["Add 10 Seconds"] = { menu=i18n.get( "uiR2AA0TimerAdd10s" ):toUtf8(),
text=i18n.get( "uiR2AA1TimerAdds10s" ):toUtf8()},
["Add 1 minute"] = { menu=i18n.get( "uiR2AA0TimerAdd1m" ):toUtf8(),
text=i18n.get( "uiR2AA1TimerAdds1m" ):toUtf8()},
["Sub 10 seconds"] = { menu=i18n.get( "uiR2AA0TimerSub10s" ):toUtf8(),
text=i18n.get( "uiR2AA1TimerSubs10s" ):toUtf8()},
["Sub 1 minute"] = { menu=i18n.get( "uiR2AA0TimerSub1m" ):toUtf8(),
text=i18n.get( "uiR2AA1TimerSubs1m" ):toUtf8()},
["add seconds"] = { menu=i18n.get( "uiR2AA0TimerAddNSeconds" ):toUtf8(),
text=i18n.get( "uiR2AA1TimerAddNSeconds" ):toUtf8()},
["sub seconds"] = { menu=i18n.get( "uiR2AA0TimerSubNSeconds" ):toUtf8(),
text=i18n.get( "uiR2AA1TimerSubNSeconds" ):toUtf8()},
},
["Events"] = {
["On Activation"] = { menu=i18n.get( "uiR2Event0Activation" ):toUtf8(),
text=i18n.get( "uiR2Event1Activation" ):toUtf8()},
["On Desactivation"]= { menu=i18n.get( "uiR2Event0Deactivation" ):toUtf8(),
text=i18n.get( "uiR2Event1Deactivation" ):toUtf8()},
["On Trigger"] = { menu=i18n.get( "uiR2Event0Trigger" ):toUtf8(),
text=i18n.get( "uiR2Event1Trigger" ):toUtf8()},
["On Pause"] = { menu=i18n.get( "uiR2Event0TimerPause" ):toUtf8(),
text=i18n.get( "uiR2Event1TimerPause" ):toUtf8()},
["On Resume"] = { menu=i18n.get( "uiR2Event0TimerResume" ):toUtf8(),
text=i18n.get( "uiR2Event1TimerResume" ):toUtf8()},
},
["Conditions"] = {
["is active"] = { menu=i18n.get( "uiR2Test0Active" ):toUtf8(),
text=i18n.get( "uiR2Test1Active" ):toUtf8()},
["is inactive"] = { menu=i18n.get( "uiR2Test0Inactive" ):toUtf8(),
text=i18n.get( "uiR2Test1Inactive" ):toUtf8()},
["is paused"] = { menu=i18n.get( "uiR2Test0TimerPaused" ):toUtf8(),
text=i18n.get( "uiR2Test1TimerPaused" ):toUtf8()},
["is running"] = { menu=i18n.get( "uiR2Test0TimerRunning" ):toUtf8(),
text=i18n.get( "uiR2Test1TimerRunning" ):toUtf8()},
["is finished"] = { menu=i18n.get( "uiR2Test0TimerFinished" ):toUtf8(),
text=i18n.get( "uiR2Test1TimerFinished" ):toUtf8()},
}
}
return logicTranslations
end
function component.initEventValuesMenu(this, menu, categoryEvent)
--local startTime = nltime.getPreciseLocalTime()
for ev=0,menu:getNumLine()-1 do
local eventType = tostring(menu:getLineId(ev))
--local endTime = nltime.getPreciseLocalTime()
--debugInfo(string.format("time for 10 is %f", endTime - startTime))
--startTime = nltime.getPreciseLocalTime()
if r2.events.eventTypeWithValue[eventType] == "Number" then
menu:addSubMenu(ev)
local subMenu = menu:getSubMenu(ev)
local func = ""
-- for i=0, 9 do
-- local uc_name = ucstring()
-- uc_name:fromUtf8( tostring(i) )
-- func = "r2.events:setEventValue('','" .. categoryEvent .."','".. tostring(i).."')"
-- subMenu:addLine(uc_name, "lua", func, tostring(i))
-- end
--endTime = nltime.getPreciseLocalTime()
--debugInfo(string.format("time for 11 is %f", endTime - startTime))
--startTime = nltime.getPreciseLocalTime()
local lineNb = 0
for i=0, 50, 10 do
local lineStr = tostring(i).."/"..tostring(i+9)
subMenu:addLine(ucstring(lineStr), "", "", tostring(i))
--endTime = nltime.getPreciseLocalTime()
--debugInfo(string.format("time for 12 is %f", endTime - startTime))
--startTime = nltime.getPreciseLocalTime()
subMenu:addSubMenu(lineNb)
local subMenu2= subMenu:getSubMenu(lineNb)
for s=0,9 do
lineStr = tostring(i+s)
local func = "r2.events:setEventValue('','" .. categoryEvent .."','".. lineStr.."')"
subMenu2:addLine(ucstring(lineStr), "lua", func, lineStr)
end
lineNb = lineNb+1
--endTime = nltime.getPreciseLocalTime()
--debugInfo(string.format("time for 13 is %f", endTime - startTime))
--startTime = nltime.getPreciseLocalTime()
end
for i=0, 50, 10 do
local lineStr = tostring(i).." m /"..tostring(i+9).." m"
subMenu:addLine(ucstring(lineStr), "", "", tostring(i))
subMenu:addSubMenu(lineNb)
local subMenu2= subMenu:getSubMenu(lineNb)
local index = 0
--endTime = nltime.getPreciseLocalTime()
--debugInfo(string.format("time for 14 is %f", endTime - startTime))
--startTime = nltime.getPreciseLocalTime()
for m=0,9 do
lineStr = tostring( (i+m)*60)
-- local func = "r2.events:setEventValue('','" .. categoryEvent .."','".. lineStr.."')"
subMenu2:addLine(ucstring(tostring(i+m) .. "m"), "", "", lineStr)
subMenu2:addSubMenu(index)
local subMenu3= subMenu2:getSubMenu(index)
index = index + 1
for s=0, 55, 5 do
lineStr = tostring( (i+m)*60 + s)
local func = "r2.events:setEventValue('','" .. categoryEvent .."','".. lineStr.."')"
subMenu3:addLine(ucstring(tostring(i+m) .. "m ".. s .. "s"), "lua", func, lineStr)
end
end
lineNb = lineNb+1
--endTime = nltime.getPreciseLocalTime()
--debugInfo(string.format("time for 15 is %f", endTime - startTime))
--startTime = nltime.getPreciseLocalTime()
end
end
end
end
r2.Features["TimerFeature"] = feature
| agpl-3.0 |
xinjuncoding/skynet | 3rd/lpeg/re.lua | 160 | 6286 | -- $Id: re.lua,v 1.44 2013/03/26 20:11:40 roberto Exp $
-- imported functions and modules
local tonumber, type, print, error = tonumber, type, print, error
local setmetatable = setmetatable
local m = require"lpeg"
-- 'm' will be used to parse expressions, and 'mm' will be used to
-- create expressions; that is, 're' runs on 'm', creating patterns
-- on 'mm'
local mm = m
-- pattern's metatable
local mt = getmetatable(mm.P(0))
-- No more global accesses after this point
local version = _VERSION
if version == "Lua 5.2" then _ENV = nil end
local any = m.P(1)
-- Pre-defined names
local Predef = { nl = m.P"\n" }
local mem
local fmem
local gmem
local function updatelocale ()
mm.locale(Predef)
Predef.a = Predef.alpha
Predef.c = Predef.cntrl
Predef.d = Predef.digit
Predef.g = Predef.graph
Predef.l = Predef.lower
Predef.p = Predef.punct
Predef.s = Predef.space
Predef.u = Predef.upper
Predef.w = Predef.alnum
Predef.x = Predef.xdigit
Predef.A = any - Predef.a
Predef.C = any - Predef.c
Predef.D = any - Predef.d
Predef.G = any - Predef.g
Predef.L = any - Predef.l
Predef.P = any - Predef.p
Predef.S = any - Predef.s
Predef.U = any - Predef.u
Predef.W = any - Predef.w
Predef.X = any - Predef.x
mem = {} -- restart memoization
fmem = {}
gmem = {}
local mt = {__mode = "v"}
setmetatable(mem, mt)
setmetatable(fmem, mt)
setmetatable(gmem, mt)
end
updatelocale()
local I = m.P(function (s,i) print(i, s:sub(1, i-1)); return i end)
local function getdef (id, defs)
local c = defs and defs[id]
if not c then error("undefined name: " .. id) end
return c
end
local function patt_error (s, i)
local msg = (#s < i + 20) and s:sub(i)
or s:sub(i,i+20) .. "..."
msg = ("pattern error near '%s'"):format(msg)
error(msg, 2)
end
local function mult (p, n)
local np = mm.P(true)
while n >= 1 do
if n%2 >= 1 then np = np * p end
p = p * p
n = n/2
end
return np
end
local function equalcap (s, i, c)
if type(c) ~= "string" then return nil end
local e = #c + i
if s:sub(i, e - 1) == c then return e else return nil end
end
local S = (Predef.space + "--" * (any - Predef.nl)^0)^0
local name = m.R("AZ", "az", "__") * m.R("AZ", "az", "__", "09")^0
local arrow = S * "<-"
local seq_follow = m.P"/" + ")" + "}" + ":}" + "~}" + "|}" + (name * arrow) + -1
name = m.C(name)
-- a defined name only have meaning in a given environment
local Def = name * m.Carg(1)
local num = m.C(m.R"09"^1) * S / tonumber
local String = "'" * m.C((any - "'")^0) * "'" +
'"' * m.C((any - '"')^0) * '"'
local defined = "%" * Def / function (c,Defs)
local cat = Defs and Defs[c] or Predef[c]
if not cat then error ("name '" .. c .. "' undefined") end
return cat
end
local Range = m.Cs(any * (m.P"-"/"") * (any - "]")) / mm.R
local item = defined + Range + m.C(any)
local Class =
"["
* (m.C(m.P"^"^-1)) -- optional complement symbol
* m.Cf(item * (item - "]")^0, mt.__add) /
function (c, p) return c == "^" and any - p or p end
* "]"
local function adddef (t, k, exp)
if t[k] then
error("'"..k.."' already defined as a rule")
else
t[k] = exp
end
return t
end
local function firstdef (n, r) return adddef({n}, n, r) end
local function NT (n, b)
if not b then
error("rule '"..n.."' used outside a grammar")
else return mm.V(n)
end
end
local exp = m.P{ "Exp",
Exp = S * ( m.V"Grammar"
+ m.Cf(m.V"Seq" * ("/" * S * m.V"Seq")^0, mt.__add) );
Seq = m.Cf(m.Cc(m.P"") * m.V"Prefix"^0 , mt.__mul)
* (#seq_follow + patt_error);
Prefix = "&" * S * m.V"Prefix" / mt.__len
+ "!" * S * m.V"Prefix" / mt.__unm
+ m.V"Suffix";
Suffix = m.Cf(m.V"Primary" * S *
( ( m.P"+" * m.Cc(1, mt.__pow)
+ m.P"*" * m.Cc(0, mt.__pow)
+ m.P"?" * m.Cc(-1, mt.__pow)
+ "^" * ( m.Cg(num * m.Cc(mult))
+ m.Cg(m.C(m.S"+-" * m.R"09"^1) * m.Cc(mt.__pow))
)
+ "->" * S * ( m.Cg((String + num) * m.Cc(mt.__div))
+ m.P"{}" * m.Cc(nil, m.Ct)
+ m.Cg(Def / getdef * m.Cc(mt.__div))
)
+ "=>" * S * m.Cg(Def / getdef * m.Cc(m.Cmt))
) * S
)^0, function (a,b,f) return f(a,b) end );
Primary = "(" * m.V"Exp" * ")"
+ String / mm.P
+ Class
+ defined
+ "{:" * (name * ":" + m.Cc(nil)) * m.V"Exp" * ":}" /
function (n, p) return mm.Cg(p, n) end
+ "=" * name / function (n) return mm.Cmt(mm.Cb(n), equalcap) end
+ m.P"{}" / mm.Cp
+ "{~" * m.V"Exp" * "~}" / mm.Cs
+ "{|" * m.V"Exp" * "|}" / mm.Ct
+ "{" * m.V"Exp" * "}" / mm.C
+ m.P"." * m.Cc(any)
+ (name * -arrow + "<" * name * ">") * m.Cb("G") / NT;
Definition = name * arrow * m.V"Exp";
Grammar = m.Cg(m.Cc(true), "G") *
m.Cf(m.V"Definition" / firstdef * m.Cg(m.V"Definition")^0,
adddef) / mm.P
}
local pattern = S * m.Cg(m.Cc(false), "G") * exp / mm.P * (-any + patt_error)
local function compile (p, defs)
if mm.type(p) == "pattern" then return p end -- already compiled
local cp = pattern:match(p, 1, defs)
if not cp then error("incorrect pattern", 3) end
return cp
end
local function match (s, p, i)
local cp = mem[p]
if not cp then
cp = compile(p)
mem[p] = cp
end
return cp:match(s, i or 1)
end
local function find (s, p, i)
local cp = fmem[p]
if not cp then
cp = compile(p) / 0
cp = mm.P{ mm.Cp() * cp * mm.Cp() + 1 * mm.V(1) }
fmem[p] = cp
end
local i, e = cp:match(s, i or 1)
if i then return i, e - 1
else return i
end
end
local function gsub (s, p, rep)
local g = gmem[p] or {} -- ensure gmem[p] is not collected while here
gmem[p] = g
local cp = g[rep]
if not cp then
cp = compile(p)
cp = mm.Cs((cp / rep + 1)^0)
g[rep] = cp
end
return cp:match(s)
end
-- exported names
local re = {
compile = compile,
match = match,
find = find,
gsub = gsub,
updatelocale = updatelocale,
}
if version == "Lua 5.1" then _G.re = re end
return re
| mit |
rasolllll/tele_gold | libs/JSON.lua | 3765 | 34843 | -- -*- coding: utf-8 -*-
--
-- Simple JSON encoding and decoding in pure Lua.
--
-- Copyright 2010-2014 Jeffrey Friedl
-- http://regex.info/blog/
--
-- Latest version: http://regex.info/blog/lua/json
--
-- This code is released under a Creative Commons CC-BY "Attribution" License:
-- http://creativecommons.org/licenses/by/3.0/deed.en_US
--
-- It can be used for any purpose so long as the copyright notice above,
-- the web-page links above, and the 'AUTHOR_NOTE' string below are
-- maintained. Enjoy.
--
local VERSION = 20141223.14 -- version history at end of file
local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-"
--
-- The 'AUTHOR_NOTE' variable exists so that information about the source
-- of the package is maintained even in compiled versions. It's also
-- included in OBJDEF below mostly to quiet warnings about unused variables.
--
local OBJDEF = {
VERSION = VERSION,
AUTHOR_NOTE = AUTHOR_NOTE,
}
--
-- Simple JSON encoding and decoding in pure Lua.
-- http://www.json.org/
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
--
--
--
-- DECODING (from a JSON string to a Lua table)
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- If the JSON text is for an object or an array, e.g.
-- { "what": "books", "count": 3 }
-- or
-- [ "Larry", "Curly", "Moe" ]
--
-- the result is a Lua table, e.g.
-- { what = "books", count = 3 }
-- or
-- { "Larry", "Curly", "Moe" }
--
--
-- The encode and decode routines accept an optional second argument,
-- "etc", which is not used during encoding or decoding, but upon error
-- is passed along to error handlers. It can be of any type (including nil).
--
--
--
-- ERROR HANDLING
--
-- With most errors during decoding, this code calls
--
-- JSON:onDecodeError(message, text, location, etc)
--
-- with a message about the error, and if known, the JSON text being
-- parsed and the byte count where the problem was discovered. You can
-- replace the default JSON:onDecodeError() with your own function.
--
-- The default onDecodeError() merely augments the message with data
-- about the text and the location if known (and if a second 'etc'
-- argument had been provided to decode(), its value is tacked onto the
-- message as well), and then calls JSON.assert(), which itself defaults
-- to Lua's built-in assert(), and can also be overridden.
--
-- For example, in an Adobe Lightroom plugin, you might use something like
--
-- function JSON:onDecodeError(message, text, location, etc)
-- LrErrors.throwUserError("Internal Error: invalid JSON data")
-- end
--
-- or even just
--
-- function JSON.assert(message)
-- LrErrors.throwUserError("Internal Error: " .. message)
-- end
--
-- If JSON:decode() is passed a nil, this is called instead:
--
-- JSON:onDecodeOfNilError(message, nil, nil, etc)
--
-- and if JSON:decode() is passed HTML instead of JSON, this is called:
--
-- JSON:onDecodeOfHTMLError(message, text, nil, etc)
--
-- The use of the fourth 'etc' argument allows stronger coordination
-- between decoding and error reporting, especially when you provide your
-- own error-handling routines. Continuing with the the Adobe Lightroom
-- plugin example:
--
-- function JSON:onDecodeError(message, text, location, etc)
-- local note = "Internal Error: invalid JSON data"
-- if type(etc) = 'table' and etc.photo then
-- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName')
-- end
-- LrErrors.throwUserError(note)
-- end
--
-- :
-- :
--
-- for i, photo in ipairs(photosToProcess) do
-- :
-- :
-- local data = JSON:decode(someJsonText, { photo = photo })
-- :
-- :
-- end
--
--
--
--
--
-- DECODING AND STRICT TYPES
--
-- Because both JSON objects and JSON arrays are converted to Lua tables,
-- it's not normally possible to tell which original JSON type a
-- particular Lua table was derived from, or guarantee decode-encode
-- round-trip equivalency.
--
-- However, if you enable strictTypes, e.g.
--
-- JSON = assert(loadfile "JSON.lua")() --load the routines
-- JSON.strictTypes = true
--
-- then the Lua table resulting from the decoding of a JSON object or
-- JSON array is marked via Lua metatable, so that when re-encoded with
-- JSON:encode() it ends up as the appropriate JSON type.
--
-- (This is not the default because other routines may not work well with
-- tables that have a metatable set, for example, Lightroom API calls.)
--
--
-- ENCODING (from a lua table to a JSON string)
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
-- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false })
--
-- On error during encoding, this code calls:
--
-- JSON:onEncodeError(message, etc)
--
-- which you can override in your local JSON object.
--
-- The 'etc' in the error call is the second argument to encode()
-- and encode_pretty(), or nil if it wasn't provided.
--
--
-- PRETTY-PRINTING
--
-- An optional third argument, a table of options, allows a bit of
-- configuration about how the encoding takes place:
--
-- pretty = JSON:encode(val, etc, {
-- pretty = true, -- if false, no other options matter
-- indent = " ", -- this provides for a three-space indent per nesting level
-- align_keys = false, -- see below
-- })
--
-- encode() and encode_pretty() are identical except that encode_pretty()
-- provides a default options table if none given in the call:
--
-- { pretty = true, align_keys = false, indent = " " }
--
-- For example, if
--
-- JSON:encode(data)
--
-- produces:
--
-- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11}
--
-- then
--
-- JSON:encode_pretty(data)
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- The following three lines return identical results:
-- JSON:encode_pretty(data)
-- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " })
-- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " })
--
-- An example of setting your own indent string:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " })
--
-- produces:
--
-- {
-- | "city": "Kyoto",
-- | "climate": {
-- | | "avg_temp": 16,
-- | | "humidity": "high",
-- | | "snowfall": "minimal"
-- | },
-- | "country": "Japan",
-- | "wards": 11
-- }
--
-- An example of setting align_keys to true:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true })
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- which I must admit is kinda ugly, sorry. This was the default for
-- encode_pretty() prior to version 20141223.14.
--
--
-- AMBIGUOUS SITUATIONS DURING THE ENCODING
--
-- During the encode, if a Lua table being encoded contains both string
-- and numeric keys, it fits neither JSON's idea of an object, nor its
-- idea of an array. To get around this, when any string key exists (or
-- when non-positive numeric keys exist), numeric keys are converted to
-- strings.
--
-- For example,
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- produces the JSON object
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To prohibit this conversion and instead make it an error condition, set
-- JSON.noKeyConversion = true
--
--
-- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT
--
-- assert
-- onDecodeError
-- onDecodeOfNilError
-- onDecodeOfHTMLError
-- onEncodeError
--
-- If you want to create a separate Lua JSON object with its own error handlers,
-- you can reload JSON.lua or use the :new() method.
--
---------------------------------------------------------------------------
local default_pretty_indent = " "
local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent }
local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray
local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject
function OBJDEF:newArray(tbl)
return setmetatable(tbl or {}, isArray)
end
function OBJDEF:newObject(tbl)
return setmetatable(tbl or {}, isObject)
end
local function unicode_codepoint_as_utf8(codepoint)
--
-- codepoint is a number
--
if codepoint <= 127 then
return string.char(codepoint)
elseif codepoint <= 2047 then
--
-- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8
--
local highpart = math.floor(codepoint / 0x40)
local lowpart = codepoint - (0x40 * highpart)
return string.char(0xC0 + highpart,
0x80 + lowpart)
elseif codepoint <= 65535 then
--
-- 1110yyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x1000)
local remainder = codepoint - 0x1000 * highpart
local midpart = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midpart
highpart = 0xE0 + highpart
midpart = 0x80 + midpart
lowpart = 0x80 + lowpart
--
-- Check for an invalid character (thanks Andy R. at Adobe).
-- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070
--
if ( highpart == 0xE0 and midpart < 0xA0 ) or
( highpart == 0xED and midpart > 0x9F ) or
( highpart == 0xF0 and midpart < 0x90 ) or
( highpart == 0xF4 and midpart > 0x8F )
then
return "?"
else
return string.char(highpart,
midpart,
lowpart)
end
else
--
-- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x40000)
local remainder = codepoint - 0x40000 * highpart
local midA = math.floor(remainder / 0x1000)
remainder = remainder - 0x1000 * midA
local midB = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midB
return string.char(0xF0 + highpart,
0x80 + midA,
0x80 + midB,
0x80 + lowpart)
end
end
function OBJDEF:onDecodeError(message, text, location, etc)
if text then
if location then
message = string.format("%s at char %d of: %s", message, location, text)
else
message = string.format("%s: %s", message, text)
end
end
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError
OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError
function OBJDEF:onEncodeError(message, etc)
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
local function grok_number(self, text, start, etc)
--
-- Grab the integer part
--
local integer_part = text:match('^-?[1-9]%d*', start)
or text:match("^-?0", start)
if not integer_part then
self:onDecodeError("expected number", text, start, etc)
end
local i = start + integer_part:len()
--
-- Grab an optional decimal part
--
local decimal_part = text:match('^%.%d+', i) or ""
i = i + decimal_part:len()
--
-- Grab an optional exponential part
--
local exponent_part = text:match('^[eE][-+]?%d+', i) or ""
i = i + exponent_part:len()
local full_number_text = integer_part .. decimal_part .. exponent_part
local as_number = tonumber(full_number_text)
if not as_number then
self:onDecodeError("bad number", text, start, etc)
end
return as_number, i
end
local function grok_string(self, text, start, etc)
if text:sub(start,start) ~= '"' then
self:onDecodeError("expected string's opening quote", text, start, etc)
end
local i = start + 1 -- +1 to bypass the initial quote
local text_len = text:len()
local VALUE = ""
while i <= text_len do
local c = text:sub(i,i)
if c == '"' then
return VALUE, i + 1
end
if c ~= '\\' then
VALUE = VALUE .. c
i = i + 1
elseif text:match('^\\b', i) then
VALUE = VALUE .. "\b"
i = i + 2
elseif text:match('^\\f', i) then
VALUE = VALUE .. "\f"
i = i + 2
elseif text:match('^\\n', i) then
VALUE = VALUE .. "\n"
i = i + 2
elseif text:match('^\\r', i) then
VALUE = VALUE .. "\r"
i = i + 2
elseif text:match('^\\t', i) then
VALUE = VALUE .. "\t"
i = i + 2
else
local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if hex then
i = i + 6 -- bypass what we just read
-- We have a Unicode codepoint. It could be standalone, or if in the proper range and
-- followed by another in a specific range, it'll be a two-code surrogate pair.
local codepoint = tonumber(hex, 16)
if codepoint >= 0xD800 and codepoint <= 0xDBFF then
-- it's a hi surrogate... see whether we have a following low
local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if lo_surrogate then
i = i + 6 -- bypass the low surrogate we just read
codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16)
else
-- not a proper low, so we'll just leave the first codepoint as is and spit it out.
end
end
VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint)
else
-- just pass through what's escaped
VALUE = VALUE .. text:match('^\\(.)', i)
i = i + 2
end
end
end
self:onDecodeError("unclosed string", text, start, etc)
end
local function skip_whitespace(text, start)
local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2
if match_end then
return match_end + 1
else
return start
end
end
local grok_one -- assigned later
local function grok_object(self, text, start, etc)
if text:sub(start,start) ~= '{' then
self:onDecodeError("expected '{'", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '{'
local VALUE = self.strictTypes and self:newObject { } or { }
if text:sub(i,i) == '}' then
return VALUE, i + 1
end
local text_len = text:len()
while i <= text_len do
local key, new_i = grok_string(self, text, i, etc)
i = skip_whitespace(text, new_i)
if text:sub(i, i) ~= ':' then
self:onDecodeError("expected colon", text, i, etc)
end
i = skip_whitespace(text, i + 1)
local new_val, new_i = grok_one(self, text, i)
VALUE[key] = new_val
--
-- Expect now either '}' to end things, or a ',' to allow us to continue.
--
i = skip_whitespace(text, new_i)
local c = text:sub(i,i)
if c == '}' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '}'", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '{'", text, start, etc)
end
local function grok_array(self, text, start, etc)
if text:sub(start,start) ~= '[' then
self:onDecodeError("expected '['", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '['
local VALUE = self.strictTypes and self:newArray { } or { }
if text:sub(i,i) == ']' then
return VALUE, i + 1
end
local VALUE_INDEX = 1
local text_len = text:len()
while i <= text_len do
local val, new_i = grok_one(self, text, i)
-- can't table.insert(VALUE, val) here because it's a no-op if val is nil
VALUE[VALUE_INDEX] = val
VALUE_INDEX = VALUE_INDEX + 1
i = skip_whitespace(text, new_i)
--
-- Expect now either ']' to end things, or a ',' to allow us to continue.
--
local c = text:sub(i,i)
if c == ']' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '['", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '['", text, start, etc)
end
grok_one = function(self, text, start, etc)
-- Skip any whitespace
start = skip_whitespace(text, start)
if start > text:len() then
self:onDecodeError("unexpected end of string", text, nil, etc)
end
if text:find('^"', start) then
return grok_string(self, text, start, etc)
elseif text:find('^[-0123456789 ]', start) then
return grok_number(self, text, start, etc)
elseif text:find('^%{', start) then
return grok_object(self, text, start, etc)
elseif text:find('^%[', start) then
return grok_array(self, text, start, etc)
elseif text:find('^true', start) then
return true, start + 4
elseif text:find('^false', start) then
return false, start + 5
elseif text:find('^null', start) then
return nil, start + 4
else
self:onDecodeError("can't parse JSON", text, start, etc)
end
end
function OBJDEF:decode(text, etc)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc)
end
if text == nil then
self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc)
elseif type(text) ~= 'string' then
self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc)
end
if text:match('^%s*$') then
return nil
end
if text:match('^%s*<') then
-- Can't be JSON... we'll assume it's HTML
self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc)
end
--
-- Ensure that it's not UTF-32 or UTF-16.
-- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3),
-- but this package can't handle them.
--
if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then
self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc)
end
local success, value = pcall(grok_one, self, text, 1, etc)
if success then
return value
else
-- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert.
if self.assert then
self.assert(false, value)
else
assert(false, value)
end
-- and if we're still here, return a nil and throw the error message on as a second arg
return nil, value
end
end
local function backslash_replacement_function(c)
if c == "\n" then
return "\\n"
elseif c == "\r" then
return "\\r"
elseif c == "\t" then
return "\\t"
elseif c == "\b" then
return "\\b"
elseif c == "\f" then
return "\\f"
elseif c == '"' then
return '\\"'
elseif c == '\\' then
return '\\\\'
else
return string.format("\\u%04x", c:byte())
end
end
local chars_to_be_escaped_in_JSON_string
= '['
.. '"' -- class sub-pattern to match a double quote
.. '%\\' -- class sub-pattern to match a backslash
.. '%z' -- class sub-pattern to match a null
.. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters
.. ']'
local function json_string_literal(value)
local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function)
return '"' .. newval .. '"'
end
local function object_or_array(self, T, etc)
--
-- We need to inspect all the keys... if there are any strings, we'll convert to a JSON
-- object. If there are only numbers, it's a JSON array.
--
-- If we'll be converting to a JSON object, we'll want to sort the keys so that the
-- end result is deterministic.
--
local string_keys = { }
local number_keys = { }
local number_keys_must_be_strings = false
local maximum_number_key
for key in pairs(T) do
if type(key) == 'string' then
table.insert(string_keys, key)
elseif type(key) == 'number' then
table.insert(number_keys, key)
if key <= 0 or key >= math.huge then
number_keys_must_be_strings = true
elseif not maximum_number_key or key > maximum_number_key then
maximum_number_key = key
end
else
self:onEncodeError("can't encode table with a key of type " .. type(key), etc)
end
end
if #string_keys == 0 and not number_keys_must_be_strings then
--
-- An empty table, or a numeric-only array
--
if #number_keys > 0 then
return nil, maximum_number_key -- an array
elseif tostring(T) == "JSON array" then
return nil
elseif tostring(T) == "JSON object" then
return { }
else
-- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects
return nil
end
end
table.sort(string_keys)
local map
if #number_keys > 0 then
--
-- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array
-- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object.
--
if self.noKeyConversion then
self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc)
end
--
-- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings
--
map = { }
for key, val in pairs(T) do
map[key] = val
end
table.sort(number_keys)
--
-- Throw numeric keys in there as strings
--
for _, number_key in ipairs(number_keys) do
local string_key = tostring(number_key)
if map[string_key] == nil then
table.insert(string_keys , string_key)
map[string_key] = T[number_key]
else
self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc)
end
end
end
return string_keys, nil, map
end
--
-- Encode
--
-- 'options' is nil, or a table with possible keys:
-- pretty -- if true, return a pretty-printed version
-- indent -- a string (usually of spaces) used to indent each nested level
-- align_keys -- if true, align all the keys when formatting a table
--
local encode_value -- must predeclare because it calls itself
function encode_value(self, value, parents, etc, options, indent)
if value == nil then
return 'null'
elseif type(value) == 'string' then
return json_string_literal(value)
elseif type(value) == 'number' then
if value ~= value then
--
-- NaN (Not a Number).
-- JSON has no NaN, so we have to fudge the best we can. This should really be a package option.
--
return "null"
elseif value >= math.huge then
--
-- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should
-- really be a package option. Note: at least with some implementations, positive infinity
-- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is.
-- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">="
-- case first.
--
return "1e+9999"
elseif value <= -math.huge then
--
-- Negative infinity.
-- JSON has no INF, so we have to fudge the best we can. This should really be a package option.
--
return "-1e+9999"
else
return tostring(value)
end
elseif type(value) == 'boolean' then
return tostring(value)
elseif type(value) ~= 'table' then
self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc)
else
--
-- A table to be converted to either a JSON object or array.
--
local T = value
if type(options) ~= 'table' then
options = {}
end
if type(indent) ~= 'string' then
indent = ""
end
if parents[T] then
self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc)
else
parents[T] = true
end
local result_value
local object_keys, maximum_number_key, map = object_or_array(self, T, etc)
if maximum_number_key then
--
-- An array...
--
local ITEMS = { }
for i = 1, maximum_number_key do
table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent))
end
if options.pretty then
result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]"
else
result_value = "[" .. table.concat(ITEMS, ",") .. "]"
end
elseif object_keys then
--
-- An object
--
local TT = map or T
if options.pretty then
local KEYS = { }
local max_key_length = 0
for _, key in ipairs(object_keys) do
local encoded = encode_value(self, tostring(key), parents, etc, options, indent)
if options.align_keys then
max_key_length = math.max(max_key_length, #encoded)
end
table.insert(KEYS, encoded)
end
local key_indent = indent .. tostring(options.indent or "")
local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "")
local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s"
local COMBINED_PARTS = { }
for i, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent)
table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val))
end
result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}"
else
local PARTS = { }
for _, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, indent)
local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent)
table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val))
end
result_value = "{" .. table.concat(PARTS, ",") .. "}"
end
else
--
-- An empty array/object... we'll treat it as an array, though it should really be an option
--
result_value = "[]"
end
parents[T] = false
return result_value
end
end
function OBJDEF:encode(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or nil)
end
function OBJDEF:encode_pretty(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or default_pretty_options)
end
function OBJDEF.__tostring()
return "JSON encode/decode package"
end
OBJDEF.__index = OBJDEF
function OBJDEF:new(args)
local new = { }
if args then
for key, val in pairs(args) do
new[key] = val
end
end
return setmetatable(new, OBJDEF)
end
return OBJDEF:new()
--
-- Version history:
--
-- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really
-- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines
-- more flexible, and changed the default encode_pretty() to be more generally useful.
--
-- Added a third 'options' argument to the encode() and encode_pretty() routines, to control
-- how the encoding takes place.
--
-- Updated docs to add assert() call to the loadfile() line, just as good practice so that
-- if there is a problem loading JSON.lua, the appropriate error message will percolate up.
--
-- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string,
-- so that the source of the package, and its version number, are visible in compiled copies.
--
-- 20140911.12 Minor lua cleanup.
-- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'.
-- (Thanks to SmugMug's David Parry for these.)
--
-- 20140418.11 JSON nulls embedded within an array were being ignored, such that
-- ["1",null,null,null,null,null,"seven"],
-- would return
-- {1,"seven"}
-- It's now fixed to properly return
-- {1, nil, nil, nil, nil, nil, "seven"}
-- Thanks to "haddock" for catching the error.
--
-- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up.
--
-- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2",
-- and this caused some problems.
--
-- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate,
-- and had of course diverged (encode_pretty didn't get the fixes that encode got, so
-- sometimes produced incorrect results; thanks to Mattie for the heads up).
--
-- Handle encoding tables with non-positive numeric keys (unlikely, but possible).
--
-- If a table has both numeric and string keys, or its numeric keys are inappropriate
-- (such as being non-positive or infinite), the numeric keys are turned into
-- string keys appropriate for a JSON object. So, as before,
-- JSON:encode({ "one", "two", "three" })
-- produces the array
-- ["one","two","three"]
-- but now something with mixed key types like
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- instead of throwing an error produces an object:
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To maintain the prior throw-an-error semantics, set
-- JSON.noKeyConversion = true
--
-- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry.
--
-- 20130120.6 Comment update: added a link to the specific page on my blog where this code can
-- be found, so that folks who come across the code outside of my blog can find updates
-- more easily.
--
-- 20111207.5 Added support for the 'etc' arguments, for better error reporting.
--
-- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent.
--
-- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules:
--
-- * When encoding lua for JSON, Sparse numeric arrays are now handled by
-- spitting out full arrays, such that
-- JSON:encode({"one", "two", [10] = "ten"})
-- returns
-- ["one","two",null,null,null,null,null,null,null,"ten"]
--
-- In 20100810.2 and earlier, only up to the first non-null value would have been retained.
--
-- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999".
-- Version 20100810.2 and earlier created invalid JSON in both cases.
--
-- * Unicode surrogate pairs are now detected when decoding JSON.
--
-- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding
--
-- 20100731.1 initial public release
--
| gpl-2.0 |
elixboy/Yelixboy | libs/JSON.lua | 3765 | 34843 | -- -*- coding: utf-8 -*-
--
-- Simple JSON encoding and decoding in pure Lua.
--
-- Copyright 2010-2014 Jeffrey Friedl
-- http://regex.info/blog/
--
-- Latest version: http://regex.info/blog/lua/json
--
-- This code is released under a Creative Commons CC-BY "Attribution" License:
-- http://creativecommons.org/licenses/by/3.0/deed.en_US
--
-- It can be used for any purpose so long as the copyright notice above,
-- the web-page links above, and the 'AUTHOR_NOTE' string below are
-- maintained. Enjoy.
--
local VERSION = 20141223.14 -- version history at end of file
local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-"
--
-- The 'AUTHOR_NOTE' variable exists so that information about the source
-- of the package is maintained even in compiled versions. It's also
-- included in OBJDEF below mostly to quiet warnings about unused variables.
--
local OBJDEF = {
VERSION = VERSION,
AUTHOR_NOTE = AUTHOR_NOTE,
}
--
-- Simple JSON encoding and decoding in pure Lua.
-- http://www.json.org/
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
--
--
--
-- DECODING (from a JSON string to a Lua table)
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- If the JSON text is for an object or an array, e.g.
-- { "what": "books", "count": 3 }
-- or
-- [ "Larry", "Curly", "Moe" ]
--
-- the result is a Lua table, e.g.
-- { what = "books", count = 3 }
-- or
-- { "Larry", "Curly", "Moe" }
--
--
-- The encode and decode routines accept an optional second argument,
-- "etc", which is not used during encoding or decoding, but upon error
-- is passed along to error handlers. It can be of any type (including nil).
--
--
--
-- ERROR HANDLING
--
-- With most errors during decoding, this code calls
--
-- JSON:onDecodeError(message, text, location, etc)
--
-- with a message about the error, and if known, the JSON text being
-- parsed and the byte count where the problem was discovered. You can
-- replace the default JSON:onDecodeError() with your own function.
--
-- The default onDecodeError() merely augments the message with data
-- about the text and the location if known (and if a second 'etc'
-- argument had been provided to decode(), its value is tacked onto the
-- message as well), and then calls JSON.assert(), which itself defaults
-- to Lua's built-in assert(), and can also be overridden.
--
-- For example, in an Adobe Lightroom plugin, you might use something like
--
-- function JSON:onDecodeError(message, text, location, etc)
-- LrErrors.throwUserError("Internal Error: invalid JSON data")
-- end
--
-- or even just
--
-- function JSON.assert(message)
-- LrErrors.throwUserError("Internal Error: " .. message)
-- end
--
-- If JSON:decode() is passed a nil, this is called instead:
--
-- JSON:onDecodeOfNilError(message, nil, nil, etc)
--
-- and if JSON:decode() is passed HTML instead of JSON, this is called:
--
-- JSON:onDecodeOfHTMLError(message, text, nil, etc)
--
-- The use of the fourth 'etc' argument allows stronger coordination
-- between decoding and error reporting, especially when you provide your
-- own error-handling routines. Continuing with the the Adobe Lightroom
-- plugin example:
--
-- function JSON:onDecodeError(message, text, location, etc)
-- local note = "Internal Error: invalid JSON data"
-- if type(etc) = 'table' and etc.photo then
-- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName')
-- end
-- LrErrors.throwUserError(note)
-- end
--
-- :
-- :
--
-- for i, photo in ipairs(photosToProcess) do
-- :
-- :
-- local data = JSON:decode(someJsonText, { photo = photo })
-- :
-- :
-- end
--
--
--
--
--
-- DECODING AND STRICT TYPES
--
-- Because both JSON objects and JSON arrays are converted to Lua tables,
-- it's not normally possible to tell which original JSON type a
-- particular Lua table was derived from, or guarantee decode-encode
-- round-trip equivalency.
--
-- However, if you enable strictTypes, e.g.
--
-- JSON = assert(loadfile "JSON.lua")() --load the routines
-- JSON.strictTypes = true
--
-- then the Lua table resulting from the decoding of a JSON object or
-- JSON array is marked via Lua metatable, so that when re-encoded with
-- JSON:encode() it ends up as the appropriate JSON type.
--
-- (This is not the default because other routines may not work well with
-- tables that have a metatable set, for example, Lightroom API calls.)
--
--
-- ENCODING (from a lua table to a JSON string)
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
-- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false })
--
-- On error during encoding, this code calls:
--
-- JSON:onEncodeError(message, etc)
--
-- which you can override in your local JSON object.
--
-- The 'etc' in the error call is the second argument to encode()
-- and encode_pretty(), or nil if it wasn't provided.
--
--
-- PRETTY-PRINTING
--
-- An optional third argument, a table of options, allows a bit of
-- configuration about how the encoding takes place:
--
-- pretty = JSON:encode(val, etc, {
-- pretty = true, -- if false, no other options matter
-- indent = " ", -- this provides for a three-space indent per nesting level
-- align_keys = false, -- see below
-- })
--
-- encode() and encode_pretty() are identical except that encode_pretty()
-- provides a default options table if none given in the call:
--
-- { pretty = true, align_keys = false, indent = " " }
--
-- For example, if
--
-- JSON:encode(data)
--
-- produces:
--
-- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11}
--
-- then
--
-- JSON:encode_pretty(data)
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- The following three lines return identical results:
-- JSON:encode_pretty(data)
-- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " })
-- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " })
--
-- An example of setting your own indent string:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " })
--
-- produces:
--
-- {
-- | "city": "Kyoto",
-- | "climate": {
-- | | "avg_temp": 16,
-- | | "humidity": "high",
-- | | "snowfall": "minimal"
-- | },
-- | "country": "Japan",
-- | "wards": 11
-- }
--
-- An example of setting align_keys to true:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true })
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- which I must admit is kinda ugly, sorry. This was the default for
-- encode_pretty() prior to version 20141223.14.
--
--
-- AMBIGUOUS SITUATIONS DURING THE ENCODING
--
-- During the encode, if a Lua table being encoded contains both string
-- and numeric keys, it fits neither JSON's idea of an object, nor its
-- idea of an array. To get around this, when any string key exists (or
-- when non-positive numeric keys exist), numeric keys are converted to
-- strings.
--
-- For example,
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- produces the JSON object
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To prohibit this conversion and instead make it an error condition, set
-- JSON.noKeyConversion = true
--
--
-- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT
--
-- assert
-- onDecodeError
-- onDecodeOfNilError
-- onDecodeOfHTMLError
-- onEncodeError
--
-- If you want to create a separate Lua JSON object with its own error handlers,
-- you can reload JSON.lua or use the :new() method.
--
---------------------------------------------------------------------------
local default_pretty_indent = " "
local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent }
local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray
local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject
function OBJDEF:newArray(tbl)
return setmetatable(tbl or {}, isArray)
end
function OBJDEF:newObject(tbl)
return setmetatable(tbl or {}, isObject)
end
local function unicode_codepoint_as_utf8(codepoint)
--
-- codepoint is a number
--
if codepoint <= 127 then
return string.char(codepoint)
elseif codepoint <= 2047 then
--
-- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8
--
local highpart = math.floor(codepoint / 0x40)
local lowpart = codepoint - (0x40 * highpart)
return string.char(0xC0 + highpart,
0x80 + lowpart)
elseif codepoint <= 65535 then
--
-- 1110yyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x1000)
local remainder = codepoint - 0x1000 * highpart
local midpart = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midpart
highpart = 0xE0 + highpart
midpart = 0x80 + midpart
lowpart = 0x80 + lowpart
--
-- Check for an invalid character (thanks Andy R. at Adobe).
-- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070
--
if ( highpart == 0xE0 and midpart < 0xA0 ) or
( highpart == 0xED and midpart > 0x9F ) or
( highpart == 0xF0 and midpart < 0x90 ) or
( highpart == 0xF4 and midpart > 0x8F )
then
return "?"
else
return string.char(highpart,
midpart,
lowpart)
end
else
--
-- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x40000)
local remainder = codepoint - 0x40000 * highpart
local midA = math.floor(remainder / 0x1000)
remainder = remainder - 0x1000 * midA
local midB = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midB
return string.char(0xF0 + highpart,
0x80 + midA,
0x80 + midB,
0x80 + lowpart)
end
end
function OBJDEF:onDecodeError(message, text, location, etc)
if text then
if location then
message = string.format("%s at char %d of: %s", message, location, text)
else
message = string.format("%s: %s", message, text)
end
end
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError
OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError
function OBJDEF:onEncodeError(message, etc)
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
local function grok_number(self, text, start, etc)
--
-- Grab the integer part
--
local integer_part = text:match('^-?[1-9]%d*', start)
or text:match("^-?0", start)
if not integer_part then
self:onDecodeError("expected number", text, start, etc)
end
local i = start + integer_part:len()
--
-- Grab an optional decimal part
--
local decimal_part = text:match('^%.%d+', i) or ""
i = i + decimal_part:len()
--
-- Grab an optional exponential part
--
local exponent_part = text:match('^[eE][-+]?%d+', i) or ""
i = i + exponent_part:len()
local full_number_text = integer_part .. decimal_part .. exponent_part
local as_number = tonumber(full_number_text)
if not as_number then
self:onDecodeError("bad number", text, start, etc)
end
return as_number, i
end
local function grok_string(self, text, start, etc)
if text:sub(start,start) ~= '"' then
self:onDecodeError("expected string's opening quote", text, start, etc)
end
local i = start + 1 -- +1 to bypass the initial quote
local text_len = text:len()
local VALUE = ""
while i <= text_len do
local c = text:sub(i,i)
if c == '"' then
return VALUE, i + 1
end
if c ~= '\\' then
VALUE = VALUE .. c
i = i + 1
elseif text:match('^\\b', i) then
VALUE = VALUE .. "\b"
i = i + 2
elseif text:match('^\\f', i) then
VALUE = VALUE .. "\f"
i = i + 2
elseif text:match('^\\n', i) then
VALUE = VALUE .. "\n"
i = i + 2
elseif text:match('^\\r', i) then
VALUE = VALUE .. "\r"
i = i + 2
elseif text:match('^\\t', i) then
VALUE = VALUE .. "\t"
i = i + 2
else
local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if hex then
i = i + 6 -- bypass what we just read
-- We have a Unicode codepoint. It could be standalone, or if in the proper range and
-- followed by another in a specific range, it'll be a two-code surrogate pair.
local codepoint = tonumber(hex, 16)
if codepoint >= 0xD800 and codepoint <= 0xDBFF then
-- it's a hi surrogate... see whether we have a following low
local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if lo_surrogate then
i = i + 6 -- bypass the low surrogate we just read
codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16)
else
-- not a proper low, so we'll just leave the first codepoint as is and spit it out.
end
end
VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint)
else
-- just pass through what's escaped
VALUE = VALUE .. text:match('^\\(.)', i)
i = i + 2
end
end
end
self:onDecodeError("unclosed string", text, start, etc)
end
local function skip_whitespace(text, start)
local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2
if match_end then
return match_end + 1
else
return start
end
end
local grok_one -- assigned later
local function grok_object(self, text, start, etc)
if text:sub(start,start) ~= '{' then
self:onDecodeError("expected '{'", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '{'
local VALUE = self.strictTypes and self:newObject { } or { }
if text:sub(i,i) == '}' then
return VALUE, i + 1
end
local text_len = text:len()
while i <= text_len do
local key, new_i = grok_string(self, text, i, etc)
i = skip_whitespace(text, new_i)
if text:sub(i, i) ~= ':' then
self:onDecodeError("expected colon", text, i, etc)
end
i = skip_whitespace(text, i + 1)
local new_val, new_i = grok_one(self, text, i)
VALUE[key] = new_val
--
-- Expect now either '}' to end things, or a ',' to allow us to continue.
--
i = skip_whitespace(text, new_i)
local c = text:sub(i,i)
if c == '}' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '}'", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '{'", text, start, etc)
end
local function grok_array(self, text, start, etc)
if text:sub(start,start) ~= '[' then
self:onDecodeError("expected '['", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '['
local VALUE = self.strictTypes and self:newArray { } or { }
if text:sub(i,i) == ']' then
return VALUE, i + 1
end
local VALUE_INDEX = 1
local text_len = text:len()
while i <= text_len do
local val, new_i = grok_one(self, text, i)
-- can't table.insert(VALUE, val) here because it's a no-op if val is nil
VALUE[VALUE_INDEX] = val
VALUE_INDEX = VALUE_INDEX + 1
i = skip_whitespace(text, new_i)
--
-- Expect now either ']' to end things, or a ',' to allow us to continue.
--
local c = text:sub(i,i)
if c == ']' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '['", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '['", text, start, etc)
end
grok_one = function(self, text, start, etc)
-- Skip any whitespace
start = skip_whitespace(text, start)
if start > text:len() then
self:onDecodeError("unexpected end of string", text, nil, etc)
end
if text:find('^"', start) then
return grok_string(self, text, start, etc)
elseif text:find('^[-0123456789 ]', start) then
return grok_number(self, text, start, etc)
elseif text:find('^%{', start) then
return grok_object(self, text, start, etc)
elseif text:find('^%[', start) then
return grok_array(self, text, start, etc)
elseif text:find('^true', start) then
return true, start + 4
elseif text:find('^false', start) then
return false, start + 5
elseif text:find('^null', start) then
return nil, start + 4
else
self:onDecodeError("can't parse JSON", text, start, etc)
end
end
function OBJDEF:decode(text, etc)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc)
end
if text == nil then
self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc)
elseif type(text) ~= 'string' then
self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc)
end
if text:match('^%s*$') then
return nil
end
if text:match('^%s*<') then
-- Can't be JSON... we'll assume it's HTML
self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc)
end
--
-- Ensure that it's not UTF-32 or UTF-16.
-- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3),
-- but this package can't handle them.
--
if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then
self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc)
end
local success, value = pcall(grok_one, self, text, 1, etc)
if success then
return value
else
-- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert.
if self.assert then
self.assert(false, value)
else
assert(false, value)
end
-- and if we're still here, return a nil and throw the error message on as a second arg
return nil, value
end
end
local function backslash_replacement_function(c)
if c == "\n" then
return "\\n"
elseif c == "\r" then
return "\\r"
elseif c == "\t" then
return "\\t"
elseif c == "\b" then
return "\\b"
elseif c == "\f" then
return "\\f"
elseif c == '"' then
return '\\"'
elseif c == '\\' then
return '\\\\'
else
return string.format("\\u%04x", c:byte())
end
end
local chars_to_be_escaped_in_JSON_string
= '['
.. '"' -- class sub-pattern to match a double quote
.. '%\\' -- class sub-pattern to match a backslash
.. '%z' -- class sub-pattern to match a null
.. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters
.. ']'
local function json_string_literal(value)
local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function)
return '"' .. newval .. '"'
end
local function object_or_array(self, T, etc)
--
-- We need to inspect all the keys... if there are any strings, we'll convert to a JSON
-- object. If there are only numbers, it's a JSON array.
--
-- If we'll be converting to a JSON object, we'll want to sort the keys so that the
-- end result is deterministic.
--
local string_keys = { }
local number_keys = { }
local number_keys_must_be_strings = false
local maximum_number_key
for key in pairs(T) do
if type(key) == 'string' then
table.insert(string_keys, key)
elseif type(key) == 'number' then
table.insert(number_keys, key)
if key <= 0 or key >= math.huge then
number_keys_must_be_strings = true
elseif not maximum_number_key or key > maximum_number_key then
maximum_number_key = key
end
else
self:onEncodeError("can't encode table with a key of type " .. type(key), etc)
end
end
if #string_keys == 0 and not number_keys_must_be_strings then
--
-- An empty table, or a numeric-only array
--
if #number_keys > 0 then
return nil, maximum_number_key -- an array
elseif tostring(T) == "JSON array" then
return nil
elseif tostring(T) == "JSON object" then
return { }
else
-- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects
return nil
end
end
table.sort(string_keys)
local map
if #number_keys > 0 then
--
-- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array
-- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object.
--
if self.noKeyConversion then
self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc)
end
--
-- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings
--
map = { }
for key, val in pairs(T) do
map[key] = val
end
table.sort(number_keys)
--
-- Throw numeric keys in there as strings
--
for _, number_key in ipairs(number_keys) do
local string_key = tostring(number_key)
if map[string_key] == nil then
table.insert(string_keys , string_key)
map[string_key] = T[number_key]
else
self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc)
end
end
end
return string_keys, nil, map
end
--
-- Encode
--
-- 'options' is nil, or a table with possible keys:
-- pretty -- if true, return a pretty-printed version
-- indent -- a string (usually of spaces) used to indent each nested level
-- align_keys -- if true, align all the keys when formatting a table
--
local encode_value -- must predeclare because it calls itself
function encode_value(self, value, parents, etc, options, indent)
if value == nil then
return 'null'
elseif type(value) == 'string' then
return json_string_literal(value)
elseif type(value) == 'number' then
if value ~= value then
--
-- NaN (Not a Number).
-- JSON has no NaN, so we have to fudge the best we can. This should really be a package option.
--
return "null"
elseif value >= math.huge then
--
-- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should
-- really be a package option. Note: at least with some implementations, positive infinity
-- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is.
-- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">="
-- case first.
--
return "1e+9999"
elseif value <= -math.huge then
--
-- Negative infinity.
-- JSON has no INF, so we have to fudge the best we can. This should really be a package option.
--
return "-1e+9999"
else
return tostring(value)
end
elseif type(value) == 'boolean' then
return tostring(value)
elseif type(value) ~= 'table' then
self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc)
else
--
-- A table to be converted to either a JSON object or array.
--
local T = value
if type(options) ~= 'table' then
options = {}
end
if type(indent) ~= 'string' then
indent = ""
end
if parents[T] then
self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc)
else
parents[T] = true
end
local result_value
local object_keys, maximum_number_key, map = object_or_array(self, T, etc)
if maximum_number_key then
--
-- An array...
--
local ITEMS = { }
for i = 1, maximum_number_key do
table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent))
end
if options.pretty then
result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]"
else
result_value = "[" .. table.concat(ITEMS, ",") .. "]"
end
elseif object_keys then
--
-- An object
--
local TT = map or T
if options.pretty then
local KEYS = { }
local max_key_length = 0
for _, key in ipairs(object_keys) do
local encoded = encode_value(self, tostring(key), parents, etc, options, indent)
if options.align_keys then
max_key_length = math.max(max_key_length, #encoded)
end
table.insert(KEYS, encoded)
end
local key_indent = indent .. tostring(options.indent or "")
local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "")
local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s"
local COMBINED_PARTS = { }
for i, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent)
table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val))
end
result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}"
else
local PARTS = { }
for _, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, indent)
local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent)
table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val))
end
result_value = "{" .. table.concat(PARTS, ",") .. "}"
end
else
--
-- An empty array/object... we'll treat it as an array, though it should really be an option
--
result_value = "[]"
end
parents[T] = false
return result_value
end
end
function OBJDEF:encode(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or nil)
end
function OBJDEF:encode_pretty(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or default_pretty_options)
end
function OBJDEF.__tostring()
return "JSON encode/decode package"
end
OBJDEF.__index = OBJDEF
function OBJDEF:new(args)
local new = { }
if args then
for key, val in pairs(args) do
new[key] = val
end
end
return setmetatable(new, OBJDEF)
end
return OBJDEF:new()
--
-- Version history:
--
-- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really
-- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines
-- more flexible, and changed the default encode_pretty() to be more generally useful.
--
-- Added a third 'options' argument to the encode() and encode_pretty() routines, to control
-- how the encoding takes place.
--
-- Updated docs to add assert() call to the loadfile() line, just as good practice so that
-- if there is a problem loading JSON.lua, the appropriate error message will percolate up.
--
-- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string,
-- so that the source of the package, and its version number, are visible in compiled copies.
--
-- 20140911.12 Minor lua cleanup.
-- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'.
-- (Thanks to SmugMug's David Parry for these.)
--
-- 20140418.11 JSON nulls embedded within an array were being ignored, such that
-- ["1",null,null,null,null,null,"seven"],
-- would return
-- {1,"seven"}
-- It's now fixed to properly return
-- {1, nil, nil, nil, nil, nil, "seven"}
-- Thanks to "haddock" for catching the error.
--
-- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up.
--
-- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2",
-- and this caused some problems.
--
-- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate,
-- and had of course diverged (encode_pretty didn't get the fixes that encode got, so
-- sometimes produced incorrect results; thanks to Mattie for the heads up).
--
-- Handle encoding tables with non-positive numeric keys (unlikely, but possible).
--
-- If a table has both numeric and string keys, or its numeric keys are inappropriate
-- (such as being non-positive or infinite), the numeric keys are turned into
-- string keys appropriate for a JSON object. So, as before,
-- JSON:encode({ "one", "two", "three" })
-- produces the array
-- ["one","two","three"]
-- but now something with mixed key types like
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- instead of throwing an error produces an object:
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To maintain the prior throw-an-error semantics, set
-- JSON.noKeyConversion = true
--
-- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry.
--
-- 20130120.6 Comment update: added a link to the specific page on my blog where this code can
-- be found, so that folks who come across the code outside of my blog can find updates
-- more easily.
--
-- 20111207.5 Added support for the 'etc' arguments, for better error reporting.
--
-- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent.
--
-- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules:
--
-- * When encoding lua for JSON, Sparse numeric arrays are now handled by
-- spitting out full arrays, such that
-- JSON:encode({"one", "two", [10] = "ten"})
-- returns
-- ["one","two",null,null,null,null,null,null,null,"ten"]
--
-- In 20100810.2 and earlier, only up to the first non-null value would have been retained.
--
-- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999".
-- Version 20100810.2 and earlier created invalid JSON in both cases.
--
-- * Unicode surrogate pairs are now detected when decoding JSON.
--
-- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding
--
-- 20100731.1 initial public release
--
| gpl-2.0 |
samuelctabor/ardupilot | libraries/AP_Scripting/tests/math.lua | 26 | 25303 | -- $Id: math.lua,v 1.77 2016/06/23 15:17:20 roberto Exp roberto $
--[[
*****************************************************************************
* Copyright (C) 1994-2016 Lua.org, PUC-Rio.
*
* 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.
*****************************************************************************
]]
-- This code is copied from https://github.com/lua/tests and slightly modified to work within ArduPilot
gcs:send_text(6, "testing numbers and math lib")
local minint = math.mininteger
local maxint = math.maxinteger
local intbits = math.floor(math.log(maxint, 2) + 0.5) + 1
assert((1 << intbits) == 0)
assert(minint == 1 << (intbits - 1))
assert(maxint == minint - 1)
-- number of bits in the mantissa of a floating-point number
local floatbits = 24
do
local p = 2.0^floatbits
while p < p + 1.0 do
p = p * 2.0
floatbits = floatbits + 1
end
end
local function isNaN (x)
return (x ~= x)
end
assert(isNaN(0/0))
assert(not isNaN(1/0))
do
local x = 2.0^floatbits
assert(x > x - 1.0 and x == x + 1.0)
gcs:send_text(6, string.format("%d-bit integers, %d-bit (mantissa) floats",
intbits, floatbits))
end
assert(math.type(0) == "integer" and math.type(0.0) == "float"
and math.type("10") == nil)
local function checkerror (msg, f, ...)
local s, err = pcall(f, ...)
assert(not s and string.find(err, msg))
end
local msgf2i = "number.* has no integer representation"
-- float equality
function eq (a,b,limit)
if not limit then
if floatbits >= 50 then limit = 1E-11
else limit = 1E-5
end
end
-- a == b needed for +inf/-inf
return a == b or math.abs(a-b) <= limit
end
-- equality with types
function eqT (a,b)
return a == b and math.type(a) == math.type(b)
end
-- basic float notation
assert(0e12 == 0 and .0 == 0 and 0. == 0 and .2e2 == 20 and 2.E-1 == 0.2)
do
local a,b,c = "2", " 3e0 ", " 10 "
assert(a+b == 5 and -b == -3 and b+"2" == 5 and "10"-c == 0)
assert(type(a) == 'string' and type(b) == 'string' and type(c) == 'string')
assert(a == "2" and b == " 3e0 " and c == " 10 " and -c == -" 10 ")
assert(c%a == 0 and a^b == 08)
a = 0
assert(a == -a and 0 == -0)
end
do
local x = -1
local mz = 0/x -- minus zero
t = {[0] = 10, 20, 30, 40, 50}
assert(t[mz] == t[0] and t[-0] == t[0])
end
do -- tests for 'modf'
local a,b = math.modf(3.5)
assert(a == 3.0 and b == 0.5)
a,b = math.modf(-2.5)
assert(a == -2.0 and b == -0.5)
a,b = math.modf(-3e23)
assert(a == -3e23 and b == 0.0)
a,b = math.modf(3e35)
assert(a == 3e35 and b == 0.0)
a,b = math.modf(-1/0) -- -inf
assert(a == -1/0 and b == 0.0)
a,b = math.modf(1/0) -- inf
assert(a == 1/0 and b == 0.0)
a,b = math.modf(0/0) -- NaN
assert(isNaN(a) and isNaN(b))
a,b = math.modf(3) -- integer argument
assert(eqT(a, 3) and eqT(b, 0.0))
a,b = math.modf(minint)
assert(eqT(a, minint) and eqT(b, 0.0))
end
assert(math.huge > 10e30)
assert(-math.huge < -10e30)
-- integer arithmetic
assert(minint < minint + 1)
assert(maxint - 1 < maxint)
assert(0 - minint == minint)
assert(minint * minint == 0)
assert(maxint * maxint * maxint == maxint)
-- testing floor division and conversions
for _, i in pairs{-16, -15, -3, -2, -1, 0, 1, 2, 3, 15} do
for _, j in pairs{-16, -15, -3, -2, -1, 1, 2, 3, 15} do
for _, ti in pairs{0, 0.0} do -- try 'i' as integer and as float
for _, tj in pairs{0, 0.0} do -- try 'j' as integer and as float
local x = i + ti
local y = j + tj
assert(i//j == math.floor(i/j))
end
end
end
end
assert(1//0.0 == 1/0)
assert(-1 // 0.0 == -1/0)
assert(eqT(3.5 // 1.5, 2.0))
assert(eqT(3.5 // -1.5, -3.0))
assert(maxint // maxint == 1)
assert(maxint // 1 == maxint)
assert((maxint - 1) // maxint == 0)
assert(maxint // (maxint - 1) == 1)
assert(minint // minint == 1)
assert(minint // minint == 1)
assert((minint + 1) // minint == 0)
assert(minint // (minint + 1) == 1)
assert(minint // 1 == minint)
assert(minint // -1 == -minint)
assert(minint // -2 == 2^(intbits - 2))
assert(maxint // -1 == -maxint)
-- negative exponents
do
assert(2^-3 == 1 / 2^3)
assert(eq((-3)^-3, 1 / (-3)^3))
for i = -3, 3 do -- variables avoid constant folding
for j = -3, 3 do
-- domain errors (0^(-n)) are not portable
if not _port or i ~= 0 or j > 0 then
assert(eq(i^j, 1 / i^(-j)))
end
end
end
end
-- comparison between floats and integers (border cases)
if floatbits < intbits then
assert(2.0^floatbits == (1 << floatbits))
assert(2.0^floatbits - 1.0 == (1 << floatbits) - 1.0)
assert(2.0^floatbits - 1.0 ~= (1 << floatbits))
-- float is rounded, int is not
assert(2.0^floatbits + 1.0 ~= (1 << floatbits) + 1)
else -- floats can express all integers with full accuracy
assert(maxint == maxint + 0.0)
assert(maxint - 1 == maxint - 1.0)
assert(minint + 1 == minint + 1.0)
assert(maxint ~= maxint - 1.0)
end
assert(maxint + 0.0 == 2.0^(intbits - 1) - 1.0)
assert(minint + 0.0 == minint)
assert(minint + 0.0 == -2.0^(intbits - 1))
-- order between floats and integers
assert(1 < 1.1); assert(not (1 < 0.9))
assert(1 <= 1.1); assert(not (1 <= 0.9))
assert(-1 < -0.9); assert(not (-1 < -1.1))
assert(1 <= 1.1); assert(not (-1 <= -1.1))
assert(-1 < -0.9); assert(not (-1 < -1.1))
assert(-1 <= -0.9); assert(not (-1 <= -1.1))
assert(minint <= minint + 0.0)
assert(minint + 0.0 <= minint)
assert(not (minint < minint + 0.0))
assert(not (minint + 0.0 < minint))
assert(maxint < minint * -1.0)
assert(maxint <= minint * -1.0)
do
local fmaxi1 = 2^(intbits - 1)
assert(maxint < fmaxi1)
assert(maxint <= fmaxi1)
assert(not (fmaxi1 <= maxint))
assert(minint <= -2^(intbits - 1))
assert(-2^(intbits - 1) <= minint)
end
if floatbits < intbits then
gcs:send_text(6, "testing order (floats can't represent all int)")
local fmax = 2^floatbits
local ifmax = fmax | 0
assert(fmax < ifmax + 1)
assert(fmax - 1 < ifmax)
assert(-(fmax - 1) > -ifmax)
assert(not (fmax <= ifmax - 1))
assert(-fmax > -(ifmax + 1))
assert(not (-fmax >= -(ifmax - 1)))
assert(fmax/2 - 0.5 < ifmax//2)
assert(-(fmax/2 - 0.5) > -ifmax//2)
assert(maxint < 2^intbits)
assert(minint > -2^intbits)
assert(maxint <= 2^intbits)
assert(minint >= -2^intbits)
else
gcs:send_text(6, "testing order (floats can represent all ints)")
assert(maxint < maxint + 1.0)
assert(maxint < maxint + 0.5)
assert(maxint - 1.0 < maxint)
assert(maxint - 0.5 < maxint)
assert(not (maxint + 0.0 < maxint))
assert(maxint + 0.0 <= maxint)
assert(not (maxint < maxint + 0.0))
assert(maxint + 0.0 <= maxint)
assert(maxint <= maxint + 0.0)
assert(not (maxint + 1.0 <= maxint))
assert(not (maxint + 0.5 <= maxint))
assert(not (maxint <= maxint - 1.0))
assert(not (maxint <= maxint - 0.5))
assert(minint < minint + 1.0)
assert(minint < minint + 0.5)
assert(minint <= minint + 0.5)
assert(minint - 1.0 < minint)
assert(minint - 1.0 <= minint)
assert(not (minint + 0.0 < minint))
assert(not (minint + 0.5 < minint))
assert(not (minint < minint + 0.0))
assert(minint + 0.0 <= minint)
assert(minint <= minint + 0.0)
assert(not (minint + 1.0 <= minint))
assert(not (minint + 0.5 <= minint))
assert(not (minint <= minint - 1.0))
end
do
local NaN = 0/0
assert(not (NaN < 0))
assert(not (NaN > minint))
assert(not (NaN <= -9))
assert(not (NaN <= maxint))
assert(not (NaN < maxint))
assert(not (minint <= NaN))
assert(not (minint < NaN))
end
-- avoiding errors at compile time
--local function checkcompt (msg, code)
-- checkerror(msg, assert(load(code)))
--end
--checkcompt("divide by zero", "return 2 // 0")
--checkcompt(msgf2i, "return 2.3 >> 0")
--checkcompt(msgf2i, ("return 2.0^%d & 1"):format(intbits - 1))
--checkcompt("field 'huge'", "return math.huge << 1")
--checkcompt(msgf2i, ("return 1 | 2.0^%d"):format(intbits - 1))
--checkcompt(msgf2i, "return 2.3 ~ '0.0'")
-- testing overflow errors when converting from float to integer (runtime)
local function f2i (x) return x | x end
checkerror(msgf2i, f2i, math.huge) -- +inf
checkerror(msgf2i, f2i, -math.huge) -- -inf
checkerror(msgf2i, f2i, 0/0) -- NaN
if floatbits < intbits then
-- conversion tests when float cannot represent all integers
assert(maxint + 1.0 == maxint + 0.0)
assert(minint - 1.0 == minint + 0.0)
checkerror(msgf2i, f2i, maxint + 0.0)
assert(f2i(2.0^(intbits - 2)) == 1 << (intbits - 2))
assert(f2i(-2.0^(intbits - 2)) == -(1 << (intbits - 2)))
assert((2.0^(floatbits - 1) + 1.0) // 1 == (1 << (floatbits - 1)) + 1)
-- maximum integer representable as a float
local mf = maxint - (1 << (floatbits - intbits)) + 1
assert(f2i(mf + 0.0) == mf) -- OK up to here
mf = mf + 1
assert(f2i(mf + 0.0) ~= mf) -- no more representable
else
-- conversion tests when float can represent all integers
assert(maxint + 1.0 > maxint)
assert(minint - 1.0 < minint)
assert(f2i(maxint + 0.0) == maxint)
checkerror("no integer rep", f2i, maxint + 1.0)
checkerror("no integer rep", f2i, minint - 1.0)
end
-- 'minint' should be representable as a float no matter the precision
assert(f2i(minint + 0.0) == minint)
-- testing numeric strings
assert("2" + 1 == 3)
assert("2 " + 1 == 3)
assert(" -2 " + 1 == -1)
assert(" -0xa " + 1 == -9)
-- Literal integer Overflows (new behavior in 5.3.3)
do
-- no overflows
assert(eqT(tonumber(tostring(maxint)), maxint))
assert(eqT(tonumber(tostring(minint)), minint))
-- add 1 to last digit as a string (it cannot be 9...)
local function incd (n)
local s = string.format("%d", n)
s = string.gsub(s, "%d$", function (d)
assert(d ~= '9')
return string.char(string.byte(d) + 1)
end)
return s
end
-- 'tonumber' with overflow by 1
assert(eqT(tonumber(incd(maxint)), maxint + 1.0))
assert(eqT(tonumber(incd(minint)), minint - 1.0))
-- large numbers
assert(eqT(tonumber("1"..string.rep("0", 30)), 1e30))
assert(eqT(tonumber("-1"..string.rep("0", 30)), -1e30))
-- hexa format still wraps around
assert(eqT(tonumber("0x1"..string.rep("0", 30)), 0))
-- lexer in the limits
--assert(minint == load("return " .. minint)())
--assert(eqT(maxint, load("return " .. maxint)()))
assert(eqT(10000000000000000000000.0, 10000000000000000000000))
assert(eqT(-10000000000000000000000.0, -10000000000000000000000))
end
-- testing 'tonumber'
-- 'tonumber' with numbers
assert(tonumber(3.4) == 3.4)
assert(eqT(tonumber(3), 3))
assert(eqT(tonumber(maxint), maxint) and eqT(tonumber(minint), minint))
assert(tonumber(1/0) == 1/0)
-- 'tonumber' with strings
assert(tonumber("0") == 0)
assert(tonumber("") == nil)
assert(tonumber(" ") == nil)
assert(tonumber("-") == nil)
assert(tonumber(" -0x ") == nil)
assert(tonumber{} == nil)
assert(tonumber'+0.01' == 1/100 and tonumber'+.01' == 0.01 and
tonumber'.01' == 0.01 and tonumber'-1.' == -1 and
tonumber'+1.' == 1)
assert(tonumber'+ 0.01' == nil and tonumber'+.e1' == nil and
tonumber'1e' == nil and tonumber'1.0e+' == nil and
tonumber'.' == nil)
assert(tonumber('-012') == -010-2)
assert(tonumber('-1.2e2') == - - -120)
assert(tonumber("0xffffffffffff") == (1 << (4*12)) - 1)
assert(tonumber("0x"..string.rep("f", (intbits//4))) == -1)
assert(tonumber("-0x"..string.rep("f", (intbits//4))) == 1)
-- testing 'tonumber' with base
assert(tonumber(' 001010 ', 2) == 10)
assert(tonumber(' 001010 ', 10) == 001010)
assert(tonumber(' -1010 ', 2) == -10)
assert(tonumber('10', 36) == 36)
assert(tonumber(' -10 ', 36) == -36)
assert(tonumber(' +1Z ', 36) == 36 + 35)
assert(tonumber(' -1z ', 36) == -36 + -35)
assert(tonumber('-fFfa', 16) == -(10+(16*(15+(16*(15+(16*15)))))))
assert(tonumber(string.rep('1', (intbits - 2)), 2) + 1 == 2^(intbits - 2))
assert(tonumber('ffffFFFF', 16)+1 == (1 << 32))
assert(tonumber('0ffffFFFF', 16)+1 == (1 << 32))
assert(tonumber('-0ffffffFFFF', 16) - 1 == -(1 << 40))
for i = 2,36 do
local i2 = i * i
local i10 = i2 * i2 * i2 * i2 * i2 -- i^10
assert(tonumber('\t10000000000\t', i) == i10)
end
if not _soft then
-- tests with very long numerals
assert(tonumber("0x"..string.rep("f", 13)..".0") == 2.0^(4*13) - 1)
assert(tonumber("0x"..string.rep("f", 150)..".0") == 2.0^(4*150) - 1)
assert(tonumber("0x"..string.rep("f", 300)..".0") == 2.0^(4*300) - 1)
assert(tonumber("0x"..string.rep("f", 500)..".0") == 2.0^(4*500) - 1)
assert(tonumber('0x3.' .. string.rep('0', 1000)) == 3)
assert(tonumber('0x' .. string.rep('0', 1000) .. 'a') == 10)
assert(tonumber('0x0.' .. string.rep('0', 13).."1") == 2.0^(-4*14))
assert(tonumber('0x0.' .. string.rep('0', 150).."1") == 2.0^(-4*151))
assert(tonumber('0x0.' .. string.rep('0', 300).."1") == 2.0^(-4*301))
assert(tonumber('0x0.' .. string.rep('0', 500).."1") == 2.0^(-4*501))
assert(tonumber('0xe03' .. string.rep('0', 1000) .. 'p-4000') == 3587.0)
assert(tonumber('0x.' .. string.rep('0', 1000) .. '74p4004') == 0x7.4)
end
-- testing 'tonumber' for invalid formats
--[[
local function f (...)
if select('#', ...) == 1 then
return (...)
else
return "***"
end
end
assert(f(tonumber('fFfa', 15)) == nil)
assert(f(tonumber('099', 8)) == nil)
assert(f(tonumber('1\0', 2)) == nil)
assert(f(tonumber('', 8)) == nil)
assert(f(tonumber(' ', 9)) == nil)
assert(f(tonumber(' ', 9)) == nil)
assert(f(tonumber('0xf', 10)) == nil)
assert(f(tonumber('inf')) == nil)
assert(f(tonumber(' INF ')) == nil)
assert(f(tonumber('Nan')) == nil)
assert(f(tonumber('nan')) == nil)
assert(f(tonumber(' ')) == nil)
assert(f(tonumber('')) == nil)
assert(f(tonumber('1 a')) == nil)
assert(f(tonumber('1 a', 2)) == nil)
assert(f(tonumber('1\0')) == nil)
assert(f(tonumber('1 \0')) == nil)
assert(f(tonumber('1\0 ')) == nil)
assert(f(tonumber('e1')) == nil)
assert(f(tonumber('e 1')) == nil)
assert(f(tonumber(' 3.4.5 ')) == nil)
]]
-- testing 'tonumber' for invalid hexadecimal formats
assert(tonumber('0x') == nil)
assert(tonumber('x') == nil)
assert(tonumber('x3') == nil)
assert(tonumber('0x3.3.3') == nil) -- two decimal points
assert(tonumber('00x2') == nil)
assert(tonumber('0x 2') == nil)
assert(tonumber('0 x2') == nil)
assert(tonumber('23x') == nil)
assert(tonumber('- 0xaa') == nil)
assert(tonumber('-0xaaP ') == nil) -- no exponent
assert(tonumber('0x0.51p') == nil)
assert(tonumber('0x5p+-2') == nil)
-- testing hexadecimal numerals
assert(0x10 == 16 and 0xfff == 2^12 - 1 and 0XFB == 251)
assert(0x0p12 == 0 and 0x.0p-3 == 0)
assert(0xFFFFFFFF == (1 << 32) - 1)
assert(tonumber('+0x2') == 2)
assert(tonumber('-0xaA') == -170)
assert(tonumber('-0xffFFFfff') == -(1 << 32) + 1)
-- possible confusion with decimal exponent
assert(0E+1 == 0 and 0xE+1 == 15 and 0xe-1 == 13)
-- floating hexas
assert(tonumber(' 0x2.5 ') == 0x25/16)
assert(tonumber(' -0x2.5 ') == -0x25/16)
assert(tonumber(' +0x0.51p+8 ') == 0x51)
assert(0x.FfffFFFF == 1 - '0x.00000001')
assert('0xA.a' + 0 == 10 + 10/16)
assert(0xa.aP4 == 0XAA)
assert(0x4P-2 == 1)
assert(0x1.1 == '0x1.' + '+0x.1')
assert(0Xabcdef.0 == 0x.ABCDEFp+24)
assert(1.1 == 1.+.1)
assert(100.0 == 1E2 and .01 == 1e-2)
assert(1111111111 - 1111111110 == 1000.00e-03)
assert(1.1 == '1.'+'.1')
assert(tonumber'1111111111' - tonumber'1111111110' ==
tonumber" +0.001e+3 \n\t")
assert(0.1e-30 > 0.9E-31 and 0.9E30 < 0.1e31)
assert(0.123456 > 0.123455)
assert(tonumber('+1.23E18') == 1.23*10.0^18)
-- testing order operators
assert(not(1<1) and (1<2) and not(2<1))
assert(not('a'<'a') and ('a'<'b') and not('b'<'a'))
assert((1<=1) and (1<=2) and not(2<=1))
assert(('a'<='a') and ('a'<='b') and not('b'<='a'))
assert(not(1>1) and not(1>2) and (2>1))
assert(not('a'>'a') and not('a'>'b') and ('b'>'a'))
assert((1>=1) and not(1>=2) and (2>=1))
assert(('a'>='a') and not('a'>='b') and ('b'>='a'))
assert(1.3 < 1.4 and 1.3 <= 1.4 and not (1.3 < 1.3) and 1.3 <= 1.3)
-- testing mod operator
assert(eqT(-4 % 3, 2))
assert(eqT(4 % -3, -2))
assert(eqT(-4.0 % 3, 2.0))
assert(eqT(4 % -3.0, -2.0))
assert(math.pi - math.pi % 1 == 3)
assert(math.pi - math.pi % 0.001 == 3.141)
assert(eqT(minint % minint, 0))
assert(eqT(maxint % maxint, 0))
assert((minint + 1) % minint == minint + 1)
assert((maxint - 1) % maxint == maxint - 1)
assert(minint % maxint == maxint - 1)
assert(minint % -1 == 0)
assert(minint % -2 == 0)
assert(maxint % -2 == -1)
-- testing unsigned comparisons
assert(math.ult(3, 4))
assert(not math.ult(4, 4))
assert(math.ult(-2, -1))
assert(math.ult(2, -1))
assert(not math.ult(-2, -2))
assert(math.ult(maxint, minint))
assert(not math.ult(minint, maxint))
assert(eq(math.sin(-9.8)^2 + math.cos(-9.8)^2, 1))
assert(eq(math.tan(math.pi/4), 1))
assert(eq(math.sin(math.pi/2), 1) and eq(math.cos(math.pi/2), 0))
assert(eq(math.atan(1), math.pi/4) and eq(math.acos(0), math.pi/2) and
eq(math.asin(1), math.pi/2))
assert(eq(math.deg(math.pi/2), 90) and eq(math.rad(90), math.pi/2))
assert(math.abs(-10.43) == 10.43)
assert(eqT(math.abs(minint), minint))
assert(eqT(math.abs(maxint), maxint))
assert(eqT(math.abs(-maxint), maxint))
assert(eq(math.atan(1,0), math.pi/2))
assert(math.fmod(10,3) == 1)
assert(eq(math.sqrt(10)^2, 10))
assert(eq(math.log(2, 10), math.log(2)/math.log(10)))
assert(eq(math.log(2, 2), 1))
assert(eq(math.log(9, 3), 2))
assert(eq(math.exp(0), 1))
assert(eq(math.sin(10), math.sin(10%(2*math.pi))))
assert(tonumber(' 1.3e-2 ') == 1.3e-2)
assert(tonumber(' -1.00000000000001 ') == -1.00000000000001)
-- testing constant limits
-- 2^23 = 8388608
assert(8388609 + -8388609 == 0)
assert(8388608 + -8388608 == 0)
assert(8388607 + -8388607 == 0)
do -- testing floor & ceil
assert(eqT(math.floor(3.4), 3))
assert(eqT(math.ceil(3.4), 4))
assert(eqT(math.floor(-3.4), -4))
assert(eqT(math.ceil(-3.4), -3))
assert(eqT(math.floor(maxint), maxint))
assert(eqT(math.ceil(maxint), maxint))
assert(eqT(math.floor(minint), minint))
assert(eqT(math.floor(minint + 0.0), minint))
assert(eqT(math.ceil(minint), minint))
assert(eqT(math.ceil(minint + 0.0), minint))
assert(math.floor(1e50) == 1e50)
assert(math.ceil(1e50) == 1e50)
assert(math.floor(-1e50) == -1e50)
assert(math.ceil(-1e50) == -1e50)
for _, p in pairs{31,32,63,64} do
assert(math.floor(2^p) == 2^p)
assert(math.floor(2^p + 0.5) == 2^p)
assert(math.ceil(2^p) == 2^p)
assert(math.ceil(2^p - 0.5) == 2^p)
end
checkerror("number expected", math.floor, {})
checkerror("number expected", math.ceil, print)
assert(eqT(math.tointeger(minint), minint))
assert(eqT(math.tointeger(minint .. ""), minint))
assert(eqT(math.tointeger(maxint), maxint))
assert(eqT(math.tointeger(maxint .. ""), maxint))
assert(eqT(math.tointeger(minint + 0.0), minint))
assert(math.tointeger(0.0 - minint) == nil)
assert(math.tointeger(math.pi) == nil)
assert(math.tointeger(-math.pi) == nil)
assert(math.floor(math.huge) == math.huge)
assert(math.ceil(math.huge) == math.huge)
assert(math.tointeger(math.huge) == nil)
assert(math.floor(-math.huge) == -math.huge)
assert(math.ceil(-math.huge) == -math.huge)
assert(math.tointeger(-math.huge) == nil)
assert(math.tointeger("34.0") == 34)
assert(math.tointeger("34.3") == nil)
assert(math.tointeger({}) == nil)
assert(math.tointeger(0/0) == nil) -- NaN
end
-- testing fmod for integers
for i = -6, 6 do
for j = -6, 6 do
if j ~= 0 then
local mi = math.fmod(i, j)
local mf = math.fmod(i + 0.0, j)
assert(mi == mf)
assert(math.type(mi) == 'integer' and math.type(mf) == 'float')
if (i >= 0 and j >= 0) or (i <= 0 and j <= 0) or mi == 0 then
assert(eqT(mi, i % j))
end
end
end
end
assert(eqT(math.fmod(minint, minint), 0))
assert(eqT(math.fmod(maxint, maxint), 0))
assert(eqT(math.fmod(minint + 1, minint), minint + 1))
assert(eqT(math.fmod(maxint - 1, maxint), maxint - 1))
checkerror("zero", math.fmod, 3, 0)
do -- testing max/min
checkerror("value expected", math.max)
checkerror("value expected", math.min)
assert(eqT(math.max(3), 3))
assert(eqT(math.max(3, 5, 9, 1), 9))
assert(math.max(maxint, 10e60) == 10e60)
assert(eqT(math.max(minint, minint + 1), minint + 1))
assert(eqT(math.min(3), 3))
assert(eqT(math.min(3, 5, 9, 1), 1))
assert(math.min(3.2, 5.9, -9.2, 1.1) == -9.2)
assert(math.min(1.9, 1.7, 1.72) == 1.7)
assert(math.min(-10e60, minint) == -10e60)
assert(eqT(math.min(maxint, maxint - 1), maxint - 1))
assert(eqT(math.min(maxint - 2, maxint, maxint - 1), maxint - 2))
end
-- testing implicit convertions
local a,b = '10', '20'
assert(a*b == 200 and a+b == 30 and a-b == -10 and a/b == 0.5 and -b == -20)
assert(a == '10' and b == '20')
do
gcs:send_text(6, "testing -0 and NaN")
local mz, z = -0.0, 0.0
assert(mz == z)
assert(1/mz < 0 and 0 < 1/z)
local a = {[mz] = 1}
assert(a[z] == 1 and a[mz] == 1)
a[z] = 2
assert(a[z] == 2 and a[mz] == 2)
local inf = math.huge * 2 + 1
mz, z = -1/inf, 1/inf
assert(mz == z)
assert(1/mz < 0 and 0 < 1/z)
local NaN = inf - inf
assert(NaN ~= NaN)
assert(not (NaN < NaN))
assert(not (NaN <= NaN))
assert(not (NaN > NaN))
assert(not (NaN >= NaN))
assert(not (0 < NaN) and not (NaN < 0))
local NaN1 = 0/0
assert(NaN ~= NaN1 and not (NaN <= NaN1) and not (NaN1 <= NaN))
local a = {}
assert(not pcall(rawset, a, NaN, 1))
assert(a[NaN] == nil)
a[1] = 1
assert(not pcall(rawset, a, NaN, 1))
assert(a[NaN] == nil)
-- strings with same binary representation as 0.0 (might create problems
-- for constant manipulation in the pre-compiler)
local a1, a2, a3, a4, a5 = 0, 0, "\0\0\0\0\0\0\0\0", 0, "\0\0\0\0\0\0\0\0"
assert(a1 == a2 and a2 == a4 and a1 ~= a3)
assert(a3 == a5)
end
gcs:send_text(6, "testing 'math.random'")
math.randomseed(0)
do -- test random for floats
local max = -math.huge
local min = math.huge
for i = 0, 20000 do
local t = math.random()
assert(0 <= t and t < 1)
max = math.max(max, t)
min = math.min(min, t)
if eq(max, 1, 0.001) and eq(min, 0, 0.001) then
goto ok
end
end
-- loop ended without satisfing condition
assert(false)
::ok::
end
do
local function aux (p, lim) -- test random for small intervals
local x1, x2
if #p == 1 then x1 = 1; x2 = p[1]
else x1 = p[1]; x2 = p[2]
end
local mark = {}; local count = 0 -- to check that all values appeared
for i = 0, lim or 2000 do
local t = math.random(table.unpack(p))
assert(x1 <= t and t <= x2)
if not mark[t] then -- new value
mark[t] = true
count = count + 1
end
if count == x2 - x1 + 1 then -- all values appeared; OK
goto ok
end
end
-- loop ended without satisfing condition
assert(false)
::ok::
end
aux({-10,0})
aux({6})
aux({-10, 10})
aux({minint, minint})
aux({maxint, maxint})
aux({minint, minint + 9})
aux({maxint - 3, maxint})
end
do
local function aux(p1, p2) -- test random for large intervals
local max = minint
local min = maxint
local n = 200
local mark = {}; local count = 0 -- to count how many different values
for _ = 1, n do
local t = math.random(p1, p2)
max = math.max(max, t)
min = math.min(min, t)
if not mark[t] then -- new value
mark[t] = true
count = count + 1
end
end
-- at least 80% of values are different
assert(count >= n * 0.8)
-- min and max not too far from formal min and max
local diff = (p2 - p1) // 8
assert(min < p1 + diff and max > p2 - diff)
end
aux(0, maxint)
aux(1, maxint)
aux(minint, -1)
aux(minint // 2, maxint // 2)
end
for i=1,100 do
assert(math.random(maxint) > 0)
assert(math.random(minint, -1) < 0)
end
assert(not pcall(math.random, 1, 2, 3)) -- too many arguments
-- empty interval
assert(not pcall(math.random, minint + 1, minint))
assert(not pcall(math.random, maxint, maxint - 1))
assert(not pcall(math.random, maxint, minint))
-- interval too large
assert(not pcall(math.random, minint, 0))
assert(not pcall(math.random, -1, maxint))
assert(not pcall(math.random, minint // 2, maxint // 2 + 1))
function update()
gcs:send_text(6, 'Math tests passed')
return update, 1000
end
return update()
| gpl-3.0 |
yetsky/extra | luci/applications/luci-chinadns/luasrc/model/cbi/chinadns.lua | 8 | 1329 | --[[
RA-MOD
]]--
local fs = require "nixio.fs"
local running=(luci.sys.call("pidof chinadns > /dev/null") == 0)
if running then
m = Map("chinadns", translate("chinadns"), translate("chinadns is running"))
else
m = Map("chinadns", translate("chinadns"), translate("chinadns is not running"))
end
s = m:section(TypedSection, "chinadns", "")
s.anonymous = true
switch = s:option(Flag, "enabled", translate("Enable"))
switch.rmempty = false
upstream = s:option(Value, "dns", translate("Upstream DNS Server"))
upstream.optional = false
upstream.default = "114.114.114.114,8.8.8.8"
port = s:option(Value, "port", translate("Port"))
port.datatype = "range(0,65535)"
port.optional = false
chn = s:option(Value, "chn", translate("CHNroute"), "")
chn.template = "cbi/tvalue"
chn.size = 30
chn.rows = 10
chn.wrap = "off"
function chn.cfgvalue(self, section)
return fs.readfile("/etc/chinadns_chnroute.txt") or ""
end
function chn.write(self, section, value)
if value then
value = value:gsub("\r\n?", "\n")
fs.writefile("/tmp/chinadns_chnroute.txt", value)
if (fs.access("/etc/chinadns_chnroute.txt") ~= true or luci.sys.call("cmp -s /tmp/chinadns_chnroute.txt /etc/chinadns_chnroute.txt") == 1) then
fs.writefile("/etc/chinadns_chnroute.txt", value)
end
fs.remove("/tmp/chinadns_chnroute.txt")
end
end
return m
| gpl-2.0 |
aryajur/luarocks | src/luarocks/loader.lua | 20 | 8685 |
--- A module which installs a Lua package loader that is LuaRocks-aware.
-- This loader uses dependency information from the LuaRocks tree to load
-- correct versions of modules. It does this by constructing a "context"
-- table in the environment, which records which versions of packages were
-- used to load previous modules, so that the loader chooses versions
-- that are declared to be compatible with the ones loaded earlier.
local loaders = package.loaders or package.searchers
local package, require, ipairs, pairs, table, type, next, tostring, error =
package, require, ipairs, pairs, table, type, next, tostring, error
local unpack = unpack or table.unpack
--module("luarocks.loader")
local loader = {}
package.loaded["luarocks.loader"] = loader
local cfg = require("luarocks.cfg")
cfg.init_package_paths()
local path = require("luarocks.path")
local manif_core = require("luarocks.manif_core")
local deps = require("luarocks.deps")
loader.context = {}
-- Contains a table when rocks trees are loaded,
-- or 'false' to indicate rocks trees failed to load.
-- 'nil' indicates rocks trees were not attempted to be loaded yet.
loader.rocks_trees = nil
local function load_rocks_trees()
local any_ok = false
local trees = {}
for _, tree in ipairs(cfg.rocks_trees) do
local manifest, err = manif_core.load_local_manifest(path.rocks_dir(tree))
if manifest then
any_ok = true
table.insert(trees, {tree=tree, manifest=manifest})
end
end
if not any_ok then
loader.rocks_trees = false
return false
end
loader.rocks_trees = trees
return true
end
--- Process the dependencies of a package to determine its dependency
-- chain for loading modules.
-- @param name string: The name of an installed rock.
-- @param version string: The version of the rock, in string format
function loader.add_context(name, version)
-- assert(type(name) == "string")
-- assert(type(version) == "string")
if loader.context[name] then
return
end
loader.context[name] = version
if not loader.rocks_trees and not load_rocks_trees() then
return nil
end
for _, tree in ipairs(loader.rocks_trees) do
local manifest = tree.manifest
local pkgdeps
if manifest.dependencies and manifest.dependencies[name] then
pkgdeps = manifest.dependencies[name][version]
end
if not pkgdeps then
return nil
end
for _, dep in ipairs(pkgdeps) do
local pkg, constraints = dep.name, dep.constraints
for _, tree in ipairs(loader.rocks_trees) do
local entries = tree.manifest.repository[pkg]
if entries then
for version, pkgs in pairs(entries) do
if (not constraints) or deps.match_constraints(deps.parse_version(version), constraints) then
loader.add_context(pkg, version)
end
end
end
end
end
end
end
--- Internal sorting function.
-- @param a table: A provider table.
-- @param b table: Another provider table.
-- @return boolean: True if the version of a is greater than that of b.
local function sort_versions(a,b)
return a.version > b.version
end
--- Request module to be loaded through other loaders,
-- once the proper name of the module has been determined.
-- For example, in case the module "socket.core" has been requested
-- to the LuaRocks loader and it determined based on context that
-- the version 2.0.2 needs to be loaded and it is not the current
-- version, the module requested for the other loaders will be
-- "socket.core_2_0_2".
-- @param module The module name requested by the user, such as "socket.core"
-- @param name The rock name, such as "luasocket"
-- @param version The rock version, such as "2.0.2-1"
-- @param module_name The actual module name, such as "socket.core" or "socket.core_2_0_2".
-- @return table or (nil, string): The module table as returned by some other loader,
-- or nil followed by an error message if no other loader managed to load the module.
local function call_other_loaders(module, name, version, module_name)
for i, a_loader in ipairs(loaders) do
if a_loader ~= loader.luarocks_loader then
local results = { a_loader(module_name) }
if type(results[1]) == "function" then
return unpack(results)
end
end
end
return "Failed loading module "..module.." in LuaRocks rock "..name.." "..version
end
--- Search for a module in the rocks trees
-- @param module string: module name (eg. "socket.core")
-- @param filter_module_name function(string, string, string, string, number):
-- a function that takes the module name (eg "socket.core"), the rock name
-- (eg "luasocket"), the version (eg "2.0.2-1"), the path of the rocks tree
-- (eg "/usr/local"), and the numeric index of the matching entry, so the
-- filter function can know if the matching module was the first entry or not.
-- @return string, string, string, (string or table):
-- * name of the rock containing the module (eg. "luasocket")
-- * version of the rock (eg. "2.0.2-1")
-- * name of the module (eg. "socket.core", or "socket.core_2_0_2" if file is stored versioned).
-- * tree of the module (string or table in `rocks_trees` format)
local function select_module(module, filter_module_name)
--assert(type(module) == "string")
--assert(type(filter_module_name) == "function")
if not loader.rocks_trees and not load_rocks_trees() then
return nil
end
local providers = {}
for _, tree in ipairs(loader.rocks_trees) do
local entries = tree.manifest.modules[module]
if entries then
for i, entry in ipairs(entries) do
local name, version = entry:match("^([^/]*)/(.*)$")
local module_name = tree.manifest.repository[name][version][1].modules[module]
if type(module_name) ~= "string" then
error("Invalid data in manifest file for module "..tostring(module).." (invalid data for "..tostring(name).." "..tostring(version)..")")
end
module_name = filter_module_name(module_name, name, version, tree.tree, i)
if loader.context[name] == version then
return name, version, module_name
end
version = deps.parse_version(version)
table.insert(providers, {name = name, version = version, module_name = module_name, tree = tree})
end
end
end
if next(providers) then
table.sort(providers, sort_versions)
local first = providers[1]
return first.name, first.version.string, first.module_name, first.tree
end
end
--- Search for a module
-- @param module string: module name (eg. "socket.core")
-- @return string, string, string, (string or table):
-- * name of the rock containing the module (eg. "luasocket")
-- * version of the rock (eg. "2.0.2-1")
-- * name of the module (eg. "socket.core", or "socket.core_2_0_2" if file is stored versioned).
-- * tree of the module (string or table in `rocks_trees` format)
local function pick_module(module)
return
select_module(module, function(module_name, name, version, tree, i)
if i > 1 then
module_name = path.versioned_name(module_name, "", name, version)
end
module_name = path.path_to_module(module_name)
return module_name
end)
end
--- Return the pathname of the file that would be loaded for a module.
-- @param module string: module name (eg. "socket.core")
-- @return string: filename of the module (eg. "/usr/local/lib/lua/5.1/socket/core.so")
function loader.which(module)
local name, version, module_name = select_module(module, path.which_i)
return module_name
end
--- Package loader for LuaRocks support.
-- A module is searched in installed rocks that match the
-- current LuaRocks context. If module is not part of the
-- context, or if a context has not yet been set, the module
-- in the package with the highest version is used.
-- @param module string: The module name, like in plain require().
-- @return table: The module table (typically), like in plain
-- require(). See <a href="http://www.lua.org/manual/5.1/manual.html#pdf-require">require()</a>
-- in the Lua reference manual for details.
function loader.luarocks_loader(module)
local name, version, module_name = pick_module(module)
if not name then
return "No LuaRocks module found for "..module
else
loader.add_context(name, version)
return call_other_loaders(module, name, version, module_name)
end
end
table.insert(loaders, 1, loader.luarocks_loader)
return loader
| mit |
jcmoyer/hug | extensions/string.lua | 1 | 1536 | --
-- Copyright 2013 J.C. Moyer
--
-- 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.
--
--- Provides extra string functions.
-- @alias extensions
local extensions = {}
--- Splits a string on a delimiter.
-- @string s String to split.
-- @string p Pattern to split on.
-- @bool[opt=false] noempty If true, the resulting table will have any empty
-- entries removed from it. If false or omitted, empty entries will be
-- preserved.
-- @treturn table A table containing the pieces `s` was split into.
function extensions.split(s, p, noempty)
if s == '' then
return {}
end
noempty = noempty or false
local t = {}
local base = 1
local a, b = s:find(p, 1)
while a do
local part = s:sub(base, a - 1)
if #part > 0 or (#part == 0 and not noempty) then
t[#t + 1] = part
end
base = b + 1
a, b = s:find(p, base)
end
if base <= #s then
t[#t + 1] = s:sub(base)
elseif base > #s and not noempty then
t[#t + 1] = ''
end
return t
end
return extensions
| apache-2.0 |
weitjong/Urho3D | bin/Data/LuaScripts/20_HugeObjectCount.lua | 24 | 9039 | -- Huge object count example.
-- This sample demonstrates:
-- - Creating a scene with 250 x 250 simple objects
-- - Competing with http://yosoygames.com.ar/wp/2013/07/ogre-2-0-is-up-to-3x-faster/ :)
-- - Allowing examination of performance hotspots in the rendering code
-- - Optionally speeding up rendering by grouping objects with the StaticModelGroup component
require "LuaScripts/Utilities/Sample"
local boxNodes = {}
local animate = false
local useGroups = false
function Start()
-- Execute the common startup for samples
SampleStart()
-- Create the scene content
CreateScene()
-- Create the UI content
CreateInstructions()
-- Setup the viewport for displaying the scene
SetupViewport()
-- Set the mouse mode to use in the sample
SampleInitMouseMode(MM_RELATIVE)
-- Hook up to the frame update events
SubscribeToEvents()
end
function CreateScene()
if scene_ == nil then
scene_ = Scene()
else
scene_:Clear()
boxNodes = {}
end
-- Create the Octree component to the scene so that drawable objects can be rendered. Use default volume
-- (-1000, -1000, -1000) to (1000, 1000, 1000)
scene_:CreateComponent("Octree")
-- Create a Zone for ambient light & fog control
local zoneNode = scene_:CreateChild("Zone")
local zone = zoneNode:CreateComponent("Zone")
zone.boundingBox = BoundingBox(-1000.0, 1000.0)
zone.fogColor = Color(0.2, 0.2, 0.2)
zone.fogStart = 200.0
zone.fogEnd = 300.0
-- Create a directional light
local lightNode = scene_:CreateChild("DirectionalLight")
lightNode.direction = Vector3(-0.6, -1.0, -0.8) -- The direction vector does not need to be normalized
local light = lightNode:CreateComponent("Light")
light.lightType = LIGHT_DIRECTIONAL
if not useGroups then
light.color = Color(0.7, 0.35, 0.0)
-- Create individual box StaticModels in the scene
for y = -125, 125 do
for x = -125, 125 do
local boxNode = scene_:CreateChild("Box")
boxNode.position = Vector3(x * 0.3, 0.0, y * 0.3)
boxNode:SetScale(0.25)
local boxObject = boxNode:CreateComponent("StaticModel")
boxObject.model = cache:GetResource("Model", "Models/Box.mdl")
table.insert(boxNodes, boxNode)
end
end
else
light.color = Color(0.6, 0.6, 0.6)
light.specularIntensity = 1.5
-- Create StaticModelGroups in the scene
local lastGroup = nil
for y = -125, 125 do
for x = -125, 125 do
-- Create new group if no group yet, or the group has already "enough" objects. The tradeoff is between culling
-- accuracy and the amount of CPU processing needed for all the objects. Note that the group's own transform
-- does not matter, and it does not render anything if instance nodes are not added to it
if lastGroup == nil or lastGroup.numInstanceNodes >= 25 * 25 then
local boxGroupNode = scene_:CreateChild("BoxGroup")
lastGroup = boxGroupNode:CreateComponent("StaticModelGroup")
lastGroup.model = cache:GetResource("Model", "Models/Box.mdl")
end
local boxNode = scene_:CreateChild("Box")
boxNode.position = Vector3(x * 0.3, 0.0, y * 0.3)
boxNode:SetScale(0.25)
table.insert(boxNodes, boxNode)
lastGroup:AddInstanceNode(boxNode)
end
end
end
-- Create the camera. Create it outside the scene so that we can clear the whole scene without affecting it
if cameraNode == nil then
cameraNode = Node()
cameraNode.position = Vector3(0.0, 10.0, -100.0)
local camera = cameraNode:CreateComponent("Camera")
camera.farClip = 300.0
end
end
function CreateInstructions()
-- Construct new Text object, set string to display and font to use
local instructionText = ui.root:CreateChild("Text")
instructionText:SetText("Use WASD keys and mouse to move\n"..
"Space to toggle animation\n"..
"G to toggle object group optimization")
instructionText:SetFont(cache:GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15)
-- The text has multiple rows. Center them in relation to each other
instructionText.textAlignment = HA_CENTER
-- Position the text relative to the screen center
instructionText.horizontalAlignment = HA_CENTER
instructionText.verticalAlignment = VA_CENTER
instructionText:SetPosition(0, ui.root.height / 4)
end
function SetupViewport()
-- Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
local viewport = Viewport:new(scene_, cameraNode:GetComponent("Camera"))
renderer:SetViewport(0, viewport)
end
function SubscribeToEvents()
-- Subscribe HandleUpdate() function for processing update events
SubscribeToEvent("Update", "HandleUpdate")
end
function MoveCamera(timeStep)
-- Do not move if the UI has a focused element (the console)
if ui.focusElement ~= nil then
return
end
-- Movement speed as world units per second
local MOVE_SPEED = 20.0
-- Mouse sensitivity as degrees per pixel
local MOUSE_SENSITIVITY = 0.1
-- Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
local mouseMove = input.mouseMove
yaw = yaw + MOUSE_SENSITIVITY * mouseMove.x
pitch = pitch + MOUSE_SENSITIVITY * mouseMove.y
pitch = Clamp(pitch, -90.0, 90.0)
-- Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
cameraNode.rotation = Quaternion(pitch, yaw, 0.0)
-- Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
if input:GetKeyDown(KEY_W) then
cameraNode:Translate(Vector3(0.0, 0.0, 1.0) * MOVE_SPEED * timeStep)
end
if input:GetKeyDown(KEY_S) then
cameraNode:Translate(Vector3(0.0, 0.0, -1.0) * MOVE_SPEED * timeStep)
end
if input:GetKeyDown(KEY_A) then
cameraNode:Translate(Vector3(-1.0, 0.0, 0.0) * MOVE_SPEED * timeStep)
end
if input:GetKeyDown(KEY_D) then
cameraNode:Translate(Vector3(1.0, 0.0, 0.0) * MOVE_SPEED * timeStep)
end
end
function AnimateObjects(timeStep)
local ROTATE_SPEED = 15.0
local delta = ROTATE_SPEED * timeStep
local rotateQuat = Quaternion(delta, Vector3(0.0, 0.0, 1.0))
for i, v in ipairs(boxNodes) do
v:Rotate(rotateQuat)
end
end
function HandleUpdate(eventType, eventData)
-- Take the frame time step, which is stored as a float
local timeStep = eventData["TimeStep"]:GetFloat()
-- Toggle animation with space
if input:GetKeyPress(KEY_SPACE) then
animate = not animate
end
-- Toggle grouped / ungrouped mode
if input:GetKeyPress(KEY_G) then
useGroups = not useGroups
CreateScene()
end
-- Move the camera, scale movement with time step
MoveCamera(timeStep)
-- Animate scene if enabled
if animate then
AnimateObjects(timeStep)
end
end
-- Create XML patch instructions for screen joystick layout specific to this sample app
function GetScreenJoystickPatchString()
return
"<patch>" ..
" <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/attribute[@name='Is Visible']\" />" ..
" <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Group</replace>" ..
" <add sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]\">" ..
" <element type=\"Text\">" ..
" <attribute name=\"Name\" value=\"KeyBinding\" />" ..
" <attribute name=\"Text\" value=\"G\" />" ..
" </element>" ..
" </add>" ..
" <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/attribute[@name='Is Visible']\" />" ..
" <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Animation</replace>" ..
" <add sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]\">" ..
" <element type=\"Text\">" ..
" <attribute name=\"Name\" value=\"KeyBinding\" />" ..
" <attribute name=\"Text\" value=\"SPACE\" />" ..
" </element>" ..
" </add>" ..
"</patch>"
end
| mit |
lcheylus/haka | sample/stats/stats_utils.lua | 5 | 2760 |
local function group_by(tab, field)
local ret = {}
for _, entry in ipairs(tab) do
local value = entry[field]
assert(value, string.format("stats are not available on field %s", field))
if not ret[value] then
ret[value] = {}
end
table.insert(ret[value], entry)
end
return ret
end
local function order_by(tab, order)
local ret = {}
for k, v in pairs(tab) do
table.insert(ret, {k, v})
end
table.sort(ret, order)
return ret
end
local function max_length_field(tab, nb)
local max = {}
if nb > #tab then nb = #tab end
for iter = 1, nb do
for k, v in sorted_pairs(tab[iter]) do
local size = #v
if size > 99 then
-- Lua formating limits width to 99
size = 99
end
if not max[k] then
max[k] = #k
end
if size > max[k] then
max[k] = size
end
end
end
return max
end
local function print_columns(tab, nb)
local max = max_length_field(tab, nb)
if #tab > 0 then
local columns = {}
for k, _ in sorted_pairs(tab[1]) do
table.insert(columns, string.format("%-" .. tostring(max[k]) .. "s", k))
end
print("| " .. table.concat(columns, " | ") .. " |")
end
return max
end
-- Metatable for storing 'sql-like' table and methods. Intended to be used to
-- store 'stats' data and to provide methods to request them
local table_mt = {}
table_mt.__index = table_mt
function table_mt:select_table(elements, where)
local ret = {}
for _, entry in ipairs(self) do
local selected_entry = {}
if not where or where(entry) then
for _, field in ipairs(elements) do
selected_entry[field] = entry[field]
end
table.insert(ret, selected_entry)
end
end
setmetatable(ret, table_mt)
return ret
end
function table_mt:top(field, nb)
nb = nb or 10
assert(field, "missing field parameter")
local grouped = group_by(self, field)
local sorted = order_by(grouped, function(p, q)
return #p[2] > #q[2] or
(#p[2] == #q[2] and p[1] > q[1])
end)
for _, entry in ipairs(sorted) do
if nb <= 0 then break end
print(entry[1], ":", #entry[2])
nb = nb - 1
end
end
function table_mt:dump(nb)
nb = nb or #self
assert(nb > 0, "illegal negative value")
local max = print_columns(self, nb)
local iter = nb
for _, entry in ipairs(self) do
if iter <= 0 then break end
local content = {}
for k, v in sorted_pairs(entry) do
table.insert(content, string.format("%-" .. tostring(max[k]) .. "s", v))
end
print("| " .. table.concat(content, " | ") .. " |")
iter = iter -1
end
if #self > nb then
print("... " .. tostring(#self - nb) .. " remaining entries")
end
end
function table_mt:list()
if #stats > 1 then
for k, _ in sorted_pairs(self[1]) do
print(k)
end
end
end
return {
new = function ()
local ret = {}
setmetatable(ret, table_mt)
return ret
end
}
| mpl-2.0 |
emptyrivers/WeakAuras2 | WeakAuras/Prototypes.lua | 1 | 253945 | if not WeakAuras.IsCorrectVersion() then return end
local AddonName, Private = ...
-- Lua APIs
local tinsert, tsort = table.insert, table.sort
local tostring = tostring
local select, pairs, type = select, pairs, type
local ceil, min = ceil, min
-- WoW APIs
local GetTalentInfo = GetTalentInfo
local GetNumSpecializationsForClassID, GetSpecialization = GetNumSpecializationsForClassID, GetSpecialization
local UnitClass, UnitHealth, UnitHealthMax, UnitName, UnitStagger, UnitPower, UnitPowerMax = UnitClass, UnitHealth, UnitHealthMax, UnitName, UnitStagger, UnitPower, UnitPowerMax
local GetSpellInfo, GetItemInfo, GetItemCount, GetItemIcon = GetSpellInfo, GetItemInfo, GetItemCount, GetItemIcon
local GetShapeshiftFormInfo, GetShapeshiftForm = GetShapeshiftFormInfo, GetShapeshiftForm
local GetRuneCooldown, UnitCastingInfo, UnitChannelInfo = GetRuneCooldown, UnitCastingInfo, UnitChannelInfo
local UnitDetailedThreatSituation, UnitThreatSituation = UnitDetailedThreatSituation, UnitThreatSituation
local CastingInfo, ChannelInfo = CastingInfo, ChannelInfo
local WeakAuras = WeakAuras
local L = WeakAuras.L
local SpellRange = LibStub("SpellRange-1.0")
function WeakAuras.IsSpellInRange(spellId, unit)
return SpellRange.IsSpellInRange(spellId, unit)
end
local LibRangeCheck = LibStub("LibRangeCheck-2.0")
function WeakAuras.GetRange(unit, checkVisible)
return LibRangeCheck:GetRange(unit, checkVisible);
end
function WeakAuras.CheckRange(unit, range, operator)
local min, max = LibRangeCheck:GetRange(unit, true);
if (type(range) ~= "number") then
range = tonumber(range);
end
if (not range) then
return
end
if (operator == "<=") then
return (max or 999) <= range;
else
return (min or 0) >= range;
end
end
local RangeCacheStrings = {friend = "", harm = "", misc = ""}
local function RangeCacheUpdate()
local friend, harm, misc = {}, {}, {}
local friendString, harmString, miscString
for range in LibRangeCheck:GetFriendCheckers() do
tinsert(friend, range)
end
tsort(friend)
for range in LibRangeCheck:GetHarmCheckers() do
tinsert(harm, range)
end
tsort(harm)
for range in LibRangeCheck:GetMiscCheckers() do
tinsert(misc, range)
end
tsort(misc)
for _, key in pairs(friend) do
friendString = (friendString and (friendString .. ", ") or "") .. key
end
for _, key in pairs(harm) do
harmString = (harmString and (harmString .. ", ") or "") .. key
end
for _, key in pairs(misc) do
miscString = (miscString and (miscString .. ", ") or "") .. key
end
RangeCacheStrings.friend, RangeCacheStrings.harm, RangeCacheStrings.misc = friendString, harmString, miscString
end
LibRangeCheck:RegisterCallback(LibRangeCheck.CHECKERS_CHANGED, RangeCacheUpdate)
function WeakAuras.UnitDetailedThreatSituation(unit1, unit2)
local ok, aggro, status, threatpct, rawthreatpct, threatvalue = pcall(UnitDetailedThreatSituation, unit1, unit2)
if ok then
return aggro, status, threatpct, rawthreatpct, threatvalue
end
end
local LibClassicCasterino
if WeakAuras.IsClassic() then
LibClassicCasterino = LibStub("LibClassicCasterino")
end
if not WeakAuras.IsClassic() then
WeakAuras.UnitCastingInfo = UnitCastingInfo
else
WeakAuras.UnitCastingInfo = function(unit)
if UnitIsUnit(unit, "player") then
return CastingInfo()
else
return LibClassicCasterino:UnitCastingInfo(unit)
end
end
end
function WeakAuras.UnitChannelInfo(unit)
if not WeakAuras.IsClassic() then
return UnitChannelInfo(unit)
elseif UnitIsUnit(unit, "player") then
return ChannelInfo()
else
return LibClassicCasterino:UnitChannelInfo(unit)
end
end
local constants = {
nameRealmFilterDesc = L[" Filter formats: 'Name', 'Name-Realm', '-Realm'. \n\nSupports multiple entries, separated by commas\n"],
}
if WeakAuras.IsClassic() then
WeakAuras.UnitRaidRole = function(unit)
local raidID = UnitInRaid(unit)
if raidID then
return select(10, GetRaidRosterInfo(raidID))
end
end
end
local encounter_list = ""
local zoneId_list = ""
local zoneGroupId_list = ""
function Private.InitializeEncounterAndZoneLists()
if encounter_list ~= "" then
return
end
if WeakAuras.IsClassic() then
local classic_raids = {
[L["Black Wing Lair"]] = {
{ L["Razorgore the Untamed"], 610 },
{ L["Vaelastrasz the Corrupt"], 611 },
{ L["Broodlord Lashlayer"], 612 },
{ L["Firemaw"], 613 },
{ L["Ebonroc"], 614 },
{ L["Flamegor"], 615 },
{ L["Chromaggus"], 616 },
{ L["Nefarian"], 617 }
},
[L["Molten Core"]] = {
{ L["Lucifron"], 663 },
{ L["Magmadar"], 664 },
{ L["Gehennas"], 665 },
{ L["Garr"], 666 },
{ L["Shazzrah"], 667 },
{ L["Baron Geddon"], 668 },
{ L["Sulfuron Harbinger"], 669 },
{ L["Golemagg the Incinerator"], 670 },
{ L["Majordomo Executus"], 671 },
{ L["Ragnaros"], 672 }
},
[L["Ahn'Qiraj"]] = {
{ L["The Prophet Skeram"], 709 },
{ L["Silithid Royalty"], 710 },
{ L["Battleguard Sartura"], 711 },
{ L["Fankriss the Unyielding"], 712 },
{ L["Viscidus"], 713 },
{ L["Princess Huhuran"], 714 },
{ L["Twin Emperors"], 715 },
{ L["Ouro"], 716 },
{ L["C'thun"], 717 }
},
[L["Ruins of Ahn'Qiraj"]] = {
{ L["Kurinnaxx"], 718 },
{ L["General Rajaxx"], 719 },
{ L["Moam"], 720 },
{ L["Buru the Gorger"], 721 },
{ L["Ayamiss the Hunter"], 722 },
{ L["Ossirian the Unscarred"], 723 }
},
[L["Zul'Gurub"]] = {
{ L["High Priest Venoxis"], 784 },
{ L["High Priestess Jeklik"], 785 },
{ L["High Priestess Mar'li"], 786 },
{ L["Bloodlord Mandokir"], 787 },
{ L["Edge of Madness"], 788 },
{ L["High Priest Thekal"], 789 },
{ L["Gahz'ranka"], 790 },
{ L["High Priestess Arlokk"], 791 },
{ L["Jin'do the Hexxer"], 792 },
{ L["Hakkar"], 793 }
},
[L["Onyxia's Lair"]] = {
{ L["Onyxia"], 1084 }
},
[L["Naxxramas"]] = {
-- The Arachnid Quarter
{ L["Anub'Rekhan"], 1107 },
{ L["Grand Widow Faerlina"], 1110 },
{ L["Maexxna"], 1116 },
-- The Plague Quarter
{ L["Noth the Plaguebringer"], 1117 },
{ L["Heigan the Unclean"], 1112 },
{ L["Loatheb"], 1115 },
-- The Military Quarter
{ L["Instructor Razuvious"], 1113 },
{ L["Gothik the Harvester"], 1109 },
{ L["The Four Horsemen"], 1121 },
-- The Construct Quarter
{ L["Patchwerk"], 1118 },
{ L["Grobbulus"], 1111 },
{ L["Gluth"], 1108 },
{ L["Thaddius"], 1120 },
-- Frostwyrm Lair
{ L["Sapphiron"], 1119 },
{ L["Kel'Thuzad"], 1114 }
}
}
for instance_name, instance_boss in pairs(classic_raids) do
encounter_list = ("%s|cffffd200%s|r\n"):format(encounter_list, instance_name)
for _, data in ipairs(instance_boss) do
encounter_list = ("%s%s: %d\n"):format(encounter_list, data[1], data[2])
end
encounter_list = encounter_list .. "\n"
end
else
EJ_SelectTier(EJ_GetCurrentTier())
for _, inRaid in ipairs({false, true}) do
local instance_index = 1
local instance_id = EJ_GetInstanceByIndex(instance_index, inRaid)
local title = inRaid and L["Raids"] or L["Dungeons"]
zoneId_list = ("%s|cffffd200%s|r\n"):format(zoneId_list, title)
zoneGroupId_list = ("%s|cffffd200%s|r\n"):format(zoneGroupId_list, title)
while instance_id do
EJ_SelectInstance(instance_id)
local instance_name, _, _, _, _, _, dungeonAreaMapID = EJ_GetInstanceInfo(instance_id)
local ej_index = 1
local boss, _, _, _, _, _, encounter_id = EJ_GetEncounterInfoByIndex(ej_index, instance_id)
-- zone ids and zone group ids
if dungeonAreaMapID and dungeonAreaMapID ~= 0 then
local mapGroupId = C_Map.GetMapGroupID(dungeonAreaMapID)
if mapGroupId then
zoneGroupId_list = ("%s%s: %d\n"):format(zoneGroupId_list, instance_name, mapGroupId)
local maps = ""
for k, map in ipairs(C_Map.GetMapGroupMembersInfo(mapGroupId)) do
if map.mapID then
maps = maps .. map.mapID .. ", "
end
end
maps = maps:match "^(.*), \n?$" or "" -- trim last ", "
zoneId_list = ("%s%s: %s\n"):format(zoneId_list, instance_name, maps)
else
zoneId_list = ("%s%s: %d\n"):format(zoneId_list, instance_name, dungeonAreaMapID)
end
end
-- Encounter ids
if inRaid then
while boss do
if encounter_id then
if instance_name then
encounter_list = ("%s|cffffd200%s|r\n"):format(encounter_list, instance_name)
instance_name = nil -- Only add it once per section
end
encounter_list = ("%s%s: %d\n"):format(encounter_list, boss, encounter_id)
end
ej_index = ej_index + 1
boss, _, _, _, _, _, encounter_id = EJ_GetEncounterInfoByIndex(ej_index, instance_id)
end
encounter_list = encounter_list .. "\n"
end
instance_index = instance_index + 1
instance_id = EJ_GetInstanceByIndex(instance_index, inRaid)
end
zoneId_list = zoneId_list .. "\n"
zoneGroupId_list = zoneGroupId_list .. "\n"
end
end
encounter_list = encounter_list:sub(1, -3) .. "\n\n" .. L["Supports multiple entries, separated by commas\n"]
end
local function get_encounters_list()
return encounter_list
end
local function get_zoneId_list()
if WeakAuras.IsClassic() then return "" end
local currentmap_id = C_Map.GetBestMapForUnit("player")
local currentmap_info = C_Map.GetMapInfo(currentmap_id)
local currentmap_name = currentmap_info and currentmap_info.name or ""
local mapGroupId = C_Map.GetMapGroupID(currentmap_id)
if mapGroupId then
-- if map is in a group, its real name is (or should be?) found in GetMapGroupMembersInfo
for k, map in ipairs(C_Map.GetMapGroupMembersInfo(mapGroupId)) do
if map.mapID and map.mapID == currentmap_id and map.name then
currentmap_name = map.name
break
end
end
end
return ("%s|cffffd200%s|r%s: %d\n\n%s"):format(
zoneId_list,
L["Current Zone\n"],
currentmap_name,
currentmap_id,
L["Supports multiple entries, separated by commas"]
)
end
local function get_zoneGroupId_list()
if WeakAuras.IsClassic() then return "" end
local currentmap_id = C_Map.GetBestMapForUnit("player")
local currentmap_info = C_Map.GetMapInfo(currentmap_id)
local currentmap_name = currentmap_info and currentmap_info.name
local currentmapgroup_id = C_Map.GetMapGroupID(currentmap_id)
return ("%s|cffffd200%s|r\n%s%s\n\n%s"):format(
zoneGroupId_list,
L["Current Zone Group"],
currentmapgroup_id and currentmap_name and currentmap_name..": " or "",
currentmapgroup_id or L["None"],
L["Supports multiple entries, separated by commas"]
)
end
Private.function_strings = {
count = [[
return function(count)
if(count %s %s) then
return true
else
return false
end
end
]],
count_fraction = [[
return function(count, max)
if max == 0 then
return false
end
local fraction = count/max
if(fraction %s %s) then
return true
else
return false
end
end
]],
always = [[
return function()
return true
end
]]
};
local hsvFrame = CreateFrame("Colorselect")
-- HSV transition, for a much prettier color transition in many cases
-- see http://www.wowinterface.com/forums/showthread.php?t=48236
function WeakAuras.GetHSVTransition(perc, r1, g1, b1, a1, r2, g2, b2, a2)
--get hsv color for colorA
hsvFrame:SetColorRGB(r1, g1, b1)
local h1, s1, v1 = hsvFrame:GetColorHSV() -- hue, saturation, value
--get hsv color for colorB
hsvFrame:SetColorRGB(r2, g2, b2)
local h2, s2, v2 = hsvFrame:GetColorHSV() -- hue, saturation, value
local h3 = floor(h1 - (h1 - h2) * perc)
-- find the shortest arc through the color circle, then interpolate
local diff = h2 - h1
if diff < -180 then
diff = diff + 360
elseif diff > 180 then
diff = diff - 360
end
h3 = (h1 + perc * diff) % 360
local s3 = s1 - ( s1 - s2 ) * perc
local v3 = v1 - ( v1 - v2 ) * perc
--get the RGB values of the new color
hsvFrame:SetColorHSV(h3, s3, v3)
local r, g, b = hsvFrame:GetColorRGB()
--interpolate alpha
local a = a1 - ( a1 - a2 ) * perc
--return the new color
return r, g, b, a
end
Private.anim_function_strings = {
straight = [[
function(progress, start, delta)
return start + (progress * delta)
end
]],
straightTranslate = [[
function(progress, startX, startY, deltaX, deltaY)
return startX + (progress * deltaX), startY + (progress * deltaY)
end
]],
straightScale = [[
function(progress, startX, startY, scaleX, scaleY)
return startX + (progress * (scaleX - startX)), startY + (progress * (scaleY - startY))
end
]],
straightColor = [[
function(progress, r1, g1, b1, a1, r2, g2, b2, a2)
return r1 + (progress * (r2 - r1)), g1 + (progress * (g2 - g1)), b1 + (progress * (b2 - b1)), a1 + (progress * (a2 - a1))
end
]],
straightHSV = [[
function(progress, r1, g1, b1, a1, r2, g2, b2, a2)
return WeakAuras.GetHSVTransition(progress, r1, g1, b1, a1, r2, g2, b2, a2)
end
]],
circle = [[
function(progress, startX, startY, deltaX, deltaY)
local angle = progress * 2 * math.pi
return startX + (deltaX * math.cos(angle)), startY + (deltaY * math.sin(angle))
end
]],
circle2 = [[
function(progress, startX, startY, deltaX, deltaY)
local angle = progress * 2 * math.pi
return startX + (deltaX * math.sin(angle)), startY + (deltaY * math.cos(angle))
end
]],
spiral = [[
function(progress, startX, startY, deltaX, deltaY)
local angle = progress * 2 * math.pi
return startX + (progress * deltaX * math.cos(angle)), startY + (progress * deltaY * math.sin(angle))
end
]],
spiralandpulse = [[
function(progress, startX, startY, deltaX, deltaY)
local angle = (progress + 0.25) * 2 * math.pi
return startX + (math.cos(angle) * deltaX * math.cos(angle*2)), startY + (math.abs(math.cos(angle)) * deltaY * math.sin(angle*2))
end
]],
shake = [[
function(progress, startX, startY, deltaX, deltaY)
local prog
if(progress < 0.25) then
prog = progress * 4
elseif(progress < .75) then
prog = 2 - (progress * 4)
else
prog = (progress - 1) * 4
end
return startX + (prog * deltaX), startY + (prog * deltaY)
end
]],
starShakeDecay = [[
function(progress, startX, startY, deltaX, deltaY)
local spokes = 10
local fullCircles = 4
local r = min(abs(deltaX), abs(deltaY))
local xScale = deltaX / r
local yScale = deltaY / r
local deltaAngle = fullCircles *2 / spokes * math.pi
local p = progress * spokes
local i1 = floor(p)
p = p - i1
local angle1 = i1 * deltaAngle
local angle2 = angle1 + deltaAngle
local x1 = r * math.cos(angle1)
local y1 = r * math.sin(angle1)
local x2 = r * math.cos(angle2)
local y2 = r * math.sin(angle2)
local x, y = p * x2 + (1-p) * x1, p * y2 + (1-p) * y1
local ease = math.sin(progress * math.pi / 2)
return ease * x * xScale, ease * y * yScale
end
]],
bounceDecay = [[
function(progress, startX, startY, deltaX, deltaY)
local prog = (progress * 3.5) % 1
local bounce = math.ceil(progress * 3.5)
local bounceDistance = math.sin(prog * math.pi) * (bounce / 4)
return startX + (bounceDistance * deltaX), startY + (bounceDistance * deltaY)
end
]],
bounce = [[
function(progress, startX, startY, deltaX, deltaY)
local bounceDistance = math.sin(progress * math.pi)
return startX + (bounceDistance * deltaX), startY + (bounceDistance * deltaY)
end
]],
flash = [[
function(progress, start, delta)
local prog
if(progress < 0.5) then
prog = progress * 2
else
prog = (progress - 1) * 2
end
return start + (prog * delta)
end
]],
pulse = [[
function(progress, startX, startY, scaleX, scaleY)
local angle = (progress * 2 * math.pi) - (math.pi / 2)
return startX + (((math.sin(angle) + 1)/2) * (scaleX - 1)), startY + (((math.sin(angle) + 1)/2) * (scaleY - 1))
end
]],
alphaPulse = [[
function(progress, start, delta)
local angle = (progress * 2 * math.pi) - (math.pi / 2)
return start + (((math.sin(angle) + 1)/2) * delta)
end
]],
pulseColor = [[
function(progress, r1, g1, b1, a1, r2, g2, b2, a2)
local angle = (progress * 2 * math.pi) - (math.pi / 2)
local newProgress = ((math.sin(angle) + 1)/2);
return r1 + (newProgress * (r2 - r1)),
g1 + (newProgress * (g2 - g1)),
b1 + (newProgress * (b2 - b1)),
a1 + (newProgress * (a2 - a1))
end
]],
pulseHSV = [[
function(progress, r1, g1, b1, a1, r2, g2, b2, a2)
local angle = (progress * 2 * math.pi) - (math.pi / 2)
local newProgress = ((math.sin(angle) + 1)/2);
return WeakAuras.GetHSVTransition(newProgress, r1, g1, b1, a1, r2, g2, b2, a2)
end
]],
fauxspin = [[
function(progress, startX, startY, scaleX, scaleY)
local angle = progress * 2 * math.pi
return math.cos(angle) * scaleX, startY + (progress * (scaleY - startY))
end
]],
fauxflip = [[
function(progress, startX, startY, scaleX, scaleY)
local angle = progress * 2 * math.pi
return startX + (progress * (scaleX - startX)), math.cos(angle) * scaleY
end
]],
backandforth = [[
function(progress, start, delta)
local prog
if(progress < 0.25) then
prog = progress * 4
elseif(progress < .75) then
prog = 2 - (progress * 4)
else
prog = (progress - 1) * 4
end
return start + (prog * delta)
end
]],
wobble = [[
function(progress, start, delta)
local angle = progress * 2 * math.pi
return start + math.sin(angle) * delta
end
]],
hide = [[
function()
return 0
end
]]
};
Private.anim_presets = {
-- Start and Finish
slidetop = {
type = "custom",
duration = 0.25,
use_translate = true,
x = 0, y = 50,
use_alpha = true,
alpha = 0
},
slideleft = {
type = "custom",
duration = 0.25,
use_translate = true,
x = -50,
y = 0,
use_alpha = true,
alpha = 0
},
slideright = {
type = "custom",
duration = 0.25,
use_translate = true,
x = 50,
y = 0,
use_alpha = true,
alpha = 0
},
slidebottom = {
type = "custom",
duration = 0.25,
use_translate = true,
x = 0,
y = -50,
use_alpha = true,
alpha = 0
},
fade = {
type = "custom",
duration = 0.25,
use_alpha = true,
alpha = 0
},
grow = {
type = "custom",
duration = 0.25,
use_scale = true,
scalex = 2,
scaley = 2,
use_alpha = true,
alpha = 0
},
shrink = {
type = "custom",
duration = 0.25,
use_scale = true,
scalex = 0,
scaley = 0,
use_alpha = true,
alpha = 0
},
spiral = {
type = "custom",
duration = 0.5,
use_translate = true,
x = 100,
y = 100,
translateType = "spiral",
use_alpha = true,
alpha = 0
},
bounceDecay = {
type = "custom",
duration = 1.5,
use_translate = true,
x = 50,
y = 50,
translateType = "bounceDecay",
use_alpha = true,
alpha = 0
},
starShakeDecay = {
type = "custom",
duration = 1,
use_translate = true,
x = 50,
y = 50,
translateType = "starShakeDecay",
use_alpha = true,
alpha = 0
},
-- Main
shake = {
type = "custom",
duration = 0.5,
use_translate = true,
x = 10,
y = 0,
translateType = "circle2"
},
spin = {
type = "custom",
duration = 1,
use_scale = true,
scalex = 1,
scaley = 1,
scaleType = "fauxspin"
},
flip = {
type = "custom",
duration = 1,
use_scale = true,
scalex = 1,
scaley = 1,
scaleType = "fauxflip"
},
wobble = {
type = "custom",
duration = 0.5,
use_rotate = true,
rotate = 3,
rotateType = "wobble"
},
pulse = {
type = "custom",
duration = 0.75,
use_scale = true,
scalex = 1.05,
scaley = 1.05,
scaleType = "pulse"
},
alphaPulse = {
type = "custom",
duration = 0.5,
use_alpha = true,
alpha = 0.5,
alphaType = "alphaPulse"
},
rotateClockwise = {
type = "custom",
duration = 4,
use_rotate = true,
rotate = -360
},
rotateCounterClockwise = {
type = "custom",
duration = 4,
use_rotate = true,
rotate = 360
},
spiralandpulse = {
type = "custom",
duration = 6,
use_translate = true,
x = 100,
y = 100,
translateType = "spiralandpulse"
},
circle = {
type = "custom",
duration = 4,
use_translate = true,
x = 100,
y = 100,
translateType = "circle"
},
orbit = {
type = "custom",
duration = 4,
use_translate = true,
x = 100,
y = 100,
translateType = "circle",
use_rotate = true,
rotate = 360
},
bounce = {
type = "custom",
duration = 0.6,
use_translate = true,
x = 0,
y = 25,
translateType = "bounce"
}
};
WeakAuras.class_ids = {}
for classID = 1, 20 do -- GetNumClasses not supported by wow classic
local classInfo = C_CreatureInfo.GetClassInfo(classID)
if classInfo then
WeakAuras.class_ids[classInfo.classFile] = classInfo.classID
end
end
function WeakAuras.CheckTalentByIndex(index)
if WeakAuras.IsClassic() then
local tab = ceil(index / 20)
local num_talent = (index - 1) % 20 + 1
local _, _, _, _, rank = GetTalentInfo(tab, num_talent)
return rank and rank > 0;
else
local tier = ceil(index / 3)
local column = (index - 1) % 3 + 1
local _, _, _, selected, _, _, _, _, _, _, known = GetTalentInfo(tier, column, 1)
return selected or known;
end
end
function WeakAuras.CheckPvpTalentByIndex(index)
local checkTalentSlotInfo = C_SpecializationInfo.GetPvpTalentSlotInfo(1)
if checkTalentSlotInfo then
local checkTalentId = checkTalentSlotInfo.availableTalentIDs[index]
for i = 1, 3 do
local talentSlotInfo = C_SpecializationInfo.GetPvpTalentSlotInfo(i)
if talentSlotInfo and (talentSlotInfo.selectedTalentID == checkTalentId) then
return true, checkTalentId
end
end
return false, checkTalentId
end
return false
end
function WeakAuras.CheckNumericIds(loadids, currentId)
if (not loadids or not currentId) then
return false;
end
local searchFrom = 0;
local startI, endI = string.find(loadids, currentId, searchFrom);
while (startI) do
searchFrom = endI + 1; -- start next search from end
if (startI == 1 or tonumber(string.sub(loadids, startI - 1, startI - 1)) == nil) then
-- Either right at start, or character before is not a number
if (endI == string.len(loadids) or tonumber(string.sub(loadids, endI + 1, endI + 1)) == nil) then
return true;
end
end
startI, endI = string.find(loadids, currentId, searchFrom);
end
return false;
end
function WeakAuras.CheckString(ids, currentId)
if (not ids or not currentId) then
return false;
end
for id in ids:gmatch('([^,]+)') do
if id:trim() == currentId then
return true
end
end
return false;
end
function WeakAuras.ValidateNumeric(info, val)
if val ~= nil and val ~= "" and (not tonumber(val) or tonumber(val) >= 2^31) then
return false;
end
return true
end
function WeakAuras.ValidateNumericOrPercent(info, val)
if val ~= nil and val ~= "" then
local percent = string.match(val, "(%d+)%%")
local number = percent and tonumber(percent) or tonumber(val)
if(not number or number >= 2^31) then
return false;
end
end
return true
end
function WeakAuras.CheckMPlusAffixIds(loadids, currentId)
if (not loadids or not currentId) or type(currentId) ~= "table" then
return false
end
for i=1, #currentId do
if loadids == currentId[i] then
return true
end
end
return false
end
function WeakAuras.CheckChargesDirection(direction, triggerDirection)
return triggerDirection == "CHANGED"
or (triggerDirection == "GAINED" and direction > 0)
or (triggerDirection == "LOST" and direction < 0)
end
function WeakAuras.CheckCombatLogFlags(flags, flagToCheck)
if type(flags) ~= "number" then return end
if (flagToCheck == "InGroup") then
return bit.band(flags, 7) > 0;
elseif (flagToCheck == "NotInGroup") then
return bit.band(flags, 7) == 0;
end
end
function WeakAuras.CheckCombatLogFlagsReaction(flags, flagToCheck)
if type(flags) ~= "number" then return end
if (flagToCheck == "Hostile") then
return bit.band(flags, 64) ~= 0;
elseif (flagToCheck == "Neutral") then
return bit.band(flags, 32) ~= 0;
elseif (flagToCheck == "Friendly") then
return bit.band(flags, 16) ~= 0;
end
end
local objectTypeToBit = {
Object = 16384,
Guardian = 8192,
Pet = 4096,
NPC = 2048,
Player = 1024,
}
function WeakAuras.CheckCombatLogFlagsObjectType(flags, flagToCheck)
if type(flags) ~= "number" then return end
local bitToCheck = objectTypeToBit[flagToCheck]
if not bitToCheck then return end
return bit.band(flags, bitToCheck) ~= 0;
end
function WeakAuras.CheckRaidFlags(flags, flagToCheck)
flagToCheck = tonumber(flagToCheck)
if not flagToCheck or not flags then return end --bailout
if flagToCheck == 0 then --no raid mark
return bit.band(flags, COMBATLOG_OBJECT_RAIDTARGET_MASK) == 0
elseif flagToCheck == 9 then --any raid mark
return bit.band(flags, COMBATLOG_OBJECT_RAIDTARGET_MASK) > 0
else -- specific raid mark
return bit.band(flags, _G['COMBATLOG_OBJECT_RAIDTARGET'..flagToCheck]) > 0
end
end
function WeakAuras.IsSpellKnownForLoad(spell, exact)
local result = WeakAuras.IsSpellKnown(spell)
if exact or result then
return result
end
-- Dance through the spellname to the current spell id
spell = GetSpellInfo(spell)
if (spell) then
spell = select(7, GetSpellInfo(spell))
end
if spell then
return WeakAuras.IsSpellKnown(spell)
end
end
function WeakAuras.IsSpellKnown(spell, pet)
if (pet) then
return IsSpellKnown(spell, pet);
end
return IsPlayerSpell(spell) or IsSpellKnown(spell);
end
function WeakAuras.IsSpellKnownIncludingPet(spell)
if (not tonumber(spell)) then
spell = select(7, GetSpellInfo(spell));
end
if (not spell) then
return false;
end
if (WeakAuras.IsSpellKnown(spell) or WeakAuras.IsSpellKnown(spell, true)) then
return true;
end
-- WORKAROUND brain damage around void eruption
-- In shadow form void eruption is overridden by void bolt, yet IsSpellKnown for void bolt
-- returns false, whereas it returns true for void eruption
local baseSpell = FindBaseSpellByID(spell);
if (not baseSpell) then
return false;
end
if (baseSpell ~= spell) then
return WeakAuras.IsSpellKnown(baseSpell) or WeakAuras.IsSpellKnown(baseSpell, true);
end
end
function WeakAuras.UnitPowerDisplayMod(powerType)
if (powerType == 7) then
return 10;
end
return 1;
end
function WeakAuras.UseUnitPowerThirdArg(powerType)
if (powerType == 7) then
return true;
end
return nil;
end
function WeakAuras.GetNumSetItemsEquipped(setID)
if not setID or not type(setID) == "number" then return end
local equipped = 0
local setName = GetItemSetInfo(setID)
for i = 1, 18 do
local item = GetInventoryItemID("player", i)
if item and select(16, GetItemInfo(item)) == setID then
equipped = equipped + 1
end
end
return equipped, 18, setName
end
function WeakAuras.GetEffectiveAttackPower()
local base, pos, neg = UnitAttackPower("player")
return base + pos + neg
end
local function valuesForTalentFunction(trigger)
return function()
local single_class;
-- First check to use if the class load is on multi-select with only one class selected
if(trigger.use_class == false and trigger.class and trigger.class.multi) then
local num_classes = 0;
for class in pairs(trigger.class.multi) do
single_class = class;
num_classes = num_classes + 1;
end
if(num_classes ~= 1) then
single_class = nil;
end
end
-- If that is not the case, see if it is on single-select
if((not single_class) and trigger.use_class and trigger.class and trigger.class.single) then
single_class = trigger.class.single
end
if (trigger.use_class == nil) then -- no class selected, fallback to current class
single_class = select(2, UnitClass("player"));
end
local single_spec;
if not WeakAuras.IsClassic() then
if single_class then
if(trigger.use_spec == false and trigger.spec and trigger.spec.multi) then
local num_specs = 0;
for spec in pairs(trigger.spec.multi) do
single_spec = spec;
num_specs = num_specs + 1;
end
if (num_specs ~= 1) then
single_spec = nil;
end
end
end
if ((not single_spec) and trigger.use_spec and trigger.spec and trigger.spec.single) then
single_spec = trigger.spec.single;
end
if (trigger.use_spec == nil) then
single_spec = GetSpecialization();
end
end
-- If a single specific class was found, load the specific list for it
if(single_class and Private.talent_types_specific[single_class]
and single_spec and Private.talent_types_specific[single_class][single_spec]) then
return Private.talent_types_specific[single_class][single_spec];
elseif(WeakAuras.IsClassic() and single_class and Private.talent_types_specific[single_class]
and Private.talent_types_specific[single_class]) then
return Private.talent_types_specific[single_class];
else
return Private.talent_types;
end
end
end
Private.load_prototype = {
args = {
{
name = "combat",
display = L["In Combat"],
type = "tristate",
width = WeakAuras.normalWidth,
init = "arg",
optional = true,
events = {"PLAYER_REGEN_DISABLED", "PLAYER_REGEN_ENABLED"}
},
{
name = "encounter",
display = L["In Encounter"],
type = "tristate",
width = WeakAuras.normalWidth,
init = "arg",
optional = true,
events = {"ENCOUNTER_START", "ENCOUNTER_END"}
},
{
name = "warmode",
display = L["War Mode Active"],
type = "tristate",
init = "arg",
width = WeakAuras.doubleWidth,
optional = true,
enable = not WeakAuras.IsClassic(),
hidden = WeakAuras.IsClassic(),
events = {"UNIT_FLAGS"}
},
{
name = "never",
display = L["Never"],
type = "toggle",
width = WeakAuras.normalWidth,
init = "false",
},
{
name = "petbattle",
display = L["In Pet Battle"],
type = "tristate",
init = "arg",
width = WeakAuras.normalWidth,
optional = true,
enable = not WeakAuras.IsClassic(),
hidden = WeakAuras.IsClassic(),
events = {"PET_BATTLE_OPENING_START", "PET_BATTLE_CLOSE"}
},
{
name = "vehicle",
display = WeakAuras.IsClassic() and L["On Taxi"] or L["In Vehicle"],
type = "tristate",
init = "arg",
width = WeakAuras.normalWidth,
optional = true,
events = WeakAuras.IsClassic() and {"UNIT_FLAGS"}
or {"VEHICLE_UPDATE", "UNIT_ENTERED_VEHICLE", "UNIT_EXITED_VEHICLE", "UPDATE_OVERRIDE_ACTIONBAR", "UNIT_FLAGS"}
},
{
name = "vehicleUi",
display = L["Has Vehicle UI"],
type = "tristate",
init = "arg",
width = WeakAuras.normalWidth,
optional = true,
enable = not WeakAuras.IsClassic(),
hidden = WeakAuras.IsClassic(),
events = {"VEHICLE_UPDATE", "UNIT_ENTERED_VEHICLE", "UNIT_EXITED_VEHICLE", "UPDATE_OVERRIDE_ACTIONBAR", "UPDATE_VEHICLE_ACTIONBAR"}
},
{
name = "ingroup",
display = L["In Group"],
type = "multiselect",
width = WeakAuras.normalWidth,
init = "arg",
values = "group_types",
events = {"GROUP_ROSTER_UPDATE"}
},
{
name = "player",
hidden = true,
init = "arg",
test = "true"
},
{
name = "realm",
hidden = true,
init = "arg",
test = "true"
},
{
name = "namerealm",
display = L["Player Name/Realm"],
type = "string",
test = "nameRealmChecker:Check(player, realm)",
preamble = "local nameRealmChecker = WeakAuras.ParseNameCheck(%q)",
desc = constants.nameRealmFilterDesc,
},
{
name = "ignoreNameRealm",
display = L["|cFFFF0000Not|r Player Name/Realm"],
type = "string",
test = "not nameRealmIgnoreChecker:Check(player, realm)",
preamble = "local nameRealmIgnoreChecker = WeakAuras.ParseNameCheck(%q)",
desc = constants.nameRealmFilterDesc,
},
{
name = "class",
display = L["Player Class"],
type = "multiselect",
values = "class_types",
init = "arg"
},
{
name = "spec",
display = L["Talent Specialization"],
type = "multiselect",
values = function(trigger)
return function()
local single_class;
local min_specs = 4;
-- First check to use if the class load is on multi-select with only one class selected
-- Also check the number of specs for each class selected in the multi-select and keep track of the minimum
-- (i.e., 3 unless Druid is the only thing selected, but this method is flexible in case another spec gets added to another class)
if(trigger.use_class == false and trigger.class and trigger.class.multi) then
local num_classes = 0;
for class in pairs(trigger.class.multi) do
single_class = class;
-- If any checked class has only 3 specs, min_specs will become 3
min_specs = min(min_specs, GetNumSpecializationsForClassID(WeakAuras.class_ids[class]))
num_classes = num_classes + 1;
end
if(num_classes ~= 1) then
single_class = nil;
end
end
-- If that is not the case, see if it is on single-select
if((not single_class) and trigger.use_class and trigger.class and trigger.class.single) then
single_class = trigger.class.single
end
if (trigger.use_class == nil) then -- no class selected, fallback to current class
single_class = select(2, UnitClass("player"));
end
-- If a single specific class was found, load the specific list for it
if(single_class) then
return WeakAuras.spec_types_specific[single_class];
else
-- List 4 specs if no class is specified, but if any multi-selected classes have less than 4 specs, list 3 instead
if (min_specs < 3) then
return Private.spec_types_2;
elseif(min_specs < 4) then
return Private.spec_types_3;
else
return Private.spec_types;
end
end
end
end,
init = "arg",
enable = not WeakAuras.IsClassic(),
hidden = WeakAuras.IsClassic(),
events = {"PLAYER_TALENT_UPDATE"}
},
{
name = "class_and_spec",
display = L["Class and Specialization"],
type = "multiselect",
values = "spec_types_all",
init = "arg",
enable = not WeakAuras.IsClassic(),
hidden = WeakAuras.IsClassic(),
events = {"PLAYER_TALENT_UPDATE"}
},
{
name = "talent",
display = L["Talent selected"],
type = "multiselect",
values = valuesForTalentFunction,
test = "WeakAuras.CheckTalentByIndex(%d)",
events = WeakAuras.IsClassic() and {"CHARACTER_POINTS_CHANGED"} or {"PLAYER_TALENT_UPDATE"}
},
{
name = "talent2",
display = L["And Talent selected"],
type = "multiselect",
values = valuesForTalentFunction,
test = "WeakAuras.CheckTalentByIndex(%d)",
enable = function(trigger)
return trigger.use_talent ~= nil or trigger.use_talent2 ~= nil;
end,
events = WeakAuras.IsClassic() and {"CHARACTER_POINTS_CHANGED"} or {"PLAYER_TALENT_UPDATE"}
},
{
name = "talent3",
display = L["And Talent selected"],
type = "multiselect",
values = valuesForTalentFunction,
test = "WeakAuras.CheckTalentByIndex(%d)",
enable = function(trigger)
return (trigger.use_talent ~= nil and trigger.use_talent2 ~= nil) or trigger.use_talent3 ~= nil;
end,
events = WeakAuras.IsClassic() and {"CHARACTER_POINTS_CHANGED"} or {"PLAYER_TALENT_UPDATE"}
},
{
name = "pvptalent",
display = L["PvP Talent selected"],
type = "multiselect",
values = function(trigger)
return function()
local single_class;
-- First check to use if the class load is on multi-select with only one class selected
if(trigger.use_class == false and trigger.class and trigger.class.multi) then
local num_classes = 0;
for class in pairs(trigger.class.multi) do
single_class = class;
num_classes = num_classes + 1;
end
if(num_classes ~= 1) then
single_class = nil;
end
end
-- If that is not the case, see if it is on single-select
if((not single_class) and trigger.use_class and trigger.class and trigger.class.single) then
single_class = trigger.class.single
end
if (trigger.use_class == nil) then -- no class selected, fallback to current class
single_class = select(2, UnitClass("player"));
end
local single_spec;
if (single_class) then
if(trigger.use_spec == false and trigger.spec and trigger.spec.multi) then
local num_specs = 0;
for spec in pairs(trigger.spec.multi) do
single_spec = spec;
num_specs = num_specs + 1;
end
if (num_specs ~= 1) then
single_spec = nil;
end
end
end
if ((not single_spec) and trigger.use_spec and trigger.spec and trigger.spec.single) then
single_spec = trigger.spec.single;
end
if (trigger.use_spec == nil) then
single_spec = GetSpecialization();
end
-- print ("Using talent cache", single_class, single_spec);
-- If a single specific class was found, load the specific list for it
if(single_class and Private.pvp_talent_types_specific[single_class]
and single_spec and Private.pvp_talent_types_specific[single_class][single_spec]) then
return Private.pvp_talent_types_specific[single_class][single_spec];
else
return Private.pvp_talent_types;
end
end
end,
test = "WeakAuras.CheckPvpTalentByIndex(%d)",
enable = not WeakAuras.IsClassic(),
hidden = WeakAuras.IsClassic(),
events = {"PLAYER_PVP_TALENT_UPDATE"}
},
{
name = "spellknown",
display = L["Spell Known"],
type = "spell",
test = "WeakAuras.IsSpellKnownForLoad(%s, %s)",
events = {"SPELLS_CHANGED"},
showExactOption = true
},
{
name = "covenant",
display = WeakAuras.newFeatureString .. L["Player Covenant"],
type = "multiselect",
values = "covenant_types",
init = "arg",
enable = not WeakAuras.IsClassic(),
hidden = WeakAuras.IsClassic(),
events = {"COVENANT_CHOSEN"}
},
{
name = "race",
display = L["Player Race"],
type = "multiselect",
values = "race_types",
init = "arg"
},
{
name = "faction",
display = L["Player Faction"],
type = "multiselect",
values = "faction_group",
init = "arg"
},
{
name = "level",
display = L["Player Level"],
type = "number",
init = "arg",
events = {"PLAYER_LEVEL_UP"}
},
{
name = "effectiveLevel",
display = L["Player Effective Level"],
type = "number",
init = "arg",
desc = L["The effective level differs from the level in e.g. Time Walking dungeons."],
enable = not WeakAuras.IsClassic(),
hidden = WeakAuras.IsClassic(),
events = {"PLAYER_LEVEL_UP", "UNIT_FLAGS", "ZONE_CHANGED", "ZONE_CHANGED_INDOORS", "ZONE_CHANGED_NEW_AREA"}
},
{
name = "zone",
display = L["Zone Name"],
type = "string",
init = "arg",
test = "WeakAuras.CheckString(%q, zone)",
events = {"ZONE_CHANGED", "ZONE_CHANGED_INDOORS", "ZONE_CHANGED_NEW_AREA", "VEHICLE_UPDATE"},
desc = L["Supports multiple entries, separated by commas"]
},
{
name = "zoneId",
display = L["Zone ID(s)"],
type = "string",
init = "arg",
desc = get_zoneId_list,
test = "WeakAuras.CheckNumericIds(%q, zoneId)",
enable = not WeakAuras.IsClassic(),
hidden = WeakAuras.IsClassic(),
events = {"ZONE_CHANGED", "ZONE_CHANGED_INDOORS", "ZONE_CHANGED_NEW_AREA", "VEHICLE_UPDATE"}
},
{
name = "zonegroupId",
display = L["Zone Group ID(s)"],
type = "string",
init = "arg",
desc = get_zoneGroupId_list,
test = "WeakAuras.CheckNumericIds(%q, zonegroupId)",
enable = not WeakAuras.IsClassic(),
hidden = WeakAuras.IsClassic(),
events = {"ZONE_CHANGED", "ZONE_CHANGED_INDOORS", "ZONE_CHANGED_NEW_AREA", "VEHICLE_UPDATE"}
},
{
name = "encounterid",
display = L["Encounter ID(s)"],
type = "string",
init = "arg",
desc = get_encounters_list,
test = "WeakAuras.CheckNumericIds(%q, encounterid)",
events = {"ENCOUNTER_START", "ENCOUNTER_END"}
},
{
name = "size",
display = L["Instance Size Type"],
type = "multiselect",
values = "instance_types",
init = "arg",
control = "WeakAurasSortedDropdown",
events = {"ZONE_CHANGED", "ZONE_CHANGED_INDOORS", "ZONE_CHANGED_NEW_AREA"}
},
{
name = "difficulty",
display = L["Instance Difficulty"],
type = "multiselect",
values = "difficulty_types",
init = "arg",
enable = not WeakAuras.IsClassic(),
hidden = WeakAuras.IsClassic(),
events = {"PLAYER_DIFFICULTY_CHANGED", "ZONE_CHANGED", "ZONE_CHANGED_INDOORS", "ZONE_CHANGED_NEW_AREA"}
},
{
name = "instance_type",
display = L["Instance Type"],
type = "multiselect",
values = "instance_difficulty_types",
init = "arg",
control = "WeakAurasSortedDropdown",
events = {"PLAYER_DIFFICULTY_CHANGED", "ZONE_CHANGED", "ZONE_CHANGED_INDOORS", "ZONE_CHANGED_NEW_AREA"},
enable = not WeakAuras.IsClassic(),
hidden = WeakAuras.IsClassic(),
},
{
name = "role",
display = L["Spec Role"],
type = "multiselect",
values = "role_types",
init = "arg",
enable = not WeakAuras.IsClassic(),
hidden = WeakAuras.IsClassic(),
events = {"PLAYER_ROLES_ASSIGNED", "PLAYER_TALENT_UPDATE"}
},
{
name = "raid_role",
display = WeakAuras.newFeatureString .. L["Raid Role"],
type = "multiselect",
values = "raid_role_types",
init = "arg",
enable = WeakAuras.IsClassic(),
hidden = not WeakAuras.IsClassic(),
events = {"PLAYER_ROLES_ASSIGNED"}
},
{
name = "affixes",
display = L["Mythic+ Affix"],
type = "multiselect",
values = "mythic_plus_affixes",
init = "arg",
test = "WeakAuras.CheckMPlusAffixIds(%d, affixes)",
enable = not WeakAuras.IsClassic(),
hidden = WeakAuras.IsClassic(),
events = {"CHALLENGE_MODE_START", "CHALLENGE_MODE_COMPLETED"},
},
{
name = "itemequiped",
display = L["Item Equipped"],
type = "item",
test = "IsEquippedItem(%s)",
events = { "UNIT_INVENTORY_CHANGED", "PLAYER_EQUIPMENT_CHANGED"}
},
{
name = "itemtypeequipped",
display = WeakAuras.newFeatureString .. L["Item Type Equipped"],
type = "multiselect",
test = "IsEquippedItemType(WeakAuras.GetItemSubClassInfo(%s))",
events = { "UNIT_INVENTORY_CHANGED", "PLAYER_EQUIPMENT_CHANGED"},
values = "item_weapon_types"
},
{
name = "item_bonusid_equipped",
display = WeakAuras.newFeatureString .. L["Item Bonus Id Equipped"],
type = "string",
test = "WeakAuras.CheckForItemBonusId(%q)",
events = { "UNIT_INVENTORY_CHANGED", "PLAYER_EQUIPMENT_CHANGED"},
desc = function()
return WeakAuras.GetLegendariesBonusIds()
.. L["\n\nSupports multiple entries, separated by commas"]
end
},
{
name = "not_item_bonusid_equipped",
display = WeakAuras.newFeatureString .. L["|cFFFF0000Not|r Item Bonus Id Equipped"],
type = "string",
test = "not WeakAuras.CheckForItemBonusId(%q)",
events = { "UNIT_INVENTORY_CHANGED", "PLAYER_EQUIPMENT_CHANGED"},
desc = function()
return WeakAuras.GetLegendariesBonusIds()
.. L["\n\nSupports multiple entries, separated by commas"]
end
}
}
};
local function AddUnitChangeInternalEvents(triggerUnit, t)
if (triggerUnit == nil) then
return
end
if (triggerUnit == "multi") then
-- Handled by normal events"
elseif triggerUnit == "pet" then
WeakAuras.WatchForPetDeath();
tinsert(t, "PET_UPDATE")
else
if Private.multiUnitUnits[triggerUnit] then
for unit in pairs(Private.multiUnitUnits[triggerUnit]) do
tinsert(t, "UNIT_CHANGED_" .. string.lower(unit))
WeakAuras.WatchUnitChange(unit)
end
else
tinsert(t, "UNIT_CHANGED_" .. string.lower(triggerUnit))
WeakAuras.WatchUnitChange(triggerUnit)
end
end
end
local function AddUnitRoleChangeInternalEvents(triggerUnit, t)
if (triggerUnit == nil) then
return
end
if Private.multiUnitUnits[triggerUnit] then
for unit in pairs(Private.multiUnitUnits[triggerUnit]) do
tinsert(t, "UNIT_ROLE_CHANGED_" .. string.lower(unit))
end
else
tinsert(t, "UNIT_ROLE_CHANGED_" .. string.lower(triggerUnit))
end
end
local function AddUnitEventForEvents(result, unit, event)
if unit then
if not result.unit_events then
result.unit_events = {}
end
if not result.unit_events[unit] then
result.unit_events[unit] = {}
end
tinsert(result.unit_events[unit], event)
else
if not result.events then
result.events = {}
end
tinsert(result.events, event)
end
end
local unitHelperFunctions = {
UnitChangedForceEvents = function(trigger)
local events = {}
if Private.multiUnitUnits[trigger.unit] then
for unit in pairs(Private.multiUnitUnits[trigger.unit]) do
tinsert(events, {"UNIT_CHANGED_" .. unit, unit})
end
else
if trigger.unit then
tinsert(events, {"UNIT_CHANGED_" .. trigger.unit, trigger.unit})
end
end
return events
end,
SpecificUnitCheck = function(trigger)
if not trigger.use_specific_unit then
return "local specificUnitCheck = true\n"
end
if trigger.unit == nil then
return "local specificUnitCheck = false\n"
end
return string.format([=[
local specificUnitCheck = UnitIsUnit(%q, unit)
]=], trigger.unit or "")
end
}
Private.event_prototypes = {
["Unit Characteristics"] = {
type = "status",
events = function(trigger)
local unit = trigger.unit
local result = {}
AddUnitEventForEvents(result, unit, "UNIT_LEVEL")
AddUnitEventForEvents(result, unit, "UNIT_FACTION")
AddUnitEventForEvents(result, unit, "UNIT_NAME_UPDATE")
AddUnitEventForEvents(result, unit, "UNIT_FLAGS")
return result;
end,
internal_events = function(trigger)
local unit = trigger.unit
local result = {}
AddUnitChangeInternalEvents(unit, result)
if trigger.unitisunit then
AddUnitChangeInternalEvents(trigger.unitisunit, result)
end
AddUnitRoleChangeInternalEvents(unit, result)
return result
end,
force_events = unitHelperFunctions.UnitChangedForceEvents,
name = L["Unit Characteristics"],
init = function(trigger)
trigger.unit = trigger.unit or "target";
local ret = [=[
unit = string.lower(unit)
local smart = %s
local extraUnit = %q;
local name, realm = WeakAuras.UnitNameWithRealm(unit)
]=];
ret = ret .. unitHelperFunctions.SpecificUnitCheck(trigger)
return ret:format(trigger.unit == "group" and "true" or "false", trigger.unitisunit or "");
end,
statesParameter = "unit",
args = {
{
name = "unit",
required = true,
display = L["Unit"],
type = "unit",
init = "arg",
values = "actual_unit_types_cast",
test = "true",
store = true
},
{
name = "unitisunit",
display = L["Unit is Unit"],
type = "unit",
init = "UnitIsUnit(unit, extraUnit)",
values = "actual_unit_types_with_specific",
test = "unitisunit",
store = true,
conditionType = "bool",
desc = function() return L["Can be used for e.g. checking if \"boss1target\" is the same as \"player\"."] end,
enable = function(trigger) return not Private.multiUnitUnits[trigger.unit] end
},
{
name = "name",
display = L["Name"],
type = "string",
store = true,
hidden = true,
test = "true"
},
{
name = "realm",
display = L["Realm"],
type = "string",
store = true,
hidden = true,
test = "true"
},
{
name = "namerealm",
display = L["Unit Name/Realm"],
type = "string",
preamble = "local nameRealmChecker = WeakAuras.ParseNameCheck(%q)",
test = "nameRealmChecker:Check(name, realm)",
conditionType = "string",
conditionPreamble = function(input)
return WeakAuras.ParseNameCheck(input)
end,
conditionTest = function(state, needle, op, preamble)
return preamble:Check(state.name, state.realm)
end,
operator_types = "none",
},
{
name = "class",
display = L["Class"],
type = "select",
init = "select(2, UnitClass(unit))",
values = "class_types",
store = true,
conditionType = "select"
},
{
name = "classification",
display = L["Classification"],
type = "multiselect",
init = "UnitClassification(unit)",
values = "classification_types",
store = true,
conditionType = "select"
},
{
name = "role",
display = L["Assigned Role"],
type = "select",
init = "UnitGroupRolesAssigned(unit)",
values = "role_types",
store = true,
conditionType = "select",
enable = function(trigger)
return not WeakAuras.IsClassic() and (trigger.unit == "group" or trigger.unit == "raid" or trigger.unit == "party")
end
},
{
name = "raid_role",
display = L["Assigned Role"],
type = "select",
init = "WeakAuras.UnitRaidRole(unit)",
values = "raid_role_types",
store = true,
conditionType = "select",
enable = function(trigger)
return WeakAuras.IsClassic() and (trigger.unit == "group" or trigger.unit == "raid" or trigger.unit == "party")
end
},
{
name = "ignoreSelf",
display = L["Ignore Self"],
type = "toggle",
width = WeakAuras.doubleWidth,
enable = function(trigger)
return trigger.unit == "nameplate" or trigger.unit == "group" or trigger.unit == "raid" or trigger.unit == "party"
end,
init = "not UnitIsUnit(\"player\", unit)"
},
{
name = "ignoreDead",
display = L["Ignore Dead"],
type = "toggle",
width = WeakAuras.doubleWidth,
enable = function(trigger)
return trigger.unit == "group" or trigger.unit == "raid" or trigger.unit == "party"
end,
init = "not UnitIsDeadOrGhost(unit)"
},
{
name = "ignoreDisconnected",
display = L["Ignore Disconnected"],
type = "toggle",
width = WeakAuras.doubleWidth,
enable = function(trigger)
return trigger.unit == "group" or trigger.unit == "raid" or trigger.unit == "party"
end,
init = "UnitIsConnected(unit)"
},
{
name = "hostility",
display = L["Hostility"],
type = "select",
init = "WeakAuras.GetPlayerReaction(unit)",
values = "hostility_types",
store = true,
conditionType = "select",
},
{
name = "character",
display = L["Character Type"],
type = "select",
init = "UnitIsPlayer(unit) and 'player' or 'npc'",
values = "character_types",
store = true,
conditionType = "select"
},
{
name = "level",
display = L["Level"],
type = "number",
init = "UnitLevel(unit)",
store = true,
conditionType = "number"
},
{
name = "npcId",
display = L["Npc ID"],
type = "string",
store = true,
conditionType = "string",
test = "select(6, strsplit('-', UnitGUID(unit) or '')) == %q",
},
{
name = "attackable",
display = L["Attackable"],
type = "tristate",
init = "UnitCanAttack('player', unit)",
store = true,
conditionType = "bool"
},
{
name = "inCombat",
display = L["In Combat"],
type = "tristate",
init = "UnitAffectingCombat(unit)",
store = true,
conditionType = "bool"
},
{
hidden = true,
test = "WeakAuras.UnitExistsFixed(unit, smart) and specificUnitCheck"
}
},
automaticrequired = true
},
["Faction Reputation"] = {
type = "status",
canHaveDuration = false,
events = {
["events"] = {
"UPDATE_FACTION",
}
},
internal_events = {"WA_DELAYED_PLAYER_ENTERING_WORLD"},
force_events = "UPDATE_FACTION",
name = L["Faction Reputation"],
init = function(trigger)
local ret = [=[
local factionID = %q
local name, description, standingId, bottomValue, topValue, earnedValue, _, _, isHeader, _, _, _, _, factionID = GetFactionInfoByID(factionID)
local standing
if tonumber(standingId) then
standing = getglobal("FACTION_STANDING_LABEL"..standingId)
end
]=]
return ret:format(trigger.factionID or 0)
end,
statesParameter = "one",
args = {
{
name = "factionID",
display = L["Faction"],
required = true,
type = "select",
values = function()
local ret = {}
for i = 1, GetNumFactions() do
local name, _, _, _, _, _, _, _, isHeader, _, _, _, _, factionID = GetFactionInfo(i)
if not isHeader and factionID then
ret[factionID] = name
end
end
return ret
end,
conditionType = "select",
test = "true"
},
{
name = "name",
display = L["Faction Name"],
type = "string",
store = "true",
hidden = "true",
init = "name",
test = "true"
},
{
name = "total",
display = L["Total"],
type = "number",
store = true,
init = [[topValue - bottomValue]],
hidden = true,
test = "true",
conditionType = "number",
},
{
name = "value",
display = L["Value"],
type = "number",
store = true,
init = [[earnedValue - bottomValue]],
hidden = true,
test = "true",
conditionType = "number",
},
{
name = "standingId",
display = L["Standing"],
type = "select",
values = function()
local ret = {}
for i = 0, 8 do
ret[i] = getglobal("FACTION_STANDING_LABEL"..i)
end
return ret
end,
init = "standingId",
store = "true",
conditionType = "select",
},
{
name = "standing",
display = L["Standing"],
type = "string",
init = "standing",
store = "true",
hidden = "true",
test = "true"
},
{
name = "progressType",
hidden = true,
init = "'static'",
store = true,
test = "true"
},
},
automaticrequired = true
},
["Experience"] = {
type = "status",
canHaveDuration = false,
events = {
["events"] = {
"PLAYER_XP_UPDATE",
}
},
internal_events = {"WA_DELAYED_PLAYER_ENTERING_WORLD"},
force_events = "PLAYER_XP_UPDATE",
name = L["Player Experience"],
init = function(trigger)
return ""
end,
statesParameter = "one",
args = {
{
name = "level",
display = L["Level"],
required = false,
type = "number",
store = true,
init = [[UnitLevel("player")]],
conditionType = "number",
},
{
name = "currentXP",
display = L["Current Experience"],
type = "number",
store = true,
init = [[UnitXP("player")]],
conditionType = "number",
},
{
name = "totalXP",
display = L["Total Experience"],
type = "number",
store = true,
init = [[UnitXPMax("player")]],
conditionType = "number",
},
{
name = "value",
type = "number",
store = true,
init = "currentXP",
hidden = true,
test = "true",
},
{
name = "total",
type = "number",
store = true,
init = "totalXP",
hidden = true,
test = "true",
},
{
name = "progressType",
hidden = true,
init = "'static'",
store = true,
test = "true"
},
{
name = "percentXP",
display = L["Experience (%)"],
type = "number",
init = "total ~= 0 and (value / total) * 100",
store = true,
conditionType = "number"
},
{
name = "showRested",
display = L["Show Rested Overlay"],
type = "toggle",
test = "true",
reloadOptions = true,
},
{
name = "restedXP",
display = L["Rested Experience"],
init = [[GetXPExhaustion() or 0]],
type = "number",
store = true,
conditionType = "number",
},
{
name = "percentrested",
display = L["Rested Experience (%)"],
init = "total ~= 0 and (restedXP / total) * 100",
type = "number",
store = true,
conditionType = "number",
},
},
overlayFuncs = {
{
name = L["Rested"],
func = function(trigger, state)
return "forward", state.restedXP
end,
enable = function(trigger)
return trigger.use_showRested
end
},
},
automaticrequired = true
},
["Health"] = {
type = "status",
canHaveDuration = true,
events = function(trigger)
local unit = trigger.unit
local result = {}
AddUnitEventForEvents(result, unit, "UNIT_HEALTH")
AddUnitEventForEvents(result, unit, "UNIT_NAME_UPDATE")
if not WeakAuras.IsClassic() then
if trigger.use_showAbsorb then
AddUnitEventForEvents(result, unit, "UNIT_ABSORB_AMOUNT_CHANGED")
end
if trigger.use_showIncomingHeal then
AddUnitEventForEvents(result, unit, "UNIT_HEAL_PREDICTION")
end
end
if trigger.use_ignoreDead or trigger.use_ignoreDisconnected then
AddUnitEventForEvents(result, unit, "UNIT_FLAGS")
end
return result
end,
internal_events = function(trigger)
local unit = trigger.unit
local result = {}
AddUnitChangeInternalEvents(unit, result)
AddUnitRoleChangeInternalEvents(unit, result)
return result
end,
force_events = unitHelperFunctions.UnitChangedForceEvents,
name = L["Health"],
init = function(trigger)
trigger.unit = trigger.unit or "player";
local ret = [=[
unit = string.lower(unit)
local name, realm = WeakAuras.UnitNameWithRealm(unit)
local smart = %s
]=];
ret = ret .. unitHelperFunctions.SpecificUnitCheck(trigger)
return ret:format(trigger.unit == "group" and "true" or "false");
end,
statesParameter = "unit",
args = {
{
name = "unit",
required = true,
display = L["Unit"],
type = "unit",
init = "arg",
values = "actual_unit_types_cast",
test = "true",
store = true
},
{
name = "health",
display = L["Health"],
type = "number",
init = "UnitHealth(unit)",
store = true,
conditionType = "number"
},
{
name = "value",
hidden = true,
init = "health",
store = true,
test = "true"
},
{
name = "total",
hidden = true,
init = "UnitHealthMax(unit)",
store = true,
test = "true"
},
{
name = "progressType",
hidden = true,
init = "'static'",
store = true,
test = "true"
},
{
name = "percenthealth",
display = L["Health (%)"],
type = "number",
init = "total ~= 0 and (value / total) * 100",
store = true,
conditionType = "number"
},
{
name = "showAbsorb",
display = L["Show Absorb"],
type = "toggle",
test = "true",
reloadOptions = true,
enable = not WeakAuras.IsClassic(),
hidden = WeakAuras.IsClassic()
},
{
name = "absorbMode",
display = L["Absorb Display"],
type = "select",
test = "true",
values = "absorb_modes",
required = true,
enable = function(trigger) return WeakAuras.IsClassic() and trigger.use_showAbsorb end,
hidden = WeakAuras.IsClassic()
},
{
name = "showIncomingHeal",
display = L["Show Incoming Heal"],
type = "toggle",
test = "true",
reloadOptions = true,
enable = not WeakAuras.IsClassic(),
hidden = WeakAuras.IsClassic()
},
{
name = "absorb",
type = "number",
display = L["Absorb"],
init = "UnitGetTotalAbsorbs(unit)",
store = true,
conditionType = "number",
enable = function(trigger) return not WeakAuras.IsClassic() and trigger.use_showAbsorb end,
hidden = WeakAuras.IsClassic()
},
{
name = "healprediction",
type = "number",
display = L["Incoming Heal"],
init = "UnitGetIncomingHeals(unit)",
store = true,
conditionType = "number",
enable = function(trigger) return not WeakAuras.IsClassic() and trigger.use_showIncomingHeal end,
hidden = WeakAuras.IsClassic()
},
{
name = "name",
display = L["Unit Name"],
type = "string",
store = true,
hidden = true,
test = "true"
},
{
name = "realm",
display = L["Realm"],
type = "string",
store = true,
hidden = true,
test = "true"
},
{
name = "namerealm",
display = L["Unit Name/Realm"],
type = "string",
preamble = "local nameRealmChecker = WeakAuras.ParseNameCheck(%q)",
test = "nameRealmChecker:Check(name, realm)",
conditionType = "string",
conditionPreamble = function(input)
return WeakAuras.ParseNameCheck(input)
end,
conditionTest = function(state, needle, op, preamble)
return preamble:Check(state.name, state.realm)
end,
operator_types = "none",
desc = constants.nameRealmFilterDesc,
},
{
name = "npcId",
display = L["Npc ID"],
type = "string",
store = true,
conditionType = "string",
test = "select(6, strsplit('-', UnitGUID(unit) or '')) == %q",
},
{
name = "class",
display = L["Class"],
type = "select",
init = "select(2, UnitClass(unit))",
values = "class_types",
store = true,
conditionType = "select"
},
{
name = "role",
display = L["Assigned Role"],
type = "select",
init = "UnitGroupRolesAssigned(unit)",
values = "role_types",
store = true,
conditionType = "select",
enable = function(trigger)
return not WeakAuras.IsClassic() and (trigger.unit == "group" or trigger.unit == "raid" or trigger.unit == "party")
end
},
{
name = "raid_role",
display = L["Assigned Role"],
type = "select",
init = "WeakAuras.UnitRaidRole(unit)",
values = "raid_role_types",
store = true,
conditionType = "select",
enable = function(trigger)
return WeakAuras.IsClassic() and (trigger.unit == "group" or trigger.unit == "raid" or trigger.unit == "party")
end
},
{
name = "ignoreSelf",
display = L["Ignore Self"],
type = "toggle",
width = WeakAuras.doubleWidth,
enable = function(trigger)
return trigger.unit == "nameplate" or trigger.unit == "group" or trigger.unit == "raid" or trigger.unit == "party"
end,
init = "not UnitIsUnit(\"player\", unit)"
},
{
name = "ignoreDead",
display = L["Ignore Dead"],
type = "toggle",
width = WeakAuras.doubleWidth,
enable = function(trigger)
return trigger.unit == "group" or trigger.unit == "raid" or trigger.unit == "party"
end,
init = "not UnitIsDeadOrGhost(unit)"
},
{
name = "ignoreDisconnected",
display = L["Ignore Disconnected"],
type = "toggle",
width = WeakAuras.doubleWidth,
enable = function(trigger)
return trigger.unit == "group" or trigger.unit == "raid" or trigger.unit == "party"
end,
init = "UnitIsConnected(unit)"
},
{
name = "nameplateType",
display = L["Nameplate Type"],
type = "select",
init = "WeakAuras.GetPlayerReaction(unit)",
values = "hostility_types",
conditionType = "select",
store = true,
enable = function(trigger)
return trigger.unit == "nameplate"
end
},
{
name = "name",
hidden = true,
init = "UnitName(unit)",
test = "true"
},
{
hidden = true,
test = "WeakAuras.UnitExistsFixed(unit, smart) and specificUnitCheck"
}
},
overlayFuncs = {
{
name = L["Absorb"],
func = function(trigger, state)
local absorb = state.absorb
if (trigger.absorbMode == "OVERLAY_FROM_START") then
return 0, absorb;
else
return "forward", absorb;
end
end,
enable = function(trigger)
return not WeakAuras.IsClassic() and trigger.use_showAbsorb;
end
},
{
name = L["Incoming Heal"],
func = function(trigger, state)
if (trigger.use_showIncomingHeal) then
local heal = state.healprediction;
return "forward", heal;
end
end,
enable = function(trigger)
return not WeakAuras.IsClassic() and trigger.use_showIncomingHeal;
end
}
},
automaticrequired = true
},
["Power"] = {
type = "status",
canHaveDuration = true,
events = function(trigger)
local unit = trigger.unit
local result = {}
AddUnitEventForEvents(result, unit, "UNIT_POWER_FREQUENT")
AddUnitEventForEvents(result, unit, "UNIT_MAXPOWER")
AddUnitEventForEvents(result, unit, "UNIT_DISPLAYPOWER")
AddUnitEventForEvents(result, unit, "UNIT_NAME_UPDATE")
-- The api for spell power costs is not meant to be for other units
if trigger.use_showCost and trigger.unit == "player" then
AddUnitEventForEvents(result, "player", "UNIT_SPELLCAST_START")
AddUnitEventForEvents(result, "player", "UNIT_SPELLCAST_STOP")
AddUnitEventForEvents(result, "player", "UNIT_SPELLCAST_FAILED")
AddUnitEventForEvents(result, "player", "UNIT_SPELLCAST_SUCCEEDED")
end
if trigger.use_powertype and trigger.powertype == 99 then
AddUnitEventForEvents(result, unit, "UNIT_ABSORB_AMOUNT_CHANGED")
end
if trigger.use_ignoreDead or trigger.use_ignoreDisconnected then
AddUnitEventForEvents(result, unit, "UNIT_FLAGS")
end
if not WeakAuras.IsClassic()
and trigger.use_powertype and trigger.powertype == 4
then
AddUnitEventForEvents(result, unit, "UNIT_POWER_POINT_CHARGE")
end
return result;
end,
internal_events = function(trigger)
local unit = trigger.unit
local result = {}
AddUnitChangeInternalEvents(unit, result)
AddUnitRoleChangeInternalEvents(unit, result)
return result
end,
force_events = unitHelperFunctions.UnitChangedForceEvents,
name = L["Power"],
init = function(trigger)
trigger.unit = trigger.unit or "player";
local ret = [=[
unit = string.lower(unit)
local name, realm = WeakAuras.UnitNameWithRealm(unit)
local smart = %s
local powerType = %s;
local unitPowerType = UnitPowerType(unit);
local powerTypeToCheck = powerType or unitPowerType;
local powerThirdArg = WeakAuras.UseUnitPowerThirdArg(powerTypeToCheck);
if WeakAuras.IsClassic() and powerType == 99 then powerType = 1 end
]=];
ret = ret:format(trigger.unit == "group" and "true" or "false", trigger.use_powertype and trigger.powertype or "nil");
ret = ret .. unitHelperFunctions.SpecificUnitCheck(trigger)
if (trigger.use_powertype and trigger.powertype == 99 and not WeakAuras.IsClassic()) then
ret = ret .. [[
local UnitPower = UnitStagger;
local UnitPowerMax = UnitHealthMax;
]]
if (trigger.use_scaleStagger and trigger.scaleStagger) then
ret = ret .. string.format([[
local UnitPowerMax = function(unit)
return UnitHealthMax(unit) * %s
end
]], trigger.scaleStagger)
else
ret = ret .. [[
local UnitPowerMax = UnitHealthMax;
]]
end
end
local canEnableShowCost = (not trigger.use_powertype or trigger.powertype ~= 99) and trigger.unit == "player";
if (canEnableShowCost and trigger.use_showCost) then
ret = ret .. [[
if (event == "UNIT_DISPLAYPOWER") then
local cost = WeakAuras.GetSpellCost(powerTypeToCheck)
if state.cost ~= cost then
state.cost = cost
state.changed = true
end
elseif ( (event == "UNIT_SPELLCAST_START" or event == "UNIT_SPELLCAST_STOP" or event == "UNIT_SPELLCAST_FAILED" or event == "UNIT_SPELLCAST_SUCCEEDED") and unit == "player") then
local cost = WeakAuras.GetSpellCost(powerTypeToCheck)
if state.cost ~= cost then
state.cost = cost
state.changed = true
end
end
]]
end
if not WeakAuras.IsClassic()
and trigger.unit == 'player' and trigger.use_powertype and trigger.powertype == 4
then
ret = ret .. [[
local chargedComboPoint = GetUnitChargedPowerPoints('player')
chargedComboPoint = chargedComboPoint and chargedComboPoint[1]
if state.chargedComboPoint ~= chargedComboPoint then
state.chargedComboPoint = chargedComboPoint
state.changed = true
end
]]
end
return ret
end,
statesParameter = "unit",
args = {
{
name = "unit",
required = true,
display = L["Unit"],
type = "unit",
init = "arg",
values = "actual_unit_types_cast",
test = "true",
store = true
},
{
name = "powertype",
display = L["Power Type"],
type = "select",
values = function() return WeakAuras.IsClassic() and Private.power_types or Private.power_types_with_stagger end,
init = "unitPowerType",
test = "true",
store = true,
conditionType = "select",
reloadOptions = true
},
{
name = "requirePowerType",
display = L["Only if Primary"],
type = "toggle",
test = "unitPowerType == powerType",
enable = function(trigger)
return trigger.use_powertype
end,
},
{
name = "showCost",
display = L["Overlay Cost of Casts"],
type = "toggle",
test = "true",
enable = function(trigger)
return (not trigger.use_powertype or trigger.powertype ~= 99) and trigger.unit == "player";
end,
reloadOptions = true
},
{
name = "showChargedComboPoints",
display = WeakAuras.newFeatureString .. L["Overlay Charged Combo Points"],
type = "toggle",
test = "true",
reloadOptions = true,
enable = function(trigger)
return not WeakAuras.IsClassic() and trigger.unit == 'player' and trigger.use_powertype and trigger.powertype == 4
end,
hidden = WeakAuras.IsClassic()
},
{
name = "chargedComboPoint",
type = "number",
display = WeakAuras.newFeatureString .. L["Charged Combo Point"],
store = true,
conditionType = "number",
enable = function(trigger)
return not WeakAuras.IsClassic() and trigger.unit == 'player'and trigger.use_powertype and trigger.powertype == 4
end,
hidden = true,
test = "true"
},
{
name = "scaleStagger",
display = L["Stagger Scale"],
type = "string",
validate = WeakAuras.ValidateNumeric,
enable = function(trigger)
return trigger.use_powertype and trigger.powertype == 99
end,
test = "true"
},
{
name = "power",
display = L["Power"],
type = "number",
init = WeakAuras.IsClassic() and "powerType == 4 and GetComboPoints(unit, unit .. '-target') or UnitPower(unit, powerType, powerThirdArg)"
or "UnitPower(unit, powerType, powerThirdArg) / WeakAuras.UnitPowerDisplayMod(powerTypeToCheck)",
store = true,
conditionType = "number",
},
{
name = "value",
hidden = true,
init = "power",
store = true,
test = "true"
},
{
name = "total",
hidden = true,
init = WeakAuras.IsClassic() and "powerType == 4 and (math.max(1, UnitPowerMax(unit, 14))) or math.max(1, UnitPowerMax(unit, powerType, powerThirdArg))"
or "math.max(1, UnitPowerMax(unit, powerType, powerThirdArg)) / WeakAuras.UnitPowerDisplayMod(powerTypeToCheck)",
store = true,
test = "true"
},
{
name = "stacks",
hidden = true,
init = "power",
store = true,
test = "true"
},
{
name = "progressType",
hidden = true,
init = "'static'",
store = true,
test = "true"
},
{
name = "percentpower",
display = L["Power (%)"],
type = "number",
init = "total ~= 0 and (value / total) * 100",
store = true,
conditionType = "number"
},
{
name = "name",
display = L["Unit Name"],
type = "string",
store = true,
hidden = true,
test = "true"
},
{
name = "realm",
display = L["Realm"],
type = "string",
store = true,
hidden = true,
test = "true"
},
{
name = "namerealm",
display = L["Unit Name/Realm"],
type = "string",
preamble = "local nameRealmChecker = WeakAuras.ParseNameCheck(%q)",
test = "nameRealmChecker:Check(name, realm)",
conditionType = "string",
conditionPreamble = function(input)
return WeakAuras.ParseNameCheck(input)
end,
conditionTest = function(state, needle, op, preamble)
return preamble:Check(state.name, state.realm)
end,
operator_types = "none",
desc = constants.nameRealmFilterDesc,
},
{
name = "npcId",
display = L["Npc ID"],
type = "string",
store = true,
conditionType = "string",
test = "select(6, strsplit('-', UnitGUID(unit) or '')) == %q",
},
{
name = "class",
display = L["Class"],
type = "select",
init = "select(2, UnitClass(unit))",
values = "class_types",
store = true,
conditionType = "select"
},
{
name = "role",
display = L["Assigned Role"],
type = "select",
init = "UnitGroupRolesAssigned(unit)",
values = "role_types",
store = true,
conditionType = "select",
enable = function(trigger)
return not WeakAuras.IsClassic() and (trigger.unit == "group" or trigger.unit == "raid" or trigger.unit == "party")
end
},
{
name = "raid_role",
display = L["Assigned Role"],
type = "select",
init = "WeakAuras.UnitRaidRole(unit)",
values = "raid_role_types",
store = true,
conditionType = "select",
enable = function(trigger)
return WeakAuras.IsClassic() and (trigger.unit == "group" or trigger.unit == "raid" or trigger.unit == "party")
end
},
{
name = "ignoreSelf",
display = L["Ignore Self"],
type = "toggle",
width = WeakAuras.doubleWidth,
enable = function(trigger)
return trigger.unit == "nameplate" or trigger.unit == "group" or trigger.unit == "raid" or trigger.unit == "party"
end,
init = "not UnitIsUnit(\"player\", unit)"
},
{
name = "ignoreDead",
display = L["Ignore Dead"],
type = "toggle",
width = WeakAuras.doubleWidth,
enable = function(trigger)
return trigger.unit == "group" or trigger.unit == "raid" or trigger.unit == "party"
end,
init = "not UnitIsDeadOrGhost(unit)"
},
{
name = "ignoreDisconnected",
display = L["Ignore Disconnected"],
type = "toggle",
width = WeakAuras.doubleWidth,
enable = function(trigger)
return trigger.unit == "group" or trigger.unit == "raid" or trigger.unit == "party"
end,
init = "UnitIsConnected(unit)"
},
{
name = "nameplateType",
display = L["Nameplate Type"],
type = "select",
init = "WeakAuras.GetPlayerReaction(unit)",
values = "hostility_types",
store = true,
conditionType = "select",
enable = function(trigger)
return trigger.unit == "nameplate"
end
},
{
hidden = true,
test = "WeakAuras.UnitExistsFixed(unit, smart) and specificUnitCheck"
}
},
overlayFuncs = {
{
name = L["Spell Cost"],
func = function(trigger, state)
return "back", type(state.cost) == "number" and state.cost;
end,
enable = function(trigger)
return trigger.use_showCost and (not trigger.use_powertype or trigger.powertype ~= 99) and trigger.unit == "player";
end
},
{
name = L["Charged Combo Point"],
func = function(trigger, state)
if type(state.chargedComboPoint) == "number" then
return state.chargedComboPoint - 1, state.chargedComboPoint
end
return 0, 0
end,
enable = function(trigger)
return not WeakAuras.IsClassic() and trigger.unit == 'player' and trigger.use_powertype and trigger.powertype == 4 and trigger.use_showChargedComboPoints
end,
}
},
automaticrequired = true
},
["Alternate Power"] = {
type = "status",
canHaveDuration = true,
events = function(trigger)
local unit = trigger.unit
local result = {}
AddUnitEventForEvents(result, unit, "UNIT_POWER_FREQUENT")
AddUnitEventForEvents(result, unit, "UNIT_NAME_UPDATE")
if trigger.use_ignoreDead or trigger.use_ignoreDisconnected then
AddUnitEventForEvents(result, unit, "UNIT_FLAGS")
end
AddUnitEventForEvents(result, unit, "UNIT_POWER_BAR_SHOW")
return result
end,
internal_events = function(trigger)
local unit = trigger.unit
local result = { }
AddUnitChangeInternalEvents(unit, result)
AddUnitRoleChangeInternalEvents(unit, result)
return result
end,
force_events = unitHelperFunctions.UnitChangedForceEvents,
name = L["Alternate Power"],
init = function(trigger)
trigger.unit = trigger.unit or "player";
local ret = [=[
unit = string.lower(unit)
local unitname, realm = WeakAuras.UnitNameWithRealm(unit)
local smart = %s
]=]
ret = ret .. unitHelperFunctions.SpecificUnitCheck(trigger)
return ret:format(trigger.unit == "group" and "true" or "false");
end,
statesParameter = "unit",
args = {
{
name = "unit",
required = true,
display = L["Unit"],
type = "unit",
init = "arg",
values = "actual_unit_types_cast",
test = "true",
store = true
},
{
name = "power",
display = L["Alternate Power"],
type = "number",
init = "UnitPower(unit, 10)"
},
{
name = "value",
hidden = true,
init = "power",
store = true,
test = "true"
},
{
name = "total",
hidden = true,
init = "UnitPowerMax(unit, 10)",
store = true,
test = "true"
},
{
name = "progressType",
hidden = true,
init = "'static'",
store = true,
test = "true"
},
{
name = "name",
hidden = true,
init = "GetUnitPowerBarStrings(unit)",
store = true,
test = "true"
},
{
name = "unitname",
display = L["Unit Name"],
type = "string",
store = true,
hidden = true,
test = "true"
},
{
name = "unitrealm",
display = L["Realm"],
type = "string",
store = true,
hidden = true,
test = "true"
},
{
name = "namerealm",
display = L["Unit Name/Realm"],
type = "string",
preamble = "local nameRealmChecker = WeakAuras.ParseNameCheck(%q)",
test = "nameRealmChecker:Check(unitname, unitrealm)",
conditionType = "string",
conditionPreamble = function(input)
return WeakAuras.ParseNameCheck(input)
end,
conditionTest = function(state, needle, op, preamble)
return preamble:Check(state.unitname, state.unitrealm)
end,
operator_types = "none",
desc = constants.nameRealmFilterDesc,
},
{
name = "icon",
hidden = true,
init = "GetUnitPowerBarTextureInfo(unit, 1)",
store = true,
test = "true"
},
{
name = "class",
display = L["Class"],
type = "select",
init = "select(2, UnitClass(unit))",
values = "class_types",
store = true,
conditionType = "select"
},
{
name = "role",
display = L["Assigned Role"],
type = "select",
init = "UnitGroupRolesAssigned(unit)",
values = "role_types",
store = true,
conditionType = "select",
enable = function(trigger)
return not WeakAuras.IsClassic() and (trigger.unit == "group" or trigger.unit == "raid" or trigger.unit == "party")
end
},
{
name = "raid_role",
display = L["Assigned Role"],
type = "select",
init = "WeakAuras.UnitRaidRole(unit)",
values = "raid_role_types",
store = true,
conditionType = "select",
enable = function(trigger)
return WeakAuras.IsClassic() and (trigger.unit == "group" or trigger.unit == "raid" or trigger.unit == "party")
end
},
{
name = "ignoreSelf",
display = L["Ignore Self"],
type = "toggle",
width = WeakAuras.doubleWidth,
enable = function(trigger)
return trigger.unit == "nameplate" or trigger.unit == "group" or trigger.unit == "raid" or trigger.unit == "party"
end,
init = "not UnitIsUnit(\"player\", unit)"
},
{
name = "ignoreDead",
display = L["Ignore Dead"],
type = "toggle",
width = WeakAuras.doubleWidth,
enable = function(trigger)
return trigger.unit == "group" or trigger.unit == "raid" or trigger.unit == "party"
end,
init = "not UnitIsDeadOrGhost(unit)"
},
{
name = "ignoreDisconnected",
display = L["Ignore Disconnected"],
type = "toggle",
width = WeakAuras.doubleWidth,
enable = function(trigger)
return trigger.unit == "group" or trigger.unit == "raid" or trigger.unit == "party"
end,
init = "UnitIsConnected(unit)"
},
{
name = "nameplateType",
display = L["Nameplate Type"],
type = "select",
init = "WeakAuras.GetPlayerReaction(unit)",
values = "hostility_types",
store = true,
conditionType = "select",
enable = function(trigger)
return trigger.unit == "nameplate"
end
},
{
hidden = true,
test = "name and WeakAuras.UnitExistsFixed(unit, smart) and specificUnitCheck"
}
},
automaticrequired = true
},
-- Todo: Give useful options to condition based on GUID and flag info
["Combat Log"] = {
type = "event",
events = {
["events"] = {"COMBAT_LOG_EVENT_UNFILTERED"}
},
init = function(trigger)
local ret = [[
local use_cloneId = %s;
]];
return ret:format(trigger.use_cloneId and "true" or "false");
end,
name = L["Combat Log"],
statesParameter = "all",
args = {
{}, -- timestamp ignored with _ argument
{}, -- messageType ignored with _ argument (it is checked before the dynamic function)
{}, -- hideCaster ignored with _ argument
{
name = "sourceGUID",
init = "arg",
hidden = "true",
test = "true",
store = true,
display = L["Source GUID"]
},
{
name = "sourceUnit",
display = L["Source Unit"],
type = "unit",
test = "(sourceGUID or '') == (UnitGUID(%q) or '') and sourceGUID",
values = "actual_unit_types_with_specific",
enable = function(trigger)
return not (trigger.subeventPrefix == "ENVIRONMENTAL")
end,
store = true,
conditionType = "select",
conditionTest = function(state, needle, op)
return state and state.show and ((state.sourceGUID or '') == (UnitGUID(needle) or '')) == (op == "==")
end
},
{
name = "sourceName",
display = L["Source Name"],
type = "string",
init = "arg",
store = true,
conditionType = "string"
},
{
name = "sourceNpcId",
display = L["Source NPC Id"],
type = "string",
test = "select(6, strsplit('-', sourceGUID or '')) == %q",
enable = function(trigger)
return not (trigger.subeventPrefix == "ENVIRONMENTAL")
end,
},
{
name = "sourceFlags",
display = L["Source In Group"],
type = "select",
values = "combatlog_flags_check_type",
init = "arg",
store = true,
test = "WeakAuras.CheckCombatLogFlags(sourceFlags, %q)",
conditionType = "select",
conditionTest = function(state, needle)
return state and state.show and WeakAuras.CheckCombatLogFlags(state.sourceFlags, needle);
end
},
{
name = "sourceFlags2",
display = L["Source Reaction"],
type = "select",
values = "combatlog_flags_check_reaction",
test = "WeakAuras.CheckCombatLogFlagsReaction(sourceFlags, %q)",
conditionType = "select",
conditionTest = function(state, needle)
return state and state.show and WeakAuras.CheckCombatLogFlagsReaction(state.sourceFlags, needle);
end
},
{
name = "sourceFlags3",
display = L["Source Object Type"],
type = "select",
values = "combatlog_flags_check_object_type",
test = "WeakAuras.CheckCombatLogFlagsObjectType(sourceFlags, %q)",
conditionType = "select",
conditionTest = function(state, needle)
return state and state.show and WeakAuras.CheckCombatLogFlagsObjectType(state.sourceFlags, needle);
end
},
{
name = "sourceRaidFlags",
display = L["Source Raid Mark"],
type = "select",
values = "combatlog_raid_mark_check_type",
init = "arg",
store = true,
test = "WeakAuras.CheckRaidFlags(sourceRaidFlags, %q)",
conditionType = "select",
conditionTest = function(state, needle)
return state and state.show and WeakAuras.CheckRaidFlags(state.sourceRaidFlags, needle);
end
},
{
name = "destGUID",
init = "arg",
hidden = "true",
test = "true",
store = true,
display = L["Destination GUID"]
},
{
name = "destUnit",
display = L["Destination Unit"],
type = "unit",
test = "(destGUID or '') == (UnitGUID(%q) or '') and destGUID",
values = "actual_unit_types_with_specific",
enable = function(trigger)
return not (trigger.subeventPrefix == "SPELL" and trigger.subeventSuffix == "_CAST_START");
end,
store = true,
conditionType = "select",
conditionTest = function(state, needle, op)
return state and state.show and ((state.destGUID or '') == (UnitGUID(needle) or '')) == (op == "==")
end
},
{
name = "destName",
display = L["Destination Name"],
type = "string",
init = "arg",
enable = function(trigger)
return not (trigger.subeventPrefix == "SPELL" and trigger.subeventSuffix == "_CAST_START");
end,
store = true,
conditionType = "string"
},
{
name = "destNpcId",
display = L["Destination NPC Id"],
type = "string",
test = "select(6, strsplit('-', destGUID or '')) == %q",
enable = function(trigger)
return not (trigger.subeventPrefix == "SPELL" and trigger.subeventSuffix == "_CAST_START");
end,
},
{ -- destName ignore for SPELL_CAST_START
enable = function(trigger)
return (trigger.subeventPrefix == "SPELL" and trigger.subeventSuffix == "_CAST_START");
end
},
{
name = "destFlags",
display = L["Destination In Group"],
type = "select",
values = "combatlog_flags_check_type",
init = "arg",
store = true,
test = "WeakAuras.CheckCombatLogFlags(destFlags, %q)",
conditionType = "select",
conditionTest = function(state, needle)
return state and state.show and WeakAuras.CheckCombatLogFlags(state.destFlags, needle);
end,
enable = function(trigger)
return not (trigger.subeventPrefix == "SPELL" and trigger.subeventSuffix == "_CAST_START");
end,
},
{
name = "destFlags2",
display = L["Destination Reaction"],
type = "select",
values = "combatlog_flags_check_reaction",
test = "WeakAuras.CheckCombatLogFlagsReaction(destFlags, %q)",
conditionType = "select",
conditionTest = function(state, needle)
return state and state.show and WeakAuras.CheckCombatLogFlagsReaction(state.destFlags, needle);
end,
enable = function(trigger)
return not (trigger.subeventPrefix == "SPELL" and trigger.subeventSuffix == "_CAST_START");
end,
},
{
name = "destFlags3",
display = L["Destination Object Type"],
type = "select",
values = "combatlog_flags_check_object_type",
test = "WeakAuras.CheckCombatLogFlagsObjectType(destFlags, %q)",
conditionType = "select",
conditionTest = function(state, needle)
return state and state.show and WeakAuras.CheckCombatLogFlagsObjectType(state.destFlags, needle);
end,
enable = function(trigger)
return not (trigger.subeventPrefix == "SPELL" and trigger.subeventSuffix == "_CAST_START");
end,
},
{-- destFlags ignore for SPELL_CAST_START
enable = function(trigger)
return (trigger.subeventPrefix == "SPELL" and trigger.subeventSuffix == "_CAST_START");
end,
},
{
name = "destRaidFlags",
display = L["Dest Raid Mark"],
type = "select",
values = "combatlog_raid_mark_check_type",
init = "arg",
store = true,
test = "WeakAuras.CheckRaidFlags(destRaidFlags, %q)",
conditionType = "select",
conditionTest = function(state, needle)
return state and state.show and WeakAuras.CheckRaidFlags(state.destRaidFlags, needle);
end,
enable = function(trigger)
return not (trigger.subeventPrefix == "SPELL" and trigger.subeventSuffix == "_CAST_START");
end,
},
{ -- destRaidFlags ignore for SPELL_CAST_START
enable = function(trigger)
return (trigger.subeventPrefix == "SPELL" and trigger.subeventSuffix == "_CAST_START");
end
},
{
name = "spellId",
display = L["Spell Id"],
type = "string",
init = "arg",
enable = function(trigger)
return trigger.subeventPrefix and (trigger.subeventPrefix:find("SPELL") or trigger.subeventPrefix == "RANGE" or trigger.subeventPrefix:find("DAMAGE"))
end,
test = WeakAuras.IsClassic() and "GetSpellInfo(%q) == spellName" or nil,
store = true,
conditionType = "number"
},
{
name = "spellName",
display = L["Spell Name"],
type = "string",
init = "arg",
enable = function(trigger)
return trigger.subeventPrefix and (trigger.subeventPrefix:find("SPELL") or trigger.subeventPrefix == "RANGE" or trigger.subeventPrefix:find("DAMAGE"))
end,
store = true,
conditionType = "string"
},
{
enable = function(trigger)
return trigger.subeventPrefix and (trigger.subeventPrefix:find("SPELL") or trigger.subeventPrefix == "RANGE" or trigger.subeventPrefix:find("DAMAGE"))
end
}, -- spellSchool ignored with _ argument
{
name = "environmentalType",
display = L["Environment Type"],
type = "select",
init = "arg",
values = "environmental_types",
enable = function(trigger)
return trigger.subeventPrefix == "ENVIRONMENTAL"
end,
store = true,
conditionType = "select"
},
{
name = "missType",
display = L["Miss Type"],
type = "select",
init = "arg",
values = "miss_types",
enable = function(trigger)
return trigger.subeventSuffix and trigger.subeventPrefix and (trigger.subeventSuffix == "_MISSED" or trigger.subeventPrefix == "DAMAGE_SHIELD_MISSED")
end,
conditionType = "select",
store = true
},
{
enable = function(trigger)
return trigger.subeventSuffix and (trigger.subeventSuffix == "_ABSORBED")
end
}, -- source of absorb GUID ignored with SPELL_ABSORBED
{
enable = function(trigger)
return trigger.subeventSuffix and (trigger.subeventSuffix == "_ABSORBED")
end
}, -- source of absorb Name ignored with SPELL_ABSORBED
{
enable = function(trigger)
return trigger.subeventSuffix and (trigger.subeventSuffix == "_ABSORBED")
end
}, -- source of absorb Flags ignored with SPELL_ABSORBED
{
enable = function(trigger)
return trigger.subeventSuffix and (trigger.subeventSuffix == "_ABSORBED")
end
}, -- source of absorb Raid Flags ignored with SPELL_ABSORBED
{
enable = function(trigger)
return trigger.subeventSuffix and (trigger.subeventSuffix == "_ABSORBED" or trigger.subeventSuffix == "_INTERRUPT" or trigger.subeventSuffix == "_DISPEL" or trigger.subeventSuffix == "_DISPEL_FAILED" or trigger.subeventSuffix == "_STOLEN" or trigger.subeventSuffix == "_AURA_BROKEN_SPELL")
end
}, -- extraSpellId ignored with SPELL_ABSORBED
{
name = "extraSpellName",
display = L["Extra Spell Name"],
type = "string",
init = "arg",
enable = function(trigger)
return trigger.subeventSuffix and (trigger.subeventSuffix == "_ABSORBED" or trigger.subeventSuffix == "_INTERRUPT" or trigger.subeventSuffix == "_DISPEL" or trigger.subeventSuffix == "_DISPEL_FAILED" or trigger.subeventSuffix == "_STOLEN" or trigger.subeventSuffix == "_AURA_BROKEN_SPELL")
end,
store = true,
conditionType = "string"
},
{
enable = function(trigger)
return trigger.subeventSuffix and (trigger.subeventSuffix == "_ABSORBED" or trigger.subeventSuffix == "_INTERRUPT" or trigger.subeventSuffix == "_DISPEL" or trigger.subeventSuffix == "_DISPEL_FAILED" or trigger.subeventSuffix == "_STOLEN" or trigger.subeventSuffix == "_AURA_BROKEN_SPELL")
end
}, -- extraSchool ignored with _ argument
{
name = "auraType",
display = L["Aura Type"],
type = "select",
init = "arg",
values = "aura_types",
store = true,
enable = function(trigger)
return trigger.subeventSuffix and (trigger.subeventSuffix:find("AURA") or trigger.subeventSuffix == "_DISPEL" or trigger.subeventSuffix == "_STOLEN")
end,
conditionType = "select"
},
{
name = "amount",
display = L["Amount"],
type = "number",
init = "arg",
enable = function(trigger)
return trigger.subeventSuffix and trigger.subeventPrefix and (trigger.subeventSuffix == "_ABSORBED" or trigger.subeventSuffix == "_DAMAGE" or trigger.subeventSuffix == "_HEAL" or trigger.subeventSuffix == "_ENERGIZE" or trigger.subeventSuffix == "_DRAIN" or trigger.subeventSuffix == "_LEECH" or trigger.subeventPrefix:find("DAMAGE"))
end,
store = true,
conditionType = "number"
},
{
name = "overkill",
display = L["Overkill"],
type = "number",
init = "arg",
enable = function(trigger)
return trigger.subeventSuffix and trigger.subeventPrefix and (trigger.subeventSuffix == "_DAMAGE" or trigger.subeventPrefix == "DAMAGE_SHIELD" or trigger.subeventPrefix == "DAMAGE_SPLIT")
end,
store = true,
conditionType = "number"
},
{
name = "overhealing",
display = L["Overhealing"],
type = "number",
init = "arg",
enable = function(trigger)
return trigger.subeventSuffix and trigger.subeventSuffix == "_HEAL"
end,
store = true,
conditionType = "number"
},
{
enable = function(trigger)
return trigger.subeventSuffix and trigger.subeventPrefix and (trigger.subeventSuffix == "_DAMAGE" or trigger.subeventPrefix == "DAMAGE_SHIELD" or trigger.subeventPrefix == "DAMAGE_SPLIT")
end
}, -- damage school ignored with _ argument
{
name = "resisted",
display = L["Resisted"],
type = "number",
init = "arg",
enable = function(trigger)
return trigger.subeventSuffix and trigger.subeventPrefix and (trigger.subeventSuffix == "_DAMAGE" or trigger.subeventPrefix == "DAMAGE_SHIELD" or trigger.subeventPrefix == "DAMAGE_SPLIT")
end,
store = true,
conditionType = "number"
},
{
name = "blocked",
display = L["Blocked"],
type = "number",
init = "arg",
enable = function(trigger)
return trigger.subeventSuffix and trigger.subeventPrefix and (trigger.subeventSuffix == "_DAMAGE" or trigger.subeventPrefix == "DAMAGE_SHIELD" or trigger.subeventPrefix == "DAMAGE_SPLIT")
end,
store = true,
conditionType = "number"
},
{
name = "absorbed",
display = L["Absorbed"],
type = "number",
init = "arg",
enable = function(trigger)
return trigger.subeventSuffix and trigger.subeventPrefix and (trigger.subeventSuffix == "_DAMAGE" or trigger.subeventPrefix == "DAMAGE_SHIELD" or trigger.subeventPrefix == "DAMAGE_SPLIT" or trigger.subeventSuffix == "_HEAL")
end,
store = true,
conditionType = "number"
},
{
name = "critical",
display = L["Critical"],
type = "tristate",
init = "arg",
enable = function(trigger)
return trigger.subeventSuffix and trigger.subeventPrefix and (trigger.subeventSuffix == "_DAMAGE" or trigger.subeventPrefix == "DAMAGE_SHIELD" or trigger.subeventPrefix == "DAMAGE_SPLIT" or trigger.subeventSuffix == "_HEAL")
end,
store = true,
conditionType = "bool"
},
{
name = "glancing",
display = L["Glancing"],
type = "tristate",
init = "arg",
enable = function(trigger)
return trigger.subeventSuffix and trigger.subeventPrefix and (trigger.subeventSuffix == "_DAMAGE" or trigger.subeventPrefix == "DAMAGE_SHIELD" or trigger.subeventPrefix == "DAMAGE_SPLIT")
end,
store = true,
conditionType = "bool"
},
{
name = "crushing",
display = L["Crushing"],
type = "tristate",
init = "arg",
enable = function(trigger)
return trigger.subeventSuffix and trigger.subeventPrefix and (trigger.subeventSuffix == "_DAMAGE" or trigger.subeventPrefix == "DAMAGE_SHIELD" or trigger.subeventPrefix == "DAMAGE_SPLIT")
end,
store = true,
conditionType = "bool"
},
{
name = "isOffHand",
display = L["Is Off Hand"],
type = "tristate",
init = "arg",
enable = function(trigger)
return trigger.subeventSuffix and trigger.subeventPrefix and (
trigger.subeventSuffix == "_DAMAGE" or trigger.subeventPrefix == "DAMAGE_SHIELD" or trigger.subeventPrefix == "DAMAGE_SPLIT"
or trigger.subeventSuffix == "_MISSED" or trigger.subeventPrefix == "DAMAGE_SHIELD_MISSED")
end,
store = true,
conditionType = "bool"
},
{
name = "number",
display = L["Number"],
type = "number",
init = "arg",
enable = function(trigger)
return trigger.subeventSuffix and (trigger.subeventSuffix == "_EXTRA_ATTACKS" or trigger.subeventSuffix:find("DOSE"))
end,
store = true,
conditionType = "number"
},
{
enable = function(trigger)
return trigger.subeventSuffix and (trigger.subeventSuffix == "_ENERGIZE")
end
}, -- unknown argument for _ENERGIZE ignored
{
name = "powerType",
display = L["Power Type"],
type = "select",
init = "arg",
values = "power_types",
store = true,
enable = function(trigger)
return trigger.subeventSuffix and (trigger.subeventSuffix == "_ENERGIZE" or trigger.subeventSuffix == "_DRAIN" or trigger.subeventSuffix == "_LEECH")
end,
conditionType = "select"
},
{
name = "extraAmount",
display = L["Extra Amount"],
type = "number",
init = "arg",
enable = function(trigger)
return trigger.subeventSuffix and (trigger.subeventSuffix == "_ENERGIZE" or trigger.subeventSuffix == "_DRAIN" or trigger.subeventSuffix == "_LEECH")
end,
store = true,
conditionType = "number"
},
{
enable = function(trigger)
return trigger.subeventSuffix == "_CAST_FAILED"
end
}, -- failedType ignored with _ argument - theoretically this is not necessary because it is the last argument in the event, but it is added here for completeness
{
name = "cloneId",
display = L["Clone per Event"],
type = "toggle",
test = "true",
init = "use_cloneId and WeakAuras.GetUniqueCloneId() or ''"
},
{
hidden = true,
name = "icon",
init = "spellId and select(3, GetSpellInfo(spellId)) or 'Interface\\\\Icons\\\\INV_Misc_QuestionMark'",
store = true,
test = "true"
}
},
timedrequired = true
},
["Spell Activation Overlay"] = {
type = "status",
events = {
},
internal_events = {
"WA_UPDATE_OVERLAY_GLOW"
},
force_events = "WA_UPDATE_OVERLAY_GLOW",
name = L["Spell Activation Overlay Glow"],
loadFunc = function(trigger)
if (trigger.use_exact_spellName) then
WeakAuras.WatchSpellActivation(tonumber(trigger.spellName));
else
WeakAuras.WatchSpellActivation(type(trigger.spellName) == "number" and GetSpellInfo(trigger.spellName) or trigger.spellName);
end
end,
init = function(trigger)
local spellName
if (trigger.use_exact_spellName) then
spellName = trigger.spellName
return string.format("local spellName = %s\n", tonumber(spellName) or "nil");
else
spellName = type(trigger.spellName) == "number" and GetSpellInfo(trigger.spellName) or trigger.spellName;
return string.format("local spellName = %q\n", spellName or "");
end
end,
args = {
{
name = "spellName",
required = true,
display = L["Spell"],
type = "spell",
test = "true",
showExactOption = true
},
{
hidden = true,
test = "WeakAuras.SpellActivationActive(spellName)";
}
},
iconFunc = function(trigger)
local _, _, icon = GetSpellInfo(trigger.spellName or 0);
return icon;
end,
automaticrequired = true
},
["Cooldown Progress (Spell)"] = {
type = "status",
events = {},
internal_events = function(trigger, untrigger)
local events = {
"SPELL_COOLDOWN_CHANGED",
"COOLDOWN_REMAINING_CHECK",
"WA_DELAYED_PLAYER_ENTERING_WORLD"
};
if (trigger.use_showgcd) then
tinsert(events, "GCD_START");
tinsert(events, "GCD_CHANGE");
tinsert(events, "GCD_END");
end
return events;
end,
force_events = "SPELL_COOLDOWN_FORCE",
name = L["Cooldown Progress (Spell)"],
loadFunc = function(trigger)
trigger.spellName = trigger.spellName or 0;
local spellName;
if (trigger.use_exact_spellName) then
spellName = trigger.spellName;
else
spellName = type(trigger.spellName) == "number" and GetSpellInfo(trigger.spellName) or trigger.spellName;
end
WeakAuras.WatchSpellCooldown(spellName, trigger.use_matchedRune);
if (trigger.use_showgcd) then
WeakAuras.WatchGCD();
end
end,
init = function(trigger)
trigger.spellName = trigger.spellName or 0;
local spellName;
if (trigger.use_exact_spellName) then
spellName = trigger.spellName;
else
spellName = type(trigger.spellName) == "number" and GetSpellInfo(trigger.spellName) or trigger.spellName;
end
trigger.realSpellName = spellName; -- Cache
local ret = [=[
local spellname = %s
local ignoreRuneCD = %s
local showgcd = %s;
local ignoreSpellKnown = %s;
local track = %q
local startTime, duration, gcdCooldown, readyTime = WeakAuras.GetSpellCooldown(spellname, ignoreRuneCD, showgcd, ignoreSpellKnown, track);
local charges, maxCharges, spellCount, chargeGainTime, chargeLostTime = WeakAuras.GetSpellCharges(spellname, ignoreSpellKnown);
local stacks = maxCharges and maxCharges ~= 1 and charges or (spellCount and spellCount > 0 and spellCount) or nil;
if (charges == nil) then
-- Use fake charges for spells that use GetSpellCooldown
charges = (duration == 0) and 1 or 0;
end
local genericShowOn = %s
local expirationTime = startTime and duration and startTime + duration
state.spellname = spellname;
]=];
local showOnCheck = "false";
if (trigger.genericShowOn == "showOnReady") then
showOnCheck = "startTime and startTime == 0 or gcdCooldown";
elseif (trigger.genericShowOn == "showOnCooldown") then
showOnCheck = "startTime and startTime > 0 and not gcdCooldown";
elseif (trigger.genericShowOn == "showAlways") then
showOnCheck = "startTime ~= nil";
end
if (type(spellName) == "string") then
spellName = "[[" .. spellName .. "]]";
end
ret = ret:format(spellName,
(trigger.use_matchedRune and "true" or "false"),
(trigger.use_showgcd and "true" or "false"),
(trigger.use_ignoreSpellKnown and "true" or "false"),
(trigger.track or "auto"),
showOnCheck
);
if (not trigger.use_trackcharge or not trigger.trackcharge) then
ret = ret .. [=[
if (state.expirationTime ~= expirationTime) then
state.expirationTime = expirationTime;
state.changed = true;
end
if (state.duration ~= duration) then
state.duration = duration;
state.changed = true;
end
state.progressType = 'timed';
]=];
else
local ret2 = [=[
local trackedCharge = %s
if (charges < trackedCharge) then
if (state.value ~= duration) then
state.value = duration;
state.changed = true;
end
if (state.total ~= duration) then
state.total = duration;
state.changed = true;
end
state.expirationTime = nil;
state.duration = nil;
state.progressType = 'static';
elseif (charges > trackedCharge) then
if (state.expirationTime ~= 0) then
state.expirationTime = 0;
state.changed = true;
end
if (state.duration ~= 0) then
state.duration = 0;
state.changed = true;
end
state.value = nil;
state.total = nil;
state.progressType = 'timed';
else
if (state.expirationTime ~= expirationTime) then
state.expirationTime = expirationTime;
state.changed = true;
state.changed = true;
end
if (state.duration ~= duration) then
state.duration = duration;
state.changed = true;
end
state.value = nil;
state.total = nil;
state.progressType = 'timed';
end
]=];
local trackedCharge = tonumber(trigger.trackcharge or 1) or 1;
ret = ret .. ret2:format(trackedCharge - 1);
end
if(trigger.use_remaining and trigger.genericShowOn ~= "showOnReady") then
local ret2 = [[
local remaining = 0;
if (expirationTime and expirationTime > 0) then
remaining = expirationTime - GetTime();
local remainingCheck = %s;
if(remaining >= remainingCheck and remaining > 0) then
WeakAuras.ScheduleScan(expirationTime - remainingCheck);
end
end
]];
ret = ret..ret2:format(tonumber(trigger.remaining or 0) or 0);
end
return ret;
end,
statesParameter = "one",
canHaveDuration = "timed",
args = {
{
}, -- Ignore first argument (id)
{
name = "spellName",
required = true,
display = L["Spell"],
type = "spell",
test = "true",
showExactOption = true,
},
{
name = "extra Cooldown Progress (Spell)",
display = function(trigger)
return function()
local text = "";
if trigger.track == "charges" then
text = L["Tracking Charge CDs"]
elseif trigger.track == "cooldown" then
text = L["Tracking Only Cooldown"]
end
if trigger.use_showgcd then
if text ~= "" then text = text .. "; " end
text = text .. L["Show GCD"]
end
if trigger.use_matchedRune then
if text ~= "" then text = text .. "; " end
text = text ..L["Ignore Rune CDs"]
end
if trigger.use_ignoreSpellKnown then
if text ~= "" then text = text .. "; " end
text = text .. L["Ignore Unknown Spell"]
end
if trigger.genericShowOn ~= "showOnReady" and trigger.track ~= "cooldown" then
if trigger.use_trackcharge and trigger.trackcharge then
if text ~= "" then text = text .. "; " end
text = text .. L["Tracking Charge %i"]:format(trigger.trackcharge)
end
end
if text == "" then
return L["|cFFffcc00Extra Options:|r None"]
end
return L["|cFFffcc00Extra Options:|r %s"]:format(text)
end
end,
type = "collapse",
},
{
name = "track",
display = L["Track Cooldowns"],
type = "select",
values = "cooldown_types",
collapse = "extra Cooldown Progress (Spell)",
test = "true",
required = true,
default = "auto"
},
{
name = "showgcd",
display = L["Show Global Cooldown"],
type = "toggle",
test = "true",
collapse = "extra Cooldown Progress (Spell)"
},
{
name = "matchedRune",
display = L["Ignore Rune CD"],
type = "toggle",
test = "true",
collapse = "extra Cooldown Progress (Spell)"
},
{
name = "ignoreSpellKnown",
display = L["Disable Spell Known Check"],
type = "toggle",
test = "true",
collapse = "extra Cooldown Progress (Spell)"
},
{
name = "trackcharge",
display = L["Show CD of Charge"],
type = "number",
enable = function(trigger)
return (trigger.genericShowOn ~= "showOnReady") and trigger.track ~= "cooldown"
end,
test = "true",
noOperator = true,
collapse = "extra Cooldown Progress (Spell)"
},
{
name = "remaining",
display = L["Remaining Time"],
type = "number",
enable = function(trigger) return (trigger.genericShowOn ~= "showOnReady") end
},
{
name = "charges",
display = L["Charges"],
type = "number",
store = true,
conditionType = "number"
},
{
name = "spellCount",
display = L["Spell Count"],
type = "number",
store = true,
conditionType = "number"
},
{
name = "stacks",
init = "stacks",
hidden = true,
test = "true",
store = true
},
{
hidden = true,
name = "maxCharges",
store = true,
display = L["Max Charges"],
conditionType = "number",
test = "true",
},
{
hidden = true,
name = "readyTime",
display = L["Since Ready"],
conditionType = "elapsedTimer",
store = true,
test = "true"
},
{
hidden = true,
name = "chargeGainTime",
display = L["Since Charge Gain"],
conditionType = "elapsedTimer",
store = true,
test = "true"
},
{
hidden = true,
name = "chargeLostTime",
display = L["Since Charge Lost"],
conditionType = "elapsedTimer",
store = true,
test = "true"
},
{
name = "genericShowOn",
display = L["Show"],
type = "select",
values = "cooldown_progress_behavior_types",
test = "true",
required = true,
default = "showOnCooldown"
},
{
hidden = true,
name = "onCooldown",
test = "true",
display = L["On Cooldown"],
conditionType = "bool",
conditionTest = function(state, needle)
return state and state.show and (not state.gcdCooldown and state.expirationTime and state.expirationTime > GetTime()) == (needle == 1)
end,
},
{
hidden = true,
name = "gcdCooldown",
store = true,
test = "true"
},
{
name = "spellUsable",
display = L["Spell Usable"],
hidden = true,
test = "true",
conditionType = "bool",
conditionTest = function(state, needle)
return state and state.show and (IsUsableSpell(state.spellname) == (needle == 1))
end,
conditionEvents = {
"SPELL_UPDATE_USABLE",
"PLAYER_TARGET_CHANGED",
"UNIT_POWER_FREQUENT",
},
},
{
name = "insufficientResources",
display = L["Insufficient Resources"],
hidden = true,
test = "true",
conditionType = "bool",
conditionTest = function(state, needle)
return state and state.show and (select(2, IsUsableSpell(state.spellname)) == (needle == 1));
end,
conditionEvents = {
"SPELL_UPDATE_USABLE",
"PLAYER_TARGET_CHANGED",
"UNIT_POWER_FREQUENT",
}
},
{
name = "spellInRange",
display = L["Spell in Range"],
hidden = true,
test = "true",
conditionType = "bool",
conditionTest = function(state, needle)
return state and state.show and (UnitExists('target') and state.spellname and WeakAuras.IsSpellInRange(state.spellname, 'target') == needle)
end,
conditionEvents = {
"PLAYER_TARGET_CHANGED",
"WA_SPELL_RANGECHECK",
}
},
{
hidden = true,
test = "genericShowOn"
}
},
nameFunc = function(trigger)
local name = GetSpellInfo(trigger.realSpellName or 0);
if(name) then
return name;
end
name = GetSpellInfo(trigger.spellName or 0);
if (name) then
return name;
end
return "Invalid";
end,
iconFunc = function(trigger)
local _, _, icon = GetSpellInfo(trigger.realSpellName or 0);
if (not icon) then
icon = select(3, GetSpellInfo(trigger.spellName or 0));
end
return icon;
end,
hasSpellID = true,
automaticrequired = true,
},
["Cooldown Ready (Spell)"] = {
type = "event",
events = {},
internal_events = {
"SPELL_COOLDOWN_READY",
},
name = L["Cooldown Ready (Spell)"],
loadFunc = function(trigger)
trigger.spellName = trigger.spellName or 0;
local spellName;
if (trigger.use_exact_spellName) then
spellName = trigger.spellName;
else
spellName = type(trigger.spellName) == "number" and GetSpellInfo(trigger.spellName) or trigger.spellName;
end
trigger.realSpellName = spellName; -- Cache
WeakAuras.WatchSpellCooldown(spellName);
end,
init = function(trigger)
trigger.spellName = trigger.spellName or 0;
local spellName;
if (trigger.use_exact_spellName) then
spellName = trigger.spellName;
else
spellName = type(trigger.spellName) == "number" and GetSpellInfo(trigger.spellName) or trigger.spellName;
end
if (type(spellName) == "string") then
spellName = "[[" .. spellName .. "]]";
end
local ret = [=[
local spellname = %s
]=]
return ret:format(spellName);
end,
args = {
{
name = "spellName",
required = true,
display = L["Spell"],
type = "spell",
init = "arg",
showExactOption = true,
test = "spellname == spellName"
}
},
nameFunc = function(trigger)
local name = GetSpellInfo(trigger.realSpellName or 0);
if(name) then
return name;
end
name = GetSpellInfo(trigger.spellName or 0);
if (name) then
return name;
end
return "Invalid";
end,
iconFunc = function(trigger)
local _, _, icon = GetSpellInfo(trigger.realSpellName or 0);
if (not icon) then
icon = select(3, GetSpellInfo(trigger.spellName or 0));
end
return icon;
end,
hasSpellID = true,
timedrequired = true
},
["Charges Changed (Spell)"] = {
type = "event",
events = {},
internal_events = {
"SPELL_CHARGES_CHANGED",
},
name = L["Charges Changed (Spell)"],
loadFunc = function(trigger)
trigger.spellName = trigger.spellName or 0;
local spellName;
if (trigger.use_exact_spellName) then
spellName = trigger.spellName;
else
spellName = type(trigger.spellName) == "number" and GetSpellInfo(trigger.spellName) or trigger.spellName;
end
trigger.realSpellName = spellName; -- Cache
WeakAuras.WatchSpellCooldown(spellName);
end,
init = function(trigger)
local spellName;
if (trigger.use_exact_spellName) then
spellName = trigger.spellName;
else
spellName = type(trigger.spellName) == "number" and GetSpellInfo(trigger.spellName) or trigger.spellName;
end
spellName = string.format("%q", spellName or "");
return string.format("local spell = %s;\n", spellName);
end,
statesParameter = "one",
args = {
{
name = "spellName",
required = true,
display = L["Spell"],
type = "spell",
init = "arg",
showExactOption = true,
test = "spell == spellName"
},
{
name = "direction",
required = true,
display = L["Charge gained/lost"],
type = "select",
values = "charges_change_type",
init = "arg",
test = "WeakAuras.CheckChargesDirection(direction, %q)",
store = true,
conditionType = "select",
conditionValues = "charges_change_condition_type";
conditionTest = function(state, needle)
return state and state.show and WeakAuras.CheckChargesDirection(state.direction, needle)
end,
},
{
name = "charges",
display = L["Charges"],
type = "number",
init = "arg",
store = true,
conditionType = "number"
}
},
nameFunc = function(trigger)
local name = GetSpellInfo(trigger.realSpellName or 0);
if(name) then
return name;
end
name = GetSpellInfo(trigger.spellName or 0);
if (name) then
return name;
end
return "Invalid";
end,
iconFunc = function(trigger)
local _, _, icon = GetSpellInfo(trigger.realSpellName or 0);
if (not icon) then
icon = select(3, GetSpellInfo(trigger.spellName or 0));
end
return icon;
end,
hasSpellID = true,
timedrequired = true
},
["Cooldown Progress (Item)"] = {
type = "status",
events = {},
internal_events = function(trigger, untrigger)
local events = {
"ITEM_COOLDOWN_READY",
"ITEM_COOLDOWN_CHANGED",
"ITEM_COOLDOWN_STARTED",
"COOLDOWN_REMAINING_CHECK",
}
if (trigger.use_showgcd) then
tinsert(events, "GCD_START");
tinsert(events, "GCD_CHANGE");
tinsert(events, "GCD_END");
end
return events
end,
force_events = "ITEM_COOLDOWN_FORCE",
name = L["Cooldown Progress (Item)"],
loadFunc = function(trigger)
trigger.itemName = trigger.itemName or 0;
local itemName = type(trigger.itemName) == "number" and trigger.itemName or "[["..trigger.itemName.."]]";
WeakAuras.WatchItemCooldown(trigger.itemName);
if (trigger.use_showgcd) then
WeakAuras.WatchGCD();
end
end,
init = function(trigger)
trigger.itemName = trigger.itemName or 0;
local itemName = type(trigger.itemName) == "number" and trigger.itemName or "[["..trigger.itemName.."]]";
local ret = [=[
local itemname = %s;
local showgcd = %s
local startTime, duration, enabled, gcdCooldown = WeakAuras.GetItemCooldown(itemname, showgcd);
local genericShowOn = %s
state.itemname = itemname;
]=];
if(trigger.use_remaining and trigger.genericShowOn ~= "showOnReady") then
local ret2 = [[
local expirationTime = startTime + duration
local remaining = expirationTime > 0 and (expirationTime - GetTime()) or 0;
local remainingCheck = %s;
if(remaining >= remainingCheck and remaining > 0) then
WeakAuras.ScheduleScan(expirationTime - remainingCheck);
end
]];
ret = ret..ret2:format(tonumber(trigger.remaining or 0) or 0);
end
return ret:format(itemName,
trigger.use_showgcd and "true" or "false",
"[[" .. (trigger.genericShowOn or "") .. "]]");
end,
statesParameter = "one",
args = {
{
name = "itemName",
required = true,
display = L["Item"],
type = "item",
test = "true"
},
{
name = "remaining",
display = L["Remaining Time"],
type = "number",
enable = function(trigger) return (trigger.genericShowOn ~= "showOnReady") end,
init = "remaining"
},
{
name = "extra Cooldown Progress (Item)",
display = function(trigger)
return function()
local text = "";
if trigger.use_showgcd then
if text ~= "" then text = text .. "; " end
text = text .. L["Show GCD"]
end
if text == "" then
return L["|cFFffcc00Extra Options:|r None"]
end
return L["|cFFffcc00Extra Options:|r %s"]:format(text)
end
end,
type = "collapse",
},
{
name = "showgcd",
display = L["Show Global Cooldown"],
type = "toggle",
test = "true",
collapse = "extra Cooldown Progress (Item)"
},
{
name = "genericShowOn",
display = L["Show"],
type = "select",
values = "cooldown_progress_behavior_types",
test = "true",
required = true,
default = "showOnCooldown"
},
{
hidden = true,
name = "enabled",
store = true,
test = "true",
},
{
hidden = true,
name = "onCooldown",
test = "true",
display = L["On Cooldown"],
conditionType = "bool",
conditionTest = function(state, needle)
return state and state.show and (not state.gcdCooldown and state.expirationTime and state.expirationTime > GetTime() or state.enabled == 0) == (needle == 1)
end,
},
{
name = "itemInRange",
display = L["Item in Range"],
hidden = true,
test = "true",
conditionType = "bool",
conditionTest = function(state, needle)
return state and state.show and (UnitExists('target') and IsItemInRange(state.itemname, 'target')) == (needle == 1)
end,
conditionEvents = {
"PLAYER_TARGET_CHANGED",
"WA_SPELL_RANGECHECK",
}
},
{
hidden = true,
name = "gcdCooldown",
store = true,
test = "true"
},
{
hidden = true,
test = "(genericShowOn == \"showOnReady\" and (startTime == 0 and enabled == 1 or gcdCooldown))" ..
"or (genericShowOn == \"showOnCooldown\" and (startTime > 0 or enabled == 0) and not gcdCooldown) " ..
"or (genericShowOn == \"showAlways\")"
}
},
durationFunc = function(trigger)
local startTime, duration = WeakAuras.GetItemCooldown(type(trigger.itemName) == "number" and trigger.itemName or 0, trigger.use_showgcd);
startTime = startTime or 0;
duration = duration or 0;
return duration, startTime + duration;
end,
nameFunc = function(trigger)
local name = GetItemInfo(trigger.itemName or 0);
if(name) then
return name;
else
return "Invalid";
end
end,
iconFunc = function(trigger)
local _, _, _, _, icon = GetItemInfoInstant(trigger.itemName or 0);
return icon;
end,
hasItemID = true,
automaticrequired = true,
automaticAutoHide = false
},
["Cooldown Progress (Equipment Slot)"] = {
type = "status",
events = {
["unit_events"] = {
["player"] = {"UNIT_INVENTORY_CHANGED"}
}
},
internal_events = function(trigger, untrigger)
local events = {
"ITEM_SLOT_COOLDOWN_STARTED",
"ITEM_SLOT_COOLDOWN_CHANGED",
"COOLDOWN_REMAINING_CHECK",
"ITEM_SLOT_COOLDOWN_ITEM_CHANGED",
"ITEM_SLOT_COOLDOWN_READY",
"WA_DELAYED_PLAYER_ENTERING_WORLD"
}
if (trigger.use_showgcd) then
tinsert(events, "GCD_START");
tinsert(events, "GCD_CHANGE");
tinsert(events, "GCD_END");
end
return events
end,
force_events = "ITEM_COOLDOWN_FORCE",
name = L["Cooldown Progress (Equipment Slot)"],
loadFunc = function(trigger)
WeakAuras.WatchItemSlotCooldown(trigger.itemSlot);
if (trigger.use_showgcd) then
WeakAuras.WatchGCD();
end
end,
init = function(trigger)
local ret = [[
local showgcd = %s
local startTime, duration, enable, gcdCooldown = WeakAuras.GetItemSlotCooldown(%s, showgcd);
local genericShowOn = %s
local remaining = startTime + duration - GetTime();
]];
if(trigger.use_remaining and trigger.genericShowOn ~= "showOnReady") then
local ret2 = [[
local expirationTime = startTime + duration
local remaining = expirationTime > 0 and (expirationTime - GetTime()) or 0;
local remainingCheck = %s;
if(remaining >= remainingCheck and remaining > 0) then
WeakAuras.ScheduleScan(expirationTime - remainingCheck);
end
]];
ret = ret..ret2:format(tonumber(trigger.remaining or 0) or 0);
end
return ret:format(trigger.use_showgcd and "true" or "false",
trigger.itemSlot or "0",
"[[" .. (trigger.genericShowOn or "") .. "]]");
end,
statesParameter = "one",
args = {
{
name = "itemSlot",
required = true,
display = L["Equipment Slot"],
type = "select",
values = "item_slot_types",
test = "true"
},
{
name = "extra Cooldown Progress (Equipment Slot)",
display = function(trigger)
return function()
local text = "";
if trigger.use_showgcd then
if text ~= "" then text = text .. "; " end
text = text .. L["Show GCD"]
end
if text == "" then
return L["|cFFffcc00Extra Options:|r None"]
end
return L["|cFFffcc00Extra Options:|r %s"]:format(text)
end
end,
type = "collapse",
},
{
name = "showgcd",
display = L["Show Global Cooldown"],
type = "toggle",
test = "true",
collapse = "extra Cooldown Progress (Equipment Slot)"
},
{
name = "remaining",
display = L["Remaining Time"],
type = "number",
enable = function(trigger) return (trigger.genericShowOn ~= "showOnReady") end,
init = "remaining"
},
{
name = "testForCooldown",
display = L["is useable"],
type = "toggle",
test = "enable == 1"
},
{
name = "genericShowOn",
display = L["Show"],
type = "select",
values = "cooldown_progress_behavior_types",
test = "true",
required = true,
default = "showOnCooldown"
},
{
hidden = true,
name = "onCooldown",
test = "true",
display = L["On Cooldown"],
conditionType = "bool",
conditionTest = function(state, needle)
return state and state.show and (not state.gcdCooldown and state.expirationTime and state.expirationTime > GetTime()) == (needle == 1);
end,
},
{
hidden = true,
name = "gcdCooldown",
store = true,
test = "true"
},
{
hidden = true,
test = "(genericShowOn == \"showOnReady\" and (startTime == 0 or gcdCooldown)) " ..
"or (genericShowOn == \"showOnCooldown\" and startTime > 0 and not gcdCooldown) " ..
"or (genericShowOn == \"showAlways\")"
}
},
durationFunc = function(trigger)
local startTime, duration = WeakAuras.GetItemSlotCooldown(trigger.itemSlot or 0, trigger.use_showgcd);
startTime = startTime or 0;
duration = duration or 0;
return duration, startTime + duration;
end,
nameFunc = function(trigger)
local item = GetInventoryItemID("player", trigger.itemSlot or 0);
if (item) then
return GetItemInfo(item);
end
end,
stacksFunc = function(trigger)
local count = GetInventoryItemCount("player", trigger.itemSlot or 0)
if ((count == 1) and (not GetInventoryItemTexture("player", trigger.itemSlot or 0))) then
count = 0
end
return count
end,
iconFunc = function(trigger)
return GetInventoryItemTexture("player", trigger.itemSlot or 0) or "Interface\\Icons\\INV_Misc_QuestionMark";
end,
automaticrequired = true,
},
["Cooldown Ready (Item)"] = {
type = "event",
events = {},
internal_events = {
"ITEM_COOLDOWN_READY",
},
name = L["Cooldown Ready (Item)"],
loadFunc = function(trigger)
trigger.itemName = trigger.itemName or 0;
WeakAuras.WatchItemCooldown(trigger.itemName);
end,
init = function(trigger)
trigger.itemName = trigger.itemName or 0;
end,
args = {
{
name = "itemName",
required = true,
display = L["Item"],
type = "item",
init = "arg"
}
},
nameFunc = function(trigger)
local name = GetItemInfo(trigger.itemName or 0);
if(name) then
return name;
else
return "Invalid";
end
end,
iconFunc = function(trigger)
local _, _, _, _, icon = GetItemInfoInstant(trigger.itemName or 0);
return icon;
end,
hasItemID = true,
timedrequired = true
},
["Cooldown Ready (Equipment Slot)"] = {
type = "event",
events = {},
internal_events = {
"ITEM_SLOT_COOLDOWN_READY"
},
name = L["Cooldown Ready (Equipment Slot)"],
loadFunc = function(trigger)
WeakAuras.WatchItemSlotCooldown(trigger.itemSlot);
end,
init = function(trigger)
end,
args = {
{
name = "itemSlot",
required = true,
display = L["Equipment Slot"],
type = "select",
values = "item_slot_types",
init = "arg"
}
},
nameFunc = function(trigger)
return "";
end,
iconFunc = function(trigger)
return GetInventoryItemTexture("player", trigger.itemSlot or 0) or "Interface\\Icons\\INV_Misc_QuestionMark";
end,
hasItemID = true,
timedrequired = true
},
["GTFO"] = {
type = "event",
events = {
["events"] = {"GTFO_DISPLAY"}
},
name = L["GTFO Alert"],
statesParameter = "one",
args = {
{
name = "alertType",
display = L["Alert Type"],
type = "select",
init = "arg",
values = "gtfo_types",
store = true,
conditionType = "select"
},
},
timedrequired = true
},
-- DBM events
["DBM Announce"] = {
type = "event",
events = {},
internal_events = {
"DBM_Announce"
},
name = L["DBM Announce"],
init = function(trigger)
WeakAuras.RegisterDBMCallback("DBM_Announce");
local ret = "local use_cloneId = %s;"
return ret:format(trigger.use_cloneId and "true" or "false");
end,
statesParameter = "all",
args = {
{
name = "message",
init = "arg",
display = L["Message"],
type = "longstring",
store = true,
conditionType = "string"
},
{
name = "name",
init = "message",
hidden = true,
test = "true",
store = true,
},
{
name = "icon",
init = "arg",
store = true,
hidden = true,
test = "true"
},
{
name = "cloneId",
display = L["Clone per Event"],
type = "toggle",
test = "true",
init = "use_cloneId and WeakAuras.GetUniqueCloneId() or ''"
},
},
timedrequired = true
},
["DBM Timer"] = {
type = "status",
events = {},
internal_events = {
"DBM_TimerStart", "DBM_TimerStop", "DBM_TimerStopAll", "DBM_TimerUpdate", "DBM_TimerForce"
},
force_events = "DBM_TimerForce",
name = L["DBM Timer"],
canHaveDuration = "timed",
triggerFunction = function(trigger)
WeakAuras.RegisterDBMCallback("DBM_TimerStart")
WeakAuras.RegisterDBMCallback("DBM_TimerStop")
WeakAuras.RegisterDBMCallback("DBM_TimerUpdate")
WeakAuras.RegisterDBMCallback("wipe")
WeakAuras.RegisterDBMCallback("kill")
local ret = [=[
return function (states, event, id)
local triggerId = %q
local triggerSpellId = %q
local triggerText = %q
local triggerTextOperator = %q
local useClone = %s
local extendTimer = %s
local triggerUseRemaining = %s
local triggerRemaining = %s
local triggerCount = %q
local triggerDbmType = %s
local cloneId = useClone and id or ""
local state = states[cloneId]
function copyOrSchedule(bar, cloneId)
if triggerUseRemaining then
local remainingTime = bar.expirationTime - GetTime() + extendTimer
if remainingTime %s triggerRemaining then
WeakAuras.CopyBarToState(bar, states, cloneId, extendTimer)
else
local state = states[cloneId]
if state and state.show then
state.show = false
state.changed = true
end
end
if remainingTime >= triggerRemaining then
WeakAuras.ScheduleDbmCheck(bar.expirationTime - triggerRemaining + extendTimer)
end
else
WeakAuras.CopyBarToState(bar, states, cloneId, extendTimer)
end
end
if useClone then
if event == "DBM_TimerStart" then
if WeakAuras.DBMTimerMatches(id, triggerId, triggerText, triggerTextOperator, triggerSpellId, triggerDbmType, triggerCount) then
local bar = WeakAuras.GetDBMTimerById(id)
if bar then
copyOrSchedule(bar, cloneId)
end
end
elseif event == "DBM_TimerStop" and state then
local bar_remainingTime = GetTime() - state.expirationTime + (state.extend or 0)
if state.extend == 0 or bar_remainingTime > 0.2 then
state.show = false
state.changed = true
end
elseif event == "DBM_TimerUpdate" then
for id, bar in pairs(WeakAuras.GetAllDBMTimers()) do
if WeakAuras.DBMTimerMatches(id, triggerId, triggerText, triggerTextOperator, triggerSpellId, triggerDbmType, triggerCount) then
copyOrSchedule(bar, id)
else
local state = states[id]
if state then
local bar_remainingTime = GetTime() - state.expirationTime + (state.extend or 0)
if state.extend == 0 or bar_remainingTime > 0.2 then
state.show = false
state.changed = true
end
end
end
end
elseif event == "DBM_TimerForce" then
wipe(states)
for id, bar in pairs(WeakAuras.GetAllDBMTimers()) do
if WeakAuras.DBMTimerMatches(id, triggerId, triggerText, triggerTextOperator, triggerSpellId, triggerDbmType, triggerCount) then
copyOrSchedule(bar, cloneId)
end
end
end
else
if event == "DBM_TimerStart" or event == "DBM_TimerUpdate" then
if extendTimer ~= 0 then
if WeakAuras.DBMTimerMatches(id, triggerId, triggerText, triggerTextOperator, triggerSpellId, triggerDbmType, triggerCount) then
local bar = WeakAuras.GetDBMTimerById(id)
WeakAuras.ScheduleDbmCheck(bar.expirationTime + extendTimer)
end
end
end
local bar = WeakAuras.GetDBMTimer(triggerId, triggerText, triggerTextOperator, triggerSpellId, extendTimer, triggerDbmType, triggerCount)
if bar then
if extendTimer == 0
or not (state and state.show)
or (state and state.show and state.expirationTime > (bar.expirationTime + extendTimer))
then
copyOrSchedule(bar, cloneId)
end
else
if state and state.show then
local bar_remainingTime = GetTime() - state.expirationTime + (state.extend or 0)
if state.extend == 0 or bar_remainingTime > 0.2 then
state.show = false
state.changed = true
end
end
end
end
return true
end
]=]
return ret:format(
trigger.use_id and trigger.id or "",
trigger.use_spellId and trigger.spellId or "",
trigger.use_message and trigger.message or "",
trigger.use_message and trigger.message_operator or "",
trigger.use_cloneId and "true" or "false",
trigger.use_extend and tonumber(trigger.extend or 0) or 0,
trigger.use_remaining and "true" or "false",
trigger.remaining or 0,
trigger.use_count and trigger.count or "",
trigger.use_dbmType and trigger.dbmType or "nil",
trigger.remaining_operator or "<"
)
end,
statesParameter = "full",
args = {
{
name = "id",
display = L["Timer Id"],
type = "string",
},
{
name = "spellId",
display = L["Spell Id"],
type = "string",
store = true,
conditionType = "string"
},
{
name = "message",
display = L["Message"],
type = "longstring",
store = true,
conditionType = "string"
},
{
name = "remaining",
display = L["Remaining Time"],
type = "number",
},
{
name = "extend",
display = L["Offset Timer"],
type = "string",
},
{
name = "count",
display = L["Count"],
desc = L["Only if DBM shows it on it's bar"],
type = "string",
conditionType = "string",
},
{
name = "dbmType",
display = L["Type"],
type = "select",
values = "dbm_types",
conditionType = "select",
test = "true"
},
{
name = "cloneId",
display = L["Clone per Event"],
type = "toggle"
}
},
automaticrequired = true,
automaticAutoHide = false
},
-- BigWigs
["BigWigs Message"] = {
type = "event",
events = {},
internal_events = {
"BigWigs_Message"
},
name = L["BigWigs Message"],
init = function(trigger)
WeakAuras.RegisterBigWigsCallback("BigWigs_Message");
local ret = "local use_cloneId = %s;"
return ret:format(trigger.use_cloneId and "true" or "false");
end,
statesParameter = "all",
args = {
{
name = "addon",
init = "arg",
display = L["BigWigs Addon"],
type = "string"
},
{
name = "spellId",
init = "arg",
display = L["Spell Id"],
type = "longstring"
},
{
name = "text",
init = "arg",
display = L["Message"],
type = "longstring",
store = true,
conditionType = "string"
},
{
name = "name",
init = "text",
hidden = true,
test = "true",
store = true
},
{}, -- Importance, might be useful
{
name = "icon",
init = "arg",
hidden = true,
test = "true",
store = true
},
{
name = "cloneId",
display = L["Clone per Event"],
type = "toggle",
test = "true",
init = "use_cloneId and WeakAuras.GetUniqueCloneId() or ''"
},
},
timedrequired = true
},
["BigWigs Timer"] = {
type = "status",
events = {},
internal_events = {
"BigWigs_StartBar", "BigWigs_StopBar", "BigWigs_Timer_Update",
},
force_events = "BigWigs_Timer_Force",
name = L["BigWigs Timer"],
canHaveDuration = "timed",
triggerFunction = function(trigger)
WeakAuras.RegisterBigWigsTimer()
local ret = [=[
return function(states, event, id)
local triggerSpellId = %q
local triggerText = %q
local triggerTextOperator = %q
local useClone = %s
local extendTimer = %s
local triggerUseRemaining = %s
local triggerRemaining = %s
local triggerCount = %q
local triggerCast = %s
local cloneId = useClone and id or ""
local state = states[cloneId]
function copyOrSchedule(bar, cloneId)
if triggerUseRemaining then
local remainingTime = bar.expirationTime - GetTime() + extendTimer
if remainingTime %s triggerRemaining then
WeakAuras.CopyBigWigsTimerToState(bar, states, cloneId, extendTimer)
else
local state = states[cloneId]
if state and state.show then
state.show = false
state.changed = true
end
end
if remainingTime >= triggerRemaining then
WeakAuras.ScheduleBigWigsCheck(bar.expirationTime - triggerRemaining + extendTimer)
end
else
WeakAuras.CopyBigWigsTimerToState(bar, states, cloneId, extendTimer)
end
end
if useClone then
if event == "BigWigs_StartBar" then
if WeakAuras.BigWigsTimerMatches(id, triggerText, triggerTextOperator, triggerSpellId, triggerCount, triggerCast) then
local bar = WeakAuras.GetBigWigsTimerById(id)
if bar then
copyOrSchedule(bar, cloneId)
end
end
elseif event == "BigWigs_StopBar" and state then
local bar_remainingTime = GetTime() - state.expirationTime + (state.extend or 0)
if state.extend == 0 or bar_remainingTime > 0.2 then
state.show = false
state.changed = true
end
elseif event == "BigWigs_Timer_Update" then
for id, bar in pairs(WeakAuras.GetAllBigWigsTimers()) do
if WeakAuras.BigWigsTimerMatches(id, triggerText, triggerTextOperator, triggerSpellId, triggerCount, triggerCast) then
copyOrSchedule(bar, id)
end
end
elseif event == "BigWigs_Timer_Force" then
wipe(states)
for id, bar in pairs(WeakAuras.GetAllBigWigsTimers()) do
if WeakAuras.BigWigsTimerMatches(id, triggerText, triggerTextOperator, triggerSpellId, triggerCount, triggerCast) then
copyOrSchedule(bar, id)
end
end
end
else
if event == "BigWigs_StartBar" then
if extendTimer ~= 0 then
if WeakAuras.BigWigsTimerMatches(id, triggerText, triggerTextOperator, triggerSpellId, triggerCount, triggerCast) then
local bar = WeakAuras.GetBigWigsTimerById(id)
WeakAuras.ScheduleBigWigsCheck(bar.expirationTime + extendTimer)
end
end
end
local bar = WeakAuras.GetBigWigsTimer(triggerText, triggerTextOperator, triggerSpellId, extendTimer, triggerCount, triggerCast)
if bar then
if extendTimer == 0
or not (state and state.show)
or (state and state.show and state.expirationTime > (bar.expirationTime + extendTimer))
then
copyOrSchedule(bar, cloneId)
end
else
if state and state.show then
local bar_remainingTime = GetTime() - state.expirationTime + (state.extend or 0)
if state.extend == 0 or bar_remainingTime > 0.2 then
state.show = false
state.changed = true
end
end
end
end
return true
end
]=]
return ret:format(
trigger.use_spellId and trigger.spellId or "",
trigger.use_text and trigger.text or "",
trigger.use_text and trigger.text_operator or "",
trigger.use_cloneId and "true" or "false",
trigger.use_extend and tonumber(trigger.extend or 0) or 0,
trigger.use_remaining and "true" or "false",
trigger.remaining or 0,
trigger.use_count and trigger.count or "",
trigger.use_cast == nil and "nil" or trigger.use_cast and "true" or "false",
trigger.remaining_operator or "<"
)
end,
statesParameter = "full",
args = {
{
name = "spellId",
display = L["Spell Id"],
type = "string",
conditionType = "string",
},
{
name = "text",
display = L["Message"],
type = "longstring",
store = true,
conditionType = "string"
},
{
name = "remaining",
display = L["Remaining Time"],
type = "number",
},
{
name = "extend",
display = L["Offset Timer"],
type = "string",
},
{
name = "count",
display = L["Count"],
desc = L["Only if BigWigs shows it on it's bar"],
type = "string",
conditionType = "string",
},
{
name = "cast",
display = L["Cast Bar"],
desc = L["Filter messages with format <message>"],
type = "tristate",
test = "true",
init = "false",
conditionType = "bool"
},
{
name = "cloneId",
display = L["Clone per Event"],
type = "toggle",
test = "true",
init = "false"
},
},
automaticrequired = true,
},
["Global Cooldown"] = {
type = "status",
events = {},
internal_events = {
"GCD_START",
"GCD_CHANGE",
"GCD_END",
"GCD_UPDATE",
"WA_DELAYED_PLAYER_ENTERING_WORLD"
},
force_events = "GCD_UPDATE",
name = L["Global Cooldown"],
loadFunc = function(trigger)
WeakAuras.WatchGCD();
end,
init = function(trigger)
local ret = [[
local inverse = %s;
local onGCD = WeakAuras.GetGCDInfo();
local hasSpellName = WeakAuras.GcdSpellName();
]];
return ret:format(trigger.use_inverse and "true" or "false");
end,
args = {
{
name = "inverse",
display = L["Inverse"],
type = "toggle",
test = "true"
},
{
hidden = true,
test = "(inverse and onGCD == 0) or (not inverse and onGCD > 0 and hasSpellName)"
}
},
durationFunc = function(trigger)
local duration, expirationTime = WeakAuras.GetGCDInfo();
return duration, expirationTime;
end,
nameFunc = function(trigger)
local _, _, name = WeakAuras.GetGCDInfo();
return name;
end,
iconFunc = function(trigger)
local _, _, _, icon = WeakAuras.GetGCDInfo();
return icon;
end,
hasSpellID = true,
automaticrequired = true,
automaticAutoHide = false
},
["Swing Timer"] = {
type = "status",
events = {},
internal_events = {
"SWING_TIMER_START",
"SWING_TIMER_CHANGE",
"SWING_TIMER_END",
"SWING_TIMER_UPDATE"
},
force_events = "SWING_TIMER_UPDATE",
name = L["Swing Timer"],
loadFunc = function()
WeakAuras.InitSwingTimer();
end,
init = function(trigger)
local ret = [=[
local inverse = %s;
local hand = %q;
local triggerRemaining = %s
local duration, expirationTime, name, icon = WeakAuras.GetSwingTimerInfo(hand)
local remaining = expirationTime and expirationTime - GetTime()
local remainingCheck = not triggerRemaining or remaining and remaining %s triggerRemaining
if triggerRemaining and remaining and remaining >= triggerRemaining and remaining > 0 then
WeakAuras.ScheduleScan(expirationTime - triggerRemaining, "SWING_TIMER_UPDATE")
end
]=];
return ret:format(
(trigger.use_inverse and "true" or "false"),
trigger.hand or "main",
trigger.use_remaining and tonumber(trigger.remaining or 0) or "nil",
trigger.remaining_operator or "<"
);
end,
args = {
{
name = "hand",
required = true,
display = L["Weapon"],
type = "select",
values = "swing_types",
test = "true"
},
{
name = "duration",
hidden = true,
init = "duration",
test = "true",
store = true
},
{
name = "expirationTime",
init = "expirationTime",
hidden = true,
test = "true",
store = true
},
{
name = "progressType",
hidden = true,
init = "'timed'",
test = "true",
store = true
},
{
name = "name",
hidden = true,
init = "spell",
test = "true",
store = true
},
{
name = "icon",
hidden = true,
init = "icon or 'Interface\\AddOns\\WeakAuras\\Media\\Textures\\icon'",
test = "true",
store = true
},
{
name = "remaining",
display = L["Remaining Time"],
type = "number",
enable = function(trigger) return not trigger.use_inverse end,
test = "true"
},
{
name = "inverse",
display = L["Inverse"],
type = "toggle",
test = "true"
},
{
hidden = true,
test = "(inverse and duration == 0) or (not inverse and duration > 0)"
}
},
automaticrequired = true,
canHaveDuration = true,
statesParameter = "one"
},
["Action Usable"] = {
type = "status",
events = {
["events"] = {
"SPELL_UPDATE_USABLE",
"PLAYER_TARGET_CHANGED",
"RUNE_POWER_UPDATE",
},
["unit_events"] = {
["player"] = { "UNIT_POWER_FREQUENT" }
}
},
internal_events = {
"SPELL_COOLDOWN_CHANGED",
},
force_events = "SPELL_UPDATE_USABLE",
name = L["Action Usable"],
statesParameter = "one",
loadFunc = function(trigger)
trigger.spellName = trigger.spellName or 0;
local spellName;
if (trigger.use_exact_spellName) then
spellName = trigger.spellName;
else
spellName = type(trigger.spellName) == "number" and GetSpellInfo(trigger.spellName) or trigger.spellName;
end
trigger.realSpellName = spellName; -- Cache
WeakAuras.WatchSpellCooldown(spellName);
end,
init = function(trigger)
trigger.spellName = trigger.spellName or 0;
local spellName;
if (trigger.use_exact_spellName) then
spellName = trigger.spellName;
else
spellName = type(trigger.spellName) == "number" and GetSpellInfo(trigger.spellName) or trigger.spellName;
end
trigger.realSpellName = spellName; -- Cache
local ret = [=[
local spellName = %s
local startTime, duration, _, readyTime = WeakAuras.GetSpellCooldown(spellName);
local charges, _, spellCount, chargeGainTime, chargeLostTime = WeakAuras.GetSpellCharges(spellName);
if (charges == nil) then
charges = (duration == 0) and 1 or 0;
end
local ready = startTime == 0 or charges > 0
local active = IsUsableSpell(spellName) and ready
]=]
if(trigger.use_targetRequired) then
ret = ret.."active = active and WeakAuras.IsSpellInRange(spellName or '', 'target')\n";
end
if(trigger.use_inverse) then
ret = ret.."active = not active\n";
end
if (type(spellName) == "string") then
spellName = "[[" .. spellName .. "]]";
end
return ret:format(spellName)
end,
args = {
{
name = "spellName",
display = L["Spell"],
required = true,
type = "spell",
test = "true",
showExactOption = true,
store = true
},
-- This parameter uses the IsSpellInRange API function, but it does not check spell range at all
-- IsSpellInRange returns nil for invalid targets, 0 for out of range, 1 for in range (0 and 1 are both "positive" values)
{
name = "targetRequired",
display = L["Require Valid Target"],
type = "toggle",
test = "true"
},
{
name = "charges",
display = L["Charges"],
type = "number",
enable = function(trigger) return not(trigger.use_inverse) end,
store = true,
conditionType = "number"
},
{
name = "spellCount",
display = L["Spell Count"],
type = "number",
enable = function(trigger) return not(trigger.use_inverse) end,
store = true,
conditionType = "number"
},
{
hidden = true,
name = "readyTime",
display = L["Since Ready"],
conditionType = "elapsedTimer",
store = true,
test = "true"
},
{
hidden = true,
name = "chargeGainTime",
display = L["Since Charge Gain"],
conditionType = "elapsedTimer",
store = true,
test = "true"
},
{
hidden = true,
name = "chargeLostTime",
display = L["Since Charge Lost"],
conditionType = "elapsedTimer",
store = true,
test = "true"
},
{
name = "inverse",
display = L["Inverse"],
type = "toggle",
test = "true",
reloadOptions = true
},
{
name = "spellInRange",
display = L["Spell in Range"],
hidden = true,
test = "true",
conditionType = "bool",
conditionTest = function(state, needle)
return state and state.show and (UnitExists('target') and state.spellName and WeakAuras.IsSpellInRange(state.spellName, 'target') == needle)
end,
conditionEvents = {
"PLAYER_TARGET_CHANGED",
"WA_SPELL_RANGECHECK",
}
},
{
hidden = true,
test = "active"
}
},
nameFunc = function(trigger)
local name = GetSpellInfo(trigger.realSpellName or 0);
if(name) then
return name;
end
name = GetSpellInfo(trigger.spellName or 0);
if (name) then
return name;
end
return "Invalid";
end,
iconFunc = function(trigger)
local _, _, icon = GetSpellInfo(trigger.realSpellName or 0);
if (not icon) then
icon = select(3, GetSpellInfo(trigger.spellName or 0));
end
return icon;
end,
stacksFunc = function(trigger)
local charges, maxCharges, spellCount = WeakAuras.GetSpellCharges(trigger.realSpellName);
if maxCharges and maxCharges > 1 then
return charges
elseif spellCount and spellCount > 0 then
return spellCount
end
end,
hasSpellID = true,
automaticrequired = true
},
["Talent Known"] = {
type = "status",
events = function()
local events
if WeakAuras.IsClassic() then
events = {
"CHARACTER_POINTS_CHANGED",
"SPELLS_CHANGED"
}
else
events = { "PLAYER_TALENT_UPDATE" }
end
return {
["events"] = events
}
end,
force_events = WeakAuras.IsClassic() and "CHARACTER_POINTS_CHANGED" or "PLAYER_TALENT_UPDATE",
name = L["Talent Selected"],
init = function(trigger)
local inverse = trigger.use_inverse;
if (trigger.use_talent) then
-- Single selection
local index = trigger.talent and trigger.talent.single;
local tier, column
if WeakAuras.IsClassic() then
tier = index and ceil(index / 20)
column = index and ((index - 1) % 20 + 1)
else
tier = index and ceil(index / 3)
column = index and ((index - 1) % 3 + 1)
end
local ret = [[
local tier = %s;
local column = %s;
local active, _, activeName, activeIcon, selected, known, rank
if WeakAuras.IsClassic() then
_, _, _, _, rank = GetTalentInfo(tier, column)
active = rank > 0
else
_, activeName, activeIcon, selected, _, _, _, _, _, _, known = GetTalentInfo(tier, column, 1)
active = selected or known;
end
]]
if (inverse) then
ret = ret .. [[
active = not (active);
]]
end
return ret:format(tier or 0, column or 0)
elseif (trigger.use_talent == false) then
if (trigger.talent.multi) then
local ret = [[
local tier
local column
local active = false;
local activeIcon;
local activeName;
]]
for index in pairs(trigger.talent.multi) do
local tier, column
if WeakAuras.IsClassic() then
tier = index and ceil(index / 20)
column = index and ((index - 1) % 20 + 1)
else
tier = index and ceil(index / 3)
column = index and ((index - 1) % 3 + 1)
end
local ret2 = [[
if (not active) then
tier = %s
column = %s
if WeakAuras.IsClassic() then
local name, icon, _, _, rank = GetTalentInfo(tier, column)
if rank > 0 then
active = true;
activeName = name;
activeIcon = icon;
end
else
local _, name, icon, selected, _, _, _, _, _, _, known = GetTalentInfo(tier, column, 1)
if (selected or known) then
active = true;
activeName = name;
activeIcon = icon;
end
end
end
]]
ret = ret .. ret2:format(tier, column);
end
if (inverse) then
ret = ret .. [[
active = not (active);
]]
end
return ret;
end
end
return "";
end,
args = {
{
name = "talent",
display = L["Talent selected"],
type = "multiselect",
values = function()
local class = select(2, UnitClass("player"));
local spec = not WeakAuras.IsClassic() and GetSpecialization();
if(Private.talent_types_specific[class] and Private.talent_types_specific[class][spec]) then
return Private.talent_types_specific[class][spec];
elseif WeakAuras.IsClassic() and Private.talent_types_specific[class] then
return Private.talent_types_specific[class];
else
return Private.talent_types;
end
end,
test = "active",
},
{
name = "inverse",
display = L["Inverse"],
type = "toggle",
test = "true"
},
{
hidden = true,
name = "icon",
init = "activeIcon",
store = "true",
test = "true"
},
{
hidden = true,
name = "name",
init = "activeName",
store = "true",
test = "true"
},
},
automaticrequired = true,
statesParameter = "one",
},
["PvP Talent Selected"] = {
type = "status",
events = function()
return {
["events"] = { "PLAYER_PVP_TALENT_UPDATE" }
}
end,
force_events = "PLAYER_PVP_TALENT_UPDATE",
name = L["PvP Talent Selected"],
init = function(trigger)
local inverse = trigger.use_inverse;
if (trigger.use_talent) then
-- Single selection
local index = trigger.talent and trigger.talent.single;
local ret = [[
local index = %s
local activeName, activeIcon, _
local active, talentId = WeakAuras.CheckPvpTalentByIndex(index)
if talentId then
_, activeName, activeIcon = GetPvpTalentInfoByID(talentId)
end
]]
if (inverse) then
ret = ret .. [[
active = not (active);
]]
end
return ret:format(index or 0)
elseif (trigger.use_talent == false) then
if (trigger.talent.multi) then
local ret = [[
local active = false;
local activeIcon;
local activeName
local talentId
local _
]]
for index in pairs(trigger.talent.multi) do
local ret2 = [[
if (not active) then
local index = %s
active, talentId = WeakAuras.CheckPvpTalentByIndex(index)
if active and talentId then
_, activeName, activeIcon = GetPvpTalentInfoByID(talentId)
end
end
]]
ret = ret .. ret2:format(index)
end
if (inverse) then
ret = ret .. [[
active = not (active);
]]
end
return ret;
end
end
return "";
end,
args = {
{
name = "talent",
display = L["Talent selected"],
type = "multiselect",
values = function()
local class = select(2, UnitClass("player"));
local spec = GetSpecialization();
if(Private.pvp_talent_types_specific[class] and Private.pvp_talent_types_specific[class][spec]) then
return Private.pvp_talent_types_specific[class][spec];
else
return Private.pvp_talent_types;
end
end,
test = "active",
},
{
name = "inverse",
display = L["Inverse"],
type = "toggle",
test = "true"
},
{
hidden = true,
name = "icon",
init = "activeIcon",
store = "true",
test = "true"
},
{
hidden = true,
name = "name",
init = "activeName",
store = "true",
test = "true"
},
},
automaticrequired = true,
statesParameter = "one",
},
["Class/Spec"] = {
type = "status",
events = function()
local events = { "PLAYER_TALENT_UPDATE" }
return {
["events"] = events
}
end,
force_events = "PLAYER_TALENT_UPDATE",
name = L["Class and Specialization"],
init = function(trigger)
return [[
local specId, specName, _, specIcon = GetSpecializationInfo(GetSpecialization())
]]
end,
args = {
{
name = "specId",
display = L["Class and Specialization"],
type = "multiselect",
values = "spec_types_all",
},
{
hidden = true,
name = "icon",
init = "specIcon",
store = "true",
test = "true"
},
{
hidden = true,
name = "name",
init = "specName",
store = "true",
test = "true"
},
},
automaticrequired = true,
statesParameter = "one",
},
["Totem"] = {
type = "status",
events = {
["events"] = {
"PLAYER_TOTEM_UPDATE",
"PLAYER_ENTERING_WORLD"
}
},
internal_events = {
"COOLDOWN_REMAINING_CHECK",
},
force_events = "PLAYER_ENTERING_WORLD",
name = L["Totem"],
statesParameter = "full",
canHaveDuration = "timed",
triggerFunction = function(trigger)
local ret = [[return
function (states)
local totemType = %s;
local triggerTotemName = %q
local triggerTotemPattern = %q
local triggerTotemPatternOperator = %q
local clone = %s
local inverse = %s
local remainingCheck = %s
local function checkActive(remaining)
return remaining %s remainingCheck;
end
if (totemType) then -- Check a specific totem slot
local _, totemName, startTime, duration, icon = GetTotemInfo(totemType);
active = (startTime and startTime ~= 0);
if not WeakAuras.CheckTotemName(totemName, triggerTotemName, triggerTotemPattern, triggerTotemPatternOperator) then
active = false;
end
if (inverse) then
active = not active;
if (triggerTotemName) then
icon = select(3, GetSpellInfo(triggerTotemName));
end
elseif (active and remainingCheck) then
local expirationTime = startTime and (startTime + duration) or 0;
local remainingTime = expirationTime - GetTime()
if (remainingTime >= remainingCheck) then
WeakAuras.ScheduleScan(expirationTime - remainingCheck);
end
active = checkActive(remainingTime);
end
states[""] = states[""] or {}
local state = states[""];
state.show = active;
state.changed = true;
if (active) then
state.name = totemName;
state.totemName = totemName;
state.progressType = "timed";
state.duration = duration;
state.expirationTime = startTime and (startTime + duration);
state.icon = icon;
end
elseif inverse then -- inverse without a specific slot
local found = false;
for i = 1, 5 do
local _, totemName, startTime, duration, icon = GetTotemInfo(i);
if ((startTime and startTime ~= 0) and
WeakAuras.CheckTotemName(totemName, triggerTotemName, triggerTotemPattern, triggerTotemPatternOperator)
) then
found = true;
end
end
local cloneId = "";
states[cloneId] = states[cloneId] or {};
local state = states[cloneId];
state.show = not found;
state.changed = true;
state.name = triggerTotemName;
state.totemName = triggerTotemName;
if (triggerTotemName) then
state.icon = select(3, GetSpellInfo(triggerTotemName));
end
else -- check all slots
for i = 1, 5 do
local _, totemName, startTime, duration, icon = GetTotemInfo(i);
active = (startTime and startTime ~= 0);
if not WeakAuras.CheckTotemName(totemName, triggerTotemName, triggerTotemPattern, triggerTotemPatternOperator) then
active = false;
end
if (active and remainingCheck) then
local expirationTime = startTime and (startTime + duration) or 0;
local remainingTime = expirationTime - GetTime()
if (remainingTime >= remainingCheck) then
WeakAuras.ScheduleScan(expirationTime - remainingCheck);
end
active = checkActive(remainingTime);
end
local cloneId = clone and tostring(i) or "";
states[cloneId] = states[cloneId] or {};
local state = states[cloneId];
state.show = active;
state.changed = true;
if (active) then
state.name = totemName;
state.totemName = totemName;
state.progressType = "timed";
state.duration = duration;
state.expirationTime = startTime and (startTime + duration);
state.icon = icon;
end
if (active and not clone) then
break;
end
end
end
return true;
end
]];
local totemName = tonumber(trigger.totemName) and GetSpellInfo(tonumber(trigger.totemName)) or trigger.totemName;
ret = ret:format(trigger.use_totemType and tonumber(trigger.totemType) or "nil",
trigger.use_totemName and totemName or "",
trigger.use_totemNamePattern and trigger.totemNamePattern or "",
trigger.use_totemNamePattern and trigger.totemNamePattern_operator or "",
trigger.use_clones and "true" or "false",
trigger.use_inverse and "true" or "false",
trigger.use_remaining and trigger.remaining or "nil",
trigger.use_remaining and trigger.remaining_operator or "<");
return ret;
end,
args = {
{
name = "totemType",
display = L["Totem Number"],
type = "select",
values = "totem_types"
},
{
name = "totemName",
display = L["Totem Name"],
type = "string",
conditionType = "string",
store = true
},
{
name = "totemNamePattern",
display = L["Totem Name Pattern Match"],
type = "longstring",
},
{
name = "clones",
display = L["Clone per Match"],
type = "toggle",
test = "true",
enable = function(trigger) return not trigger.use_totemType end,
},
{
name = "remaining",
display = L["Remaining Time"],
type = "number",
enable = function(trigger) return not(trigger.use_inverse) end
},
{
name = "inverse",
display = L["Inverse"],
type = "toggle",
test = "true",
enable = function(trigger) return (trigger.use_totemName or trigger.use_totemNamePattern) and not trigger.use_clones end
}
},
automaticrequired = true
},
["Item Count"] = {
type = "status",
events = {
["events"] = {
"BAG_UPDATE",
"BAG_UPDATE_COOLDOWN",
"PLAYER_ENTERING_WORLD"
}
},
internal_events = {
"ITEM_COUNT_UPDATE",
},
force_events = "BAG_UPDATE",
name = L["Item Count"],
loadFunc = function(trigger)
if(trigger.use_includeCharges) then
WeakAuras.RegisterItemCountWatch();
end
end,
init = function(trigger)
trigger.itemName = trigger.itemName or 0;
local itemName = type(trigger.itemName) == "number" and trigger.itemName or "[["..trigger.itemName.."]]";
local ret = [[
local count = GetItemCount(%s, %s, %s);
]];
return ret:format(itemName, trigger.use_includeBank and "true" or "nil", trigger.use_includeCharges and "true" or "nil");
end,
args = {
{
name = "itemName",
required = true,
display = L["Item"],
type = "item",
test = "true"
},
{
name = "includeBank",
display = L["Include Bank"],
type = "toggle",
test = "true"
},
{
name = "includeCharges",
display = L["Include Charges"],
type = "toggle",
test = "true"
},
{
name = "count",
display = L["Item Count"],
type = "number"
}
},
durationFunc = function(trigger)
local count = GetItemCount(trigger.itemName, trigger.use_includeBank, trigger.use_includeCharges);
return count, 0, true;
end,
stacksFunc = function(trigger)
local count = GetItemCount(trigger.itemName, trigger.use_includeBank, trigger.use_includeCharges);
return count, 0, true;
end,
nameFunc = function(trigger)
return C_Item.GetItemNameByID(trigger.itemName) or trigger.itemName;
end,
iconFunc = function(trigger)
return GetItemIcon(trigger.itemName);
end,
hasItemID = true,
automaticrequired = true
},
["Stance/Form/Aura"] = {
type = "status",
events = {
["events"] = {
"UPDATE_SHAPESHIFT_FORM",
"UPDATE_SHAPESHIFT_COOLDOWN"
}
},
internal_events = { "WA_DELAYED_PLAYER_ENTERING_WORLD" },
force_events = "WA_DELAYED_PLAYER_ENTERING_WORLD",
name = L["Stance/Form/Aura"],
init = function(trigger)
local inverse = trigger.use_inverse;
local ret = [[
local form = GetShapeshiftForm()
local active = false
]]
if trigger.use_form and trigger.form and trigger.form.single then
-- Single selection
ret = ret .. [[
local trigger_form = %d
active = form == trigger_form
]]
if inverse then
ret = ret .. [[
active = not active
]]
end
return ret:format(trigger.form.single)
elseif trigger.use_form == false and trigger.form and trigger.form.multi then
for index in pairs(trigger.form.multi) do
local ret2 = [[
if not active then
local index = %d
active = form == index
end
]]
ret = ret .. ret2:format(index)
end
if inverse then
ret = ret .. [[
active = not active
]]
end
return ret
elseif trigger.use_form == nil then
ret = ret .. [[
active = true
]]
return ret
end
end,
statesParameter = "one",
args = {
{
name = "form",
display = L["Form"],
type = "multiselect",
values = "form_types",
test = "active",
store = true,
conditionType = "select"
},
{
name = "inverse",
display = L["Inverse"],
type = "toggle",
test = "true",
enable = function(trigger) return type(trigger.use_form) == "boolean" end
},
},
nameFunc = function(trigger)
local _, class = UnitClass("player");
local name
if(class == trigger.class) then
local form = GetShapeshiftForm();
if form > 0 then
local _, name = GetShapeshiftFormInfo(form);
else
name = "Humanoid";
end
return name;
else
local types = WeakAuras[class:lower().."_form_types"];
if(types) then
return types[GetShapeshiftForm()];
end
end
end,
iconFunc = function(trigger)
local icon = "136116"
local form = GetShapeshiftForm()
if form and form > 0 then
icon = GetShapeshiftFormInfo(form);
end
return icon or "136116"
end,
automaticrequired = true
},
["Weapon Enchant"] = {
type = "status",
events = {},
internal_events = {
"TENCH_UPDATE",
},
force_events = "TENCH_UPDATE",
name = WeakAuras.IsClassic() and L["Weapon Enchant"] or L["Weapon Enchant / Fishing Lure"],
init = function(trigger)
WeakAuras.TenchInit();
local ret = [[
local triggerWeaponType = %q
local triggerName = %q
local triggerStack = %s
local triggerRemaining = %s
local triggerShowOn = %q
local _, expirationTime, duration, name, icon, stacks, enchantID
if triggerWeaponType == "main" then
expirationTime, duration, name, shortenedName, icon, stacks, enchantID = WeakAuras.GetMHTenchInfo()
else
expirationTime, duration, name, shortenedName, icon, stacks, enchantID = WeakAuras.GetOHTenchInfo()
end
local remaining = expirationTime and expirationTime - GetTime()
local nameCheck = triggerName == "" or name and triggerName == name or shortenedName and triggerName == shortenedName or tonumber(triggerName) and enchantID and tonumber(triggerName) == enchantID
local stackCheck = not triggerStack or stacks and stacks %s triggerStack
local remainingCheck = not triggerRemaining or remaining and remaining %s triggerRemaining
local found = expirationTime and nameCheck and stackCheck and remainingCheck
if(triggerRemaining and remaining and remaining >= triggerRemaining and remaining > 0) then
WeakAuras.ScheduleScan(expirationTime - triggerRemaining, "TENCH_UPDATE");
end
if not found then
expirationTime = nil
duration = nil
remaining = nil
end
]];
return ret:format(trigger.weapon or "main",
trigger.use_enchant and trigger.enchant or "",
trigger.use_stack and tonumber(trigger.stack or 0) or "nil",
trigger.use_remaining and tonumber(trigger.remaining or 0) or "nil",
trigger.showOn or "showOnActive",
trigger.stack_operator or "<",
trigger.remaining_operator or "<")
end,
args = {
{
name = "weapon",
display = L["Weapon"],
type = "select",
values = "weapon_types",
test = "true",
default = "main",
required = true
},
{
name = "enchant",
display = L["Weapon Enchant"],
desc = L["Enchant Name or ID"],
type = "string",
test = "true"
},
{
name = "stacks",
display = L["Stack Count"],
type = "number",
test = "true",
enable = WeakAuras.IsClassic(),
hidden = not WeakAuras.IsClassic(),
store = true
},
{
name = "duration",
hidden = true,
init = "duration",
test = "true",
store = true
},
{
name = "expirationTime",
init = "expirationTime",
hidden = true,
test = "true",
store = true
},
{
name = "progressType",
hidden = true,
init = "duration and 'timed'",
test = "true",
store = true
},
{
name = "name",
hidden = true,
init = "spell",
test = "true",
store = true
},
{
name = "icon",
hidden = true,
init = "icon or 'Interface\\AddOns\\WeakAuras\\Media\\Textures\\icon'",
test = "true",
store = true
},
{
name = "enchanted",
display = L["Enchanted"],
hidden = true,
init = "found ~= nil",
test = "true",
store = true,
conditionType = "bool",
conditionTest = function(state, needle)
return state and state.show and state.enchanted == (needle == 1)
end,
},
{
name = "remaining",
display = L["Remaining Time"],
type = "number",
test = "true"
},
{
name = "showOn",
display = L["Show On"],
type = "select",
values = "weapon_enchant_types",
test = 'true',
default = "showOnActive",
required = true
},
{
hidden = true,
test = "(triggerShowOn == 'showOnActive' and found) " ..
"or (triggerShowOn == 'showOnMissing' and not found) " ..
"or (triggerShowOn == 'showAlways')"
}
},
automaticrequired = true,
canHaveDuration = true,
statesParameter = "one"
},
["Chat Message"] = {
type = "event",
events = {
["events"] = {
"CHAT_MSG_INSTANCE_CHAT",
"CHAT_MSG_INSTANCE_CHAT_LEADER",
"CHAT_MSG_BG_SYSTEM_ALLIANCE",
"CHAT_MSG_BG_SYSTEM_HORDE",
"CHAT_MSG_BG_SYSTEM_NEUTRAL",
"CHAT_MSG_BN_WHISPER",
"CHAT_MSG_CHANNEL",
"CHAT_MSG_EMOTE",
"CHAT_MSG_GUILD",
"CHAT_MSG_MONSTER_EMOTE",
"CHAT_MSG_MONSTER_PARTY",
"CHAT_MSG_MONSTER_SAY",
"CHAT_MSG_MONSTER_WHISPER",
"CHAT_MSG_MONSTER_YELL",
"CHAT_MSG_OFFICER",
"CHAT_MSG_PARTY",
"CHAT_MSG_PARTY_LEADER",
"CHAT_MSG_RAID",
"CHAT_MSG_RAID_LEADER",
"CHAT_MSG_RAID_BOSS_EMOTE",
"CHAT_MSG_RAID_BOSS_WHISPER",
"CHAT_MSG_RAID_WARNING",
"CHAT_MSG_SAY",
"CHAT_MSG_WHISPER",
"CHAT_MSG_YELL",
"CHAT_MSG_SYSTEM",
"CHAT_MSG_TEXT_EMOTE"
}
},
name = L["Chat Message"],
init = function(trigger)
local ret = [[
if (event:find('LEADER')) then
event = event:sub(1, -8);
end
if (event == 'CHAT_MSG_TEXT_EMOTE') then
event = 'CHAT_MSG_EMOTE';
end
local use_cloneId = %s;
]];
return ret:format(trigger.use_cloneId and "true" or "false");
end,
statesParameter = "all",
args = {
{
name = "messageType",
display = L["Message Type"],
type = "select",
values = "chat_message_types",
test = "event == %q",
control = "WeakAurasSortedDropdown"
},
{
name = "message",
display = L["Message"],
init = "arg",
type = "longstring",
store = true,
conditionType = "string",
},
{
name = "sourceName",
display = L["Source Name"],
init = "arg",
type = "string",
store = true,
conditionType = "string",
},
{ -- language Name
},
{ -- Channel Name
},
{
name = "destName",
display = L["Destination Name"],
init = "arg",
type = "string",
store = true,
conditionType = "string",
},
{
name = "cloneId",
display = L["Clone per Event"],
type = "toggle",
test = "true",
init = "use_cloneId and WeakAuras.GetUniqueCloneId() or ''",
reloadOptions = true
},
},
timedrequired = function(trigger)
return trigger.use_cloneId
end
},
["Ready Check"] = {
type = "event",
events = {
["events"] = {"READY_CHECK"}
},
name = L["Ready Check"],
args = {},
timedrequired = true
},
["Combat Events"] = {
type = "event",
events = {
["events"] = {
"PLAYER_REGEN_ENABLED",
"PLAYER_REGEN_DISABLED"
}
},
name = L["Entering/Leaving Combat"],
args = {
{
name = "eventtype",
required = true,
display = L["Type"],
type = "select",
values = "combat_event_type",
test = "event == %q"
}
},
timedrequired = true
},
["Death Knight Rune"] = {
type = "status",
events = {
["events"] = {"RUNE_POWER_UPDATE"}
},
internal_events = {
"RUNE_COOLDOWN_READY",
"RUNE_COOLDOWN_CHANGED",
"RUNE_COOLDOWN_STARTED",
"COOLDOWN_REMAINING_CHECK",
"WA_DELAYED_PLAYER_ENTERING_WORLD"
},
force_events = "RUNE_COOLDOWN_FORCE",
name = L["Death Knight Rune"],
loadFunc = function(trigger)
trigger.rune = trigger.rune or 0;
if (trigger.use_rune) then
WeakAuras.WatchRuneCooldown(trigger.rune);
else
for i = 1, 6 do
WeakAuras.WatchRuneCooldown(i);
end
end
end,
init = function(trigger)
trigger.rune = trigger.rune or 0;
local ret = [[
local rune = %s;
local startTime, duration = WeakAuras.GetRuneCooldown(rune);
local genericShowOn = %s
local numRunes = 0;
for index = 1, 6 do
local startTime = WeakAuras.GetRuneCooldown(index);
if startTime == 0 then
numRunes = numRunes + 1;
end
end
]];
if(trigger.use_remaining and not trigger.use_inverse) then
local ret2 = [[
local expirationTime = startTime + duration
local remaining = expirationTime - GetTime();
local remainingCheck = %s;
if(remaining >= remainingCheck and remaining > 0) then
WeakAuras.ScheduleScan(expirationTime - remainingCheck);
end
]];
ret = ret..ret2:format(tonumber(trigger.remaining or 0) or 0);
end
return ret:format(trigger.rune, "[[" .. (trigger.genericShowOn or "") .. "]]");
end,
args = {
{
name = "rune",
display = L["Rune"],
type = "select",
values = "rune_specific_types",
test = "(genericShowOn == \"showOnReady\" and (startTime == 0)) " ..
"or (genericShowOn == \"showOnCooldown\" and startTime > 0) " ..
"or (genericShowOn == \"showAlways\")",
enable = function(trigger) return not trigger.use_runesCount end,
reloadOptions = true
},
{
name = "remaining",
display = L["Remaining Time"],
type = "number",
enable = function(trigger) return trigger.use_rune and not(trigger.genericShowOn == "showOnReady") end
},
{
name = "genericShowOn",
display = L["Show"],
type = "select",
values = "cooldown_progress_behavior_types",
test = "true",
enable = function(trigger) return trigger.use_rune end,
required = true
},
{
name = "runesCount",
display = L["Runes Count"],
type = "number",
init = "numRunes",
enable = function(trigger) return not trigger.use_rune end
},
{
hidden = true,
name = "onCooldown",
test = "true",
display = L["On Cooldown"],
conditionType = "bool",
conditionTest = function(state, needle)
return state and state.show and (state.expirationTime and state.expirationTime > GetTime()) == (needle == 1)
end,
enable = function(trigger) return trigger.use_rune end
},
},
durationFunc = function(trigger)
if trigger.use_rune then
local startTime, duration
if not(trigger.use_inverse) then
startTime, duration = WeakAuras.GetRuneCooldown(trigger.rune);
end
startTime = startTime or 0;
duration = duration or 0;
return duration, startTime + duration;
else
local numRunes = 0;
for index = 1, 6 do
local startTime = GetRuneCooldown(index);
if startTime == 0 then
numRunes = numRunes + 1;
end
end
return numRunes, 6, true;
end
end,
stacksFunc = function(trigger)
local numRunes = 0;
for index = 1, 6 do
local startTime = select(1, GetRuneCooldown(index));
if startTime == 0 then
numRunes = numRunes + 1;
end
end
return numRunes;
end,
iconFunc = function(trigger)
return "Interface\\PlayerFrame\\UI-PlayerFrame-Deathknight-SingleRune";
end,
automaticrequired = true,
},
["Item Equipped"] = {
type = "status",
events = {
["events"] = {
"UNIT_INVENTORY_CHANGED",
"PLAYER_EQUIPMENT_CHANGED",
}
},
internal_events = { "WA_DELAYED_PLAYER_ENTERING_WORLD", },
force_events = "UNIT_INVENTORY_CHANGED",
name = L["Item Equipped"],
init = function(trigger)
trigger.itemName = trigger.itemName or 0;
local itemName = type(trigger.itemName) == "number" and trigger.itemName or "[[" .. trigger.itemName .. "]]";
local ret = [[
local inverse = %s;
local equipped = IsEquippedItem(%s);
]];
return ret:format(trigger.use_inverse and "true" or "false", itemName);
end,
args = {
{
name = "itemName",
display = L["Item"],
type = "item",
required = true,
test = "true"
},
{
name = "inverse",
display = L["Inverse"],
type = "toggle",
test = "true"
},
{
hidden = true,
test = "(inverse and not equipped) or (equipped and not inverse)"
}
},
nameFunc = function(trigger)
if not trigger.use_inverse then
local name = GetItemInfo(trigger.itemName);
return name;
else
return nil;
end
end,
iconFunc = function(trigger)
if not trigger.use_inverse then
local _, _, _, _, icon = GetItemInfoInstant(trigger.itemName or 0);
return icon;
else
return nil;
end
end,
hasItemID = true,
automaticrequired = true
},
["Item Type Equipped"] = {
type = "status",
events = {
["events"] = {
"UNIT_INVENTORY_CHANGED",
"PLAYER_EQUIPMENT_CHANGED",
}
},
internal_events = { "WA_DELAYED_PLAYER_ENTERING_WORLD", },
force_events = "UNIT_INVENTORY_CHANGED",
name = L["Item Type Equipped"],
args = {
{
name = "itemTypeName",
display = L["Item Type"],
type = "multiselect",
values = "item_weapon_types",
test = "IsEquippedItemType(WeakAuras.GetItemSubClassInfo(%s))"
},
},
automaticrequired = true
},
["Item Bonus Id Equipped"] = {
type = "status",
events = {
["events"] = {
"UNIT_INVENTORY_CHANGED",
"PLAYER_EQUIPMENT_CHANGED",
}
},
internal_events = { "WA_DELAYED_PLAYER_ENTERING_WORLD", },
force_events = "UNIT_INVENTORY_CHANGED",
name = L["Item Bonus Id Equipped"],
statesParameter = "one",
init = function(trigger)
local ret = [=[
local fetchLegendaryPower = %s
local item = %q
local inverse = %s
local useItemSlot, slotSelected = %s, %d
local itemBonusId, itemId, itemName, icon, itemSlot, itemSlotString = WeakAuras.GetBonusIdInfo(item, useItemSlot and slotSelected)
local itemBonusId = tonumber(itemBonusId)
if fetchLegendaryPower then
itemName, icon = WeakAuras.GetLegendaryData(itemBonusId or item)
end
local slotValidation = (useItemSlot and itemSlot == slotSelected) or (not useItemSlot)
]=]
return ret:format(trigger.use_legendaryIcon and "true" or "false", trigger.itemBonusId or "", trigger.use_inverse and "true" or "false",
trigger.use_itemSlot and "true" or "false", trigger.itemSlot)
end,
args = {
{
name = "itemBonusId",
display = L["Item Bonus Id"],
type = "string",
store = "true",
test = "true",
required = true,
desc = function()
return WeakAuras.GetLegendariesBonusIds()
.. L["\n\nSupports multiple entries, separated by commas"]
end,
conditionType = "number",
},
{
name = "legendaryIcon",
display = L["Fetch Legendary Power"],
type = "toggle",
test = "true",
desc = L["Fetches the name and icon of the Legendary Power that matches this bonus id."],
enable = not WeakAuras.IsClassic(),
hidden = WeakAuras.IsClassic(),
},
{
name = "name",
display = L["Item Name"],
hidden = "true",
init = "itemName",
store = "true",
test = "true",
},
{
name = "icon",
hidden = "true",
init = "icon or 'Interface/Icons/INV_Misc_QuestionMark'",
store = "true",
test = "true",
},
{
name = "itemId",
display = L["Item Id"],
hidden = "true",
store = "true",
test = "true",
conditionType = "number",
operator_types = "only_equal",
},
{
name = "itemSlot",
display = L["Item Slot"],
type = "select",
store = "true",
conditionType = "select",
values = "item_slot_types",
test = "true",
},
{
name = "inverse",
display = L["Inverse"],
type = "toggle",
test = "true",
},
{
name = "itemSlotString",
display = L["Item Slot String"],
hidden = "true",
store = "true",
test = "true",
},
{
hidden = true,
test = "not inverse == (itemBonusId and slotValidation or false)",
}
},
automaticrequired = true
},
["Item Set"] = {
type = "status",
events = {
["events"] = {"PLAYER_EQUIPMENT_CHANGED"}
},
force_events = "PLAYER_EQUIPMENT_CHANGED",
name = L["Item Set Equipped"],
automaticrequired = true,
init = function(trigger)
return string.format("local setid = %s;\n", trigger.itemSetId and tonumber(trigger.itemSetId) or "0");
end,
statesParameter = "one",
args = {
{
name = "itemSetId",
display = L["Item Set Id"],
type = "string",
test = "true",
store = "true",
required = true,
validate = WeakAuras.ValidateNumeric,
desc = function()
if not WeakAuras.IsClassic() then
return L["Set IDs can be found on websites such as wowhead.com/item-sets"]
else
return L["Set IDs can be found on websites such as classic.wowhead.com/item-sets"]
end
end
},
{
name = "equipped",
display = L["Equipped"],
type = "number",
init = "WeakAuras.GetNumSetItemsEquipped(setid)",
store = true,
required = true,
conditionType = "number"
}
},
durationFunc = function(trigger)
return WeakAuras.GetNumSetItemsEquipped(trigger.itemSetId and tonumber(trigger.itemSetId) or 0)
end,
nameFunc = function(trigger)
return select(3, WeakAuras.GetNumSetItemsEquipped(trigger.itemSetId and tonumber(trigger.itemSetId) or 0));
end
},
["Equipment Set"] = {
type = "status",
events = {
["events"] = {
"PLAYER_EQUIPMENT_CHANGED",
"WEAR_EQUIPMENT_SET",
"EQUIPMENT_SETS_CHANGED",
"EQUIPMENT_SWAP_FINISHED",
}
},
internal_events = {"WA_DELAYED_PLAYER_ENTERING_WORLD"},
force_events = "PLAYER_EQUIPMENT_CHANGED",
name = L["Equipment Set Equipped"],
init = function(trigger)
trigger.itemSetName = trigger.itemSetName or "";
local itemSetName = type(trigger.itemSetName) == "string" and ("[=[" .. trigger.itemSetName .. "]=]") or "nil";
local ret = [[
local useItemSetName = %s;
local triggerItemSetName = %s;
local inverse = %s;
local partial = %s;
]];
return ret:format(trigger.use_itemSetName and "true" or "false", itemSetName, trigger.use_inverse and "true" or "false", trigger.use_partial and "true" or "false");
end,
statesParameter = "one",
args = {
{
name = "itemSetName",
display = L["Equipment Set"],
type = "string",
test = "true",
store = true,
conditionType = "string",
init = "WeakAuras.GetEquipmentSetInfo(useItemSetName and triggerItemSetName or nil, partial)"
},
{
name = "partial",
display = L["Allow partial matches"],
type = "toggle",
test = "true"
},
{
name = "inverse",
display = L["Inverse"],
type = "toggle",
test = "true"
},
{
hidden = true,
test = "(inverse and itemSetName == nil) or (not inverse and itemSetName)"
}
},
nameFunc = function(trigger)
return WeakAuras.GetEquipmentSetInfo(trigger.use_itemSetName and trigger.itemSetName or nil, trigger.use_partial);
end,
iconFunc = function(trigger)
local _, icon = WeakAuras.GetEquipmentSetInfo(trigger.use_itemSetName and trigger.itemSetName or nil, trigger.use_partial);
return icon;
end,
durationFunc = function(trigger)
local _, _, numEquipped, numItems = WeakAuras.GetEquipmentSetInfo(trigger.use_itemSetName and trigger.itemSetName or nil, trigger.use_partial);
return numEquipped, numItems, true;
end,
hasItemID = true,
automaticrequired = true
},
["Threat Situation"] = {
type = "status",
events = function(trigger)
local result = {}
if trigger.threatUnit and trigger.threatUnit ~= "none" then
AddUnitEventForEvents(result, trigger.threatUnit, "UNIT_THREAT_LIST_UPDATE")
else
AddUnitEventForEvents(result, "player", "UNIT_THREAT_SITUATION_UPDATE")
end
return result
end,
internal_events = function(trigger)
local result = {}
if trigger.threatUnit and trigger.threatUnit ~= "none" then
AddUnitChangeInternalEvents(trigger.threatUnit, result)
end
return result
end,
force_events = "UNIT_THREAT_LIST_UPDATE",
name = L["Threat Situation"],
init = function(trigger)
local ret = [[
local unit = %s
local ok = true
local aggro, status, threatpct, rawthreatpct, threatvalue, threattotal
if unit then
aggro, status, threatpct, rawthreatpct, threatvalue = WeakAuras.UnitDetailedThreatSituation('player', unit)
threattotal = (threatvalue or 0) * 100 / (threatpct ~= 0 and threatpct or 1)
else
status = UnitThreatSituation('player')
aggro = status == 2 or status == 3
threatpct, rawthreatpct, threatvalue, threattotal = 100, 100, 0, 100
end
]];
return ret:format(trigger.threatUnit and trigger.threatUnit ~= "none" and "[["..trigger.threatUnit.."]]" or "nil");
end,
canHaveDuration = true,
statesParameter = "one",
args = {
{
name = "threatUnit",
display = L["Unit"],
required = true,
type = "unit",
values = "threat_unit_types",
test = "true",
default = "target"
},
{
name = "status",
display = L["Status"],
type = "select",
values = "unit_threat_situation_types",
store = true,
conditionType = "select"
},
{
name = "aggro",
display = L["Aggro"],
type = "tristate",
store = true,
conditionType = "bool",
},
{
name = "threatpct",
display = L["Threat Percent"],
desc = L["Your threat on the mob as a percentage of the amount required to pull aggro. Will pull aggro at 100."],
type = "number",
store = true,
conditionType = "number",
enable = function(trigger) return trigger.threatUnit ~= "none" end,
},
{
name = "rawthreatpct",
display = L["Raw Threat Percent"],
desc = L["Your threat as a percentage of the tank's current threat."],
type = "number",
store = true,
conditionType = "number",
enable = function(trigger) return trigger.threatUnit ~= "none" end,
},
{
name = "threatvalue",
display = L["Threat Value"],
desc = L["Your total threat on the mob."],
type = "number",
store = true,
conditionType = "number",
enable = function(trigger) return trigger.threatUnit ~= "none" end,
},
{
name = "value",
hidden = true,
init = "threatvalue",
store = true,
test = "true"
},
{
name = "total",
hidden = true,
init = "threattotal",
store = true,
test = "true"
},
{
name = "progressType",
hidden = true,
init = "'static'",
store = true,
test = "true"
},
{
hidden = true,
test = "status ~= nil and ok"
}
},
automaticrequired = true
},
["Crowd Controlled"] = {
type = "status",
events = {
["events"] = {
"LOSS_OF_CONTROL_UPDATE"
}
},
force_events = "LOSS_OF_CONTROL_UPDATE",
name = L["Crowd Controlled"],
canHaveDuration = true,
statesParameter = "one",
init = function(trigger)
local ret = [=[
local show = false
local use_controlType = %s
local controlType = %s
local inverse = %s
local use_interruptSchool = %s
local interruptSchool = tonumber(%q)
local duration, expirationTime, spellName, icon, spellName, spellId, locType, lockoutSchool, name, _
for i = 1, C_LossOfControl.GetActiveLossOfControlDataCount() do
local data = C_LossOfControl.GetActiveLossOfControlData(i)
if data then
if (not use_controlType)
or (data.locType == controlType and (controlType ~= "SCHOOL_INTERRUPT" or ((not use_interruptSchool) or bit.band(data.lockoutSchool, interruptSchool) > 0)))
then
spellId = data.spellID
spellName, _, icon = GetSpellInfo(data.spellID)
duration = data.duration
if data.startTime and data.duration then
expirationTime = data.startTime + data.duration
end
locType = data.locType
lockoutSchool = data.lockoutSchool
name = data.displayText
show = true
break
end
end
end
]=]
ret = ret:format(
trigger.use_controlType and "true" or "false",
type(trigger.controlType) == "string" and "[["..trigger.controlType.."]]" or [["STUN"]],
trigger.use_inverse and "true" or "false",
trigger.use_interruptSchool and "true" or "false",
trigger.interruptSchool or 0
)
return ret
end,
args = {
{
name = "controlType",
display = L["Specific Type"],
type = "select",
values = "loss_of_control_types",
conditionType = "select",
test = "true",
default = "STUN",
init = "locType",
store = true,
},
{
name = "interruptSchool",
display = L["Interrupt School"],
type = "select",
values = "main_spell_schools",
conditionType = "select",
default = 1,
test = "true",
enable = function(trigger) return trigger.controlType == "SCHOOL_INTERRUPT" end,
init = "lockoutSchool",
store = true,
},
{
name = "inverse",
display = L["Inverse"],
type = "toggle",
test = "true",
},
{
name = "name",
display = L["Name"],
hidden = true,
conditionType = "string",
store = true,
test = "true",
},
{
name = "spellName",
display = L["Spell Name"],
hidden = true,
conditionType = "string",
store = true,
test = "true",
},
{
name = "spellId",
display = L["Spell Id"],
hidden = true,
conditionType = "number",
operator_types = "only_equal",
store = true,
test = "true",
},
{
name = "lockoutSchool",
display = L["Interrupted School Text"],
hidden = true,
init = "lockoutSchool and lockoutSchool > 0 and GetSchoolString(lockoutSchool) or nil",
store = true,
test = "true",
},
{
name = "icon",
hidden = true,
store = true,
test = "true",
},
{
name = "duration",
hidden = true,
store = true,
test = "true",
},
{
name = "expirationTime",
hidden = true,
store = true,
test = "true",
},
{
name = "progressType",
hidden = true,
init = "'timed'",
store = true,
test = "true",
},
{
hidden = true,
test = "inverse ~= show",
},
},
automaticrequired = true,
},
["Cast"] = {
type = "status",
events = function(trigger)
local result = {}
local unit = trigger.unit
AddUnitEventForEvents(result, unit, "UNIT_SPELLCAST_START")
AddUnitEventForEvents(result, unit, "UNIT_SPELLCAST_DELAYED")
AddUnitEventForEvents(result, unit, "UNIT_SPELLCAST_STOP")
AddUnitEventForEvents(result, unit, "UNIT_SPELLCAST_CHANNEL_START")
AddUnitEventForEvents(result, unit, "UNIT_SPELLCAST_CHANNEL_UPDATE")
AddUnitEventForEvents(result, unit, "UNIT_SPELLCAST_CHANNEL_STOP")
AddUnitEventForEvents(result, unit, "UNIT_SPELLCAST_INTERRUPTIBLE")
AddUnitEventForEvents(result, unit, "UNIT_SPELLCAST_NOT_INTERRUPTIBLE")
AddUnitEventForEvents(result, unit, "UNIT_SPELLCAST_INTERRUPTED")
AddUnitEventForEvents(result, unit, "UNIT_NAME_UPDATE")
if WeakAuras.IsClassic() and unit ~= "player" then
LibClassicCasterino.RegisterCallback("WeakAuras", "UNIT_SPELLCAST_START", WeakAuras.ScanUnitEvents)
LibClassicCasterino.RegisterCallback("WeakAuras", "UNIT_SPELLCAST_DELAYED", WeakAuras.ScanUnitEvents) -- only for player
LibClassicCasterino.RegisterCallback("WeakAuras", "UNIT_SPELLCAST_STOP", WeakAuras.ScanUnitEvents)
LibClassicCasterino.RegisterCallback("WeakAuras", "UNIT_SPELLCAST_CHANNEL_START", WeakAuras.ScanUnitEvents)
LibClassicCasterino.RegisterCallback("WeakAuras", "UNIT_SPELLCAST_CHANNEL_UPDATE", WeakAuras.ScanUnitEvents) -- only for player
LibClassicCasterino.RegisterCallback("WeakAuras", "UNIT_SPELLCAST_CHANNEL_STOP", WeakAuras.ScanUnitEvents)
LibClassicCasterino.RegisterCallback("WeakAuras", "UNIT_SPELLCAST_INTERRUPTED", WeakAuras.ScanUnitEvents)
end
AddUnitEventForEvents(result, unit, "UNIT_TARGET")
return result
end,
internal_events = function(trigger)
local unit = trigger.unit
local result = {"CAST_REMAINING_CHECK"}
if WeakAuras.IsClassic() and unit ~= "player" then
tinsert(result, "UNIT_SPELLCAST_START")
tinsert(result, "UNIT_SPELLCAST_DELAYED")
tinsert(result, "UNIT_SPELLCAST_CHANNEL_START")
end
AddUnitChangeInternalEvents(unit, result)
AddUnitRoleChangeInternalEvents(unit, result)
return result
end,
force_events = unitHelperFunctions.UnitChangedForceEvents,
canHaveDuration = "timed",
name = L["Cast"],
init = function(trigger)
trigger.unit = trigger.unit or "player";
local ret = [=[
unit = string.lower(unit)
local destUnit = unit .. '-target'
local sourceName, sourceRealm = WeakAuras.UnitNameWithRealm(unit)
local destName, destRealm = WeakAuras.UnitNameWithRealm(destUnit)
destName = destName or ""
destRealm = destRealm or ""
local smart = %s
local remainingCheck = %s
local inverseTrigger = %s
local show, expirationTime, castType, spell, icon, startTime, endTime, interruptible, spellId, remaining, _
spell, _, icon, startTime, endTime, _, _, interruptible, spellId = WeakAuras.UnitCastingInfo(unit)
if spell then
castType = "cast"
else
spell, _, icon, startTime, endTime, _, interruptible, spellId = WeakAuras.UnitChannelInfo(unit)
if spell then
castType = "channel"
end
end
interruptible = not interruptible
expirationTime = endTime and endTime > 0 and (endTime / 1000) or 0
remaining = expirationTime - GetTime()
if remainingCheck and remaining >= remainingCheck and remaining > 0 then
WeakAuras.ScheduleCastCheck(expirationTime - remainingCheck, unit)
end
]=];
ret = ret:format(trigger.unit == "group" and "true" or "false",
trigger.use_remaining and tonumber(trigger.remaining or 0) or "nil",
trigger.use_inverse and "true" or "false");
ret = ret .. unitHelperFunctions.SpecificUnitCheck(trigger)
return ret
end,
statesParameter = "unit",
args = {
{
name = "unit",
required = true,
display = L["Unit"],
type = "unit",
init = "arg",
values = function(trigger)
if trigger.use_inverse then
return Private.actual_unit_types_with_specific
else
return Private.actual_unit_types_cast
end
end,
test = "true",
store = true
},
{
name = "spell",
display = L["Spell Name"],
type = "string",
enable = function(trigger) return not trigger.use_inverse end,
conditionType = "string",
store = true,
},
{
name = "spellId",
display = L["Spell Id"],
type = "spell",
enable = function(trigger) return not trigger.use_inverse end,
conditionType = "number",
forceExactOption = true,
test = "GetSpellInfo(%s) == spell",
store = true,
},
{
name = "castType",
display = L["Cast Type"],
type = "select",
values = "cast_types",
enable = function(trigger) return not trigger.use_inverse end,
store = true,
conditionType = "select"
},
{
name = "interruptible",
display = L["Interruptible"],
type = "tristate",
enable = function(trigger) return not trigger.use_inverse end,
store = true,
conditionType = "bool"
},
{
name = "remaining",
display = L["Remaining Time"],
type = "number",
enable = function(trigger) return not trigger.use_inverse end,
},
{
name = "name",
hidden = true,
init = "spell",
test = "true",
store = true
},
{
name = "icon",
hidden = true,
init = "icon or 'Interface\\AddOns\\WeakAuras\\Media\\Textures\\icon'",
test = "true",
store = true
},
{
name = "duration",
hidden = true,
init = "endTime and startTime and (endTime - startTime)/1000 or 0",
test = "true",
store = true
},
{
name = "expirationTime",
init = "expirationTime",
hidden = true,
test = "true",
store = true
},
{
name = "progressType",
hidden = true,
init = "'timed'",
test = "true",
store = true
},
{
name = "inverse",
hidden = true,
init = "castType == 'cast'",
test = "true",
store = true
},
{
name = "autoHide",
hidden = true,
init = "true",
test = "true",
store = true
},
{
name = "npcId",
display = L["Npc ID"],
type = "string",
store = true,
conditionType = "string",
test = "select(6, strsplit('-', UnitGUID(unit) or '')) == %q",
enable = function(trigger)
return not trigger.use_inverse
end
},
{
name = "class",
display = L["Class"],
type = "select",
init = "select(2, UnitClass(unit))",
values = "class_types",
store = true,
conditionType = "select",
enable = function(trigger)
return not trigger.use_inverse
end
},
{
name = "role",
display = L["Assigned Role"],
type = "select",
init = "UnitGroupRolesAssigned(unit)",
values = "role_types",
store = true,
conditionType = "select",
enable = function(trigger)
return not WeakAuras.IsClassic() and (trigger.unit == "group" or trigger.unit == "raid" or trigger.unit == "party")
and not trigger.use_inverse
end
},
{
name = "raid_role",
display = L["Assigned Role"],
type = "select",
init = "WeakAuras.UnitRaidRole(unit)",
values = "raid_role_types",
store = true,
conditionType = "select",
enable = function(trigger)
return WeakAuras.IsClassic() and (trigger.unit == "group" or trigger.unit == "raid" or trigger.unit == "party")
and not trigger.use_inverse
end
},
{
name = "ignoreSelf",
display = L["Ignore Self"],
type = "toggle",
width = WeakAuras.doubleWidth,
enable = function(trigger)
return trigger.unit == "nameplate" or trigger.unit == "group" or trigger.unit == "raid" or trigger.unit == "party"
end,
init = "not UnitIsUnit(\"player\", unit)"
},
{
name = "nameplateType",
display = L["Nameplate Type"],
type = "select",
init = "WeakAuras.GetPlayerReaction(unit)",
values = "hostility_types",
store = true,
conditionType = "select",
enable = function(trigger)
return trigger.unit == "nameplate"
end
},
{
name = "sourceUnit",
init = "unit",
display = L["Caster"],
type = "unit",
values = "actual_unit_types_with_specific",
conditionType = "unit",
conditionTest = function(state, unit, op)
return state and state.show and state.unit and (UnitIsUnit(state.sourceUnit, unit) == (op == "=="))
end,
store = true,
hidden = true,
enable = function(trigger) return not trigger.use_inverse end,
test = "true"
},
{
name = "sourceName",
display = L["Caster Name"],
type = "string",
store = true,
hidden = true,
test = "true",
enable = function(trigger) return not trigger.use_inverse end,
},
{
name = "sourceRealm",
display = L["Caster Realm"],
type = "string",
store = true,
hidden = true,
test = "true",
enable = function(trigger) return not trigger.use_inverse end,
},
{
name = "sourceNameRealm",
display = L["Source Unit Name/Realm"],
type = "string",
preamble = "local sourceNameRealmChecker = WeakAuras.ParseNameCheck(%q)",
test = "sourceNameRealmChecker:Check(sourceName, sourceRealm)",
conditionType = "string",
conditionPreamble = function(input)
return WeakAuras.ParseNameCheck(input)
end,
conditionTest = function(state, needle, op, preamble)
return preamble:Check(state.sourceName, state.sourceRealm)
end,
operator_types = "none",
enable = function(trigger) return not trigger.use_inverse end,
desc = constants.nameRealmFilterDesc,
},
{
name = "destUnit",
display = L["Caster's Target"],
type = "unit",
values = "actual_unit_types_with_specific",
conditionType = "unit",
conditionTest = function(state, unit, op)
return state and state.show and state.destUnit and (UnitIsUnit(state.destUnit, unit) == (op == "=="))
end,
store = true,
enable = function(trigger) return not trigger.use_inverse end,
test = "UnitIsUnit(destUnit, [[%s]])"
},
{
name = "destName",
display = L["Name of Caster's Target"],
type = "string",
store = true,
hidden = true,
test = "true",
enable = function(trigger) return not trigger.use_inverse end,
},
{
name = "destRealm",
display = L["Realm of Caster's Target"],
type = "string",
store = true,
hidden = true,
test = "true",
enable = function(trigger) return not trigger.use_inverse end,
},
{
name = "destNameRealm",
display = L["Name/Realm of Caster's Target"],
type = "string",
preamble = "local destNameRealmChecker = WeakAuras.ParseNameCheck(%q)",
test = "destNameRealmChecker:Check(destName, destRealm)",
conditionType = "string",
conditionPreamble = function(input)
return WeakAuras.ParseNameCheck(input)
end,
conditionTest = function(state, needle, op, preamble)
return preamble:Check(state.destName, state.destRealm)
end,
operator_types = "none",
enable = function(trigger) return not trigger.use_inverse end,
desc = constants.nameRealmFilterDesc,
},
{
name = "inverse",
display = L["Inverse"],
type = "toggle",
test = "true",
reloadOptions = true
},
{
hidden = true,
test = "WeakAuras.UnitExistsFixed(unit, smart) and ((not inverseTrigger and spell) or (inverseTrigger and not spell)) and specificUnitCheck"
}
},
automaticrequired = true,
},
["Character Stats"] = {
type = "status",
name = L["Character Stats"],
events = {
["events"] = {
"COMBAT_RATING_UPDATE",
"PLAYER_TARGET_CHANGED"
},
["unit_events"] = {
["player"] = {"UNIT_STATS", "UNIT_ATTACK_POWER", "UNIT_AURA"}
}
},
internal_events = function(trigger, untrigger)
local events = { "WA_DELAYED_PLAYER_ENTERING_WORLD", "PLAYER_MOVING_UPDATE" }
if trigger.use_moveSpeed then
tinsert(events, "PLAYER_MOVE_SPEED_UPDATE")
end
return events
end,
loadFunc = function(trigger)
if trigger.use_moveSpeed then
WeakAuras.WatchPlayerMoveSpeed()
end
WeakAuras.WatchForPlayerMoving()
end,
init = function()
local ret = [[
local main_stat, _
if not WeakAuras.IsClassic() then
_, _, _, _, _, main_stat = GetSpecializationInfo(GetSpecialization() or 0)
end
]]
return ret;
end,
force_events = "CONDITIONS_CHECK",
statesParameter = "one",
args = {
{
name = "mainstat",
display = L["Main Stat"],
type = "number",
init = "UnitStat('player', main_stat or 1)",
store = true,
enable = not WeakAuras.IsClassic(),
conditionType = "number",
hidden = WeakAuras.IsClassic()
},
{
name = "strength",
display = L["Strength"],
type = "number",
init = "UnitStat('player', LE_UNIT_STAT_STRENGTH)",
store = true,
enable = WeakAuras.IsClassic(),
conditionType = "number",
hidden = not WeakAuras.IsClassic()
},
{
name = "agility",
display = L["Agility"],
type = "number",
init = "UnitStat('player', LE_UNIT_STAT_AGILITY)",
store = true,
enable = WeakAuras.IsClassic(),
conditionType = "number",
hidden = not WeakAuras.IsClassic()
},
{
name = "intellect",
display = L["Intellect"],
type = "number",
init = "UnitStat('player', LE_UNIT_STAT_INTELLECT)",
store = true,
enable = WeakAuras.IsClassic(),
conditionType = "number",
hidden = not WeakAuras.IsClassic()
},
{
name = "stamina",
display = L["Stamina"],
type = "number",
init = "select(2, UnitStat('player', LE_UNIT_STAT_STAMINA)) * GetUnitMaxHealthModifier('player')",
store = true,
conditionType = "number"
},
{
name = "criticalrating",
display = L["Critical Rating"],
type = "number",
init = "GetCombatRating(CR_CRIT_SPELL)",
store = true,
enable = not WeakAuras.IsClassic(),
conditionType = "number",
hidden = WeakAuras.IsClassic()
},
{
name = "criticalpercent",
display = L["Critical (%)"],
type = "number",
init = "GetCritChance()",
store = true,
conditionType = "number"
},
{
name = "hasterating",
display = L["Haste Rating"],
type = "number",
init = "GetCombatRating(CR_HASTE_SPELL)",
store = true,
enable = not WeakAuras.IsClassic(),
conditionType = "number",
hidden = WeakAuras.IsClassic()
},
{
name = "hastepercent",
display = L["Haste (%)"],
type = "number",
init = "GetHaste()",
store = true,
conditionType = "number"
},
{
name = "masteryrating",
display = L["Mastery Rating"],
type = "number",
init = "GetCombatRating(CR_MASTERY)",
store = true,
enable = not WeakAuras.IsClassic(),
conditionType = "number",
hidden = WeakAuras.IsClassic()
},
{
name = "masterypercent",
display = L["Mastery (%)"],
type = "number",
init = "GetMasteryEffect()",
store = true,
enable = not WeakAuras.IsClassic(),
conditionType = "number",
hidden = WeakAuras.IsClassic()
},
{
name = "versatilityrating",
display = L["Versatility Rating"],
type = "number",
init = "GetCombatRating(CR_VERSATILITY_DAMAGE_DONE)",
store = true,
enable = not WeakAuras.IsClassic(),
conditionType = "number",
hidden = WeakAuras.IsClassic()
},
{
name = "versatilitypercent",
display = L["Versatility (%)"],
type = "number",
init = "GetCombatRatingBonus(CR_VERSATILITY_DAMAGE_DONE) + GetVersatilityBonus(CR_VERSATILITY_DAMAGE_DONE)",
store = true,
enable = not WeakAuras.IsClassic(),
conditionType = "number",
hidden = WeakAuras.IsClassic()
},
{
name = "attackpower",
display = L["Attack Power"],
type = "number",
init = "WeakAuras.GetEffectiveAttackPower()",
store = true,
conditionType = "number"
},
{
name = "resistanceholy",
display = L["Holy Resistance"],
type = "number",
init = "select(2, UnitResistance('player', 1))",
store = true,
enable = WeakAuras.IsClassic(),
conditionType = "number",
hidden = not WeakAuras.IsClassic()
},
{
name = "resistancefire",
display = L["Fire Resistance"],
type = "number",
init = "select(2, UnitResistance('player', 2))",
store = true,
enable = WeakAuras.IsClassic(),
conditionType = "number",
hidden = not WeakAuras.IsClassic()
},
{
name = "resistancenature",
display = L["Nature Resistance"],
type = "number",
init = "select(2, UnitResistance('player', 3))",
store = true,
enable = WeakAuras.IsClassic(),
conditionType = "number",
hidden = not WeakAuras.IsClassic()
},
{
name = "resistancefrost",
display = L["Frost Resistance"],
type = "number",
init = "select(2, UnitResistance('player', 4))",
store = true,
enable = WeakAuras.IsClassic(),
conditionType = "number",
hidden = not WeakAuras.IsClassic()
},
{
name = "resistanceshadow",
display = L["Shadow Resistance"],
type = "number",
init = "select(2, UnitResistance('player', 5))",
store = true,
enable = WeakAuras.IsClassic(),
conditionType = "number",
hidden = not WeakAuras.IsClassic()
},
{
name = "resistancearcane",
display = L["Arcane Resistance"],
type = "number",
init = "select(2, UnitResistance('player', 6))",
store = true,
enable = WeakAuras.IsClassic(),
conditionType = "number",
hidden = not WeakAuras.IsClassic()
},
{
name = "leechrating",
display = L["Leech Rating"],
type = "number",
init = "GetCombatRating(CR_LIFESTEAL)",
store = true,
enable = not WeakAuras.IsClassic(),
conditionType = "number",
hidden = WeakAuras.IsClassic()
},
{
name = "leechpercent",
display = L["Leech (%)"],
type = "number",
init = "GetLifesteal()",
store = true,
enable = not WeakAuras.IsClassic(),
conditionType = "number",
hidden = WeakAuras.IsClassic()
},
{
name = "movespeedrating",
display = L["Movement Speed Rating"],
type = "number",
init = "GetCombatRating(CR_SPEED)",
store = true,
enable = not WeakAuras.IsClassic(),
conditionType = "number",
hidden = WeakAuras.IsClassic()
},
{
name = "moveSpeed",
display = L["Continuously update Movement Speed"],
type = "boolean",
test = true,
width = WeakAuras.doubleWidth
},
{
name = "movespeedpercent",
display = L["Movement Speed (%)"],
type = "number",
init = "GetUnitSpeed('player') / 7 * 100",
store = true,
conditionType = "number"
},
{
name = "avoidancerating",
display = L["Avoidance Rating"],
type = "number",
init = "GetCombatRating(CR_AVOIDANCE)",
store = true,
enable = not WeakAuras.IsClassic(),
conditionType = "number",
hidden = WeakAuras.IsClassic()
},
{
name = "avoidancepercent",
display = L["Avoidance (%)"],
type = "number",
init = "GetAvoidance()",
store = true,
enable = not WeakAuras.IsClassic(),
conditionType = "number",
hidden = WeakAuras.IsClassic()
},
{
name = "dodgerating",
display = L["Dodge Rating"],
type = "number",
init = "GetCombatRating(CR_DODGE)",
store = true,
enable = not WeakAuras.IsClassic(),
conditionType = "number",
hidden = WeakAuras.IsClassic()
},
{
name = "dodgepercent",
display = L["Dodge (%)"],
type = "number",
init = "GetDodgeChance()",
store = true,
conditionType = "number"
},
{
name = "parryrating",
display = L["Parry Rating"],
type = "number",
init = "GetCombatRating(CR_PARRY)",
store = true,
enable = not WeakAuras.IsClassic(),
conditionType = "number",
hidden = WeakAuras.IsClassic()
},
{
name = "parrypercent",
display = L["Parry (%)"],
type = "number",
init = "GetParryChance()",
store = true,
conditionType = "number"
},
{
name = "blockpercent",
display = L["Block (%)"],
type = "number",
init = "GetBlockChance()",
store = true,
conditionType = "number"
},
{
name = "blocktargetpercent",
display = L["Block against Target (%)"],
type = "number",
init = "PaperDollFrame_GetArmorReductionAgainstTarget(GetShieldBlock())",
store = true,
enable = not WeakAuras.IsClassic(),
conditionType = "number",
hidden = WeakAuras.IsClassic()
},
{
name = "armorrating",
display = L["Armor Rating"],
type = "number",
init = "select(2, UnitArmor('player'))",
store = true,
conditionType = "number"
},
{
name = "armorpercent",
display = L["Armor (%)"],
type = "number",
init = "PaperDollFrame_GetArmorReduction(select(2, UnitArmor('player')), UnitEffectiveLevel('player'))",
store = true,
enable = not WeakAuras.IsClassic(),
conditionType = "number",
hidden = WeakAuras.IsClassic()
},
{
name = "armortargetpercent",
display = L["Armor against Target (%)"],
type = "number",
init = "PaperDollFrame_GetArmorReductionAgainstTarget(select(2, UnitArmor('player')))",
store = true,
enable = not WeakAuras.IsClassic(),
conditionType = "number",
hidden = WeakAuras.IsClassic()
},
},
automaticrequired = true
},
["Conditions"] = {
type = "status",
events = function(trigger, untrigger)
local events = {}
if trigger.use_incombat ~= nil then
tinsert(events, "PLAYER_REGEN_ENABLED")
tinsert(events, "PLAYER_REGEN_DISABLED")
tinsert(events, "PLAYER_ENTERING_WORLD")
end
if trigger.use_pvpflagged ~= nil or trigger.use_afk ~= nil then
tinsert(events, "PLAYER_FLAGS_CHANGED")
end
if trigger.use_alive ~= nil then
tinsert(events, "PLAYER_DEAD")
tinsert(events, "PLAYER_ALIVE")
tinsert(events, "PLAYER_UNGHOST")
end
if trigger.use_resting ~= nil then
tinsert(events, "PLAYER_UPDATE_RESTING")
tinsert(events, "PLAYER_ENTERING_WORLD")
end
if trigger.use_mounted ~= nil then
tinsert(events, "PLAYER_MOUNT_DISPLAY_CHANGED")
tinsert(events, "PLAYER_ENTERING_WORLD")
end
local unit_events = {}
local pet_unit_events = {}
if trigger.use_vehicle ~= nil then
if WeakAuras.IsClassic() then
tinsert(unit_events, "UNIT_FLAGS")
else
tinsert(unit_events, "UNIT_ENTERED_VEHICLE")
tinsert(unit_events, "UNIT_EXITED_VEHICLE")
end
tinsert(events, "PLAYER_ENTERING_WORLD")
end
if trigger.use_HasPet ~= nil then
tinsert(pet_unit_events, "UNIT_HEALTH")
end
if trigger.use_ingroup ~= nil then
tinsert(events, "GROUP_ROSTER_UPDATE")
end
if trigger.use_instance_size ~= nil then
tinsert(events, "ZONE_CHANGED")
tinsert(events, "ZONE_CHANGED_INDOORS")
tinsert(events, "ZONE_CHANGED_NEW_AREA")
end
if trigger.use_instance_difficulty ~= nil or trigger.use_instance_type then
tinsert(events, "PLAYER_DIFFICULTY_CHANGED")
tinsert(events, "ZONE_CHANGED")
tinsert(events, "ZONE_CHANGED_INDOORS")
tinsert(events, "ZONE_CHANGED_NEW_AREA")
end
return {
["events"] = events,
["unit_events"] = {
["player"] = unit_events,
["pet"] = pet_unit_events
}
}
end,
internal_events = function(trigger, untrigger)
local events = { "CONDITIONS_CHECK"};
if (trigger.use_ismoving ~= nil) then
tinsert(events, "PLAYER_MOVING_UPDATE");
end
if (trigger.use_HasPet ~= nil) then
AddUnitChangeInternalEvents("pet", events)
end
return events;
end,
force_events = "CONDITIONS_CHECK",
name = L["Conditions"],
loadFunc = function(trigger)
if (trigger.use_ismoving ~= nil) then
WeakAuras.WatchForPlayerMoving();
end
end,
init = function(trigger)
return "";
end,
args = {
{
name = "alwaystrue",
display = L["Always active trigger"],
type = "tristate",
init = "true"
},
{
name = "incombat",
display = L["In Combat"],
type = "tristate",
init = "UnitAffectingCombat('player')"
},
{
name = "pvpflagged",
display = L["PvP Flagged"],
type = "tristate",
init = "UnitIsPVP('player')",
enable = not WeakAuras.IsClassic(),
hidden = WeakAuras.IsClassic()
},
{
name = "alive",
display = L["Alive"],
type = "tristate",
init = "not UnitIsDeadOrGhost('player')"
},
{
name = "vehicle",
display = WeakAuras.IsClassic() and L["On Taxi"] or L["In Vehicle"],
type = "tristate",
init = WeakAuras.IsClassic() and "UnitOnTaxi('player')" or "UnitInVehicle('player')",
},
{
name = "resting",
display = L["Resting"],
type = "tristate",
init = "IsResting()"
},
{
name = "mounted",
display = L["Mounted"],
type = "tristate",
init = "IsMounted()"
},
{
name = "HasPet",
display = L["HasPet"],
type = "tristate",
init = "UnitExists('pet') and not UnitIsDead('pet')"
},
{
name = "ismoving",
display = L["Is Moving"],
type = "tristate",
init = "IsPlayerMoving()"
},
{
name = "afk",
display = L["Is Away from Keyboard"],
type = "tristate",
init = "UnitIsAFK('player')"
},
{
name = "ingroup",
display = L["In Group"],
type = "multiselect",
values = "group_types",
init = "WeakAuras.GroupType()",
},
{
name = "instance_size",
display = L["Instance Size Type"],
type = "multiselect",
values = "instance_types",
init = "WeakAuras.InstanceType()",
control = "WeakAurasSortedDropdown",
},
{
name = "instance_difficulty",
display = L["Instance Difficulty"],
type = "multiselect",
values = "difficulty_types",
init = "WeakAuras.InstanceDifficulty()",
enable = not WeakAuras.IsClassic(),
hidden = WeakAuras.IsClassic(),
},
{
name = "instance_type",
display = L["Instance Type"],
type = "multiselect",
values = "instance_difficulty_types",
init = "WeakAuras.InstanceTypeRaw()",
enable = not WeakAuras.IsClassic(),
hidden = WeakAuras.IsClassic(),
},
},
automaticrequired = true
},
["Spell Known"] = {
type = "status",
events = {
["events"] = {"SPELLS_CHANGED"},
["unit_events"] = {
["player"] = {"UNIT_PET"}
}
},
internal_events = {
"WA_DELAYED_PLAYER_ENTERING_WORLD"
},
force_events = "SPELLS_CHANGED",
name = L["Spell Known"],
init = function(trigger)
local spellName;
if (trigger.use_exact_spellName) then
spellName = tonumber(trigger.spellName) or "nil";
if spellName == 0 then
spellName = "nil"
end
local ret = [[
local spellName = %s;
local usePet = %s;
]]
return ret:format(spellName, trigger.use_petspell and "true" or "false");
else
local name = type(trigger.spellName) == "number" and GetSpellInfo(trigger.spellName) or trigger.spellName or "";
local ret = [[
local spellName = select(7, GetSpellInfo(%q));
local usePet = %s;
]]
return ret:format(name, trigger.use_petspell and "true" or "false");
end
end,
args = {
{
name = "spellName",
required = true,
display = L["Spell"],
type = "spell",
test = "true",
showExactOption = true,
},
{
name = "petspell",
display = L["Pet Spell"],
type = "toggle",
test = "true"
},
{
hidden = true,
test = "spellName and WeakAuras.IsSpellKnown(spellName, usePet)";
}
},
nameFunc = function(trigger)
return GetSpellInfo(trigger.spellName or 0)
end,
iconFunc = function(trigger)
local _, _, icon = GetSpellInfo(trigger.spellName or 0);
return icon;
end,
automaticrequired = true
},
["Pet Behavior"] = {
type = "status",
events = function(trigger)
local result = {};
if (trigger.use_behavior) then
tinsert(result, "PET_BAR_UPDATE");
end
if (trigger.use_petspec) then
tinsert(result, "PET_SPECIALIZATION_CHANGED");
end
return {
["events"] = result,
["unit_events"] = {
["player"] = {"UNIT_PET"}
}
};
end,
internal_events = {
"WA_DELAYED_PLAYER_ENTERING_WORLD"
},
force_events = "WA_DELAYED_PLAYER_ENTERING_WORLD",
name = L["Pet"],
init = function(trigger)
local ret = "local activeIcon\n";
if (trigger.use_behavior) then
ret = [[
local inverse = %s
local check_behavior = %s
local name, i, active, behavior, _
for index = 1, NUM_PET_ACTION_SLOTS do
name, i, _, active = GetPetActionInfo(index)
if active then
activeIcon = _G[i]
if name == "PET_MODE_AGGRESSIVE" then
behavior = "aggressive"
break
elseif name == "PET_MODE_ASSIST" then
behavior = "assist"
break
elseif name == "PET_MODE_DEFENSIVEASSIST" then
behavior = "defensive"
break
elseif name == "PET_MODE_DEFENSIVE" then
behavior = "defensive"
break
elseif name == "PET_MODE_PASSIVE" then
behavior = "passive"
break
end
end
end
]]
ret = ret:format(trigger.use_inverse and "true" or "false", trigger.use_behavior and ('"' .. (trigger.behavior or "") .. '"') or "nil");
end
if (trigger.use_petspec) then
ret = ret .. [[
local petspec = GetSpecialization(false, true)
if (petspec) then
activeIcon = select(4, GetSpecializationInfo(petspec, false, true));
end
]]
end
return ret;
end,
statesParameter = "one",
args = {
{
name = "behavior",
display = L["Pet Behavior"],
type = "select",
values = "pet_behavior_types",
test = "UnitExists('pet') and (not check_behavior or (inverse and check_behavior ~= behavior) or (not inverse and check_behavior == behavior))",
},
{
name = "inverse",
display = L["Inverse Pet Behavior"],
type = "toggle",
test = "true",
enable = function(trigger) return trigger.use_behavior end
},
{
name = "petspec",
display = L["Pet Specialization"],
type = "select",
values = "pet_spec_types",
},
{
hidden = true,
name = "icon",
init = "activeIcon",
store = "true",
test = "true"
},
},
automaticrequired = true
},
["Queued Action"] = {
type = "status",
events = {
["events"] = {"ACTIONBAR_UPDATE_STATE"}
},
internal_events = {
"ACTIONBAR_SLOT_CHANGED",
"ACTIONBAR_PAGE_CHANGED"
},
name = L["Queued Action"],
init = function(trigger)
trigger.spellName = trigger.spellName or 0
local spellName
if trigger.use_exact_spellName then
spellName = trigger.spellName
else
spellName = type(trigger.spellName) == "number" and GetSpellInfo(trigger.spellName) or trigger.spellName
end
local ret = [=[
local spellname = %q
local spellid = select(7, GetSpellInfo(spellname))
local button
if spellid then
local slotList = C_ActionBar.FindSpellActionButtons(spellid)
button = slotList and slotList[1]
end
]=]
return ret:format(spellName)
end,
args = {
{
name = "spellName",
required = true,
display = L["Spell"],
type = "spell",
test = "true",
showExactOption = true,
},
{
hidden = true,
test = "button and IsCurrentAction(button)";
},
},
iconFunc = function(trigger)
local _, _, icon = GetSpellInfo(trigger.spellName or 0);
return icon;
end,
automaticrequired = true
},
["Range Check"] = {
type = "status",
events = {
["events"] = {"FRAME_UPDATE"}
},
name = L["Range Check"],
init = function(trigger)
trigger.unit = trigger.unit or "target";
local ret = [=[
local unit = %q;
local min, max = WeakAuras.GetRange(unit, true);
min = min or 0;
max = max or 999;
local triggerResult = true;
]=]
if (trigger.use_range) then
trigger.range = trigger.range or 8;
if (trigger.range_operator == "<=") then
ret = ret .. "triggerResult = max <= " .. tostring(trigger.range) .. "\n";
else
ret = ret .. "triggerResult = min >= " .. tostring(trigger.range).. "\n";
end
end
return ret:format(trigger.unit);
end,
statesParameter = "one",
args = {
{
name = "note",
type = "description",
display = "",
text = function() return L["Note: This trigger type estimates the range to the hitbox of a unit. The actual range of friendly players is usually 3 yards more than the estimate. Range checking capabilities depend on your current class and known abilities as well as the type of unit being checked. Some of the ranges may also not work with certain NPCs.|n|n|cFFAAFFAAFriendly Units:|r %s|n|cFFFFAAAAHarmful Units:|r %s|n|cFFAAAAFFMiscellanous Units:|r %s"]:format(RangeCacheStrings.friend or "", RangeCacheStrings.harm or "", RangeCacheStrings.misc or "") end
},
{
name = "unit",
required = true,
display = L["Unit"],
type = "unit",
init = "unit",
values = "unit_types_range_check",
test = "true",
store = true
},
{
hidden = true,
name = "minRange",
display = L["Minimum Estimate"],
type = "number",
init = "min",
store = true,
test = "true"
},
{
hidden = true,
name = "maxRange",
display = L["Maximum Estimate"],
type = "number",
init = "max",
store = true,
test = "true"
},
{
name = "range",
display = L["Distance"],
type = "number",
operator_types = "without_equal",
test = "triggerResult",
conditionType = "number",
conditionTest = function(state, needle, needle2)
return state and state.show and WeakAuras.CheckRange(state.unit, needle, needle2);
end,
},
{
hidden = true,
test = "UnitExists(unit)"
}
},
automaticrequired = true
},
};
if WeakAuras.IsClassic() then
if not UnitDetailedThreatSituation then
Private.event_prototypes["Threat Situation"] = nil
end
Private.event_prototypes["Death Knight Rune"] = nil
Private.event_prototypes["Alternate Power"] = nil
Private.event_prototypes["Equipment Set"] = nil
Private.event_prototypes["Spell Activation Overlay"] = nil
Private.event_prototypes["Crowd Controlled"] = nil
Private.event_prototypes["PvP Talent Selected"] = nil
Private.event_prototypes["Class/Spec"] = nil
else
Private.event_prototypes["Queued Action"] = nil
end
Private.dynamic_texts = {
["p"] = {
get = function(state)
if not state then return nil end
if state.progressType == "static" then
return state.value or nil
end
if state.progressType == "timed" then
if not state.expirationTime or not state.duration then
return nil
end
local remaining = state.expirationTime - GetTime();
return remaining >= 0 and remaining or nil
end
end,
func = function(remaining, state, progressPrecision)
progressPrecision = progressPrecision or 1
if not state or state.progressType ~= "timed" then
return remaining
end
if type(remaining) ~= "number" then
return ""
end
local remainingStr = "";
if remaining == math.huge then
remainingStr = " ";
elseif remaining > 60 then
remainingStr = string.format("%i:", math.floor(remaining / 60));
remaining = remaining % 60;
remainingStr = remainingStr..string.format("%02i", remaining);
elseif remaining > 0 then
if progressPrecision == 4 and remaining <= 3 then
remainingStr = remainingStr..string.format("%.1f", remaining);
elseif progressPrecision == 5 and remaining <= 3 then
remainingStr = remainingStr..string.format("%.2f", remaining);
elseif progressPrecision == 6 and remaining <= 3 then
remainingStr = remainingStr..string.format("%.3f", remaining);
elseif (progressPrecision == 4 or progressPrecision == 5 or progressPrecision == 6) and remaining > 3 then
remainingStr = remainingStr..string.format("%d", remaining);
else
remainingStr = remainingStr..string.format("%.".. progressPrecision .."f", remaining);
end
else
remainingStr = " ";
end
return remainingStr
end
},
["t"] = {
get = function(state)
if not state then return "" end
if state.progressType == "static" then
return state.total, false
end
if state.progressType == "timed" then
if not state.duration then
return nil
end
return state.duration, true
end
end,
func = function(duration, state, totalPrecision)
if not state or state.progressType ~= "timed" then
return duration
end
if type(duration) ~= "number" then
return ""
end
local durationStr = "";
if math.abs(duration) == math.huge or tostring(duration) == "nan" then
durationStr = " ";
elseif duration > 60 then
durationStr = string.format("%i:", math.floor(duration / 60));
duration = duration % 60;
durationStr = durationStr..string.format("%02i", duration);
elseif duration > 0 then
if totalPrecision == 4 and duration <= 3 then
durationStr = durationStr..string.format("%.1f", duration);
elseif totalPrecision == 5 and duration <= 3 then
durationStr = durationStr..string.format("%.2f", duration);
elseif totalPrecision == 6 and duration <= 3 then
durationStr = durationStr..string.format("%.3f", duration);
elseif (totalPrecision == 4 or totalPrecision == 5 or totalPrecision == 6) and duration > 3 then
durationStr = durationStr..string.format("%d", duration);
else
durationStr = durationStr..string.format("%."..totalPrecision.."f", duration);
end
else
durationStr = " ";
end
return durationStr
end
},
["n"] = {
get = function(state)
if not state then return "" end
return state.name or state.id or "", true
end,
func = function(v)
return v
end
},
["i"] = {
get = function(state)
if not state then return "" end
return state.icon or "Interface\\Icons\\INV_Misc_QuestionMark"
end,
func = function(v)
return "|T".. v ..":12:12:0:0:64:64:4:60:4:60|t"
end
},
["s"] = {
get = function(state)
if not state or state.stacks == 0 then return "" end
return state.stacks
end,
func = function(v)
return v
end
}
};
| gpl-2.0 |
LacusCon/hugula | Client/Assets/Lua/game/brain/Doc.lua | 7 | 3418 | --===================================决策节点====================================================
-------------------------------------条件节点-----------------------------
ConditionNode(luafunction) ConditionNode(Condition)
--条件等待节点
ConditionWaitNode(luafunction) ConditionWaitNode(Condition)
--按一定时间执行的条件节点
DeltaConditionNode(float delta, Condition condition) DeltaConditionNode(float delta, Condition condition)
-------------------------------------行动节点-------------------------------------
ActionNode((System.Action<BTInput, BTOutput> action) --返回true
ActionNotNode((System.Action<BTInput, BTOutput> action) --返回false
--间隔时间执行的行动节点
DeltaActionNode(float delta,System.Action<BTInput, BTOutput> action)
-- 事件行动节点
ActionEventNode(System.Action<BTInput,BTOutput> action)
-------------------------------------等待节点-------------------------------------
WaitNode(float duration, float variation)--(等待指定时间后返回成功)
-------------------------------------装饰节点-------------------------------------
DecoratorNotNode() -- 反转结果
-------------------------------------选择节点------------------------------------- [从begin到end依次执行子节点]
SelectorNode() --(遇到true返回True)
-------------------------------------顺序节点------------------------------------- [从begin到end依次执行子节点]
SequenceNode() --(遇到false返回false)
SequenceTrueNode() --(遇到false返回true,否则循环完成后返回true)
-------------------------------------并行节点------------------------------------- [同时执行所有子节点]
ParallelNode() --平行执行它的所有Child Node,遇到False则返回False,全True才返回True。
ParallelNodeAny() --平行执行它的所有Child Node,遇到False则返回False,有True返回True
ParallelSelectorNode() --遇到True则返回True,全False才返回False
ParallelFallOnAllNode() --所有False才返回False,否则返回True
-------------------------------------事件节点-------------------------------------
EventNode(int eventType) --事件触发的时候执行,只能有一个子节点
TriggerNode(int eventType) --触发事件节点,运行到当前节点时候会触发eventType事件 返回成功
-------------------------------------循环节点-------------------------------------
LoopNode(int count) --The Loop node allows to execute one child a multiple number of times n (if n is not specified then it's considered to be infinite) or until the child FAILS its execution
LoopUntilSuccessNode() --The LoopUntilSuccess node allows to execute one child until it SUCCEEDS. A maximum number of attempts can be specified. If no maximum number of attempts is specified or if it's set to <= 0, then this node will try to run its child over and over again until the child succeeds.
-------------------------------------压制失败-------------------------------------
SuppressFailure() --只能有一个子节点,总是返回true
--===================================输入域输出===================================--
input.target RoleActor --输入目标角色
input.position Vector3 --输入目标位置
input.skill int --输入技能
input.stopDistance --移动停止距离
input.isDragging --是否拖动状态
output.leafNode --当前叶节点
output.eventData --传输数据
| mit |
MmxBoy/mmxanti2 | bot/utils.lua | 356 | 14963 | 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 superuser 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
-- user has admins privileges
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
-- user has moderator privileges
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['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
-- 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)
-- Berfungsi utk mengecek user jika plugin moderated = true
if plugin.moderated and not is_momod(msg) then --Cek apakah user adalah momod
if plugin.moderated and not is_admin(msg) then -- Cek apakah user adalah admin
if plugin.moderated and not is_sudo(msg) then -- Cek apakah user adalah sudoers
return false
end
end
end
-- Berfungsi mengecek user jika plugin privileged = true
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 | gpl-2.0 |
Dadido3/D3classic | Lua/Physic/Special/Fire.lua | 2 | 1286 | function Physic_Special_Fire(Map_ID, X, Y, Z)
Block_Type = Map_Block_Get_Type(Map_ID, X, Y, Z)
Player_Number = Map_Block_Get_Player_Last(Map_ID, X, Y, Z)
if math.random(5) == 1 then
Map_Block_Change(Player_Number, Map_ID, X, Y, Z, 0, 1, 0, 1, 5)
else
rx = math.random(3)-2
ry = math.random(3)-2
rz = 1
Type = Map_Block_Get_Type(Map_ID, X+rx, Y+ry, Z+rz)
if Type ~= 20 and Type ~= 7 then
if Type == 0 or math.random(40) == 1 then
Map_Block_Move(Map_ID, X, Y, Z, X+rx, Y+ry, Z+rz, 1, 1, 5)
elseif Type ~= Block_Type and Type ~= 5 and Type ~= 17 and Type ~= 47 and math.random(20) == 1 then
Map_Block_Change(Player_Number, Map_ID, X+rx, Y+ry, Z+rz, 232, 1, 0, 1, 5)
end
end
end
for ix = -1, 1 do
for iy = -1, 1 do
for iz = -1, 1 do
Type = Map_Block_Get_Type(Map_ID, X+ix, Y+iy, Z+iz)
if Type == 5 or Type == 17 or Type == 47 then
for i = 1, 4 do
rx = math.random(3)-2
ry = math.random(3)-2
rz = math.random(3)-2
Type = Map_Block_Get_Type(Map_ID, X+rx, Y+ry, Z+rz)
if Type ~= 20 and Type ~= 7 then
if Type == 0 or math.random(50) == 1 then
Map_Block_Change(Player_Number, Map_ID, X+rx, Y+ry, Z+rz, Block_Type, 1, 1, 1, 5)
end
end
end
end
end
end
end
end
| mit |
JamesWilko/GoonMod | GoonMod/lua/WeaponFlashlight.lua | 1 | 1482 |
CloneClass( WeaponFlashLight )
Hooks:RegisterHook("WeaponFlashLightInit")
function WeaponFlashLight.init(self, unit)
self.orig.init(self, unit)
Hooks:Call( "WeaponFlashLightInit", self, unit )
end
Hooks:RegisterHook("WeaponFlashLightCheckState")
function WeaponFlashLight._check_state(self)
self.orig._check_state(self)
Hooks:Call( "WeaponFlashLightCheckState", self )
end
-- TODO: This is a messy hack-fix. Fix this up proper sometime.
function WeaponFlashLight:overkill_update(unit, t, dt)
t = Application:time()
self._light_speed = self._light_speed or 1
self._light_speed = math.step(self._light_speed, 1, dt * (math.random(4) + 2))
-- self._light:set_rotation(self._light:rotation() * Rotation(dt * -50 * self._light_speed, 0))
self:update_flicker(t, dt)
self:update_laughter(t, dt)
if not self._kittens_timer then
self._kittens_timer = t + 25
end
if t > self._kittens_timer then
if math.rand(1) < 0.75 then
self:run_net_event(self.HALLOWEEN_FLICKER)
self._kittens_timer = t + math.random(10) + 5
elseif math.rand(1) < 0.35 then
self:run_net_event(self.HALLOWEEN_WARP)
self._kittens_timer = t + math.random(12) + 3
elseif math.rand(1) < 0.25 then
self:run_net_event(self.HALLOWEEN_LAUGHTER)
self._kittens_timer = t + math.random(5) + 8
elseif math.rand(1) < 0.15 then
self:run_net_event(self.HALLOWEEN_SPOOC)
self._kittens_timer = t + math.random(2) + 3
else
self._kittens_timer = t + math.random(5) + 3
end
end
end
| mit |
mamaddeveloper/outo | plugins/commit.lua | 13 | 12985 | -- Commits from https://github.com/ngerakines/commitment.
local doc = [[
/commit
Returns a commit message from whatthecommit.com.
]]
local triggers = {
'^/commit[@'..bot.username..']*'
}
local commits = {
"One does not simply merge into master",
"Merging the merge",
"Another bug bites the dust",
"de-misunderestimating",
"Some shit.",
"add actual words",
"I CAN HAZ COMMENTZ.",
"giggle.",
"Whatever.",
"Finished fondling.",
"FONDLED THE CODE",
"this is how we generate our shit.",
"unh",
"It works!",
"unionfind is no longer being molested.",
"Well, it's doing something.",
"I'M PUSHING.",
"Whee.",
"Whee, good night.",
"It'd be nice if type errors caused the compiler to issue a type error",
"Fucking templates.",
"I hate this fucking language.",
"marks",
"that coulda been bad",
"hoo boy",
"It was the best of times, it was the worst of times",
"Fucking egotistical bastard. adds expandtab to vimrc",
"if you're not using et, fuck off",
"WHO THE FUCK CAME UP WITH MAKE?",
"This is a basic implementation that works.",
"By works, I meant 'doesnt work'. Works now..",
"Last time I said it works? I was kidding. Try this.",
"Just stop reading these for a while, ok..",
"Give me a break, it's 2am. But it works now.",
"Make that it works in 90% of the cases. 3:30.",
"Ok, 5am, it works. For real.",
"FOR REAL.",
"I don't know what these changes are supposed to accomplish but somebody told me to make them.",
"I don't get paid enough for this shit.",
"fix some fucking errors",
"first blush",
"So my boss wanted this button ...",
"uhhhhhh",
"forgot we're not using a smart language",
"include shit",
"To those I leave behind, good luck!",
"things occurred",
"i dunno, maybe this works",
"8==========D",
"No changes made",
"whooooooooooooooooooooooooooo",
"clarify further the brokenness of C++. why the fuck are we using C++?",
".",
"Friday 5pm",
"changes",
"A fix I believe, not like I tested or anything",
"Useful text",
"pgsql is being a pain",
"pgsql is more strict, increase the hackiness up to 11",
"c&p fail",
"syntax",
"fix",
"just shoot me",
"arrrggghhhhh fixed!",
"someone fails and it isn't me",
"totally more readable",
"better grepping",
"fix",
"fix bug, for realz",
"fix /sigh",
"Does this work",
"MOAR BIFURCATION",
"bifurcation",
"REALLY FUCKING FIXED",
"FIX",
"better ignores",
"More ignore",
"more ignores",
"more ignores",
"more ignores",
"more ignores",
"more ignores",
"more ignored words",
"more fixes",
"really ignore ignored worsd",
"fixes",
"/sigh",
"fix",
"fail",
"pointless limitation",
"omg what have I done?",
"added super-widget 2.0.",
"tagging release w.t.f.",
"I can't believe it took so long to fix this.",
"I must have been drunk.",
"This is why the cat shouldn't sit on my keyboard.",
"This is why git rebase is a horrible horrible thing.",
"ajax-loader hotness, oh yeah",
"small is a real HTML tag, who knew.",
"WTF is this.",
"Do things better, faster, stronger",
"Use a real JS construct, WTF knows why this works in chromium.",
"Added a banner to the default admin page. Please have mercy on me =(",
"needs more cow bell",
"Switched off unit test X because the build had to go out now and there was no time to fix it properly.",
"Updated",
"I must sleep... it's working... in just three hours...",
"I was wrong...",
"Completed with no bugs...",
"Fixed a little bug...",
"Fixed a bug in NoteLineCount... not seriously...",
"woa!! this one was really HARD!",
"Made it to compile...",
"changed things...",
"touched...",
"i think i fixed a bug...",
"perfect...",
"Moved something to somewhere... goodnight...",
"oops, forgot to add the file",
"Corrected mistakes",
"oops",
"oops!",
"put code that worked where the code that didn't used to be",
"Nothing to see here, move along",
"I am even stupider than I thought",
"I don't know what the hell I was thinking.",
"fixed errors in the previous commit",
"Committed some changes",
"Some bugs fixed",
"Minor updates",
"Added missing file in previous commit",
"bug fix",
"typo",
"bara bra grejjor",
"Continued development...",
"Does anyone read this? I'll be at the coffee shop accross the street.",
"That's just how I roll",
"work in progress",
"minor changes",
"some brief changes",
"assorted changes",
"lots and lots of changes",
"another big bag of changes",
"lots of changes after a lot of time",
"LOTS of changes. period",
"Test commit. Please ignore",
"I'm just a grunt. Don't blame me for this awful PoS.",
"I did it for the lulz!",
"I'll explain this when I'm sober .. or revert it",
"Obligatory placeholder commit message",
"A long time ago, in a galaxy far far away...",
"Fixed the build.",
"various changes",
"One more time, but with feeling.",
"Handled a particular error.",
"Fixed unnecessary bug.",
"Removed code.",
"Added translation.",
"Updated build targets.",
"Refactored configuration.",
"Locating the required gigapixels to render...",
"Spinning up the hamster...",
"Shovelling coal into the server...",
"Programming the flux capacitor",
"The last time I tried this the monkey didn't survive. Let's hope it works better this time.",
"I should have had a V8 this morning.",
"640K ought to be enough for anybody",
"pay no attention to the man behind the curtain",
"a few bits tried to escape, but we caught them",
"Who has two thumbs and remembers the rudiments of his linear algebra courses? Apparently, this guy.",
"workaround for ant being a pile of fail",
"Don't push this commit",
"rats",
"squash me",
"fixed mistaken bug",
"Final commit, ready for tagging",
"-m \'So I hear you like commits ...\'",
"epic",
"need another beer",
"Well the book was obviously wrong.",
"lolwhat?",
"Another commit to keep my CAN streak going.",
"I cannot believe that it took this long to write a test for this.",
"TDD: 1, Me: 0",
"Yes, I was being sarcastic.",
"Apparently works-for-me is a crappy excuse.",
"tl;dr",
"I would rather be playing SC2.",
"Crap. Tonight is raid night and I am already late.",
"I know what I am doing. Trust me.",
"You should have trusted me.",
"Is there an award for this?",
"Is there an achievement for this?",
"I'm totally adding this to epic win. +300",
"This really should not take 19 minutes to build.",
"fixed the israeli-palestinian conflict",
"SHIT ===> GOLD",
"Committing in accordance with the prophecy.",
"It compiles! Ship it!",
"LOL!",
"Reticulating splines...",
"SEXY RUSSIAN CODES WAITING FOR YOU TO CALL",
"s/import/include/",
"extra debug for stuff module",
"debug line test",
"debugo",
"remove debug<br/>all good",
"debug suff",
"more debug... who overwrote!",
"these confounded tests drive me nuts",
"For great justice.",
"QuickFix.",
"oops - thought I got that one.",
"removed echo and die statements, lolz.",
"somebody keeps erasing my changes.",
"doh.",
"pam anderson is going to love me.",
"added security.",
"arrgghh... damn this thing for not working.",
"jobs... steve jobs",
"and a comma",
"this is my quickfix branch and i will use to do my quickfixes",
"Fix my stupidness",
"and so the crazy refactoring process sees the sunlight after some months in the dark!",
"gave up and used tables.",
"[Insert your commit message here. Be sure to make it descriptive.]",
"Removed test case since code didn't pass QA",
"removed tests since i can't make them green",
"stuff",
"more stuff",
"Become a programmer, they said. It'll be fun, they said.",
"Same as last commit with changes",
"foo",
"just checking if git is working properly...",
"fixed some minor stuff, might need some additional work.",
"just trolling the repo",
"All your codebase are belong to us.",
"Somebody set up us the bomb.",
"should work I guess...",
"To be honest, I do not quite remember everything I changed here today. But it is all good, I tell ya.",
"well crap.",
"herpderp (redux)",
"herpderp",
"Derp",
"derpherp",
"Herping the derp",
"sometimes you just herp the derp so hard it herpderps",
"Derp. Fix missing constant post rename",
"Herping the fucking derp right here and now.",
"Derp, asset redirection in dev mode",
"mergederp",
"Derp search/replace fuckup",
"Herpy dooves.",
"Derpy hooves",
"derp, helper method rename",
"Herping the derp derp (silly scoping error)",
"Herp derp I left the debug in there and forgot to reset errors.",
"Reset error count between rows. herpderp",
"hey, what's that over there?!",
"hey, look over there!",
"It worked for me...",
"Does not work.",
"Either Hot Shit or Total Bollocks",
"Arrrrgggg",
"Don’t mess with Voodoo",
"I expected something different.",
"Todo!!!",
"This is supposed to crash",
"No changes after this point.",
"I know, I know, this is not how I’m supposed to do it, but I can't think of something better.",
"Don’t even try to refactor it.",
"(c) Microsoft 1988",
"Please no changes this time.",
"Why The Fuck?",
"We should delete this crap before shipping.",
"Shit code!",
"ALL SORTS OF THINGS",
"Herpderp, shoulda check if it does really compile.",
"I CAN HAZ PYTHON, I CAN HAZ INDENTS",
"Major fixup.",
"less french words",
"breathe, =, breathe",
"IEize",
"this doesn't really make things faster, but I tried",
"this should fix it",
"forgot to save that file",
"Glue. Match sticks. Paper. Build script!",
"Argh! About to give up :(",
"Blaming regex.",
"oops",
"it's friday",
"yo recipes",
"Not sure why",
"lol digg",
"grrrr",
"For real, this time.",
"Feed. You. Stuff. No time.",
"I don't give a damn 'bout my reputation",
"DEAL WITH IT",
"commit",
"tunning",
"I really should've committed this when I finished it...",
"It's getting hard to keep up with the crap I've trashed",
"I honestly wish I could remember what was going on here...",
"I must enjoy torturing myself",
"For the sake of my sanity, just ignore this...",
"That last commit message about silly mistakes pales in comparision to this one",
"My bad",
"Still can't get this right...",
"Nitpicking about alphabetizing methods, minor OCD thing",
"Committing fixes in the dark, seriously, who killed my power!?",
"You can't see it, but I'm making a very angry face right now",
"Fix the fixes",
"It's secret!",
"Commit committed....",
"No time to commit.. My people need me!",
"Something fixed",
"I'm hungry",
"asdfasdfasdfasdfasdfasdfadsf",
"hmmm",
"formatted all",
"Replace all whitespaces with tabs.",
"s/ / /g",
"I'm too foo for this bar",
"Things went wrong...",
"??! what the ...",
"This solves it.",
"Working on tests (haha)",
"fixed conflicts (LOL merge -s ours; push -f)",
"last minute fixes.",
"fuckup.",
"Revert \"fuckup\".",
"should work now.",
"final commit.",
"done. going to bed now.",
"buenas those-things.",
"Your commit is writing checks your merge can't cash.",
"This branch is so dirty, even your mom can't clean it.",
"wip",
"Revert \"just testing, remember to revert\"",
"bla",
"harharhar",
"restored deleted entities just to be sure",
"added some filthy stuff",
"bugger",
"lol",
"oopsie B|",
"Copy pasta fail. still had a instead of a",
"Now added delete for real",
"grmbl",
"move your body every every body",
"Trying to fake a conflict",
"And a commit that I don't know the reason of...",
"ffs",
"that's all folks",
"Fucking submodule bull shit",
"apparently i did something…",
"bump to 0.0.3-dev:wq",
"pep8 - cause I fell like doing a barrel roll",
"pep8 fixer",
"it is hump day _^_",
"happy monday _ bleh _",
"after of this commit remember do a git reset hard",
"someday I gonna kill someone for this shit...",
"magic, have no clue but it works",
"I am sorry",
"dirty hack, have a better idea ?",
"Code was clean until manager requested to fuck it up",
" - Temporary commit.",
":(:(",
"...",
"GIT :/",
"stopped caring 10 commits ago",
"Testing in progress ;)",
"Fixed Bug",
"Fixed errors",
"Push poorly written test can down the road another ten years",
"commented out failing tests",
"I'm human",
"TODO: write meaningful commit message",
"Pig",
"SOAP is a piece of shit",
"did everything",
"project lead is allergic to changes...",
"making this thing actually usable.",
"I was told to leave it alone, but I have this thing called OCD, you see",
"Whatever will be, will be 8{",
"It's 2015; why are we using ColdFusion?!",
"#GrammarNazi",
"Future self, please forgive me and don't hit me with the baseball bat again!",
"Hide those navs, boi!",
"Who knows...",
"Who knows WTF?!",
"I should get a raise for this.",
"Done, to whoever merges this, good luck.",
"Not one conflict, today was a good day.",
"First Blood",
"Fixed the fuck out of #526!",
"I'm too old for this shit!",
"One little whitespace gets its very own commit! Oh, life is so erratic!"
}
local action = function(msg)
sendMessage(msg.chat.id, commits[math.random(#commits)])
end
return {
action = action,
triggers = triggers,
doc = doc
}
| gpl-2.0 |
MohammadPishro/Spam-Detector | plugins/configure.lua | 2 | 1420 | local function do_keyboard_config(chat_id)
local keyboard = {
inline_keyboard = {
{{text = _("🛠 Menu"), callback_data = 'config:menu:'..chat_id}},
{{text = _("⚡️ Antiflood"), callback_data = 'config:antiflood:'..chat_id}},
{{text = _("🌈 Media"), callback_data = 'config:media:'..chat_id}},
}
}
return keyboard
end
local function action(msg, blocks)
if msg.chat.type == 'private' and not msg.cb then return end
local chat_id = msg.target_id or msg.chat.id
local keyboard = do_keyboard_config(chat_id)
if msg.cb then
chat_id = msg.target_id
api.editMessageText(msg.chat.id, msg.message_id, _("_Navigate the keyboard to change the settings_"), keyboard, true)
else
if not roles.is_admin_cached(msg) then return end
local res = api.sendKeyboard(msg.from.id, _("_Navigate the keyboard to change the settings_"), keyboard, true)
if not misc.is_silentmode_on(msg.chat.id) then --send the responde in the group only if the silent mode is off
if res then
api.sendMessage(msg.chat.id, _("_I've sent you the keyboard in private_"), true)
else
misc.sendStartMe(msg, msg.ln)
end
end
end
end
return {
action = action,
triggers = {
config.cmd..'config$',
'^###cb:config:back:'
}
}
| gpl-2.0 |
vzaramel/kong | spec/integration/dao/cassandra/cascade_spec.lua | 2 | 7669 | local spec_helper = require "spec.spec_helpers"
local env = spec_helper.get_env()
local dao_factory = env.dao_factory
dao_factory:load_plugins({"keyauth", "basicauth", "oauth2"})
describe("Cassandra cascade delete", function()
setup(function()
spec_helper.prepare_db()
end)
describe("API -> plugins", function()
local api, untouched_api
setup(function()
local fixtures = spec_helper.insert_fixtures {
api = {
{name = "cascade-delete",
request_host = "mockbin.com",
upstream_url = "http://mockbin.com"},
{name = "untouched-cascade-delete",
request_host = "untouched.com",
upstream_url = "http://mockbin.com"}
},
plugin = {
{name = "key-auth", __api = 1},
{name = "rate-limiting", config = {minute = 6}, __api = 1},
{name = "file-log", config = {path = "/tmp/spec.log"}, __api = 1},
{name = "key-auth", __api = 2}
}
}
api = fixtures.api[1]
untouched_api = fixtures.api[2]
end)
teardown(function()
spec_helper.drop_db()
end)
it("should delete foreign plugins when deleting an API", function()
local ok, err = dao_factory.apis:delete(api)
assert.falsy(err)
assert.True(ok)
-- Make sure we have 0 matches
local results, err = dao_factory.plugins:find_by_keys {
api_id = api.id
}
assert.falsy(err)
assert.equal(0, #results)
-- Make sure the untouched API still has its plugins
results, err = dao_factory.plugins:find_by_keys {
api_id = untouched_api.id
}
assert.falsy(err)
assert.equal(1, #results)
end)
end)
describe("Consumer -> plugins", function()
local consumer, untouched_consumer
setup(function()
local fixtures = spec_helper.insert_fixtures {
api = {
{name = "cascade-delete",
request_host = "mockbin.com",
upstream_url = "http://mockbin.com"}
},
consumer = {
{username = "king kong"},
{username = "untouched consumer"}
},
plugin = {
{name = "rate-limiting", config = {minute = 6}, __api = 1, __consumer = 1},
{name = "response-transformer", __api = 1, __consumer = 1},
{name = "file-log", config = {path = "/tmp/spec.log"}, __api = 1, __consumer = 1},
{name = "request-transformer", __api = 1, __consumer = 2}
}
}
consumer = fixtures.consumer[1]
untouched_consumer = fixtures.consumer[2]
end)
teardown(function()
spec_helper.drop_db()
end)
it("should delete foreign plugins when deleting a Consumer", function()
local ok, err = dao_factory.consumers:delete(consumer)
assert.falsy(err)
assert.True(ok)
local results, err = dao_factory.plugins:find_by_keys {
consumer_id = consumer.id
}
assert.falsy(err)
assert.equal(0, #results)
-- Make sure the untouched Consumer still has its plugin
results, err = dao_factory.plugins:find_by_keys {
consumer_id = untouched_consumer.id
}
assert.falsy(err)
assert.equal(1, #results)
end)
end)
describe("Consumer -> keyauth_credentials", function()
local consumer, untouched_consumer
setup(function()
local fixtures = spec_helper.insert_fixtures {
consumer = {
{username = "cascade_delete_consumer"},
{username = "untouched_consumer"}
},
keyauth_credential = {
{key = "apikey123", __consumer = 1},
{key = "apikey456", __consumer = 2}
}
}
consumer = fixtures.consumer[1]
untouched_consumer = fixtures.consumer[2]
end)
teardown(function()
spec_helper.drop_db()
end)
it("should delete foreign keyauth_credentials when deleting a Consumer", function()
local ok, err = dao_factory.consumers:delete(consumer)
assert.falsy(err)
assert.True(ok)
local results, err = dao_factory.keyauth_credentials:find_by_keys {
consumer_id = consumer.id
}
assert.falsy(err)
assert.equal(0, #results)
results, err = dao_factory.keyauth_credentials:find_by_keys {
consumer_id = untouched_consumer.id
}
assert.falsy(err)
assert.equal(1, #results)
end)
end)
describe("Consumer -> basicauth_credentials", function()
local consumer, untouched_consumer
setup(function()
local fixtures = spec_helper.insert_fixtures {
consumer = {
{username = "cascade_delete_consumer"},
{username = "untouched_consumer"}
},
basicauth_credential = {
{username = "username", password = "password", __consumer = 1},
{username = "username2", password = "password2", __consumer = 2}
}
}
consumer = fixtures.consumer[1]
untouched_consumer = fixtures.consumer[2]
end)
teardown(function()
spec_helper.drop_db()
end)
it("should delete foreign basicauth_credentials when deleting a Consumer", function()
local ok, err = dao_factory.consumers:delete(consumer)
assert.falsy(err)
assert.True(ok)
local results, err = dao_factory.basicauth_credentials:find_by_keys {
consumer_id = consumer.id
}
assert.falsy(err)
assert.equal(0, #results)
results, err = dao_factory.basicauth_credentials:find_by_keys {
consumer_id = untouched_consumer.id
}
assert.falsy(err)
assert.equal(1, #results)
end)
end)
describe("Consumer -> oauth2_credentials -> oauth2_tokens", function()
local consumer, untouched_consumer, credential
setup(function()
local fixtures = spec_helper.insert_fixtures {
consumer = {
{username = "cascade_delete_consumer"},
{username = "untouched_consumer"}
},
oauth2_credential = {
{client_id = "clientid123",
client_secret = "secret123",
redirect_uri = "http://google.com/kong",
name = "testapp",
__consumer = 1},
{client_id = "clientid1232",
client_secret = "secret1232",
redirect_uri = "http://google.com/kong",
name = "testapp",
__consumer = 2}
}
}
consumer = fixtures.consumer[1]
untouched_consumer = fixtures.consumer[2]
credential = fixtures.oauth2_credential[1]
local _, err = dao_factory.oauth2_tokens:insert {
credential_id = credential.id,
authenticated_userid = consumer.id,
expires_in = 100,
scope = "email"
}
assert.falsy(err)
end)
teardown(function()
spec_helper.drop_db()
end)
it("should delete foreign oauth2_credentials and tokens when deleting a Consumer", function()
local ok, err = dao_factory.consumers:delete(consumer)
assert.falsy(err)
assert.True(ok)
local results, err = dao_factory.oauth2_credentials:find_by_keys {
consumer_id = consumer.id
}
assert.falsy(err)
assert.equal(0, #results)
results, err = dao_factory.oauth2_tokens:find_by_keys {
credential_id = credential.id
}
assert.falsy(err)
assert.equal(0, #results)
results, err = dao_factory.oauth2_credentials:find_by_keys {
consumer_id = untouched_consumer.id
}
assert.falsy(err)
assert.equal(1, #results)
end)
end)
end)
| apache-2.0 |
m-creations/openwrt | feeds/luci/build/luadoc/doc.lua | 78 | 3419 | #!/usr/bin/env lua
-------------------------------------------------------------------------------
-- LuaDoc launcher.
-- @release $Id: luadoc.lua.in,v 1.1 2008/02/17 06:42:51 jasonsantos Exp $
-------------------------------------------------------------------------------
--local source = debug.getinfo(1).source or ""
--local mypath = source:match("@(.+)/[^/]+")
--package.path = package.path .. ";" .. mypath .. "/?.lua;" .. mypath .. "/?/init.lua"
require "luadoc.init"
-------------------------------------------------------------------------------
-- Print version number.
local function print_version ()
print (string.format("%s\n%s\n%s",
luadoc._VERSION,
luadoc._DESCRIPTION,
luadoc._COPYRIGHT))
end
-------------------------------------------------------------------------------
-- Print usage message.
local function print_help ()
print ("Usage: "..arg[0]..[[ [options|files]
Generate documentation from files. Available options are:
-d path output directory path
-t path template directory path
-h, --help print this help and exit
--noindexpage do not generate global index page
--nofiles do not generate documentation for files
--nomodules do not generate documentation for modules
--doclet doclet_module doclet module to generate output
--taglet taglet_module taglet module to parse input code
-q, --quiet suppress all normal output
-v, --version print version information]])
end
local function off_messages (arg, i, options)
options.verbose = nil
end
-------------------------------------------------------------------------------
-- Process options. TODO: use getopts.
-- @class table
-- @name OPTIONS
local OPTIONS = {
d = function (arg, i, options)
local dir = arg[i+1]
if string.sub (dir, -2) ~= "/" then
dir = dir..'/'
end
options.output_dir = dir
return 1
end,
t = function (arg, i, options)
local dir = arg[i+1]
if string.sub (dir, -2) ~= "/" then
dir = dir..'/'
end
options.template_dir = dir
return 1
end,
h = print_help,
help = print_help,
q = off_messages,
quiet = off_messages,
v = print_version,
version = print_version,
doclet = function (arg, i, options)
options.doclet = arg[i+1]
return 1
end,
taglet = function (arg, i, options)
options.taglet = arg[i+1]
return 1
end,
}
-------------------------------------------------------------------------------
local function process_options (arg)
local files = {}
local options = require "luadoc.config"
local i = 1
while i <= #arg do
local argi = arg[i]
if string.sub (argi, 1, 1) ~= '-' then
table.insert (files, argi)
else
local opt = string.sub (argi, 2)
if string.sub (opt, 1, 1) == '-' then
opt = string.gsub (opt, "%-", "")
end
if OPTIONS[opt] then
if OPTIONS[opt] (arg, i, options) then
i = i + 1
end
else
options[opt] = 1
end
end
i = i+1
end
return files, options
end
-------------------------------------------------------------------------------
-- Main function. Process command-line parameters and call luadoc processor.
function main (arg)
-- Process options
local argc = #arg
if argc < 1 then
print_help ()
return
end
local files, options = process_options (arg)
return luadoc.main(files, options)
end
main(arg)
| gpl-2.0 |
mehranmix/tel | libs/JSON.lua | 3765 | 34843 | -- -*- coding: utf-8 -*-
--
-- Simple JSON encoding and decoding in pure Lua.
--
-- Copyright 2010-2014 Jeffrey Friedl
-- http://regex.info/blog/
--
-- Latest version: http://regex.info/blog/lua/json
--
-- This code is released under a Creative Commons CC-BY "Attribution" License:
-- http://creativecommons.org/licenses/by/3.0/deed.en_US
--
-- It can be used for any purpose so long as the copyright notice above,
-- the web-page links above, and the 'AUTHOR_NOTE' string below are
-- maintained. Enjoy.
--
local VERSION = 20141223.14 -- version history at end of file
local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-"
--
-- The 'AUTHOR_NOTE' variable exists so that information about the source
-- of the package is maintained even in compiled versions. It's also
-- included in OBJDEF below mostly to quiet warnings about unused variables.
--
local OBJDEF = {
VERSION = VERSION,
AUTHOR_NOTE = AUTHOR_NOTE,
}
--
-- Simple JSON encoding and decoding in pure Lua.
-- http://www.json.org/
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
--
--
--
-- DECODING (from a JSON string to a Lua table)
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- If the JSON text is for an object or an array, e.g.
-- { "what": "books", "count": 3 }
-- or
-- [ "Larry", "Curly", "Moe" ]
--
-- the result is a Lua table, e.g.
-- { what = "books", count = 3 }
-- or
-- { "Larry", "Curly", "Moe" }
--
--
-- The encode and decode routines accept an optional second argument,
-- "etc", which is not used during encoding or decoding, but upon error
-- is passed along to error handlers. It can be of any type (including nil).
--
--
--
-- ERROR HANDLING
--
-- With most errors during decoding, this code calls
--
-- JSON:onDecodeError(message, text, location, etc)
--
-- with a message about the error, and if known, the JSON text being
-- parsed and the byte count where the problem was discovered. You can
-- replace the default JSON:onDecodeError() with your own function.
--
-- The default onDecodeError() merely augments the message with data
-- about the text and the location if known (and if a second 'etc'
-- argument had been provided to decode(), its value is tacked onto the
-- message as well), and then calls JSON.assert(), which itself defaults
-- to Lua's built-in assert(), and can also be overridden.
--
-- For example, in an Adobe Lightroom plugin, you might use something like
--
-- function JSON:onDecodeError(message, text, location, etc)
-- LrErrors.throwUserError("Internal Error: invalid JSON data")
-- end
--
-- or even just
--
-- function JSON.assert(message)
-- LrErrors.throwUserError("Internal Error: " .. message)
-- end
--
-- If JSON:decode() is passed a nil, this is called instead:
--
-- JSON:onDecodeOfNilError(message, nil, nil, etc)
--
-- and if JSON:decode() is passed HTML instead of JSON, this is called:
--
-- JSON:onDecodeOfHTMLError(message, text, nil, etc)
--
-- The use of the fourth 'etc' argument allows stronger coordination
-- between decoding and error reporting, especially when you provide your
-- own error-handling routines. Continuing with the the Adobe Lightroom
-- plugin example:
--
-- function JSON:onDecodeError(message, text, location, etc)
-- local note = "Internal Error: invalid JSON data"
-- if type(etc) = 'table' and etc.photo then
-- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName')
-- end
-- LrErrors.throwUserError(note)
-- end
--
-- :
-- :
--
-- for i, photo in ipairs(photosToProcess) do
-- :
-- :
-- local data = JSON:decode(someJsonText, { photo = photo })
-- :
-- :
-- end
--
--
--
--
--
-- DECODING AND STRICT TYPES
--
-- Because both JSON objects and JSON arrays are converted to Lua tables,
-- it's not normally possible to tell which original JSON type a
-- particular Lua table was derived from, or guarantee decode-encode
-- round-trip equivalency.
--
-- However, if you enable strictTypes, e.g.
--
-- JSON = assert(loadfile "JSON.lua")() --load the routines
-- JSON.strictTypes = true
--
-- then the Lua table resulting from the decoding of a JSON object or
-- JSON array is marked via Lua metatable, so that when re-encoded with
-- JSON:encode() it ends up as the appropriate JSON type.
--
-- (This is not the default because other routines may not work well with
-- tables that have a metatable set, for example, Lightroom API calls.)
--
--
-- ENCODING (from a lua table to a JSON string)
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
-- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false })
--
-- On error during encoding, this code calls:
--
-- JSON:onEncodeError(message, etc)
--
-- which you can override in your local JSON object.
--
-- The 'etc' in the error call is the second argument to encode()
-- and encode_pretty(), or nil if it wasn't provided.
--
--
-- PRETTY-PRINTING
--
-- An optional third argument, a table of options, allows a bit of
-- configuration about how the encoding takes place:
--
-- pretty = JSON:encode(val, etc, {
-- pretty = true, -- if false, no other options matter
-- indent = " ", -- this provides for a three-space indent per nesting level
-- align_keys = false, -- see below
-- })
--
-- encode() and encode_pretty() are identical except that encode_pretty()
-- provides a default options table if none given in the call:
--
-- { pretty = true, align_keys = false, indent = " " }
--
-- For example, if
--
-- JSON:encode(data)
--
-- produces:
--
-- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11}
--
-- then
--
-- JSON:encode_pretty(data)
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- The following three lines return identical results:
-- JSON:encode_pretty(data)
-- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " })
-- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " })
--
-- An example of setting your own indent string:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " })
--
-- produces:
--
-- {
-- | "city": "Kyoto",
-- | "climate": {
-- | | "avg_temp": 16,
-- | | "humidity": "high",
-- | | "snowfall": "minimal"
-- | },
-- | "country": "Japan",
-- | "wards": 11
-- }
--
-- An example of setting align_keys to true:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true })
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- which I must admit is kinda ugly, sorry. This was the default for
-- encode_pretty() prior to version 20141223.14.
--
--
-- AMBIGUOUS SITUATIONS DURING THE ENCODING
--
-- During the encode, if a Lua table being encoded contains both string
-- and numeric keys, it fits neither JSON's idea of an object, nor its
-- idea of an array. To get around this, when any string key exists (or
-- when non-positive numeric keys exist), numeric keys are converted to
-- strings.
--
-- For example,
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- produces the JSON object
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To prohibit this conversion and instead make it an error condition, set
-- JSON.noKeyConversion = true
--
--
-- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT
--
-- assert
-- onDecodeError
-- onDecodeOfNilError
-- onDecodeOfHTMLError
-- onEncodeError
--
-- If you want to create a separate Lua JSON object with its own error handlers,
-- you can reload JSON.lua or use the :new() method.
--
---------------------------------------------------------------------------
local default_pretty_indent = " "
local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent }
local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray
local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject
function OBJDEF:newArray(tbl)
return setmetatable(tbl or {}, isArray)
end
function OBJDEF:newObject(tbl)
return setmetatable(tbl or {}, isObject)
end
local function unicode_codepoint_as_utf8(codepoint)
--
-- codepoint is a number
--
if codepoint <= 127 then
return string.char(codepoint)
elseif codepoint <= 2047 then
--
-- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8
--
local highpart = math.floor(codepoint / 0x40)
local lowpart = codepoint - (0x40 * highpart)
return string.char(0xC0 + highpart,
0x80 + lowpart)
elseif codepoint <= 65535 then
--
-- 1110yyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x1000)
local remainder = codepoint - 0x1000 * highpart
local midpart = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midpart
highpart = 0xE0 + highpart
midpart = 0x80 + midpart
lowpart = 0x80 + lowpart
--
-- Check for an invalid character (thanks Andy R. at Adobe).
-- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070
--
if ( highpart == 0xE0 and midpart < 0xA0 ) or
( highpart == 0xED and midpart > 0x9F ) or
( highpart == 0xF0 and midpart < 0x90 ) or
( highpart == 0xF4 and midpart > 0x8F )
then
return "?"
else
return string.char(highpart,
midpart,
lowpart)
end
else
--
-- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x40000)
local remainder = codepoint - 0x40000 * highpart
local midA = math.floor(remainder / 0x1000)
remainder = remainder - 0x1000 * midA
local midB = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midB
return string.char(0xF0 + highpart,
0x80 + midA,
0x80 + midB,
0x80 + lowpart)
end
end
function OBJDEF:onDecodeError(message, text, location, etc)
if text then
if location then
message = string.format("%s at char %d of: %s", message, location, text)
else
message = string.format("%s: %s", message, text)
end
end
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError
OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError
function OBJDEF:onEncodeError(message, etc)
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
local function grok_number(self, text, start, etc)
--
-- Grab the integer part
--
local integer_part = text:match('^-?[1-9]%d*', start)
or text:match("^-?0", start)
if not integer_part then
self:onDecodeError("expected number", text, start, etc)
end
local i = start + integer_part:len()
--
-- Grab an optional decimal part
--
local decimal_part = text:match('^%.%d+', i) or ""
i = i + decimal_part:len()
--
-- Grab an optional exponential part
--
local exponent_part = text:match('^[eE][-+]?%d+', i) or ""
i = i + exponent_part:len()
local full_number_text = integer_part .. decimal_part .. exponent_part
local as_number = tonumber(full_number_text)
if not as_number then
self:onDecodeError("bad number", text, start, etc)
end
return as_number, i
end
local function grok_string(self, text, start, etc)
if text:sub(start,start) ~= '"' then
self:onDecodeError("expected string's opening quote", text, start, etc)
end
local i = start + 1 -- +1 to bypass the initial quote
local text_len = text:len()
local VALUE = ""
while i <= text_len do
local c = text:sub(i,i)
if c == '"' then
return VALUE, i + 1
end
if c ~= '\\' then
VALUE = VALUE .. c
i = i + 1
elseif text:match('^\\b', i) then
VALUE = VALUE .. "\b"
i = i + 2
elseif text:match('^\\f', i) then
VALUE = VALUE .. "\f"
i = i + 2
elseif text:match('^\\n', i) then
VALUE = VALUE .. "\n"
i = i + 2
elseif text:match('^\\r', i) then
VALUE = VALUE .. "\r"
i = i + 2
elseif text:match('^\\t', i) then
VALUE = VALUE .. "\t"
i = i + 2
else
local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if hex then
i = i + 6 -- bypass what we just read
-- We have a Unicode codepoint. It could be standalone, or if in the proper range and
-- followed by another in a specific range, it'll be a two-code surrogate pair.
local codepoint = tonumber(hex, 16)
if codepoint >= 0xD800 and codepoint <= 0xDBFF then
-- it's a hi surrogate... see whether we have a following low
local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if lo_surrogate then
i = i + 6 -- bypass the low surrogate we just read
codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16)
else
-- not a proper low, so we'll just leave the first codepoint as is and spit it out.
end
end
VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint)
else
-- just pass through what's escaped
VALUE = VALUE .. text:match('^\\(.)', i)
i = i + 2
end
end
end
self:onDecodeError("unclosed string", text, start, etc)
end
local function skip_whitespace(text, start)
local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2
if match_end then
return match_end + 1
else
return start
end
end
local grok_one -- assigned later
local function grok_object(self, text, start, etc)
if text:sub(start,start) ~= '{' then
self:onDecodeError("expected '{'", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '{'
local VALUE = self.strictTypes and self:newObject { } or { }
if text:sub(i,i) == '}' then
return VALUE, i + 1
end
local text_len = text:len()
while i <= text_len do
local key, new_i = grok_string(self, text, i, etc)
i = skip_whitespace(text, new_i)
if text:sub(i, i) ~= ':' then
self:onDecodeError("expected colon", text, i, etc)
end
i = skip_whitespace(text, i + 1)
local new_val, new_i = grok_one(self, text, i)
VALUE[key] = new_val
--
-- Expect now either '}' to end things, or a ',' to allow us to continue.
--
i = skip_whitespace(text, new_i)
local c = text:sub(i,i)
if c == '}' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '}'", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '{'", text, start, etc)
end
local function grok_array(self, text, start, etc)
if text:sub(start,start) ~= '[' then
self:onDecodeError("expected '['", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '['
local VALUE = self.strictTypes and self:newArray { } or { }
if text:sub(i,i) == ']' then
return VALUE, i + 1
end
local VALUE_INDEX = 1
local text_len = text:len()
while i <= text_len do
local val, new_i = grok_one(self, text, i)
-- can't table.insert(VALUE, val) here because it's a no-op if val is nil
VALUE[VALUE_INDEX] = val
VALUE_INDEX = VALUE_INDEX + 1
i = skip_whitespace(text, new_i)
--
-- Expect now either ']' to end things, or a ',' to allow us to continue.
--
local c = text:sub(i,i)
if c == ']' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '['", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '['", text, start, etc)
end
grok_one = function(self, text, start, etc)
-- Skip any whitespace
start = skip_whitespace(text, start)
if start > text:len() then
self:onDecodeError("unexpected end of string", text, nil, etc)
end
if text:find('^"', start) then
return grok_string(self, text, start, etc)
elseif text:find('^[-0123456789 ]', start) then
return grok_number(self, text, start, etc)
elseif text:find('^%{', start) then
return grok_object(self, text, start, etc)
elseif text:find('^%[', start) then
return grok_array(self, text, start, etc)
elseif text:find('^true', start) then
return true, start + 4
elseif text:find('^false', start) then
return false, start + 5
elseif text:find('^null', start) then
return nil, start + 4
else
self:onDecodeError("can't parse JSON", text, start, etc)
end
end
function OBJDEF:decode(text, etc)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc)
end
if text == nil then
self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc)
elseif type(text) ~= 'string' then
self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc)
end
if text:match('^%s*$') then
return nil
end
if text:match('^%s*<') then
-- Can't be JSON... we'll assume it's HTML
self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc)
end
--
-- Ensure that it's not UTF-32 or UTF-16.
-- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3),
-- but this package can't handle them.
--
if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then
self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc)
end
local success, value = pcall(grok_one, self, text, 1, etc)
if success then
return value
else
-- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert.
if self.assert then
self.assert(false, value)
else
assert(false, value)
end
-- and if we're still here, return a nil and throw the error message on as a second arg
return nil, value
end
end
local function backslash_replacement_function(c)
if c == "\n" then
return "\\n"
elseif c == "\r" then
return "\\r"
elseif c == "\t" then
return "\\t"
elseif c == "\b" then
return "\\b"
elseif c == "\f" then
return "\\f"
elseif c == '"' then
return '\\"'
elseif c == '\\' then
return '\\\\'
else
return string.format("\\u%04x", c:byte())
end
end
local chars_to_be_escaped_in_JSON_string
= '['
.. '"' -- class sub-pattern to match a double quote
.. '%\\' -- class sub-pattern to match a backslash
.. '%z' -- class sub-pattern to match a null
.. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters
.. ']'
local function json_string_literal(value)
local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function)
return '"' .. newval .. '"'
end
local function object_or_array(self, T, etc)
--
-- We need to inspect all the keys... if there are any strings, we'll convert to a JSON
-- object. If there are only numbers, it's a JSON array.
--
-- If we'll be converting to a JSON object, we'll want to sort the keys so that the
-- end result is deterministic.
--
local string_keys = { }
local number_keys = { }
local number_keys_must_be_strings = false
local maximum_number_key
for key in pairs(T) do
if type(key) == 'string' then
table.insert(string_keys, key)
elseif type(key) == 'number' then
table.insert(number_keys, key)
if key <= 0 or key >= math.huge then
number_keys_must_be_strings = true
elseif not maximum_number_key or key > maximum_number_key then
maximum_number_key = key
end
else
self:onEncodeError("can't encode table with a key of type " .. type(key), etc)
end
end
if #string_keys == 0 and not number_keys_must_be_strings then
--
-- An empty table, or a numeric-only array
--
if #number_keys > 0 then
return nil, maximum_number_key -- an array
elseif tostring(T) == "JSON array" then
return nil
elseif tostring(T) == "JSON object" then
return { }
else
-- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects
return nil
end
end
table.sort(string_keys)
local map
if #number_keys > 0 then
--
-- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array
-- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object.
--
if self.noKeyConversion then
self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc)
end
--
-- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings
--
map = { }
for key, val in pairs(T) do
map[key] = val
end
table.sort(number_keys)
--
-- Throw numeric keys in there as strings
--
for _, number_key in ipairs(number_keys) do
local string_key = tostring(number_key)
if map[string_key] == nil then
table.insert(string_keys , string_key)
map[string_key] = T[number_key]
else
self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc)
end
end
end
return string_keys, nil, map
end
--
-- Encode
--
-- 'options' is nil, or a table with possible keys:
-- pretty -- if true, return a pretty-printed version
-- indent -- a string (usually of spaces) used to indent each nested level
-- align_keys -- if true, align all the keys when formatting a table
--
local encode_value -- must predeclare because it calls itself
function encode_value(self, value, parents, etc, options, indent)
if value == nil then
return 'null'
elseif type(value) == 'string' then
return json_string_literal(value)
elseif type(value) == 'number' then
if value ~= value then
--
-- NaN (Not a Number).
-- JSON has no NaN, so we have to fudge the best we can. This should really be a package option.
--
return "null"
elseif value >= math.huge then
--
-- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should
-- really be a package option. Note: at least with some implementations, positive infinity
-- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is.
-- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">="
-- case first.
--
return "1e+9999"
elseif value <= -math.huge then
--
-- Negative infinity.
-- JSON has no INF, so we have to fudge the best we can. This should really be a package option.
--
return "-1e+9999"
else
return tostring(value)
end
elseif type(value) == 'boolean' then
return tostring(value)
elseif type(value) ~= 'table' then
self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc)
else
--
-- A table to be converted to either a JSON object or array.
--
local T = value
if type(options) ~= 'table' then
options = {}
end
if type(indent) ~= 'string' then
indent = ""
end
if parents[T] then
self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc)
else
parents[T] = true
end
local result_value
local object_keys, maximum_number_key, map = object_or_array(self, T, etc)
if maximum_number_key then
--
-- An array...
--
local ITEMS = { }
for i = 1, maximum_number_key do
table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent))
end
if options.pretty then
result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]"
else
result_value = "[" .. table.concat(ITEMS, ",") .. "]"
end
elseif object_keys then
--
-- An object
--
local TT = map or T
if options.pretty then
local KEYS = { }
local max_key_length = 0
for _, key in ipairs(object_keys) do
local encoded = encode_value(self, tostring(key), parents, etc, options, indent)
if options.align_keys then
max_key_length = math.max(max_key_length, #encoded)
end
table.insert(KEYS, encoded)
end
local key_indent = indent .. tostring(options.indent or "")
local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "")
local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s"
local COMBINED_PARTS = { }
for i, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent)
table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val))
end
result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}"
else
local PARTS = { }
for _, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, indent)
local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent)
table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val))
end
result_value = "{" .. table.concat(PARTS, ",") .. "}"
end
else
--
-- An empty array/object... we'll treat it as an array, though it should really be an option
--
result_value = "[]"
end
parents[T] = false
return result_value
end
end
function OBJDEF:encode(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or nil)
end
function OBJDEF:encode_pretty(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or default_pretty_options)
end
function OBJDEF.__tostring()
return "JSON encode/decode package"
end
OBJDEF.__index = OBJDEF
function OBJDEF:new(args)
local new = { }
if args then
for key, val in pairs(args) do
new[key] = val
end
end
return setmetatable(new, OBJDEF)
end
return OBJDEF:new()
--
-- Version history:
--
-- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really
-- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines
-- more flexible, and changed the default encode_pretty() to be more generally useful.
--
-- Added a third 'options' argument to the encode() and encode_pretty() routines, to control
-- how the encoding takes place.
--
-- Updated docs to add assert() call to the loadfile() line, just as good practice so that
-- if there is a problem loading JSON.lua, the appropriate error message will percolate up.
--
-- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string,
-- so that the source of the package, and its version number, are visible in compiled copies.
--
-- 20140911.12 Minor lua cleanup.
-- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'.
-- (Thanks to SmugMug's David Parry for these.)
--
-- 20140418.11 JSON nulls embedded within an array were being ignored, such that
-- ["1",null,null,null,null,null,"seven"],
-- would return
-- {1,"seven"}
-- It's now fixed to properly return
-- {1, nil, nil, nil, nil, nil, "seven"}
-- Thanks to "haddock" for catching the error.
--
-- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up.
--
-- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2",
-- and this caused some problems.
--
-- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate,
-- and had of course diverged (encode_pretty didn't get the fixes that encode got, so
-- sometimes produced incorrect results; thanks to Mattie for the heads up).
--
-- Handle encoding tables with non-positive numeric keys (unlikely, but possible).
--
-- If a table has both numeric and string keys, or its numeric keys are inappropriate
-- (such as being non-positive or infinite), the numeric keys are turned into
-- string keys appropriate for a JSON object. So, as before,
-- JSON:encode({ "one", "two", "three" })
-- produces the array
-- ["one","two","three"]
-- but now something with mixed key types like
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- instead of throwing an error produces an object:
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To maintain the prior throw-an-error semantics, set
-- JSON.noKeyConversion = true
--
-- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry.
--
-- 20130120.6 Comment update: added a link to the specific page on my blog where this code can
-- be found, so that folks who come across the code outside of my blog can find updates
-- more easily.
--
-- 20111207.5 Added support for the 'etc' arguments, for better error reporting.
--
-- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent.
--
-- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules:
--
-- * When encoding lua for JSON, Sparse numeric arrays are now handled by
-- spitting out full arrays, such that
-- JSON:encode({"one", "two", [10] = "ten"})
-- returns
-- ["one","two",null,null,null,null,null,null,null,"ten"]
--
-- In 20100810.2 and earlier, only up to the first non-null value would have been retained.
--
-- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999".
-- Version 20100810.2 and earlier created invalid JSON in both cases.
--
-- * Unicode surrogate pairs are now detected when decoding JSON.
--
-- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding
--
-- 20100731.1 initial public release
--
| gpl-3.0 |
paulmarsy/Console | Libraries/nmap/App/nselib/mongodb.lua | 2 | 22926 | ---
-- Library methods for handling MongoDB, creating and parsing packets.
--
-- @author Martin Holst Swende
-- @copyright Same as Nmap--See http://nmap.org/book/man-legal.html
--
-- Version 0.2
--
-- @args mongodb.db - the database to use for authentication
-- Created 01/13/2010 - v0.1 - created by Martin Holst Swende <martin@swende.se>
-- Revised 01/03/2012 - v0.2 - added authentication support <patrik@cqure.net>
local bin = require "bin"
local nmap = require "nmap"
local stdnse = require "stdnse"
local string = require "string"
local table = require "table"
local openssl = stdnse.silent_require "openssl"
_ENV = stdnse.module("mongodb", stdnse.seeall)
-- this is not yet widely implemented but at least used for authentication
-- ideally, it would be used to set the database against which operations,
-- that do not require a specific database, should run
local arg_DB = stdnse.get_script_args("mongodb.db")
-- Some lazy shortcuts
local function dbg(str,...)
stdnse.debug3("MngoDb:"..str, ...)
end
--local dbg =stdnse.debug1
local err =stdnse.debug1
----------------------------------------------------------------------
-- First of all comes a Bson parsing library. This can easily be moved out into a separate library should other
-- services start to use Bson
----------------------------------------------------------------------
-- Library methods for handling the BSON format
--
-- For more documentation about the BSON format,
---and more details about its implementations, check out the
-- python BSON implementation which is available at
-- http://github.com/mongodb/mongo-python-driver/blob/master/pymongo/bson.py
-- and licensed under the Apache License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0)
--
-- @author Martin Holst Swende
-- @copyright Same as Nmap--See http://nmap.org/book/man-legal.html
--
-- Version 0.1
-- Created 01/13/2010 - v0.1 - created by Martin Holst Swende <martin@swende.se>
--module("bson", package.seeall)
--require("bin")
local function dbg_err(str,...)
stdnse.debug1("Bson-ERR:"..str, ...)
end
--local err =stdnse.log_error
-- Packs data into nullterminated string
--@param input the string to pack
--@return the packed nullterminated string
local function make_nullterminated_string(input)
return bin.pack("z",input)
end
--Converts an element (key, value) into bson binary data
--@param key the key name, must *NOT* contain . (period) or start with $
--@param value, the element value
--@return status : true if ok, false if error
--@return result : the packed binary data OR error message
local function _element_to_bson(key, value)
--Some constraints-checking
if type(key) ~= 'string' then
return false, "Documents must have only string keys, key was " .. type(key)
end
if key:sub(1,1) == "$" then
return false, "key must not start with $: ".. key
end
if key:find("%.") then
return false, ("key %r must not contain '.'"):format(tostring(key))
end
local name =bin.pack("z",key) -- null-terminated string
if type(value) == 'string' then
local cstring = bin.pack("z",value) -- null-terminated string
local length = bin.pack("<i", cstring:len())
local op = "\x02"
return true, op .. name .. length .. cstring
elseif type(value) =='table' then
return true, "\x02" .. name .. toBson(value)
elseif type(value)== 'boolean' then
return true, "\x08" .. name .. (value and '\x01' or '\0')
elseif type(value) == 'number' then
--return "\x10" .. name .. bin.pack("<i", value)
-- Use 01 - double for - works better than 10
return true, '\x01' .. name .. bin.pack("<d", value)
end
local _ = ("cannot convert value of type %s to bson"):format(type(value))
return false, _
end
--Converts a table of elements to binary bson format
--@param dict the table
--@return status : true if ok, false if error
--@return result : a string of binary data OR error message
function toBson(dict)
local elements = ""
--Put id first
if dict._id then
local status,res = _element_to_bson("_id", dict._id)
if not status then return false, res end
elements = elements..res
elseif ( dict._cmd ) then
for k, v in pairs(dict._cmd) do
local status,res = _element_to_bson(k, v)
if not status then return false, res end
elements = elements..res
end
end
--Concatenate binary values
for key, value in pairs( dict ) do
if key ~= "_id" and key ~= "_cmd" then
dbg("dictionary to bson : key,value =(%s,%s)",key,value)
local status,res = _element_to_bson(key,value)
if not status then return false, res end
elements = elements..res
end
end
-- Get length
local length = #elements + 5
if length > 4 * 1024 * 1024 then
return false, "document too large - BSON documents are limited to 4 MB"
end
dbg("Packet length is %d",length)
--Final pack
return true, bin.pack("I", length) .. elements .. "\0"
end
-- Reads a null-terminated string. If length is supplied, it is just cut
-- out from the data, otherwise the data is scanned for at null-char.
--@param data the data which starts with a c-string
--@param length optional length of the string
--@return the string
--@return the remaining data (*without* null-char)
local function get_c_string(data,length)
if not length then
local index = data:find('\0')
if index == nil then
error({code="C-string did not contain NULL char"})
end
length = index
end
local value = data:sub(1,length-1)
--dbg("Found char at pos %d, data is %s c-string is %s",length, data, value)
return value, data:sub(length+1)
end
-- Element parser. Parse data elements
-- @param data String containing binary data
-- @return Position in the data string where parsing stopped
-- @return Unpacked value
-- @return error string if error occurred
local function parse(code,data)
if 1 == code then -- double
return bin.unpack("<d", data)
elseif 2 == code then -- string
-- data length = first four bytes
local _,len = bin.unpack("<i",data)
-- string data = data[5] -->
local value = get_c_string(data:sub(5), len)
-- Count position as header (=4) + length of string (=len)+ null char (=1)
return 4+len+1,value
elseif 3 == code or 4 == code then -- table or array
local object, err
-- Need to know the length, to return later
local _,obj_size = bin.unpack("<i", data)
-- Now, get the data object
dbg("Recursing into bson array")
object, data, err = fromBson(data)
dbg("Recurse finished, got data object")
-- And return where the parsing stopped
return obj_size+1, object
--6 = _get_null
--7 = _get_oid
elseif 8 == code then -- Boolean
return 2, data:byte(1) == 1
elseif 9 == code then -- int64, UTC datetime
return bin.unpack("<l", data)
elseif 10 == code then -- nullvalue
return 0,nil
--11= _get_regex
--12= _get_ref
--13= _get_string, # code
--14= _get_string, # symbol
--15= _get_code_w_scope
elseif 16 == code then -- 4 byte integer
return bin.unpack("<i", data)
--17= _get_timestamp
elseif 18 == code then -- long
return bin.unpack("<l", data)
end
local err = ("Getter for %d not implemented"):format(code)
return 0, data, err
end
-- Reads an element from binary to BSon
--@param data a string of data to convert
--@return Name of the element
--@return Value of the element
--@return Residual data not used
--@return any error that occurred
local function _element_to_dict(data)
local element_type, element_name, err, pos, value
--local element_size = data:byte(1)
element_type = data:byte(1)
element_name, data = get_c_string(data:sub(2))
dbg(" Read element name '%s' (type:%s), data left: %d",element_name, element_type,data:len())
--pos,value,err = parsers.get(element_type)(data)
pos,value,err = parse(element_type,data)
if(err ~= nil) then
dbg_err(err)
return nil,nil, data, err
end
data=data:sub(pos)
dbg(" Read element value '%s', data left: %d",tostring(value), data:len())
return element_name, value, data
end
--Reads all elements from binary to BSon
--@param data the data to read from
--@return the resulting table
local function _elements_to_dict(data)
local result = {}
local key,value
while data and data:len() > 1 do
key, value, data = _element_to_dict(data)
dbg("Parsed (%s='%s'), data left : %d", tostring(key),tostring(value), data:len())
if type(value) ~= 'table' then value=tostring(value) end
result[key] = value
end
return result
end
--Checks if enough data to parse the result is captured
--@data binary bson data read from socket
--@return true if the full bson table is contained in the data, false if data is incomplete
--@return required size of packet, if known, otherwise nil
function isPacketComplete(data)
-- First, we check that the header is complete
if data:len() < 4 then
local err_msg = "Not enough data in buffer, at least 4 bytes header info expected"
return false
end
local _,obj_size = bin.unpack("<i", data)
dbg("BSon packet size is %s", obj_size)
-- Check that all data is read and the packet is complete
if data:len() < obj_size then
return false,obj_size
end
return true,obj_size
end
-- Converts bson binary data read from socket into a table
-- of elements
--@param data: binary data
--@return table containing elements
--@return remaining data
--@return error message if not enough data was in packet
function fromBson(data)
dbg("Decoding, got %s bytes of data", data:len())
local complete, object_size = isPacketComplete(data)
if not complete then
local err_msg = ("Not enough data in buffer, expected %s but only has %d"):format(object_size or "?", data:len())
dbg(err_msg)
return {},data, err_msg
end
local element_portion = data:sub(5,object_size)
local remainder = data:sub(object_size+1)
return _elements_to_dict(element_portion), remainder
end
----------------------------------------------------------------------------------
-- Test-code for debugging purposes below
----------------------------------------------------------------------------------
function testBson()
local p = toBson({hello="world", test="ok"})
print( "Encoded something ok")
local orig = fromBson(p)
print(" Decoded something else ok")
for i,v in pairs(orig) do
print(i,v)
end
end
--testBson()
--------------------------------------------------------------------------------------------------------------
--- END of BSON part
--------------------------------------------------------------------------------------------------------------
--[[ MongoDB wire protocol format
Standard message header :
struct {
int32 messageLength; // total size of the message, including the 4 bytes of length
int32 requestID; // client or database-generated identifier for this message
int32 responseTo; // requestID from the original request (used in responses from db)
int32 opCode; // request type - see table below
}
Opcodes :
OP_REPLY 1 Reply to a client request. responseTo is set
OP_MSG 1000 generic msg command followed by a string
OP_UPDATE 2001 update document
OP_INSERT 2002 insert new document
OP_GET_BY_OID 2003 is this used?
OP_QUERY 2004 query a collection
OP_GET_MORE 2005 Get more data from a query. See Cursors
OP_DELETE 2006 Delete documents
OP_KILL_CURSORS 2007 Tell database client is done with a cursor
Query message :
struct {
MsgHeader header; // standard message header
int32 opts; // query options. See below for details.
cstring fullCollectionName; // "dbname.collectionname"
int32 numberToSkip; // number of documents to skip when returning results
int32 numberToReturn; // number of documents to return in the first OP_REPLY
BSON query ; // query object. See below for details.
[ BSON returnFieldSelector; ] // OPTIONAL : selector indicating the fields to return. See below for details.
}
For more info about the MongoDB wire protocol, see http://www.mongodb.org/display/DOCS/Mongo+Wire+Protocol
--]]
-- DIY lua-class to create Mongo packets
--@usage call MongoData:new({opCode=MongoData.OP.QUERY}) to create query object
MongoData ={
uniqueRequestId = 12345,
-- Opcodes used by Mongo db
OP = {
REPLY = 1,
MSG = 1000,
UPDATE = 2001,
INSERT = 2002,
GET_BY_IOD = 2003,
QUERY = 2004,
GET_MORE = 2005,
DELETE = 2006,
KILL_CURSORS = 2007,
},
-- Lua-DIY constructor
new = function (self,o,opCode,responseTo)
o = o or {} -- create object if user does not provide one
setmetatable(o, self) -- DIY inheritance a'la javascript
self.__index = self
self.valueString = ''
self.requestID = MongoData.uniqueRequestId -- Create unique id for message
MongoData.uniqueRequestId = MongoData.uniqueRequestId +1
return o
end
}
--Adds unsigned int32 to the message body
--@param value the value to add
function MongoData:addUnsignedInt32(value)
self.valueString = self.valueString..bin.pack("I",value)
end
-- Adds a string to the message body
--@param value the string to add
function MongoData:addString(value)
self.valueString = self.valueString..bin.pack('z',value)
end
-- Add a table as a BSon object to the body
--@param dict the table to be converted to BSon
--@return status : true if ok, false if error occurred
--@return Error message if error occurred
function MongoData:addBSON(dict)
-- status, res = bson.toBson(dict)
local status, res = toBson(dict)
if not status then
dbg(res)
return status,res
end
self.valueString = self.valueString..res
return true
end
-- Returns the data in this packet in a raw string format to be sent on socket
-- This method creates necessary header information and puts it with the body
function MongoData:data()
local header = MongoData:new()
header:addUnsignedInt32( self.valueString:len()+4+4+4+4)
header:addUnsignedInt32( self.requestID)
header:addUnsignedInt32( self.responseTo or 0xFFFFFFFF)
header:addUnsignedInt32( self.opCode)
return header.valueString .. self.valueString
end
-- Creates a query
-- @param collectionName string specifying the collection to run query against
-- @param a table containing the query
--@return status : true for OK, false for error
--@return packet data OR error message
local function createQuery(collectionName, query)
local packet = MongoData:new({opCode=MongoData.OP.QUERY})
packet:addUnsignedInt32(0); -- options
packet:addString(collectionName);
packet:addUnsignedInt32(0) -- number to skip
packet:addUnsignedInt32(-1) -- number to return : no limit
local status, error = packet:addBSON(query)
if not status then
return status, error
end
return true, packet:data()
end
-- Creates a get last error query
-- @param responseTo optional identifier this packet is a response to
--@return status : true for OK, false for error
--@return packet data OR error message
function lastErrorQuery(responseTo)
local collectionName = "test.$cmd"
local query = {getlasterror=1}
return createQuery(collectionName, query)
end
-- Creates a server status query
-- @param responseTo optional identifier this packet is a response to
--@return status : true for OK, false for error
--@return packet data OR error message
function serverStatusQuery(responseTo)
local collectionName = "test.$cmd"
local query = {serverStatus = 1}
return createQuery(collectionName, query)
end
-- Creates a optime query
-- @param responseTo optional identifier this packet is a response to
--@return status : true for OK, false for error
--@return packet data OR error message
function opTimeQuery(responseTo)
local collectionName = "test.$cmd"
local query = {getoptime = 1}
return createQuery(collectionName, query)
end
-- Creates a list databases query
-- @param responseTo optional identifier this packet is a response to
--@return status : true for OK, false for error
--@return packet data OR error message
function listDbQuery(responseTo)
local collectionName = "admin.$cmd"
local query = {listDatabases = 1}
return createQuery(collectionName, query)
end
-- Creates a build info query
-- @param responseTo optional identifier this packet is a response to
--@return status : true for OK, false for error
--@return packet data OR error message
--@return status : true for OK, false for error
--@return packet data OR error message
function buildInfoQuery(responseTo)
local collectionName = "admin.$cmd"
local query = {buildinfo = 1}
return createQuery(collectionName, query)
end
--Reads an int32 from data
--@return int32 value
--@return data unread
local function parseInt32(data)
local pos,val = bin.unpack("<i",data)
return val, data:sub(pos)
end
local function parseInt64(data)
local pos,val = bin.unpack("<l",data)
return val, data:sub(pos)
end
-- Parses response header
-- The response header looks like this :
--[[
struct {
MsgHeader header; // standard message header
int32 responseFlag; // normally zero, non-zero on query failure
int64 cursorID; // id of the cursor created for this query response
int32 startingFrom; // indicates where in the cursor this reply is starting
int32 numberReturned; // number of documents in the reply
BSON[] documents; // documents
}
--]]
--@param the data from socket
--@return a table containing the header data
local function parseResponseHeader(data)
local response= {}
local hdr, rflag, cID, sfrom, nRet, docs
-- First std message header
hdr ={}
hdr["messageLength"], data = parseInt32(data)
hdr["requestID"], data = parseInt32(data)
hdr["responseTo"], data = parseInt32(data)
hdr["opCode"], data = parseInt32(data)
response["header"] = hdr
-- Some additional fields
response["responseFlag"] ,data = parseInt32(data)
response["cursorID"] ,data = parseInt64(data)
response["startingFrom"] ,data = parseInt32(data)
response["numberReturned"] ,data = parseInt32(data)
response["bson"] = data
return response
end
--Checks if enough data to parse the result is captured
--@data binary mongodb data read from socket
--@return true if the full mongodb packet is contained in the data, false if data is incomplete
--@return required size of packet, if known, otherwise nil
function isPacketComplete(data)
-- First, we check that the header is complete
if data:len() < 4 then
local err_msg = "Not enough data in buffer, at least 4 bytes header info expected"
return false
end
local _,obj_size = bin.unpack("<i", data)
dbg("MongoDb Packet size is %s, (got %d)", obj_size,data:len())
-- Check that all data is read and the packet is complete
if data:len() < obj_size then
return false,obj_size
end
return true,obj_size
end
-- Sends a packet over a socket, reads the response
-- and parses it into a table
--@return status : true if ok; false if bad
--@return result : table of status ok, error msg if bad
--@return if status ok : remaining data read from socket but not used
function query(socket, data)
--Create an error handler
local catch = function()
socket:close()
stdnse.debug1("Query failed")
end
local try = nmap.new_try(catch)
try( socket:send( data ) )
local data = ""
local result = {}
local err_msg
local isComplete, pSize
while not isComplete do
dbg("mongo: waiting for data from socket, got %d bytes so far...",data:len())
data = data .. try( socket:receive() )
isComplete, pSize = isPacketComplete(data)
end
-- All required data should be read now
local packetData = data:sub(1,pSize)
local residualData = data:sub(pSize+1)
local responseHeader = parseResponseHeader(packetData)
if responseHeader["responseFlag"] ~= 0 then
dbg("Response flag not zero : %d, some error occurred", responseHeader["responseFlag"])
end
local bsonData = responseHeader["bson"]
if #bsonData == 0 then
dbg("No BSon data returned ")
return false, "No Bson data returned"
end
-- result, data, err_msg = bson.fromBson(bsonData)
result, data, err_msg = fromBson(bsonData)
if err_msg then
dbg("Got error converting from bson: %s" , err_msg)
return false, ("Got error converting from bson: %s"):format(err_msg)
end
return true,result, residualData
end
function login(socket, db, username, password)
local collectionName = ("%s.$cmd"):format(arg_DB or db)
local q = { getnonce = 1 }
local status, packet = createQuery(collectionName, q)
local response
status, response = query(socket, packet)
if ( not(status) or not(response.nonce) ) then
return false, "Failed to retrieve nonce"
end
local nonce = response.nonce
local pwdigest = stdnse.tohex(openssl.md5(username .. ':mongo:' ..password))
local digest = stdnse.tohex(openssl.md5(nonce .. username .. pwdigest))
q = { user = username, nonce = nonce, key = digest }
q._cmd = { authenticate = 1 }
local status, packet = createQuery(collectionName, q)
status, response = query(socket, packet)
if ( not(status) ) then
return status, response
elseif ( response.errmsg == "auth fails" ) then
return false, "Authentication failed"
elseif ( response.errmsg ) then
return false, response.errmsg
end
return status, response
end
--- Converts a query result as received from MongoDB query into nmap "result" table
-- @param resultTable table as returned from a query
-- @return table suitable for <code>stdnse.format_output</code>
function queryResultToTable( resultTable )
local result = {}
for k,v in pairs( resultTable ) do
if type(v) == 'table' then
table.insert(result,k)
table.insert(result,queryResultToTable(v))
else
table.insert(result,(("%s = %s"):format(tostring(k), tostring(v))))
end
end
return result
end
----------------------------------------------------------------------------------
-- Test-code for debugging purposes below
----------------------------------------------------------------------------------
--- Prints data (string) as Hex values, e.g so it more easily can
-- be compared with a packet dump
-- @param strData the data in a string format
local function printBuffer(strData)
local out = ''
local ch
for i = 1,strData:len() do
out = out .." "
ch =strData:byte(i)
if(ch < 16) then
ch = string.format("0%x",ch)
else ch = string.format("%x",ch)
end
--if ch > 64 and ch < 123 then
-- out = out .. string.char(ch)
--else
out = out .. ch
--end
end
print(out)
end
-- function test()
-- local res
-- res = versionQuery()
-- print(type(res),res:len(),res)
-- local out= bin.unpack('C'..#res,res)
-- printBuffer(res)
-- end
--test()
return _ENV;
| mit |
zhaohao/waifu2x | web.lua | 23 | 6744 | _G.TURBO_SSL = true
local turbo = require 'turbo'
local uuid = require 'uuid'
local ffi = require 'ffi'
local md5 = require 'md5'
require 'pl'
require './lib/portable'
require './lib/LeakyReLU'
local cmd = torch.CmdLine()
cmd:text()
cmd:text("waifu2x-api")
cmd:text("Options:")
cmd:option("-port", 8812, 'listen port')
cmd:option("-gpu", 1, 'Device ID')
cmd:option("-core", 2, 'number of CPU cores')
local opt = cmd:parse(arg)
cutorch.setDevice(opt.gpu)
torch.setdefaulttensortype('torch.FloatTensor')
torch.setnumthreads(opt.core)
local iproc = require './lib/iproc'
local reconstruct = require './lib/reconstruct'
local image_loader = require './lib/image_loader'
local MODEL_DIR = "./models/anime_style_art_rgb"
local noise1_model = torch.load(path.join(MODEL_DIR, "noise1_model.t7"), "ascii")
local noise2_model = torch.load(path.join(MODEL_DIR, "noise2_model.t7"), "ascii")
local scale20_model = torch.load(path.join(MODEL_DIR, "scale2.0x_model.t7"), "ascii")
local USE_CACHE = true
local CACHE_DIR = "./cache"
local MAX_NOISE_IMAGE = 2560 * 2560
local MAX_SCALE_IMAGE = 1280 * 1280
local CURL_OPTIONS = {
request_timeout = 15,
connect_timeout = 10,
allow_redirects = true,
max_redirects = 2
}
local CURL_MAX_SIZE = 2 * 1024 * 1024
local BLOCK_OFFSET = 7 -- see srcnn.lua
local function valid_size(x, scale)
if scale == 0 then
return x:size(2) * x:size(3) <= MAX_NOISE_IMAGE
else
return x:size(2) * x:size(3) <= MAX_SCALE_IMAGE
end
end
local function get_image(req)
local file = req:get_argument("file", "")
local url = req:get_argument("url", "")
local blob = nil
local img = nil
local alpha = nil
if file and file:len() > 0 then
blob = file
img, alpha = image_loader.decode_float(blob)
elseif url and url:len() > 0 then
local res = coroutine.yield(
turbo.async.HTTPClient({verify_ca=false},
nil,
CURL_MAX_SIZE):fetch(url, CURL_OPTIONS)
)
if res.code == 200 then
local content_type = res.headers:get("Content-Type", true)
if type(content_type) == "table" then
content_type = content_type[1]
end
if content_type and content_type:find("image") then
blob = res.body
img, alpha = image_loader.decode_float(blob)
end
end
end
return img, blob, alpha
end
local function apply_denoise1(x)
return reconstruct.image(noise1_model, x, BLOCK_OFFSET)
end
local function apply_denoise2(x)
return reconstruct.image(noise2_model, x, BLOCK_OFFSET)
end
local function apply_scale2x(x)
return reconstruct.scale(scale20_model, 2.0, x, BLOCK_OFFSET)
end
local function cache_do(cache, x, func)
if path.exists(cache) then
return image.load(cache)
else
x = func(x)
image.save(cache, x)
return x
end
end
local function client_disconnected(handler)
return not(handler.request and
handler.request.connection and
handler.request.connection.stream and
(not handler.request.connection.stream:closed()))
end
local APIHandler = class("APIHandler", turbo.web.RequestHandler)
function APIHandler:post()
if client_disconnected(self) then
self:set_status(400)
self:write("client disconnected")
return
end
local x, src, alpha = get_image(self)
local scale = tonumber(self:get_argument("scale", "0"))
local noise = tonumber(self:get_argument("noise", "0"))
if x and valid_size(x, scale) then
if USE_CACHE and (noise ~= 0 or scale ~= 0) then
local hash = md5.sumhexa(src)
local cache_noise1 = path.join(CACHE_DIR, hash .. "_noise1.png")
local cache_noise2 = path.join(CACHE_DIR, hash .. "_noise2.png")
local cache_scale = path.join(CACHE_DIR, hash .. "_scale.png")
local cache_noise1_scale = path.join(CACHE_DIR, hash .. "_noise1_scale.png")
local cache_noise2_scale = path.join(CACHE_DIR, hash .. "_noise2_scale.png")
if noise == 1 then
x = cache_do(cache_noise1, x, apply_denoise1)
elseif noise == 2 then
x = cache_do(cache_noise2, x, apply_denoise2)
end
if scale == 1 or scale == 2 then
if noise == 1 then
x = cache_do(cache_noise1_scale, x, apply_scale2x)
elseif noise == 2 then
x = cache_do(cache_noise2_scale, x, apply_scale2x)
else
x = cache_do(cache_scale, x, apply_scale2x)
end
if scale == 1 then
x = iproc.scale(x,
math.floor(x:size(3) * (1.6 / 2.0) + 0.5),
math.floor(x:size(2) * (1.6 / 2.0) + 0.5),
"Jinc")
end
end
elseif noise ~= 0 or scale ~= 0 then
if noise == 1 then
x = apply_denoise1(x)
elseif noise == 2 then
x = apply_denoise2(x)
end
if scale == 1 then
local x16 = {math.floor(x:size(3) * 1.6 + 0.5), math.floor(x:size(2) * 1.6 + 0.5)}
x = apply_scale2x(x)
x = iproc.scale(x, x16[1], x16[2], "Jinc")
elseif scale == 2 then
x = apply_scale2x(x)
end
end
local name = uuid() .. ".png"
local blob, len = image_loader.encode_png(x, alpha)
self:set_header("Content-Disposition", string.format('filename="%s"', name))
self:set_header("Content-Type", "image/png")
self:set_header("Content-Length", string.format("%d", len))
self:write(ffi.string(blob, len))
else
if not x then
self:set_status(400)
self:write("ERROR: unsupported image format.")
else
self:set_status(400)
self:write("ERROR: image size exceeds maximum allowable size.")
end
end
collectgarbage()
end
local FormHandler = class("FormHandler", turbo.web.RequestHandler)
local index_ja = file.read("./assets/index.ja.html")
local index_ru = file.read("./assets/index.ru.html")
local index_en = file.read("./assets/index.html")
function FormHandler:get()
local lang = self.request.headers:get("Accept-Language")
if lang then
local langs = utils.split(lang, ",")
for i = 1, #langs do
langs[i] = utils.split(langs[i], ";")[1]
end
if langs[1] == "ja" then
self:write(index_ja)
elseif langs[1] == "ru" then
self:write(index_ru)
else
self:write(index_en)
end
else
self:write(index_en)
end
end
turbo.log.categories = {
["success"] = true,
["notice"] = false,
["warning"] = true,
["error"] = true,
["debug"] = false,
["development"] = false
}
local app = turbo.web.Application:new(
{
{"^/$", FormHandler},
{"^/index.html", turbo.web.StaticFileHandler, path.join("./assets", "index.html")},
{"^/index.ja.html", turbo.web.StaticFileHandler, path.join("./assets", "index.ja.html")},
{"^/index.ru.html", turbo.web.StaticFileHandler, path.join("./assets", "index.ru.html")},
{"^/api$", APIHandler},
}
)
app:listen(opt.port, "0.0.0.0", {max_body_size = CURL_MAX_SIZE})
turbo.ioloop.instance():start()
| mit |
cochrane/OpenTomb | scripts/trigger/trigger_functions.lua | 2 | 2981 | -- OPENTOMB TRIGGER FUNCTION SCRIPT
-- by Lwmte, April 2015
--------------------------------------------------------------------------------
-- This file contains core trigger routines which are used to initialize, run
-- and do other actions related to trigger array.
-- Trigger array itself is generated on the fly from each level file and is not
-- visible for user. You can turn on debug output of trigger array via config
-- command "system->output_triggers = 1".
--------------------------------------------------------------------------------
dofile("scripts/trigger/flipeffects.lua") -- Initialize flipeffects.
trigger_list = {}; -- Initialize trigger array.
-- Run trigger. Called when desired entity is on trigger sector.
function tlist_RunTrigger(index, activator_type, activator)
if((trigger_list[index] ~= nil) and (trigger_list[index].func ~= nil) and (trigger_list[index].activator_type == activator_type)) then
return trigger_list[index].func(activator);
else
return 0;
end;
end;
-- Erase single trigger.
function tlist_EraseTrigger(index)
if(trigger_list[index] ~= nil) then
trigger_list[index].func = nil;
trigger_list[index].activator_type = nil;
trigger_list[index] = nil;
end;
end;
-- Clear whole trigger array. Must be called on each level loading.
function tlist_Clear()
for k,v in pairs(trigger_list) do
tlist_EraseTrigger(k);
end;
print("Trigger table cleaned");
end;
-- Moves desired entity to specified sink.
function moveToSink(entity_index, sink_index)
local movetype = getEntityMoveType(entity_index);
if(movetype == 5) then -- Dive, if on water.
if(getEntityAnim(entity_index) ~= 113) then
setEntityAnim(entity_index, 113);
setEntityMoveType(entity_index, 6);
end;
elseif(movetype == 6) then
moveEntityToSink(entity_index, sink_index);
end;
end
-- Does specified flipeffect.
function doEffect(effect_index, extra_parameter) -- extra parameter is usually the timer field
if(flipeffects[effect_index] ~= nil) then
return flipeffects[effect_index](parameter);
else
return nil; -- Add hardcoded flipeffect routine here
end;
end
-- Sets specified secret index as found and plays audiotrack with pop-up notification.
function findSecret(secret_number)
if(getSecretStatus(secret_number) == 0) then
setSecretStatus(secret_number, 1); -- Set actual secret status
playStream(getSecretTrackNumber(getLevelVersion())); -- Play audiotrack
--showNotify("You have found a secret!", NOTIFY_ACHIEVEMENT);
end;
end
-- Clear dead enemies, if they have CLEAR BODY flag specified.
function clearBodies()
print("CLEAR BODIES");
end
-- Plays specified cutscene. Only valid in retail TR4-5.
function playCutscene(cutscene_index)
if(getLevelVersion() < TR_IV) then return 0 end;
print("CUTSCENE: index = " .. cutscene_index);
end | lgpl-3.0 |
alexd2580/igjam2016 | src/systems/MothershipSystem.lua | 1 | 1588 | local MothershipSystem = class("MothershipSystem", System)
function MothershipSystem:update()
for index, entity in pairs(self.targets) do
--enemy_mothership = entity:get("HasEnemy").enemy_mothership
--enemy_x, enemy_y = enemy_mothership:get("Physical").body:getPosition()
--enemy_pos = Vector(enemy_x, enemy_y)
local body = entity:get('Physical').body
local x, y = body:getPosition()
--local window_w, window_h,_ = love.window:getMode()
local window_w, window_h = 512, 448
local vel_x, vel_y = body:getLinearVelocity()
local imp_x, imp_y = 0,0
local hard_margin = 20
local soft_margin = 60
if x < hard_margin then x = hard_margin end
if x > window_w - hard_margin then x = window_w - hard_margin end
if y < hard_margin then y = hard_margin end
if y > window_h - hard_margin then y = window_h - hard_margin end
--if x < soft_margin then
-- if vel_x < 0 then imp_x = 150-2.5*x/100 end
-- end
--elseif member_x > window_w - margin then
-- vel_x = math.min(0, vel_y)
-- end
body:setPosition(x, y)
-- print(imp_x, vel_x)
-- body:applyLinearImpulse(-imp_x*vel_x, -imp_y*vel_y)
--member_pos = Vector(member_x, member_y)
--relative = enemy_pos - member_pos
--direction_rad = relative:getRadian()
--body:setAngle(direction_rad)
end
end
function MothershipSystem:requires()
return {"Mothership", "Physical", "HasEnemy"}
end
return MothershipSystem
| mit |
spacebuild/sbep | lua/data/sbep/smallbridge_filename_changes.lua | 3 | 90700 | ------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
OLD | NEW
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
SW HULLS/CORRIDORS
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbcorridorcurves/sbcorridorcurves.mdl | models/smallbridge/hulls_sw/sbhullcurves.mdl
models/smallbridge/hulls,sw/sbhullcurves.mdl | models/smallbridge/hulls_sw/sbhullcurves.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbcorridore1/sbcorridore1.mdl | models/smallbridge/hulls_sw/sbhulle1.mdl
models/smallbridge/hulls,sw/sbhulle1.mdl | models/smallbridge/hulls_sw/sbhulle1.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbcorridore2/sbcorridore2.mdl | models/smallbridge/hulls_sw/sbhulle2.mdl
models/smallbridge/hulls,sw/sbhulle2.mdl | models/smallbridge/hulls_sw/sbhulle2.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbcorridore3/sbcorridore3.mdl | models/smallbridge/hulls_sw/sbhulle3.mdl
models/smallbridge/hulls,sw/sbhulle3.mdl | models/smallbridge/hulls_sw/sbhulle3.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbcorridore4/sbcorridore4.mdl | models/smallbridge/hulls_sw/sbhulle4.mdl
models/smallbridge/hulls,sw/sbhulle4.mdl | models/smallbridge/hulls_sw/sbhulle4.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbcorridore05/sbcorridore05.mdl | models/smallbridge/hulls_sw/sbhulle05.mdl
models/smallbridge/hulls,sw/sbhulle05.mdl | models/smallbridge/hulls_sw/sbhulle05.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbcorridoredh/sbcorridoredh.mdl | models/smallbridge/hulls_sw/sbhulledh.mdl
models/smallbridge/hulls,sw/sbhulledh.mdl | models/smallbridge/hulls_sw/sbhulledh.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbcorridoredh2/sbcorridoredh2.mdl | models/smallbridge/hulls_sw/sbhulledh2.mdl
models/smallbridge/hulls,sw/sbhulledh2.mdl | models/smallbridge/hulls_sw/sbhulledh2.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbcorridoredh3/sbcorridoredh3.mdl | models/smallbridge/hulls_sw/sbhulledh3.mdl
models/smallbridge/hulls,sw/sbhulledh3.mdl | models/smallbridge/hulls_sw/sbhulledh3.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbcorridoredh4/sbcorridoredh4.mdl | models/smallbridge/hulls_sw/sbhulledh4.mdl
models/smallbridge/hulls,sw/sbhulledh4.mdl | models/smallbridge/hulls_sw/sbhulledh4.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbcorridoreflip/sbcorridoreflip.mdl | models/smallbridge/hulls_sw/sbhulleflip.mdl
models/smallbridge/hulls,sw/sbhulleflip.mdl | models/smallbridge/hulls_sw/sbhulleflip.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbcorridorend/sbcorridorend.mdl | models/smallbridge/hulls_sw/sbhullend.mdl
models/smallbridge/hulls,sw/sbhullend.mdl | models/smallbridge/hulls_sw/sbhullend.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/hulls,sw/sbhullenddh.mdl | models/smallbridge/hulls_sw/sbhullenddh.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbcorridorr/sbcorridorr.mdl | models/smallbridge/hulls_sw/sbhullr.mdl
models/smallbridge/hulls,sw/sbhullr.mdl | models/smallbridge/hulls_sw/sbhullr.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/hulls,sw/sbhullrdh.mdl | models/smallbridge/hulls_sw/sbhullrdh.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbcorridorrtri/sbcorridorrtri.mdl | models/smallbridge/hulls_sw/sbhullrtri.mdl
models/smallbridge/hulls,sw/sbhullrtri.mdl | models/smallbridge/hulls_sw/sbhullrtri.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbcorridorslanthalfl/sbcorridorslanthalfl.mdl | models/smallbridge/hulls_sw/sbhullslanthalfr.mdl
models/smallbridge/hulls,sw/sbhullslanthalfr.mdl | models/smallbridge/hulls_sw/sbhullslanthalfr.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbcorridorslanthalfr/sbcorridorslanthalfr.mdl | models/smallbridge/hulls_sw/sbhullslanthalfl.mdl
models/smallbridge/hulls,sw/sbhullslanthalfl.mdl | models/smallbridge/hulls_sw/sbhullslanthalfl.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbcorridorslantl/sbcorridorslantl.mdl | models/smallbridge/hulls_sw/sbhullslantr.mdl
models/smallbridge/hulls,sw/sbhullslantr.mdl | models/smallbridge/hulls_sw/sbhullslantr.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbcorridorslantr/sbcorridorslantr.mdl | models/smallbridge/hulls_sw/sbhullslantl.mdl
models/smallbridge/hulls,sw/sbhullslantl.mdl | models/smallbridge/hulls_sw/sbhullslantl.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbcorridort/sbcorridort.mdl | models/smallbridge/hulls_sw/sbhullt.mdl
models/smallbridge/hulls,sw/sbhullt.mdl | models/smallbridge/hulls_sw/sbhullt.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbcorridortdl/sbcorridortdl.mdl | models/smallbridge/hulls_sw/sbhulltdl.mdl
models/smallbridge/hulls,sw/sbhulltdl.mdl | models/smallbridge/hulls_sw/sbhulltdl.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbcorridortdldw/sbcorridortdldw.mdl | models/smallbridge/hulls_sw/sbhulltdldw.mdl
models/smallbridge/hulls,sw/sbhulltdldw.mdl | models/smallbridge/hulls_sw/sbhulltdldw.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbtrianglee1/sbtrianglee1.mdl | models/smallbridge/hulls_sw/sbhulltri1.mdl
models/smallbridge/hulls,sw/sbhulltri1.mdl | models/smallbridge/hulls_sw/sbhulltri1.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbtrianglee2/sbtrianglee2.mdl | models/smallbridge/hulls_sw/sbhulltri2.mdl
models/smallbridge/hulls,sw/sbhulltri2.mdl | models/smallbridge/hulls_sw/sbhulltri2.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbtrianglee3/sbtrianglee3.mdl | models/smallbridge/hulls_sw/sbhulltri3.mdl
models/smallbridge/hulls,sw/sbhulltri3.mdl | models/smallbridge/hulls_sw/sbhulltri3.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbcorridorx/sbcorridorx.mdl | models/smallbridge/hulls_sw/sbhullx.mdl
models/smallbridge/hulls,sw/sbhullx.mdl | models/smallbridge/hulls_sw/sbhullx.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbcorridorxdl/sbcorridorxdl.mdl | models/smallbridge/hulls_sw/sbhullxdl.mdl
models/smallbridge/hulls,sw/sbhullxdl.mdl | models/smallbridge/hulls_sw/sbhullxdl.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbcorridorxdldw/sbcorridorxdldw.mdl | models/smallbridge/hulls_sw/sbhullxdldw.mdl
models/smallbridge/hulls,sw/sbhullxdldw.mdl | models/smallbridge/hulls_sw/sbhullxdldw.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
DW HULLS/CORRIDORS
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbcorridoredw/sbcorridoredw.mdl | models/smallbridge/hulls_dw/sbhulldwe1.mdl
models/smallbridge/hulls,dw/sbhulldwe1.mdl | models/smallbridge/hulls_dw/sbhulldwe1.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbcorridoredw2/sbcorridoredw2.mdl | models/smallbridge/hulls_dw/sbhulldwe2.mdl
models/smallbridge/hulls,dw/sbhulldwe2.mdl | models/smallbridge/hulls_dw/sbhulldwe2.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbcorridoredw3/sbcorridoredw3.mdl | models/smallbridge/hulls_dw/sbhulldwe3.mdl
models/smallbridge/hulls,dw/sbhulldwe3.mdl | models/smallbridge/hulls_dw/sbhulldwe3.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbcorridoredw4/sbcorridoredw4.mdl | models/smallbridge/hulls_dw/sbhulldwe4.mdl
models/smallbridge/hulls,dw/sbhulldwe4.mdl | models/smallbridge/hulls_dw/sbhulldwe4.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbcorridoredw05/sbcorridoredw05.mdl | models/smallbridge/hulls_dw/sbhulldwe05.mdl
models/smallbridge/hulls,dw/sbhulldwe05.mdl | models/smallbridge/hulls_dw/sbhulldwe05.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbcorridorflipdw/sbcorridorflipdw.mdl | models/smallbridge/hulls_dw/sbhulldweflip.mdl
models/smallbridge/hulls,dw/sbhulldweflip.mdl | models/smallbridge/hulls_dw/sbhulldweflip.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbcorridoredhdw/sbcorridoredhdw.mdl | models/smallbridge/hulls_dw/sbhulldwedh.mdl
models/smallbridge/hulls,dw/sbhulldwedh.mdl | models/smallbridge/hulls_dw/sbhulldwedh.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbcorridoredhdw2/sbcorridoredhdw2.mdl | models/smallbridge/hulls_dw/sbhulldwedh2.mdl
models/smallbridge/hulls,dw/sbhulldwedh2.mdl | models/smallbridge/hulls_dw/sbhulldwedh2.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbcorridoredhdw3/sbcorridoredhdw3.mdl | models/smallbridge/hulls_dw/sbhulldwedh3.mdl
models/smallbridge/hulls,dw/sbhulldwedh3.mdl | models/smallbridge/hulls_dw/sbhulldwedh3.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbcorridoredhdw4/sbcorridoredhdw4.mdl | models/smallbridge/hulls_dw/sbhulldwedh4.mdl
models/smallbridge/hulls,dw/sbhulldwedh4.mdl | models/smallbridge/hulls_dw/sbhulldwedh4.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbcorridorenddw/sbcorridorenddw.mdl | models/smallbridge/hulls_dw/sbhulldwend.mdl
models/smallbridge/hulls,dw/sbhulldwend.mdl | models/smallbridge/hulls_dw/sbhulldwend.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbcorridorenddw2/sbcorridorenddw2.mdl | models/smallbridge/hulls_dw/sbhulldwend2.mdl
models/smallbridge/hulls,dw/sbhulldwend2.mdl | models/smallbridge/hulls_dw/sbhulldwend2.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbcorridorrdw/sbcorridorrdw.mdl | models/smallbridge/hulls_dw/sbhulldwr.mdl
models/smallbridge/hulls,dw/sbhulldwr.mdl | models/smallbridge/hulls_dw/sbhulldwr.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbcorridortdw/sbcorridortdw.mdl | models/smallbridge/hulls_dw/sbhulldwt.mdl
models/smallbridge/hulls,dw/sbhulldwt.mdl | models/smallbridge/hulls_dw/sbhulldwt.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbcorridortdwdl/sbcorridortdwdl.mdl | models/smallbridge/hulls_dw/sbhulldwtdl.mdl
models/smallbridge/hulls,dw/sbhulldwtdl.mdl | models/smallbridge/hulls_dw/sbhulldwtdl.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbcorridortdwsl/sbcorridortdwsl.mdl | models/smallbridge/hulls_dw/sbhulldwtsl.mdl
models/smallbridge/hulls,dw/sbhulldwtsl.mdl | models/smallbridge/hulls_dw/sbhulldwtsl.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbcorridorxdw/sbcorridorxdw.mdl | models/smallbridge/hulls_dw/sbhulldwx.mdl
models/smallbridge/hulls,dw/sbhulldwx.mdl | models/smallbridge/hulls_dw/sbhulldwx.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbcorridorxdwdl/sbcorridorxdwdl.mdl | models/smallbridge/hulls_dw/sbhulldwxdl.mdl
models/smallbridge/hulls,dw/sbhulldwxdl.mdl | models/smallbridge/hulls_dw/sbhulldwxdl.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
WALKWAYS
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbwalkwaye/sbwalkwaye.mdl | models/smallbridge/walkways/sbwalkwaye.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbwalkwaye2/sbwalkwaye2.mdl | models/smallbridge/walkways/sbwalkwaye2.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbwalkwayr/sbwalkwayr.mdl | models/smallbridge/walkways/sbwalkwayr.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbwalkwayt/sbwalkwayt.mdl | models/smallbridge/walkways/sbwalkwayt.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbwalkwayx/sbwalkwayx.mdl | models/smallbridge/walkways/sbwalkwayx.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
VEHICLES
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbchair/sbchair.mdl | models/smallbridge/vehicles/sbvpchair.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbdroppod1/sbdroppod1.mdl | models/smallbridge/vehicles/sbvdroppod1.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
OTHER PARTS
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbconsole1s/sbconsole1s.mdl | models/smallbridge/other/sbconsole.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbconsole1low/sbconsole1low.mdl | models/smallbridge/other/sbconsolelow.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbconsoletop1/sbconsoletop1.mdl | models/smallbridge/other/sbconsoletop.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
SENTS/ANIMATED PARTS
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbdooranim1/sbdooranim1.mdl | models/smallbridge/sents/sbadoor1.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbdooranim2/sbdooranim2.mdl | models/smallbridge/sents/sbadoor2.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbdooranimwide.mdl | models/smallbridge/sents/sbadoorwide.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
PANELS/DOORS
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbdoor/sbdoor.mdl | models/smallbridge/panels/sbdoor.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbdoorsquare/sbdoorsquare.mdl | models/smallbridge/panels/sbdoorsquare.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbdooriris.mdl | models/smallbridge/panels/sbdooriris.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbdoorwide/sbdoorwide.mdl | models/smallbridge/panels/sbdoorwide.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbpanelsolidg/sbpanelsolidg.mdl | models/smallbridge/panels/sbpanelsolid.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbpanelsolidgdw/sbpanelsolidgdw.mdl | models/smallbridge/panels/sbpanelsoliddw.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbpaneldh/sbpaneldh.mdl | models/smallbridge/panels/sbpaneldh.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbpaneldhdw/sbpaneldhdw.mdl | models/smallbridge/panels/sbpaneldhdw.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbpaneldoor/sbpaneldoor.mdl | models/smallbridge/panels/sbpaneldoor.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbpaneldoordw/sbpaneldoordw.mdl | models/smallbridge/panels/sbpaneldoordw.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbpaneldoor2dw/sbpaneldoor2dw.mdl | models/smallbridge/panels/sbpaneldoordw2.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbpanelsquaredoor/sbpanelsquaredoor.mdl | models/smallbridge/panels/sbpaneldoorsquare.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbpanelsquaredoordw/sbpanelsquaredoordw.mdl | models/smallbridge/panels/sbpaneldoorsquaredw.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbdooriris2.mdl | models/smallbridge/panels/sbpaneldooriris.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbpanelwidedoor/sbpanelwidedoor.mdl | models/smallbridge/panels/sbpaneldoorwide.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbpanelsquaredoordockin/sbpanelsquaredoordockin.mdl | models/smallbridge/panels/sbpaneldockin.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbpanelsquaredoordocko/sbpanelsquaredoordocko.mdl | models/smallbridge/panels/sbpaneldockout.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
DROP BAY HANGARS
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbdropbay1left/sbdropbay1left.mdl | models/smallbridge/hangars/sbdb1l.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbdropbay1lefts/sbdropbay1lefts.mdl | models/smallbridge/hangars/sbdb1ls.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbdropbay1mide/sbdropbay1mide.mdl | models/smallbridge/hangars/sbdb1m.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbdropbay1midd/sbdropbay1midd.mdl | models/smallbridge/hangars/sbdb1m1.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbdropbay1mid/sbdropbay1mid.mdl | models/smallbridge/hangars/sbdb1m12.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbdropbay1right/sbdropbay1right.mdl | models/smallbridge/hangars/sbdb1r.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbdropbay1rights/sbdropbay1rights.mdl | models/smallbridge/hangars/sbdb1rs.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbdropbay2left/sbdropbay2left.mdl | models/smallbridge/hangars/sbdb2l.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbdropbay2mid/sbdropbay2mid.mdl | models/smallbridge/hangars/sbdb2m.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbdropbay2middw/sbdropbay2middw.mdl | models/smallbridge/hangars/sbdb2mdw.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbdropbay2right/sbdropbay2right.mdl | models/smallbridge/hangars/sbdb2r.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbdropbay3mid/sbdropbay3mid.mdl | models/smallbridge/hangars/sbdb3m.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbdropbay3middw/sbdropbay3middw.mdl | models/smallbridge/hangars/sbdb3mdw.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbdropbay3midx/sbdropbay3midx.mdl | models/smallbridge/hangars/sbdb3mx.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbdropbay3midxdw/sbdropbay3midxdw.mdl | models/smallbridge/hangars/sbdb3mxdw.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbdropbay3side/sbdropbay3side.mdl | models/smallbridge/hangars/sbdb3side.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbdropbay4left/sbdropbay4left.mdl | models/smallbridge/hangars/sbdb4l.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbdropbay4mid/sbdropbay4mid.mdl | models/smallbridge/hangars/sbdb4m.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbdropbay4middw/sbdropbay4middw.mdl | models/smallbridge/hangars/sbdb4mdw.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbdropbay4right/sbdropbay4right.mdl | models/smallbridge/hangars/sbdb4r.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbdropbaycomplete1s/sbdropbaycomplete1s.mdl | models/smallbridge/hangars/sbdbcomp1.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbdropbay1s/sbdropbay1s.mdl | models/smallbridge/hangars/sbdbseg1s.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbdropbay1ss/sbdropbay1ss.mdl | models/smallbridge/hangars/sbdbseg1ss.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbdropbay2s/sbdropbay2s.mdl | models/smallbridge/hangars/sbdbseg2s.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbdropbay3s/sbdropbay3s.mdl | models/smallbridge/hangars/sbdbseg3s.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbdropbay4s/sbdropbay4s.mdl | models/smallbridge/hangars/sbdbseg4s.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
WINGS
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbwingc1l/sbwingc1l.mdl | models/smallbridge/wings/sbwingc1l.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbwingc1r/sbwingc1r.mdl | models/smallbridge/wings/sbwingc1r.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbwingls1l/sbwingls1l.mdl | models/smallbridge/wings/sbwingls1l.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbwingls1r/sbwingls1r.mdl | models/smallbridge/wings/sbwingls1r.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbwingm1l/sbwingm1l.mdl | models/smallbridge/wings/sbwingm1l.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbwingm1le/sbwingm1le.mdl | models/smallbridge/wings/sbwingm1le.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbwingm1r/sbwingm1r.mdl | models/smallbridge/wings/sbwingm1r.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbwingm1re/sbwingm1re.mdl | models/smallbridge/wings/sbwingm1re.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbwings1l/sbwings1l.mdl | models/smallbridge/wings/sbwings1l.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbwings1r/sbwings1r.mdl | models/smallbridge/wings/sbwings1r.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
LIFE SUPPORT
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbfusiongen2/sbfusiongen2.mdl | models/smallbridge/life support/sbfusiongen.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbwallcachee1/sbwallcachee1.mdl | models/smallbridge/life support/sbwallcachee.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbwallcachel/sbwallcachel.mdl | models/smallbridge/life support/sbwallcachel.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbwallcaches/sbwallcaches.mdl | models/smallbridge/life support/sbwallcaches.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
HEIGHT TRANSFER
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbcramp1/sbcramp1.mdl | models/smallbridge/height transfer/sbhtcramp.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbcramp2dwd/sbcramp2dwd.mdl | models/smallbridge/height transfer/sbhtcramp2d.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbcorridorramp/sbcorridorramp.mdl | models/smallbridge/height transfer/sbhtramp.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbcorridorramphalf/sbcorridorramphalf.mdl | models/smallbridge/height transfer/sbhtramp05.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbsrampd/sbsrampd.mdl | models/smallbridge/height transfer/sbhtsrampd.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbsrampm/sbsrampm.mdl | models/smallbridge/height transfer/sbhtsrampm.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbsrampu/sbsrampu.mdl | models/smallbridge/height transfer/sbhtsrampu.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbsrampz/sbsrampz.mdl | models/smallbridge/height transfer/sbhtsrampz.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbsrampzdw/sbsrampzdw.mdl | models/smallbridge/height transfer/sbhtsrampzdw.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
SPLITTERS
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbconvertersbtomb/sbconvertersbtomb.mdl | models/smallbridge/splitters/sbconvmb.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbcorridore2swto2sw/sbcorridore2swto2sw.mdl | models/smallbridge/splitters/sbsplit2s-2sw.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbcorridoredto2sw/sbcorridoredto2sw.mdl | models/smallbridge/splitters/sbsplit2s-dw.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbcorridorestodhdo/sbcorridorestodhdo.mdl | models/smallbridge/splitters/sbsplits-dhd.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbcorridorestodhdwdo/sbcorridorestodhdwdo.mdl | models/smallbridge/splitters/sbsplitdws-dhd.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbcorridorestodhdwmid/sbcorridorestodhdwmid.mdl | models/smallbridge/splitters/sbsplitdws-dhm.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbcorridorestodhdwup/sbcorridorestodhdwup.mdl | models/smallbridge/splitters/sbsplitdws-dhu.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbcorridorestodhmid/sbcorridorestodhmid.mdl | models/smallbridge/splitters/sbsplits-dhm.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbcorridorestodhup/sbcorridorestodhup.mdl | models/smallbridge/splitters/sbsplits-dhu.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbcorridorestodw/sbcorridorestodw.mdl | models/smallbridge/splitters/sbsplits-dw.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbcorridorestodwangular/sbcorridorestodwangular.mdl | models/smallbridge/splitters/sbsplits-dwa.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbcorridorv/sbcorridorv.mdl | models/smallbridge/splitters/sbsplitv.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbcorridorvwide/sbcorridorvwide.mdl | models/smallbridge/splitters/sbsplitvw.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
ELEVATORS, SMALL
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbpanelelev0s/sbpanelelev0s.mdl | models/smallbridge/elevators_small/sbselevp0.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbpanelelev1s/sbpanelelev1s.mdl | models/smallbridge/elevators_small/sbselevp1.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbpanelelev2s/sbpanelelev2s.mdl | models/smallbridge/elevators_small/sbselevp2e.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbpanelelev2se/sbpanelelev2se.mdl | models/smallbridge/elevators_small/sbselevp2r.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbpanelelev3s/sbpanelelev3s.mdl | models/smallbridge/elevators_small/sbselevp3.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbelevshaft/sbelevshaft.mdl | models/smallbridge/elevators_small/sbselevs.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbelevshaft2/sbelevshaft2.mdl | models/smallbridge/elevators_small/sbselevs2.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbelevbase/sbelevbase.mdl | models/smallbridge/elevators_small/sbselevb.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbelevbasee/sbelevbasee.mdl | models/smallbridge/elevators_small/sbselevbe.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbelevbaseedh/sbelevbaseedh.mdl | models/smallbridge/elevators_small/sbselevbedh.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbelevbaseedl/sbelevbaseedl.mdl | models/smallbridge/elevators_small/sbselevbedw.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbelevbaser/sbelevbaser.mdl | models/smallbridge/elevators_small/sbselevbr.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbelevbaset/sbelevbaset.mdl | models/smallbridge/elevators_small/sbselevbt.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbelevbasex/sbelevbasex.mdl | models/smallbridge/elevators_small/sbselevbx.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbelevmid/sbelevmid.mdl | models/smallbridge/elevators_small/sbselevm.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbelevmide/sbelevmide.mdl | models/smallbridge/elevators_small/sbselevme.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbelevmidedh/sbelevmidedh.mdl | models/smallbridge/elevators_small/sbselevmedh.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbelevmidedl/sbelevmidedl.mdl | models/smallbridge/elevators_small/sbselevmedw.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbelevmidr/sbelevmidr.mdl | models/smallbridge/elevators_small/sbselevmr.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbelevmidt/sbelevmidt.mdl | models/smallbridge/elevators_small/sbselevmt.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbelevmidx/sbelevmidx.mdl | models/smallbridge/elevators_small/sbselevmx.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbelevtop/sbelevtop.mdl | models/smallbridge/elevators_small/sbselevt.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbelevtope/sbelevtope.mdl | models/smallbridge/elevators_small/sbselevte.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbelevtopedh/sbelevtopedh.mdl | models/smallbridge/elevators_small/sbselevtedh.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbelevtopedl/sbelevtopedl.mdl | models/smallbridge/elevators_small/sbselevtedw.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbelevtopr/sbelevtopr.mdl | models/smallbridge/elevators_small/sbselevtr.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbelevtopt/sbelevtopt.mdl | models/smallbridge/elevators_small/sbselevtt.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbelevtopx/sbelevtopx.mdl | models/smallbridge/elevators_small/sbselevtx.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
SHIP PARTS
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbbridge1s/sbbridge1s.mdl | models/smallbridge/ship parts/sbcockpit1.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbbridgeo1/sbbridgeo1.mdl | models/smallbridge/ship parts/sbcockpit2.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbbridgeo1base/sbbridgeo1base.mdl | models/smallbridge/ship parts/sbcockpit2o.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbbridgeo1cover/sbbridgeo1cover.mdl | models/smallbridge/ship parts/sbcockpit2or.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbedoorsn/sbedoorsn.mdl | models/smallbridge/ship parts/sbhulldsp.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbedoorsn2/sbedoorsn2.mdl | models/smallbridge/ship parts/sbhulldsp2.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbengine1s/sbengine1s.mdl | models/smallbridge/ship parts/sbengine1.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbengine2/sbengine2.mdl | models/smallbridge/ship parts/sbengine2.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbengine2b/sbengine2b.mdl | models/smallbridge/ship parts/sbengine2o.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbengine2bramp/sbengine2bramp.mdl | models/smallbridge/ship parts/sbengine2or.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbengine3/sbengine3.mdl | models/smallbridge/ship parts/sbengine3.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbenginedw1s/sbenginedw1s.mdl | models/smallbridge/ship parts/sbengine4dw.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbenginesw1ls/sbenginesw1ls.mdl | models/smallbridge/ship parts/sbengine4l.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbenginesw1ms/sbenginesw1ms.mdl | models/smallbridge/ship parts/sbengine4m.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbenginesw1rs/sbenginesw1rs.mdl | models/smallbridge/ship parts/sbengine4r.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbhulldoors/sbhulldoors.mdl | models/smallbridge/ship parts/sbhulldseb.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbhulledoors/sbhulledoors.mdl | models/smallbridge/ship parts/sbhulldse.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbhulledoors2/sbhulledoors2.mdl | models/smallbridge/ship parts/sbhulldse2.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbhulledoorsdw/sbhulledoorsdw.mdl | models/smallbridge/ship parts/sbhulldsdwe.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbhulledoorsdw2/sbhulledoorsdw2.mdl | models/smallbridge/ship parts/sbhulldsdwe2.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbhulltdoors/sbhulltdoors.mdl | models/smallbridge/ship parts/sbhulldst.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sblanddock1/sblanddock1.mdl | models/smallbridge/ship parts/sblandramp.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sblanddock1dw/sblanddock1dw.mdl | models/smallbridge/ship parts/sblandrampdw.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sblanddock1dwdh/sblanddock1dwdh.mdl | models/smallbridge/ship parts/sblandrampdwdh.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sblanddockramp1/sblanddockramp1.mdl | models/smallbridge/ship parts/sblandrampp.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sblanddockramp1dw/sblanddockramp1dw.mdl | models/smallbridge/ship parts/sblandramppdw.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sblanddockramp1dwdh/sblanddockramp1dwdh.mdl | models/smallbridge/ship parts/sblandramppdwdh.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
STATION PARTS
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbcommandbridge/sbcommandbridge.mdl | models/smallbridge/station parts/sbbridgecomm.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbcommandbridgedw/sbcommandbridgedw.mdl | models/smallbridge/station parts/sbbridgecommdw.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbcommandbridgeelev/sbcommandbridgeelev.mdl | models/smallbridge/station parts/sbbridgecommelev.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbcorridorsgc1/sbcorridorsgc1.mdl | models/smallbridge/station parts/sbrooml1.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbcorridorsgc2/sbcorridorsgc2.mdl | models/smallbridge/station parts/sbroomsgc.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbdock1/sbdock1.mdl | models/smallbridge/station parts/sbdockcs.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbhangardhdw1/sbhangardhdw1.mdl | models/smallbridge/station parts/sbhangarlu.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbhangardhdw1d/sbhangardhdw1d.mdl | models/smallbridge/station parts/sbhangarld.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbhangardhdw1ud/sbhangardhdw1ud.mdl | models/smallbridge/station parts/sbhangarlud.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbhangardhdw2/sbhangardhdw2.mdl | models/smallbridge/station parts/sbhangarlud2.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbhub/sbhub.mdl | models/smallbridge/station parts/sbhubl.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbocthub1/sbocthub1.mdl | models/smallbridge/station parts/sbhubs.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbpodbay1/sbpodbay1.mdl | models/smallbridge/station parts/sbbaydps.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbspherebridge1/sbspherebridge1.mdl | models/smallbridge/station parts/sbbridgesphere.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbvisorbridge1/sbvisorbridge1.mdl | models/smallbridge/station parts/sbbridgevisor.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbvisorcontroltop/sbvisorcontroltop.mdl | models/smallbridge/station parts/sbbridgevisorelev.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
ELEVATORS, LARGE
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbelevbasedw/sbelevbasedw.mdl | models/smallbridge/elevators_large/sblelevb.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbelevbaseedhdw/sbelevbaseedhdw.mdl | models/smallbridge/elevators_large/sblelevbedh.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbelevbaseedw/sbelevbaseedw.mdl | models/smallbridge/elevators_large/sblelevbe.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbelevbaserdw/sbelevbaserdw.mdl | models/smallbridge/elevators_large/sblelevbr.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbelevbasetdw/sbelevbasetdw.mdl | models/smallbridge/elevators_large/sblelevbt.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbelevbasexdw/sbelevbasexdw.mdl | models/smallbridge/elevators_large/sblelevbx.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbelevmiddw/sbelevmiddw.mdl | models/smallbridge/elevators_large/sblelevm.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbelevmidedhdw/sbelevmidedhdw.mdl | models/smallbridge/elevators_large/sblelevmedh.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbelevmidedw/sbelevmidedw.mdl | models/smallbridge/elevators_large/sblelevme.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbelevmidrdw/sbelevmidrdw.mdl | models/smallbridge/elevators_large/sblelevmr.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbelevmidtdw/sbelevmidtdw.mdl | models/smallbridge/elevators_large/sblelevmt.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbelevmidxdw/sbelevmidxdw.mdl | models/smallbridge/elevators_large/sblelevmx.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbelevshaftdw/sbelevshaftdw.mdl | models/smallbridge/elevators_large/sblelevs.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbelevshaftdw2/sbelevshaftdw2.mdl | models/smallbridge/elevators_large/sblelevs2.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbelevtopdw/sbelevtopdw.mdl | models/smallbridge/elevators_large/sblelevt.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbelevtopedhdw/sbelevtopedhdw.mdl | models/smallbridge/elevators_large/sblelevtedh.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbelevtopedw/sbelevtopedw.mdl | models/smallbridge/elevators_large/sblelevte.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbelevtoprdw/sbelevtoprdw.mdl | models/smallbridge/elevators_large/sblelevtr.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbelevtoptdw/sbelevtoptdw.mdl | models/smallbridge/elevators_large/sblelevtt.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbelevtopxdw/sbelevtopxdw.mdl | models/smallbridge/elevators_large/sblelevtx.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbpanelelev0sdw/sbpanelelev0sdw.mdl | models/smallbridge/elevators_large/sblelevp0.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbpanelelev1sdw/sbpanelelev1sdw.mdl | models/smallbridge/elevators_large/sblelevp1.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbpanelelev2sdw/sbpanelelev2sdw.mdl | models/smallbridge/elevators_large/sblelevp2r.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbpanelelev2sedw/sbpanelelev2sedw.mdl | models/smallbridge/elevators_large/sblelevp2e.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/smallbridge/sbpanelelev3sdw/sbpanelelev3sdw.mdl | models/smallbridge/elevators_large/sblelevp3.mdl
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
BLANK CATEGORY
------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
models/ | models/
------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------- | apache-2.0 |
ImagicTheCat/vRP | vrp/client/audio.lua | 1 | 8346 | -- https://github.com/ImagicTheCat/vRP
-- MIT license (see LICENSE or vrp/vRPShared.lua)
if not vRP.modules.audio then return end
local Audio = class("Audio", vRP.Extension)
-- METHODS
function Audio:__construct()
vRP.Extension.__construct(self)
self.channel_callbacks = {}
self.voice_channels = {} -- map of channel => map of player => state (0-1)
self.vrp_voip = false
self.voip_interval = 5000
self.voip_proximity = 100
self.active_channels = {}
self.speaking = false
-- listener task
self.listener_wait = math.ceil(1/vRP.cfg.audio_listener_rate*1000)
Citizen.CreateThread(function()
while true do
Citizen.Wait(self.listener_wait)
local x,y,z
if vRP.cfg.audio_listener_on_player then
local ped = GetPlayerPed(PlayerId())
x,y,z = table.unpack(GetPedBoneCoords(ped, 31086, 0,0,0)) -- head pos
else
x,y,z = table.unpack(GetGameplayCamCoord())
end
local fx,fy,fz = vRP.EXT.Base:getCamDirection()
SendNUIMessage({act="audio_listener", x = x, y = y, z = z, fx = fx, fy = fy, fz = fz})
end
end)
-- task: detect players near, give positions to AudioEngine
Citizen.CreateThread(function()
local n = 0
local ns = math.ceil(self.voip_interval/self.listener_wait) -- connect/disconnect every x milliseconds
local connections = {}
while true do
Citizen.Wait(self.listener_wait)
n = n+1
local voip_check = (n >= ns)
if voip_check then n = 0 end
local pid = PlayerId()
local spid = GetPlayerServerId(pid)
local px,py,pz = vRP.EXT.Base:getPosition()
local positions = {}
local players = vRP.EXT.Base.players
for k,v in pairs(players) do
local player = GetPlayerFromServerId(k)
if NetworkIsPlayerConnected(player) or player == pid then
local oped = GetPlayerPed(player)
local x,y,z = table.unpack(GetPedBoneCoords(oped, 31086, 0,0,0)) -- head pos
positions[k] = {x,y,z} -- add position
if player ~= pid and self.vrp_voip and voip_check then -- vRP voip detection/connection
local distance = GetDistanceBetweenCoords(x,y,z,px,py,pz,true)
local in_radius = (distance <= self.voip_proximity)
if not connections[k] and in_radius then -- join radius
self:connectVoice("world", k)
connections[k] = true
elseif connections[k] and not in_radius then -- leave radius
self:disconnectVoice("world", k)
connections[k] = nil
end
end
end
end
positions._ = true -- prevent JS array type
SendNUIMessage({act="set_player_positions", positions=positions})
end
end)
-- task: voice controls
Citizen.CreateThread(function()
while true do
Citizen.Wait(0)
-- voip/speaking
local old_speaking = self.speaking
self.speaking = IsControlPressed(1,249)
if old_speaking ~= self.speaking then -- change
if not self.speaking then -- delay off
self.speaking = true
SetTimeout(vRP.cfg.push_to_talk_end_delay+1, function()
if self.speaking_time and GetGameTimer()-self.speaking_time >= vRP.cfg.push_to_talk_end_delay then
self.speaking = false
vRP:triggerEvent("speakingChange", self.speaking)
self.speaking_time = nil
end
end)
else -- instantaneous
vRP:triggerEvent("speakingChange", self.speaking)
self.speaking_time = GetGameTimer()
end
end
end
end)
-- task: voice proximity
Citizen.CreateThread(function()
while true do
Citizen.Wait(500)
if self.vrp_voip then -- vRP voip
NetworkSetTalkerProximity(self.voip_proximity) -- disable voice chat
else -- regular voice chat
local ped = GetPlayerPed(-1)
local proximity = vRP.cfg.voice_proximity
if IsPedSittingInAnyVehicle(ped) then
local veh = GetVehiclePedIsIn(ped,false)
local hash = GetEntityModel(veh)
-- make open vehicles (bike,etc) use the default proximity
if IsThisModelACar(hash) or IsThisModelAHeli(hash) or IsThisModelAPlane(hash) then
proximity = vRP.cfg.voice_proximity_vehicle
end
elseif vRP.EXT.Base:isInside() then
proximity = vRP.cfg.voice_proximity_inside
end
NetworkSetTalkerProximity(proximity+0.0001)
end
end
end)
end
-- play audio source (once)
--- url: valid audio HTML url (ex: .ogg/.wav/direct ogg-stream url)
--- volume: 0-1
--- x,y,z: position (omit for unspatialized)
--- max_dist (omit for unspatialized)
--- player: (optional) player source id, if passed the spatialized source will be relative to the player (parented)
function Audio:playAudioSource(url, volume, x, y, z, max_dist, player)
SendNUIMessage({act="play_audio_source", url = url, x = x, y = y, z = z, volume = volume, max_dist = max_dist, player = player})
end
-- set named audio source (looping)
--- name: source name
--- url: valid audio HTML url (ex: .ogg/.wav/direct ogg-stream url)
--- volume: 0-1
--- x,y,z: position (omit for unspatialized)
--- max_dist (omit for unspatialized)
--- player: (optional) player source id, if passed the spatialized source will be relative to the player (parented)
function Audio:setAudioSource(name, url, volume, x, y, z, max_dist, player)
SendNUIMessage({act="set_audio_source", name = name, url = url, x = x, y = y, z = z, volume = volume, max_dist = max_dist, player = player})
end
-- remove named audio source
function Audio:removeAudioSource(name)
SendNUIMessage({act="remove_audio_source", name = name})
end
-- VoIP
-- create connection to another player for a specific channel
function Audio:connectVoice(channel, player)
SendNUIMessage({act="connect_voice", channel=channel, player=player})
end
-- delete connection to another player for a specific channel
-- player: nil to disconnect from all players
function Audio:disconnectVoice(channel, player)
SendNUIMessage({act="disconnect_voice", channel=channel, player=player})
end
-- enable/disable speaking for a specific channel
--- active: true/false
function Audio:setVoiceState(channel, active)
SendNUIMessage({act="set_voice_state", channel=channel, active=active})
end
function Audio:isSpeaking()
return self.speaking
end
-- EVENT
Audio.event = {}
function Audio.event:speakingChange(speaking)
-- voip
if self.vrp_voip then
self:setVoiceState("world", speaking)
end
end
function Audio.event:voiceChannelTransmittingChange(channel, transmitting)
local old_state = (next(self.active_channels) ~= nil)
if transmitting then
self.active_channels[channel] = true
else
self.active_channels[channel] = nil
end
local state = next(self.active_channels) ~= nil
if old_state ~= state then -- update indicator/local player talking
SendNUIMessage({act="set_voice_indicator", state = state})
SetPlayerTalkingOverride(PlayerId(), state)
end
end
function Audio.event:voiceChannelPlayerSpeakingChange(channel, player, speaking)
if channel == "world" then -- remote player talking
SetPlayerTalkingOverride(GetPlayerFromServerId(player), speaking)
end
end
-- TUNNEL
Audio.tunnel = {}
function Audio.tunnel:configureVoIP(config, vrp_voip, interval, proximity)
self.vrp_voip = vrp_voip
self.voip_interval = interval
self.voip_proximity = proximity
if self.vrp_voip then
NetworkSetVoiceChannel(config.id)
end
SendNUIMessage({act="configure_voip", config = config})
end
Audio.tunnel.playAudioSource = Audio.playAudioSource
Audio.tunnel.setAudioSource = Audio.setAudioSource
Audio.tunnel.removeAudioSource = Audio.removeAudioSource
Audio.tunnel.connectVoice = Audio.connectVoice
Audio.tunnel.disconnectVoice = Audio.disconnectVoice
Audio.tunnel.setVoiceState = Audio.setVoiceState
-- NUI
RegisterNUICallback("audio",function(data,cb)
if data.act == "voice_channel_player_speaking_change" then
vRP:triggerEvent("voiceChannelPlayerSpeakingChange", data.channel, tonumber(data.player), data.speaking)
elseif data.act == "voice_channel_transmitting_change" then
vRP:triggerEvent("voiceChannelTransmittingChange", data.channel, data.transmitting)
end
end)
vRP:registerExtension(Audio)
| mit |
masterweb121/telegram-bot | bot/bot.lua | 15 | 6562 | package.path = package.path .. ';.luarocks/share/lua/5.2/?.lua'
..';.luarocks/share/lua/5.2/?/init.lua'
package.cpath = package.cpath .. ';.luarocks/lib/lua/5.2/?.so'
require("./bot/utils")
VERSION = '0.13.1'
-- This function is called when tg receive a msg
function on_msg_receive (msg)
if not started then
return
end
local receiver = get_receiver(msg)
-- vardump(msg)
msg = pre_process_service_msg(msg)
if msg_valid(msg) then
msg = pre_process_msg(msg)
if msg then
match_plugins(msg)
mark_read(receiver, ok_cb, false)
end
end
end
function ok_cb(extra, success, result)
end
function on_binlog_replay_end()
started = true
postpone (cron_plugins, false, 60*5.0)
-- See plugins/isup.lua as an example for cron
_config = load_config()
-- load plugins
plugins = {}
load_plugins()
end
function msg_valid(msg)
-- Don't process outgoing messages
if msg.out then
print('\27[36mNot valid: msg from us\27[39m')
return false
end
-- Before bot was started
if msg.date < now then
print('\27[36mNot valid: old msg\27[39m')
return false
end
if msg.unread == 0 then
print('\27[36mNot valid: readed\27[39m')
return false
end
if not msg.to.id then
print('\27[36mNot valid: To id not provided\27[39m')
return false
end
if not msg.from.id then
print('\27[36mNot valid: From id not provided\27[39m')
return false
end
if msg.from.id == our_id then
print('\27[36mNot valid: Msg from our id\27[39m')
return false
end
if msg.to.type == 'encr_chat' then
print('\27[36mNot valid: Encrypted chat\27[39m')
return false
end
if msg.from.id == 777000 then
print('\27[36mNot valid: Telegram message\27[39m')
return false
end
return true
end
--
function pre_process_service_msg(msg)
if msg.service then
local action = msg.action or {type=""}
-- Double ! to discriminate of normal actions
msg.text = "!!tgservice " .. action.type
-- wipe the data to allow the bot to read service messages
if msg.out then
msg.out = false
end
if msg.from.id == our_id then
msg.from.id = 0
end
end
return msg
end
-- Apply plugin.pre_process function
function pre_process_msg(msg)
for name,plugin in pairs(plugins) do
if plugin.pre_process and msg then
print('Preprocess', name)
msg = plugin.pre_process(msg)
end
end
return msg
end
-- Go over enabled plugins patterns.
function match_plugins(msg)
for name, plugin in pairs(plugins) do
match_plugin(plugin, name, msg)
end
end
-- Check if plugin is on _config.disabled_plugin_on_chat table
local function is_plugin_disabled_on_chat(plugin_name, receiver)
local disabled_chats = _config.disabled_plugin_on_chat
-- Table exists and chat has disabled plugins
if disabled_chats and disabled_chats[receiver] then
-- Checks if plugin is disabled on this chat
for disabled_plugin,disabled in pairs(disabled_chats[receiver]) do
if disabled_plugin == plugin_name and disabled then
local warning = 'Plugin '..disabled_plugin..' is disabled on this chat'
print(warning)
send_msg(receiver, warning, ok_cb, false)
return true
end
end
end
return false
end
function match_plugin(plugin, plugin_name, msg)
local receiver = get_receiver(msg)
-- Go over patterns. If one matches it's enough.
for k, pattern in pairs(plugin.patterns) do
local matches = match_pattern(pattern, msg.text)
if matches then
print("msg matches: ", pattern)
if is_plugin_disabled_on_chat(plugin_name, receiver) then
return nil
end
-- Function exists
if plugin.run then
-- If plugin is for privileged users only
if not warns_user_not_allowed(plugin, msg) then
local result = plugin.run(msg, matches)
if result then
send_large_msg(receiver, result)
end
end
end
-- One patterns matches
return
end
end
end
-- DEPRECATED, use send_large_msg(destination, text)
function _send_msg(destination, text)
send_large_msg(destination, text)
end
-- Save the content of _config to config.lua
function save_config( )
serialize_to_file(_config, './data/config.lua')
print ('saved config into ./data/config.lua')
end
-- Returns the config from config.lua file.
-- If file doesn't exist, create it.
function load_config( )
local f = io.open('./data/config.lua', "r")
-- If config.lua doesn't exist
if not f then
print ("Created new config file: data/config.lua")
create_config()
else
f:close()
end
local config = loadfile ("./data/config.lua")()
for v,user in pairs(config.sudo_users) do
print("Allowed user: " .. user)
end
return config
end
-- Create a basic config.json file and saves it.
function create_config( )
-- A simple config with basic plugins and ourselves as privileged user
config = {
enabled_plugins = {
"9gag",
"eur",
"echo",
"btc",
"get",
"giphy",
"google",
"gps",
"help",
"id",
"images",
"img_google",
"location",
"media",
"plugins",
"channels",
"set",
"stats",
"time",
"version",
"weather",
"xkcd",
"youtube" },
sudo_users = {our_id},
disabled_channels = {}
}
serialize_to_file(config, './data/config.lua')
print ('saved config into ./data/config.lua')
end
function on_our_id (id)
our_id = id
end
function on_user_update (user, what)
--vardump (user)
end
function on_chat_update (chat, what)
--vardump (chat)
end
function on_secret_chat_update (schat, what)
--vardump (schat)
end
function on_get_difference_end ()
end
-- Enable plugins in config.json
function load_plugins()
for k, v in pairs(_config.enabled_plugins) do
print("Loading plugin", v)
local ok, err = pcall(function()
local t = loadfile("plugins/"..v..'.lua')()
plugins[v] = t
end)
if not ok then
print('\27[31mError loading plugin '..v..'\27[39m')
print('\27[31m'..err..'\27[39m')
end
end
end
-- Call and postpone execution for cron plugins
function cron_plugins()
for name, plugin in pairs(plugins) do
-- Only plugins with cron function
if plugin.cron ~= nil then
plugin.cron()
end
end
-- Called again in 5 mins
postpone (cron_plugins, false, 5*60.0)
end
-- Start and load values
our_id = 0
now = os.time()
math.randomseed(now)
started = false
| gpl-2.0 |
Godfather021/best | libs/JSON.lua | 3765 | 34843 | -- -*- coding: utf-8 -*-
--
-- Simple JSON encoding and decoding in pure Lua.
--
-- Copyright 2010-2014 Jeffrey Friedl
-- http://regex.info/blog/
--
-- Latest version: http://regex.info/blog/lua/json
--
-- This code is released under a Creative Commons CC-BY "Attribution" License:
-- http://creativecommons.org/licenses/by/3.0/deed.en_US
--
-- It can be used for any purpose so long as the copyright notice above,
-- the web-page links above, and the 'AUTHOR_NOTE' string below are
-- maintained. Enjoy.
--
local VERSION = 20141223.14 -- version history at end of file
local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-"
--
-- The 'AUTHOR_NOTE' variable exists so that information about the source
-- of the package is maintained even in compiled versions. It's also
-- included in OBJDEF below mostly to quiet warnings about unused variables.
--
local OBJDEF = {
VERSION = VERSION,
AUTHOR_NOTE = AUTHOR_NOTE,
}
--
-- Simple JSON encoding and decoding in pure Lua.
-- http://www.json.org/
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
--
--
--
-- DECODING (from a JSON string to a Lua table)
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- If the JSON text is for an object or an array, e.g.
-- { "what": "books", "count": 3 }
-- or
-- [ "Larry", "Curly", "Moe" ]
--
-- the result is a Lua table, e.g.
-- { what = "books", count = 3 }
-- or
-- { "Larry", "Curly", "Moe" }
--
--
-- The encode and decode routines accept an optional second argument,
-- "etc", which is not used during encoding or decoding, but upon error
-- is passed along to error handlers. It can be of any type (including nil).
--
--
--
-- ERROR HANDLING
--
-- With most errors during decoding, this code calls
--
-- JSON:onDecodeError(message, text, location, etc)
--
-- with a message about the error, and if known, the JSON text being
-- parsed and the byte count where the problem was discovered. You can
-- replace the default JSON:onDecodeError() with your own function.
--
-- The default onDecodeError() merely augments the message with data
-- about the text and the location if known (and if a second 'etc'
-- argument had been provided to decode(), its value is tacked onto the
-- message as well), and then calls JSON.assert(), which itself defaults
-- to Lua's built-in assert(), and can also be overridden.
--
-- For example, in an Adobe Lightroom plugin, you might use something like
--
-- function JSON:onDecodeError(message, text, location, etc)
-- LrErrors.throwUserError("Internal Error: invalid JSON data")
-- end
--
-- or even just
--
-- function JSON.assert(message)
-- LrErrors.throwUserError("Internal Error: " .. message)
-- end
--
-- If JSON:decode() is passed a nil, this is called instead:
--
-- JSON:onDecodeOfNilError(message, nil, nil, etc)
--
-- and if JSON:decode() is passed HTML instead of JSON, this is called:
--
-- JSON:onDecodeOfHTMLError(message, text, nil, etc)
--
-- The use of the fourth 'etc' argument allows stronger coordination
-- between decoding and error reporting, especially when you provide your
-- own error-handling routines. Continuing with the the Adobe Lightroom
-- plugin example:
--
-- function JSON:onDecodeError(message, text, location, etc)
-- local note = "Internal Error: invalid JSON data"
-- if type(etc) = 'table' and etc.photo then
-- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName')
-- end
-- LrErrors.throwUserError(note)
-- end
--
-- :
-- :
--
-- for i, photo in ipairs(photosToProcess) do
-- :
-- :
-- local data = JSON:decode(someJsonText, { photo = photo })
-- :
-- :
-- end
--
--
--
--
--
-- DECODING AND STRICT TYPES
--
-- Because both JSON objects and JSON arrays are converted to Lua tables,
-- it's not normally possible to tell which original JSON type a
-- particular Lua table was derived from, or guarantee decode-encode
-- round-trip equivalency.
--
-- However, if you enable strictTypes, e.g.
--
-- JSON = assert(loadfile "JSON.lua")() --load the routines
-- JSON.strictTypes = true
--
-- then the Lua table resulting from the decoding of a JSON object or
-- JSON array is marked via Lua metatable, so that when re-encoded with
-- JSON:encode() it ends up as the appropriate JSON type.
--
-- (This is not the default because other routines may not work well with
-- tables that have a metatable set, for example, Lightroom API calls.)
--
--
-- ENCODING (from a lua table to a JSON string)
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
-- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false })
--
-- On error during encoding, this code calls:
--
-- JSON:onEncodeError(message, etc)
--
-- which you can override in your local JSON object.
--
-- The 'etc' in the error call is the second argument to encode()
-- and encode_pretty(), or nil if it wasn't provided.
--
--
-- PRETTY-PRINTING
--
-- An optional third argument, a table of options, allows a bit of
-- configuration about how the encoding takes place:
--
-- pretty = JSON:encode(val, etc, {
-- pretty = true, -- if false, no other options matter
-- indent = " ", -- this provides for a three-space indent per nesting level
-- align_keys = false, -- see below
-- })
--
-- encode() and encode_pretty() are identical except that encode_pretty()
-- provides a default options table if none given in the call:
--
-- { pretty = true, align_keys = false, indent = " " }
--
-- For example, if
--
-- JSON:encode(data)
--
-- produces:
--
-- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11}
--
-- then
--
-- JSON:encode_pretty(data)
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- The following three lines return identical results:
-- JSON:encode_pretty(data)
-- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " })
-- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " })
--
-- An example of setting your own indent string:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " })
--
-- produces:
--
-- {
-- | "city": "Kyoto",
-- | "climate": {
-- | | "avg_temp": 16,
-- | | "humidity": "high",
-- | | "snowfall": "minimal"
-- | },
-- | "country": "Japan",
-- | "wards": 11
-- }
--
-- An example of setting align_keys to true:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true })
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- which I must admit is kinda ugly, sorry. This was the default for
-- encode_pretty() prior to version 20141223.14.
--
--
-- AMBIGUOUS SITUATIONS DURING THE ENCODING
--
-- During the encode, if a Lua table being encoded contains both string
-- and numeric keys, it fits neither JSON's idea of an object, nor its
-- idea of an array. To get around this, when any string key exists (or
-- when non-positive numeric keys exist), numeric keys are converted to
-- strings.
--
-- For example,
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- produces the JSON object
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To prohibit this conversion and instead make it an error condition, set
-- JSON.noKeyConversion = true
--
--
-- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT
--
-- assert
-- onDecodeError
-- onDecodeOfNilError
-- onDecodeOfHTMLError
-- onEncodeError
--
-- If you want to create a separate Lua JSON object with its own error handlers,
-- you can reload JSON.lua or use the :new() method.
--
---------------------------------------------------------------------------
local default_pretty_indent = " "
local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent }
local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray
local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject
function OBJDEF:newArray(tbl)
return setmetatable(tbl or {}, isArray)
end
function OBJDEF:newObject(tbl)
return setmetatable(tbl or {}, isObject)
end
local function unicode_codepoint_as_utf8(codepoint)
--
-- codepoint is a number
--
if codepoint <= 127 then
return string.char(codepoint)
elseif codepoint <= 2047 then
--
-- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8
--
local highpart = math.floor(codepoint / 0x40)
local lowpart = codepoint - (0x40 * highpart)
return string.char(0xC0 + highpart,
0x80 + lowpart)
elseif codepoint <= 65535 then
--
-- 1110yyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x1000)
local remainder = codepoint - 0x1000 * highpart
local midpart = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midpart
highpart = 0xE0 + highpart
midpart = 0x80 + midpart
lowpart = 0x80 + lowpart
--
-- Check for an invalid character (thanks Andy R. at Adobe).
-- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070
--
if ( highpart == 0xE0 and midpart < 0xA0 ) or
( highpart == 0xED and midpart > 0x9F ) or
( highpart == 0xF0 and midpart < 0x90 ) or
( highpart == 0xF4 and midpart > 0x8F )
then
return "?"
else
return string.char(highpart,
midpart,
lowpart)
end
else
--
-- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x40000)
local remainder = codepoint - 0x40000 * highpart
local midA = math.floor(remainder / 0x1000)
remainder = remainder - 0x1000 * midA
local midB = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midB
return string.char(0xF0 + highpart,
0x80 + midA,
0x80 + midB,
0x80 + lowpart)
end
end
function OBJDEF:onDecodeError(message, text, location, etc)
if text then
if location then
message = string.format("%s at char %d of: %s", message, location, text)
else
message = string.format("%s: %s", message, text)
end
end
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError
OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError
function OBJDEF:onEncodeError(message, etc)
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
local function grok_number(self, text, start, etc)
--
-- Grab the integer part
--
local integer_part = text:match('^-?[1-9]%d*', start)
or text:match("^-?0", start)
if not integer_part then
self:onDecodeError("expected number", text, start, etc)
end
local i = start + integer_part:len()
--
-- Grab an optional decimal part
--
local decimal_part = text:match('^%.%d+', i) or ""
i = i + decimal_part:len()
--
-- Grab an optional exponential part
--
local exponent_part = text:match('^[eE][-+]?%d+', i) or ""
i = i + exponent_part:len()
local full_number_text = integer_part .. decimal_part .. exponent_part
local as_number = tonumber(full_number_text)
if not as_number then
self:onDecodeError("bad number", text, start, etc)
end
return as_number, i
end
local function grok_string(self, text, start, etc)
if text:sub(start,start) ~= '"' then
self:onDecodeError("expected string's opening quote", text, start, etc)
end
local i = start + 1 -- +1 to bypass the initial quote
local text_len = text:len()
local VALUE = ""
while i <= text_len do
local c = text:sub(i,i)
if c == '"' then
return VALUE, i + 1
end
if c ~= '\\' then
VALUE = VALUE .. c
i = i + 1
elseif text:match('^\\b', i) then
VALUE = VALUE .. "\b"
i = i + 2
elseif text:match('^\\f', i) then
VALUE = VALUE .. "\f"
i = i + 2
elseif text:match('^\\n', i) then
VALUE = VALUE .. "\n"
i = i + 2
elseif text:match('^\\r', i) then
VALUE = VALUE .. "\r"
i = i + 2
elseif text:match('^\\t', i) then
VALUE = VALUE .. "\t"
i = i + 2
else
local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if hex then
i = i + 6 -- bypass what we just read
-- We have a Unicode codepoint. It could be standalone, or if in the proper range and
-- followed by another in a specific range, it'll be a two-code surrogate pair.
local codepoint = tonumber(hex, 16)
if codepoint >= 0xD800 and codepoint <= 0xDBFF then
-- it's a hi surrogate... see whether we have a following low
local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if lo_surrogate then
i = i + 6 -- bypass the low surrogate we just read
codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16)
else
-- not a proper low, so we'll just leave the first codepoint as is and spit it out.
end
end
VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint)
else
-- just pass through what's escaped
VALUE = VALUE .. text:match('^\\(.)', i)
i = i + 2
end
end
end
self:onDecodeError("unclosed string", text, start, etc)
end
local function skip_whitespace(text, start)
local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2
if match_end then
return match_end + 1
else
return start
end
end
local grok_one -- assigned later
local function grok_object(self, text, start, etc)
if text:sub(start,start) ~= '{' then
self:onDecodeError("expected '{'", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '{'
local VALUE = self.strictTypes and self:newObject { } or { }
if text:sub(i,i) == '}' then
return VALUE, i + 1
end
local text_len = text:len()
while i <= text_len do
local key, new_i = grok_string(self, text, i, etc)
i = skip_whitespace(text, new_i)
if text:sub(i, i) ~= ':' then
self:onDecodeError("expected colon", text, i, etc)
end
i = skip_whitespace(text, i + 1)
local new_val, new_i = grok_one(self, text, i)
VALUE[key] = new_val
--
-- Expect now either '}' to end things, or a ',' to allow us to continue.
--
i = skip_whitespace(text, new_i)
local c = text:sub(i,i)
if c == '}' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '}'", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '{'", text, start, etc)
end
local function grok_array(self, text, start, etc)
if text:sub(start,start) ~= '[' then
self:onDecodeError("expected '['", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '['
local VALUE = self.strictTypes and self:newArray { } or { }
if text:sub(i,i) == ']' then
return VALUE, i + 1
end
local VALUE_INDEX = 1
local text_len = text:len()
while i <= text_len do
local val, new_i = grok_one(self, text, i)
-- can't table.insert(VALUE, val) here because it's a no-op if val is nil
VALUE[VALUE_INDEX] = val
VALUE_INDEX = VALUE_INDEX + 1
i = skip_whitespace(text, new_i)
--
-- Expect now either ']' to end things, or a ',' to allow us to continue.
--
local c = text:sub(i,i)
if c == ']' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '['", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '['", text, start, etc)
end
grok_one = function(self, text, start, etc)
-- Skip any whitespace
start = skip_whitespace(text, start)
if start > text:len() then
self:onDecodeError("unexpected end of string", text, nil, etc)
end
if text:find('^"', start) then
return grok_string(self, text, start, etc)
elseif text:find('^[-0123456789 ]', start) then
return grok_number(self, text, start, etc)
elseif text:find('^%{', start) then
return grok_object(self, text, start, etc)
elseif text:find('^%[', start) then
return grok_array(self, text, start, etc)
elseif text:find('^true', start) then
return true, start + 4
elseif text:find('^false', start) then
return false, start + 5
elseif text:find('^null', start) then
return nil, start + 4
else
self:onDecodeError("can't parse JSON", text, start, etc)
end
end
function OBJDEF:decode(text, etc)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc)
end
if text == nil then
self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc)
elseif type(text) ~= 'string' then
self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc)
end
if text:match('^%s*$') then
return nil
end
if text:match('^%s*<') then
-- Can't be JSON... we'll assume it's HTML
self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc)
end
--
-- Ensure that it's not UTF-32 or UTF-16.
-- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3),
-- but this package can't handle them.
--
if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then
self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc)
end
local success, value = pcall(grok_one, self, text, 1, etc)
if success then
return value
else
-- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert.
if self.assert then
self.assert(false, value)
else
assert(false, value)
end
-- and if we're still here, return a nil and throw the error message on as a second arg
return nil, value
end
end
local function backslash_replacement_function(c)
if c == "\n" then
return "\\n"
elseif c == "\r" then
return "\\r"
elseif c == "\t" then
return "\\t"
elseif c == "\b" then
return "\\b"
elseif c == "\f" then
return "\\f"
elseif c == '"' then
return '\\"'
elseif c == '\\' then
return '\\\\'
else
return string.format("\\u%04x", c:byte())
end
end
local chars_to_be_escaped_in_JSON_string
= '['
.. '"' -- class sub-pattern to match a double quote
.. '%\\' -- class sub-pattern to match a backslash
.. '%z' -- class sub-pattern to match a null
.. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters
.. ']'
local function json_string_literal(value)
local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function)
return '"' .. newval .. '"'
end
local function object_or_array(self, T, etc)
--
-- We need to inspect all the keys... if there are any strings, we'll convert to a JSON
-- object. If there are only numbers, it's a JSON array.
--
-- If we'll be converting to a JSON object, we'll want to sort the keys so that the
-- end result is deterministic.
--
local string_keys = { }
local number_keys = { }
local number_keys_must_be_strings = false
local maximum_number_key
for key in pairs(T) do
if type(key) == 'string' then
table.insert(string_keys, key)
elseif type(key) == 'number' then
table.insert(number_keys, key)
if key <= 0 or key >= math.huge then
number_keys_must_be_strings = true
elseif not maximum_number_key or key > maximum_number_key then
maximum_number_key = key
end
else
self:onEncodeError("can't encode table with a key of type " .. type(key), etc)
end
end
if #string_keys == 0 and not number_keys_must_be_strings then
--
-- An empty table, or a numeric-only array
--
if #number_keys > 0 then
return nil, maximum_number_key -- an array
elseif tostring(T) == "JSON array" then
return nil
elseif tostring(T) == "JSON object" then
return { }
else
-- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects
return nil
end
end
table.sort(string_keys)
local map
if #number_keys > 0 then
--
-- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array
-- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object.
--
if self.noKeyConversion then
self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc)
end
--
-- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings
--
map = { }
for key, val in pairs(T) do
map[key] = val
end
table.sort(number_keys)
--
-- Throw numeric keys in there as strings
--
for _, number_key in ipairs(number_keys) do
local string_key = tostring(number_key)
if map[string_key] == nil then
table.insert(string_keys , string_key)
map[string_key] = T[number_key]
else
self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc)
end
end
end
return string_keys, nil, map
end
--
-- Encode
--
-- 'options' is nil, or a table with possible keys:
-- pretty -- if true, return a pretty-printed version
-- indent -- a string (usually of spaces) used to indent each nested level
-- align_keys -- if true, align all the keys when formatting a table
--
local encode_value -- must predeclare because it calls itself
function encode_value(self, value, parents, etc, options, indent)
if value == nil then
return 'null'
elseif type(value) == 'string' then
return json_string_literal(value)
elseif type(value) == 'number' then
if value ~= value then
--
-- NaN (Not a Number).
-- JSON has no NaN, so we have to fudge the best we can. This should really be a package option.
--
return "null"
elseif value >= math.huge then
--
-- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should
-- really be a package option. Note: at least with some implementations, positive infinity
-- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is.
-- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">="
-- case first.
--
return "1e+9999"
elseif value <= -math.huge then
--
-- Negative infinity.
-- JSON has no INF, so we have to fudge the best we can. This should really be a package option.
--
return "-1e+9999"
else
return tostring(value)
end
elseif type(value) == 'boolean' then
return tostring(value)
elseif type(value) ~= 'table' then
self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc)
else
--
-- A table to be converted to either a JSON object or array.
--
local T = value
if type(options) ~= 'table' then
options = {}
end
if type(indent) ~= 'string' then
indent = ""
end
if parents[T] then
self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc)
else
parents[T] = true
end
local result_value
local object_keys, maximum_number_key, map = object_or_array(self, T, etc)
if maximum_number_key then
--
-- An array...
--
local ITEMS = { }
for i = 1, maximum_number_key do
table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent))
end
if options.pretty then
result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]"
else
result_value = "[" .. table.concat(ITEMS, ",") .. "]"
end
elseif object_keys then
--
-- An object
--
local TT = map or T
if options.pretty then
local KEYS = { }
local max_key_length = 0
for _, key in ipairs(object_keys) do
local encoded = encode_value(self, tostring(key), parents, etc, options, indent)
if options.align_keys then
max_key_length = math.max(max_key_length, #encoded)
end
table.insert(KEYS, encoded)
end
local key_indent = indent .. tostring(options.indent or "")
local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "")
local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s"
local COMBINED_PARTS = { }
for i, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent)
table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val))
end
result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}"
else
local PARTS = { }
for _, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, indent)
local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent)
table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val))
end
result_value = "{" .. table.concat(PARTS, ",") .. "}"
end
else
--
-- An empty array/object... we'll treat it as an array, though it should really be an option
--
result_value = "[]"
end
parents[T] = false
return result_value
end
end
function OBJDEF:encode(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or nil)
end
function OBJDEF:encode_pretty(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or default_pretty_options)
end
function OBJDEF.__tostring()
return "JSON encode/decode package"
end
OBJDEF.__index = OBJDEF
function OBJDEF:new(args)
local new = { }
if args then
for key, val in pairs(args) do
new[key] = val
end
end
return setmetatable(new, OBJDEF)
end
return OBJDEF:new()
--
-- Version history:
--
-- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really
-- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines
-- more flexible, and changed the default encode_pretty() to be more generally useful.
--
-- Added a third 'options' argument to the encode() and encode_pretty() routines, to control
-- how the encoding takes place.
--
-- Updated docs to add assert() call to the loadfile() line, just as good practice so that
-- if there is a problem loading JSON.lua, the appropriate error message will percolate up.
--
-- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string,
-- so that the source of the package, and its version number, are visible in compiled copies.
--
-- 20140911.12 Minor lua cleanup.
-- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'.
-- (Thanks to SmugMug's David Parry for these.)
--
-- 20140418.11 JSON nulls embedded within an array were being ignored, such that
-- ["1",null,null,null,null,null,"seven"],
-- would return
-- {1,"seven"}
-- It's now fixed to properly return
-- {1, nil, nil, nil, nil, nil, "seven"}
-- Thanks to "haddock" for catching the error.
--
-- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up.
--
-- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2",
-- and this caused some problems.
--
-- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate,
-- and had of course diverged (encode_pretty didn't get the fixes that encode got, so
-- sometimes produced incorrect results; thanks to Mattie for the heads up).
--
-- Handle encoding tables with non-positive numeric keys (unlikely, but possible).
--
-- If a table has both numeric and string keys, or its numeric keys are inappropriate
-- (such as being non-positive or infinite), the numeric keys are turned into
-- string keys appropriate for a JSON object. So, as before,
-- JSON:encode({ "one", "two", "three" })
-- produces the array
-- ["one","two","three"]
-- but now something with mixed key types like
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- instead of throwing an error produces an object:
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To maintain the prior throw-an-error semantics, set
-- JSON.noKeyConversion = true
--
-- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry.
--
-- 20130120.6 Comment update: added a link to the specific page on my blog where this code can
-- be found, so that folks who come across the code outside of my blog can find updates
-- more easily.
--
-- 20111207.5 Added support for the 'etc' arguments, for better error reporting.
--
-- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent.
--
-- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules:
--
-- * When encoding lua for JSON, Sparse numeric arrays are now handled by
-- spitting out full arrays, such that
-- JSON:encode({"one", "two", [10] = "ten"})
-- returns
-- ["one","two",null,null,null,null,null,null,null,"ten"]
--
-- In 20100810.2 and earlier, only up to the first non-null value would have been retained.
--
-- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999".
-- Version 20100810.2 and earlier created invalid JSON in both cases.
--
-- * Unicode surrogate pairs are now detected when decoding JSON.
--
-- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding
--
-- 20100731.1 initial public release
--
| gpl-2.0 |
alexd2580/igjam2016 | src/systems/AttackSystem.lua | 1 | 2567 | local AttackSystem = class("AttackSystem", System)
local LaserBeam = Component.load({'LaserBeam'})
function AttackSystem:initialize(gamestate)
System.initialize(self)
self.gamestate = gamestate
end
function AttackSystem:update(dt)
for k, entity in pairs(self.targets) do
enemy_mothership = entity:get('HasEnemy').enemy_mothership
enemy_x, enemy_y = enemy_mothership:get('Physical').body:getPosition()
enemy_vector = Vector(enemy_x, enemy_y)
local weapon = entity:get('Weapon')
local body = entity:get('Physical').body
member_x, member_y = body:getPosition()
member_vector = Vector(member_x, member_y)
relative = enemy_vector - member_vector
direction = relative:normalize()
dir_rad = direction:getRadian()
local distance = member_vector:distanceTo(enemy_vector)
local final_rad = dir_rad
local rand_rad = 0
if math.random() > weapon.hitChance then
-- range in degrees
local offRange = weapon.sprayAngle
local rand_off = offRange * (love.math.random() - .5)
rand_rad = math.rad(rand_off)
final_rad = dir_rad + rand_rad
end
rad_angle = body:getAngle()
view_dir = Vector.from_radians(rad_angle)
shoot_angle = view_dir:dot(direction)
weapon.since_last_fired = weapon.since_last_fired + dt
if shoot_angle > 0.95 and weapon.since_last_fired > weapon.cooldown and distance <= weapon.range then
weapon.since_last_fired = 0
if weapon.type == 'laser' then
local beam = Entity()
local target = enemy_vector:subtract(member_vector):rotate(rand_rad):add(member_vector)
beam:add(LaserBeam(member_vector, target))
stack:current().engine:addEntity(beam)
stack:current().eventmanager:fireEvent(BulletHitMothership(nil, enemy_mothership, weapon.damage))
resources.sounds.laserShot:setVolume(0.05)
resources.sounds.laserShot:clone():play()
elseif weapon.type == 'missile' then
self.gamestate:shoot_bullet(
member_vector, Vector.from_radians(final_rad), 200, enemy_mothership, weapon.damage)
resources.sounds.rocketLaunch:setVolume(0.1)
resources.sounds.rocketLaunch:clone():play()
end
end
end
end
function AttackSystem:requires()
return {"HasEnemy", "Physical", "Weapon"}
end
return AttackSystem
| mit |
benignoc/ear-training-chord-creation | Classes/Class - Frame.lua | 1 | 3156 | --[[ Lokasenna_GUI - Frame class
---- User parameters ----
(name, z, x, y, w, h[, shadow, fill, color, round])
Required:
z Element depth, used for hiding and disabling layers. 1 is the highest.
x, y Coordinates of top-left corner
w, h Frame size
Optional:
shadow Boolean. Draw a shadow beneath the frame? Defaults to False.
fill Boolean. Fill in the frame? Defaults to False.
color Frame (and fill) color. Defaults to "elm_frame".
round Radius of the frame's corners. Defaults to 0.
Additional:
text Text to be written inside the frame. Will automatically be wrapped
to fit self.w - 2*self.pad.
txt_indent Number of spaces to indent the first line of each paragraph
txt_pad Number of spaces to indent wrapped lines (to match up with bullet
points, etc)
pad Padding between the frame's edges and text. Defaults to 0.
bg Color to be drawn underneath the text. Defaults to "wnd_bg",
but will use the frame's fill color instead if Fill = True
font Text font. Defaults to preset 4.
col_txt Text color. Defaults to "txt".
Extra methods:
GUI.Val() Returns the frame's text.
GUI.Val(new) Sets the frame's text and formats it to fit within the frame, as above.
]]--
if not GUI then
reaper.ShowMessageBox("Couldn't access GUI functions.\n\nLokasenna_GUI - Core.lua must be loaded prior to any classes.", "Library Error", 0)
missing_lib = true
return 0
end
GUI.Frame = GUI.Element:new()
function GUI.Frame:new(name, z, x, y, w, h, shadow, fill, color, round)
local Frame = {}
Frame.name = name
Frame.type = "Frame"
Frame.z = z
GUI.redraw_z[z] = true
Frame.x, Frame.y, Frame.w, Frame.h = x, y, w, h
Frame.shadow = shadow or false
Frame.fill = fill or false
Frame.color = color or "elm_frame"
Frame.round = 0
Frame.text = ""
Frame.txt_indent = 0
Frame.txt_pad = 0
Frame.bg = "wnd_bg"
Frame.font = 4
Frame.col_txt = "txt"
Frame.pad = 4
setmetatable(Frame, self)
self.__index = self
return Frame
end
function GUI.Frame:init()
if self.text ~= "" then
self.text = GUI.word_wrap(self.text, self.font, self.w - 2*self.pad, self.txt_indent, self.txt_pad)
end
end
function GUI.Frame:draw()
if self.color == "none" then return 0 end
local x, y, w, h = self.x, self.y, self.w, self.h
local dist = GUI.shadow_dist
local fill = self.fill
local round = self.round
local shadow = self.shadow
if shadow then
GUI.color("shadow")
for i = 1, dist do
if round > 0 then
GUI.roundrect(x + i, y + i, w, h, round, 1, fill)
else
gfx.rect(x + i, y + i, w, h, fill)
end
end
end
GUI.color(self.color)
if round > 0 then
GUI.roundrect(x, y, w, h, round, 1, fill)
else
gfx.rect(x, y, w, h, fill)
end
if self.text then
GUI.font(self.font)
GUI.color(self.col_txt)
gfx.x, gfx.y = self.x + self.pad, self.y + self.pad
if not fill then GUI.text_bg(self.text, self.bg) end
gfx.drawstr(self.text)
end
end
function GUI.Frame:val(new)
if new then
self.text = GUI.word_wrap(new, self.font, self.w - 2*self.pad, self.txt_indent, self.txt_pad)
GUI.redraw_z[self.z] = true
else
return self.text
end
end
| mit |
Murfalo/game-off-2016 | libs/lume.lua | 1 | 9136 | --
-- lume
--
-- Copyright (c) 2014, rxi
--
-- This library is free software; you can redistribute it and/or modify it
-- under the terms of the MIT license. See LICENSE for details.
--
local lume = { _version = "1.3.0" }
local pairs, ipairs = pairs, ipairs
local type, assert, unpack = type, assert, unpack or table.unpack
local tostring, tonumber = tostring, tonumber
local math_floor = math.floor
local math_ceil = math.ceil
local math_random = math.random
local math_cos = math.cos
local math_atan2 = math.atan2
local math_sqrt = math.sqrt
local math_abs = math.abs
local math_pi = math.pi
local patternescape = function(str)
return str:gsub("[%(%)%.%%%+%-%*%?%[%]%^%$]", "%%%1")
end
local absindex = function(len, i)
return i < 0 and (len + i + 1) or i
end
local iscallable = function(x)
return type(x) == "function" or getmetatable(x).__call ~= nil
end
function lume.clamp(x, min, max)
return x < min and min or (x > max and max or x)
end
function lume.round(x, increment)
if increment then return lume.round(x / increment) * increment end
return x > 0 and math_floor(x + .5) or math_ceil(x - .5)
end
function lume.sign(x)
return x < 0 and -1 or 1
end
function lume.lerp(a, b, amount)
return a + (b - a) * lume.clamp(amount, 0, 1)
end
function lume.smooth(a, b, amount)
local m = (1 - math_cos(lume.clamp(amount, 0, 1) * math_pi)) / 2
return a + (b - a) * m
end
function lume.pingpong(x)
return 1 - math_abs(1 - x % 2)
end
function lume.distance(x1, y1, x2, y2, squared)
local dx = x1 - x2
local dy = y1 - y2
local s = dx * dx + dy * dy
return squared and s or math_sqrt(s)
end
function lume.angle(x1, y1, x2, y2)
return math_atan2(y2 - y1, x2 - x1)
end
function lume.random(a, b)
if not a then a, b = 0, 1 end
if not b then b = 0 end
return a + math_random() * (b - a)
end
function lume.randomchoice(t)
return t[math_random(#t)]
end
function lume.weightedchoice(t)
local sum = 0
for k, v in pairs(t) do
assert(v >= 0, "weight value less than zero")
sum = sum + v
end
assert(sum ~= 0, "all weights are zero")
local rnd = lume.random(sum)
for k, v in pairs(t) do
if rnd < v then return k end
rnd = rnd - v
end
end
function lume.shuffle(t)
for i = 1, #t do
local r = math_random(#t)
t[i], t[r] = t[r], t[i]
end
return t
end
function lume.array(...)
local t = {}
for x in unpack({...}) do t[#t + 1] = x end
return t
end
function lume.each(t, fn, ...)
if type(fn) == "string" then
for _, v in pairs(t) do v[fn](v, ...) end
else
for _, v in pairs(t) do fn(v, ...) end
end
return t
end
function lume.map(t, fn)
local rtn = {}
for k, v in pairs(t) do rtn[k] = fn(v) end
return rtn
end
function lume.all(t, fn)
fn = fn or function(x) return x end
for k, v in pairs(t) do
if not fn(v) then return false end
end
return true
end
function lume.any(t, fn)
fn = fn or function(x) return x end
for k, v in pairs(t) do
if fn(v) then return true end
end
return false
end
function lume.reduce(t, fn, first)
local acc = first or t[1]
assert(acc, "reduce of an empty array with no first value")
for i = first and 1 or 2, #t do acc = fn(acc, t[i]) end
return acc
end
function lume.set(t, retainkeys)
local rtn = {}
for k, v in pairs(lume.invert(t)) do
rtn[retainkeys and v or (#rtn + 1)] = k
end
return rtn
end
function lume.filter(t, fn, retainkeys)
local rtn = {}
for k, v in pairs(t) do
if fn(v) then rtn[retainkeys and k or (#rtn + 1)] = v end
end
return rtn
end
function lume.merge(t, t2, retainkeys)
for k, v in pairs(t2) do
t[retainkeys and k or (#t + 1)] = v
end
return t
end
function lume.find(t, value)
for k, v in pairs(t) do
if v == value then return k end
end
return nil
end
function lume.match(t, fn)
for k, v in pairs(t) do
if fn(v) then return v, k end
end
return nil
end
function lume.count(t, fn)
local count = 0
if fn then
for k, v in pairs(t) do
if fn(v) then count = count + 1 end
end
else
for k in pairs(t) do count = count + 1 end
end
return count
end
function lume.slice(t, i, j)
i = i and absindex(#t, i) or 1
j = j and absindex(#t, j) or #t
local rtn = {}
for x = i < 1 and 1 or i, j > #t and #t or j do
rtn[#rtn + 1] = t[x]
end
return rtn
end
function lume.invert(t)
local rtn = {}
for k, v in pairs(t) do rtn[v] = k end
return rtn
end
function lume.clone(t)
local rtn = {}
for k, v in pairs(t) do rtn[k] = v end
return rtn
end
function lume.fn(fn, ...)
assert(iscallable(fn), "expected a function as the first argument")
local args = {...}
return function(...)
local a = lume.merge(lume.clone(args), {...})
return fn(unpack(a))
end
end
function lume.once(fn, ...)
local fn = lume.fn(fn, ...)
local done = false
return function(...)
if done then return end
done = true
return fn(...)
end
end
function lume.time(fn, ...)
local start = os.clock()
local rtn = {fn(...)}
return (os.clock() - start), unpack(rtn)
end
function lume.combine(...)
local funcs = {...}
assert(lume.all(funcs, iscallable), "expected all arguments to be functions")
return function(...)
for _, f in ipairs(funcs) do f(...) end
end
end
local lambda_cache = {}
function lume.lambda(str)
if not lambda_cache[str] then
local args, body = str:match([[^([%w,_ ]-)%->(.-)$]])
assert(args and body, "bad string lambda")
local s = "return function(" .. args .. ")\nreturn " .. body .. "\nend"
lambda_cache[str] = lume.dostring(s)
end
return lambda_cache[str]
end
function lume.serialize(x)
local f = { string = function(v) return string.format("%q", v) end,
number = tostring, boolean = tostring }
f.table = function(t)
local rtn = {}
for k, v in pairs(t) do
rtn[#rtn + 1] = "[" .. f[type(k)](k) .. "]=" .. f[type(v)](v) .. ","
end
return "{" .. table.concat(rtn) .. "}"
end
local err = function(t,k) error("unsupported serialize type: " .. k) end
setmetatable(f, { __index = err })
return f[type(x)](x)
end
function lume.deserialize(str)
return lume.dostring("return " .. str)
end
function lume.split(str, sep)
if not sep then
return lume.array(str:gmatch("([%S]+)"))
else
assert(sep ~= "", "empty separator")
local psep = patternescape(sep)
return lume.array((str..sep):gmatch("(.-)("..psep..")"))
end
end
function lume.trim(str, chars)
if not chars then return str:match("^[%s]*(.-)[%s]*$") end
chars = patternescape(chars)
return str:match("^[" .. chars .. "]*(.-)[" .. chars .. "]*$")
end
function lume.format(str, vars)
if not vars then return str end
local f = function(x)
return tostring(vars[x] or vars[tonumber(x)] or "{" .. x .. "}")
end
return (str:gsub("{(.-)}", f))
end
function lume.trace(...)
local info = debug.getinfo(2, "Sl")
local t = { "[" .. info.short_src .. ":" .. info.currentline .. "]" }
for i = 1, select("#", ...) do
local x = select(i, ...)
t[#t + 1] = (type(x) == "number") and lume.round(x, .01) or (tostring(x) or "nil")
end
print(table.concat(t, " "))
end
function lume.dostring(str)
return assert((loadstring or load)(str))()
end
function lume.uuid()
local fn = function(x)
local r = math_random(16) - 1
r = (x == "x") and (r + 1) or (r % 4) + 9
return ("0123456789abcdef"):sub(r, r)
end
return (("xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx"):gsub("[xy]", fn))
end
function lume.hotswap(modname)
local oldglobal = lume.clone(_G)
local updated = {}
local function update(old, new)
if updated[old] then return end
updated[old] = true
local oldmt, newmt = getmetatable(old), getmetatable(new)
if oldmt and newmt then update(oldmt, newmt) end
for k, v in pairs(new) do
if type(v) == "table" then update(old[k], v) else old[k] = v end
end
end
local err = nil
local function onerror(e)
for k, v in pairs(_G) do _G[k] = oldglobal[k] end
err = lume.trim(e)
end
local ok, oldmod = pcall(require, modname)
oldmod = ok and oldmod or nil
xpcall(function()
package.loaded[modname] = nil
local newmod = require(modname)
if type(oldmod) == "table" then update(oldmod, newmod) end
for k, v in pairs(oldglobal) do
if v ~= _G[k] and type(v) == "table" then
update(v, _G[k])
_G[k] = v
end
end
end, onerror)
package.loaded[modname] = oldmod
if err then return nil, err end
return oldmod
end
function lume.rgba(color)
local a = math_floor((color / 2 ^ 24) % 256)
local r = math_floor((color / 2 ^ 16) % 256)
local g = math_floor((color / 2 ^ 08) % 256)
local b = math_floor((color) % 256)
return r, g, b, a
end
local chain_mt = {}
chain_mt.__index = lume.map(lume.filter(lume, iscallable, true),
function(fn)
return function(self, ...)
self._value = fn(self._value, ...)
return self
end
end)
chain_mt.__index.result = function(x) return x._value end
function lume.chain(value)
return setmetatable({ _value = value }, chain_mt)
end
return lume
| mit |
ImagicTheCat/vRP | vrp/cfg/gui.lua | 1 | 1135 |
-- gui config file
local cfg = {}
-- additional CSS loaded to customize the gui display (see gui/design.css to know the available css elements)
-- it is not recommended to modify the vRP core files outside the cfg/ directory, create a new resource instead
-- you can load external images/fonts/etc using the NUI absolute path: nui://my_resource/myfont.ttf
-- example, changing the gui font (suppose a vrp_mod resource containing a custom font)
cfg.css = [[
@font-face {
font-family: "Custom Font";
src: url(nui://vrp_mod/customfont.ttf) format("truetype");
}
body{
font-family: "Custom Font";
}
]]
-- list of static menu types (map of name => {.title,.blipid,.blipcolor,.permissions (optional)})
-- static menus are menu with choices defined by menu builders (named "static:name" and with the player parameter)
cfg.static_menu_types = {
["missions"] = { -- example of a mission menu that can be filled by other resources
title = "Missions",
blipid = 205,
blipcolor = 5
}
}
-- list of static menu points
cfg.static_menus = {
{"missions", 1855.13940429688,3688.68579101563,34.2670478820801}
}
return cfg
| mit |
mamaddeveloper/uzz | plugins/steam.lua | 645 | 2117 | -- See https://wiki.teamfortress.com/wiki/User:RJackson/StorefrontAPI
do
local BASE_URL = 'http://store.steampowered.com/api/appdetails/'
local DESC_LENTH = 200
local function unescape(str)
str = string.gsub( str, '<', '<' )
str = string.gsub( str, '>', '>' )
str = string.gsub( str, '"', '"' )
str = string.gsub( str, ''', "'" )
str = string.gsub( str, '&#(%d+);', function(n) return string.char(n) end )
str = string.gsub( str, '&#x(%d+);', function(n) return string.char(tonumber(n,16)) end )
str = string.gsub( str, '&', '&' ) -- Be sure to do this after all others
return str
end
local function get_steam_data (appid)
local url = BASE_URL
url = url..'?appids='..appid
url = url..'&cc=us'
local res,code = http.request(url)
if code ~= 200 then return nil end
local data = json:decode(res)[appid].data
return data
end
local function price_info (data)
local price = '' -- If no data is empty
if data then
local initial = data.initial
local final = data.final or data.initial
local min = math.min(data.initial, data.final)
price = tostring(min/100)
if data.discount_percent and initial ~= final then
price = price..data.currency..' ('..data.discount_percent..'% OFF)'
end
price = price..' (US)'
end
return price
end
local function send_steam_data(data, receiver)
local description = string.sub(unescape(data.about_the_game:gsub("%b<>", "")), 1, DESC_LENTH) .. '...'
local title = data.name
local price = price_info(data.price_overview)
local text = title..' '..price..'\n'..description
local image_url = data.header_image
local cb_extra = {
receiver = receiver,
url = image_url
}
send_msg(receiver, text, send_photo_from_url_callback, cb_extra)
end
local function run(msg, matches)
local appid = matches[1]
local data = get_steam_data(appid)
local receiver = get_receiver(msg)
send_steam_data(data, receiver)
end
return {
description = "Grabs Steam info for Steam links.",
usage = "",
patterns = {
"http://store.steampowered.com/app/([0-9]+)",
},
run = run
}
end
| gpl-2.0 |
cjshmyr/OpenRA | mods/d2k/maps/atreides-01a/atreides01a.lua | 2 | 5022 | --[[
Copyright 2007-2017 The OpenRA Developers (see AUTHORS)
This file is part of OpenRA, which is free software. It is made
available to you 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. For more
information, see COPYING.
]]
HarkonnenReinforcements =
{
easy =
{
{ "light_inf", "light_inf" }
},
normal =
{
{ "light_inf", "light_inf" },
{ "light_inf", "light_inf", "light_inf" },
{ "light_inf", "trike" }
},
hard =
{
{ "light_inf", "light_inf" },
{ "trike", "trike" },
{ "light_inf", "light_inf", "light_inf" },
{ "light_inf", "trike" },
{ "trike", "trike" }
}
}
HarkonnenEntryWaypoints = { HarkonnenWaypoint1.Location, HarkonnenWaypoint2.Location, HarkonnenWaypoint3.Location, HarkonnenWaypoint4.Location }
HarkonnenAttackDelay = DateTime.Seconds(30)
HarkonnenAttackWaves =
{
easy = 1,
normal = 5,
hard = 12
}
ToHarvest =
{
easy = 2500,
normal = 3000,
hard = 3500
}
AtreidesReinforcements = { "light_inf", "light_inf", "light_inf" }
AtreidesEntryPath = { AtreidesWaypoint.Location, AtreidesRally.Location }
Messages =
{
"Build a concrete foundation before placing your buildings.",
"Build a Wind Trap for power.",
"Build a Refinery to collect Spice.",
"Build a Silo to store additional Spice."
}
Tick = function()
if HarkonnenArrived and harkonnen.HasNoRequiredUnits() then
player.MarkCompletedObjective(KillHarkonnen)
end
if player.Resources > SpiceToHarvest - 1 then
player.MarkCompletedObjective(GatherSpice)
end
-- player has no Wind Trap
if (player.PowerProvided <= 20 or player.PowerState ~= "Normal") and DateTime.GameTime % DateTime.Seconds(32) == 0 then
HasPower = false
Media.DisplayMessage(Messages[2], "Mentat")
else
HasPower = true
end
-- player has no Refinery and no Silos
if HasPower and player.ResourceCapacity == 0 and DateTime.GameTime % DateTime.Seconds(32) == 0 then
Media.DisplayMessage(Messages[3], "Mentat")
end
if HasPower and player.Resources > player.ResourceCapacity * 0.8 and DateTime.GameTime % DateTime.Seconds(32) == 0 then
Media.DisplayMessage(Messages[4], "Mentat")
end
UserInterface.SetMissionText("Harvested resources: " .. player.Resources .. "/" .. SpiceToHarvest, player.Color)
end
WorldLoaded = function()
player = Player.GetPlayer("Atreides")
harkonnen = Player.GetPlayer("Harkonnen")
SpiceToHarvest = ToHarvest[Difficulty]
InitObjectives(player)
KillAtreides = harkonnen.AddPrimaryObjective("Kill all Atreides units.")
GatherSpice = player.AddPrimaryObjective("Harvest " .. tostring(SpiceToHarvest) .. " Solaris worth of Spice.")
KillHarkonnen = player.AddSecondaryObjective("Eliminate all Harkonnen units and reinforcements\nin the area.")
local checkResourceCapacity = function()
Trigger.AfterDelay(0, function()
if player.ResourceCapacity < SpiceToHarvest then
Media.DisplayMessage("We don't have enough silo space to store the required amount of Spice!", "Mentat")
Trigger.AfterDelay(DateTime.Seconds(3), function()
harkonnen.MarkCompletedObjective(KillAtreides)
end)
return true
end
end)
end
Trigger.OnRemovedFromWorld(AtreidesConyard, function()
-- Mission already failed, no need to check the other conditions as well
if checkResourceCapacity() then
return
end
local refs = Utils.Where(Map.ActorsInWorld, function(actor) return actor.Type == "refinery" and actor.Owner == player end)
if #refs == 0 then
harkonnen.MarkCompletedObjective(KillAtreides)
else
Trigger.OnAllRemovedFromWorld(refs, function()
harkonnen.MarkCompletedObjective(KillAtreides)
end)
local silos = Utils.Where(Map.ActorsInWorld, function(actor) return actor.Type == "silo" and actor.Owner == player end)
Utils.Do(refs, function(actor) Trigger.OnRemovedFromWorld(actor, checkResourceCapacity) end)
Utils.Do(silos, function(actor) Trigger.OnRemovedFromWorld(actor, checkResourceCapacity) end)
end
end)
Media.DisplayMessage(Messages[1], "Mentat")
Trigger.AfterDelay(DateTime.Seconds(25), function()
Media.PlaySpeechNotification(player, "Reinforce")
Reinforcements.Reinforce(player, AtreidesReinforcements, AtreidesEntryPath)
end)
WavesLeft = HarkonnenAttackWaves[Difficulty]
SendReinforcements()
end
SendReinforcements = function()
local units = HarkonnenReinforcements[Difficulty]
local delay = Utils.RandomInteger(HarkonnenAttackDelay - DateTime.Seconds(2), HarkonnenAttackDelay)
HarkonnenAttackDelay = HarkonnenAttackDelay - (#units * 3 - 3 - WavesLeft) * DateTime.Seconds(1)
if HarkonnenAttackDelay < 0 then HarkonnenAttackDelay = 0 end
Trigger.AfterDelay(delay, function()
Reinforcements.Reinforce(harkonnen, Utils.Random(units), { Utils.Random(HarkonnenEntryWaypoints) }, 10, IdleHunt)
WavesLeft = WavesLeft - 1
if WavesLeft == 0 then
Trigger.AfterDelay(DateTime.Seconds(1), function() HarkonnenArrived = true end)
else
SendReinforcements()
end
end)
end
| gpl-3.0 |
Godfather021/best | plugins/banhammer.lua | 1 | 16333 | -- data saved to moderation.json
do
-- make sure to set with value that not higher than stats.lua
local NUM_MSG_MAX = 4 -- Max number of messages per TIME_CHECK seconds
local TIME_CHECK = 4
local function kick_user(user_id, chat_id)
if user_id == tostring(our_id) then
send_msg('chat#id'..chat_id, 'I won\'t kick myself!', ok_cb, true)
else
chat_del_user('chat#id'..chat_id, 'user#id'..user_id, ok_cb, true)
end
end
local function ban_user(user_id, chat_id)
-- Save to redis
redis:set('banned:'..chat_id..':'..user_id, true)
-- Kick from chat
kick_user(user_id, chat_id)
end
local function superban_user(user_id, chat_id)
redis:set('superbanned:'..user_id, true)
kick_user(user_id, chat_id)
end
local function is_super_banned(user_id)
return redis:get('superbanned:'..user_id) or false
end
local function unban_user(user_id, chat_id)
redis:del('banned:'..chat_id..':'..user_id)
end
local function superunban_user(user_id, chat_id)
redis:del('superbanned:'..user_id)
return 'user '..user_id..' globally banned'
end
local function is_banned(user_id, chat_id)
return redis:get('banned:'..chat_id..':'..user_id) or false
end
local function action_by_id(extra, success, result)
if success == 1 then
local matches = extra.matches
local chat_id = result.id
local receiver = 'chat#id'..chat_id
local group_member = false
for k,v in pairs(result.members) do
if matches[2] == tostring(v.id) then
group_member = true
local full_name = (v.first_name or '')..' '..(v.last_name or '')
if matches[1] == 'ban' then
ban_user(matches[2], chat_id)
send_msg(receiver, full_name..' ['..matches[2]..'] banned', ok_cb, true)
elseif matches[1] == 'superban' then
superban_user(matches[2], chat_id)
send_msg(receiver, full_name..' ['..matches[2]..'] globally banned!', ok_cb, true)
elseif matches[1] == 'kick' then
kick_user(matches[2], chat_id)
end
end
end
if matches[1] == 'unban' then
if is_banned(matches[2], chat_id) then
unban_user(matches[2], chat_id)
send_msg(receiver, 'User with ID ['..matches[2]..'] is unbanned.')
else
send_msg(receiver, 'No user with ID '..matches[2]..' in (super)ban list.')
end
elseif matches[1] == 'superunban' then
if is_super_banned(matches[2]) then
superunban_user(matches[2], chat_id)
send_msg(receiver, 'User with ID ['..matches[2]..'] is globally unbanned.')
else
send_msg(receiver, 'No user with ID '..matches[2]..' in (super)ban list.')
end
end
if not group_member then
send_msg(receiver, 'No user with ID '..matches[2]..' in this group.')
end
end
end
local function action_by_reply(extra, success, result)
local chat_id = result.to.id
local user_id = result.from.id
local full_name = (result.from.first_name or '')..' '..(result.from.last_name or '')
if is_chat_msg(result) and not is_momod(result) then
if extra.match == 'kick' then
chat_del_user('chat#id'..chat_id, 'user#id'..user_id, ok_cb, false)
elseif extra.match == 'ban' then
ban_user(user_id, chat_id)
send_msg('chat#id'..chat_id, 'user '..user_id..' banned', ok_cb, true)
elseif extra.match == 'superban' then
superban_user(user_id, chat_id)
send_msg('chat#id'..chat_id, full_name..' ['..user_id..'] globally banned!')
elseif extra.match == 'unban' then
unban_user(user_id, chat_id)
send_msg('chat#id'..chat_id, 'user '..user_id..' unbanned', ok_cb, true)
elseif extra.match == 'superunban' then
superunban_user(user_id, chat_id)
send_msg('chat#id'..chat_id, full_name..' ['..user_id..'] globally unbanned!')
elseif extra.match == 'whitelist' then
redis:set('whitelist:user#id'..user_id, true)
send_msg('chat#id'..chat_id, full_name..' ['..user_id..'] whitelisted', ok_cb, true)
elseif extra.match == 'unwhitelist' then
redis:del('whitelist:user#id'..user_id)
send_msg('chat#id'..chat_id, full_name..' ['..user_id..'] removed from whitelist', ok_cb, true)
end
else
return 'Use This in Your Groups'
end
end
local function resolve_username(extra, success, result)
local chat_id = extra.msg.to.id
if result ~= false then
local user_id = result.id
local username = result.username
if is_chat_msg(extra.msg) then
-- check if momod users
local is_momoders = false
for v,sudoer in pairs(_config.sudo_users) do
if momoder == user_id then
is_mpmoders = true
end
end
if not is_momoders then
if extra.match == 'kick' then
chat_del_user('chat#id'..chat_id, 'user#id'..result.id, ok_cb, false)
elseif extra.match == 'ban' then
ban_user(user_id, chat_id)
send_msg('chat#id'..chat_id, 'user @'..username..' banned', ok_cb, true)
elseif extra.match == 'superban' then
superban_user(user_id, chat_id)
send_msg('chat#id'..chat_id, 'user @'..username..' ['..user_id..'] globally banned', ok_cb, true)
elseif extra.match == 'unban' then
unban_user(user_id, chat_id)
send_msg('chat#id'..chat_id, 'user @'..username..' unbanned', ok_cb, true)
elseif extra.match == 'superunban' then
superunban_user(user_id, chat_id)
send_msg('chat#id'..chat_id, 'user @'..username..' ['..user_id..'] globally unbanned', ok_cb, true)
end
end
else
return 'Use This in Your Groups.'
end
else
send_msg('chat#id'..chat_id, 'No user @'..extra.user..' in this group.')
end
end
local function trigger_anti_splooder(user_id, chat_id, splooder)
local data = load_data(_config.moderation.data)
local anti_spam_stat = data[tostring(chat_id)]['settings']['anti_flood']
if not redis:get('kicked:'..chat_id..':'..user_id) or false then
if anti_spam_stat == 'kick' then
kick_user(user_id, chat_id)
send_msg('chat#id'..chat_id, 'User '..user_id..' is '..splooder, ok_cb, true)
elseif anti_spam_stat == 'ban' then
ban_user(user_id, chat_id)
send_msg('chat#id'..chat_id, 'User '..user_id..' is '..splooder..'. Banned', ok_cb, true)
end
-- hackish way to avoid mulptiple kicking
redis:setex('kicked:'..chat_id..':'..user_id, 2, 'true')
end
msg = nil
end
local function pre_process(msg)
local user_id = msg.from.id
local chat_id = msg.to.id
-- ANTI SPAM
if msg.from.type == 'user' and msg.text and not is_momod(msg) then
local _nl, ctrl_chars = string.gsub(msg.text, '%c', '')
-- if string length more than 2048 or control characters is more than 50
if string.len(msg.text) > 2048 or ctrl_chars > 50 then
local _c, chars = string.gsub(msg.text, '%a', '')
local _nc, non_chars = string.gsub(msg.text, '%A', '')
-- if non characters is bigger than characters
if non_chars > chars then
local splooder = 'spamming'
trigger_anti_splooder(user_id, chat_id, splooder)
end
end
end
-- ANTI FLOOD
local post_count = 'floodc:'..user_id..':'..chat_id
redis:incr(post_count)
if msg.from.type == 'user' and not is_momod(msg) then
local post_count = 'user:'..user_id..':floodc'
local msgs = tonumber(redis:get(post_count) or 0)
if msgs > NUM_MSG_MAX then
local splooder = 'flooding'
trigger_anti_splooder(user_id, chat_id, splooder)
end
redis:setex(post_count, TIME_CHECK, msgs+1)
end
-- SERVICE MESSAGE
if msg.action and msg.action.type then
local action = msg.action.type
-- Check if banned user joins chat
if action == 'chat_add_user' or action == 'chat_add_user_link' then
if msg.action.link_issuer then
user_id = msg.from.id
else
user_id = msg.action.user.id
end
print('>>> banhammer : Checking invited user '..user_id)
if is_super_banned(user_id) or is_banned(user_id, chat_id) then
print('>>> banhammer : '..user_id..' is (super)banned from '..chat_id)
kick_user(user_id, chat_id)
end
end
-- No further checks
return msg
end
-- BANNED USER TALKING
if is_chat_msg(msg) then
if is_super_banned(user_id) then
print('>>> banhammer : SuperBanned user talking!')
superban_user(user_id, chat_id)
msg.text = ''
elseif is_banned(user_id, chat_id) then
print('>>> banhammer : Banned user talking!')
ban_user(user_id, chat_id)
msg.text = ''
end
end
-- WHITELIST
-- Allow all momod users even if whitelist is allowed
if redis:get('whitelist:enabled') and not is_momod(msg) then
print('>>> banhammer : Whitelist enabled and not momod')
-- Check if user or chat is whitelisted
local allowed = redis:get('whitelist:user#id'..user_id) or false
if not allowed then
print('>>> banhammer : User '..user_id..' not whitelisted')
if is_chat_msg(msg) then
allowed = redis:get('whitelist:chat#id'..chat_id) or false
if not allowed then
print ('Chat '..chat_id..' not whitelisted')
else
print ('Chat '..chat_id..' whitelisted :)')
end
end
else
print('>>> banhammer : User '..user_id..' allowed :)')
end
if not allowed then
msg.text = ''
end
else
print('>>> banhammer : Whitelist not enabled or is momod')
end
return msg
end
local function run(msg, matches)
local receiver = get_receiver(msg)
local user = 'user#id'..(matches[2] or '')
if is_chat_msg(msg) then
if matches[1] == 'kickme' then
if is_momod(msg) or is_admin(msg) then
return 'I won\'t kick an admin!'
elseif is_mod(msg) then
return 'I won\'t kick a moderator!'
else
kick_user(msg.from.id, msg.to.id)
end
end
if is_momod(msg) then
if matches[1] == 'kick' then
if msg.reply_id then
msgr = get_message(msg.reply_id, action_by_reply, {msg=msg, match=matches[1]})
elseif string.match(matches[2], '^%d+$') then
chat_info(receiver, action_by_id, {msg=msg, matches=matches})
elseif string.match(matches[2], '^@.+$') then
msgr = res_user(string.gsub(matches[2], '@', ''), resolve_username, {msg=msg, match=matches[1]})
end
elseif matches[1] == 'ban' then
if msg.reply_id then
msgr = get_message(msg.reply_id, action_by_reply, {msg=msg, match=matches[1]})
elseif string.match(matches[2], '^%d+$') then
chat_info(receiver, action_by_id, {msg=msg, matches=matches})
elseif string.match(matches[2], '^@.+$') then
msgr = res_user(string.gsub(matches[2], '@', ''), resolve_username, {msg=msg, match=matches[1]})
end
elseif matches[1] == 'banlist' then
local text = 'ban list'..msg.to.title..' ['..msg.to.id..']:\n\n'
for k,v in pairs(redis:keys('banned:'..msg.to.id..':*')) do
text = text..k..'. '..v..'\n'
end
return string.gsub(text, 'banned:'..msg.to.id..':', '')
elseif matches[1] == 'unban' then
if msg.reply_id then
msgr = get_message(msg.reply_id, action_by_reply, {msg=msg, match=matches[1]})
elseif string.match(matches[2], '^%d+$') then
chat_info(receiver, action_by_id, {msg=msg, matches=matches})
elseif string.match(matches[2], '^@.+$') then
msgr = res_user(string.gsub(matches[2], '@', ''), resolve_username, {msg=msg, match=matches[1]})
end
end
if matches[1] == 'antispam' then
local data = load_data(_config.moderation.data)
local settings = data[tostring(msg.to.id)]['settings']
if matches[2] == 'kick' then
if settings.anti_flood ~= 'kick' then
settings.anti_flood = 'kick'
save_data(_config.moderation.data, data)
end
return '\n antiflood enabled.'
end
if matches[2] == 'ban' then
if settings.anti_flood ~= 'ban' then
settings.anti_flood = 'ban'
save_data(_config.moderation.data, data)
end
return '\n antiflood enabled and flooder will banned'
end
if matches[2] == 'disable' then
if settings.anti_flood == 'no' then
return 'antiflood disabled'
else
settings.anti_flood = 'no'
save_data(_config.moderation.data, data)
return 'antiflood is not enabled'
end
end
end
if matches[1] == 'whitelist' then
if msg.reply_id then
msgr = get_message(msg.reply_id, action_by_reply, {msg=msg, match=matches[1]})
end
if matches[2] == 'enable' then
redis:set('whitelist:enabled', true)
return 'Enabled whitelist'
elseif matches[2] == 'disable' then
redis:del('whitelist:enabled')
return 'Disabled whitelist'
elseif matches[2] == 'user' then
redis:set('whitelist:user#id'..matches[3], true)
return 'User '..matches[3]..' whitelisted'
elseif matches[2] == 'delete' and matches[3] == 'user' then
redis:del('whitelist:user#id'..matches[4])
return 'User '..matches[4]..' removed from whitelist'
elseif matches[2] == 'chat' then
redis:set('whitelist:chat#id'..msg.to.id, true)
return 'Chat '..msg.to.id..' whitelisted'
elseif matches[2] == 'delete' and matches[3] == 'chat' then
redis:del('whitelist:chat#id'..msg.to.id)
return 'Chat '..msg.to.id..' removed from whitelist'
end
elseif matches[1] == 'unwhitelist' and msg.reply_id then
msgr = get_message(msg.reply_id, action_by_reply, {msg=msg, match=matches[1]})
end
end
if is_admin(msg) then
if matches[1] == 'superban' then
if msg.reply_id then
msgr = get_message(msg.reply_id, action_by_reply, {msg=msg, match=matches[1]})
elseif string.match(matches[2], '^%d+$') then
chat_info(receiver, action_by_id, {msg=msg, matches=matches})
elseif string.match(matches[2], '^@.+$') then
msgr = res_user(string.gsub(matches[2], '@', ''), resolve_username, {msg=msg, match=matches[1]})
end
elseif matches[1] == 'superunban' then
if msg.reply_id then
msgr = get_message(msg.reply_id, action_by_reply, {msg=msg, match=matches[1]})
elseif string.match(matches[2], '^%d+$') then
chat_info(receiver, action_by_id, {msg=msg, matches=matches})
elseif string.match(matches[2], '^@.+$') then
msgr = res_user(string.gsub(matches[2], '@', ''), resolve_username, {msg=msg, match=matches[1]})
end
end
end
else
print '>>> This is not a chat group.'
end
end
return {
patterns = {
'^[!/](antispam) (.*)$',
'^[!/](ban) (.*)$',
'^[!/](ban)$',
'^[!/](banlist)$',
'^[!/](unban) (.*)$',
'^[!/](unban)$',
'^[!/](kick) (.+)$',
'^[!/](kick)$',
'^[!/](kickme)$',
'^!!tgservice (.+)$',
'^[!/](whitelist)$',
'^[!/](whitelist) (chat)$',
'^[!/](whitelist) (delete) (chat)$',
'^[!/](whitelist) (delete) (user) (%d+)$',
'^[!/](whitelist) (disable)$',
'^[!/](whitelist) (enable)$',
'^[!/](whitelist) (user) (%d+)$',
'^[!/](unwhitelist)$',
'^[!/](superban)$',
'^[!/](superban) (.*)$',
'^[!/](superunban)$',
'^[!/](superunban) (.*)$'
},
run = run,
pre_process = pre_process
}
end
| gpl-2.0 |
mamaddeveloper/outo | config.lua | 1 | 2004 | return {
bot_api_key = '138754454:AAHcY427ix65C8XtIb1kgvyoIe2prqxDmg8',
google_api_key = '',
google_cse_key = '',
lastfm_api_key = '',
owm_api_key = '',
biblia_api_key = '',
thecatapi_key = '',
time_offset = 0,
lang = 'en',
admin = 94477327,
admin_name = '💲🔚➰Dev MaMaD Z〽️🔜🔝',
about_text = [[
I am MamadBot, the plugin-wielding, multi-purpose Telegram bot written by @GenerousMan_Bot
/help ro befres!
]] ,
errors = {
connection = 'Connection error.',
results = 'No results found.',
argument = 'Invalid argument.',
syntax = 'Invalid syntax.',
antisquig = 'This group is English only.',
moderation = 'I do not moderate this group.',
not_mod = 'This command must be run by a moderator.',
not_admin = 'This command must be run by an administrator.',
chatter_connection = 'I don\'t feel like talking right now.',
chatter_response = 'I don\'t know what to say to that.'
},
greetings = {
['Hello, #NAME.'] = {
'hello',
'hey',
'sup',
'hi',
'good morning',
'good day',
'good afternoon',
'good evening'
},
['Goodbye, #NAME.'] = {
'bye',
'later',
'see ya',
'good night'
},
['Welcome back, #NAME.'] = {
'i\'m home',
'i\'m back'
},
['You\'re welcome, #NAME.'] = {
'thanks',
'thank you'
}
},
moderation = {
admins = {
['94477327'] = 'You'
},
admin_group = -00000000,
realm_name = 'My Realm'
},
plugins = {
'blacklist.lua',
'floodcontrol.lua',
'control.lua',
'about.lua',
'ping.lua',
'whoami.lua',
'nick.lua',
'echo.lua',
'gSearch.lua',
'gImages.lua',
'gMaps.lua',
'youtube.lua',
'wikipedia.lua',
'hackernews.lua',
'imdb.lua',
'calc.lua',
'urbandictionary.lua',
'time.lua',
'eightball.lua',
'reactions.lua',
'dice.lua',
'reddit.lua',
'xkcd.lua',
'slap.lua',
'commit.lua',
'pun.lua',
'pokedex.lua',
'bandersnatch.lua',
'currency.lua',
'cats.lua',
'shout.lua',
-- Put new plugins here.
'help.lua',
'greetings.lua'
}
}
| gpl-2.0 |
loringmoore/The-Forgotten-Server | data/actions/scripts/quests/quests.lua | 1 | 1502 | local annihilatorReward = {1990, 2400, 2431, 2494}
function onUse(cid, item, fromPosition, itemEx, toPosition, isHotkey)
if item.uid > 1000 and item.uid <= 22670 then
local itemType = ItemType(item.itemid)
local itemWeight = itemType:getWeight()
local player = Player(cid)
local playerCap = player:getFreeCapacity()
if isInArray(annihilatorReward, item.uid) then
if player:getStorageValue(30015) == -1 then
if playerCap >= itemWeight then
if item.uid == 1990 then
player:addItem(1990, 1):addItem(2326, 1)
else
player:addItem(item.uid, 1)
end
player:sendTextMessage(MESSAGE_INFO_DESCR, 'You have found a ' .. itemType:getName() .. '.')
player:setStorageValue(30015, 1)
else
player:sendTextMessage(MESSAGE_INFO_DESCR, 'You have found a ' .. itemType:getName() .. ' weighing ' .. itemWeight .. ' oz it\'s too heavy.')
end
else
player:sendTextMessage(MESSAGE_INFO_DESCR, "It is empty.")
end
elseif player:getStorageValue(item.uid) == -1 then
if playerCap >= itemWeight then
player:sendTextMessage(MESSAGE_INFO_DESCR, 'You have found a ' .. itemType:getName() .. '.')
player:addItem(item.uid, 1)
player:setStorageValue(item.uid, 1)
else
player:sendTextMessage(MESSAGE_INFO_DESCR, 'You have found a ' .. itemType:getName() .. ' weighing ' .. itemWeight .. ' oz it\'s too heavy.')
end
else
player:sendTextMessage(MESSAGE_INFO_DESCR, "It is empty.")
end
else
return false
end
return true
end
| gpl-2.0 |
jfzazo/wireshark-hwgen | src/epan/wslua/template-init.lua | 2 | 4802 | -- init.lua
--
-- initialize wireshark's lua
--
-- This file is going to be executed before any other lua script.
-- It can be used to load libraries, disable functions and more.
--
-- $Id$
--
-- Wireshark - Network traffic analyzer
-- By Gerald Combs <gerald@wireshark.org>
-- Copyright 1998 Gerald Combs
--
-- 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.
-- Set disable_lua to true to disable Lua support.
disable_lua = false
if disable_lua then
return
end
-- If set and we are running with special privileges this setting
-- tells whether scripts other than this one are to be run.
run_user_scripts_when_superuser = false
-- disable potentialy harmful lua functions when running superuser
if running_superuser then
local hint = "has been disabled due to running Wireshark as superuser. See http://wiki.wireshark.org/CaptureSetup/CapturePrivileges for help in running Wireshark as an unprivileged user."
local disabled_lib = {}
setmetatable(disabled_lib,{ __index = function() error("this package ".. hint) end } );
dofile = function() error("dofile " .. hint) end
loadfile = function() error("loadfile " .. hint) end
loadlib = function() error("loadlib " .. hint) end
require = function() error("require " .. hint) end
os = disabled_lib
io = disabled_lib
file = disabled_lib
end
-- to avoid output to stdout which can cause problems lua's print ()
-- has been suppresed so that it yields an error.
-- have print() call info() instead.
if gui_enabled() then
print = info
end
function typeof(obj)
local mt = getmetatable(obj)
return mt and mt.__typeof or obj.__typeof or type(obj)
end
-- the following function checks if a file exists
-- since 1.11.3
function file_exists(name)
local f = io.open(name,"r")
if f ~= nil then io.close(f) return true else return false end
end
-- the following function prepends the given directory name to
-- the package.path, so that a 'require "foo"' will work if 'foo'
-- is in the directory name given to this function. For example,
-- if your Lua file will do a 'require "foo"' and the foo.lua
-- file is in a local directory (local to your script) named 'bar',
-- then call this function before doing your 'require', by doing
-- package.prepend_path("bar")
-- and that will let Wireshark's Lua find the file "bar/foo.lua"
-- when you later do 'require "foo"'
--
-- Because this function resides here in init.lua, it does not
-- have the same environment as your script, so it has to get it
-- using the debug library, which is why the code appears so
-- cumbersome.
--
-- since 1.11.3
function package.prepend_path(name)
local debug = require "debug"
-- get the function calling this package.prepend_path function
local dt = debug.getinfo(2, "f")
if not dt then
error("could not retrieve debug info table")
end
-- get its upvalue
local _, val = debug.getupvalue(dt.func, 1)
if not val or type(val) ~= 'table' then
error("No calling function upvalue or it is not a table")
end
-- get the __DIR__ field in its upvalue table
local dir = val["__DIR__"]
-- get the platform-specific directory separator character
local sep = package.config:sub(1,1)
-- prepend the dir and given name to path
if dir and dir:len() > 0 then
package.path = dir .. sep .. name .. sep .. "?.lua;" .. package.path
end
-- also prepend just the name as a directory
package.path = name .. sep .. "?.lua;" .. package.path
end
-- %WTAP_ENCAPS%
-- %WTAP_FILETYPES%
-- %WTAP_COMMENTTYPES%
-- %FT_TYPES%
-- the following table is since 1.12
-- %WTAP_REC_TYPES%
-- the following table is since 1.11.3
-- %WTAP_PRESENCE_FLAGS%
-- %BASES%
-- %ENCODINGS%
-- %EXPERT%
-- the following table is since 1.11.3
-- %EXPERT_TABLE%
-- %MENU_GROUPS%
-- other useful constants
GUI_ENABLED = gui_enabled()
DATA_DIR = Dir.global_config_path()
USER_DIR = Dir.personal_config_path()
-- deprecated function names
datafile_path = Dir.global_config_path
persconffile_path = Dir.personal_config_path
dofile(DATA_DIR.."console.lua")
--dofile(DATA_DIR.."dtd_gen.lua")
| gpl-2.0 |
jozadaquebatista/textadept | modules/textadept/menu.lua | 1 | 16930 | -- Copyright 2007-2015 Mitchell mitchell.att.foicica.com. See LICENSE.
-- Contributions from Robert Gieseke.
local M = {}
--[[ This comment is for LuaDoc.
---
-- Defines the menus used by Textadept.
-- Menus are simply tables and may be edited in place. Submenus have `title`
-- keys with string text.
-- If applicable, load this module last in your *~/.textadept/init.lua*, after
-- [`textadept.keys`]() since it looks up defined key commands to show them in
-- menus.
module('textadept.menu')]]
local _L, buffer, view = _L, buffer, view
local editing, utils = textadept.editing, textadept.keys.utils
local SEPARATOR = {''}
---
-- The default main menubar.
-- @class table
-- @name menubar
local default_menubar = {
{ title = _L['_File'],
{_L['_New'], buffer.new},
{_L['_Open'], io.open_file},
{_L['Open _Recent...'], io.open_recent_file},
{_L['Re_load'], io.reload_file},
{_L['_Save'], io.save_file},
{_L['Save _As'], io.save_file_as},
{_L['Save All'], io.save_all_files},
SEPARATOR,
{_L['_Close'], io.close_buffer},
{_L['Close All'], io.close_all_buffers},
SEPARATOR,
{_L['Loa_d Session...'], textadept.session.load},
{_L['Sav_e Session...'], textadept.session.save},
SEPARATOR,
{_L['_Quit'], quit},
},
{ title = _L['_Edit'],
{_L['_Undo'], buffer.undo},
{_L['_Redo'], buffer.redo},
SEPARATOR,
{_L['Cu_t'], buffer.cut},
{_L['_Copy'], buffer.copy},
{_L['_Paste'], buffer.paste},
{_L['Duplicate _Line'], buffer.line_duplicate},
{_L['_Delete'], buffer.clear},
{_L['D_elete Word'], utils.delete_word},
{_L['Select _All'], buffer.select_all},
SEPARATOR,
{_L['_Match Brace'], editing.match_brace},
{_L['Complete _Word'], {editing.autocomplete, 'word'}},
{_L['_Highlight Word'], editing.highlight_word},
{_L['Toggle _Block Comment'], editing.block_comment},
{_L['T_ranspose Characters'], editing.transpose_chars},
{_L['_Join Lines'], editing.join_lines},
{_L['_Filter Through'],
{ui.command_entry.enter_mode, 'filter_through', 'bash'}},
{ title = _L['_Select'],
{_L['Select to _Matching Brace'], {editing.match_brace, 'select'}},
{_L['Select between _XML Tags'], {editing.select_enclosed, '>', '<'}},
{_L['Select in XML _Tag'], {editing.select_enclosed, '<', '>'}},
{_L['Select in _Single Quotes'], {editing.select_enclosed, "'", "'"}},
{_L['Select in _Double Quotes'], {editing.select_enclosed, '"', '"'}},
{_L['Select in _Parentheses'], {editing.select_enclosed, '(', ')'}},
{_L['Select in _Brackets'], {editing.select_enclosed, '[', ']'}},
{_L['Select in B_races'], {editing.select_enclosed, '{', '}'}},
{_L['Select _Word'], editing.select_word},
{_L['Select _Line'], editing.select_line},
{_L['Select Para_graph'], editing.select_paragraph},
},
{ title = _L['Selectio_n'],
{_L['_Upper Case Selection'], buffer.upper_case},
{_L['_Lower Case Selection'], buffer.lower_case},
SEPARATOR,
{_L['Enclose as _XML Tags'], utils.enclose_as_xml_tags},
{_L['Enclose as Single XML _Tag'], {editing.enclose, '<', ' />'}},
{_L['Enclose in Single _Quotes'], {editing.enclose, "'", "'"}},
{_L['Enclose in _Double Quotes'], {editing.enclose, '"', '"'}},
{_L['Enclose in _Parentheses'], {editing.enclose, '(', ')'}},
{_L['Enclose in _Brackets'], {editing.enclose, '[', ']'}},
{_L['Enclose in B_races'], {editing.enclose, '{', '}'}},
SEPARATOR,
{_L['_Move Selected Lines Up'], buffer.move_selected_lines_up},
{_L['Move Selected Lines Do_wn'], buffer.move_selected_lines_down},
},
},
{ title = _L['_Search'],
{_L['_Find'], utils.find},
{_L['Find _Next'], ui.find.find_next},
{_L['Find _Previous'], ui.find.find_prev},
{_L['_Replace'], ui.find.replace},
{_L['Replace _All'], ui.find.replace_all},
{_L['Find _Incremental'], ui.find.find_incremental},
SEPARATOR,
{_L['Find in Fi_les'], {utils.find, true}},
{_L['Goto Nex_t File Found'], {ui.find.goto_file_found, false, true}},
{_L['Goto Previou_s File Found'], {ui.find.goto_file_found, false, false}},
SEPARATOR,
{_L['_Jump to'], editing.goto_line},
},
{ title = _L['_Tools'],
{_L['Command _Entry'], {ui.command_entry.enter_mode, 'lua_command', 'lua'}},
{_L['Select Co_mmand'], utils.select_command},
SEPARATOR,
{_L['_Run'], textadept.run.run},
{_L['_Compile'], textadept.run.compile},
{_L['Buil_d'], textadept.run.build},
{_L['S_top'], textadept.run.stop},
{_L['_Next Error'], {textadept.run.goto_error, false, true}},
{_L['_Previous Error'], {textadept.run.goto_error, false, false}},
SEPARATOR,
{ title = _L['_Bookmark'],
{_L['_Toggle Bookmark'], textadept.bookmarks.toggle},
{_L['_Clear Bookmarks'], textadept.bookmarks.clear},
{_L['_Next Bookmark'], {textadept.bookmarks.goto_mark, true}},
{_L['_Previous Bookmark'], {textadept.bookmarks.goto_mark, false}},
{_L['_Goto Bookmark...'], textadept.bookmarks.goto_mark},
},
{ title = _L['Snap_open'],
{_L['Snapopen _User Home'], {io.snapopen, _USERHOME}},
{_L['Snapopen _Textadept Home'], {io.snapopen, _HOME}},
{_L['Snapopen _Current Directory'], utils.snapopen_filedir},
{_L['Snapopen Current _Project'], io.snapopen},
},
{ title = _L['_Snippets'],
{_L['_Insert Snippet...'], textadept.snippets._select},
{_L['_Expand Snippet/Next Placeholder'], textadept.snippets._insert},
{_L['_Previous Snippet Placeholder'], textadept.snippets._previous},
{_L['_Cancel Snippet'], textadept.snippets._cancel_current},
},
SEPARATOR,
{_L['_Complete Symbol'], utils.autocomplete_symbol},
{_L['Show _Documentation'], textadept.editing.show_documentation},
{_L['Show St_yle'], utils.show_style},
},
{ title = _L['_Buffer'],
{_L['_Next Buffer'], {view.goto_buffer, view, 1, true}},
{_L['_Previous Buffer'], {view.goto_buffer, view, -1, true}},
{_L['_Switch to Buffer...'], ui.switch_buffer},
SEPARATOR,
{ title = _L['_Indentation'],
{_L['Tab width: _2'], {utils.set_indentation, 2}},
{_L['Tab width: _3'], {utils.set_indentation, 3}},
{_L['Tab width: _4'], {utils.set_indentation, 4}},
{_L['Tab width: _8'], {utils.set_indentation, 8}},
SEPARATOR,
{_L['_Toggle Use Tabs'], {utils.toggle_property, 'use_tabs'}},
{_L['_Convert Indentation'], editing.convert_indentation},
},
{ title = _L['_EOL Mode'],
{_L['CRLF'], {utils.set_eol_mode, buffer.EOL_CRLF}},
{_L['CR'], {utils.set_eol_mode, buffer.EOL_CR}},
{_L['LF'], {utils.set_eol_mode, buffer.EOL_LF}},
},
{ title = _L['E_ncoding'],
{_L['_UTF-8 Encoding'], {utils.set_encoding, 'UTF-8'}},
{_L['_ASCII Encoding'], {utils.set_encoding, 'ASCII'}},
{_L['_ISO-8859-1 Encoding'], {utils.set_encoding, 'ISO-8859-1'}},
{_L['_MacRoman Encoding'], {utils.set_encoding, 'MacRoman'}},
{_L['UTF-1_6 Encoding'], {utils.set_encoding, 'UTF-16LE'}},
},
SEPARATOR,
{_L['Toggle View _EOL'], {utils.toggle_property, 'view_eol'}},
{_L['Toggle _Wrap Mode'], {utils.toggle_property, 'wrap_mode'}},
{_L['Toggle View White_space'], {utils.toggle_property, 'view_ws'}},
SEPARATOR,
{_L['Select _Lexer...'], textadept.file_types.select_lexer},
{_L['_Refresh Syntax Highlighting'], {buffer.colourise, buffer, 0, -1}},
},
{ title = _L['_View'],
{_L['_Next View'], {ui.goto_view, 1, true}},
{_L['_Previous View'], {ui.goto_view, -1, true}},
SEPARATOR,
{_L['Split View _Horizontal'], {view.split, view}},
{_L['Split View _Vertical'], {view.split, view, true}},
{_L['_Unsplit View'], {view.unsplit, view}},
{_L['Unsplit _All Views'], utils.unsplit_all},
{_L['_Grow View'], utils.grow},
{_L['Shrin_k View'], utils.shrink},
SEPARATOR,
{_L['Toggle Current _Fold'], utils.toggle_current_fold},
SEPARATOR,
{_L['Toggle Show In_dent Guides'],
{utils.toggle_property, 'indentation_guides'}},
{_L['Toggle _Virtual Space'],
{utils.toggle_property, 'virtual_space_options',
buffer.VS_USERACCESSIBLE}},
SEPARATOR,
{_L['Zoom _In'], buffer.zoom_in},
{_L['Zoom _Out'], buffer.zoom_out},
{_L['_Reset Zoom'], utils.reset_zoom},
},
{ title = _L['_Help'],
{_L['Show _Manual'], {utils.open_webpage, _HOME..'/doc/manual.html'}},
{_L['Show _LuaDoc'], {utils.open_webpage, _HOME..'/doc/api.html'}},
SEPARATOR,
{_L['_About'],
{ui.dialogs.msgbox, {title = 'Textadept', text = _RELEASE,
informative_text = 'Copyright © 2007-2015 Mitchell. See LICENSE\n'..
'http://foicica.com/textadept',
icon_file = _HOME..'/core/images/ta_64x64.png'}}},
},
}
---
-- The default right-click context menu.
-- @class table
-- @name context_menu
local default_context_menu = {
{_L['_Undo'], buffer.undo},
{_L['_Redo'], buffer.redo},
SEPARATOR,
{_L['Cu_t'], buffer.cut},
{_L['_Copy'], buffer.copy},
{_L['_Paste'], buffer.paste},
{_L['_Delete'], buffer.clear},
SEPARATOR,
{_L['Select _All'], buffer.select_all}
}
---
-- The default tabbar context menu.
-- @class table
-- @name tab_context_menu
local default_tab_context_menu = {
{_L['_Close'], io.close_buffer},
SEPARATOR,
{_L['_Save'], io.save_file},
{_L['Save _As'], io.save_file_as},
SEPARATOR,
{_L['Re_load'], io.reload_file},
}
-- Table of proxy tables for menus.
local proxies = {}
local key_shortcuts, menu_actions, contextmenu_actions
-- Returns the GDK integer keycode and modifier mask for a key sequence.
-- This is used for creating menu accelerators.
-- @param key_seq The string key sequence.
-- @return keycode and modifier mask
local function get_gdk_key(key_seq)
if not key_seq then return nil end
local mods, key = key_seq:match('^([cams]*)(.+)$')
if not mods or not key then return nil end
local modifiers = ((mods:find('s') or key:lower() ~= key) and 1 or 0) +
(mods:find('c') and 4 or 0) + (mods:find('a') and 8 or 0) +
(mods:find('m') and 0x10000000 or 0)
local byte = string.byte(key)
if #key > 1 or byte < 32 then
for i, s in pairs(keys.KEYSYMS) do
if s == key and i > 0xFE20 then byte = i break end
end
end
return byte, modifiers
end
-- Get a string uniquely identifying a key binding.
-- This is used to match menu items with key bindings to show the key shortcut.
-- @param f A value in the `keys` table.
local function get_id(f)
local id = ''
if type(f) == 'function' then
id = tostring(f)
elseif type(f) == 'table' then
for i = 1, #f do id = id..tostring(f[i]) end
end
return id
end
-- Creates a menu suitable for `ui.menu()` from the menu table format.
-- Also assigns key commands.
-- @param menu The menu to create a GTK+ menu from.
-- @param contextmenu Flag indicating whether or not the menu is a context menu.
-- If so, menu_id offset is 1000. The default value is `false`.
-- @return GTK+ menu that can be passed to `ui.menu()`.
-- @see ui.menu
local function read_menu_table(menu, contextmenu)
local gtkmenu = {}
gtkmenu.title = menu.title
for _, menuitem in ipairs(menu) do
if menuitem.title then
gtkmenu[#gtkmenu + 1] = read_menu_table(menuitem, contextmenu)
else
local label, f = menuitem[1], menuitem[2]
local menu_id = not contextmenu and #menu_actions + 1 or
#contextmenu_actions + 1000 + 1
local key, mods = get_gdk_key(key_shortcuts[get_id(f)])
gtkmenu[#gtkmenu + 1] = {label, menu_id, key, mods}
if f then
local actions = not contextmenu and menu_actions or contextmenu_actions
actions[menu_id < 1000 and menu_id or menu_id - 1000] = f
end
end
end
return gtkmenu
end
-- Builds the item and commands tables for the filtered list dialog.
-- @param menu The menu to read from.
-- @param title The title of the menu.
-- @param items The current list of items.
-- @param commands The current list of commands.
local function build_command_tables(menu, title, items, commands)
for _, menuitem in ipairs(menu) do
if menuitem.title then
build_command_tables(menuitem, menuitem.title, items, commands)
elseif menuitem[1] ~= '' then
local label, f = menuitem[1], menuitem[2]
if title then label = title..': '..label end
items[#items + 1] = label:gsub('_([^_])', '%1')
items[#items + 1] = key_shortcuts[get_id(f)] or ''
commands[#commands + 1] = f
end
end
end
local items, commands
-- Returns a proxy table for menu table *menu* such that when a menu item is
-- changed or added, *update* is called to update the menu in the UI.
-- @param menu The menu or table of menus to create a proxy for.
-- @param update The function to call to update the menu in the UI when a menu
-- item is changed or added.
-- @param menubar Used internally to keep track of the top-level menu for
-- calling *update* with.
local function proxy_menu(menu, update, menubar)
return setmetatable({}, {
__index = function(_, k)
local v = menu[k]
return type(v) == 'table' and proxy_menu(v, update, menubar or menu) or v
end,
__newindex = function(_, k, v)
menu[k] = getmetatable(v) and getmetatable(v).menu or v
update(menubar or menu)
end,
__len = function() return #menu end,
menu = menu -- store existing menu for copying (e.g. m[#m + 1] = m[#m])
})
end
-- Sets `ui.menubar` from menu table *menubar*.
-- Each menu is an ordered list of menu items and has a `title` key for the
-- title text. Menu items are tables containing menu text and either a function
-- to call or a table containing a function with its parameters to call when an
-- item is clicked. Menu items may also be sub-menus, ordered lists of menu
-- items with an additional `title` key for the sub-menu's title text.
-- @param menubar The table of menu tables to create the menubar from.
-- @see ui.menubar
-- @see ui.menu
local function set_menubar(menubar)
key_shortcuts, menu_actions = {}, {}
for key, f in pairs(keys) do key_shortcuts[get_id(f)] = key end
local _menubar = {}
for i = 1, #menubar do
_menubar[#_menubar + 1] = ui.menu(read_menu_table(menubar[i]))
end
ui.menubar = _menubar
items, commands = {}, {}
build_command_tables(menubar, nil, items, commands)
proxies.menubar = proxy_menu(menubar, set_menubar)
end
set_menubar(default_menubar)
-- Sets `ui.context_menu` and `ui.tab_context_menu` from menu item lists
-- *buffer_menu* and *tab_menu*, respectively.
-- Menu items are tables containing menu text and either a function to call or
-- a table containing a function with its parameters to call when an item is
-- clicked. Menu items may also be sub-menus, ordered lists of menu items with
-- an additional `title` key for the sub-menu's title text.
-- @param buffer_menu Optional menu table to create the buffer context menu
-- from. If `nil`, uses the default context menu.
-- @param tab_menu Optional menu table to create the tabbar context menu from.
-- If `nil`, uses the default tab context menu.
-- @see ui.context_menu
-- @see ui.tab_context_menu
-- @see ui.menu
local function set_contextmenus(buffer_menu, tab_menu)
contextmenu_actions = {}
local menu = buffer_menu or default_context_menu
ui.context_menu = ui.menu(read_menu_table(menu, true))
proxies.context_menu = proxy_menu(menu, set_contextmenus)
menu = tab_menu or default_tab_context_menu
ui.tab_context_menu = ui.menu(read_menu_table(menu, true))
proxies.tab_context_menu = proxy_menu(menu, function()
set_contextmenus(nil, menu)
end)
end
if not CURSES then set_contextmenus() end
---
-- Prompts the user to select a menu command to run.
-- @name select_command
function M.select_command()
local button, i = ui.dialogs.filteredlist{
title = _L['Run Command'], columns = {_L['Command'], _L['Key Command']},
items = items, width = CURSES and ui.size[1] - 2 or nil
}
if button ~= 1 or not i then return end
keys.run_command(commands[i], type(commands[i]))
end
-- Performs the appropriate action when clicking a menu item.
events.connect(events.MENU_CLICKED, function(menu_id)
local actions = menu_id < 1000 and menu_actions or contextmenu_actions
local action = actions[menu_id < 1000 and menu_id or menu_id - 1000]
assert(type(action) == 'function' or type(action) == 'table',
_L['Unknown command:']..' '..tostring(action))
keys.run_command(action, type(action))
end)
return setmetatable(M, {
__index = function(_, k) return proxies[k] or M[k] end,
__newindex = function(_, k, v)
if k == 'menubar' then
set_menubar(v)
elseif k == 'context_menu' then
set_contextmenus(v)
elseif k == 'tab_context_menu' then
set_contextmenus(nil, v)
else
rawset(M, k, v)
end
end
})
| mit |
werpat/MoonGen | rfc2544/benchmarks/throughput.lua | 9 | 14322 | package.path = package.path .. "rfc2544/?.lua"
local standalone = false
if master == nil then
standalone = true
master = "dummy"
end
local dpdk = require "dpdk"
local memory = require "memory"
local device = require "device"
local filter = require "filter"
local ffi = require "ffi"
local barrier = require "barrier"
local timer = require "timer"
local utils = require "utils.utils"
local arp = require "proto.arp"
local tikz = require "utils.tikz"
local UDP_PORT = 42
local benchmark = {}
benchmark.__index = benchmark
function benchmark.create()
local self = setmetatable({}, benchmark)
self.initialized = false
return self
end
setmetatable(benchmark, {__call = benchmark.create})
function benchmark:init(arg)
self.duration = arg.duration or 10
self.rateThreshold = arg.rateThreshold or 10
self.maxLossRate = arg.maxLossRate or 0.001
self.rxQueues = arg.rxQueues
self.txQueues = arg.txQueues
self.numIterations = arg.numIterations or 1
self.skipConf = arg.skipConf
self.dut = arg.dut
self.initialized = true
end
function benchmark:config()
self.undoStack = {}
utils.addInterfaceIP(self.dut.ifIn, "198.18.1.1", 24)
table.insert(self.undoStack, {foo = utils.delInterfaceIP, args = {self.dut.ifIn, "198.18.1.1", 24}})
utils.addInterfaceIP(self.dut.ifOut, "198.19.1.1", 24)
table.insert(self.undoStack, {foo = utils.delInterfaceIP, args = {self.dut.ifOut, "198.19.1.1", 24}})
end
function benchmark:undoConfig()
local len = #self.undoStack
for k, v in ipairs(self.undoStack) do
--work in stack order
local elem = self.undoStack[len - k + 1]
elem.foo(unpack(elem.args))
end
--clear stack
self.undoStack = {}
end
function benchmark:getCSVHeader()
local str = "frame size(byte),duration(s),max loss rate(%),rate threshold(packets)"
for i=1, self.numIterations do
str = str .. "," .. "rate(mpps) iter" .. i .. ",spkts(byte) iter" .. i .. ",rpkts(byte) iter" .. i
end
return str
end
function benchmark:resultToCSV(result)
local str = ""
for i=1, self.numIterations do
str = str .. result[i].frameSize .. "," .. self.duration .. "," .. self.maxLossRate * 100 .. "," .. self.rateThreshold .. "," .. result[i].mpps .. "," .. result[i].spkts .. "," .. result[i].rpkts
if i < self.numIterations then
str = str .. "\n"
end
end
return str
end
function benchmark:toTikz(filename, ...)
local values = {}
local numResults = select("#", ...)
for i=1, numResults do
local result = select(i, ...)
local avg = 0
local numVals = 0
local frameSize
for _, v in ipairs(result) do
frameSize = v.frameSize
avg = avg + v.mpps
numVals = numVals + 1
end
avg = avg / numVals
table.insert(values, {k = frameSize, v = avg})
end
table.sort(values, function(e1, e2) return e1.k < e2.k end)
local xtick = ""
local t64 = false
local last = -math.huge
for k, p in ipairs(values) do
if (p.k - last) >= 128 then
xtick = xtick .. p.k
if values[k + 1] then
xtick = xtick .. ","
end
last = p.k
end
end
local imgMpps = tikz.new(filename .. "_mpps" .. ".tikz", [[ xlabel={packet size [byte]}, ylabel={rate [Mpps]}, grid=both, ymin=0, xmin=0, xtick={]] .. xtick .. [[},scaled ticks=false, width=9cm, height=4cm, cycle list name=exotic]])
local imgMbps = tikz.new(filename .. "_mbps" .. ".tikz", [[ xlabel={packet size [byte]}, ylabel={rate [Gbit/s]}, grid=both, ymin=0, xmin=0, xtick={]] .. xtick .. [[},scaled ticks=false, width=9cm, height=4cm, cycle list name=exotic,legend style={at={(0.99,0.02)},anchor=south east}]])
imgMpps:startPlot()
imgMbps:startPlot()
for _, p in ipairs(values) do
imgMpps:addPoint(p.k, p.v)
imgMbps:addPoint(p.k, p.v * (p.k + 20) * 8 / 1000)
end
local legend = "throughput at max " .. self.maxLossRate * 100 .. " \\% packet loss"
imgMpps:endPlot(legend)
imgMbps:endPlot(legend)
imgMpps:startPlot()
imgMbps:startPlot()
for _, p in ipairs(values) do
local linkRate = self.txQueues[1].dev:getLinkStatus().speed
imgMpps:addPoint(p.k, linkRate / (p.k + 20) / 8)
imgMbps:addPoint(p.k, linkRate / 1000)
end
imgMpps:finalize("link rate")
imgMbps:finalize("link rate")
end
function benchmark:bench(frameSize)
if not self.initialized then
return print("benchmark not initialized");
elseif frameSize == nil then
return error("benchmark got invalid frameSize");
end
if not self.skipConf then
self:config()
end
local binSearch = utils.binarySearch()
local pktLost = true
local maxLinkRate = self.txQueues[1].dev:getLinkStatus().speed
local rate, lastRate
local bar = barrier.new(2)
local results = {}
local rateSum = 0
local finished = false
--repeat the test for statistical purpose
for iteration=1,self.numIterations do
local port = UDP_PORT
binSearch:init(0, maxLinkRate)
rate = maxLinkRate -- start at maximum, so theres a chance at reaching maximum (otherwise only maximum - threshold can be reached)
lastRate = rate
printf("starting iteration %d for frameSize %d", iteration, frameSize)
--init maximal transfer rate without packetloss of this iteration to zero
results[iteration] = {spkts = 0, rpkts = 0, mpps = 0, frameSize = frameSize}
-- loop until no packetloss
while dpdk.running() do
-- workaround for rate bug
local numQueues = rate > (64 * 64) / (84 * 84) * maxLinkRate and rate < maxLinkRate and 3 or 1
bar:reinit(numQueues + 1)
if rate < maxLinkRate then
-- not maxLinkRate
-- eventual multiple slaves
-- set rate is payload rate not wire rate
for i=1, numQueues do
printf("set queue %i to rate %d", i, rate * frameSize / (frameSize + 20) / numQueues)
self.txQueues[i]:setRate(rate * frameSize / (frameSize + 20) / numQueues)
end
else
-- maxLinkRate
self.txQueues[1]:setRate(rate)
end
local loadTasks = {}
-- traffic generator
for i=1, numQueues do
table.insert(loadTasks, dpdk.launchLua("throughputLoadSlave", self.txQueues[i], port, frameSize, self.duration, mod, bar))
end
-- count the incoming packets
local ctrTask = dpdk.launchLua("throughputCounterSlave", self.rxQueues[1], port, frameSize, self.duration, bar)
-- wait until all slaves are finished
local spkts = 0
for _, loadTask in pairs(loadTasks) do
spkts = spkts + loadTask:wait()
end
local rpkts = ctrTask:wait()
local lossRate = (spkts - rpkts) / spkts
local validRun = lossRate <= self.maxLossRate
if validRun then
-- theres a minimal gap between self.duration and the real measured duration, but that
-- doesnt matter
results[iteration] = { spkts = spkts, rpkts = rpkts, mpps = spkts / 10^6 / self.duration, frameSize = frameSize}
end
printf("sent %d packets, received %d", spkts, rpkts)
printf("rate %f and packetloss %f => %d", rate, lossRate, validRun and 1 or 0)
lastRate = rate
rate, finished = binSearch:next(rate, validRun, self.rateThreshold)
if finished then
-- not setting rate in table as it is not guaranteed that last round all
-- packets were received properly
local mpps = results[iteration].mpps
printf("maximal rate for packetsize %d: %0.2f Mpps, %0.2f MBit/s, %0.2f MBit/s wire rate", frameSize, mpps, mpps * frameSize * 8, mpps * (frameSize + 20) * 8)
rateSum = rateSum + results[iteration].mpps
break
end
printf("changing rate from %d MBit/s to %d MBit/s", lastRate, rate)
-- TODO: maybe wait for resettlement of DUT (RFC2544)
port = port + 1
dpdk.sleepMillis(100)
--device.reclaimTxBuffers()
end
end
if not self.skipConf then
self:undoConfig()
end
return results, rateSum / self.numIterations
end
function throughputLoadSlave(queue, port, frameSize, duration, modifier, bar)
local ethDst = arp.blockingLookup("198.18.1.1", 10)
--TODO: error on timeout
--wait for counter slave
bar:wait()
-- gen payload template suggested by RFC2544
local udpPayloadLen = frameSize - 46
local udpPayload = ffi.new("uint8_t[?]", udpPayloadLen)
for i = 0, udpPayloadLen - 1 do
udpPayload[i] = bit.band(i, 0xf)
end
local mem = memory.createMemPool(function(buf)
local pkt = buf:getUdpPacket()
pkt:fill{
pktLength = frameSize - 4, -- self sets all length headers fields in all used protocols, -4 for FCS
ethSrc = queue, -- get the src mac from the device
ethDst = ethDst,
-- TODO: too slow with conditional -- eventual launch a second slave for self
-- ethDst SHOULD be in 1% of the frames the hardware broadcast address
-- for switches ethDst also SHOULD be randomized
-- if ipDest is dynamical created it is overwritten
-- does not affect performance, as self fill is done before any packet is sent
ip4Src = "198.18.1.2",
ip4Dst = "198.19.1.2",
udpSrc = UDP_PORT,
-- udpSrc will be set later as it varies
}
-- fill udp payload with prepared udp payload
ffi.copy(pkt.payload, udpPayload, udpPayloadLen)
end)
local bufs = mem:bufArray()
--local modifierFoo = utils.getPktModifierFunction(modifier, baseIp, wrapIp, baseEth, wrapEth)
-- TODO: RFC2544 routing updates if router
-- send learning frames:
-- ARP for IP
local sendBufs = function(bufs, port)
-- allocate buffers from the mem pool and store them in self array
bufs:alloc(frameSize - 4)
for _, buf in ipairs(bufs) do
local pkt = buf:getUdpPacket()
-- set packet udp port
pkt.udp:setDstPort(port)
-- apply modifier like ip or mac randomisation to packet
-- modifierFoo(pkt)
end
-- send packets
bufs:offloadUdpChecksums()
return queue:send(bufs)
end
-- warmup phase to wake up card
local timer = timer:new(0.1)
while timer:running() do
sendBufs(bufs, port - 1)
end
-- benchmark phase
timer:reset(duration)
local totalSent = 0
while timer:running() do
totalSent = totalSent + sendBufs(bufs, port)
end
return totalSent
end
function throughputCounterSlave(queue, port, frameSize, duration, bar)
local bufs = memory.bufArray()
local stats = {}
bar:wait()
local timer = timer:new(duration + 3)
while timer:running() do
local rx = queue:tryRecv(bufs, 1000)
for i = 1, rx do
local buf = bufs[i]
local pkt = buf:getUdpPacket()
local port = pkt.udp:getDstPort()
stats[port] = (stats[port] or 0) + 1
end
bufs:freeAll()
end
return stats[port] or 0
end
--for standalone benchmark
if standalone then
function master()
local args = utils.parseArguments(arg)
local txPort, rxPort = args.txport, args.rxport
if not txPort or not rxPort then
return print("usage: --txport <txport> --rxport <rxport> --duration <duration> --numiterations <numiterations>")
end
local rxDev, txDev
if txPort == rxPort then
-- sending and receiving from the same port
txDev = device.config({port = txPort, rxQueues = 2, txQueues = 4})
rxDev = txDev
else
-- two different ports, different configuration
txDev = device.config({port = txPort, rxQueues = 2, txQueues = 4})
rxDev = device.config({port = rxPort, rxQueues = 2, txQueues = 3})
end
device.waitForLinks()
if txPort == rxPort then
dpdk.launchLua(arp.arpTask, {
{
txQueue = txDev:getTxQueue(0),
rxQueue = txDev:getRxQueue(1),
ips = {"198.18.1.2", "198.19.1.2"}
}
})
else
dpdk.launchLua(arp.arpTask, {
{
txQueue = txDev:getTxQueue(0),
rxQueue = txDev:getRxQueue(1),
ips = {"198.18.1.2"}
},
{
txQueue = rxDev:getTxQueue(0),
rxQueue = rxDev:getRxQueue(1),
ips = {"198.19.1.2", "198.18.1.1"}
}
})
end
local bench = benchmark()
bench:init({
txQueues = {txDev:getTxQueue(1), txDev:getTxQueue(2), txDev:getTxQueue(3)},
rxQueues = {rxDev:getRxQueue(0)},
duration = args.duration,
numIterations = args.numiterations,
skipConf = true,
})
print(bench:getCSVHeader())
local results = {}
local FRAME_SIZES = {64, 128, 256, 512, 1024, 1280, 1518}
for _, frameSize in ipairs(FRAME_SIZES) do
local result = bench:bench(frameSize)
-- save and report results
table.insert(results, result)
print(bench:resultToCSV(result))
end
bench:toTikz("throughput", unpack(results))
end
end
local mod = {}
mod.__index = mod
mod.benchmark = benchmark
return mod
| mit |
frodrigo/osrm-backend | third_party/flatbuffers/tests/MyGame/Example/Vec3.lua | 11 | 1440 | -- automatically generated by the FlatBuffers compiler, do not modify
-- namespace: Example
local flatbuffers = require('flatbuffers')
local Vec3 = {} -- the module
local Vec3_mt = {} -- the class metatable
function Vec3.New()
local o = {}
setmetatable(o, {__index = Vec3_mt})
return o
end
function Vec3_mt:Init(buf, pos)
self.view = flatbuffers.view.New(buf, pos)
end
function Vec3_mt:X()
return self.view:Get(flatbuffers.N.Float32, self.view.pos + 0)
end
function Vec3_mt:Y()
return self.view:Get(flatbuffers.N.Float32, self.view.pos + 4)
end
function Vec3_mt:Z()
return self.view:Get(flatbuffers.N.Float32, self.view.pos + 8)
end
function Vec3_mt:Test1()
return self.view:Get(flatbuffers.N.Float64, self.view.pos + 16)
end
function Vec3_mt:Test2()
return self.view:Get(flatbuffers.N.Uint8, self.view.pos + 24)
end
function Vec3_mt:Test3(obj)
obj:Init(self.view.bytes, self.view.pos + 26)
return obj
end
function Vec3.CreateVec3(builder, x, y, z, test1, test2, test3_a, test3_b)
builder:Prep(8, 32)
builder:Pad(2)
builder:Prep(2, 4)
builder:Pad(1)
builder:PrependInt8(test3_b)
builder:PrependInt16(test3_a)
builder:Pad(1)
builder:PrependUint8(test2)
builder:PrependFloat64(test1)
builder:Pad(4)
builder:PrependFloat32(z)
builder:PrependFloat32(y)
builder:PrependFloat32(x)
return builder:Offset()
end
return Vec3 -- return the module | bsd-2-clause |
osgcc/ryzom | ryzom/client/data/gamedev/interfaces_v3/out_v2_appear.lua | 3 | 5855 | -- In this file we define functions that serves outgame character creation
------------------------------------------------------------------------------------------------------------
-- create the game namespace without reseting if already created in an other file.
if (outgame==nil) then
outgame= {};
end
------------------------------------------------------------------------------------------------------------
-- called to construct icons
function outgame:activePackElement(id, icon)
local uiDesc = getUI("ui:outgame:appear:job_options:options:desc");
uiDesc['ico' .. tostring(id)].active= true;
uiDesc['ico' .. tostring(id)].texture= icon;
uiDesc['ico' .. tostring(id) .. 'txt'].active= true;
end
------------------------------------------------------------------------------------------------------------
-- called to construct pack text
function outgame:setPackJobText(id, spec)
-- Set Pack content
local uiPackText = getUI("ui:outgame:appear:job_options:options:desc:pack_" .. id);
uiPackText.hardtext= "uiCP_Job_" .. id .. tostring(spec);
-- Set specialization text
local uiResText = getUI("ui:outgame:appear:job_options:options:result:res");
if(spec==2) then
uiResText.hardtext= "uiCP_Res_" .. id;
end
end
------------------------------------------------------------------------------------------------------------
-- called to construct pack
function outgame:buildActionPack()
local uiDesc = getUI("ui:outgame:appear:job_options:options:desc");
if (uiDesc==nil) then
return;
end
-- Reset All
for i = 1,20 do
uiDesc['ico' .. tostring(i)].active= false;
uiDesc['ico' .. tostring(i) .. 'txt'].active= false;
end
-- Build Default Combat
self:activePackElement(1, 'f1.tga'); -- Dagger
self:activePackElement(2, 'f2.tga'); -- Accurate Attack
-- Build Default Magic
self:activePackElement(6, 'm2.tga'); -- Gloves
self:activePackElement(7, 'm1.tga'); -- Acid
-- Build Default Forage
self:activePackElement(11, 'g1.tga'); -- Forage Tool
self:activePackElement(12, 'g2.tga'); -- Basic Extract
-- Build Default Craft
self:activePackElement(16, 'c2.tga'); -- Craft Tool
self:activePackElement(17, 'c1.tga'); -- 50 raw mat
self:activePackElement(18, 'c3.tga'); -- Craft Root
self:activePackElement(19, 'c4.tga'); -- Boots Plan
-- Build Option
if (getDbProp('UI:TEMP:JOB_FIGHT') == 2) then
self:activePackElement(3, 'f3.tga'); -- Increase damage
elseif (getDbProp('UI:TEMP:JOB_MAGIC') == 2) then
self:activePackElement(8, 'm5.tga'); -- Fear
elseif (getDbProp('UI:TEMP:JOB_FORAGE') == 2) then
self:activePackElement(13, 'g3.tga'); -- Basic Prospection
elseif (getDbProp('UI:TEMP:JOB_CRAFT') == 2) then
self:activePackElement(20, 'c6.tga'); -- Gloves Plan
self:activePackElement(17, 'c5.tga'); -- Replace 17, with 100x RawMat
end
-- Reset Text
self:setPackJobText('F', 1);
self:setPackJobText('M', 1);
self:setPackJobText('G', 1);
self:setPackJobText('C', 1);
-- Set correct text for specalized version
if (getDbProp('UI:TEMP:JOB_FIGHT') == 2) then
self:setPackJobText('F', 2);
elseif (getDbProp('UI:TEMP:JOB_MAGIC') == 2) then
self:setPackJobText('M', 2);
elseif (getDbProp('UI:TEMP:JOB_FORAGE') == 2) then
self:setPackJobText('G', 2);
elseif (getDbProp('UI:TEMP:JOB_CRAFT') == 2) then
self:setPackJobText('C', 2);
end
end
------------------------------------------------------------------------------------------------------------
-------------------
-- BG DOWNLOADER --
-------------------
--function outgame:getProgressGroup()
-- --debugInfo("*** 1 ***")
-- local grp = getUI("ui:outgame:charsel:bgd_progress")
-- --debugInfo(tostring(grp))
-- return grp
--end
--
--function outgame:setProgressText(ucstr, color, progress, ellipsis)
-- --debugInfo("*** 2 ***")
-- local text = self:getProgressGroup():find("text")
-- local ellipsisTxt = self:getProgressGroup():find("ellipsis")
-- text.color = color
-- text.uc_hardtext = ucstr
-- if ellipsis then
-- ellipsisTxt.hardtext = ellipsis
-- else
-- ellipsisTxt.hardtext = ""
-- end
-- ellipsisTxt.color = color
-- local progressCtrl = self:getProgressGroup():find("progress")
-- progressCtrl.range = 100
-- progressCtrl.value = progress * 100
-- progressCtrl.active = true
--end
--
--
--local progress progressSymbol = { ".", "..", "..." }
--
---- set patching progression (from 0 to 1)
--function outgame:setPatchProgress(progress)
-- --debugInfo("*** 3 ***")
-- local progressPercentText = string.format("%d%%", 100 * progress)
-- local progressPostfix = math.mod(os.time(), 3)
-- --debugInfo("Patch in progress : " .. tostring(progress))
-- local progressDate = nltime.getLocalTime() / 500
-- local colValue = math.floor(230 + 24 * math.sin(progressDate))
-- local color = string.format("%d %d %d %d", colValue, colValue, colValue, 255)
-- self:setProgressText(concatUCString(i18n.get("uiBGD_Progress"), ucstring(progressPercentText)), color, progress, progressSymbol[progressPostfix + 1])
--end
--
--function outgame:setPatchSuccess()
-- --debugInfo("*** 4 ***")
-- --debugInfo("Patch up to date")
-- self:setProgressText(i18n.get("uiBGD_PatchUpToDate"), "0 255 0 255", 1)
--end
--
--
--function outgame:setPatchError()
-- --debugInfo("*** 5 ***")
-- --debugInfo("Patch error")
-- self:setProgressText(i18n.get("uiBGD_PatchError"), "255 0 0 255", 0)
--end
--
--function outgame:setNoPatch()
-- --self:getProgressGroup().active = false
--end
------------------------------------------------------------------------------------------------------------
----------------
--LAUNCH GAME --
----------------
function outgame:launchGame()
if not isPlayerSlotNewbieLand(getPlayerSelectedSlot()) then
if not isFullyPatched() then
messageBoxWithHelp(i18n.get("uiBGD_MainlandCharFullPatchNeeded"), "ui:outgame")
return
end
end
runAH(getUICaller(), "proc", "proc_charsel_play")
end
| agpl-3.0 |
spark51/spark_robot | libs/JSON.lua | 3765 | 34843 | -- -*- coding: utf-8 -*-
--
-- Simple JSON encoding and decoding in pure Lua.
--
-- Copyright 2010-2014 Jeffrey Friedl
-- http://regex.info/blog/
--
-- Latest version: http://regex.info/blog/lua/json
--
-- This code is released under a Creative Commons CC-BY "Attribution" License:
-- http://creativecommons.org/licenses/by/3.0/deed.en_US
--
-- It can be used for any purpose so long as the copyright notice above,
-- the web-page links above, and the 'AUTHOR_NOTE' string below are
-- maintained. Enjoy.
--
local VERSION = 20141223.14 -- version history at end of file
local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-"
--
-- The 'AUTHOR_NOTE' variable exists so that information about the source
-- of the package is maintained even in compiled versions. It's also
-- included in OBJDEF below mostly to quiet warnings about unused variables.
--
local OBJDEF = {
VERSION = VERSION,
AUTHOR_NOTE = AUTHOR_NOTE,
}
--
-- Simple JSON encoding and decoding in pure Lua.
-- http://www.json.org/
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
--
--
--
-- DECODING (from a JSON string to a Lua table)
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- If the JSON text is for an object or an array, e.g.
-- { "what": "books", "count": 3 }
-- or
-- [ "Larry", "Curly", "Moe" ]
--
-- the result is a Lua table, e.g.
-- { what = "books", count = 3 }
-- or
-- { "Larry", "Curly", "Moe" }
--
--
-- The encode and decode routines accept an optional second argument,
-- "etc", which is not used during encoding or decoding, but upon error
-- is passed along to error handlers. It can be of any type (including nil).
--
--
--
-- ERROR HANDLING
--
-- With most errors during decoding, this code calls
--
-- JSON:onDecodeError(message, text, location, etc)
--
-- with a message about the error, and if known, the JSON text being
-- parsed and the byte count where the problem was discovered. You can
-- replace the default JSON:onDecodeError() with your own function.
--
-- The default onDecodeError() merely augments the message with data
-- about the text and the location if known (and if a second 'etc'
-- argument had been provided to decode(), its value is tacked onto the
-- message as well), and then calls JSON.assert(), which itself defaults
-- to Lua's built-in assert(), and can also be overridden.
--
-- For example, in an Adobe Lightroom plugin, you might use something like
--
-- function JSON:onDecodeError(message, text, location, etc)
-- LrErrors.throwUserError("Internal Error: invalid JSON data")
-- end
--
-- or even just
--
-- function JSON.assert(message)
-- LrErrors.throwUserError("Internal Error: " .. message)
-- end
--
-- If JSON:decode() is passed a nil, this is called instead:
--
-- JSON:onDecodeOfNilError(message, nil, nil, etc)
--
-- and if JSON:decode() is passed HTML instead of JSON, this is called:
--
-- JSON:onDecodeOfHTMLError(message, text, nil, etc)
--
-- The use of the fourth 'etc' argument allows stronger coordination
-- between decoding and error reporting, especially when you provide your
-- own error-handling routines. Continuing with the the Adobe Lightroom
-- plugin example:
--
-- function JSON:onDecodeError(message, text, location, etc)
-- local note = "Internal Error: invalid JSON data"
-- if type(etc) = 'table' and etc.photo then
-- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName')
-- end
-- LrErrors.throwUserError(note)
-- end
--
-- :
-- :
--
-- for i, photo in ipairs(photosToProcess) do
-- :
-- :
-- local data = JSON:decode(someJsonText, { photo = photo })
-- :
-- :
-- end
--
--
--
--
--
-- DECODING AND STRICT TYPES
--
-- Because both JSON objects and JSON arrays are converted to Lua tables,
-- it's not normally possible to tell which original JSON type a
-- particular Lua table was derived from, or guarantee decode-encode
-- round-trip equivalency.
--
-- However, if you enable strictTypes, e.g.
--
-- JSON = assert(loadfile "JSON.lua")() --load the routines
-- JSON.strictTypes = true
--
-- then the Lua table resulting from the decoding of a JSON object or
-- JSON array is marked via Lua metatable, so that when re-encoded with
-- JSON:encode() it ends up as the appropriate JSON type.
--
-- (This is not the default because other routines may not work well with
-- tables that have a metatable set, for example, Lightroom API calls.)
--
--
-- ENCODING (from a lua table to a JSON string)
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
-- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false })
--
-- On error during encoding, this code calls:
--
-- JSON:onEncodeError(message, etc)
--
-- which you can override in your local JSON object.
--
-- The 'etc' in the error call is the second argument to encode()
-- and encode_pretty(), or nil if it wasn't provided.
--
--
-- PRETTY-PRINTING
--
-- An optional third argument, a table of options, allows a bit of
-- configuration about how the encoding takes place:
--
-- pretty = JSON:encode(val, etc, {
-- pretty = true, -- if false, no other options matter
-- indent = " ", -- this provides for a three-space indent per nesting level
-- align_keys = false, -- see below
-- })
--
-- encode() and encode_pretty() are identical except that encode_pretty()
-- provides a default options table if none given in the call:
--
-- { pretty = true, align_keys = false, indent = " " }
--
-- For example, if
--
-- JSON:encode(data)
--
-- produces:
--
-- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11}
--
-- then
--
-- JSON:encode_pretty(data)
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- The following three lines return identical results:
-- JSON:encode_pretty(data)
-- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " })
-- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " })
--
-- An example of setting your own indent string:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " })
--
-- produces:
--
-- {
-- | "city": "Kyoto",
-- | "climate": {
-- | | "avg_temp": 16,
-- | | "humidity": "high",
-- | | "snowfall": "minimal"
-- | },
-- | "country": "Japan",
-- | "wards": 11
-- }
--
-- An example of setting align_keys to true:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true })
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- which I must admit is kinda ugly, sorry. This was the default for
-- encode_pretty() prior to version 20141223.14.
--
--
-- AMBIGUOUS SITUATIONS DURING THE ENCODING
--
-- During the encode, if a Lua table being encoded contains both string
-- and numeric keys, it fits neither JSON's idea of an object, nor its
-- idea of an array. To get around this, when any string key exists (or
-- when non-positive numeric keys exist), numeric keys are converted to
-- strings.
--
-- For example,
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- produces the JSON object
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To prohibit this conversion and instead make it an error condition, set
-- JSON.noKeyConversion = true
--
--
-- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT
--
-- assert
-- onDecodeError
-- onDecodeOfNilError
-- onDecodeOfHTMLError
-- onEncodeError
--
-- If you want to create a separate Lua JSON object with its own error handlers,
-- you can reload JSON.lua or use the :new() method.
--
---------------------------------------------------------------------------
local default_pretty_indent = " "
local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent }
local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray
local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject
function OBJDEF:newArray(tbl)
return setmetatable(tbl or {}, isArray)
end
function OBJDEF:newObject(tbl)
return setmetatable(tbl or {}, isObject)
end
local function unicode_codepoint_as_utf8(codepoint)
--
-- codepoint is a number
--
if codepoint <= 127 then
return string.char(codepoint)
elseif codepoint <= 2047 then
--
-- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8
--
local highpart = math.floor(codepoint / 0x40)
local lowpart = codepoint - (0x40 * highpart)
return string.char(0xC0 + highpart,
0x80 + lowpart)
elseif codepoint <= 65535 then
--
-- 1110yyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x1000)
local remainder = codepoint - 0x1000 * highpart
local midpart = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midpart
highpart = 0xE0 + highpart
midpart = 0x80 + midpart
lowpart = 0x80 + lowpart
--
-- Check for an invalid character (thanks Andy R. at Adobe).
-- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070
--
if ( highpart == 0xE0 and midpart < 0xA0 ) or
( highpart == 0xED and midpart > 0x9F ) or
( highpart == 0xF0 and midpart < 0x90 ) or
( highpart == 0xF4 and midpart > 0x8F )
then
return "?"
else
return string.char(highpart,
midpart,
lowpart)
end
else
--
-- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x40000)
local remainder = codepoint - 0x40000 * highpart
local midA = math.floor(remainder / 0x1000)
remainder = remainder - 0x1000 * midA
local midB = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midB
return string.char(0xF0 + highpart,
0x80 + midA,
0x80 + midB,
0x80 + lowpart)
end
end
function OBJDEF:onDecodeError(message, text, location, etc)
if text then
if location then
message = string.format("%s at char %d of: %s", message, location, text)
else
message = string.format("%s: %s", message, text)
end
end
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError
OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError
function OBJDEF:onEncodeError(message, etc)
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
local function grok_number(self, text, start, etc)
--
-- Grab the integer part
--
local integer_part = text:match('^-?[1-9]%d*', start)
or text:match("^-?0", start)
if not integer_part then
self:onDecodeError("expected number", text, start, etc)
end
local i = start + integer_part:len()
--
-- Grab an optional decimal part
--
local decimal_part = text:match('^%.%d+', i) or ""
i = i + decimal_part:len()
--
-- Grab an optional exponential part
--
local exponent_part = text:match('^[eE][-+]?%d+', i) or ""
i = i + exponent_part:len()
local full_number_text = integer_part .. decimal_part .. exponent_part
local as_number = tonumber(full_number_text)
if not as_number then
self:onDecodeError("bad number", text, start, etc)
end
return as_number, i
end
local function grok_string(self, text, start, etc)
if text:sub(start,start) ~= '"' then
self:onDecodeError("expected string's opening quote", text, start, etc)
end
local i = start + 1 -- +1 to bypass the initial quote
local text_len = text:len()
local VALUE = ""
while i <= text_len do
local c = text:sub(i,i)
if c == '"' then
return VALUE, i + 1
end
if c ~= '\\' then
VALUE = VALUE .. c
i = i + 1
elseif text:match('^\\b', i) then
VALUE = VALUE .. "\b"
i = i + 2
elseif text:match('^\\f', i) then
VALUE = VALUE .. "\f"
i = i + 2
elseif text:match('^\\n', i) then
VALUE = VALUE .. "\n"
i = i + 2
elseif text:match('^\\r', i) then
VALUE = VALUE .. "\r"
i = i + 2
elseif text:match('^\\t', i) then
VALUE = VALUE .. "\t"
i = i + 2
else
local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if hex then
i = i + 6 -- bypass what we just read
-- We have a Unicode codepoint. It could be standalone, or if in the proper range and
-- followed by another in a specific range, it'll be a two-code surrogate pair.
local codepoint = tonumber(hex, 16)
if codepoint >= 0xD800 and codepoint <= 0xDBFF then
-- it's a hi surrogate... see whether we have a following low
local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if lo_surrogate then
i = i + 6 -- bypass the low surrogate we just read
codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16)
else
-- not a proper low, so we'll just leave the first codepoint as is and spit it out.
end
end
VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint)
else
-- just pass through what's escaped
VALUE = VALUE .. text:match('^\\(.)', i)
i = i + 2
end
end
end
self:onDecodeError("unclosed string", text, start, etc)
end
local function skip_whitespace(text, start)
local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2
if match_end then
return match_end + 1
else
return start
end
end
local grok_one -- assigned later
local function grok_object(self, text, start, etc)
if text:sub(start,start) ~= '{' then
self:onDecodeError("expected '{'", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '{'
local VALUE = self.strictTypes and self:newObject { } or { }
if text:sub(i,i) == '}' then
return VALUE, i + 1
end
local text_len = text:len()
while i <= text_len do
local key, new_i = grok_string(self, text, i, etc)
i = skip_whitespace(text, new_i)
if text:sub(i, i) ~= ':' then
self:onDecodeError("expected colon", text, i, etc)
end
i = skip_whitespace(text, i + 1)
local new_val, new_i = grok_one(self, text, i)
VALUE[key] = new_val
--
-- Expect now either '}' to end things, or a ',' to allow us to continue.
--
i = skip_whitespace(text, new_i)
local c = text:sub(i,i)
if c == '}' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '}'", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '{'", text, start, etc)
end
local function grok_array(self, text, start, etc)
if text:sub(start,start) ~= '[' then
self:onDecodeError("expected '['", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '['
local VALUE = self.strictTypes and self:newArray { } or { }
if text:sub(i,i) == ']' then
return VALUE, i + 1
end
local VALUE_INDEX = 1
local text_len = text:len()
while i <= text_len do
local val, new_i = grok_one(self, text, i)
-- can't table.insert(VALUE, val) here because it's a no-op if val is nil
VALUE[VALUE_INDEX] = val
VALUE_INDEX = VALUE_INDEX + 1
i = skip_whitespace(text, new_i)
--
-- Expect now either ']' to end things, or a ',' to allow us to continue.
--
local c = text:sub(i,i)
if c == ']' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '['", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '['", text, start, etc)
end
grok_one = function(self, text, start, etc)
-- Skip any whitespace
start = skip_whitespace(text, start)
if start > text:len() then
self:onDecodeError("unexpected end of string", text, nil, etc)
end
if text:find('^"', start) then
return grok_string(self, text, start, etc)
elseif text:find('^[-0123456789 ]', start) then
return grok_number(self, text, start, etc)
elseif text:find('^%{', start) then
return grok_object(self, text, start, etc)
elseif text:find('^%[', start) then
return grok_array(self, text, start, etc)
elseif text:find('^true', start) then
return true, start + 4
elseif text:find('^false', start) then
return false, start + 5
elseif text:find('^null', start) then
return nil, start + 4
else
self:onDecodeError("can't parse JSON", text, start, etc)
end
end
function OBJDEF:decode(text, etc)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc)
end
if text == nil then
self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc)
elseif type(text) ~= 'string' then
self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc)
end
if text:match('^%s*$') then
return nil
end
if text:match('^%s*<') then
-- Can't be JSON... we'll assume it's HTML
self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc)
end
--
-- Ensure that it's not UTF-32 or UTF-16.
-- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3),
-- but this package can't handle them.
--
if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then
self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc)
end
local success, value = pcall(grok_one, self, text, 1, etc)
if success then
return value
else
-- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert.
if self.assert then
self.assert(false, value)
else
assert(false, value)
end
-- and if we're still here, return a nil and throw the error message on as a second arg
return nil, value
end
end
local function backslash_replacement_function(c)
if c == "\n" then
return "\\n"
elseif c == "\r" then
return "\\r"
elseif c == "\t" then
return "\\t"
elseif c == "\b" then
return "\\b"
elseif c == "\f" then
return "\\f"
elseif c == '"' then
return '\\"'
elseif c == '\\' then
return '\\\\'
else
return string.format("\\u%04x", c:byte())
end
end
local chars_to_be_escaped_in_JSON_string
= '['
.. '"' -- class sub-pattern to match a double quote
.. '%\\' -- class sub-pattern to match a backslash
.. '%z' -- class sub-pattern to match a null
.. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters
.. ']'
local function json_string_literal(value)
local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function)
return '"' .. newval .. '"'
end
local function object_or_array(self, T, etc)
--
-- We need to inspect all the keys... if there are any strings, we'll convert to a JSON
-- object. If there are only numbers, it's a JSON array.
--
-- If we'll be converting to a JSON object, we'll want to sort the keys so that the
-- end result is deterministic.
--
local string_keys = { }
local number_keys = { }
local number_keys_must_be_strings = false
local maximum_number_key
for key in pairs(T) do
if type(key) == 'string' then
table.insert(string_keys, key)
elseif type(key) == 'number' then
table.insert(number_keys, key)
if key <= 0 or key >= math.huge then
number_keys_must_be_strings = true
elseif not maximum_number_key or key > maximum_number_key then
maximum_number_key = key
end
else
self:onEncodeError("can't encode table with a key of type " .. type(key), etc)
end
end
if #string_keys == 0 and not number_keys_must_be_strings then
--
-- An empty table, or a numeric-only array
--
if #number_keys > 0 then
return nil, maximum_number_key -- an array
elseif tostring(T) == "JSON array" then
return nil
elseif tostring(T) == "JSON object" then
return { }
else
-- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects
return nil
end
end
table.sort(string_keys)
local map
if #number_keys > 0 then
--
-- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array
-- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object.
--
if self.noKeyConversion then
self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc)
end
--
-- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings
--
map = { }
for key, val in pairs(T) do
map[key] = val
end
table.sort(number_keys)
--
-- Throw numeric keys in there as strings
--
for _, number_key in ipairs(number_keys) do
local string_key = tostring(number_key)
if map[string_key] == nil then
table.insert(string_keys , string_key)
map[string_key] = T[number_key]
else
self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc)
end
end
end
return string_keys, nil, map
end
--
-- Encode
--
-- 'options' is nil, or a table with possible keys:
-- pretty -- if true, return a pretty-printed version
-- indent -- a string (usually of spaces) used to indent each nested level
-- align_keys -- if true, align all the keys when formatting a table
--
local encode_value -- must predeclare because it calls itself
function encode_value(self, value, parents, etc, options, indent)
if value == nil then
return 'null'
elseif type(value) == 'string' then
return json_string_literal(value)
elseif type(value) == 'number' then
if value ~= value then
--
-- NaN (Not a Number).
-- JSON has no NaN, so we have to fudge the best we can. This should really be a package option.
--
return "null"
elseif value >= math.huge then
--
-- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should
-- really be a package option. Note: at least with some implementations, positive infinity
-- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is.
-- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">="
-- case first.
--
return "1e+9999"
elseif value <= -math.huge then
--
-- Negative infinity.
-- JSON has no INF, so we have to fudge the best we can. This should really be a package option.
--
return "-1e+9999"
else
return tostring(value)
end
elseif type(value) == 'boolean' then
return tostring(value)
elseif type(value) ~= 'table' then
self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc)
else
--
-- A table to be converted to either a JSON object or array.
--
local T = value
if type(options) ~= 'table' then
options = {}
end
if type(indent) ~= 'string' then
indent = ""
end
if parents[T] then
self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc)
else
parents[T] = true
end
local result_value
local object_keys, maximum_number_key, map = object_or_array(self, T, etc)
if maximum_number_key then
--
-- An array...
--
local ITEMS = { }
for i = 1, maximum_number_key do
table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent))
end
if options.pretty then
result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]"
else
result_value = "[" .. table.concat(ITEMS, ",") .. "]"
end
elseif object_keys then
--
-- An object
--
local TT = map or T
if options.pretty then
local KEYS = { }
local max_key_length = 0
for _, key in ipairs(object_keys) do
local encoded = encode_value(self, tostring(key), parents, etc, options, indent)
if options.align_keys then
max_key_length = math.max(max_key_length, #encoded)
end
table.insert(KEYS, encoded)
end
local key_indent = indent .. tostring(options.indent or "")
local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "")
local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s"
local COMBINED_PARTS = { }
for i, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent)
table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val))
end
result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}"
else
local PARTS = { }
for _, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, indent)
local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent)
table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val))
end
result_value = "{" .. table.concat(PARTS, ",") .. "}"
end
else
--
-- An empty array/object... we'll treat it as an array, though it should really be an option
--
result_value = "[]"
end
parents[T] = false
return result_value
end
end
function OBJDEF:encode(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or nil)
end
function OBJDEF:encode_pretty(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or default_pretty_options)
end
function OBJDEF.__tostring()
return "JSON encode/decode package"
end
OBJDEF.__index = OBJDEF
function OBJDEF:new(args)
local new = { }
if args then
for key, val in pairs(args) do
new[key] = val
end
end
return setmetatable(new, OBJDEF)
end
return OBJDEF:new()
--
-- Version history:
--
-- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really
-- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines
-- more flexible, and changed the default encode_pretty() to be more generally useful.
--
-- Added a third 'options' argument to the encode() and encode_pretty() routines, to control
-- how the encoding takes place.
--
-- Updated docs to add assert() call to the loadfile() line, just as good practice so that
-- if there is a problem loading JSON.lua, the appropriate error message will percolate up.
--
-- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string,
-- so that the source of the package, and its version number, are visible in compiled copies.
--
-- 20140911.12 Minor lua cleanup.
-- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'.
-- (Thanks to SmugMug's David Parry for these.)
--
-- 20140418.11 JSON nulls embedded within an array were being ignored, such that
-- ["1",null,null,null,null,null,"seven"],
-- would return
-- {1,"seven"}
-- It's now fixed to properly return
-- {1, nil, nil, nil, nil, nil, "seven"}
-- Thanks to "haddock" for catching the error.
--
-- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up.
--
-- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2",
-- and this caused some problems.
--
-- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate,
-- and had of course diverged (encode_pretty didn't get the fixes that encode got, so
-- sometimes produced incorrect results; thanks to Mattie for the heads up).
--
-- Handle encoding tables with non-positive numeric keys (unlikely, but possible).
--
-- If a table has both numeric and string keys, or its numeric keys are inappropriate
-- (such as being non-positive or infinite), the numeric keys are turned into
-- string keys appropriate for a JSON object. So, as before,
-- JSON:encode({ "one", "two", "three" })
-- produces the array
-- ["one","two","three"]
-- but now something with mixed key types like
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- instead of throwing an error produces an object:
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To maintain the prior throw-an-error semantics, set
-- JSON.noKeyConversion = true
--
-- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry.
--
-- 20130120.6 Comment update: added a link to the specific page on my blog where this code can
-- be found, so that folks who come across the code outside of my blog can find updates
-- more easily.
--
-- 20111207.5 Added support for the 'etc' arguments, for better error reporting.
--
-- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent.
--
-- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules:
--
-- * When encoding lua for JSON, Sparse numeric arrays are now handled by
-- spitting out full arrays, such that
-- JSON:encode({"one", "two", [10] = "ten"})
-- returns
-- ["one","two",null,null,null,null,null,null,null,"ten"]
--
-- In 20100810.2 and earlier, only up to the first non-null value would have been retained.
--
-- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999".
-- Version 20100810.2 and earlier created invalid JSON in both cases.
--
-- * Unicode surrogate pairs are now detected when decoding JSON.
--
-- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding
--
-- 20100731.1 initial public release
--
| gpl-2.0 |
MmxBoy/mmxanti2 | libs/JSON.lua | 3765 | 34843 | -- -*- coding: utf-8 -*-
--
-- Simple JSON encoding and decoding in pure Lua.
--
-- Copyright 2010-2014 Jeffrey Friedl
-- http://regex.info/blog/
--
-- Latest version: http://regex.info/blog/lua/json
--
-- This code is released under a Creative Commons CC-BY "Attribution" License:
-- http://creativecommons.org/licenses/by/3.0/deed.en_US
--
-- It can be used for any purpose so long as the copyright notice above,
-- the web-page links above, and the 'AUTHOR_NOTE' string below are
-- maintained. Enjoy.
--
local VERSION = 20141223.14 -- version history at end of file
local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-"
--
-- The 'AUTHOR_NOTE' variable exists so that information about the source
-- of the package is maintained even in compiled versions. It's also
-- included in OBJDEF below mostly to quiet warnings about unused variables.
--
local OBJDEF = {
VERSION = VERSION,
AUTHOR_NOTE = AUTHOR_NOTE,
}
--
-- Simple JSON encoding and decoding in pure Lua.
-- http://www.json.org/
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
--
--
--
-- DECODING (from a JSON string to a Lua table)
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- If the JSON text is for an object or an array, e.g.
-- { "what": "books", "count": 3 }
-- or
-- [ "Larry", "Curly", "Moe" ]
--
-- the result is a Lua table, e.g.
-- { what = "books", count = 3 }
-- or
-- { "Larry", "Curly", "Moe" }
--
--
-- The encode and decode routines accept an optional second argument,
-- "etc", which is not used during encoding or decoding, but upon error
-- is passed along to error handlers. It can be of any type (including nil).
--
--
--
-- ERROR HANDLING
--
-- With most errors during decoding, this code calls
--
-- JSON:onDecodeError(message, text, location, etc)
--
-- with a message about the error, and if known, the JSON text being
-- parsed and the byte count where the problem was discovered. You can
-- replace the default JSON:onDecodeError() with your own function.
--
-- The default onDecodeError() merely augments the message with data
-- about the text and the location if known (and if a second 'etc'
-- argument had been provided to decode(), its value is tacked onto the
-- message as well), and then calls JSON.assert(), which itself defaults
-- to Lua's built-in assert(), and can also be overridden.
--
-- For example, in an Adobe Lightroom plugin, you might use something like
--
-- function JSON:onDecodeError(message, text, location, etc)
-- LrErrors.throwUserError("Internal Error: invalid JSON data")
-- end
--
-- or even just
--
-- function JSON.assert(message)
-- LrErrors.throwUserError("Internal Error: " .. message)
-- end
--
-- If JSON:decode() is passed a nil, this is called instead:
--
-- JSON:onDecodeOfNilError(message, nil, nil, etc)
--
-- and if JSON:decode() is passed HTML instead of JSON, this is called:
--
-- JSON:onDecodeOfHTMLError(message, text, nil, etc)
--
-- The use of the fourth 'etc' argument allows stronger coordination
-- between decoding and error reporting, especially when you provide your
-- own error-handling routines. Continuing with the the Adobe Lightroom
-- plugin example:
--
-- function JSON:onDecodeError(message, text, location, etc)
-- local note = "Internal Error: invalid JSON data"
-- if type(etc) = 'table' and etc.photo then
-- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName')
-- end
-- LrErrors.throwUserError(note)
-- end
--
-- :
-- :
--
-- for i, photo in ipairs(photosToProcess) do
-- :
-- :
-- local data = JSON:decode(someJsonText, { photo = photo })
-- :
-- :
-- end
--
--
--
--
--
-- DECODING AND STRICT TYPES
--
-- Because both JSON objects and JSON arrays are converted to Lua tables,
-- it's not normally possible to tell which original JSON type a
-- particular Lua table was derived from, or guarantee decode-encode
-- round-trip equivalency.
--
-- However, if you enable strictTypes, e.g.
--
-- JSON = assert(loadfile "JSON.lua")() --load the routines
-- JSON.strictTypes = true
--
-- then the Lua table resulting from the decoding of a JSON object or
-- JSON array is marked via Lua metatable, so that when re-encoded with
-- JSON:encode() it ends up as the appropriate JSON type.
--
-- (This is not the default because other routines may not work well with
-- tables that have a metatable set, for example, Lightroom API calls.)
--
--
-- ENCODING (from a lua table to a JSON string)
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
-- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false })
--
-- On error during encoding, this code calls:
--
-- JSON:onEncodeError(message, etc)
--
-- which you can override in your local JSON object.
--
-- The 'etc' in the error call is the second argument to encode()
-- and encode_pretty(), or nil if it wasn't provided.
--
--
-- PRETTY-PRINTING
--
-- An optional third argument, a table of options, allows a bit of
-- configuration about how the encoding takes place:
--
-- pretty = JSON:encode(val, etc, {
-- pretty = true, -- if false, no other options matter
-- indent = " ", -- this provides for a three-space indent per nesting level
-- align_keys = false, -- see below
-- })
--
-- encode() and encode_pretty() are identical except that encode_pretty()
-- provides a default options table if none given in the call:
--
-- { pretty = true, align_keys = false, indent = " " }
--
-- For example, if
--
-- JSON:encode(data)
--
-- produces:
--
-- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11}
--
-- then
--
-- JSON:encode_pretty(data)
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- The following three lines return identical results:
-- JSON:encode_pretty(data)
-- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " })
-- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " })
--
-- An example of setting your own indent string:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " })
--
-- produces:
--
-- {
-- | "city": "Kyoto",
-- | "climate": {
-- | | "avg_temp": 16,
-- | | "humidity": "high",
-- | | "snowfall": "minimal"
-- | },
-- | "country": "Japan",
-- | "wards": 11
-- }
--
-- An example of setting align_keys to true:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true })
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- which I must admit is kinda ugly, sorry. This was the default for
-- encode_pretty() prior to version 20141223.14.
--
--
-- AMBIGUOUS SITUATIONS DURING THE ENCODING
--
-- During the encode, if a Lua table being encoded contains both string
-- and numeric keys, it fits neither JSON's idea of an object, nor its
-- idea of an array. To get around this, when any string key exists (or
-- when non-positive numeric keys exist), numeric keys are converted to
-- strings.
--
-- For example,
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- produces the JSON object
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To prohibit this conversion and instead make it an error condition, set
-- JSON.noKeyConversion = true
--
--
-- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT
--
-- assert
-- onDecodeError
-- onDecodeOfNilError
-- onDecodeOfHTMLError
-- onEncodeError
--
-- If you want to create a separate Lua JSON object with its own error handlers,
-- you can reload JSON.lua or use the :new() method.
--
---------------------------------------------------------------------------
local default_pretty_indent = " "
local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent }
local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray
local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject
function OBJDEF:newArray(tbl)
return setmetatable(tbl or {}, isArray)
end
function OBJDEF:newObject(tbl)
return setmetatable(tbl or {}, isObject)
end
local function unicode_codepoint_as_utf8(codepoint)
--
-- codepoint is a number
--
if codepoint <= 127 then
return string.char(codepoint)
elseif codepoint <= 2047 then
--
-- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8
--
local highpart = math.floor(codepoint / 0x40)
local lowpart = codepoint - (0x40 * highpart)
return string.char(0xC0 + highpart,
0x80 + lowpart)
elseif codepoint <= 65535 then
--
-- 1110yyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x1000)
local remainder = codepoint - 0x1000 * highpart
local midpart = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midpart
highpart = 0xE0 + highpart
midpart = 0x80 + midpart
lowpart = 0x80 + lowpart
--
-- Check for an invalid character (thanks Andy R. at Adobe).
-- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070
--
if ( highpart == 0xE0 and midpart < 0xA0 ) or
( highpart == 0xED and midpart > 0x9F ) or
( highpart == 0xF0 and midpart < 0x90 ) or
( highpart == 0xF4 and midpart > 0x8F )
then
return "?"
else
return string.char(highpart,
midpart,
lowpart)
end
else
--
-- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x40000)
local remainder = codepoint - 0x40000 * highpart
local midA = math.floor(remainder / 0x1000)
remainder = remainder - 0x1000 * midA
local midB = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midB
return string.char(0xF0 + highpart,
0x80 + midA,
0x80 + midB,
0x80 + lowpart)
end
end
function OBJDEF:onDecodeError(message, text, location, etc)
if text then
if location then
message = string.format("%s at char %d of: %s", message, location, text)
else
message = string.format("%s: %s", message, text)
end
end
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError
OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError
function OBJDEF:onEncodeError(message, etc)
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
local function grok_number(self, text, start, etc)
--
-- Grab the integer part
--
local integer_part = text:match('^-?[1-9]%d*', start)
or text:match("^-?0", start)
if not integer_part then
self:onDecodeError("expected number", text, start, etc)
end
local i = start + integer_part:len()
--
-- Grab an optional decimal part
--
local decimal_part = text:match('^%.%d+', i) or ""
i = i + decimal_part:len()
--
-- Grab an optional exponential part
--
local exponent_part = text:match('^[eE][-+]?%d+', i) or ""
i = i + exponent_part:len()
local full_number_text = integer_part .. decimal_part .. exponent_part
local as_number = tonumber(full_number_text)
if not as_number then
self:onDecodeError("bad number", text, start, etc)
end
return as_number, i
end
local function grok_string(self, text, start, etc)
if text:sub(start,start) ~= '"' then
self:onDecodeError("expected string's opening quote", text, start, etc)
end
local i = start + 1 -- +1 to bypass the initial quote
local text_len = text:len()
local VALUE = ""
while i <= text_len do
local c = text:sub(i,i)
if c == '"' then
return VALUE, i + 1
end
if c ~= '\\' then
VALUE = VALUE .. c
i = i + 1
elseif text:match('^\\b', i) then
VALUE = VALUE .. "\b"
i = i + 2
elseif text:match('^\\f', i) then
VALUE = VALUE .. "\f"
i = i + 2
elseif text:match('^\\n', i) then
VALUE = VALUE .. "\n"
i = i + 2
elseif text:match('^\\r', i) then
VALUE = VALUE .. "\r"
i = i + 2
elseif text:match('^\\t', i) then
VALUE = VALUE .. "\t"
i = i + 2
else
local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if hex then
i = i + 6 -- bypass what we just read
-- We have a Unicode codepoint. It could be standalone, or if in the proper range and
-- followed by another in a specific range, it'll be a two-code surrogate pair.
local codepoint = tonumber(hex, 16)
if codepoint >= 0xD800 and codepoint <= 0xDBFF then
-- it's a hi surrogate... see whether we have a following low
local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if lo_surrogate then
i = i + 6 -- bypass the low surrogate we just read
codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16)
else
-- not a proper low, so we'll just leave the first codepoint as is and spit it out.
end
end
VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint)
else
-- just pass through what's escaped
VALUE = VALUE .. text:match('^\\(.)', i)
i = i + 2
end
end
end
self:onDecodeError("unclosed string", text, start, etc)
end
local function skip_whitespace(text, start)
local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2
if match_end then
return match_end + 1
else
return start
end
end
local grok_one -- assigned later
local function grok_object(self, text, start, etc)
if text:sub(start,start) ~= '{' then
self:onDecodeError("expected '{'", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '{'
local VALUE = self.strictTypes and self:newObject { } or { }
if text:sub(i,i) == '}' then
return VALUE, i + 1
end
local text_len = text:len()
while i <= text_len do
local key, new_i = grok_string(self, text, i, etc)
i = skip_whitespace(text, new_i)
if text:sub(i, i) ~= ':' then
self:onDecodeError("expected colon", text, i, etc)
end
i = skip_whitespace(text, i + 1)
local new_val, new_i = grok_one(self, text, i)
VALUE[key] = new_val
--
-- Expect now either '}' to end things, or a ',' to allow us to continue.
--
i = skip_whitespace(text, new_i)
local c = text:sub(i,i)
if c == '}' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '}'", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '{'", text, start, etc)
end
local function grok_array(self, text, start, etc)
if text:sub(start,start) ~= '[' then
self:onDecodeError("expected '['", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '['
local VALUE = self.strictTypes and self:newArray { } or { }
if text:sub(i,i) == ']' then
return VALUE, i + 1
end
local VALUE_INDEX = 1
local text_len = text:len()
while i <= text_len do
local val, new_i = grok_one(self, text, i)
-- can't table.insert(VALUE, val) here because it's a no-op if val is nil
VALUE[VALUE_INDEX] = val
VALUE_INDEX = VALUE_INDEX + 1
i = skip_whitespace(text, new_i)
--
-- Expect now either ']' to end things, or a ',' to allow us to continue.
--
local c = text:sub(i,i)
if c == ']' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '['", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '['", text, start, etc)
end
grok_one = function(self, text, start, etc)
-- Skip any whitespace
start = skip_whitespace(text, start)
if start > text:len() then
self:onDecodeError("unexpected end of string", text, nil, etc)
end
if text:find('^"', start) then
return grok_string(self, text, start, etc)
elseif text:find('^[-0123456789 ]', start) then
return grok_number(self, text, start, etc)
elseif text:find('^%{', start) then
return grok_object(self, text, start, etc)
elseif text:find('^%[', start) then
return grok_array(self, text, start, etc)
elseif text:find('^true', start) then
return true, start + 4
elseif text:find('^false', start) then
return false, start + 5
elseif text:find('^null', start) then
return nil, start + 4
else
self:onDecodeError("can't parse JSON", text, start, etc)
end
end
function OBJDEF:decode(text, etc)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc)
end
if text == nil then
self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc)
elseif type(text) ~= 'string' then
self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc)
end
if text:match('^%s*$') then
return nil
end
if text:match('^%s*<') then
-- Can't be JSON... we'll assume it's HTML
self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc)
end
--
-- Ensure that it's not UTF-32 or UTF-16.
-- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3),
-- but this package can't handle them.
--
if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then
self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc)
end
local success, value = pcall(grok_one, self, text, 1, etc)
if success then
return value
else
-- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert.
if self.assert then
self.assert(false, value)
else
assert(false, value)
end
-- and if we're still here, return a nil and throw the error message on as a second arg
return nil, value
end
end
local function backslash_replacement_function(c)
if c == "\n" then
return "\\n"
elseif c == "\r" then
return "\\r"
elseif c == "\t" then
return "\\t"
elseif c == "\b" then
return "\\b"
elseif c == "\f" then
return "\\f"
elseif c == '"' then
return '\\"'
elseif c == '\\' then
return '\\\\'
else
return string.format("\\u%04x", c:byte())
end
end
local chars_to_be_escaped_in_JSON_string
= '['
.. '"' -- class sub-pattern to match a double quote
.. '%\\' -- class sub-pattern to match a backslash
.. '%z' -- class sub-pattern to match a null
.. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters
.. ']'
local function json_string_literal(value)
local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function)
return '"' .. newval .. '"'
end
local function object_or_array(self, T, etc)
--
-- We need to inspect all the keys... if there are any strings, we'll convert to a JSON
-- object. If there are only numbers, it's a JSON array.
--
-- If we'll be converting to a JSON object, we'll want to sort the keys so that the
-- end result is deterministic.
--
local string_keys = { }
local number_keys = { }
local number_keys_must_be_strings = false
local maximum_number_key
for key in pairs(T) do
if type(key) == 'string' then
table.insert(string_keys, key)
elseif type(key) == 'number' then
table.insert(number_keys, key)
if key <= 0 or key >= math.huge then
number_keys_must_be_strings = true
elseif not maximum_number_key or key > maximum_number_key then
maximum_number_key = key
end
else
self:onEncodeError("can't encode table with a key of type " .. type(key), etc)
end
end
if #string_keys == 0 and not number_keys_must_be_strings then
--
-- An empty table, or a numeric-only array
--
if #number_keys > 0 then
return nil, maximum_number_key -- an array
elseif tostring(T) == "JSON array" then
return nil
elseif tostring(T) == "JSON object" then
return { }
else
-- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects
return nil
end
end
table.sort(string_keys)
local map
if #number_keys > 0 then
--
-- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array
-- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object.
--
if self.noKeyConversion then
self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc)
end
--
-- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings
--
map = { }
for key, val in pairs(T) do
map[key] = val
end
table.sort(number_keys)
--
-- Throw numeric keys in there as strings
--
for _, number_key in ipairs(number_keys) do
local string_key = tostring(number_key)
if map[string_key] == nil then
table.insert(string_keys , string_key)
map[string_key] = T[number_key]
else
self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc)
end
end
end
return string_keys, nil, map
end
--
-- Encode
--
-- 'options' is nil, or a table with possible keys:
-- pretty -- if true, return a pretty-printed version
-- indent -- a string (usually of spaces) used to indent each nested level
-- align_keys -- if true, align all the keys when formatting a table
--
local encode_value -- must predeclare because it calls itself
function encode_value(self, value, parents, etc, options, indent)
if value == nil then
return 'null'
elseif type(value) == 'string' then
return json_string_literal(value)
elseif type(value) == 'number' then
if value ~= value then
--
-- NaN (Not a Number).
-- JSON has no NaN, so we have to fudge the best we can. This should really be a package option.
--
return "null"
elseif value >= math.huge then
--
-- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should
-- really be a package option. Note: at least with some implementations, positive infinity
-- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is.
-- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">="
-- case first.
--
return "1e+9999"
elseif value <= -math.huge then
--
-- Negative infinity.
-- JSON has no INF, so we have to fudge the best we can. This should really be a package option.
--
return "-1e+9999"
else
return tostring(value)
end
elseif type(value) == 'boolean' then
return tostring(value)
elseif type(value) ~= 'table' then
self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc)
else
--
-- A table to be converted to either a JSON object or array.
--
local T = value
if type(options) ~= 'table' then
options = {}
end
if type(indent) ~= 'string' then
indent = ""
end
if parents[T] then
self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc)
else
parents[T] = true
end
local result_value
local object_keys, maximum_number_key, map = object_or_array(self, T, etc)
if maximum_number_key then
--
-- An array...
--
local ITEMS = { }
for i = 1, maximum_number_key do
table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent))
end
if options.pretty then
result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]"
else
result_value = "[" .. table.concat(ITEMS, ",") .. "]"
end
elseif object_keys then
--
-- An object
--
local TT = map or T
if options.pretty then
local KEYS = { }
local max_key_length = 0
for _, key in ipairs(object_keys) do
local encoded = encode_value(self, tostring(key), parents, etc, options, indent)
if options.align_keys then
max_key_length = math.max(max_key_length, #encoded)
end
table.insert(KEYS, encoded)
end
local key_indent = indent .. tostring(options.indent or "")
local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "")
local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s"
local COMBINED_PARTS = { }
for i, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent)
table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val))
end
result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}"
else
local PARTS = { }
for _, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, indent)
local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent)
table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val))
end
result_value = "{" .. table.concat(PARTS, ",") .. "}"
end
else
--
-- An empty array/object... we'll treat it as an array, though it should really be an option
--
result_value = "[]"
end
parents[T] = false
return result_value
end
end
function OBJDEF:encode(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or nil)
end
function OBJDEF:encode_pretty(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or default_pretty_options)
end
function OBJDEF.__tostring()
return "JSON encode/decode package"
end
OBJDEF.__index = OBJDEF
function OBJDEF:new(args)
local new = { }
if args then
for key, val in pairs(args) do
new[key] = val
end
end
return setmetatable(new, OBJDEF)
end
return OBJDEF:new()
--
-- Version history:
--
-- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really
-- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines
-- more flexible, and changed the default encode_pretty() to be more generally useful.
--
-- Added a third 'options' argument to the encode() and encode_pretty() routines, to control
-- how the encoding takes place.
--
-- Updated docs to add assert() call to the loadfile() line, just as good practice so that
-- if there is a problem loading JSON.lua, the appropriate error message will percolate up.
--
-- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string,
-- so that the source of the package, and its version number, are visible in compiled copies.
--
-- 20140911.12 Minor lua cleanup.
-- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'.
-- (Thanks to SmugMug's David Parry for these.)
--
-- 20140418.11 JSON nulls embedded within an array were being ignored, such that
-- ["1",null,null,null,null,null,"seven"],
-- would return
-- {1,"seven"}
-- It's now fixed to properly return
-- {1, nil, nil, nil, nil, nil, "seven"}
-- Thanks to "haddock" for catching the error.
--
-- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up.
--
-- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2",
-- and this caused some problems.
--
-- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate,
-- and had of course diverged (encode_pretty didn't get the fixes that encode got, so
-- sometimes produced incorrect results; thanks to Mattie for the heads up).
--
-- Handle encoding tables with non-positive numeric keys (unlikely, but possible).
--
-- If a table has both numeric and string keys, or its numeric keys are inappropriate
-- (such as being non-positive or infinite), the numeric keys are turned into
-- string keys appropriate for a JSON object. So, as before,
-- JSON:encode({ "one", "two", "three" })
-- produces the array
-- ["one","two","three"]
-- but now something with mixed key types like
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- instead of throwing an error produces an object:
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To maintain the prior throw-an-error semantics, set
-- JSON.noKeyConversion = true
--
-- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry.
--
-- 20130120.6 Comment update: added a link to the specific page on my blog where this code can
-- be found, so that folks who come across the code outside of my blog can find updates
-- more easily.
--
-- 20111207.5 Added support for the 'etc' arguments, for better error reporting.
--
-- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent.
--
-- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules:
--
-- * When encoding lua for JSON, Sparse numeric arrays are now handled by
-- spitting out full arrays, such that
-- JSON:encode({"one", "two", [10] = "ten"})
-- returns
-- ["one","two",null,null,null,null,null,null,null,"ten"]
--
-- In 20100810.2 and earlier, only up to the first non-null value would have been retained.
--
-- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999".
-- Version 20100810.2 and earlier created invalid JSON in both cases.
--
-- * Unicode surrogate pairs are now detected when decoding JSON.
--
-- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding
--
-- 20100731.1 initial public release
--
| gpl-2.0 |
paulmarsy/Console | Libraries/nmap/App/nselib/packet.lua | 2 | 37533 | ---
-- Facilities for manipulating raw packets.
--
-- @author Marek Majkowski <majek04+nse@gmail.com>
-- @copyright Same as Nmap--See http://nmap.org/book/man-legal.html
local bit = require "bit"
local ipOps = require "ipOps"
local nmap = require "nmap"
local stdnse = require "stdnse"
local string = require "string"
local table = require "table"
_ENV = stdnse.module("packet", stdnse.seeall)
----------------------------------------------------------------------------------------------------------------
--- Get an 8-bit integer at a 0-based byte offset in a byte string.
-- @param b A byte string.
-- @param i Offset.
-- @return An 8-bit integer.
function u8(b, i)
return string.byte(b, i+1)
end
--- Get a 16-bit integer at a 0-based byte offset in a byte string.
-- @param b A byte string.
-- @param i Offset.
-- @return A 16-bit integer.
function u16(b, i)
local b1,b2
b1, b2 = string.byte(b, i+1), string.byte(b, i+2)
-- 2^8 2^0
return b1*256 + b2
end
--- Get a 32-bit integer at a 0-based byte offset in a byte string.
-- @param b A byte string.
-- @param i Offset.
-- @return A 32-bit integer.
function u32(b,i)
local b1,b2,b3,b4
b1, b2 = string.byte(b, i+1), string.byte(b, i+2)
b3, b4 = string.byte(b, i+3), string.byte(b, i+4)
-- 2^24 2^16 2^8 2^0
return b1*16777216 + b2*65536 + b3*256 + b4
end
--- Set an 8-bit integer at a 0-based byte offset in a byte string
-- (big-endian).
-- @param b A byte string.
-- @param i Offset.
-- @param num Integer to store.
function set_u8(b, i, num)
local s = string.char(bit.band(num, 0xff))
return b:sub(0+1, i+1-1) .. s .. b:sub(i+1+1)
end
--- Set a 16-bit integer at a 0-based byte offset in a byte string
-- (big-endian).
-- @param b A byte string.
-- @param i Offset.
-- @param num Integer to store.
function set_u16(b, i, num)
local s = string.char(bit.band(bit.rshift(num, 8), 0xff)) .. string.char(bit.band(num, 0xff))
return b:sub(0+1, i+1-1) .. s .. b:sub(i+1+2)
end
--- Set a 32-bit integer at a 0-based byte offset in a byte string
-- (big-endian).
-- @param b A byte string.
-- @param i Offset.
-- @param num Integer to store.
function set_u32(b,i, num)
local s = string.char(bit.band(bit.rshift(num,24), 0xff)) ..
string.char(bit.band(bit.rshift(num,16), 0xff)) ..
string.char(bit.band(bit.rshift(num,8), 0xff)) ..
string.char(bit.band(num, 0xff))
return b:sub(0+1, i+1-1) .. s .. b:sub(i+1+4)
end
--- Get a 1-byte string from a number.
-- @param num A number.
function numtostr8(num)
return string.char(num)
end
--- Get a 2-byte string from a number.
-- (big-endian)
-- @param num A number.
function numtostr16(num)
return set_u16("..", 0, num)
end
--- Get a 4-byte string from a number.
-- (big-endian)
-- @param num A number.
function numtostr32(num)
return set_u32("....", 0, num)
end
--- Calculate a standard Internet checksum.
-- @param b Data to checksum.
-- @return Checksum.
function in_cksum(b)
local sum = 0
local i
-- Note we are using 0-based indexes here.
i = 0
while i < b:len() - 1 do
sum = sum + u16(b, i)
i = i + 2
end
if i < b:len() then
sum = sum + u8(b, i) * 256
end
sum = bit.rshift(sum, 16) + bit.band(sum, 0xffff)
sum = sum + bit.rshift(sum, 16)
sum = bit.bnot(sum)
sum = bit.band(sum, 0xffff) -- truncate to 16 bits
return sum
end
-- ip protocol field
IPPROTO_IP = 0 -- Dummy protocol for TCP
IPPROTO_HOPOPTS = 0 -- IPv6 hop-by-hop options
IPPROTO_ICMP = 1 -- Internet Control Message Protocol
IPPROTO_IGMP = 2 -- Internet Group Management Protocol
IPPROTO_IPIP = 4 -- IPIP tunnels (older KA9Q tunnels use 94)
IPPROTO_TCP = 6 -- Transmission Control Protocol
IPPROTO_EGP = 8 -- Exterior Gateway Protocol
IPPROTO_PUP = 12 -- PUP protocol
IPPROTO_UDP = 17 -- User Datagram Protocol
IPPROTO_IDP = 22 -- XNS IDP protocol
IPPROTO_DCCP = 33 -- Datagram Congestion Control Protocol
IPPROTO_RSVP = 46 -- RSVP protocol
IPPROTO_GRE = 47 -- Cisco GRE tunnels (rfc 1701,1702)
IPPROTO_IPV6 = 41 -- IPv6-in-IPv4 tunnelling
IPPROTO_ROUTING = 43 -- IPv6 routing header
IPPROTO_FRAGMENT= 44 -- IPv6 fragmentation header
IPPROTO_ESP = 50 -- Encapsulation Security Payload protocol
IPPROTO_AH = 51 -- Authentication Header protocol
IPPROTO_ICMPV6 = 58 -- ICMP for IPv6
IPPROTO_DSTOPTS = 60 -- IPv6 destination options
IPPROTO_BEETPH = 94 -- IP option pseudo header for BEET
IPPROTO_PIM = 103 -- Protocol Independent Multicast
IPPROTO_COMP = 108 -- Compression Header protocol
IPPROTO_SCTP = 132 -- Stream Control Transport Protocol
IPPROTO_UDPLITE = 136 -- UDP-Lite (RFC 3828)
ICMP_ECHO_REQUEST = 8
ICMP_ECHO_REPLY = 0
ICMP6_ECHO_REQUEST = 128
ICMP6_ECHO_REPLY = 129
MLD_LISTENER_QUERY = 130
MLD_LISTENER_REPORT = 131
MLD_LISTENER_REDUCTION = 132
ND_ROUTER_SOLICIT = 133
ND_ROUTER_ADVERT = 134
ND_NEIGHBOR_SOLICIT = 135
ND_NEIGHBOR_ADVERT = 136
ND_REDIRECT = 137
MLDV2_LISTENER_REPORT = 143
ND_OPT_SOURCE_LINKADDR = 1
ND_OPT_TARGET_LINKADDR = 2
ND_OPT_PREFIX_INFORMATION = 3
ND_OPT_REDIRECTED_HEADER = 4
ND_OPT_MTU = 5
ND_OPT_RTR_ADV_INTERVAL = 7
ND_OPT_HOME_AGENT_INFO = 8
ETHER_TYPE_IPV4 = "\x08\x00"
ETHER_TYPE_IPV6 = "\x86\xdd"
----------------------------------------------------------------------------------------------------------------
-- Frame is a class
Frame = {}
function Frame:new(frame, force_continue)
local packet = nil
local packet_len = 0
if frame and #frame > 14 then
packet = string.sub(frame, 15, -1)
packet_len = #frame - 14
end
local o = Packet:new(packet, packet_len, force_continue)
o.build_ether_frame = self.build_ether_frame
o.ether_parse = self.ether_parse
o.frame_buf = frame
o:ether_parse()
return o
end
--- Build an Ethernet frame.
-- @param mac_dst six-byte string of the destination MAC address.
-- @param mac_src six-byte string of the source MAC address.
-- @param ether_type two-byte string of the type.
-- @param packet string of the payload.
-- @return frame string of the Ether frame.
function Frame:build_ether_frame(mac_dst, mac_src, ether_type, packet)
self.mac_dst = mac_dst or self.mac_dst
self.mac_src = mac_src or self.mac_src
self.ether_type = ether_type or self.ether_type
self.buf = packet or self.buf
if not self.ether_type then
return nil, "Unknown packet type."
end
self.frame_buf = self.mac_dst..self.mac_src..self.ether_type..self.buf
end
--- Parse an Ethernet frame.
-- @param frame string of the Ether frame.
-- @return mac_dst six-byte string of the destination MAC address.
-- @return mac_src six-byte string of the source MAC address.
-- @return packet string of the payload.
function Frame:ether_parse()
if not self.frame_buf or #self.frame_buf < 14 then -- too short
return false
end
self.mac_dst = string.sub(self.frame_buf, 1, 6)
self.mac_src = string.sub(self.frame_buf, 7, 12)
self.ether_type = u16(self.frame_buf, 12)
end
----------------------------------------------------------------------------------------------------------------
-- Packet is a class
Packet = {}
--- Create a new Packet object.
-- @param packet Binary string with packet data.
-- @param packet_len Packet length. It could be more than
-- <code>#packet</code>.
-- @param force_continue whether an error in parsing headers should be fatal or
-- not. This is especially useful when parsing ICMP packets, where a small ICMP
-- payload could be a TCP header. The problem is that parsing this payload
-- normally would fail because the TCP header is too small.
-- @return A new Packet.
function Packet:new(packet, packet_len, force_continue)
local o = setmetatable({}, {__index = Packet})
if not packet then
return o
end
o.buf = packet
o.packet_len = packet_len
o.ip_v = bit.rshift(string.byte(o.buf), 4)
if o.ip_v == 4 and not o:ip_parse(force_continue) then
return nil
elseif o.ip_v == 6 and not o:ip6_parse(force_continue) then
return nil
end
if o.ip_v == 6 then
while o:ipv6_is_extension_header() do
if not o:ipv6_ext_header_parse(force_continue) or o.ip6_data_offset >= o.packet_len then
stdnse.debug1("Error while parsing IPv6 extension headers.")
return o
end
end
o.ip_p = o.ip6_nhdr
end
if o.ip_p == IPPROTO_TCP then
if not o:tcp_parse(force_continue) then
stdnse.debug1("Error while parsing TCP packet\n")
end
elseif o.ip_p == IPPROTO_UDP then
if not o:udp_parse(force_continue) then
stdnse.debug1("Error while parsing UDP packet\n")
end
elseif o.ip_p == IPPROTO_ICMP then
if not o:icmp_parse(force_continue) then
stdnse.debug1("Error while parsing ICMP packet\n")
end
elseif o.ip_p == IPPROTO_ICMPV6 then
if not o:icmpv6_parse(force_continue) then
stdnse.debug1("Error while parsing ICMPv6 packet\n")
end
end
return o
end
--- Convert Version, Traffic Class and Flow Label to a 4-byte string.
-- @param ip6_tc Number stands for Traffic Class.
-- @param ip6_fl Number stands for Flow Label.
-- @return The first four-byte string of an IPv6 header.
function ipv6_hdr_pack_tc_fl(ip6_tc, ip6_fl)
local ver_tc_fl = bit.lshift(6, 28) +
bit.lshift(bit.band(ip6_tc, 0xFF), 20) +
bit.band(ip6_fl, 0xFFFFF)
return numtostr32(ver_tc_fl)
end
--- Build an IPv6 packet.
-- @param src 16-byte string of the source IPv6 address.
-- @param dsr 16-byte string of the destination IPv6 address.
-- @param nx_hdr integer that represents next header.
-- @param h_limit integer that represents hop limit.
-- @param t_class integer that represents traffic class.
-- @param f_label integer that represents flow label.
function Packet:build_ipv6_packet(src, dst, nx_hdr, payload, h_limit, t_class, f_label)
self.ether_type = ETHER_TYPE_IPV6
self.ip_v = 6
self.ip_bin_src = src or self.ip_bin_src
self.ip_bin_dst = dst or self.ip_bin_dst
self.ip6_nhdr = nx_hdr or self.ip6_nhdr
self.l4_packet = payload or self.l4_packet
self.ip6_tc = t_class or self.ip6_tc or 1
self.ip6_fl = f_label or self.ip6_fl or 1
self.ip6_hlimit = h_limit or self.ip6_hlimit or 255
self.ip6_plen = #(self.exheader or "")+#(self.l4_packet or "")
self.buf =
ipv6_hdr_pack_tc_fl(self.ip6_tc, self.ip6_fl) ..
numtostr16(self.ip6_plen) .. --payload length
string.char(self.ip6_nhdr) .. --next header
string.char(self.ip6_hlimit) .. --hop limit
self.ip_bin_src .. --Source
self.ip_bin_dst ..--dest
(self.exheader or "")..
(self.l4_packet or "")
end
--- Return true if and only if the next header is an known extension header.
-- @param nhdr Next header.
function Packet:ipv6_is_extension_header(nhdr)
self.ip6_nhdr = nhdr or self.ip6_nhdr
if self.ip6_nhdr == IPPROTO_HOPOPTS or
self.ip6_nhdr == IPPROTO_DSTOPTS or
self.ip6_nhdr == IPPROTO_ROUTING or
self.ip6_nhdr == IPPROTO_FRAGMENT then
return true
end
return nil
end
--- Count IPv6 checksum.
-- @return the checksum.
function Packet:count_ipv6_pseudoheader_cksum()
local pseudoheader = self.ip_bin_src .. self.ip_bin_dst .. numtostr16(#self.l4_packet) .. "\0\0\0" .. string.char(self.ip6_nhdr)
local ck_content = pseudoheader .. self.l4_packet
return in_cksum(ck_content)
end
--- Set ICMPv6 checksum.
function Packet:set_icmp6_cksum(check_sum)
self.l4_packet = set_u16(self.l4_packet, 2, check_sum)
end
--- Build an ICMPv6 header.
-- @param icmpv6_type integer that represent ICMPv6 type.
-- @param icmpv6_code integer that represent ICMPv6 code.
-- @param icmpv6_payload string of the payload
-- @param ip_bin_src 16-byte string of the source IPv6 address.
-- @param ip_bin_dst 16-byte string of the destination IPv6 address.
function Packet:build_icmpv6_header(icmpv6_type, icmpv6_code, icmpv6_payload, ip_bin_src, ip_bin_dst)
self.ip6_nhdr = IPPROTO_ICMPV6
self.icmpv6_type = icmpv6_type or self.icmpv6_type
self.icmpv6_code = icmpv6_code or self.icmpv6_code
self.icmpv6_payload = icmpv6_payload or self.icmpv6_payload
self.ip_bin_src = ip_bin_src or self.ip_bin_src
self.ip_bin_dst = ip_bin_dst or self.ip_bin_dst
self.l4_packet =
string.char(self.icmpv6_type,self.icmpv6_code) ..
"\0\0" .. --checksum
(self.icmpv6_payload or "")
local check_sum = self:count_ipv6_pseudoheader_cksum()
self:set_icmp6_cksum(check_sum)
end
--- Build an ICMPv6 Echo Request frame.
-- @param mac_src six-byte string of source MAC address.
-- @param mac_dst sis-byte string of destination MAC address.
-- @param ip_bin_src 16-byte string of source IPv6 address.
-- @param ip_bin_dst 16-byte string of destination IPv6 address.
-- @param id integer that represents Echo ID.
-- @param sequence integer that represents Echo sequence.
-- @param data string of Echo data.
-- @param tc integer that represents traffic class of IPv6 packet.
-- @param fl integer that represents flow label of IPv6 packet.
-- @param hop-limit integer that represents hop limit of IPv6 packet.
function Packet:build_icmpv6_echo_request(id, sequence, data, mac_src, mac_dst, ip_bin_src, ip_bin_dst, tc, fl, hop_limit)
self.mac_src = mac_src or self.mac_src
self.mac_dst = mac_dst or self.mac_dst
self.ip_bin_src = ip_bin_src or self.ip_bin_src
self.ip_bin_dst = ip_bin_dst or self.ip_bin_dst
self.traffic_class = tc or 1
self.flow_label = fl or 1
self.ip6_hlimit = hop_limit or 255
self.icmpv6_type = ICMP6_ECHO_REQUEST
self.icmpv6_code = 0
self.echo_id = id or self.echo_id or 0xdead
self.echo_seq = sequence or self.echo_seq or 0xbeef
self.echo_data = data or self.echo_data or ""
self.icmpv6_payload = numtostr16(self.echo_id) .. numtostr16(self.echo_seq) .. self.echo_data
end
--- Set an ICMPv6 option message.
function Packet:set_icmpv6_option(opt_type,msg)
return string.char(opt_type, (#msg+2)/8) .. msg
end
--- Build an IPv4 packet.
-- @param src 4-byte string of the source IP address.
-- @param dst 4-byte string of the destination IP address.
-- @param payload string containing the IP payload
-- @param dsf byte that represents the differentiated services field
-- @param id integer that represents the IP identification
-- @param flags integer that represents the IP flags
-- @param off integer that represents the IP offset
-- @param ttl integer that represent the IP time to live
-- @param proto integer that represents the IP protocol
function Packet:build_ip_packet(src, dst, payload, dsf, id, flags, off, ttl, proto)
self.ether_type = ETHER_TYPE_IPV4
self.ip_v = 4
self.ip_bin_src = src or self.ip_bin_src
self.ip_bin_dst = dst or self.ip_bin_dst
self.l3_packet = payload or self.l3_packet
self.ip_dsf = dsf or self.ip_dsf or 0
self.ip_p = proto or self.ip_p
self.flags = flags or self.flags or 0 -- should be split into ip_rd, ip_df, ip_mv
self.ip_id = id or self.ip_id or 0xbeef
self.ip_off = off or self.ip_off or 0
self.ip_ttl = ttl or self.ip_ttl or 255
self.buf =
numtostr8(bit.lshift(self.ip_v,4) + 20 / 4) .. -- version and header length
numtostr8(self.ip_dsf) ..
numtostr16(#self.l3_packet + 20) ..
numtostr16(self.ip_id) ..
numtostr8(self.flags) ..
numtostr8(self.ip_off) ..
numtostr8(self.ip_ttl) ..
numtostr8(self.ip_p) ..
numtostr16(0) .. -- checksum
self.ip_bin_src .. --Source
self.ip_bin_dst --dest
self.buf = set_u16(self.buf, 10, in_cksum(self.buf))
self.buf = self.buf .. self.l3_packet
end
--- Build an ICMP header.
-- @param icmp_type integer that represent ICMPv6 type.
-- @param icmp_code integer that represent ICMPv6 code.
-- @param icmp_payload string of the payload
-- @param ip_bin_src 16-byte string of the source IPv6 address.
-- @param ip_bin_dst 16-byte string of the destination IPv6 address.
function Packet:build_icmp_header(icmp_type, icmp_code, icmp_payload, ip_bin_src, ip_bin_dst)
self.icmp_type = icmp_type or self.icmp_type
self.icmp_code = icmp_code or self.icmp_code
self.icmp_payload = icmp_payload or self.icmp_payload
self.ip_bin_src = ip_bin_src or self.ip_bin_src
self.ip_bin_dst = ip_bin_dst or self.ip_bin_dst
self.l3_packet =
string.char(self.icmp_type,self.icmp_code) ..
"\0\0" .. --checksum
(self.icmp_payload or "")
self.l3_packet = set_u16(self.l3_packet, 2, in_cksum(self.l3_packet))
end
--- Build an ICMP Echo Request frame.
-- @param mac_src six-byte string of source MAC address.
-- @param mac_dst sis-byte string of destination MAC address.
-- @param ip_bin_src 16-byte string of source IPv6 address.
-- @param ip_bin_dst 16-byte string of destination IPv6 address.
-- @param id integer that represents Echo ID.
-- @param seq integer that represents Echo sequence.
-- @param data string of Echo data.
-- @param dsf integer that represents differentiated services field.
function Packet:build_icmp_echo_request(id, seq, data, mac_src, mac_dst, ip_bin_src, ip_bin_dst)
self.mac_src = mac_src or self.mac_src
self.mac_dst = mac_dst or self.mac_dst
self.ip_p = IPPROTO_ICMP
self.ip_bin_src = ip_bin_src or self.ip_bin_src
self.ip_bin_dst = ip_bin_dst or self.ip_bin_dst
self.icmp_type = ICMP_ECHO_REQUEST
self.icmp_code = 0
self.echo_id = id or self.echo_id or 0xdead
self.echo_seq = seq or self.echo_seq or 0xbeef
self.echo_data = data or self.echo_data or ""
self.icmp_payload = numtostr16(self.echo_id) .. numtostr16(self.echo_seq) .. self.echo_data
end
-- Helpers
--- Convert a MAC address string (like <code>"00:23:ae:5d:3b:10"</code>) to
-- a raw six-byte long.
-- @param str MAC address string.
-- @return Six-byte string.
function mactobin(str)
if not str then
return nil, "MAC was not specified."
end
return (str:gsub("(%x%x)[^%x]?", function (x)
return string.char(tonumber(x, 16))
end))
end
--- Generate the link-local IPv6 address from the MAC address.
-- @param mac MAC address string.
-- @return Link-local IPv6 address string.
function mac_to_lladdr(mac)
if not mac then
return nil, "MAC was not specified."
end
local interfier = string.char(bit.bor(string.byte(mac,1),0x02))..string.sub(mac,2,3).."\xff\xfe"..string.sub(mac,4,6)
local ll_prefix = ipOps.ip_to_str("fe80::")
return string.sub(ll_prefix,1,8)..interfier
end
--- Get an 8-bit integer at a 0-based byte offset in the packet.
-- @param index Offset.
-- @return An 8-bit integer.
function Packet:u8(index)
return u8(self.buf, index)
end
--- Get a 16-bit integer at a 0-based byte offset in the packet.
-- @param index Offset.
-- @return A 16-bit integer.
function Packet:u16(index)
return u16(self.buf, index)
end
--- Get a 32-bit integer at a 0-based byte offset in the packet.
-- @param index Offset.
-- @return An 32-bit integer.
function Packet:u32(index)
return u32(self.buf, index)
end
--- Return part of the packet contents as a byte string.
-- @param index The beginning of the part of the packet to extract. The index
-- is 0-based. If omitted the default value is 0 (beginning of the string)
-- @param length The length of the part of the packet to extract. If omitted
-- the remaining contents from index to the end of the string are returned.
-- @return A string.
function Packet:raw(index, length)
if not index then index = 0 end
if not length then length = #self.buf-index end
return string.char(string.byte(self.buf, index+1, index+1+length-1))
end
--- Set an 8-bit integer at a 0-based byte offset in the packet.
-- (big-endian).
-- @param index Offset.
-- @param num Integer to store.
function Packet:set_u8(index, num)
self.buf = set_u8(self.buf, index, num)
return self.buf
end
--- Set a 16-bit integer at a 0-based byte offset in the packet.
-- (big-endian).
-- @param index Offset.
-- @param num Integer to store.
function Packet:set_u16(index, num)
self.buf = set_u16(self.buf, index, num)
return self.buf
end
--- Set a 32-bit integer at a 0-based byte offset in the packet.
-- (big-endian).
-- @param index Offset.
-- @param num Integer to store.
function Packet:set_u32(index, num)
self.buf = set_u32(self.buf, index, num)
return self.buf
end
--- Parse an IP packet header.
-- @param force_continue Ignored.
-- @return Whether the parsing succeeded.
function Packet:ip_parse(force_continue)
self.ip_offset = 0
if #self.buf < 20 then -- too short
print("too short")
return false
end
self.ip_v = bit.rshift(bit.band(self:u8(self.ip_offset + 0), 0xF0), 4)
self.ip_hl = bit.band(self:u8(self.ip_offset + 0), 0x0F) -- header_length or data_offset
if self.ip_v ~= 4 then -- not ip
print("not v4")
return false
end
self.ip = true
self.ip_tos = self:u8(self.ip_offset + 1)
self.ip_len = self:u16(self.ip_offset + 2)
self.ip_id = self:u16(self.ip_offset + 4)
self.ip_off = self:u16(self.ip_offset + 6)
self.ip_rf = bit.band(self.ip_off, 0x8000)~=0 -- true/false
self.ip_df = bit.band(self.ip_off, 0x4000)~=0
self.ip_mf = bit.band(self.ip_off, 0x2000)~=0
self.ip_off = bit.band(self.ip_off, 0x1FFF) -- fragment offset
self.ip_ttl = self:u8(self.ip_offset + 8)
self.ip_p = self:u8(self.ip_offset + 9)
self.ip_sum = self:u16(self.ip_offset + 10)
self.ip_bin_src = self:raw(self.ip_offset + 12,4) -- raw 4-bytes string
self.ip_bin_dst = self:raw(self.ip_offset + 16,4)
self.ip_src = ipOps.str_to_ip(self.ip_bin_src) -- formatted string
self.ip_dst = ipOps.str_to_ip(self.ip_bin_dst)
self.ip_opt_offset = self.ip_offset + 20
self.ip_options = self:parse_options(self.ip_opt_offset, ((self.ip_hl*4)-20))
self.ip_data_offset = self.ip_offset + self.ip_hl*4
return true
end
--- Parse an IPv6 packet header.
-- @param force_continue Ignored.
-- @return Whether the parsing succeeded.
function Packet:ip6_parse(force_continue)
self.ip6_offset = 0
if #self.buf < 40 then -- too short
return false
end
self.ip_v = bit.rshift(bit.band(self:u8(self.ip6_offset + 0), 0xF0), 4)
if self.ip_v ~= 6 then -- not ipv6
return false
end
self.ip6 = true
self.ip6_tc = bit.rshift(bit.band(self:u16(self.ip6_offset + 0), 0x0FF0), 4)
self.ip6_fl = bit.band(self:u8(self.ip6_offset + 1), 0x0F)*65536 + self:u16(self.ip6_offset + 2)
self.ip6_plen = self:u16(self.ip6_offset + 4)
self.ip6_nhdr = self:u8(self.ip6_offset + 6)
self.ip6_hlimt = self:u8(self.ip6_offset + 7)
self.ip_bin_src = self:raw(self.ip6_offset + 8, 16)
self.ip_bin_dst = self:raw(self.ip6_offset + 24, 16)
self.ip_src = ipOps.str_to_ip(self.ip_bin_src)
self.ip_dst = ipOps.str_to_ip(self.ip_bin_dst)
self.ip6_data_offset = 40
return true
end
--- Pare an IPv6 extension header. Just jump over it at the moment.
-- @param force_continue Ignored.
-- @return Whether the parsing succeeded.
function Packet:ipv6_ext_header_parse(force_continue)
local ext_hdr_len = self:u8(self.ip6_data_offset + 1)
ext_hdr_len = ext_hdr_len*8 + 8
self.ip6_data_offset = self.ip6_data_offset + ext_hdr_len
self.ip6_nhdr = self:u8(self.ip6_data_offset)
end
--- Set the payload length field.
-- @param plen Payload length.
function Packet:ip6_set_plen(plen)
self:set_u16(self.ip6_offset + 4, plen)
self.ip6_plen = plen
end
--- Set the header length field.
function Packet:ip_set_hl(len)
self:set_u8(self.ip_offset + 0, bit.bor(bit.lshift(self.ip_v, 4), bit.band(len, 0x0F)))
self.ip_v = bit.rshift(bit.band(self:u8(self.ip_offset + 0), 0xF0), 4)
self.ip_hl = bit.band(self:u8(self.ip_offset + 0), 0x0F) -- header_length or data_offset
end
--- Set the packet length field.
-- @param len Packet length.
function Packet:ip_set_len(len)
self:set_u16(self.ip_offset + 2, len)
self.ip_len = len
end
--- Set the packet identification field.
-- @param id packet ID.
function Packet:ip_set_id(id)
self:set_u16(self.ip_offset + 4, id)
self.ip_id = id
end
--- Set the TTL.
-- @param ttl TTL.
function Packet:ip_set_ttl(ttl)
self:set_u8(self.ip_offset + 8, ttl)
self.ip_ttl = ttl
end
--- Set the checksum.
-- @param checksum Checksum.
function Packet:ip_set_checksum(checksum)
self:set_u16(self.ip_offset + 10, checksum)
self.ip_sum = checksum
end
--- Count checksum for packet and save it.
function Packet:ip_count_checksum()
self:ip_set_checksum(0)
local csum = in_cksum( self.buf:sub(0, self.ip_offset + self.ip_hl*4) )
self:ip_set_checksum(csum)
end
--- Set the source IP address.
-- @param binip The source IP address as a byte string.
function Packet:ip_set_bin_src(binip)
local nrip = u32(binip, 0)
self:set_u32(self.ip_offset + 12, nrip)
self.ip_bin_src = self:raw(self.ip_offset + 12,4) -- raw 4-bytes string
end
--- Set the destination IP address.
-- @param binip The destination IP address as a byte string.
function Packet:ip_set_bin_dst(binip)
local nrip = u32(binip, 0)
self:set_u32(self.ip_offset + 16, nrip)
self.ip_bin_dst = self:raw(self.ip_offset + 16,4)
end
--- Set the IP options field (and move the data, count new length,
-- etc.).
-- @param ipoptions IP options.
function Packet:ip_set_options(ipoptions)
-- packet = <ip header> + ipoptions + <payload>
local buf = self.buf:sub(0+1,self.ip_offset + 20) .. ipoptions .. self.buf:sub(self.ip_data_offset+1)
self.buf = buf
-- set ip_len
self:ip_set_len(self.buf:len())
-- set ip_hl
self:ip_set_hl(5 + ipoptions:len()/4)
-- set data offset correctly
self.ip_options = self:parse_options(self.ip_opt_offset, ((self.ip_hl*4)-20))
self.ip_data_offset = self.ip_offset + self.ip_hl*4
if self.tcp then
self.tcp_offset = self.ip_data_offset
elseif self.icmp then
self.icmp_offset = self.ip_data_offset
end
end
--- Get a short string representation of the IP header.
-- @return A string representation of the IP header.
function Packet:ip_tostring()
return string.format(
"IP %s -> %s",
self.ip_src,
self.ip_dst)
end
--- Parse IP/TCP options into a table.
-- @param offset Offset at which options start.
-- @param length Length of options.
-- @return Table of options.
function Packet:parse_options(offset, length)
local options = {}
local op = 1
local opt_ptr = 0
while opt_ptr < length do
local t, l, d
options[op] = {}
t = self:u8(offset + opt_ptr)
options[op].type = t
if t==0 or t==1 then
l = 1
d = nil
else
l = self:u8(offset + opt_ptr + 1)
if l > 2 then
d = self:raw(offset + opt_ptr + 2, l-2)
end
end
options[op].len = l
options[op].data = d
opt_ptr = opt_ptr + l
op = op + 1
end
return options
end
--- Get a short string representation of the packet.
-- @return A string representation of the packet.
function Packet:tostring()
if self.tcp then
return self:tcp_tostring()
elseif self.udp then
return self:udp_tostring()
elseif self.icmp then
return self:icmp_tostring()
elseif self.ip then
return self:ip_tostring()
end
return "<no tostring!>"
end
----------------------------------------------------------------------------------------------------------------
--- Parse an ICMP packet header.
-- @param force_continue Ignored.
-- @return Whether the parsing succeeded.
function Packet:icmp_parse(force_continue)
self.icmp_offset = self.ip_data_offset
if #self.buf < self.icmp_offset + 8 then -- let's say 8 bytes minimum
return false
end
self.icmp = true
self.icmp_type = self:u8(self.icmp_offset + 0)
self.icmp_code = self:u8(self.icmp_offset + 1)
self.icmp_sum = self:u16(self.icmp_offset + 2)
if self.icmp_type == 3 or self.icmp_type == 4 or self.icmp_type == 11 or self.icmp_type == 12 then
self.icmp_payload = true
self.icmp_r0 = self:u32(self.icmp_offset + 4)
self.icmp_payload_offset = self.icmp_offset + 8
if #self.buf < self.icmp_payload_offset + 24 then
return false
end
self.icmp_payload = Packet:new(self.buf:sub(self.icmp_payload_offset+1), self.packet_len - self.icmp_payload_offset, true)
end
return true
end
--- Get a short string representation of the ICMP header.
-- @return A string representation of the ICMP header.
function Packet:icmp_tostring()
return self:ip_tostring() .. " ICMP(" .. self.icmp_payload:tostring() .. ")"
end
----------------------------------------------------------------------------------------------------------------
--- Parse an ICMPv6 packet header.
-- @param force_continue Ignored.
-- @return Whether the parsing succeeded.
function Packet:icmpv6_parse(force_continue)
self.icmpv6_offset = self.ip6_data_offset
if #self.buf < self.icmpv6_offset + 8 then -- let's say 8 bytes minimum
return false
end
self.icmpv6 = true
self.icmpv6_type = self:u8(self.icmpv6_offset + 0)
self.icmpv6_code = self:u8(self.icmpv6_offset + 1)
if self.icmpv6_type == ND_NEIGHBOR_SOLICIT then
self.ns_target = self:raw(self.icmpv6_offset + 8, 16)
end
return true
end
----------------------------------------------------------------------------------------------------------------
-- Parse a TCP packet header.
-- @param force_continue Whether a short packet causes parsing to fail.
-- @return Whether the parsing succeeded.
function Packet:tcp_parse(force_continue)
self.tcp = true
self.tcp_offset = self.ip_data_offset or self.ip6_data_offset
if #self.buf < self.tcp_offset + 4 then
return false
end
self.tcp_sport = self:u16(self.tcp_offset + 0)
self.tcp_dport = self:u16(self.tcp_offset + 2)
if #self.buf < self.tcp_offset + 20 then
if force_continue then
return true
else
return false
end
end
self.tcp_seq = self:u32(self.tcp_offset + 4)
self.tcp_ack = self:u32(self.tcp_offset + 8)
self.tcp_hl = bit.rshift(bit.band(self:u8(self.tcp_offset+12), 0xF0), 4) -- header_length or data_offset
self.tcp_x2 = bit.band(self:u8(self.tcp_offset+12), 0x0F)
self.tcp_flags = self:u8(self.tcp_offset + 13)
self.tcp_th_fin = bit.band(self.tcp_flags, 0x01)~=0 -- true/false
self.tcp_th_syn = bit.band(self.tcp_flags, 0x02)~=0
self.tcp_th_rst = bit.band(self.tcp_flags, 0x04)~=0
self.tcp_th_push = bit.band(self.tcp_flags, 0x08)~=0
self.tcp_th_ack = bit.band(self.tcp_flags, 0x10)~=0
self.tcp_th_urg = bit.band(self.tcp_flags, 0x20)~=0
self.tcp_th_ece = bit.band(self.tcp_flags, 0x40)~=0
self.tcp_th_cwr = bit.band(self.tcp_flags, 0x80)~=0
self.tcp_win = self:u16(self.tcp_offset + 14)
self.tcp_sum = self:u16(self.tcp_offset + 16)
self.tcp_urp = self:u16(self.tcp_offset + 18)
self.tcp_opt_offset = self.tcp_offset + 20
self.tcp_options = self:parse_options(self.tcp_opt_offset, ((self.tcp_hl*4)-20))
self.tcp_data_offset = self.tcp_offset + self.tcp_hl*4
if self.ip_len then
self.tcp_data_length = self.ip_len - self.tcp_offset - self.tcp_hl*4
else
self.tcp_data_length = self.ip6_plen - self.tcp_hl*4
end
self:tcp_parse_options()
return true
end
--- Get a short string representation of the TCP packet.
-- @return A string representation of the TCP header.
function Packet:tcp_tostring()
return string.format(
"TCP %s:%i -> %s:%i",
self.ip_src, self.tcp_sport,
self.ip_dst, self.tcp_dport
)
end
--- Parse options for TCP header.
function Packet:tcp_parse_options()
local eoo = false
for _,opt in ipairs(self.tcp_options) do
if eoo then
self.tcp_opt_after_eol = true
end
if opt.type == 0 then -- end of options
eoo = true
elseif opt.type == 2 then -- MSS
self.tcp_opt_mss = u16(opt.data, 0)
self.tcp_opt_mtu = self.tcp_opt_mss + 40
elseif opt.type == 3 then -- widow scaling
self.tcp_opt_ws = u8(opt.data, 0)
elseif opt.type == 8 then -- timestamp
self.tcp_opt_t1 = u32(opt.data, 0)
self.tcp_opt_t2 = u32(opt.data, 4)
end
end
end
--- Set the TCP source port.
-- @param port Source port.
function Packet:tcp_set_sport(port)
self:set_u16(self.tcp_offset + 0, port)
self.tcp_sport = port
end
--- Set the TCP destination port.
-- @param port Destination port.
function Packet:tcp_set_dport(port)
self:set_u16(self.tcp_offset + 2, port)
self.tcp_dport = port
end
--- Set the TCP sequence field.
-- @param new_seq Sequence.
function Packet:tcp_set_seq(new_seq)
self:set_u32(self.tcp_offset + 4, new_seq)
self.tcp_seq = new_seq
end
--- Set the TCP flags field (like SYN, ACK, RST).
-- @param new_flags Flags, represented as an 8-bit number.
function Packet:tcp_set_flags(new_flags)
self:set_u8(self.tcp_offset + 13, new_flags)
self.tcp_flags = new_flags
end
--- Set the urgent pointer field.
-- @param urg_ptr Urgent pointer.
function Packet:tcp_set_urp(urg_ptr)
self:set_u16(self.tcp_offset + 18, urg_ptr)
self.tcp_urp = urg_ptr
end
--- Set the TCP checksum field.
-- @param checksum Checksum.
function Packet:tcp_set_checksum(checksum)
self:set_u16(self.tcp_offset + 16, checksum)
self.tcp_sum = checksum
end
--- Count and save the TCP checksum field.
function Packet:tcp_count_checksum()
self:tcp_set_checksum(0)
local proto = self.ip_p
local length = self.buf:len() - self.tcp_offset
local b = self.ip_bin_src ..
self.ip_bin_dst ..
"\0" ..
string.char(proto) ..
set_u16("..", 0, length) ..
self.buf:sub(self.tcp_offset+1)
self:tcp_set_checksum(in_cksum(b))
end
--- Map an MTU to a link type string. Stolen from p0f.
-- @return A string describing the link type.
function Packet:tcp_lookup_link()
local mtu_def = {
{["mtu"]=256, ["txt"]= "radio modem"},
{["mtu"]=386, ["txt"]= "ethernut"},
{["mtu"]=552, ["txt"]= "SLIP line / encap ppp"},
{["mtu"]=576, ["txt"]= "sometimes modem"},
{["mtu"]=1280, ["txt"]= "gif tunnel"},
{["mtu"]=1300, ["txt"]= "PIX, SMC, sometimes wireless"},
{["mtu"]=1362, ["txt"]= "sometimes DSL (1)"},
{["mtu"]=1372, ["txt"]= "cable modem"},
{["mtu"]=1400, ["txt"]= "(Google/AOL)"},
{["mtu"]=1415, ["txt"]= "sometimes wireless"},
{["mtu"]=1420, ["txt"]= "GPRS, T1, FreeS/WAN"},
{["mtu"]=1423, ["txt"]= "sometimes cable"},
{["mtu"]=1440, ["txt"]= "sometimes DSL (2)"},
{["mtu"]=1442, ["txt"]= "IPIP tunnel"},
{["mtu"]=1450, ["txt"]= "vtun"},
{["mtu"]=1452, ["txt"]= "sometimes DSL (3)"},
{["mtu"]=1454, ["txt"]= "sometimes DSL (4)"},
{["mtu"]=1456, ["txt"]= "ISDN ppp"},
{["mtu"]=1458, ["txt"]= "BT DSL (?)"},
{["mtu"]=1462, ["txt"]= "sometimes DSL (5)"},
{["mtu"]=1470, ["txt"]= "(Google 2)"},
{["mtu"]=1476, ["txt"]= "IPSec/GRE"},
{["mtu"]=1480, ["txt"]= "IPv6/IPIP"},
{["mtu"]=1492, ["txt"]= "pppoe (DSL)"},
{["mtu"]=1496, ["txt"]= "vLAN"},
{["mtu"]=1500, ["txt"]= "ethernet/modem"},
{["mtu"]=1656, ["txt"]= "Ericsson HIS"},
{["mtu"]=2024, ["txt"]= "wireless/IrDA"},
{["mtu"]=2048, ["txt"]= "Cyclom X.25 WAN"},
{["mtu"]=2250, ["txt"]= "AiroNet wireless"},
{["mtu"]=3924, ["txt"]= "loopback"},
{["mtu"]=4056, ["txt"]= "token ring (1)"},
{["mtu"]=4096, ["txt"]= "Sangoma X.25 WAN"},
{["mtu"]=4352, ["txt"]= "FDDI"},
{["mtu"]=4500, ["txt"]= "token ring (2)"},
{["mtu"]=9180, ["txt"]= "FORE ATM"},
{["mtu"]=16384, ["txt"]= "sometimes loopback (1)"},
{["mtu"]=16436, ["txt"]= "sometimes loopback (2)"},
{["mtu"]=18000, ["txt"]= "token ring x4"},
}
if not self.tcp_opt_mss or self.tcp_opt_mss==0 then
return "unspecified"
end
for _,x in ipairs(mtu_def) do
local mtu = x["mtu"]
local txt = x["txt"]
if self.tcp_opt_mtu == mtu then
return txt
end
if self.tcp_opt_mtu < mtu then
return string.format("unknown-%i", self.tcp_opt_mtu)
end
end
return string.format("unknown-%i", self.tcp_opt_mtu)
end
----------------------------------------------------------------------------------------------------------------
-- Parse a UDP packet header.
-- @param force_continue Whether a short packet causes parsing to fail.
-- @return Whether the parsing succeeded.
function Packet:udp_parse(force_continue)
self.udp = true
self.udp_offset = self.ip_data_offset or self.ip6_data_offset
if #self.buf < self.udp_offset + 4 then
return false
end
self.udp_sport = self:u16(self.udp_offset + 0)
self.udp_dport = self:u16(self.udp_offset + 2)
if #self.buf < self.udp_offset + 8 then
if force_continue then
return true
else
return false
end
end
self.udp_len = self:u16(self.udp_offset + 4)
self.udp_sum = self:u16(self.udp_offset + 6)
return true
end
--- Get a short string representation of the UDP packet.
-- @return A string representation of the UDP header.
function Packet:udp_tostring()
return string.format(
"UDP %s:%i -> %s:%i",
self.ip_src, self.udp_sport,
self.ip_dst, self.udp_dport
)
end
---
-- Set the UDP source port.
-- @param port Source port.
function Packet:udp_set_sport(port)
self:set_u16(self.udp_offset + 0, port)
self.udp_sport = port
end
---
-- Set the UDP destination port.
-- @param port Destination port.
function Packet:udp_set_dport(port)
self:set_u16(self.udp_offset + 2, port)
self.udp_dport = port
end
---
-- Set the UDP payload length.
-- @param len UDP payload length.
function Packet:udp_set_length(len)
self:set_u16(self.udp_offset + 4, len)
self.udp_len = len
end
---
-- Set the UDP checksum field.
-- @param checksum Checksum.
function Packet:udp_set_checksum(checksum)
self:set_u16(self.udp_offset + 6, checksum)
self.udp_sum = checksum
end
---
-- Count and save the UDP checksum field.
function Packet:udp_count_checksum()
self:udp_set_checksum(0)
local proto = self.ip_p
local length = self.buf:len() - self.udp_offset
local b = self.ip_bin_src ..
self.ip_bin_dst ..
"\0" ..
string.char(proto) ..
set_u16("..", 0, length) ..
self.buf:sub(self.udp_offset+1)
self:udp_set_checksum(in_cksum(b))
end
return _ENV;
| mit |
werpat/MoonGen | rfc2544/utils/utils.lua | 9 | 5501 | local actors = {}
local status, snmp = pcall(require, 'utils.snmp')
if status then
table.insert(actors, snmp)
else
print "unable to load snmp module"
end
local status, sshMikrotik = pcall(require, 'utils.ssh-mikrotik')
if status then
table.insert(actors, sshMikrotik)
else
print "unable to load mikrotik ssh module"
end
local status, sshFreeBSD = pcall(require, 'utils.ssh-freebsd')
if status then
table.insert(actors, sshFreeBSD)
else
print "unable to load freeBSD ssh module"
end
local status, ssh = pcall(require, 'utils.ssh')
if status then
table.insert(actors, ssh)
else
print "unable to load linux ssh module"
end
local manual = require "utils.manual"
table.insert(actors, manual)
local mod = {}
mod.__index = mod
function mod.addInterfaceIP(interface, ip, pfx)
local status = -1
for k, actor in ipairs(actors) do
status = actor.addInterfaceIP(interface, ip, pfx)
if status == 0 then
break
end
end
return status
end
function mod.delInterfaceIP(interface, ip, pfx)
local status = -1
for _, actor in ipairs(actors) do
status = actor.delInterfaceIP(interface, ip, pfx)
if status == 0 then
break
end
end
return status
end
function mod.clearIPFilters()
local status = -1
for _, actor in ipairs(actors) do
status = actor.clearIPFilters()
if status == 0 then
break
end
end
return status
end
function mod.addIPFilter(src, sPfx, dst, dPfx)
local status = -1
for _, actor in ipairs(actors) do
status = actor.addIPFilter(src, sPfx, dst, dPfx)
if status == 0 then
break
end
end
return status
end
function mod.delIPFilter(src, sPfx, dst, dPfx)
local status = -1
for _, actor in ipairs(actors) do
status = actor.delIPFilter(src, sPfx, dst, dPfx)
if status == 0 then
break
end
end
return status
end
function mod.clearIPRoutes()
local status = -1
for _, actor in ipairs(actors) do
actor.clearIPRoutes()
if status == 0 then
break
end
end
return status
end
function mod.addIPRoute(dst, pfx, gateway, interface)
local status = -1
for _, actor in ipairs(actors) do
status = actor.addIPRoute(dst, pfx, gateway, interface)
if status == 0 then
break
end
end
return status
end
function mod.delIPRoute(dst, pfx, gateway, interface)
local status = -1
for _, actor in ipairs(actors) do
status = actor.delIPRoute(dst, pfx, gateway, interface)
if status == 0 then
break
end
end
return status
end
function mod.addIPRouteRange(firstIP, lastIP)
local status = -1
for _, actor in ipairs(actors) do
status = actor.addIPRouteRange(firstIP, lastIP)
if status == 0 then
break
end
end
return status
end
function mod.getIPRouteCount()
local status = -1
for _, actor in ipairs(actors) do
status = actor.getIPRouteCount()
if status == 0 then
break
end
end
return status
end
function mod.getDeviceName()
return manual.getDeviceName()
end
function mod.getDeviceOS()
return manual.getDeviceOS()
end
local binarySearch = {}
binarySearch.__index = binarySearch
function binarySearch:create(lower, upper)
local self = setmetatable({}, binarySearch)
self.lowerLimit = lower
self.upperLimit = upper
return self
end
setmetatable(binarySearch, { __call = binarySearch.create })
function binarySearch:init(lower, upper)
self.lowerLimit = lower
self.upperLimit = upper
end
function binarySearch:next(curr, top, threshold)
if top then
if curr == self.upperLimit then
return curr, true
else
self.lowerLimit = curr
end
else
if curr == lowerLimit then
return curr, true
else
self.upperLimit = curr
end
end
local nextVal = math.ceil((self.lowerLimit + self.upperLimit) / 2)
if math.abs(nextVal - curr) < threshold then
return curr, true
end
return nextVal, false
end
mod.binarySearch = binarySearch
mod.modifier = {
none = 0,
randEth = 1,
randIp = 2
}
function mod.getPktModifierFunction(modifier, baseIp, wrapIp, baseEth, wrapEth)
local foo = function() end
if modifier == mod.modifier.randEth then
local ethCtr = 0
foo = function(pkt)
pkt.ip.dst:setNumber(baseEth + ethCtr)
ethCtr = incAndWrap(ethCtr, wrapEth)
end
elseif modifier == mod.modifier.randIp then
local ipCtr = 0
foo = function(pkt)
pkt.ip.dst:set(baseIP + ipCtr)
ipCtr = incAndWrap(ipCtr, wrapIp)
end
end
return foo
end
--[[
bit faster then macAddr:setNumber or macAddr:set
and faster then macAddr:setString
but still not fast enough for one single slave and 10GbE @64b pkts
set destination MAC address
ffi.copy(macAddr, pkt.eth.dst.uint8, 6)
macAddr[0] = (macAddr[0] + 1) % macWraparound
--]]
function mod.parseArguments(args)
local results = {}
for i=1, #args, 2 do
local key = args[i]:gsub("-", "", 2) -- cut off one or two leading minus
results[key] = args[i+1]
end
return results
end
return mod
| mit |
fwmechanic/k_edit | bin.lua | 1 | 2586 | -- if you change or add to this module, _please_ update test\k_lib.lua accordingly!
module( "bin", package.seeall )
require "util"
-- very simple un/packer: supports only fixed length byte strings and 1-/2-/4-byte binary numbers
local function unpack_one( tt, byteSrc, ix, endian )
local at, bytes = tt:match( "^(%a?)(%d+)$" )
local errstr = string.format( "unknown unpack[%d] template specifier '%s'", ix, tt )
util.errassert( bytes, errstr, 3 )
bytes = 0+bytes
local raw = byteSrc( bytes, string.format( "unpack[%d] '%s'", ix, tt ) )
if at =="" then return _bin.unpack_num( raw, endian ) end
if at == "s" then return raw end
error( errstr, 3 )
end
-- ********** NB!!! There is a 'unpack' function in the Lua global scope! See PiL2e pg 39
local function unpack( tmplt, endian, byteString )
local bsbs = util.byteSource( byteString )
local aTmplts = util.matches( tmplt )
local rv = {}
for ix,ta in ipairs( aTmplts ) do
rv[ #rv + 1 ] = unpack_one( ta, bsbs, ix, endian )
end
return rv
end
function unpackLE( tmplt, byteString ) return unpack( tmplt, false, byteString ) end
function unpackBE( tmplt, byteString ) return unpack( tmplt, true , byteString ) end
------------
local function pack_one( tt, data, ix, endian )
local at, bytes = tt:match( "^(%a?)(%d+)$" )
-- print( "pattern '"..tt.."'".. at )
local errstr = string.format( "unknown pack[%d] template specifier '%s'", ix, tt )
util.errassert( bytes, errstr, 3 )
bytes = 0+bytes
local badparam = string.format( "bad pack[%d] parameter (%s) for template specifier '%s'", ix, type(data), tt )
if at == "" then
util.errassert( type(data) == "number", badparam, 3 )
return _bin.pack_num( data, bytes, endian )
end
if at == "s" then
util.errassert( type(data) == "string", badparam, 3 )
local rv = data:sub( 1, bytes )
if #rv < bytes then rv = rv .. string.rep( string.char(0), bytes - #rv ) end
return rv
end
error( errstr, 3 )
end
local function pack( tmplt, endian, ... )
local aData = { ... }
local aTmplts = util.matches( tmplt )
local rv = {}
for ix,ta in ipairs( aTmplts ) do
local data = table.remove( aData, 1 )
assert( data, "" )
rv[ #rv + 1 ] = pack_one( ta, data, ix, endian )
end
return table.concat( rv )
end
function packLE( tmplt, ... ) return pack( tmplt, false, ... ) end
function packBE( tmplt, ... ) return pack( tmplt, true , ... ) end
| gpl-3.0 |
ferstar/openwrt-dreambox | feeds/luci/luci/luci/protocols/pptp/luasrc/model/cbi/admin_network/proto_pptp.lua | 3 | 1659 | --[[
LuCI - Lua Configuration Interface
Copyright 2011 Jo-Philipp Wich <xm@subsignal.org>
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
]]--
local map, section, net = ...
local server, username, password
local buffering, defaultroute, metric, peerdns, dns
server = section:taboption("general", Value, "server", translate("VPN Server"))
server.datatype = "host"
username = section:taboption("general", Value, "username", translate("PAP/CHAP username"))
password = section:taboption("general", Value, "password", translate("PAP/CHAP password"))
password.password = true
buffering = section:taboption("advanced", Flag, "buffering", translate("Enable buffering"))
buffering.default = buffering.enabled
defaultroute = section:taboption("advanced", Flag, "defaultroute",
translate("Use default gateway"),
translate("If unchecked, no default route is configured"))
defaultroute.default = defaultroute.enabled
metric = section:taboption("advanced", Value, "metric",
translate("Use gateway metric"))
metric.placeholder = "0"
metric.datatype = "uinteger"
metric:depends("defaultroute", defaultroute.enabled)
peerdns = section:taboption("advanced", Flag, "peerdns",
translate("Use DNS servers advertised by peer"),
translate("If unchecked, the advertised DNS server addresses are ignored"))
peerdns.default = peerdns.enabled
dns = section:taboption("advanced", DynamicList, "dns",
translate("Use custom DNS servers"))
dns:depends("peerdns", "")
dns.datatype = "ipaddr"
| gpl-2.0 |
liminghuang/MavLink_FrSkySPort | Lua_Telemetry/DisplayApmPosition/SCRIPTS/MIXES/celinf.lua | 4 | 3087 | --
-- CellInfo lua
--
-- Copyright (C) 2014 Michael Wolkstein
--
-- https://github.com/Clooney82/MavLink_FrSkySPort
--
-- 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>.
--
local inputs = { {"Crit,V/100", VALUE,300,350,340}, {"Use Horn", VALUE, 0, 3, 0}, {"Warn,V/100", VALUE, 310, 380, 350}, {"Rep, Sec", VALUE, 3, 30, 4},{"Drop, mV", VALUE, 1, 500, 100} }
local lastimeplaysound=0
local repeattime=400 -- 4 sekunden
local oldcellvoltage=4.2
local drop = 0
local hornfile=""
local cellmin=0
local firstitem=0
local miditem=0
local lastitem=0
local mult=0
local newtime=0
local function init_func()
lastimeplaysound=getTime()
end
-- Math Helper
local function round(num, idp)
mult = 10^(idp or 0)
return math.floor(num * mult + 0.5) / mult
end
local function run_func(voltcritcal, horn, voltwarnlevel, repeattimeseconds, celldropmvolts)
repeattime = repeattimeseconds*100
drop = celldropmvolts/10
hornfile=""
if horn>0 then
hornfile="SOUNDS/en/TELEM/ALARM"..horn.."K.wav"
end
newtime=getTime()
if newtime-lastimeplaysound>=repeattime then
cellmin=getValue("Cmin") + 0.0001 --- 214 = cell-min
lastimeplaysound = newtime
firstitem = math.floor(cellmin)
miditem = math.floor((cellmin-firstitem) * 10)
lastitem = round((((cellmin-firstitem) * 10)-math.floor(((cellmin-firstitem) * 10))) *10)
if cellmin<=2.0 then --silent
elseif cellmin<=voltcritcal/100 then --critical
if horn>0 then
playFile(hornfile)
playFile("/SOUNDS/en/TELEM/CRICM.wav")
else
playFile("/SOUNDS/en/TELEM/CRICM.wav")
end
playNumber(firstitem, 0, 0)
playFile("/SOUNDS/en/TELEM/POINT.wav")
playNumber(miditem, 0, 0)
if lastitem ~= 0 then
playNumber(lastitem, 0, 0)
end
elseif cellmin<=voltwarnlevel/100 then --warnlevel
playFile("/SOUNDS/en/TELEM/WARNCM.wav")
playNumber(firstitem, 0, 0)
playFile("/SOUNDS/en/TELEM/POINT.wav")
playNumber(miditem, 0, 0)
if lastitem ~= 0 then
playNumber(lastitem, 0, 0)
end
elseif cellmin<=4.2 then --info level
if oldcellvoltage < cellmin then -- temp cell drop during aggressive flight
oldcellvoltage = cellmin
end
if oldcellvoltage*100 - cellmin*100 >= drop then
playFile("/SOUNDS/en/TELEM/CELLMIN.wav")
playNumber(firstitem, 0, 0)
playFile("/SOUNDS/en/TELEM/POINT.wav")
playNumber(miditem, 0, 0)
if lastitem ~= 0 then
playNumber(lastitem, 0, 0)
end
oldcellvoltage = cellmin
end
end
end
end
return {run=run_func, init=init_func, input=inputs}
| gpl-3.0 |
ImagicTheCat/vRP | vrp/client/veh_blacklist.lua | 1 | 1482 | -- https://github.com/ImagicTheCat/vRP
-- MIT license (see LICENSE or vrp/vRPShared.lua)
if not vRP.modules.veh_blacklist then return end
local VehBlacklist = class("VehBlacklist", vRP.Extension)
-- METHODS
function VehBlacklist:__construct()
vRP.Extension.__construct(self)
self.veh_models = {} -- map of model hash
self.interval = 10000
-- task: remove vehicles
Citizen.CreateThread(function()
while true do
Citizen.Wait(self.interval)
local vehicles = {}
local it, veh = FindFirstVehicle()
if veh then table.insert(vehicles, veh) end
while true do
local ok, veh = FindNextVehicle(it)
if ok and veh then
table.insert(vehicles, veh)
else
EndFindVehicle(it)
break
end
end
for _, veh in ipairs(vehicles) do
if self.veh_models[GetEntityModel(veh)] then
local cid, model = vRP.EXT.Garage:getVehicleInfo(veh)
if not cid then
SetEntityAsMissionEntity(veh, true, true)
DeleteVehicle(veh)
end
end
end
end
end)
end
-- TUNNEL
VehBlacklist.tunnel = {}
function VehBlacklist.tunnel:setConfig(cfg)
for _, model in pairs(cfg.veh_models) do
local hash
if type(model) == "string" then
hash = GetHashKey(model)
else
hash = model
end
self.veh_models[hash] = true
end
self.interval = cfg.remove_interval
end
vRP:registerExtension(VehBlacklist)
| mit |
focusworld/binbong | libs/mimetype.lua | 3662 | 2922 | -- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types
do
local mimetype = {}
-- TODO: Add more?
local types = {
["text/html"] = "html",
["text/css"] = "css",
["text/xml"] = "xml",
["image/gif"] = "gif",
["image/jpeg"] = "jpg",
["application/x-javascript"] = "js",
["application/atom+xml"] = "atom",
["application/rss+xml"] = "rss",
["text/mathml"] = "mml",
["text/plain"] = "txt",
["text/vnd.sun.j2me.app-descriptor"] = "jad",
["text/vnd.wap.wml"] = "wml",
["text/x-component"] = "htc",
["image/png"] = "png",
["image/tiff"] = "tiff",
["image/vnd.wap.wbmp"] = "wbmp",
["image/x-icon"] = "ico",
["image/x-jng"] = "jng",
["image/x-ms-bmp"] = "bmp",
["image/svg+xml"] = "svg",
["image/webp"] = "webp",
["application/java-archive"] = "jar",
["application/mac-binhex40"] = "hqx",
["application/msword"] = "doc",
["application/pdf"] = "pdf",
["application/postscript"] = "ps",
["application/rtf"] = "rtf",
["application/vnd.ms-excel"] = "xls",
["application/vnd.ms-powerpoint"] = "ppt",
["application/vnd.wap.wmlc"] = "wmlc",
["application/vnd.google-earth.kml+xml"] = "kml",
["application/vnd.google-earth.kmz"] = "kmz",
["application/x-7z-compressed"] = "7z",
["application/x-cocoa"] = "cco",
["application/x-java-archive-diff"] = "jardiff",
["application/x-java-jnlp-file"] = "jnlp",
["application/x-makeself"] = "run",
["application/x-perl"] = "pl",
["application/x-pilot"] = "prc",
["application/x-rar-compressed"] = "rar",
["application/x-redhat-package-manager"] = "rpm",
["application/x-sea"] = "sea",
["application/x-shockwave-flash"] = "swf",
["application/x-stuffit"] = "sit",
["application/x-tcl"] = "tcl",
["application/x-x509-ca-cert"] = "crt",
["application/x-xpinstall"] = "xpi",
["application/xhtml+xml"] = "xhtml",
["application/zip"] = "zip",
["application/octet-stream"] = "bin",
["audio/midi"] = "mid",
["audio/mpeg"] = "mp3",
["audio/ogg"] = "ogg",
["audio/x-m4a"] = "m4a",
["audio/x-realaudio"] = "ra",
["video/3gpp"] = "3gpp",
["video/mp4"] = "mp4",
["video/mpeg"] = "mpeg",
["video/quicktime"] = "mov",
["video/webm"] = "webm",
["video/x-flv"] = "flv",
["video/x-m4v"] = "m4v",
["video/x-mng"] = "mng",
["video/x-ms-asf"] = "asf",
["video/x-ms-wmv"] = "wmv",
["video/x-msvideo"] = "avi"
}
-- Returns the common file extension from a content-type
function mimetype.get_mime_extension(content_type)
return types[content_type]
end
-- Returns the mimetype and subtype
function mimetype.get_content_type(extension)
for k,v in pairs(types) do
if v == extension then
return k
end
end
end
-- Returns the mimetype without the subtype
function mimetype.get_content_type_no_sub(extension)
for k,v in pairs(types) do
if v == extension then
-- Before /
return k:match('([%w-]+)/')
end
end
end
return mimetype
end | gpl-2.0 |
rasolllll/tele_gold | libs/mimetype.lua | 3662 | 2922 | -- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types
do
local mimetype = {}
-- TODO: Add more?
local types = {
["text/html"] = "html",
["text/css"] = "css",
["text/xml"] = "xml",
["image/gif"] = "gif",
["image/jpeg"] = "jpg",
["application/x-javascript"] = "js",
["application/atom+xml"] = "atom",
["application/rss+xml"] = "rss",
["text/mathml"] = "mml",
["text/plain"] = "txt",
["text/vnd.sun.j2me.app-descriptor"] = "jad",
["text/vnd.wap.wml"] = "wml",
["text/x-component"] = "htc",
["image/png"] = "png",
["image/tiff"] = "tiff",
["image/vnd.wap.wbmp"] = "wbmp",
["image/x-icon"] = "ico",
["image/x-jng"] = "jng",
["image/x-ms-bmp"] = "bmp",
["image/svg+xml"] = "svg",
["image/webp"] = "webp",
["application/java-archive"] = "jar",
["application/mac-binhex40"] = "hqx",
["application/msword"] = "doc",
["application/pdf"] = "pdf",
["application/postscript"] = "ps",
["application/rtf"] = "rtf",
["application/vnd.ms-excel"] = "xls",
["application/vnd.ms-powerpoint"] = "ppt",
["application/vnd.wap.wmlc"] = "wmlc",
["application/vnd.google-earth.kml+xml"] = "kml",
["application/vnd.google-earth.kmz"] = "kmz",
["application/x-7z-compressed"] = "7z",
["application/x-cocoa"] = "cco",
["application/x-java-archive-diff"] = "jardiff",
["application/x-java-jnlp-file"] = "jnlp",
["application/x-makeself"] = "run",
["application/x-perl"] = "pl",
["application/x-pilot"] = "prc",
["application/x-rar-compressed"] = "rar",
["application/x-redhat-package-manager"] = "rpm",
["application/x-sea"] = "sea",
["application/x-shockwave-flash"] = "swf",
["application/x-stuffit"] = "sit",
["application/x-tcl"] = "tcl",
["application/x-x509-ca-cert"] = "crt",
["application/x-xpinstall"] = "xpi",
["application/xhtml+xml"] = "xhtml",
["application/zip"] = "zip",
["application/octet-stream"] = "bin",
["audio/midi"] = "mid",
["audio/mpeg"] = "mp3",
["audio/ogg"] = "ogg",
["audio/x-m4a"] = "m4a",
["audio/x-realaudio"] = "ra",
["video/3gpp"] = "3gpp",
["video/mp4"] = "mp4",
["video/mpeg"] = "mpeg",
["video/quicktime"] = "mov",
["video/webm"] = "webm",
["video/x-flv"] = "flv",
["video/x-m4v"] = "m4v",
["video/x-mng"] = "mng",
["video/x-ms-asf"] = "asf",
["video/x-ms-wmv"] = "wmv",
["video/x-msvideo"] = "avi"
}
-- Returns the common file extension from a content-type
function mimetype.get_mime_extension(content_type)
return types[content_type]
end
-- Returns the mimetype and subtype
function mimetype.get_content_type(extension)
for k,v in pairs(types) do
if v == extension then
return k
end
end
end
-- Returns the mimetype without the subtype
function mimetype.get_content_type_no_sub(extension)
for k,v in pairs(types) do
if v == extension then
-- Before /
return k:match('([%w-]+)/')
end
end
end
return mimetype
end | gpl-2.0 |
Godfather021/best | libs/mimetype.lua | 3662 | 2922 | -- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types
do
local mimetype = {}
-- TODO: Add more?
local types = {
["text/html"] = "html",
["text/css"] = "css",
["text/xml"] = "xml",
["image/gif"] = "gif",
["image/jpeg"] = "jpg",
["application/x-javascript"] = "js",
["application/atom+xml"] = "atom",
["application/rss+xml"] = "rss",
["text/mathml"] = "mml",
["text/plain"] = "txt",
["text/vnd.sun.j2me.app-descriptor"] = "jad",
["text/vnd.wap.wml"] = "wml",
["text/x-component"] = "htc",
["image/png"] = "png",
["image/tiff"] = "tiff",
["image/vnd.wap.wbmp"] = "wbmp",
["image/x-icon"] = "ico",
["image/x-jng"] = "jng",
["image/x-ms-bmp"] = "bmp",
["image/svg+xml"] = "svg",
["image/webp"] = "webp",
["application/java-archive"] = "jar",
["application/mac-binhex40"] = "hqx",
["application/msword"] = "doc",
["application/pdf"] = "pdf",
["application/postscript"] = "ps",
["application/rtf"] = "rtf",
["application/vnd.ms-excel"] = "xls",
["application/vnd.ms-powerpoint"] = "ppt",
["application/vnd.wap.wmlc"] = "wmlc",
["application/vnd.google-earth.kml+xml"] = "kml",
["application/vnd.google-earth.kmz"] = "kmz",
["application/x-7z-compressed"] = "7z",
["application/x-cocoa"] = "cco",
["application/x-java-archive-diff"] = "jardiff",
["application/x-java-jnlp-file"] = "jnlp",
["application/x-makeself"] = "run",
["application/x-perl"] = "pl",
["application/x-pilot"] = "prc",
["application/x-rar-compressed"] = "rar",
["application/x-redhat-package-manager"] = "rpm",
["application/x-sea"] = "sea",
["application/x-shockwave-flash"] = "swf",
["application/x-stuffit"] = "sit",
["application/x-tcl"] = "tcl",
["application/x-x509-ca-cert"] = "crt",
["application/x-xpinstall"] = "xpi",
["application/xhtml+xml"] = "xhtml",
["application/zip"] = "zip",
["application/octet-stream"] = "bin",
["audio/midi"] = "mid",
["audio/mpeg"] = "mp3",
["audio/ogg"] = "ogg",
["audio/x-m4a"] = "m4a",
["audio/x-realaudio"] = "ra",
["video/3gpp"] = "3gpp",
["video/mp4"] = "mp4",
["video/mpeg"] = "mpeg",
["video/quicktime"] = "mov",
["video/webm"] = "webm",
["video/x-flv"] = "flv",
["video/x-m4v"] = "m4v",
["video/x-mng"] = "mng",
["video/x-ms-asf"] = "asf",
["video/x-ms-wmv"] = "wmv",
["video/x-msvideo"] = "avi"
}
-- Returns the common file extension from a content-type
function mimetype.get_mime_extension(content_type)
return types[content_type]
end
-- Returns the mimetype and subtype
function mimetype.get_content_type(extension)
for k,v in pairs(types) do
if v == extension then
return k
end
end
end
-- Returns the mimetype without the subtype
function mimetype.get_content_type_no_sub(extension)
for k,v in pairs(types) do
if v == extension then
-- Before /
return k:match('([%w-]+)/')
end
end
end
return mimetype
end | gpl-2.0 |
blackteamgourd/Black__Team | libs/mimetype.lua | 3662 | 2922 | -- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types
do
local mimetype = {}
-- TODO: Add more?
local types = {
["text/html"] = "html",
["text/css"] = "css",
["text/xml"] = "xml",
["image/gif"] = "gif",
["image/jpeg"] = "jpg",
["application/x-javascript"] = "js",
["application/atom+xml"] = "atom",
["application/rss+xml"] = "rss",
["text/mathml"] = "mml",
["text/plain"] = "txt",
["text/vnd.sun.j2me.app-descriptor"] = "jad",
["text/vnd.wap.wml"] = "wml",
["text/x-component"] = "htc",
["image/png"] = "png",
["image/tiff"] = "tiff",
["image/vnd.wap.wbmp"] = "wbmp",
["image/x-icon"] = "ico",
["image/x-jng"] = "jng",
["image/x-ms-bmp"] = "bmp",
["image/svg+xml"] = "svg",
["image/webp"] = "webp",
["application/java-archive"] = "jar",
["application/mac-binhex40"] = "hqx",
["application/msword"] = "doc",
["application/pdf"] = "pdf",
["application/postscript"] = "ps",
["application/rtf"] = "rtf",
["application/vnd.ms-excel"] = "xls",
["application/vnd.ms-powerpoint"] = "ppt",
["application/vnd.wap.wmlc"] = "wmlc",
["application/vnd.google-earth.kml+xml"] = "kml",
["application/vnd.google-earth.kmz"] = "kmz",
["application/x-7z-compressed"] = "7z",
["application/x-cocoa"] = "cco",
["application/x-java-archive-diff"] = "jardiff",
["application/x-java-jnlp-file"] = "jnlp",
["application/x-makeself"] = "run",
["application/x-perl"] = "pl",
["application/x-pilot"] = "prc",
["application/x-rar-compressed"] = "rar",
["application/x-redhat-package-manager"] = "rpm",
["application/x-sea"] = "sea",
["application/x-shockwave-flash"] = "swf",
["application/x-stuffit"] = "sit",
["application/x-tcl"] = "tcl",
["application/x-x509-ca-cert"] = "crt",
["application/x-xpinstall"] = "xpi",
["application/xhtml+xml"] = "xhtml",
["application/zip"] = "zip",
["application/octet-stream"] = "bin",
["audio/midi"] = "mid",
["audio/mpeg"] = "mp3",
["audio/ogg"] = "ogg",
["audio/x-m4a"] = "m4a",
["audio/x-realaudio"] = "ra",
["video/3gpp"] = "3gpp",
["video/mp4"] = "mp4",
["video/mpeg"] = "mpeg",
["video/quicktime"] = "mov",
["video/webm"] = "webm",
["video/x-flv"] = "flv",
["video/x-m4v"] = "m4v",
["video/x-mng"] = "mng",
["video/x-ms-asf"] = "asf",
["video/x-ms-wmv"] = "wmv",
["video/x-msvideo"] = "avi"
}
-- Returns the common file extension from a content-type
function mimetype.get_mime_extension(content_type)
return types[content_type]
end
-- Returns the mimetype and subtype
function mimetype.get_content_type(extension)
for k,v in pairs(types) do
if v == extension then
return k
end
end
end
-- Returns the mimetype without the subtype
function mimetype.get_content_type_no_sub(extension)
for k,v in pairs(types) do
if v == extension then
-- Before /
return k:match('([%w-]+)/')
end
end
end
return mimetype
end | gpl-2.0 |
MRAHS/SBSS-v2 | libs/mimetype.lua | 3662 | 2922 | -- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types
do
local mimetype = {}
-- TODO: Add more?
local types = {
["text/html"] = "html",
["text/css"] = "css",
["text/xml"] = "xml",
["image/gif"] = "gif",
["image/jpeg"] = "jpg",
["application/x-javascript"] = "js",
["application/atom+xml"] = "atom",
["application/rss+xml"] = "rss",
["text/mathml"] = "mml",
["text/plain"] = "txt",
["text/vnd.sun.j2me.app-descriptor"] = "jad",
["text/vnd.wap.wml"] = "wml",
["text/x-component"] = "htc",
["image/png"] = "png",
["image/tiff"] = "tiff",
["image/vnd.wap.wbmp"] = "wbmp",
["image/x-icon"] = "ico",
["image/x-jng"] = "jng",
["image/x-ms-bmp"] = "bmp",
["image/svg+xml"] = "svg",
["image/webp"] = "webp",
["application/java-archive"] = "jar",
["application/mac-binhex40"] = "hqx",
["application/msword"] = "doc",
["application/pdf"] = "pdf",
["application/postscript"] = "ps",
["application/rtf"] = "rtf",
["application/vnd.ms-excel"] = "xls",
["application/vnd.ms-powerpoint"] = "ppt",
["application/vnd.wap.wmlc"] = "wmlc",
["application/vnd.google-earth.kml+xml"] = "kml",
["application/vnd.google-earth.kmz"] = "kmz",
["application/x-7z-compressed"] = "7z",
["application/x-cocoa"] = "cco",
["application/x-java-archive-diff"] = "jardiff",
["application/x-java-jnlp-file"] = "jnlp",
["application/x-makeself"] = "run",
["application/x-perl"] = "pl",
["application/x-pilot"] = "prc",
["application/x-rar-compressed"] = "rar",
["application/x-redhat-package-manager"] = "rpm",
["application/x-sea"] = "sea",
["application/x-shockwave-flash"] = "swf",
["application/x-stuffit"] = "sit",
["application/x-tcl"] = "tcl",
["application/x-x509-ca-cert"] = "crt",
["application/x-xpinstall"] = "xpi",
["application/xhtml+xml"] = "xhtml",
["application/zip"] = "zip",
["application/octet-stream"] = "bin",
["audio/midi"] = "mid",
["audio/mpeg"] = "mp3",
["audio/ogg"] = "ogg",
["audio/x-m4a"] = "m4a",
["audio/x-realaudio"] = "ra",
["video/3gpp"] = "3gpp",
["video/mp4"] = "mp4",
["video/mpeg"] = "mpeg",
["video/quicktime"] = "mov",
["video/webm"] = "webm",
["video/x-flv"] = "flv",
["video/x-m4v"] = "m4v",
["video/x-mng"] = "mng",
["video/x-ms-asf"] = "asf",
["video/x-ms-wmv"] = "wmv",
["video/x-msvideo"] = "avi"
}
-- Returns the common file extension from a content-type
function mimetype.get_mime_extension(content_type)
return types[content_type]
end
-- Returns the mimetype and subtype
function mimetype.get_content_type(extension)
for k,v in pairs(types) do
if v == extension then
return k
end
end
end
-- Returns the mimetype without the subtype
function mimetype.get_content_type_no_sub(extension)
for k,v in pairs(types) do
if v == extension then
-- Before /
return k:match('([%w-]+)/')
end
end
end
return mimetype
end | gpl-2.0 |
m-creations/openwrt | feeds/luci/modules/luci-base/luasrc/ccache.lua | 81 | 1651 | -- 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 io = require "io"
local fs = require "nixio.fs"
local util = require "luci.util"
local nixio = require "nixio"
local debug = require "debug"
local string = require "string"
local package = require "package"
local type, loadfile = type, loadfile
module "luci.ccache"
function cache_ondemand(...)
if debug.getinfo(1, 'S').source ~= "=?" then
cache_enable(...)
end
end
function cache_enable(cachepath, mode)
cachepath = cachepath or "/tmp/luci-modulecache"
mode = mode or "r--r--r--"
local loader = package.loaders[2]
local uid = nixio.getuid()
if not fs.stat(cachepath) then
fs.mkdir(cachepath)
end
local function _encode_filename(name)
local encoded = ""
for i=1, #name do
encoded = encoded .. ("%2X" % string.byte(name, i))
end
return encoded
end
local function _load_sane(file)
local stat = fs.stat(file)
if stat and stat.uid == uid and stat.modestr == mode then
return loadfile(file)
end
end
local function _write_sane(file, func)
if nixio.getuid() == uid then
local fp = io.open(file, "w")
if fp then
fp:write(util.get_bytecode(func))
fp:close()
fs.chmod(file, mode)
end
end
end
package.loaders[2] = function(mod)
local encoded = cachepath .. "/" .. _encode_filename(mod)
local modcons = _load_sane(encoded)
if modcons then
return modcons
end
-- No cachefile
modcons = loader(mod)
if type(modcons) == "function" then
_write_sane(encoded, modcons)
end
return modcons
end
end
| gpl-2.0 |
Sevenanths/boson-t-nouveau | NewBosonT/NewBosonT/bin/Debug/boson/data - Copy/gameover.lua | 2 | 16541 | local game_state = ...
local swidth = lt.right - lt.left
if not game_state then
game_state = { score = 0.97, stage_id = 1 }
end
local particle_trace = gen_particle_trace(game_state)
local stage_id = game_state.stage_id
local score = game_state.score
local experiment_no = lt.state.games_played
local prev_best = record_new_score(score, stage_id)
lt.SaveState()
local label = "AGAIN"
if game_state.stages_unlocked then
label = "SELECT EXPERIMENT"
end
local
function retry()
if game_state.stages_unlocked then
samples.uibleep:Play(1, lt.state.sfx_volume)
import("stage_select")
else
play(stage_id, game_state.music)
end
end
local restart_button
if lt.form_factor == "desktop" then
restart_button = lt.Text("ENTER: " .. label, font, "right", "bottom"):Tint(unpack(config.ui_bg))
:Scale(0.8):Translate(lt.right - 0.1, lt.bottom + 0.1)
else
local img = images.retry
if game_state.stages_unlocked then
img = images.back_arrow:Scale(-1, 1)
end
local retry_img = img:Translate(lt.right - swidth / 4, button_bar_mid_y)
local divider = lt.Rect(lt.right - swidth / 2, lt.bottom, lt.right - swidth / 2 - 0.02, lt.bottom + bottom_bar_height)
:Tint(unpack(config.ui_active_color))
restart_button = lt.Layer(retry_img, divider)
:PointerDown(retry,
lt.right - swidth / 2, lt.bottom, lt.right, lt.bottom + bottom_bar_height)
:PointerDown(retry,
lt.left, lt.bottom + bottom_bar_height, lt.right, lt.top)
end
local online_button
local update_online_button
if lt.form_factor == "desktop" then
online_button = lt.Layer():Tint(unpack(config.ui_bg))
:Scale(0.6):Translate(lt.left + 0.1, lt.bottom + 0.24)
function update_online_button()
local msg = "O: GO ONLINE"
if lt.state.online then
msg = "O: GO OFFLINE"
end
online_button.child.child.child = lt.Text(msg, font, "left", "bottom")
end
update_online_button()
end
local abandon_button
if lt.form_factor == "desktop" then
abandon_button = lt.Text("ESC:BACK", font, "left", "bottom"):Tint(unpack(config.ui_bg))
:Scale(0.6):Translate(lt.left + 0.1, lt.bottom + 0.1)
else
local back_img = images.back_arrow:Translate(lt.left + swidth / 8, button_bar_mid_y)
local divider = lt.Rect(lt.left + swidth / 4, lt.bottom, lt.left + swidth / 4 + 0.02, lt.bottom + bottom_bar_height)
:Tint(unpack(config.ui_active_color))
abandon_button = lt.Layer(back_img, divider)
:PointerDown(function(event)
flash(function() import("stage_select") end, true)
end, lt.left, lt.bottom, lt.left + swidth / 4, lt.bottom + bottom_bar_height)
end
local leaderboard_wrap = lt.Wrap()
local
function refresh_leaderboard()
local leaderboard = lt.Layer()
local
function render_neighbourhood()
local y = 0
local rank_x, name_x, score_x = 0, 1.2, 6.9
local nbh = lt.state.score_neighbourhood[stage_id]
if nbh then
local user_pos, start, finish
for p, row in ipairs(nbh) do
if row.is_user then
user_pos = p
break
end
end
if not user_pos then return end
start = user_pos - 2
if start < 1 then
start = 1
end
finish = start + 4
if finish > #nbh then
finish = #nbh
start = math.max(1, finish - 4)
end
for p = start, finish do
local row = nbh[p]
local row_layer = lt.Layer()
row_layer:Insert(lt.Text(row.rank .. ".", font, "left", "top"):Translate(rank_x, 0))
row_layer:Insert(lt.Text(row.name, font, "left", "top"):Translate(name_x, 0))
row_layer:Insert(lt.Text(string.format("%.2f%%", row.score), font, "right", "top"):Translate(score_x, 0))
if row.is_user then
row_layer = row_layer:Tint(0.5, 1, 1)
else
row_layer = row_layer:Tint(unpack(config.ui_light_grey))
end
leaderboard:Insert(row_layer:Translate(0, y))
y = y - 0.22
end
end
end
local
function submit_score()
local data = {
userid = lt.state.userid,
name = lt.state.username,
score = tostring(score * 100),
stage = stage_id,
}
if data.userid then
data.check = lt.Secret(data.score .. " " .. data.stage .. " " .. data.userid)
else
data.check = lt.Secret(data.score .. " " .. data.stage .. " " .. data.name)
end
--log(leaderboards_url)
--log(lt.ToJSON(data))
local loading_text = lt.Text("LOADING SCORES...", font, "left", "top")
:Translate(0, -0.1):Tint(unpack(config.ui_light_grey))
leaderboard:Insert(loading_text)
local msg = lt.ToJSON(data)
local req = lt.HTTPRequest(leaderboards_url, msg)
leaderboard:Action(function(dt)
req:Poll()
--log("poll")
if req.success then
--log(req.response)
local result = lt.FromJSON(req.response)
if result then
lt.state.userid = result.userid
lt.state.score_neighbourhood[stage_id] = result.neighbourhood
leaderboard:Remove(loading_text)
render_neighbourhood()
lt.state.last_leaderboard_update_time[stage_id] = os.time()
return true
else
leaderboard:Remove(loading_text)
log("Bad response: " .. req.response)
leaderboard:Remove(loading_text)
leaderboard:Insert(lt.Text("CONNECTION ERROR", font, "left", "top")
:Translate(0, -0.1):Tint(unpack(config.ui_light_grey)))
end
return true
elseif req.failure then
log("Failed to submit score: " .. req.error)
leaderboard:Remove(loading_text)
leaderboard:Insert(lt.Text("CONNECTION ERROR", font, "left", "top")
:Translate(0, -0.1):Tint(unpack(config.ui_light_grey)))
return true
end
return 0.2
end)
end
local
function get_nbh_score(nbh)
for _, row in ipairs(nbh) do
if row.is_user then
return row.score
end
end
return 0
end
if lt.form_factor == "desktop" then
local scale
if lt.state.online then
local nbh = lt.state.score_neighbourhood[stage_id]
local refresh_period = 300
if score > prev_best or not nbh or #nbh == 0 or (get_nbh_score(nbh) + 0.00001) < (score * 100) or
os.difftime(os.time(), lt.state.last_leaderboard_update_time[stage_id]) > refresh_period
then
--log("REFRESHING")
submit_score()
else
render_neighbourhood()
end
scale = 0.4
else
leaderboard:Insert(lt.Text("LEADERBOADS OFFLINE\nPRESS [O] TO GO ONLINE", font, "left", "top")
:Translate(0, -0.1):Tint(unpack(config.ui_light_grey)))
scale = 0.45
end
leaderboard_wrap.child = leaderboard:Scale(scale):Translate(-2.7, -0.4)
end
end
local gamecenter_button
if lt.form_factor ~= "desktop" then
local img
if lt.os == "ios" then
img = images.gamecenter
else
img = images.leaderboard_icon
end
local img = img:Translate(lt.left + swidth * (3/8), button_bar_mid_y)
gamecenter_button = img
:Tint(1, 1, 1):Action(function(dt, n)
if lt.GameCenterAvailable() or lt.os ~= "ios" then
n.red = 1
n.alpha = 1
else
n.red = 0.6
n.alpha = 0.6
end
return 0.5
end)
:PointerDown(function(event)
if lt.GameCenterAvailable() and lt.io == "ios" then
samples.uibleep:Play(1, lt.state.sfx_volume)
lt.ShowLeaderboard("bosonx.stage" .. stage_id)
elseif lt.os == "android" then
samples.uibleep:Play(1, lt.state.sfx_volume)
if lt.state.username == nil then
import("enter_name", function(name)
lt.state.username = name
lt.state.online = true
import("leaderboard", stage_id)
end)
else
lt.state.online = true
import("leaderboard", stage_id)
end
end
end, lt.left + swidth / 4, lt.bottom, lt.left + swidth / 4 + swidth / 4, lt.bottom + bottom_bar_height)
end
local
function text_writer(text)
local pos = 1
local len = text:len()
return lt.Wrap(lt.Layer()):Action(function(dt, node)
pos = pos + 2
node.child = lt.Text(text:sub(1, pos), font, "left", "bottom")
if pos > len then
return true
else
return 0.06
end
end)
end
local graph
do
local max = math.max(1, prev_best, score)
local graph_points = {}
local graph_width = 2.8
local graph_height = 1.1
if lt.form_factor == "desktop" then
graph_height = 0.65
end
local x = 0
local dx = graph_width / (config.score_history_size - 1)
for i = 1, config.score_history_size do
local score = lt.state.score_history[stage_id][i] or 0
if score > max then
max = score
end
end
max = math.ceil(max * 2) * 0.5
for i = 1, config.score_history_size - 1 do
if lt.state.score_history[stage_id][i + 1] then
local y1 = (lt.state.score_history[stage_id][i] / max) * graph_height
local y2 = (lt.state.score_history[stage_id][i + 1] / max) * graph_height
table.append(graph_points, {
{x, y1, 1, 1, 1, 1},
{x + dx, y2, 1, 1, 1, 1}
})
x = x + dx
end
end
local y = (math.max(prev_best, score) / max) * graph_height
table.append(graph_points, {
{0, y, 0, 1, 1, 1},
{graph_width, y, 0, 1, 1, 1},
})
local label_top = lt.Text(string.format("%d%%", max * 100), font, "left", "bottom"):Scale(0.4)
:Translate(0.02, graph_height + 0.00)
:Tint(unpack(config.ui_light_grey))
local label_bottom = lt.Text("0%", font, "left", "top"):Scale(0.4)
:Translate(0.02, -0.00)
:Tint(unpack(config.ui_light_grey))
local buffer = 0.0
graph = lt.Layer(
label_top,
label_bottom,
lt.DrawVector(lt.Vector(graph_points), "lines", 2, 3),
lt.Rect(-buffer, -buffer, graph_width + buffer, graph_height + buffer):Tint(0.9, 0.9, 0.9, 0.2)
):Translate(-2.7, -0.7 + (1.1 - graph_height))
end
if lt.form_factor == "desktop" then
refresh_leaderboard()
end
local score_text = lt.Text(string.format("%0.2f%%", score * 100), digits, "left", "top")
local prev_best_text = lt.Text(string.format("%0.2f%%", prev_best * 100), font, "left", "bottom")
local notches1 = lt.Layer()
local num_notches1 = 50
notches1:Action(function(dt, node)
if num_notches1 > 0 then
local a1 = math.random() * 360
local a2 = a1 + (math.random() * 60 - 30)
notches1:Insert(images.detector_notch1:Rotate(a1):Tween{angle = a2, time = 0.5})
num_notches1 = num_notches1 - 1
return 0.02
else
return true
end
end)
notches1 = notches1:Translate(0, 0.01)
local notches2 = lt.Layer()
local num_notches2 = 20
notches1:Action(function(dt, node)
if num_notches2 > 0 then
local a1 = math.random() * 360
local a2 = a1 + (math.random() * 60 - 30)
notches2:Insert(images.detector_notch2:Rotate(a1):Tween{angle = a2, time = 0.5})
num_notches2 = num_notches2 - 1
return 0.05
else
return true
end
end)
notches2 = notches2:Translate(0, 0.01)
particle_trace = lt.Layer(
particle_trace:Scale(0.3),
particle_trace:Scale(0.3):Translate(0.005, 0.005),
notches1,
notches2,
images.detector_graphic:Tint(1, 1, 1, 0.3)
):Translate(1.66, 0.25)
main_scene.child = lt.Layer(main_scene.child)
--main_scene.child:Insert(computer_sounds())
main_scene.child:Insert(button_bar_overlay():Translate(0, -2):Tween{y = 0, time = 0.5, action = function()
main_scene.child:Insert(restart_button)
main_scene.child:Insert(abandon_button)
if online_button then
main_scene.child:Insert(online_button)
end
if gamecenter_button then
main_scene.child:Insert(gamecenter_button)
end
end})
main_scene.child:Action(coroutine.wrap(function(dt, node)
node:Insert(lt.Text("EXPERIMENT ", font, "left", "bottom")
:Scale(0.6)
:Translate(-2.7, 1.5)
:Tint(unpack(config.ui_light_grey)))
node:Insert(lt.Text(string.upper(stages[stage_id].particle_name), font, "left", "bottom")
:Scale(0.6)
:Translate(-1.76, 1.5)
:Tint(1, 1, 1))
coroutine.yield(0.1)
local status_string = "PARTICLE UNDISCOVERED"
local status_color = {1, 1, 1}
if game_state.stages_unlocked then
status_string = "NEW PARTICLE DISCOVERED"
status_color = {1, 0.5, 0}
elseif lt.state.stage_finished[stage_id] then
status_string = "PARTICLE DISCOVERED"
end
local status_node = lt.Text(status_string, font, "left", "bottom")
:Scale(0.7):Translate(-2.7, 1.3)
:Tint(unpack(status_color))
node:Insert(status_node)
if game_state.stages_unlocked then
node:Insert(lt.Text("EXPERIMENT COMPLETE", font, "left", "top"):Scale(0.4)
:Translate(-2.7, 1.31)
:Tint(0.5, 1, 1))
end
coroutine.yield(0.1)
node:Insert(lt.Text("ENERGY\nREADING", font, "left", "top")
:Scale(0.55):Translate(-2.7, 1.145)
:Tint(unpack(config.ui_light_grey)))
node:Insert(score_text:Scale(0.8)
:Translate(-1.86, 1.15)
:Tint(1, 1, 1))
if score > prev_best then
node:Insert(lt.Text("NEW PEAK", font, "left", "top"):Scale(0.4)
:Translate(-1.85, 0.88)
:Tint(0.5, 1, 1))
end
coroutine.yield(0.1)
node:Insert(lt.Text("PREVIOUS PEAK", font, "left", "bottom")
:Scale(0.4):Translate(-2.7, 0.613)
:Tint(unpack(config.ui_light_grey)))
node:Insert(prev_best_text:Scale(0.6)
:Translate(-1.85, 0.58)
:Tint(1, 1, 1))
coroutine.yield(0.1)
node:Insert(graph)
if lt.form_factor == "desktop" then
node:Insert(leaderboard_wrap)
end
coroutine.yield(0.1)
local run_count = lt.Text("RUN COUNT", font, "left", "bottom")
node:Insert(run_count
:Scale(0.6):Translate(0.7, 1.5)
:Tint(unpack(config.ui_light_grey)))
node:Insert(lt.Text(tostring(lt.state.stages_played[stage_id]), font, "left", "bottom")
:Scale(0.6):Translate(0.7 + run_count.width * 0.6 + 0.08, 1.5)
:Tint(1, 1, 1))
local trace_text = "DETECTOR " .. stage_id .. " PARTICLE TRACE"
node:Insert(lt.Text(trace_text, font, "left", "bottom")
:Scale(0.4):Translate(0.7, 1.4)
:Tint(unpack(config.ui_light_grey)))
coroutine.yield(0.1)
node:Insert(particle_trace)
return true
end))
main_scene.child:KeyDown(function(event)
local key = event.key
if key == "enter" or key == "space" then
retry()
elseif key == "esc" then
import "stage_select"
elseif key == "O" or key == "0" then
if not lt.state.online then
if lt.state.username then
lt.state.online = true
refresh_leaderboard()
update_online_button()
else
import("enter_name", function(name)
lt.state.username = name
lt.state.online = true
refresh_leaderboard()
update_online_button()
end)
end
else
lt.state.online = nil
refresh_leaderboard()
update_online_button()
end
end
end)
| gpl-2.0 |
amohanta/rspamd | test/lua/unit/base32.lua | 9 | 1487 | -- Test zbase32 encoding/decoding
context("Base32 encodning", function()
local ffi = require("ffi")
ffi.cdef[[
void ottery_rand_bytes(void *buf, size_t n);
unsigned ottery_rand_unsigned(void);
unsigned char* rspamd_decode_base32 (const char *in, size_t inlen, size_t *outlen);
char * rspamd_encode_base32 (const unsigned char *in, size_t inlen);
void g_free(void *ptr);
int memcmp(const void *a1, const void *a2, size_t len);
]]
local function random_buf(max_size)
local l = ffi.C.ottery_rand_unsigned() % max_size + 1
local buf = ffi.new("unsigned char[?]", l)
ffi.C.ottery_rand_bytes(buf, l)
return buf, l
end
test("Base32 encode test", function()
local cases = {
{'test123', 'wm3g84fg13cy'},
{'hello', 'em3ags7p'}
}
for _,c in ipairs(cases) do
local b = ffi.C.rspamd_encode_base32(c[1], #c[1])
local s = ffi.string(b)
ffi.C.g_free(b)
assert_equal(s, c[2], s .. " not equal " .. c[2])
end
end)
test("Base32 fuzz test", function()
for i = 1,1000 do
local b, l = random_buf(4096)
local ben = ffi.C.rspamd_encode_base32(b, l)
local bs = ffi.string(ben)
local nl = ffi.new("size_t [1]")
local nb = ffi.C.rspamd_decode_base32(bs, #bs, nl)
local cmp = ffi.C.memcmp(b, nb, l)
ffi.C.g_free(ben)
ffi.C.g_free(nb)
assert_equal(cmp, 0, "fuzz test failed for length: " .. tostring(l))
end
end)
end) | bsd-2-clause |
paulmarsy/Console | Libraries/nmap/App/nselib/iscsi.lua | 1 | 21862 | --- An iSCSI library implementing written by Patrik Karlsson <patrik@cqure.net>
-- The library currently supports target discovery and login.
--
-- The implementation is based on packetdumps and the iSCSI RFC
-- * http://tools.ietf.org/html/rfc3720
--
-- The library contains the protocol message pairs in <code>Packet</code>
-- E.g. <code>LoginRequest</code> and <code>LoginResponse</code>
--
-- Each request can be "serialized" to a string using:
-- <code>tostring(request)</code>.
-- All responses can be read and instantiated from the socket by calling:
-- <code>local status,resp = Response.fromSocket(sock)</code>
--
-- In addition the library has the following classes:
-- * <code>Packet</code>
-- ** A class containing the request and response packets
-- * <code>Comm</code>
-- ** A class used to send and receive packet between the library and server
-- ** The class handles some of the packet "counting" and value updating
-- * <code>KVP</code>
-- ** A key/value pair class that holds key value pairs
-- * <code>Helper</code>
-- ** A class that wraps the <code>Comm</code> and <code>Packet</code> classes
-- ** The purpose of the class is to provide easy access to common iSCSI task
--
--
-- @author "Patrik Karlsson <patrik@cqure.net>"
-- @copyright Same as Nmap--See http://nmap.org/book/man-legal.html
-- Version 0.2
-- Created 2010/11/18 - v0.1 - created by Patrik Karlsson <patrik@cqure.net>
-- Revised 2010/11/28 - v0.2 - improved error handling, fixed discovery issues
-- with multiple addresses <patrik@cqure.net>
local bin = require "bin"
local bit = require "bit"
local ipOps = require "ipOps"
local match = require "match"
local nmap = require "nmap"
local stdnse = require "stdnse"
local openssl = stdnse.silent_require "openssl"
local string = require "string"
local table = require "table"
_ENV = stdnse.module("iscsi", stdnse.seeall)
Packet = {
Opcode = {
LOGIN = 0x03,
TEXT = 0x04,
LOGOUT = 0x06,
},
LoginRequest = {
CSG = {
SecurityNegotiation = 0,
LoginOperationalNegotiation = 1,
FullFeaturePhase = 3,
},
NSG = {
SecurityNegotiation = 0,
LoginOperationalNegotiation = 1,
FullFeaturePhase = 3,
},
--- Creates a new instance of LoginRequest
--
-- @return instance of LoginRequest
new = function( self )
local o = {}
setmetatable(o, self)
self.__index = self
o.immediate = 0
o.opcode = Packet.Opcode.LOGIN
o.flags = {}
o.ver_max = 0
o.ver_min = 0
o.total_ahs_len = 0
o.data_seg_len = 0
o.isid = { t=0x01, a=0x00, b=0x0001, c=0x37, d=0 }
o.tsih = 0
o.initiator_task_tag = 1
o.cid = 1
o.cmdsn = 0
o.expstatsn = 1
o.kvp = KVP:new()
return o
end,
setImmediate = function(self, b) self.immediate = ( b and 1 or 0 ) end,
--- Sets the transit bit
--
-- @param b boolean containing the new transit value
setTransit = function(self, b) self.flags.transit = ( b and 1 or 0 ) end,
--- Sets the continue bit
--
-- @param b boolean containing the new continue value
setContinue = function(self, b) self.flags.continue = ( b and 1 or 0 ) end,
--- Sets the CSG values
--
-- @param csg number containing the new NSG value
setCSG = function(self, csg) self.flags.csg = csg end,
--- Sets the NSG values
--
-- @param nsg number containing the new NSG value
setNSG = function(self, nsg) self.flags.nsg = nsg end,
--- Converts the class instance to string
--
-- @return string containing the converted instance
__tostring = function( self )
local reserved = 0
local kvps = tostring(self.kvp)
self.data_seg_len = #kvps
local pad = 4 - ((#kvps + 48) % 4)
pad = ( pad == 4 ) and 0 or pad
local len = bit.lshift( self.total_ahs_len, 24 ) + self.data_seg_len
local flags = bit.lshift( ( self.flags.transit or 0 ), 7 )
flags = flags + bit.lshift( ( self.flags.continue or 0 ), 6)
flags = flags + ( self.flags.nsg or 0 )
flags = flags + bit.lshift( ( self.flags.csg or 0 ), 2 )
local opcode = self.opcode + bit.lshift((self.immediate or 0), 6)
local data = bin.pack(">CCCCICSCSSISSIILLAA", opcode,
flags, self.ver_max, self.ver_min, len,
bit.lshift( self.isid.t, 6 ) + bit.band( self.isid.a, 0x3f),
self.isid.b, self.isid.c, self.isid.d, self.tsih,
self.initiator_task_tag, self.cid, reserved, self.cmdsn,
self.expstatsn, reserved, reserved, kvps, string.rep('\0', pad) )
return data
end
},
LoginResponse = {
-- Error messages
ErrorMsgs = {
[0x0000] = "Success",
[0x0101] = "Target moved temporarily",
[0x0102] = "Target moved permanently",
[0x0200] = "Initiator error",
[0x0201] = "Authentication failure",
[0x0202] = "Authorization failure",
[0x0203] = "Target not found",
[0x0204] = "Target removed",
[0x0205] = "Unsupported version",
[0x0206] = "Too many connections",
[0x0207] = "Missing parameter",
[0x0208] = "Can't include in session",
[0x0209] = "Session type not supported",
[0x020a] = "Session does not exist",
[0x020b] = "Invalid request during login",
[0x0300] = "Target error",
[0x0301] = "Service unavailable",
[0x0302] = "Out of resources",
},
-- Error constants
Errors = {
SUCCESS = 0,
AUTH_FAILED = 0x0201,
},
--- Creates a new instance of LoginResponse
--
-- @return instance of LoginResponse
new = function( self )
local o = {}
setmetatable(o, self)
self.__index = self
return o
end,
--- Returns the error message
getErrorMessage = function( self )
return Packet.LoginResponse.ErrorMsgs[self.status_code] or "Unknown error"
end,
--- Returns the error code
getErrorCode = function( self ) return self.status_code or 0 end,
--- Creates a LoginResponse with data read from the socket
--
-- @return status true on success, false on failure
-- @return resp instance of LoginResponse
fromSocket = function( s )
local status, header = s:receive_buf(match.numbytes(48), true)
if ( not(status) ) then
return false, "Failed to read header from socket"
end
local resp = Packet.LoginResponse:new()
local pos, len = bin.unpack(">I", header, 5)
resp.total_ahs_len = bit.rshift(len, 24)
resp.data_seg_len = bit.band(len, 0x00ffffff)
pos, resp.status_code = bin.unpack(">S", header, 37)
local pad = ( 4 - ( resp.data_seg_len % 4 ) )
pad = ( pad == 4 ) and 0 or pad
local status, data = s:receive_buf(match.numbytes(resp.data_seg_len + pad), true)
if ( not(status) ) then
return false, "Failed to read data from socket"
end
resp.kvp = KVP:new()
for _, kvp in ipairs(stdnse.strsplit( "\0", data )) do
local k, v = kvp:match("(.*)=(.*)")
if ( v ) then resp.kvp:add( k, v ) end
end
return true, resp
end,
},
TextRequest = {
--- Creates a new instance of TextRequest
--
-- @return instance of TextRequest
new = function( self )
local o = {}
setmetatable(o, self)
self.__index = self
o.opcode = Packet.Opcode.TEXT
o.flags = {}
o.flags.final = 0
o.flags.continue = 0
o.total_ahs_len = 0
o.data_seg_len = 0
o.lun = 0
o.initiator_task_tag = 1
o.target_trans_tag = 0xffffffff
o.cmdsn = 2
o.expstatsn = 1
o.kvp = KVP:new()
return o
end,
--- Sets the final bit of the TextRequest
setFinal = function( self, b ) self.flags.final = ( b and 1 or 0 ) end,
--- Sets the continue bit of the TextRequest
setContinue = function( self, b ) self.flags.continue = ( b and 1 or 0 ) end,
--- Converts the class instance to string
--
-- @return string containing the converted instance
__tostring = function(self)
local flags = bit.lshift( ( self.flags.final or 0 ), 7 )
flags = flags + bit.lshift( (self.flags.continue or 0), 6 )
local kvps = tostring(self.kvp)
kvps = kvps .. string.rep('\0', #kvps % 2)
self.data_seg_len = #kvps
local len = bit.lshift( self.total_ahs_len, 24 ) + self.data_seg_len
local reserved = 0
local data = bin.pack(">CCSILIIIILLA", self.opcode, flags, reserved,
len, self.lun, self.initiator_task_tag, self.target_trans_tag,
self.cmdsn, self.expstatsn, reserved, reserved, kvps)
return data
end,
},
TextResponse = {
--- Creates a new instance of TextResponse
--
-- @return instance of TextResponse
new = function( self )
local o = {}
setmetatable(o, self)
self.__index = self
return o
end,
--- Creates a TextResponse with data read from the socket
--
-- @return status true on success, false on failure
-- @return instance of TextResponse
-- err string containing error message
fromSocket = function( s )
local resp = Packet.TextResponse:new()
local textdata = ""
repeat
local status, header = s:receive_buf(match.numbytes(48), true)
if not status then return status, header end
local pos, _, flags, _, _, len = bin.unpack(">CCCCI", header)
local cont = ( bit.band(flags, 0x40) == 0x40 )
resp.total_ahs_len = bit.rshift(len, 24)
resp.data_seg_len = bit.band(len, 0x00ffffff)
local data
status, data = s:receive_buf(match.numbytes(resp.data_seg_len), true)
textdata = textdata .. data
until( not(cont) )
resp.records = {}
local kvps = stdnse.strsplit( "\0", textdata )
local record
-- Each target record starts with one text key of the form:
-- TargetName=<target-name-goes-here>
-- Followed by zero or more address keys of the form:
-- TargetAddress=<hostname-or-ipaddress>[:<tcp-port>],
-- <portal-group-tag>
for _, kvp in ipairs(kvps) do
local k, v = kvp:match("(.*)%=(.*)")
if ( k == "TargetName" ) then
if ( record ) then
table.insert(resp.records, record)
record = {}
end
if ( #resp.records == 0 ) then record = {} end
record.name = v
elseif ( k == "TargetAddress" ) then
record.addr = record.addr or {}
table.insert( record.addr, v )
elseif ( not(k) ) then
-- this should be the ending empty kvp
table.insert(resp.records, record)
break
else
stdnse.debug1("ERROR: iscsi.TextResponse: Unknown target record (%s)", k)
end
end
return true, resp
end,
},
--- Class handling a login request
LogoutRequest = {
--- Creates a new instance of LogoutRequest
--
-- @return instance of LogoutRequest
new = function( self )
local o = {}
setmetatable(o, self)
self.__index = self
o.opcode = Packet.Opcode.LOGOUT
o.immediate = 1
o.reasoncode = 0
o.total_ahs_len = 0
o.data_seg_len = 0
o.initiator_task_tag = 2
o.cid = 1
o.cmdsn = 0
o.expstatsn = 1
return o
end,
--- Converts the class instance to string
--
-- @return string containing the converted instance
__tostring = function(self)
local opcode = self.opcode + bit.lshift((self.immediate or 0), 6)
local reserved = 0
local len = bit.lshift( self.total_ahs_len, 24 ) + self.data_seg_len
local data = bin.pack(">CCSILISSIILL", opcode, (0x80 + self.reasoncode),
reserved, len, reserved,self.initiator_task_tag, self.cid,
reserved, self.cmdsn, self.expstatsn, reserved, reserved )
return data
end,
},
--- Class handling the Logout response
LogoutResponse = {
--- Creates a new instance of LogoutResponse
--
-- @return instance of LogoutResponse
new = function( self )
local o = {}
setmetatable(o, self)
self.__index = self
return o
end,
--- Creates a LogoutResponse with data read from the socket
--
-- @return status true on success, false on failure
-- @return instance of LogoutResponse
-- err string containing error message
fromSocket = function( s )
local resp = Packet.LogoutResponse:new()
local status, header = s:receive_buf(match.numbytes(48), true)
if ( not(status) ) then return status, header end
return true, resp
end
}
}
--- The communication class handles socket reads and writes
--
-- In addition it keeps track of both immediate packets and the amount of read
-- packets and updates cmdsn and expstatsn accordingly.
Comm = {
--- Creates a new instance of Comm
--
-- @return instance of Comm
new = function(self, socket)
local o = {}
setmetatable(o, self)
self.__index = self
o.expstatsn = 0
o.cmdsn = 1
o.socket = socket
return o
end,
--- Sends a packet and retrieves the response
--
-- @param out_packet instance of a packet to send
-- @param in_class class of the packet to read
-- @return status true on success, false on failure
-- @return r decoded instance of in_class
exchange = function( self, out_packet, in_class )
local expstatsn = ( self.expstatsn == 0 ) and 1 or self.expstatsn
if ( out_packet.immediate and out_packet.immediate == 1 ) then
self.cmdsn = self.cmdsn + 1
end
out_packet.expstatsn = expstatsn
out_packet.cmdsn = self.cmdsn
self.socket:send( tostring( out_packet ) )
local status, r = in_class.fromSocket( self.socket )
self.expstatsn = self.expstatsn + 1
return status, r
end,
}
--- Key/Value pairs class
KVP = {
--- Creates a new instance of KVP
--
-- @return instance of KVP
new = function( self )
local o = {}
setmetatable(o, self)
self.__index = self
o.kvp = {}
return o
end,
--- Adds a key/value pair
--
-- @param key string containing the key name
-- @param value string containing the value
add = function( self, key, value )
table.insert( self.kvp, {[key]=value} )
end,
--- Gets all values for a specific key
--
-- @param key string containing the name of the key to retrieve
-- @return values table containing all values for the specified key
get = function( self, key )
local values = {}
for _, kvp in ipairs(self.kvp) do
for k, v in pairs( kvp ) do
if ( key == k ) then
table.insert( values, v )
end
end
end
return values
end,
--- Returns all key value pairs as string delimited by \0
-- eg. "key1=val1\0key2=val2\0"
--
-- @return string containing all key/value pairs
__tostring = function( self )
local ret = ""
for _, kvp in ipairs(self.kvp) do
for k, v in pairs( kvp ) do
ret = ret .. ("%s=%s\0"):format(k,v)
end
end
return ret
end,
}
--- CHAP authentication class
CHAP = {
--- Calculate a CHAP - response
--
-- @param identifier number containing the CHAP identifier
-- @param challenge string containing the challenge
-- @param secret string containing the users password
-- @return response string containing the CHAP response
calcResponse = function( identifier, challenge, secret )
return openssl.md5( identifier .. secret .. challenge )
end,
}
--- The helper class contains functions with more descriptive names
Helper = {
--- Creates a new instance of the Helper class
--
-- @param host table as received by the script action function
-- @param port table as received by the script action function
-- @return o instance of Helper
new = function( self, host, port )
local o = {}
setmetatable(o, self)
self.__index = self
o.host, o.port = host, port
o.socket = nmap.new_socket()
return o
end,
--- Connects to the iSCSI target
--
-- @return status true on success, false on failure
-- @return err string containing error message is status is false
connect = function( self )
self.socket:set_timeout(10000)
local status, err = self.socket:connect(self.host, self.port, "tcp")
if ( not(status) ) then return false, err end
self.comm = Comm:new( self.socket )
return true
end,
--- Attempts to discover accessible iSCSI targets on the remote server
--
-- @return status true on success, false on failure
-- @return targets table containing discovered targets
-- each table entry is a target table with <code>name</code>
-- and <code>addr</code>.
-- err string containing an error message is status is false
discoverTargets = function( self )
local p = Packet.LoginRequest:new()
p:setTransit(true)
p:setNSG(Packet.LoginRequest.NSG.LoginOperationalNegotiation)
p.kvp:add( "InitiatorName", "iqn.1991-05.com.microsoft:nmap_iscsi_probe" )
p.kvp:add( "SessionType", "Discovery" )
p.kvp:add( "AuthMethod", "None" )
local status, resp = self.comm:exchange( p, Packet.LoginResponse )
if ( not(status) ) then
return false, ("ERROR: iscsi.Helper.discoverTargets: %s"):format(resp)
end
local auth_method = resp.kvp:get("AuthMethod")[1]
if ( auth_method:upper() ~= "NONE" ) then
return false, "ERROR: iscsi.Helper.discoverTargets: Unsupported authentication method"
end
p = Packet.LoginRequest:new()
p:setTransit(true)
p:setNSG(Packet.LoginRequest.NSG.FullFeaturePhase)
p:setCSG(Packet.LoginRequest.CSG.LoginOperationalNegotiation)
p.kvp:add( "HeaderDigest", "None")
p.kvp:add( "DataDigest", "None")
p.kvp:add( "MaxRecvDataSegmentLength", "65536")
p.kvp:add( "DefaultTime2Wait", "0")
p.kvp:add( "DefaultTime2Retain", "60")
status, resp = self.comm:exchange( p, Packet.LoginResponse )
p = Packet.TextRequest:new()
p:setFinal(true)
p.kvp:add( "SendTargets", "All" )
status, resp = self.comm:exchange( p, Packet.TextResponse )
if ( not(resp.records) ) then
return false, "iscsi.discoverTargets: response returned no targets"
end
for _, record in ipairs(resp.records) do
table.sort( record.addr, function(a, b) local c = ipOps.compare_ip(a:match("(.-):"), "le", b:match("(.-):")); return c end )
end
return true, resp.records
end,
--- Logs out from the iSCSI target
--
-- @return status true on success, false on failure
logout = function(self)
local p = Packet.LogoutRequest:new()
local status, resp = self.comm:exchange( p, Packet.LogoutResponse )
return status
end,
--- Authenticate to the iSCSI service
--
-- @param target_name string containing the name of the iSCSI target
-- @param username string containing the username
-- @param password string containing the password
-- @param auth_method string containing either "None" or "Chap"
-- @return status true on success false on failure
-- @return response containing the loginresponse or
-- err string containing an error message if status is false
login = function( self, target_name, username, password, auth_method )
local auth_method = auth_method or "None"
if ( not(target_name) ) then
return false, "No target name specified"
end
if ( auth_method:upper()~= "NONE" and
auth_method:upper()~= "CHAP" ) then
return false, "Unknown authentication method"
end
local p = Packet.LoginRequest:new()
p:setTransit(true)
p:setNSG(Packet.LoginRequest.NSG.LoginOperationalNegotiation)
p.kvp:add( "InitiatorName", "iqn.1991-05.com.microsoft:nmap_iscsi_probe" )
p.kvp:add( "SessionType", "Normal" )
p.kvp:add( "TargetName", target_name )
p.kvp:add( "AuthMethod", auth_method )
if ( not(self.comm) ) then
return false, "ERROR: iscsi.Helper.login: Not connected"
end
local status, resp = self.comm:exchange( p, Packet.LoginResponse )
if ( not(status) ) then
return false, ("ERROR: iscsi.Helper.login: %s"):format(resp)
end
if ( resp.status_code ~= 0 ) then
stdnse.debug3("ERROR: iscsi.Helper.login: Authentication failed (error code: %d)", resp.status_code)
return false, resp
elseif ( auth_method:upper()=="NONE" ) then
return true, resp
end
p = Packet.LoginRequest:new()
p.kvp:add( "CHAP_A", "5" )
status, resp = self.comm:exchange( p, Packet.LoginResponse )
if ( not(status) ) then
return false, ("ERROR: iscsi.Helper.login: %s"):format(resp)
end
local alg = resp.kvp:get("CHAP_A")[1]
if ( alg ~= "5" ) then return false, "Unsupported authentication algorithm" end
local chall = resp.kvp:get("CHAP_C")[1]
if ( not(chall) ) then return false, "Failed to decode challenge" end
chall = bin.pack("H", chall:sub(3))
local ident = resp.kvp:get("CHAP_I")[1]
if (not(ident)) then return false, "Failed to decoded identifier" end
ident = string.char(tonumber(ident))
local resp = CHAP.calcResponse( ident, chall, password )
resp = "0x" .. select(2, bin.unpack("H16", resp))
p = Packet.LoginRequest:new()
p:setImmediate(true)
p:setTransit(true)
p:setNSG(Packet.LoginRequest.NSG.LoginOperationalNegotiation)
p.kvp:add("CHAP_N", username)
p.kvp:add("CHAP_R", resp)
status, resp = self.comm:exchange( p, Packet.LoginResponse )
if ( not(status) ) then
return false, ("ERROR: iscsi.Helper.login: %s"):format(resp)
end
if ( resp:getErrorCode() ~= Packet.LoginResponse.Errors.SUCCESS ) then
return false, "Login failed"
end
return true, resp
end,
--- Disconnects the socket from the server
close = function(self) self.socket:close() end
}
return _ENV;
| mit |
yetsky/extra | luci/applications/luci-mwan3/luasrc/model/cbi/mwan/interface.lua | 1 | 10012 | -- ------ extra functions ------ --
function interfaceCheck() -- find issues with too many interfaces, reliability and metric
uci.cursor():foreach("mwan3", "interface",
function (section)
local interfaceName = section[".name"]
interfaceNumber = interfaceNumber+1 -- count number of mwan interfaces configured
-- create list of metrics for none and duplicate checking
local metricValue = ut.trim(sys.exec("uci get -p /var/state network." .. interfaceName .. ".metric"))
if metricValue == "" then
errorFound = 1
errorNoMetricList = errorNoMetricList .. interfaceName .. " "
else
metricList = metricList .. interfaceName .. " " .. metricValue .. "\n"
end
-- check if any interfaces have a higher reliability requirement than tracking IPs configured
local trackingNumber = tonumber(ut.trim(sys.exec("echo $(uci get -p /var/state mwan3." .. interfaceName .. ".track_ip) | wc -w")))
if trackingNumber > 0 then
local reliabilityNumber = tonumber(ut.trim(sys.exec("uci get -p /var/state mwan3." .. interfaceName .. ".reliability")))
if reliabilityNumber and reliabilityNumber > trackingNumber then
errorFound = 1
errorReliabilityList = errorReliabilityList .. interfaceName .. " "
end
end
-- check if any interfaces are not properly configured in /etc/config/network or have no default route in main routing table
if ut.trim(sys.exec("uci get -p /var/state network." .. interfaceName)) == "interface" then
local interfaceDevice = ut.trim(sys.exec("uci get -p /var/state network." .. interfaceName .. ".ifname"))
if interfaceDevice == "uci: Entry not found" or interfaceDevice == "" then
errorFound = 1
errorNetConfigList = errorNetConfigList .. interfaceName .. " "
errorRouteList = errorRouteList .. interfaceName .. " "
else
local routeCheck = ut.trim(sys.exec("route -n | awk '{if ($8 == \"" .. interfaceDevice .. "\" && $1 == \"0.0.0.0\" && $3 == \"0.0.0.0\") print $1}'"))
if routeCheck == "" then
errorFound = 1
errorRouteList = errorRouteList .. interfaceName .. " "
end
end
else
errorFound = 1
errorNetConfigList = errorNetConfigList .. interfaceName .. " "
errorRouteList = errorRouteList .. interfaceName .. " "
end
end
)
-- check if any interfaces have duplicate metrics
local metricDuplicateNumbers = sys.exec("echo '" .. metricList .. "' | awk '{print $2}' | uniq -d")
if metricDuplicateNumbers ~= "" then
errorFound = 1
local metricDuplicates = ""
for line in metricDuplicateNumbers:gmatch("[^\r\n]+") do
metricDuplicates = sys.exec("echo '" .. metricList .. "' | grep '" .. line .. "' | awk '{print $1}'")
errorDuplicateMetricList = errorDuplicateMetricList .. metricDuplicates
end
errorDuplicateMetricList = sys.exec("echo '" .. errorDuplicateMetricList .. "' | tr '\n' ' '")
end
end
function interfaceWarnings() -- display status and warning messages at the top of the page
local warnings = ""
if interfaceNumber <= 250 then
warnings = "<strong>There are currently " .. interfaceNumber .. " of 250 supported interfaces configured</strong>"
else
warnings = "<font color=\"ff0000\"><strong>WARNING: " .. interfaceNumber .. " interfaces are configured exceeding the maximum of 250!</strong></font>"
end
if errorReliabilityList ~= " " then
warnings = warnings .. "<br /><br /><font color=\"ff0000\"><strong>WARNING: some interfaces have a higher reliability requirement than there are tracking IP addresses!</strong></font>"
end
if errorRouteList ~= " " then
warnings = warnings .. "<br /><br /><font color=\"ff0000\"><strong>WARNING: some interfaces have no default route in the main routing table!</strong></font>"
end
if errorNetConfigList ~= " " then
warnings = warnings .. "<br /><br /><font color=\"ff0000\"><strong>WARNING: some interfaces are configured incorrectly or not at all in /etc/config/network!</strong></font>"
end
if errorNoMetricList ~= " " then
warnings = warnings .. "<br /><br /><font color=\"ff0000\"><strong>WARNING: some interfaces have no metric configured in /etc/config/network!</strong></font>"
end
if errorDuplicateMetricList ~= " " then
warnings = warnings .. "<br /><br /><font color=\"ff0000\"><strong>WARNING: some interfaces have duplicate metrics configured in /etc/config/network!</strong></font>"
end
return warnings
end
-- ------ interface configuration ------ --
dsp = require "luci.dispatcher"
sys = require "luci.sys"
ut = require "luci.util"
interfaceNumber = 0
metricList = ""
errorFound = 0
errorDuplicateMetricList = " "
errorNetConfigList = " "
errorNoMetricList = " "
errorReliabilityList = " "
errorRouteList = " "
interfaceCheck()
m5 = Map("mwan3", translate("MWAN Interface Configuration"),
translate(interfaceWarnings()))
m5:append(Template("mwan/config_css"))
mwan_interface = m5:section(TypedSection, "interface", translate("Interfaces"),
translate("MWAN supports up to 250 physical and/or logical interfaces<br />" ..
"MWAN requires that all interfaces have a unique metric configured in /etc/config/network<br />" ..
"Names must match the interface name found in /etc/config/network (see advanced tab)<br />" ..
"Names may contain characters A-Z, a-z, 0-9, _ and no spaces<br />" ..
"Interfaces may not share the same name as configured members, policies or rules"))
mwan_interface.addremove = true
mwan_interface.dynamic = false
mwan_interface.sectionhead = "Interface"
mwan_interface.sortable = true
mwan_interface.template = "cbi/tblsection"
mwan_interface.extedit = dsp.build_url("admin", "network", "mwan", "configuration", "interface", "%s")
function mwan_interface.create(self, section)
TypedSection.create(self, section)
m5.uci:save("mwan3")
luci.http.redirect(dsp.build_url("admin", "network", "mwan", "configuration", "interface", section))
end
enabled = mwan_interface:option(DummyValue, "enabled", translate("Enabled"))
enabled.rawhtml = true
function enabled.cfgvalue(self, s)
if self.map:get(s, "enabled") == "1" then
return "Yes"
else
return "No"
end
end
track_ip = mwan_interface:option(DummyValue, "track_ip", translate("Tracking IP"))
track_ip.rawhtml = true
function track_ip.cfgvalue(self, s)
tracked = self.map:get(s, "track_ip")
if tracked then
local ipList = ""
for k,v in pairs(tracked) do
ipList = ipList .. v .. "<br />"
end
return ipList
else
return "—"
end
end
reliability = mwan_interface:option(DummyValue, "reliability", translate("Tracking reliability"))
reliability.rawhtml = true
function reliability.cfgvalue(self, s)
if tracked then
return self.map:get(s, "reliability") or "—"
else
return "—"
end
end
count = mwan_interface:option(DummyValue, "count", translate("Ping count"))
count.rawhtml = true
function count.cfgvalue(self, s)
if tracked then
return self.map:get(s, "count") or "—"
else
return "—"
end
end
timeout = mwan_interface:option(DummyValue, "timeout", translate("Ping timeout"))
timeout.rawhtml = true
function timeout.cfgvalue(self, s)
if tracked then
local timeoutValue = self.map:get(s, "timeout")
if timeoutValue then
return timeoutValue .. "s"
else
return "—"
end
else
return "—"
end
end
interval = mwan_interface:option(DummyValue, "interval", translate("Ping interval"))
interval.rawhtml = true
function interval.cfgvalue(self, s)
if tracked then
local intervalValue = self.map:get(s, "interval")
if intervalValue then
return intervalValue .. "s"
else
return "—"
end
else
return "—"
end
end
down = mwan_interface:option(DummyValue, "down", translate("Interface down"))
down.rawhtml = true
function down.cfgvalue(self, s)
if tracked then
return self.map:get(s, "down") or "—"
else
return "—"
end
end
up = mwan_interface:option(DummyValue, "up", translate("Interface up"))
up.rawhtml = true
function up.cfgvalue(self, s)
if tracked then
return self.map:get(s, "up") or "—"
else
return "—"
end
end
metric = mwan_interface:option(DummyValue, "metric", translate("Metric"))
metric.rawhtml = true
function metric.cfgvalue(self, s)
local metricValue = sys.exec("uci get -p /var/state network." .. s .. ".metric")
if metricValue ~= "" then
return metricValue
else
return "—"
end
end
errors = mwan_interface:option(DummyValue, "errors", translate("Errors"))
errors.rawhtml = true
function errors.cfgvalue(self, s)
if errorFound == 1 then
local mouseOver, lineBreak = "", ""
if string.find(errorReliabilityList, " " .. s .. " ") then
mouseOver = "Higher reliability requirement than there are tracking IP addresses"
lineBreak = " "
end
if string.find(errorRouteList, " " .. s .. " ") then
mouseOver = mouseOver .. lineBreak .. "No default route in the main routing table"
lineBreak = " "
end
if string.find(errorNetConfigList, " " .. s .. " ") then
mouseOver = mouseOver .. lineBreak .. "Configured incorrectly or not at all in /etc/config/network"
lineBreak = " "
end
if string.find(errorNoMetricList, " " .. s .. " ") then
mouseOver = mouseOver .. lineBreak .. "No metric configured in /etc/config/network"
lineBreak = " "
end
if string.find(errorDuplicateMetricList, " " .. s .. " ") then
mouseOver = mouseOver .. lineBreak .. "Duplicate metric configured in /etc/config/network"
end
if mouseOver == "" then
return ""
else
return "<span title=\"" .. mouseOver .. "\"><img src=\"/luci-static/resources/cbi/reset.gif\" alt=\"error\"></img></span>"
end
else
return ""
end
end
return m5
| gpl-2.0 |
ziz/solarus | quests/zsdx/data/enemies/khorneth.lua | 2 | 4604 | -- The boss Khorneth from @PyroNet.
-- Khorneth has two blades that must be destroyed first.
main_sprite_name = "enemies/khorneth"
left_blade_sprite_name = "enemies/khorneth_left_blade"
right_blade_sprite_name = "enemies/khorneth_right_blade"
-- State
left_blade_life = 4
right_blade_life = 4
blade_attack = false;
function event_appear()
-- set the properties
sol.enemy.set_life(5)
sol.enemy.set_damage(2)
sol.enemy.set_pushed_back_when_hurt(false)
sol.enemy.create_sprite(main_sprite_name)
sol.enemy.create_sprite(left_blade_sprite_name)
sol.enemy.create_sprite(right_blade_sprite_name)
sol.enemy.set_size(40, 48)
sol.enemy.set_origin(20, 25)
sol.enemy.set_invincible()
sol.enemy.set_attack_consequence_sprite(get_left_blade_sprite(), "sword", "custom")
sol.enemy.set_attack_consequence_sprite(get_right_blade_sprite(), "sword", "custom")
-- when a blade sprite has the same animation than the main sprite, synchronize their frames
sol.main.sprite_synchronize(get_left_blade_sprite(), get_main_sprite())
sol.main.sprite_synchronize(get_right_blade_sprite(), get_main_sprite())
end
function event_restart()
-- set the movement
m = sol.main.random_path_movement_create(48)
sol.enemy.start_movement(m)
-- schedule a blade attack
if has_blade() then
duration = 1000 * (1 + math.random(4))
sol.main.timer_start(duration, "start_blade_attack", false)
blade_attack = false;
end
end
function has_left_blade()
return left_blade_life > 0
end
function has_right_blade()
return right_blade_life > 0
end
function has_blade()
return has_left_blade() or has_right_blade()
end
function get_main_sprite()
return sol.enemy.get_sprite(main_sprite_name)
end
function get_left_blade_sprite()
return sol.enemy.get_sprite(left_blade_sprite_name)
end
function get_right_blade_sprite()
return sol.enemy.get_sprite(right_blade_sprite_name)
end
-- The enemy receives an attack whose consequence is "custom"
function event_custom_attack_received(attack, sprite)
if has_left_blade()
and sprite == get_left_blade_sprite()
and sol.main.sprite_get_animation(sprite) ~= "stopped" then
sol.main.sprite_set_animation(sprite, "hurt")
sol.main.sprite_set_animation(get_main_sprite(), "stopped")
if has_right_blade() then
sol.main.sprite_set_animation(get_right_blade_sprite(), "stopped")
end
sol.enemy.stop_movement()
sol.main.play_sound("boss_hurt")
left_blade_life = left_blade_life - 1
sol.main.timer_start(400, "stop_hurting_left_blade", false)
elseif has_right_blade()
and sprite == get_right_blade_sprite()
and sol.main.sprite_get_animation(sprite) ~= "stopped" then
sol.main.sprite_set_animation(sprite, "hurt")
sol.main.sprite_set_animation(get_main_sprite(), "stopped")
if has_left_blade() then
sol.main.sprite_set_animation(get_left_blade_sprite(), "stopped")
end
sol.enemy.stop_movement()
sol.main.play_sound("boss_hurt")
right_blade_life = right_blade_life - 1
sol.main.timer_start(400, "stop_hurting_right_blade", false)
end
return 0 -- don't remove any life points
end
function start_blade_attack()
if has_blade() and not blade_attack then
blade_attack = true
if not has_right_blade() then
side = 0
elseif not has_left_blade() then
side = 1
else
side = math.random(2) - 1
end
if side == 0 then
animation = "left_blade_attack"
else
animation = "right_blade_attack"
end
sol.main.sprite_set_animation(get_main_sprite(), animation)
if has_left_blade() then
sol.main.sprite_set_animation(get_left_blade_sprite(), animation)
end
if has_right_blade() then
sol.main.sprite_set_animation(get_right_blade_sprite(), animation)
end
sol.enemy.stop_movement()
end
end
function event_sprite_animation_finished(sprite, animation)
if blade_attack and sprite == get_main_sprite() then
blade_attack = false
sol.enemy.restart()
end
end
function stop_hurting_left_blade()
sol.enemy.restart();
if left_blade_life <= 0 then
sol.main.play_sound("stone")
sol.enemy.remove_sprite(left_blade_sprite_name)
if not has_right_blade() then
start_final_phase()
end
end
end
function stop_hurting_right_blade()
sol.enemy.restart();
if right_blade_life <= 0 then
sol.main.play_sound("stone")
sol.enemy.remove_sprite(right_blade_sprite_name)
if not has_left_blade() then
start_final_phase()
end
end
end
function start_final_phase()
sol.enemy.set_attack_consequence("sword", 1);
end
| gpl-3.0 |
osgcc/ryzom | ryzom/common/data_common/r2/r2_logic_comp.lua | 3 | 8025 | r2.logicComponents = {}
r2.logicComponents.logicEditors = {
r2.activities,
r2.dialogs,
r2.events,
}
r2.logicComponents.undoRedoInstances = {}
----- INIT ALL EDITORS ----------------------------------------------------
function r2.logicComponents:initLogicEditors()
for k, uiClass in pairs(self.logicEditors) do
uiClass:initEditor()
end
end
------ SELECT ELEMENT --------------------------------------------
function r2.logicComponents:selectElement(classUI, selectedButtonElt)
if selectedButtonElt == nil then
selectedButtonElt = getUICaller()
end
assert(selectedButtonElt)
local sequenceUI = classUI:currentSequUI()
assert(sequenceUI)
local upDown = sequenceUI:find("order_group")
assert(upDown)
-- new selected element
if selectedButtonElt.pushed == true then
if classUI:currentEltUIId() then
local lastSelectedElement = classUI:currentEltUI()
assert(lastSelectedElement)
local lastEltsList = lastSelectedElement.parent
local editElt = lastEltsList:find("edit_element")
assert(editElt)
if classUI:currentEltUIId() == selectedButtonElt.parent.parent.parent.id then
return
end
lastSelectedElement.active = true
lastSelectedElement:find("select").pushed = false
editElt.active = false
end
classUI:setCurrentEltUIId(selectedButtonElt.parent.parent.parent.id)
local selectedElement = selectedButtonElt.parent.parent.parent
assert(selectedElement)
-- update element editor position in list
local eltsList = sequenceUI:find("elements_list")
assert(eltsList)
local editElt = eltsList:find("edit_element")
assert(editElt)
local indexSelectedElt = eltsList:getElementIndex(selectedElement)
local indexEltEditor = eltsList:getElementIndex(editElt)
if indexEltEditor<indexSelectedElt then
for i=indexEltEditor, indexSelectedElt-1 do
eltsList:downChild(editElt)
end
else
for i=indexSelectedElt, indexEltEditor-2 do
eltsList:upChild(editElt)
end
end
editElt.active = true
selectedElement.active = false
classUI:updateElementEditor()
upDown.active = (classUI.elementOrder==true and eltsList.childrenNb>2)
-- cancel current selection
else
local lastSelectedElement = classUI:currentEltUI()
assert(lastSelectedElement)
upDown.active = false
local lastEltsList = lastSelectedElement.parent
local editElt = lastEltsList:find("edit_element")
assert(editElt)
editElt.active = false
lastSelectedElement.active = true
classUI:setCurrentEltUIId(nil)
end
end
------ SELECT SEQUENCE --------------------------------------
function r2.logicComponents:selectSequence(classUI, sequenceUI)
local sequenceUI = classUI:currentSequUI()
assert(sequenceUI)
-- select first chat of dialog
local eltsList = sequenceUI:find("elements_list")
assert(eltsList)
-- if eltsList.childrenNb > 1 then
-- local firstElt = eltsList:getChild(0)
-- element editor
-- if r2.logicUI:getEltUIInstId(firstElt) == nil then
-- firstElt = eltsList:getChild(1)
-- end
-- local selectedButton = firstElt:find("select")
-- assert(selectedButton)
-- selectedButton.pushed = true
-- classUI:selectElement(selectedButton)
-- end
-- deselect old selected element
if classUI:currentEltUIId() then
local lastSelectedElement = classUI:currentEltUI()
assert(lastSelectedElement)
local lastEltsList = lastSelectedElement.parent
local editElt = lastEltsList:find("edit_element")
assert(editElt)
lastSelectedElement.active = true
lastSelectedElement:find("select").pushed = false
editElt.active = false
classUI:setCurrentEltUIId(nil)
end
eltsList.Env.Minimize = true
end
------ CREATE EDITOR -----------------------------------------------
function r2.logicComponents:createElementEditor(classUI)
-- not necessary current sequenceUI
local sequenceUI = classUI:updatedSequUI()
assert(sequenceUI)
-- create element editor
local elementsList = sequenceUI:find("elements_list")
assert(elementsList)
local newEditorElt = createGroupInstance(classUI.elementEditorTemplate, elementsList.id, {id="edit_element", active="false"})
assert(newEditorElt)
elementsList:addChild(newEditorElt)
elementsList.parent:updateCoords()
newEditorElt.active = false
return newEditorElt
end
----- CLOSE ELEMENT EDITOR ---------------------------------------------
function r2.logicComponents:closeElementEditor(classUI)
local selectedEltUI = classUI:currentEltUI()
if selectedEltUI then
local selectedEltButton = selectedEltUI:find("select")
assert(selectedEltButton)
selectedEltButton.pushed = false
classUI:selectElement(selectedEltButton)
end
end
------ NEW ELEMENT INST ------------------------------------------
function r2.logicComponents:newElementInst(classUI)
end
------ UPDATE ELEMENT TITLE -------------------------------------------
function r2.logicComponents:updateElementTitle(classUI, eltUI, showPartIndex)
local eltInst = r2:getInstanceFromId(r2.logicUI:getEltUIInstId(eltUI))
assert(eltInst)
-- part index
local partIndex = ""
if showPartIndex then
local index = self:searchElementIndex(eltInst)
partIndex = classUI.elementInitialName.." "..index.." : "
end
local eltName = eltInst:getName()
-- title
local title = eltUI:find("title")
assert(title)
local uc_title = ucstring()
uc_title:fromUtf8(partIndex..eltName)
title.uc_hardtext_format = uc_title
end
------ REMOVE ELEMENT INST ----------------------------------------
function r2.logicComponents:removeElementInst(classUI)
--r2.requestNewAction(i18n.get("uiR2EDRemoveLogicElementAction"))
local toErasedInstId = classUI:currentEltInstId()
assert(toErasedInstId)
-- request erase node
if toErasedInstId and r2:getInstanceFromId(toErasedInstId) then
r2.requestEraseNode(toErasedInstId, "", -1)
end
end
------ UP ELEMENT INST -------------------------------------------
function r2.logicComponents:upElementInst(classUI)
r2.requestNewAction(i18n.get("uiR2EDMoveLogicElementUpAction"))
local sequenceUI = classUI:currentSequUI()
assert(sequenceUI)
local listElements = sequenceUI:find("elements_list")
assert(listElements)
local selectedElement = classUI:currentEltUI()
assert(selectedElement)
local index = listElements:getElementIndex(selectedElement)
if index>0 then
local sequenceId = classUI:currentSequInstId()
assert(sequenceId)
r2.requestMoveNode(sequenceId, "Components", index,
sequenceId, "Components", index-1)
end
end
------ DOWN ELEMENT INST -----------------------------------------
function r2.logicComponents:downElementInst(classUI)
r2.requestNewAction(i18n.get("uiR2EDMoveLogicElementDownAction"))
local sequenceUI = classUI:currentSequUI()
assert(sequenceUI)
local listElements = sequenceUI:find("elements_list")
assert(listElements)
local selectedElement = classUI:currentEltUI()
assert(selectedElement)
local index = listElements:getElementIndex(selectedElement)
local sequenceId = classUI:currentSequInstId()
assert(sequenceId)
if index < r2:getInstanceFromId(sequenceId).Components.Size-1 then
r2.requestMoveNode(sequenceId, "Components", index,
sequenceId, "Components", index+1)
end
end
---- TRANSLATE SECONDS IN HOURS, MINUTES AND ECONDS
function r2.logicComponents:calculHourMinSec(totalSecNb)
local minSecNb, hourNb = totalSecNb, 0
while minSecNb > 3599 do
hourNb = hourNb+1
minSecNb = minSecNb - 3600
end
local minNb, secNb = 0, minSecNb
while secNb > 59 do
minNb = minNb+1
secNb = secNb - 60
end
return hourNb, minNb, secNb
end
--- SEARCH INDEX OF INSTANCE IN COMPONENT TABLE
function r2.logicComponents:searchElementIndex(instance, fun)
local components = instance.Parent
local decalSequ = 0
for i=0, components.Size-1 do
local comp = components[i]
if fun and not fun(comp) then
decalSequ = decalSequ+1
elseif comp.User.Deleted == true then
decalSequ = decalSequ+1
end
if comp.InstanceId == instance.InstanceId then
return i+1-decalSequ
end
end
return -1
end
| agpl-3.0 |
iamliqiang/prosody-modules | mod_data_access/mod_data_access.lua | 32 | 4906 | -- HTTP Access to datamanager
-- By Kim Alvefur <zash@zash.se>
local t_concat = table.concat;
local t_insert = table.insert;
local jid_prep = require "util.jid".prep;
local jid_split = require "util.jid".split;
local test_password = require "core.usermanager".test_password;
local is_admin = require "core.usermanager".is_admin
local dm_load = require "util.datamanager".load;
local dm_store = require "util.datamanager".store;
local dm_list_load = require "util.datamanager".list_load;
local dm_list_store = require "util.datamanager".list_store;
local dm_list_append = require "util.datamanager".list_append;
local b64_decode = require "util.encodings".base64.decode;
local saslprep = require "util.encodings".stringprep.saslprep;
local realm = module:get_host() .. "/" .. module:get_name();
module:depends"http";
local encoders = {
lua = require "util.serialization".serialize,
json = require "util.json".encode
};
local decoders = {
lua = require "util.serialization".deserialize,
json = require "util.json".decode,
};
local content_type_map = {
["text/x-lua"] = "lua"; lua = "text/x-lua";
["application/json"] = "json"; json = "application/json";
}
local function require_valid_user(f)
return function(event, path)
local request = event.request;
local response = event.response;
local headers = request.headers;
if not headers.authorization then
response.headers.www_authenticate = ("Basic realm=%q"):format(realm);
return 401
end
local from_jid, password = b64_decode(headers.authorization:match"[^ ]*$"):match"([^:]*):(.*)";
from_jid = jid_prep(from_jid);
password = saslprep(password);
if from_jid and password then
local user, host = jid_split(from_jid);
local ok, err = test_password(user, host, password);
if ok and user and host then
return f(event, path, from_jid);
elseif err then
module:log("debug", "User failed authentication: %s", err);
end
end
return 401
end
end
local function handle_request(event, path, authed_user)
local request, response = event.request, event.response;
--module:log("debug", "spliting path");
local path_items = {};
for i in string.gmatch(path, "[^/]+") do
t_insert(path_items, i);
end
--module:log("debug", "split path, got %d parts: %s", #path_items, table.concat(path_items, ", "));
local user_node, user_host = jid_split(authed_user);
if #path_items < 3 then
--module:log("debug", "since we need at least 3 parts, adding %s/%s", user_host, user_node);
t_insert(path_items, 1, user_node);
t_insert(path_items, 1, user_host);
--return http_response(400, "Bad Request");
end
if #path_items < 3 then
return 404;
end
local p_host, p_user, p_store, p_type = unpack(path_items);
if not p_store or not p_store:match("^[%a_]+$") then
return 404;
end
if user_host ~= path_items[1] or user_node ~= path_items[2] then
-- To only give admins acces to anything, move the inside of this block after authz
--module:log("debug", "%s wants access to %s@%s[%s], is admin?", authed_user, p_user, p_host, p_store)
if not is_admin(authed_user, p_host) then
return 403;
end
end
local method = request.method;
if method == "GET" then
local data = dm_load(p_user, p_host, p_store);
data = data or dm_list_load(p_user, p_host, p_store);
--TODO Use the Accept header
local content_type = p_type or "json";
if data and encoders[content_type] then
response.headers.content_type = content_type_map[content_type].."; charset=utf-8";
return encoders[content_type](data);
else
return 404;
end
elseif method == "POST" or method == "PUT" then
local body = request.body;
if not body then
return 400;
end
local content_type, content = request.headers.content_type, body;
content_type = content_type and content_type_map[content_type]
--module:log("debug", "%s: %s", content_type, tostring(content));
content = content_type and decoders[content_type] and decoders[content_type](content);
--module:log("debug", "%s: %s", type(content), tostring(content));
if not content then
return 400;
end
local ok, err
if method == "PUT" then
ok, err = dm_store(p_user, p_host, p_store, content);
elseif method == "POST" then
ok, err = dm_list_append(p_user, p_host, p_store, content);
end
if ok then
response.headers.location = t_concat({module:http_url(nil,"/data"),p_host,p_user,p_store}, "/");
return 201;
else
response.headers.debug = err;
return 500;
end
elseif method == "DELETE" then
dm_store(p_user, p_host, p_store, nil);
dm_list_store(p_user, p_host, p_store, nil);
return 204;
end
end
local handle_request_with_auth = require_valid_user(handle_request);
module:provides("http", {
default_path = "/data";
route = {
["GET /*"] = handle_request_with_auth,
["PUT /*"] = handle_request_with_auth,
["POST /*"] = handle_request_with_auth,
["DELETE /*"] = handle_request_with_auth,
};
});
| mit |
ferstar/openwrt-dreambox | feeds/luci/luci/luci/applications/luci-pbx/luasrc/model/cbi/pbx-calls.lua | 3 | 14262 | --[[
Copyright 2011 Iordan Iordanov <iiordanov (AT) gmail.com>
This file is part of luci-pbx.
luci-pbx 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.
luci-pbx 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 luci-pbx. If not, see <http://www.gnu.org/licenses/>.
]]--
if nixio.fs.access("/etc/init.d/asterisk") then
server = "asterisk"
elseif nixio.fs.access("/etc/init.d/freeswitch") then
server = "freeswitch"
else
server = ""
end
modulename = "pbx-calls"
voipmodulename = "pbx-voip"
googlemodulename = "pbx-google"
usersmodulename = "pbx-users"
-- This function builds and returns a table with all the entries in a given "module" and "section".
function get_existing_entries(module, section)
i = 1
existing_entries = {}
m.uci:foreach(module, section,
function(s1)
existing_entries[i] = s1
i = i + 1
end)
return existing_entries
end
-- This function is used to build and return a table where the name field for
-- every element in a table entries are the indexes to the table (used to check
-- validity of user input.
function get_valid_names(entries)
validnames={}
for index,value in ipairs(entries) do
validnames[entries[index].name] = true
end
return validnames
end
-- This function is used to build and return a table where the defaultuser field for
-- every element in a table entries are the indexes to the table (used to check
-- validity of user input.
function get_valid_defaultusers(entries)
validnames={}
for index,value in ipairs(entries) do
validnames[entries[index].defaultuser] = true
end
return validnames
end
function is_valid_extension(exten)
return (exten:match("[#*+0-9NXZ]+$") ~= nil)
end
m = Map (modulename, translate("Call Routing"),
translate("This is where you indicate which Google/SIP accounts are used to call what \
country/area codes, which users can use which SIP/Google accounts, how incoming\
calls are routed, what numbers can get into this PBX with a password, and what\
numbers are blacklisted."))
-- Recreate the config, and restart services after changes are commited to the configuration.
function m.on_after_commit(self)
luci.sys.call("/etc/init.d/pbx-" .. server .. " restart 1\>/dev/null 2\>/dev/null")
luci.sys.call("/etc/init.d/" .. server .. " restart 1\>/dev/null 2\>/dev/null")
end
----------------------------------------------------------------------------------------------------
s = m:section(NamedSection, "outgoing_calls", "call_routing", translate("Outgoing Calls"),
translate("If you have more than one account which can make outgoing calls, you\
should enter a list of phone numbers and prefixes in the following fields for each\
provider listed. Invalid prefixes are removed silently, and only 0-9, X, Z, N, #, *,\
and + are valid characters. The letter X matches 0-9, Z matches 1-9, and N matches 2-9.\
For example to make calls to Germany through a provider, you can enter 49. To make calls\
to North America, you can enter 1NXXNXXXXXX. If one of your providers can make \"local\"\
calls to an area code like New York's 646, you can enter 646NXXXXXX for that\
provider. You should leave one account with an empty list to make calls with\
it by default, if no other provider's prefixes match. The system will automatically\
replace an empty list with a message that the provider dials all numbers. Be as specific as\
possible (i.e. 1NXXNXXXXXX is better than 1). Please note all international dial codes\
are discarded (e.g. 00, 011, 010, 0011). Entries can be made in a\
space-separated list, and/or one per line by hitting enter after every one."))
s.anonymous = true
m.uci:foreach(googlemodulename, "gtalk_jabber",
function(s1)
if s1.username ~= nil and s1.name ~= nil and
s1.make_outgoing_calls == "yes" then
patt = s:option(DynamicList, s1.name, s1.username)
-- If the saved field is empty, we return a string
-- telling the user that this account would dial any exten.
function patt.cfgvalue(self, section)
value = self.map:get(section, self.option)
if value == nil then
return {"Dials any number"}
else
return value
end
end
-- Write only valid extensions into the config file.
function patt.write(self, section, value)
newvalue = {}
nindex = 1
for index, field in ipairs(value) do
if is_valid_extension(value[index]) == true then
newvalue[nindex] = value[index]
nindex = nindex + 1
end
end
DynamicList.write(self, section, newvalue)
end
end
end)
m.uci:foreach(voipmodulename, "voip_provider",
function(s1)
if s1.defaultuser ~= nil and s1.host ~= nil and
s1.name ~= nil and s1.make_outgoing_calls == "yes" then
patt = s:option(DynamicList, s1.name, s1.defaultuser .. "@" .. s1.host)
-- If the saved field is empty, we return a string
-- telling the user that this account would dial any exten.
function patt.cfgvalue(self, section)
value = self.map:get(section, self.option)
if value == nil then
return {"Dials any number"}
else
return value
end
end
-- Write only valid extensions into the config file.
function patt.write(self, section, value)
newvalue = {}
nindex = 1
for index, field in ipairs(value) do
if is_valid_extension(value[index]) == true then
newvalue[nindex] = value[index]
nindex = nindex + 1
end
end
DynamicList.write(self, section, newvalue)
end
end
end)
----------------------------------------------------------------------------------------------------
s = m:section(NamedSection, "incoming_calls", "call_routing", translate("Incoming Calls"),
translate("For each provider that receives calls, here you can restrict which users to ring\
on incoming calls. If the list is empty, the system will indicate that all users\
which are enabled for incoming calls will ring. Invalid usernames will be rejected\
silently. Also, entering a username here overrides the user's setting to not receive\
incoming calls, so this way, you can make users ring only for select providers.\
Entries can be made in a space-separated list, and/or one per\
line by hitting enter after every one."))
s.anonymous = true
m.uci:foreach(googlemodulename, "gtalk_jabber",
function(s1)
if s1.username ~= nil and s1.register == "yes" then
field_name=string.gsub(s1.username, "%W", "_")
gtalkaccts = s:option(DynamicList, field_name, s1.username)
-- If the saved field is empty, we return a string
-- telling the user that this account would dial any exten.
function gtalkaccts.cfgvalue(self, section)
value = self.map:get(section, self.option)
if value == nil then
return {"Rings all users"}
else
return value
end
end
-- Write only valid user names.
function gtalkaccts.write(self, section, value)
users=get_valid_defaultusers(get_existing_entries(usersmodulename, "local_user"))
newvalue = {}
nindex = 1
for index, field in ipairs(value) do
if users[value[index]] == true then
newvalue[nindex] = value[index]
nindex = nindex + 1
end
end
DynamicList.write(self, section, newvalue)
end
end
end)
m.uci:foreach(voipmodulename, "voip_provider",
function(s1)
if s1.defaultuser ~= nil and s1.host ~= nil and s1.register == "yes" then
field_name=string.gsub(s1.defaultuser .. "_" .. s1.host, "%W", "_")
voipaccts = s:option(DynamicList, field_name, s1.defaultuser .. "@" .. s1.host)
-- If the saved field is empty, we return a string
-- telling the user that this account would dial any exten.
function voipaccts.cfgvalue(self, section)
value = self.map:get(section, self.option)
if value == nil then
return {"Rings all users"}
else
return value
end
end
-- Write only valid user names.
function voipaccts.write(self, section, value)
users=get_valid_defaultusers(get_existing_entries(usersmodulename, "local_user"))
newvalue = {}
nindex = 1
for index, field in ipairs(value) do
if users[value[index]] == true then
newvalue[nindex] = value[index]
nindex = nindex + 1
end
end
DynamicList.write(self, section, newvalue)
end
end
end)
----------------------------------------------------------------------------------------------------
s = m:section(NamedSection, "providers_user_can_use", "call_routing",
translate("Providers Used for Outgoing Calls"),
translate("If you would like, you could restrict which providers users are allowed to use for outgoing\
calls. By default all users can use all providers. To show up in the list below the user should\
be allowed to make outgoing calls in the \"User Accounts\" page. Enter VoIP providers in the format\
username@some.host.name, as listed in \"Outgoing Calls\" above. It's easiest to copy and paste\
the providers from above. Invalid entries will be rejected silently. Also, any entries automatically\
change to this PBX's internal naming scheme, with \"_\" replacing all non-alphanumeric characters.\
Entries can be made in a space-separated list, and/or one per line by hitting enter after every\
one."))
s.anonymous = true
m.uci:foreach(usersmodulename, "local_user",
function(s1)
if s1.defaultuser ~= nil and s1.can_call == "yes" then
providers = s:option(DynamicList, s1.defaultuser, s1.defaultuser)
-- If the saved field is empty, we return a string
-- telling the user that this account would dial any exten.
function providers.cfgvalue(self, section)
value = self.map:get(section, self.option)
if value == nil then
return {"Uses all provider accounts"}
else
return value
end
end
-- Cook the new values prior to entering them into the config file.
-- Also, enter them only if they are valid.
function providers.write(self, section, value)
validvoip=get_valid_names(get_existing_entries(voipmodulename, "voip_provider"))
validgoog=get_valid_names(get_existing_entries(googlemodulename, "gtalk_jabber"))
cookedvalue = {}
cindex = 1
for index, field in ipairs(value) do
cooked = string.gsub(value[index], "%W", "_")
if validvoip[cooked] == true or validgoog[cooked] == true then
cookedvalue[cindex] = string.gsub(value[index], "%W", "_")
cindex = cindex + 1
end
end
DynamicList.write(self, section, cookedvalue)
end
end
end)
----------------------------------------------------------------------------------------------------
s = m:section(TypedSection, "callthrough_numbers", translate("Call-through Numbers"),
translate("Designate numbers which will be allowed to call through this system and which user's\
privileges it will have."))
s.anonymous = true
s.addremove = true
num = s:option(DynamicList, "callthrough_number_list", translate("Call-through Numbers"))
num.datatype = "uinteger"
p = s:option(ListValue, "enabled", translate("Enabled"))
p:value("yes", translate("Yes"))
p:value("no", translate("No"))
p.default = "yes"
user = s:option(Value, "defaultuser", translate("User Name"),
translate("The number(s) specified above will be able to dial outwith this user's providers.\
Invalid usernames are dropped silently, please verify that the entry was accepted."))
function user.write(self, section, value)
users=get_valid_defaultusers(get_existing_entries(usersmodulename, "local_user"))
if users[value] == true then
Value.write(self, section, value)
end
end
pwd = s:option(Value, "pin", translate("PIN"),
translate("Your PIN disappears when saved for your protection. It will be changed\
only when you enter a value different from the saved one. Leaving the PIN\
empty is possible, but please beware of the security implications."))
pwd.password = true
pwd.rmempty = false
-- We skip reading off the saved value and return nothing.
function pwd.cfgvalue(self, section)
return ""
end
-- We check the entered value against the saved one, and only write if the entered value is
-- something other than the empty string, and it differes from the saved value.
function pwd.write(self, section, value)
local orig_pwd = m:get(section, self.option)
if value and #value > 0 and orig_pwd ~= value then
Value.write(self, section, value)
end
end
----------------------------------------------------------------------------------------------------
s = m:section(NamedSection, "blacklisting", "call_routing", translate("Blacklisted Numbers"),
translate("Enter phone numbers that you want to decline calls from automatically.\
You should probably omit the country code and any leading\
zeroes, but please experiment to make sure you are blocking numbers from your\
desired area successfully."))
s.anonymous = true
b = s:option(DynamicList, "blacklist1", translate("Dynamic List of Blacklisted Numbers"),
translate("Specify numbers individually here. Press enter to add more numbers."))
b.cast = "string"
b.datatype = "uinteger"
b = s:option(Value, "blacklist2", translate("Space-Separated List of Blacklisted Numbers"),
translate("Copy-paste large lists of numbers here."))
b.template = "cbi/tvalue"
b.rows = 3
return m
| gpl-2.0 |
m-creations/openwrt | feeds/luci/applications/luci-app-ddns/luasrc/model/cbi/ddns/hints.lua | 34 | 6352 | -- Copyright 2014 Christian Schoenebeck <christian dot schoenebeck at gmail dot com>
-- Licensed to the public under the Apache License 2.0.
local CTRL = require "luci.controller.ddns" -- this application's controller
local DISP = require "luci.dispatcher"
local SYS = require "luci.sys"
local DDNS = require "luci.tools.ddns" -- ddns multiused functions
-- check supported options -- ##################################################
-- saved to local vars here because doing multiple os calls slow down the system
has_ssl = DDNS.check_ssl() -- HTTPS support and --bind-network / --interface
has_proxy = DDNS.check_proxy() -- Proxy support
has_dnstcp = DDNS.check_bind_host() -- DNS TCP support
-- correct ddns-scripts version
need_update = DDNS.ipkg_ver_compare(DDNS.ipkg_ver_installed("ddns-scripts"), "<<", CTRL.DDNS_MIN)
-- html constants
font_red = [[<font color="red">]]
font_off = [[</font>]]
bold_on = [[<strong>]]
bold_off = [[</strong>]]
-- cbi-map definition -- #######################################################
m = Map("ddns")
-- first need to close <a> from cbi map template our <a> closed by template
m.title = [[</a><a href="]] .. DISP.build_url("admin", "services", "ddns") .. [[">]] ..
translate("Dynamic DNS")
m.description = translate("Dynamic DNS allows that your router can be reached with " ..
"a fixed hostname while having a dynamically changing " ..
"IP address.")
m.redirect = DISP.build_url("admin", "services", "ddns")
-- SimpleSection definition -- #################################################
-- show Hints to optimize installation and script usage
s = m:section( SimpleSection,
translate("Hints"),
translate("Below a list of configuration tips for your system to run Dynamic DNS updates without limitations") )
-- ddns_scripts needs to be updated for full functionality
if need_update then
local dv = s:option(DummyValue, "_update_needed")
dv.titleref = DISP.build_url("admin", "system", "packages")
dv.rawhtml = true
dv.title = font_red .. bold_on ..
translate("Software update required") .. bold_off .. font_off
dv.value = translate("The currently installed 'ddns-scripts' package did not support all available settings.") ..
"<br />" ..
translate("Please update to the current version!")
end
-- DDNS Service disabled
if not SYS.init.enabled("ddns") then
local dv = s:option(DummyValue, "_not_enabled")
dv.titleref = DISP.build_url("admin", "system", "startup")
dv.rawhtml = true
dv.title = bold_on ..
translate("DDNS Autostart disabled") .. bold_off
dv.value = translate("Currently DDNS updates are not started at boot or on interface events." .. "<br />" ..
"This is the default if you run DDNS scripts by yourself (i.e. via cron with force_interval set to '0')" )
end
-- No IPv6 support
if not DDNS.check_ipv6() then
local dv = s:option(DummyValue, "_no_ipv6")
dv.titleref = 'http://www.openwrt.org" target="_blank'
dv.rawhtml = true
dv.title = bold_on ..
translate("IPv6 not supported") .. bold_off
dv.value = translate("IPv6 is currently not (fully) supported by this system" .. "<br />" ..
"Please follow the instructions on OpenWrt's homepage to enable IPv6 support" .. "<br />" ..
"or update your system to the latest OpenWrt Release")
end
-- No HTTPS support
if not has_ssl then
local dv = s:option(DummyValue, "_no_https")
dv.titleref = DISP.build_url("admin", "system", "packages")
dv.rawhtml = true
dv.title = bold_on ..
translate("HTTPS not supported") .. bold_off
dv.value = translate("Neither GNU Wget with SSL nor cURL installed to support updates via HTTPS protocol.") ..
"<br />- " ..
translate("You should install GNU Wget with SSL (prefered) or cURL package.") ..
"<br />- " ..
translate("In some versions cURL/libcurl in OpenWrt is compiled without proxy support.")
end
-- No bind_network
if not has_ssl then
local dv = s:option(DummyValue, "_no_bind_network")
dv.titleref = DISP.build_url("admin", "system", "packages")
dv.rawhtml = true
dv.title = bold_on ..
translate("Binding to a specific network not supported") .. bold_off
dv.value = translate("Neither GNU Wget with SSL nor cURL installed to select a network to use for communication.") ..
"<br />- " ..
translate("You should install GNU Wget with SSL or cURL package.") ..
"<br />- " ..
translate("GNU Wget will use the IP of given network, cURL will use the physical interface.") ..
"<br />- " ..
translate("In some versions cURL/libcurl in OpenWrt is compiled without proxy support.")
end
-- cURL without proxy support
if has_ssl and not has_proxy then
local dv = s:option(DummyValue, "_no_proxy")
dv.titleref = DISP.build_url("admin", "system", "packages")
dv.rawhtml = true
dv.title = bold_on ..
translate("cURL without Proxy Support") .. bold_off
dv.value = translate("cURL is installed, but libcurl was compiled without proxy support.") ..
"<br />- " ..
translate("You should install GNU Wget with SSL or replace libcurl.") ..
"<br />- " ..
translate("In some versions cURL/libcurl in OpenWrt is compiled without proxy support.")
end
-- "Force IP Version not supported"
if not (has_ssl and has_dnstcp) then
local dv = s:option(DummyValue, "_no_force_ip")
dv.titleref = DISP.build_url("admin", "system", "packages")
dv.rawhtml = true
dv.title = bold_on ..
translate("Force IP Version not supported") .. bold_off
local value = translate("BusyBox's nslookup and Wget do not support to specify " ..
"the IP version to use for communication with DDNS Provider.")
if not has_ssl then
value = value .. "<br />- " ..
translate("You should install GNU Wget with SSL (prefered) or cURL package.")
end
if not has_dnstcp then
value = value .. "<br />- " ..
translate("You should install BIND host package for DNS requests.")
end
dv.value = value
end
-- "DNS requests via TCP not supported"
if not has_dnstcp then
local dv = s:option(DummyValue, "_no_dnstcp")
dv.titleref = DISP.build_url("admin", "system", "packages")
dv.rawhtml = true
dv.title = bold_on ..
translate("DNS requests via TCP not supported") .. bold_off
dv.value = translate("BusyBox's nslookup does not support to specify to use TCP instead of default UDP when requesting DNS server") ..
"<br />- " ..
translate("You should install BIND host package for DNS requests.")
end
return m
| gpl-2.0 |
paulmarsy/Console | Libraries/nmap/App/nselib/informix.lua | 2 | 40718 | ---
-- Informix Library supporting a very limited subset of Informix operations
--
-- Summary
-- -------
-- Informix supports both The Open Group Distributed Relational Database
-- Architecture (DRDA) protocol, and their own. This library attempts to
-- implement a basic subset of operations. It currently supports;
-- o Authentication using plain-text usernames and passwords
-- o Simple SELECT, INSERT and UPDATE queries, possible more ...
--
-- Overview
-- --------
-- The library contains the following classes:
--
-- o Packet.*
-- - The Packet classes contain specific packets and function to serialize
-- them to strings that can be sent over the wire. Each class may also
-- contain a function to parse the servers response.
--
-- o ColMetaData
-- - A class holding the meta data for each column
--
-- o Comm
-- - Implements a number of functions to handle communication over the
-- the socket.
--
-- o Helper
-- - A helper class that provides easy access to the rest of the library
--
-- In addition the library contains the following tables with decoder functions
--
-- o MetaDataDecoders
-- - Contains functions to decode the column metadata per data type
--
-- o DataTypeDecoders
-- - Contains function to decode each data-type in the query resultset
--
-- o MessageDecoders
-- - Contains a decoder for each supported protocol message
--
-- Example
-- -------
-- The following sample code illustrates how scripts can use the Helper class
-- to interface the library:
--
-- <code>
-- helper = informix.Helper:new( host, port, "on_demo" )
-- status, err = helper:Connect()
-- status, res = helper:Login("informix", "informix")
-- status, err = helper:Close()
-- </code>
--
-- Additional information
-- ----------------------
-- The implementation is based on analysis of packet dumps and has been tested
-- against:
--
-- x IBM Informix Dynamic Server Express Edition v11.50 32-bit on Ubuntu
-- x IBM Informix Dynamic Server xxx 32-bit on Windows 2003
--
-- @copyright Same as Nmap--See http://nmap.org/book/man-legal.html
-- @author "Patrik Karlsson <patrik@cqure.net>"
--
-- @args informix.instance specifies the Informix instance to connect to
--
-- Version 0.1
-- Created 07/23/2010 - v0.1 - created by Patrik Karlsson <patrik@cqure.net>
-- Revised 07/28/2010 - v0.2 - added support for SELECT, INSERT and UPDATE
-- queries
--
local bin = require "bin"
local nmap = require "nmap"
local match = require "match"
local stdnse = require "stdnse"
local table = require "table"
_ENV = stdnse.module("informix", stdnse.seeall)
-- A bunch of constants
Constants =
{
-- A subset of supported messages
Message = {
SQ_COMMAND = 0x01,
SQ_PREPARE = 0x02,
SQ_ID = 0x04,
SQ_DESCRIBE = 0x08,
SQ_EOT = 0x0c,
SQ_ERR = 0x0d,
SQ_TUPLE = 0x0e,
SQ_DONE = 0x0f,
SQ_DBLIST = 0x1a,
SQ_DBOPEN = 0x24,
SQ_EXIT = 0x38,
SQ_INFO = 0x51,
SQ_PROTOCOLS = 0x7e,
},
-- A subset of supported data types
DataType = {
CHAR = 0x00,
SMALLINT = 0x01,
INT = 0x02,
FLOAT = 0x03,
SERIAL = 0x06,
DATE = 0x07,
DATETIME = 0x0a,
VARCHAR = 0x0d,
},
-- These were the ones I ran into when developing :-)
ErrorMsg = {
[-201] = "A syntax error has occurred.",
[-206] = "The specified table is not in the database.",
[-208] = "Memory allocation failed during query processing.",
[-258] = "System error - invalid statement id received by the sqlexec process.",
[-217] = "Column (%s) not found in any table in the query (or SLV is undefined).",
[-310] = "Table (%s) already exists in database.",
[-363] = "CURSOR not on SELECT statement.",
[-555] = "Cannot use a select or any of the database statements in a multi-query prepare.",
[-664] = "Wrong number of arguments to system function(%s).",
[-761] = "INFORMIXSERVER does not match either DBSERVERNAME or DBSERVERALIASES.",
[-951] = "Incorrect password or user is not known on the database server.",
[-329] = "Database not found or no system permission.",
[-9628] = "Type (%s) not found.",
[-23101] = "Unable to load locale categories.",
}
}
-- The ColMetaData class
ColMetaData = {
---Creates a new ColMetaData instance
--
-- @return object a new instance of ColMetaData
new = function(self)
local o = {}
setmetatable(o, self)
self.__index = self
return o
end,
--- Sets the datatype
--
-- @param typ number containing the datatype
setType = function( self, typ ) self.type = typ end,
--- Sets the name
--
-- @param name string containing the name
setName = function( self, name) self.name = name end,
--- Sets the length
--
-- @param len number containing the length of the column
setLength = function( self, len ) self.len = len end,
--- Gets the column type
--
-- @return typ the column type
getType = function( self ) return self.type end,
--- Gets the column name
--
-- @return name the column name
getName = function( self ) return self.name end,
--- Gets the column length
--
-- @return len the column length
getLength = function( self ) return self.len end,
}
Packet = {}
-- MetaData decoders used to decode the information for each data type in the
-- meta data returned by the server
--
-- The decoders, should be self explanatory
MetaDataDecoders = {
[Constants.DataType.INT] = function( data )
local col_md = ColMetaData:new( )
local pos = 19
if ( #data < pos ) then return false, "Failed to decode meta data for data type INT" end
local _, len = bin.unpack(">S", data, pos)
col_md:setLength(len)
col_md:setType( Constants.DataType.INT )
return true, col_md
end,
[Constants.DataType.CHAR] = function( data )
local status, col_md = MetaDataDecoders[Constants.DataType.INT]( data )
if( not(status) ) then
return false, "Failed to decode metadata for data type CHAR"
end
col_md:setType( Constants.DataType.CHAR )
return true, col_md
end,
[Constants.DataType.VARCHAR] = function( data )
local status, col_md = MetaDataDecoders[Constants.DataType.INT]( data )
if( not(status) ) then return false, "Failed to decode metadata for data type CHAR" end
col_md:setType( Constants.DataType.VARCHAR )
return true, col_md
end,
[Constants.DataType.SMALLINT] = function( data )
local status, col_md = MetaDataDecoders[Constants.DataType.INT]( data )
if( not(status) ) then return false, "Failed to decode metadata for data type SMALLINT" end
col_md:setType( Constants.DataType.SMALLINT )
return true, col_md
end,
[Constants.DataType.SERIAL] = function( data )
local status, col_md = MetaDataDecoders[Constants.DataType.INT]( data )
if( not(status) ) then return false, "Failed to decode metadata for data type SMALLINT" end
col_md:setType( Constants.DataType.SERIAL )
return true, col_md
end,
[Constants.DataType.DATETIME] = function( data )
local status, col_md = MetaDataDecoders[Constants.DataType.INT]( data )
if( not(status) ) then return false, "Failed to decode metadata for data type DATETIME" end
col_md:setType( Constants.DataType.DATETIME )
col_md:setLength(10)
return true, col_md
end,
[Constants.DataType.FLOAT] = function( data )
local status, col_md = MetaDataDecoders[Constants.DataType.INT]( data )
if( not(status) ) then return false, "Failed to decode metadata for data type DATETIME" end
col_md:setType( Constants.DataType.FLOAT )
return true, col_md
end,
[Constants.DataType.DATE] = function( data )
local status, col_md = MetaDataDecoders[Constants.DataType.INT]( data )
if( not(status) ) then return false, "Failed to decode metadata for data type DATETIME" end
col_md:setType( Constants.DataType.DATE )
return true, col_md
end,
}
-- DataType decoders used to decode result set returned from the server
-- This class is still incomplete and some decoders just adjust the offset
-- position rather than decode the value.
--
-- The decoders, should be self explanatory
DataTypeDecoders = {
[Constants.DataType.INT] = function( data, pos )
return bin.unpack(">i", data, pos)
end,
[Constants.DataType.FLOAT] = function( data, pos )
return bin.unpack(">d", data, pos)
end,
[Constants.DataType.DATE] = function( data, pos )
return pos + 4, "DATE"
end,
[Constants.DataType.SERIAL] = function( data, pos )
return bin.unpack(">I", data, pos)
end,
[Constants.DataType.SMALLINT] = function( data, pos )
return bin.unpack(">s", data, pos)
end,
[Constants.DataType.CHAR] = function( data, pos, len )
local pos, ret = bin.unpack("A" .. len, data, pos)
return pos, Util.ifxToLuaString( ret )
end,
[Constants.DataType.VARCHAR] = function( data, pos, len )
local pos, len = bin.unpack("C", data, pos)
local ret
pos, ret = bin.unpack("A" .. len, data, pos)
return pos, Util.ifxToLuaString( ret )
end,
[Constants.DataType.DATETIME] = function( data, pos )
return pos + 10, "DATETIME"
end,
}
-- The MessageDecoders class "holding" the Response Decoders
MessageDecoders = {
--- Decodes the SQ_ERR error message
--
-- @param socket already connected to the Informix database server
-- @return status true on success, false on failure
-- @return errmsg, Informix error message or decoding error message if
-- status is false
[Constants.Message.SQ_ERR] = function( socket )
local status, data = socket:receive_buf(match.numbytes(8), true)
local _, svcerr, oserr, errmsg, str, len, pos
if( not(status) ) then return false, "Failed to decode error response" end
pos, svcerr, oserr, _, len = bin.unpack(">ssss", data )
if( len and len > 0 ) then
status, data = socket:receive_buf(match.numbytes(len), true)
if( not(status) ) then return false, "Failed to decode error response" end
_, str = bin.unpack("A" .. len, data)
end
status, data = socket:receive_buf(match.numbytes(2), true)
errmsg = Constants.ErrorMsg[svcerr]
if ( errmsg and str ) then
errmsg = errmsg:format(str)
end
return false, errmsg or ("Informix returned an error (svcerror: %d, oserror: %d)"):format( svcerr, oserr )
end,
--- Decodes the SQ_PROTOCOLS message
--
-- @param socket already connected to the Informix database server
-- @return status true on success, false on failure
-- @return err error message if status is false
[Constants.Message.SQ_PROTOCOLS] = function( socket )
local status, data
local len, _
status, data = socket:receive_buf(match.numbytes(2), true)
if( not(status) ) then return false, "Failed to decode SQ_PROTOCOLS response" end
_, len = bin.unpack(">S", data )
-- read the remaining data
return socket:receive_buf(match.numbytes(len + 2), true)
end,
--- Decodes the SQ_EOT message
--
-- @return status, always true
[Constants.Message.SQ_EOT] = function( socket )
return true
end,
--- Decodes the SQ_DONE message
--
-- @param socket already connected to the Informix database server
-- @return status true on success, false on failure
-- @return err error message if status is false
[Constants.Message.SQ_DONE] = function( socket )
local status, data = socket:receive_buf(match.numbytes(2), true)
local _, len, tmp
if( not(status) ) then return false, "Failed to decode SQ_DONE response" end
_, len = bin.unpack(">S", data )
-- For some *@#! reason the SQ_DONE packet sometimes contains an
-- length exceeding the length of the packet by one. Attempt to
-- detect this and fix.
status, data = socket:receive_buf(match.numbytes(len), true)
_, tmp = bin.unpack(">S", data, len - 2)
return socket:receive_buf(match.numbytes((tmp == 0) and 3 or 4), true)
end,
--- Decodes the metadata for a result set
--
-- @param socket already connected to the Informix database server
-- @return status true on success, false on failure
-- @return column_meta table containing the metadata
[Constants.Message.SQ_DESCRIBE] = function( socket )
local status, data = socket:receive_buf(match.numbytes(14), true)
local pos, cols, col_type, col_name, col_len, col_md, stmt_id
local coldesc_len, x
local column_meta = {}
if( not(status) ) then return false, "Failed to decode SQ_DESCRIBE response" end
pos, cols, coldesc_len = bin.unpack(">SS", data, 11)
pos, stmt_id = bin.unpack(">S", data, 3)
if ( cols <= 0 ) then
-- We can end up here if we executed a CREATE, UPDATE OR INSERT statement
local tmp
status, data = socket:receive_buf(match.numbytes(2), true)
if( not(status) ) then return false, "Failed to decode SQ_DESCRIBE response" end
pos, tmp = bin.unpack(">S", data)
-- This was the result of a CREATE or UPDATE statement
if ( tmp == 0x0f ) then
status, data = socket:receive_buf(match.numbytes(26), true)
-- This was the result of a INSERT statement
elseif( tmp == 0x5e ) then
status, data = socket:receive_buf(match.numbytes(46), true)
end
return true
end
status, data = socket:receive_buf(match.numbytes(6), true)
if( not(status) ) then return false, "Failed to decode SQ_DESCRIBE response" end
for i=1, cols do
status, data = socket:receive_buf(match.numbytes(2), true)
if( not(status) ) then return false, "Failed to decode SQ_DESCRIBE response" end
pos, col_type = bin.unpack("C", data, 2)
if ( MetaDataDecoders[col_type] ) then
status, data = socket:receive_buf(match.numbytes(20), true)
if( not(status) ) then
return false, "Failed to read column meta data"
end
status, col_md = MetaDataDecoders[col_type]( data )
if ( not(status) ) then
return false, col_md
end
else
return false, ("No metadata decoder for column type: %d"):format(col_type)
end
if ( i<cols ) then
status, data = socket:receive_buf(match.numbytes(6), true)
if( not(status) ) then return false, "Failed to decode SQ_DESCRIBE response" end
end
col_md:setType( col_type )
table.insert( column_meta, col_md )
end
status, data = socket:receive_buf(match.numbytes(( coldesc_len % 2 ) == 0 and coldesc_len or coldesc_len + 1), true)
if( not(status) ) then return false, "Failed to decode SQ_DESCRIBE response" end
pos = 1
for i=1, cols do
local col_name
pos, col_name = bin.unpack("z", data, pos)
column_meta[i]:setName( col_name )
end
status, data = socket:receive_buf(match.numbytes(2), true)
if( not(status) ) then return false, "Failed to decode SQ_DESCRIBE response" end
pos, data = bin.unpack(">S", data)
if( data == Constants.Message.SQ_DONE ) then
status, data = socket:receive_buf(match.numbytes(26), true)
else
status, data = socket:receive_buf(match.numbytes(10), true)
end
return true, { metadata = column_meta, stmt_id = stmt_id }
end,
--- Processes the result from a query
--
-- @param socket already connected to the Informix database server
-- @param info table containing the following fields:
-- <code>metadata</code> as received from <code>SQ_DESCRIBE</code>
-- <code>rows</code> containing already retrieved rows
-- <code>id</code> containing the statement id as sent to SQ_ID
-- @return status true on success, false on failure
-- @return rows table containing the resulting columns and rows as:
-- { { col, col2, col3 } }
-- or error message if status is false
[Constants.Message.SQ_TUPLE] = function( socket, info )
local status, data
local row = {}
local count = 1
if ( not( info.rows ) ) then info.rows = {} end
while (true) do
local pos = 1
status, data = socket:receive_buf(match.numbytes(6), true)
if( not(status) ) then return false, "Failed to read column data" end
local _, total_len = bin.unpack(">I", data, 3)
status, data = socket:receive_buf(match.numbytes(( total_len % 2 == 0 ) and total_len or total_len + 1), true)
if( not(status) ) then return false, "Failed to read column data" end
row = {}
for _, col in ipairs(info.metadata) do
local typ, len, name = col:getType(), col:getLength(), col:getName()
local val
if( DataTypeDecoders[typ] ) then
pos, val = DataTypeDecoders[typ]( data, pos, len )
else
return false, ("No data type decoder for type: 0x%d"):format(typ)
end
table.insert( row, val )
end
status, data = socket:receive_buf(match.numbytes(2), true)
local _, flags = bin.unpack(">S", data)
count = count + 1
table.insert( info.rows, row )
-- Check if we're done
if ( Constants.Message.SQ_DONE == flags ) then
break
end
-- If there's more data we need to send a new SQ_ID packet
if ( flags == Constants.Message.SQ_EOT ) then
local status, tmp = socket:send( tostring(Packet.SQ_ID:new( info.id, nil, "continue" ) ) )
local pkt_type
status, tmp = socket:receive_buf(match.numbytes(2), true)
pos, pkt_type = bin.unpack(">S", tmp)
return MessageDecoders[pkt_type]( socket, info )
end
end
-- read the remaining data
status, data = socket:receive_buf(match.numbytes(26), true)
if( not(status) ) then return false, "Failed to read column data" end
-- signal finish reading
status, data = socket:send( tostring(Packet.SQ_ID:new( info.id, nil, "end" ) ) )
status, data = socket:receive_buf(match.numbytes(2), true)
return true, info
end,
--- Decodes a SQ_DBLIST response
--
-- @param socket already connected to the Informix database server
-- @return status true on success, false on failure
-- @return databases array of database names
[Constants.Message.SQ_DBLIST] = function( socket )
local status, data, pos, len, db
local databases = {}
while( true ) do
status, data = socket:receive_buf(match.numbytes(2), true)
if ( not(status) ) then return false, "Failed to parse SQ_DBLIST response" end
pos, len = bin.unpack(">S", data)
if ( 0 == len ) then break end
status, data = socket:receive_buf(match.numbytes(len), true)
if ( not(status) ) then return false, "Failed to parse SQ_DBLIST response" end
pos, db = bin.unpack("A" .. len, data )
table.insert( databases, db )
if ( len %2 == 1 ) then
socket:receive_buf(match.numbytes(1), true)
if ( not(status) ) then return false, "Failed to parse SQ_DBLIST response" end
end
end
-- read SQ_EOT
status, data = socket:receive_buf(match.numbytes(2), true)
return true, databases
end,
[Constants.Message.SQ_EXIT] = function( socket )
local status, data = socket:receive_buf(match.numbytes(2), true)
if ( not(status) ) then return false, "Failed to parse SQ_EXIT response" end
return true
end
}
-- Packet used to request a list of available databases
Packet.SQ_DBLIST =
{
--- Creates a new Packet.SQ_DBLIST instance
--
-- @return object new instance of Packet.SQ_DBLIST
new = function( self )
local o = {}
setmetatable(o, self)
self.__index = self
return o
end,
--- Converts the class to a string suitable to send over the socket
--
-- @return string containing the packet data
__tostring = function(self)
return bin.pack(">SS", Constants.Message.SQ_DBLIST, Constants.Message.SQ_EOT)
end
}
-- Packet used to open the database
Packet.SQ_DBOPEN =
{
--- Creates a new Packet.SQ_DBOPEN instance
--
-- @param database string containing the name of the database to open
-- @return object new instance of Packet.SQ_DBOPEN
new = function( self, database )
local o = {}
setmetatable(o, self)
self.__index = self
o.database = database
return o
end,
--- Converts the class to a string suitable to send over the socket
--
-- @return string containing the packet data
__tostring = function(self)
return bin.pack(">SSASS", Constants.Message.SQ_DBOPEN, #self.database,
Util.padToOdd(self.database), 0x00,
Constants.Message.SQ_EOT)
end
}
-- This packet is "a mess" and requires further analysis
Packet.SQ_ID =
{
--- Creates a new Packet.SQ_ID instance
--
-- @param id number containing the statement identifier
-- @param s1 number unknown, should be 0 on first call and 1 when more data is requested
-- @return object new instance of Packet.SQ_ID
new = function( self, id, id2, mode )
local o = {}
setmetatable(o, self)
self.__index = self
o.id = ("_ifxc%.13d"):format( id2 or 0 )
o.seq = id
o.mode = mode
return o
end,
--- Converts the class to a string suitable to send over the socket
--
-- @return string containing the packet data
__tostring = function(self)
if ( self.mode == "continue" ) then
return bin.pack( ">SSSSSS", Constants.Message.SQ_ID, self.seq, 0x0009, 0x1000, 0x0000, Constants.Message.SQ_EOT )
elseif ( self.mode == "end" ) then
return bin.pack( ">SSSS", Constants.Message.SQ_ID, self.seq, 0x000a, Constants.Message.SQ_EOT)
else
return bin.pack(">SSSSASSSSSSS", Constants.Message.SQ_ID, self.seq, 0x0003, #self.id, self.id,
0x0006, 0x0004, self.seq, 0x0009, 0x1000, 0x0000, Constants.Message.SQ_EOT )
end
end
}
Packet.SQ_INFO =
{
-- The default parameters
DEFAULT_PARAMETERS = {
[1] = { ["DBTEMP"] = "/tmp" },
[2] = { ["SUBQCACHESZ"] = "10" },
},
--- Creates a new Packet.SQ_INFO instance
--
-- @param params containing any additional parameters to use
-- @return object new instance of Packet.SQ_INFO
new = function( self, params )
local o = {}
local params = params or Packet.SQ_INFO.DEFAULT_PARAMETERS
setmetatable(o, self)
self.__index = self
o.parameters = {}
for _, v in ipairs( params ) do
for k2, v2 in pairs(v) do
o:addParameter( k2, v2 )
end
end
return o
end,
addParameter = function( self, key, value )
table.insert( self.parameters, { [key] = value } )
end,
paramToString = function( self, key, value )
return bin.pack(">SASA", #key, Util.padToOdd(key), #value, Util.padToOdd( value ) )
end,
--- Converts the class to a string suitable to send over the socket
--
-- @return string containing the packet data
__tostring = function( self )
local params = ""
local data
for _, v in ipairs( self.parameters ) do
for k2, v2 in pairs( v ) do
params = params .. self:paramToString( k2, v2 )
end
end
data = bin.pack(">SSSSSASSS", Constants.Message.SQ_INFO, 0x0006,
#params + 6, 0x000c, 0x0004, params, 0x0000, 0x0000,
Constants.Message.SQ_EOT)
return data
end
}
-- Performs protocol negotiation?
Packet.SQ_PROTOCOLS =
{
-- hex-encoded data to send as protocol negotiation
data = "0007fffc7ffc3c8c8a00000c",
--- Creates a new Packet.SQ_PROTOCOLS instance
--
-- @return object new instance of Packet.SQ_PROTOCOLS
new = function( self )
local o = {}
setmetatable(o, self)
self.__index = self
return o
end,
--- Converts the class to a string suitable to send over the socket
--
-- @return string containing the packet data
__tostring = function(self)
return bin.pack(">SH", Constants.Message.SQ_PROTOCOLS, self.data)
end
}
-- Packet used to execute SELECT Queries
Packet.SQ_PREPARE =
{
--- Creates a new Packet.SQ_PREPARE instance
--
-- @param query string containing the query to execute
-- @return object new instance of Packet.SQ_PREPARE
new = function( self, query )
local o = {}
setmetatable(o, self)
self.__index = self
o.query = Util.padToEven(query)
return o
end,
--- Converts the class to a string suitable to send over the socket
--
-- @return string containing the packet data
__tostring = function(self)
return bin.pack(">SIACSSS", Constants.Message.SQ_PREPARE, #self.query, self.query, 0, 0x0016, 0x0031, Constants.Message.SQ_EOT)
end
}
-- Packet used to execute commands other than SELECT
Packet.SQ_COMMAND =
{
--- Creates a new Packet.SQ_COMMAND instance
--
-- @param query string containing the query to execute
-- @return object new instance of Packet.SQ_COMMAND
new = function( self, query )
local o = {}
setmetatable(o, self)
self.__index = self
o.query = Util.padToEven(query)
return o
end,
--- Converts the class to a string suitable to send over the socket
--
-- @return string containing the packet data
__tostring = function(self)
return bin.pack(">SIACSSSS", Constants.Message.SQ_COMMAND, #self.query, self.query, 0, 0x0016, 0x0007, 0x000b, Constants.Message.SQ_EOT)
end
}
Packet.SQ_EXIT = {
--- Creates a new Packet.SQ_EXIT instance
--
-- @return object new instance of Packet.SQ_EXIT
new = function( self )
local o = {}
setmetatable(o, self)
self.__index = self
return o
end,
--- Converts the class to a string suitable to send over the socket
--
-- @return string containing the packet data
__tostring = function(self)
return bin.pack(">S", Constants.Message.SQ_EXIT)
end
}
-- The Utility Class
Util =
{
--- Converts a connection parameter to string
--
-- @param param string containing the parameter name
-- @param value string containing the parameter value
-- @return string containing the encoded parameter as string
paramToString = function( param, value )
return bin.pack(">PP", param, value )
end,
--- Pads a string to an even number of characters
--
-- @param str the string to pad
-- @param pad the character to pad with
-- @return result the padded string
padToEven = function( str, pad )
return (#str % 2 == 1) and str or str .. ( pad and pad or "\0")
end,
--- Pads a string to an odd number of characters
--
-- @param str the string to pad
-- @param pad the character to pad with
-- @return result the padded string
padToOdd = function( str, pad )
return (#str % 2 == 0) and str or str .. ( pad and pad or "\0")
end,
--- Formats a table to suitable script output
--
-- @param info as returned from ExecutePrepare
-- @return table suitable for use by <code>stdnse.format_output</code>
formatTable = function( info )
local header, row = "", ""
local result = {}
local metadata = info.metadata
local rows = info.rows
if ( info.error ) then
table.insert(result, info.error)
return result
end
if ( info.info ) then
table.insert(result, info.info)
return result
end
if ( not(metadata) ) then return "" end
for i=1, #metadata do
if ( metadata[i]:getType() == Constants.DataType.CHAR and metadata[i]:getLength() < 50) then
header = header .. ("%-" .. metadata[i]:getLength() .. "s "):format(metadata[i]:getName())
else
header = header .. metadata[i]:getName()
if ( i<#metadata ) then
header = header .. "\t"
end
end
end
table.insert( result, header )
for j=1, #rows do
row = ""
for i=1, #metadata do
row = row .. rows[j][i] .. " "
if ( metadata[i]:getType() ~= Constants.DataType.CHAR and i<#metadata and metadata[i]:getLength() < 50 ) then row = row .. "\t" end
end
table.insert( result, row )
end
return result
end,
-- Removes trailing nulls
--
-- @param str containing the informix string
-- @return ret the string with any trailing nulls removed
ifxToLuaString = function( str )
local ret
if ( not(str) ) then return "" end
if ( str:sub(-1, -1 ) ~= "\0" ) then
return str
end
for i=1, #str do
if ( str:sub(-i,-i) == "\0" ) then
ret = str:sub(1, -i - 1)
else
break
end
end
return ret
end,
}
-- The connection Class, used to connect and authenticate to the server
-- Currently only supports plain-text authentication
--
-- The unknown portions in the __tostring method have been derived from Java
-- code connecting to Informix using JDBC.
Packet.Connect = {
-- default parameters sent using JDBC
DEFAULT_PARAMETERS = {
[1] = { ['LOCKDOWN'] = 'no' },
[2] = { ['DBDATE'] = 'Y4MD-' },
[3] = { ['SINGLELEVEL'] = 'no' },
[4] = { ['NODEFDAC'] = 'no' },
[5] = { ['CLNT_PAM_CAPABLE'] = '1' },
[6] = { ['SKALL'] = '0' },
[7] = { ['LKNOTIFY'] = 'yes' },
[8] = { ['SKSHOW'] = '0' },
[9] = { ['IFX_UPDDESC'] = '1' },
[10] = { ['DBPATH'] = '.' },
[11] = { ['CLIENT_LOCALE'] = 'en_US.8859-1' },
[12] = { ['SKINHIBIT'] = '0' },
},
--- Creates a new Connection packet
--
-- @param username string containing the username for authentication
-- @param password string containing the password for authentication
-- @param instance string containing the instance to connect to
-- @return a new Packet.Connect instance
new = function(self, username, password, instance, parameters)
local o = {}
setmetatable(o, self)
self.__index = self
o.username = username and username .. "\0"
o.password = password and password .. "\0"
o.instance = instance and instance .. "\0"
o.parameters = parameters
return o
end,
--- Adds the default set of parameters
addDefaultParameters = function( self )
for _, v in ipairs( self.DEFAULT_PARAMETERS ) do
for k2, v2 in pairs( v ) do
self:addParameter( k2, v2 )
end
end
end,
--- Adds a parameter to the connection packet
--
-- @param param string containing the parameter name
-- @param value string containing the parameter value
-- @return status, always true
addParameter = function( self, param, value )
local tbl = {}
tbl[param] = value
table.insert( self.parameters, tbl )
return true
end,
--- Retrieves the OS error code
--
-- @return oserror number containing the OS error code
getOsError = function( self ) return self.oserror end,
--- Retrieves the Informix service error
--
-- @return svcerror number containing the service error
getSvcError = function( self ) return self.svcerror end,
--- Retrieves the Informix error message
--
-- @return errmsg string containing the "mapped" error message
getErrMsg = function( self ) return self.errmsg end,
--- Reads and decodes the response to the connect packet from the server.
--
-- The function will return true even if the response contains an Informix
-- error. In order to verify if the connection was successful, check for OS
-- or service errors using the getSvcError and getOsError methods.
--
-- @param socket already connected to the server
-- @return status true on success, false on failure
-- @return err msg if status is false
readResponse = function( self, socket )
local status, data = socket:receive_buf(match.numbytes(2), true)
local len, pos, tmp
if ( not(status) ) then return false, data end
pos, len = bin.unpack(">S", data)
status, data = socket:receive_buf(match.numbytes(len - 2), true)
if ( not(status) ) then return false, data end
pos = 13
pos, tmp = bin.unpack(">S", data, pos)
pos = pos + tmp
pos, tmp = bin.unpack(">S", data, pos)
if ( 108 ~= tmp ) then
return false, "Connect received unexpected response"
end
pos = pos + 12
-- version
pos, len = bin.unpack(">S", data, pos)
pos, self.version = bin.unpack("A" .. len, data, pos)
-- serial
pos, len = bin.unpack(">S", data, pos)
pos, self.serial = bin.unpack("A" .. len, data, pos)
-- applid
pos, len = bin.unpack(">S", data, pos)
pos, self.applid = bin.unpack("A" .. len, data, pos)
-- skip 14 bytes ahead
pos = pos + 14
-- do some more skipping
pos, tmp = bin.unpack(">S", data, pos)
pos = pos + tmp
-- do some more skipping
pos, tmp = bin.unpack(">S", data, pos)
pos = pos + tmp
-- skip another 24 bytes
pos = pos + 24
pos, tmp = bin.unpack(">S", data, pos)
if ( tmp ~= 102 ) then
return false, "Connect received unexpected response"
end
pos = pos + 6
pos, self.svcerror = bin.unpack(">s", data, pos)
pos, self.oserror = bin.unpack(">s", data, pos )
if ( self.svcerror ~= 0 ) then
self.errmsg = Constants.ErrorMsg[self.svcerror] or ("Unknown error %d occurred"):format( self.svcerror )
end
return true
end,
--- Converts the class to a string suitable to send over the socket
--
-- @return string containing the packet data
__tostring = function( self )
local data
local unknown = [[
013c0000006400650000003d0006494545454d00006c73716c65786563000000
00000006392e32383000000c524453235230303030303000000573716c690000
00013300000000000000000001
]]
local unknown2 = [[
6f6c0000000000000000003d746c697463700000000000010068000b
00000003
]]
local unknown3 = [[
00000000000000000000006a
]]
local unknown4 = [[ 007f ]]
if ( not(self.parameters) ) then
self.parameters = {}
self:addDefaultParameters()
end
data = bin.pack(">HPPHPHS", unknown, self.username, self.password, unknown2, self.instance, unknown3, #self.parameters )
if ( self.parameters ) then
for _, v in ipairs( self.parameters ) do
for k2, v2 in pairs( v ) do
data = data .. Util.paramToString( k2 .. "\0", v2 .. "\0" )
end
end
end
data = data .. bin.pack("H", unknown4)
data = bin.pack(">S", #data + 2) .. data
return data
end,
}
-- The communication class
Comm =
{
--- Creates a new Comm instance
--
-- @param socket containing a buffered socket connected to the server
-- @return a new Comm instance
new = function(self, socket)
local o = {}
setmetatable(o, self)
self.__index = self
o.socket = socket
return o
end,
--- Sends and packet and attempts to handle the response
--
-- @param packets an instance of a Packet.* class
-- @param info any additional info to pass as the second parameter to the
-- decoder
-- @return status true on success, false on failure
-- @return data returned from the ResponseDecoder
exchIfxPacket = function( self, packet, info )
local _, typ
local status, data = self.socket:send( tostring(packet) )
if ( not(status) ) then return false, data end
status, data = self.socket:receive_buf(match.numbytes(2), true)
_, typ = bin.unpack(">S", data)
if ( MessageDecoders[typ] ) then
status, data = MessageDecoders[typ]( self.socket, info )
else
return false, ("Unsupported data returned from server (type: 0x%x)"):format(typ)
end
return status, data
end
}
-- The Helper class providing easy access to the other db functionality
Helper = {
--- Creates a new Helper instance
--
-- @param host table as passed to the action script function
-- @param port table as passed to the action script function
-- @param instance [optional] string containing the instance to connect to
-- in case left empty it's populated by the informix.instance script
-- argument.
-- @return Helper instance
new = function(self, host, port, instance)
local o = {}
setmetatable(o, self)
self.__index = self
o.host = host
o.port = port
o.socket = nmap.new_socket()
o.instance = instance or "nmap_probe"
return o
end,
--- Connects to the Informix server
--
-- @return true on success, false on failure
-- @return err containing error message when status is false
Connect = function( self )
local status, data
local conn, packet
-- Some Informix server seem to take a LOT of time to respond?!
self.socket:set_timeout(20000)
status, data = self.socket:connect( self.host.ip, self.port.number, "tcp" )
if( not(status) ) then
return status, data
end
self.comm = Comm:new( self.socket )
return true
end,
--- Attempts to login to the Informix database server
--
-- The optional parameters parameter takes any informix specific parameters
-- used to connect to the database. In case it's omitted a set of default
-- parameters are set. Parameters should be past as key, value pairs inside
-- of a table array as the following example:
--
-- local params = {
-- [1] = { ["PARAM1"] = "VALUE1" },
-- [2] = { ["PARAM2"] = "VALUE2" },
-- }
--
-- @param username string containing the username for authentication
-- @param password string containing the password for authentication
-- @param parameters [optional] table of informix specific parameters
-- @param database [optional] database to connect to
-- @param retry [optional] used when autodetecting instance
-- @return status true on success, false on failure
-- @return err containing the error message if status is false
Login = function( self, username, password, parameters, database, retry )
local conn, status, data, len, packet
conn = Packet.Connect:new( username, password, self.instance, parameters )
status, data = self.socket:send( tostring(conn) )
if ( not(status) ) then return false, "Helper.Login failed to send login request" end
status = conn:readResponse( self.socket )
if ( not(status) ) then return false, "Helper.Login failed to read response" end
if ( status and ( conn:getOsError() ~= 0 or conn:getSvcError() ~= 0 ) ) then
-- Check if we didn't supply the correct instance name, if not attempt to
-- reconnect using the instance name returned by the server
if ( conn:getSvcError() == -761 and not(retry) ) then
self.instance = conn.applid
self:Close()
self:Connect()
return self:Login( username, password, parameters, database, 1 )
end
return false, conn:getErrMsg()
end
status, packet = self.comm:exchIfxPacket( Packet.SQ_PROTOCOLS:new() )
if ( not(status) ) then return false, packet end
status, packet = self.comm:exchIfxPacket( Packet.SQ_INFO:new() )
if ( not(status) ) then return false, packet end
-- If a database was supplied continue further protocol negotiation and
-- attempt to open the database.
if ( database ) then
status, packet = self:OpenDatabase( database )
if ( not(status) ) then return false, packet end
end
return true
end,
--- Opens a database
--
-- @param database string containing the database name
-- @return status true on success, false on failure
-- @return err string containing the error message if status is false
OpenDatabase = function( self, database )
return self.comm:exchIfxPacket( Packet.SQ_DBOPEN:new( database ) )
end,
--- Attempts to retrieve a list of available databases
--
-- @return status true on success, false on failure
-- @return databases array of database names or err on failure
GetDatabases = function( self )
return self.comm:exchIfxPacket( Packet.SQ_DBLIST:new() )
end,
Query = function( self, query )
local status, metadata, data, res
local id, seq = 0, 1
local result = {}
if ( type(query) == "string" ) then
query = stdnse.strsplit(";%s*", query)
end
for _, q in ipairs( query ) do
if ( q:upper():match("^%s*SELECT") ) then
status, data = self.comm:exchIfxPacket( Packet.SQ_PREPARE:new( q ) )
seq = seq + 1
else
status, data = self.comm:exchIfxPacket( Packet.SQ_COMMAND:new( q .. ";" ) )
end
if( status and data ) then
metadata = data.metadata
status, data = self.comm:exchIfxPacket( Packet.SQ_ID:new( data.stmt_id, seq, "begin" ), { metadata = metadata, id = id, rows = nil, query=q } )
-- check if any rows were returned
if ( not( data.rows ) ) then
data = { query = q, info = "No rows returned" }
end
--if( not(status) ) then return false, data end
elseif( not(status) ) then
data = { query = q, ["error"] = "ERROR: " .. data }
else
data = { query = q, info = "No rows returned" }
end
table.insert( result, data )
end
return true, result
end,
--- Closes the connection to the server
--
-- @return status true on success, false on failure
Close = function( self )
local status, packet = self.comm:exchIfxPacket( Packet.SQ_EXIT:new() )
return self.socket:close()
end,
}
return _ENV;
| mit |
ferstar/openwrt-dreambox | feeds/luci/luci/luci/modules/admin-full/luasrc/model/cbi/admin_network/iface_add.lua | 3 | 3383 | --[[
LuCI - Lua Configuration Interface
Copyright 2009-2010 Jo-Philipp Wich <xm@subsignal.org>
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: iface_add.lua 7671 2011-10-09 19:28:30Z jow $
]]--
local nw = require "luci.model.network".init()
local fw = require "luci.model.firewall".init()
local utl = require "luci.util"
local uci = require "luci.model.uci".cursor()
m = SimpleForm("network", translate("Create Interface"))
m.redirect = luci.dispatcher.build_url("admin/network/network")
m.reset = false
newnet = m:field(Value, "_netname", translate("Name of the new interface"),
translate("The allowed characters are: <code>A-Z</code>, <code>a-z</code>, " ..
"<code>0-9</code> and <code>_</code>"
))
newnet:depends("_attach", "")
newnet.default = arg[1] and "net_" .. arg[1]:gsub("[^%w_]+", "_")
newnet.datatype = "uciname"
newproto = m:field(ListValue, "_netproto", translate("Protocol of the new interface"))
netbridge = m:field(Flag, "_bridge", translate("Create a bridge over multiple interfaces"))
sifname = m:field(Value, "_ifname", translate("Cover the following interface"),
translate("Note: If you choose an interface here which is part of another network, it will be moved into this network."))
sifname.widget = "radio"
sifname.template = "cbi/network_ifacelist"
sifname.nobridges = true
mifname = m:field(Value, "_ifnames", translate("Cover the following interfaces"),
translate("Note: If you choose an interface here which is part of another network, it will be moved into this network."))
mifname.widget = "checkbox"
mifname.template = "cbi/network_ifacelist"
mifname.nobridges = true
local _, p
for _, p in ipairs(nw:get_protocols()) do
if p:is_installed() then
newproto:value(p:proto(), p:get_i18n())
if not p:is_virtual() then netbridge:depends("_netproto", p:proto()) end
if not p:is_floating() then
sifname:depends({ _bridge = "", _netproto = p:proto()})
mifname:depends({ _bridge = "1", _netproto = p:proto()})
end
end
end
function newproto.validate(self, value, section)
local name = newnet:formvalue(section)
if not name or #name == 0 then
newnet:add_error(section, translate("No network name specified"))
elseif m:get(name) then
newnet:add_error(section, translate("The given network name is not unique"))
end
local proto = nw:get_protocol(value)
if proto and not proto:is_floating() then
local br = (netbridge:formvalue(section) == "1")
local ifn = br and mifname:formvalue(section) or sifname:formvalue(section)
for ifn in utl.imatch(ifn) do
return value
end
return nil, translate("The selected protocol needs a device assigned")
end
return value
end
function newproto.write(self, section, value)
local name = newnet:formvalue(section)
if name and #name > 0 then
local br = (netbridge:formvalue(section) == "1") and "bridge" or nil
local net = nw:add_network(name, { proto = value, type = br })
if net then
local ifn
for ifn in utl.imatch(
br and mifname:formvalue(section) or sifname:formvalue(section)
) do
net:add_interface(ifn)
end
nw:save("network")
nw:save("wireless")
end
luci.http.redirect(luci.dispatcher.build_url("admin/network/network", name))
end
end
return m
| gpl-2.0 |
sajjad94/ASD_KARBALA | plugins/en-voice.lua | 5 | 1053 | --[[
▀▄ ▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀
▀▄ ▄▀ ▀▄ ▄▀
▀▄ ▄▀ BY SAJJAD NOORI ▀▄ ▄▀
▀▄ ▄▀ BY SAJAD NOORI (@SAJJADNOORI) ▀▄ ▄▀
▀▄ ▄▀ JUST WRITED BY SAJJAD NOORI ▀▄ ▄▀
▀▄ ▄▀ voice : صوت ▀▄ ▄▀
▀▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀
--]]
do
local function run(msg, matches)
local url = "http://tts.baidu.com/text2audio?lan=en&ie=UTF-8&text="..matches[1]
local receiver = get_receiver(msg)
local file = download_to_file(url,'text.ogg')
send_audio('channel#id'..msg.to.id, file, ok_cb , false)
end
return {
description = "text to voice",
usage = {
"voice [text]"
},
patterns = {
"^voice (.+)$"
},
run = run
}
end
| gpl-2.0 |
jozadaquebatista/textadept | doc/markdowndoc.lua | 1 | 8092 | -- Copyright 2007-2015 Mitchell mitchell.att.foicica.com. See LICENSE.
local ipairs, type = ipairs, type
local io_open, io_popen = io.open, io.popen
local string_format = string.format
local table_concat = table.concat
-- Markdown doclet for Luadoc.
-- Requires Discount (http://www.pell.portland.or.us/~orc/Code/discount/).
-- @usage luadoc -d [output_path] -doclet path/to/markdowndoc [file(s)]
local M = {}
local NAVFILE = '1. [%s](%s)\n'
local MODULE = '<a id="%s"></a>\n# The `%s` Module\n\n'
local FIELD = '<a id="%s"></a>\n### `%s` %s\n\n'
local FUNCTION = '<a id="%s"></a>\n### `%s`(*%s*)\n\n'
local FUNCTION_NO_PARAMS = '<a id="%s"></a>\n### `%s`()\n\n'
local DESCRIPTION = '%s\n\n'
local LIST_TITLE = '%s:\n\n'
local PARAM = '* *`%s`*: %s\n'
local USAGE = '* `%s`\n'
local RETURN = '* %s\n'
local SEE = '* [`%s`](#%s)\n'
local TABLE = '<a id="%s"></a>\n### `%s`\n\n'
local TFIELD = '* `%s`: %s\n'
local HTML = [[
<!doctype html>
<html>
<head>
<title>%(title)</title>
<link rel="stylesheet" href="style.css" type="text/css" />
<link rel="icon" href="icon.png" type="image/png" />
<meta charset="utf-8" />
</head>
<body>
<div id="content">
<div id="header">
%(header)
</div>
<div id="main">
<h1>Textadept API Documentation</h1>
<p><strong>Modules</strong></p>
%(toc)
<hr />
%(main)
</div>
<div id="footer">
%(footer)
</div>
</div>
</body>
</html>
]]
local titles = {
[PARAM] = 'Parameters', [USAGE] = 'Usage', [RETURN] = 'Return',
[SEE] = 'See also', [TFIELD] = 'Fields'
}
-- Writes a LuaDoc description to the given file.
-- @param f The markdown file being written to.
-- @param description The description.
-- @param name The name of the module the description belongs to. Used for
-- headers in module descriptions.
local function write_description(f, description, name)
if name then
-- Add anchors for module description headers.
description = description:gsub('\n(#+%s+([^\n]+))', function(header, text)
return string_format("\n\n<a id=\"%s.%s\"></a>\n\n%s", name,
text:gsub(' ', '.'), header)
end)
end
-- Substitute custom [`code`]() link convention with [`code`](#code) links.
local self_link = '(%[`([^`(]+)%(?%)?`%])%(%)'
description = description:gsub(self_link, function(link, id)
return string_format("%s(#%s)", link, id:gsub(':', '.'))
end)
f:write(string_format(DESCRIPTION, description))
end
-- Writes a LuaDoc list to the given file.
-- @param f The markdown file being written to.
-- @param fmt The format of a list item.
-- @param list The LuaDoc list.
-- @param name The name of the module the list belongs to. Used for @see.
local function write_list(f, fmt, list, name)
if not list or #list == 0 then return end
if type(list) == 'string' then list = {list} end
f:write(string_format(LIST_TITLE, titles[fmt]))
for _, value in ipairs(list) do
if fmt == SEE and name ~= '_G' then
if not value:find('%.') then
-- Prepend module name to identifier if necessary.
value = name..'.'..value
else
-- TODO: cannot link to fields, functions, or tables in `_G`?
value = value:gsub('^_G%.', '')
end
end
f:write(string_format(fmt, value, value))
end
f:write('\n')
end
-- Writes a LuaDoc hashmap to the given file.
-- @param f The markdown file being written to.
-- @param fmt The format of a hashmap item.
-- @param list The LuaDoc hashmap.
local function write_hashmap(f, fmt, hashmap)
if not hashmap or #hashmap == 0 then return end
f:write(string_format(LIST_TITLE, titles[fmt]))
for _, name in ipairs(hashmap) do
f:write(string_format(fmt, name, hashmap[name] or ''))
end
f:write('\n')
end
-- Called by LuaDoc to process a doc object.
-- @param doc The LuaDoc doc object.
function M.start(doc)
local template = {title = '', header = '', toc = '', main = '', footer = ''}
local modules, files = doc.modules, doc.files
-- Create the header and footer, if given a template.
if M.options.template_dir ~= 'luadoc/doclet/html/' then
local p = io.popen('markdown "'..M.options.template_dir..'.header.md"')
template.header = p:read('*a')
p:close()
p = io.popen('markdown "'..M.options.template_dir..'.footer.md"')
template.footer = p:read('*a')
p:close()
end
-- Create the table of contents.
local tocfile = M.options.output_dir..'/.api_toc.md'
local f = io_open(tocfile, 'wb')
for _, name in ipairs(modules) do
f:write(string_format(NAVFILE, name, '#'..name))
end
f:close()
local p = io_popen('markdown "'..tocfile..'"')
local toc = p:read('*a')
p:close()
os.remove(tocfile)
-- Create a map of doc objects to file names so their Markdown doc comments
-- can be extracted.
local filedocs = {}
for _, name in ipairs(files) do filedocs[files[name].doc] = name end
-- Loop over modules, creating Markdown documents.
local mdfile = M.options.output_dir..'/api.md'
f = io_open(mdfile, 'wb')
for _, name in ipairs(modules) do
local module = modules[name]
-- Write the header and description.
f:write(string_format(MODULE, name, name))
f:write('- - -\n\n')
write_description(f, module.description, name)
-- Write fields.
if module.doc[1].class == 'module' then
local fields = module.doc[1].field
if fields and #fields > 0 then
table.sort(fields)
f:write('## Fields defined by `', name, '`\n\n')
for _, field in ipairs(fields) do
local type, description = fields[field]:match('^(%b())%s*(.+)$')
if not field:find('%.') and name ~= '_G' then
field = name..'.'..field -- absolute name
else
field = field:gsub('^_G%.', '') -- strip _G required for Luadoc
end
f:write(string_format(FIELD, field, field, type or ''))
write_description(f, description or fields[field])
end
f:write('\n')
end
end
-- Write functions.
local funcs = module.functions
if #funcs > 0 then
f:write('## Functions defined by `', name, '`\n\n')
for _, fname in ipairs(funcs) do
local func = funcs[fname]
local params = table_concat(func.param, ', '):gsub('_', '\\_')
if not func.name:find('[%.:]') and name ~= '_G' then
func.name = name..'.'..func.name -- absolute name
end
if params ~= '' then
f:write(string_format(FUNCTION, func.name, func.name, params))
else
f:write(string_format(FUNCTION_NO_PARAMS, func.name, func.name))
end
write_description(f, func.description)
write_hashmap(f, PARAM, func.param)
write_list(f, USAGE, func.usage)
write_list(f, RETURN, func.ret)
write_list(f, SEE, func.see, name)
end
f:write('\n')
end
-- Write tables.
local tables = module.tables
if #tables > 0 then
f:write('## Tables defined by `', name, '`\n\n')
for _, tname in ipairs(tables) do
local tbl = tables[tname]
if not tbl.name:find('%.') and
(name ~= '_G' or tbl.name == 'buffer' or tbl.name == 'view') then
tbl.name = name..'.'..tbl.name -- absolute name
elseif tbl.name ~= '_G.keys' and tbl.name ~= '_G.snippets' then
tbl.name = tbl.name:gsub('^_G%.', '') -- strip _G required for Luadoc
end
f:write(string_format(TABLE, tbl.name, tbl.name))
write_description(f, tbl.description)
write_hashmap(f, TFIELD, tbl.field)
write_list(f, USAGE, tbl.usage)
write_list(f, SEE, tbl.see, name)
end
end
f:write('- - -\n\n')
end
-- Write HTML.
template.title = 'Textadept API'
template.toc = toc
p = io_popen('markdown "'..mdfile..'"')
template.main = p:read('*a')
p:close()
f = io_open(M.options.output_dir..'/api.html', 'wb')
local html = HTML:gsub('%%%(([^)]+)%)', template)
f:write(html)
f:close()
end
return M
| mit |
loringmoore/The-Forgotten-Server | data/spells/scripts/monster/undead dragon curse.lua | 12 | 1113 | local combat = {}
for i = 30, 50 do
combat[i] = Combat()
combat[i]:setParameter(COMBAT_PARAM_TYPE, COMBAT_DEATHDAMAGE)
combat[i]:setParameter(COMBAT_PARAM_EFFECT, CONST_ME_SMALLCLOUDS)
combat[i]:setParameter(COMBAT_PARAM_DISTANCEEFFECT, CONST_ANI_DEATH)
local condition = Condition(CONDITION_CURSED)
condition:setParameter(CONDITION_PARAM_DELAYED, 1)
local damage = i
condition:addDamage(1, 4000, -damage)
for j = 1, 9 do
damage = damage * 1.2
condition:addDamage(1, 4000, -damage)
end
local area = createCombatArea({
{0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0},
{0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0},
{0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0},
{0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0},
{0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0},
{0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0},
{0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0},
{0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0},
{0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0}
})
combat[i]:setArea(area)
combat[i]:setCondition(condition)
end
function onCastSpell(creature, var)
return combat[math.random(30, 50)]:execute(creature, var)
end
| gpl-2.0 |
iamliqiang/prosody-modules | mod_ipcheck/mod_ipcheck.lua | 31 | 1776 |
-- mod_ipcheck.lua
-- Implementation of XEP-0279: Server IP Check <http://xmpp.org/extensions/xep-0279.html>
local st = require "util.stanza";
module:add_feature("urn:xmpp:sic:0");
module:hook("iq/bare/urn:xmpp:sic:0:ip", function(event)
local origin, stanza = event.origin, event.stanza;
if stanza.attr.type == "get" then
if stanza.attr.to then
origin.send(st.error_reply(stanza, "auth", "forbidden", "You can only ask about your own IP address"));
elseif origin.ip then
origin.send(st.reply(stanza):tag("ip", {xmlns='urn:xmpp:sic:0'}):text(origin.ip));
else
-- IP addresses should normally be available, but in case they are not
origin.send(st.error_reply(stanza, "cancel", "service-unavailable", "IP address for this session is not available"));
end
return true;
end
end);
module:add_feature("urn:xmpp:sic:1");
module:hook("iq/bare/urn:xmpp:sic:1:address", function(event)
local origin, stanza = event.origin, event.stanza;
if stanza.attr.type == "get" then
if stanza.attr.to then
origin.send(st.error_reply(stanza, "auth", "forbidden", "You can only ask about your own IP address"));
elseif origin.ip then
local reply = st.reply(stanza):tag("address", {xmlns='urn:xmpp:sic:0'})
:tag("ip"):text(origin.ip):up()
if origin.conn and origin.conn.port then -- server_event
reply:tag("port"):text(tostring(origin.conn:port()))
elseif origin.conn and origin.conn.clientport then -- server_select
reply:tag("port"):text(tostring(origin.conn:clientport()))
end
origin.send(reply);
else
-- IP addresses should normally be available, but in case they are not
origin.send(st.error_reply(stanza, "cancel", "service-unavailable", "IP address for this session is not available"));
end
return true;
end
end);
| mit |
fanzhangio/kubernetes | test/images/echoserver/template.lua | 195 | 17200 | -- vendored from https://raw.githubusercontent.com/bungle/lua-resty-template/1f9a5c24fc7572dbf5be0b9f8168cc3984b03d24/lib/resty/template.lua
-- only modification: remove / from HTML_ENTITIES to not escape it, and fix the appropriate regex.
--[[
Copyright (c) 2014 - 2017 Aapo Talvensaari
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
* Neither the name of the {organization} nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--]]
local setmetatable = setmetatable
local loadstring = loadstring
local loadchunk
local tostring = tostring
local setfenv = setfenv
local require = require
local capture
local concat = table.concat
local assert = assert
local prefix
local write = io.write
local pcall = pcall
local phase
local open = io.open
local load = load
local type = type
local dump = string.dump
local find = string.find
local gsub = string.gsub
local byte = string.byte
local null
local sub = string.sub
local ngx = ngx
local jit = jit
local var
local _VERSION = _VERSION
local _ENV = _ENV
local _G = _G
local HTML_ENTITIES = {
["&"] = "&",
["<"] = "<",
[">"] = ">",
['"'] = """,
["'"] = "'",
}
local CODE_ENTITIES = {
["{"] = "{",
["}"] = "}",
["&"] = "&",
["<"] = "<",
[">"] = ">",
['"'] = """,
["'"] = "'",
["/"] = "/"
}
local VAR_PHASES
local ok, newtab = pcall(require, "table.new")
if not ok then newtab = function() return {} end end
local caching = true
local template = newtab(0, 12)
template._VERSION = "1.9"
template.cache = {}
local function enabled(val)
if val == nil then return true end
return val == true or (val == "1" or val == "true" or val == "on")
end
local function trim(s)
return gsub(gsub(s, "^%s+", ""), "%s+$", "")
end
local function rpos(view, s)
while s > 0 do
local c = sub(view, s, s)
if c == " " or c == "\t" or c == "\0" or c == "\x0B" then
s = s - 1
else
break
end
end
return s
end
local function escaped(view, s)
if s > 1 and sub(view, s - 1, s - 1) == "\\" then
if s > 2 and sub(view, s - 2, s - 2) == "\\" then
return false, 1
else
return true, 1
end
end
return false, 0
end
local function readfile(path)
local file = open(path, "rb")
if not file then return nil end
local content = file:read "*a"
file:close()
return content
end
local function loadlua(path)
return readfile(path) or path
end
local function loadngx(path)
local vars = VAR_PHASES[phase()]
local file, location = path, vars and var.template_location
if sub(file, 1) == "/" then file = sub(file, 2) end
if location and location ~= "" then
if sub(location, -1) == "/" then location = sub(location, 1, -2) end
local res = capture(concat{ location, '/', file})
if res.status == 200 then return res.body end
end
local root = vars and (var.template_root or var.document_root) or prefix
if sub(root, -1) == "/" then root = sub(root, 1, -2) end
return readfile(concat{ root, "/", file }) or path
end
do
if ngx then
VAR_PHASES = {
set = true,
rewrite = true,
access = true,
content = true,
header_filter = true,
body_filter = true,
log = true
}
template.print = ngx.print or write
template.load = loadngx
prefix, var, capture, null, phase = ngx.config.prefix(), ngx.var, ngx.location.capture, ngx.null, ngx.get_phase
if VAR_PHASES[phase()] then
caching = enabled(var.template_cache)
end
else
template.print = write
template.load = loadlua
end
if _VERSION == "Lua 5.1" then
local context = { __index = function(t, k)
return t.context[k] or t.template[k] or _G[k]
end }
if jit then
loadchunk = function(view)
return assert(load(view, nil, nil, setmetatable({ template = template }, context)))
end
else
loadchunk = function(view)
local func = assert(loadstring(view))
setfenv(func, setmetatable({ template = template }, context))
return func
end
end
else
local context = { __index = function(t, k)
return t.context[k] or t.template[k] or _ENV[k]
end }
loadchunk = function(view)
return assert(load(view, nil, nil, setmetatable({ template = template }, context)))
end
end
end
function template.caching(enable)
if enable ~= nil then caching = enable == true end
return caching
end
function template.output(s)
if s == nil or s == null then return "" end
if type(s) == "function" then return template.output(s()) end
return tostring(s)
end
function template.escape(s, c)
if type(s) == "string" then
if c then return gsub(s, "[}{\">/<'&]", CODE_ENTITIES) end
return gsub(s, "[\"><'&]", HTML_ENTITIES)
end
return template.output(s)
end
function template.new(view, layout)
assert(view, "view was not provided for template.new(view, layout).")
local render, compile = template.render, template.compile
if layout then
if type(layout) == "table" then
return setmetatable({ render = function(self, context)
local context = context or self
context.blocks = context.blocks or {}
context.view = compile(view)(context)
layout.blocks = context.blocks or {}
layout.view = context.view or ""
return layout:render()
end }, { __tostring = function(self)
local context = self
context.blocks = context.blocks or {}
context.view = compile(view)(context)
layout.blocks = context.blocks or {}
layout.view = context.view
return tostring(layout)
end })
else
return setmetatable({ render = function(self, context)
local context = context or self
context.blocks = context.blocks or {}
context.view = compile(view)(context)
return render(layout, context)
end }, { __tostring = function(self)
local context = self
context.blocks = context.blocks or {}
context.view = compile(view)(context)
return compile(layout)(context)
end })
end
end
return setmetatable({ render = function(self, context)
return render(view, context or self)
end }, { __tostring = function(self)
return compile(view)(self)
end })
end
function template.precompile(view, path, strip)
local chunk = dump(template.compile(view), strip ~= false)
if path then
local file = open(path, "wb")
file:write(chunk)
file:close()
end
return chunk
end
function template.compile(view, key, plain)
assert(view, "view was not provided for template.compile(view, key, plain).")
if key == "no-cache" then
return loadchunk(template.parse(view, plain)), false
end
key = key or view
local cache = template.cache
if cache[key] then return cache[key], true end
local func = loadchunk(template.parse(view, plain))
if caching then cache[key] = func end
return func, false
end
function template.parse(view, plain)
assert(view, "view was not provided for template.parse(view, plain).")
if not plain then
view = template.load(view)
if byte(view, 1, 1) == 27 then return view end
end
local j = 2
local c = {[[
context=... or {}
local function include(v, c) return template.compile(v)(c or context) end
local ___,blocks,layout={},blocks or {}
]] }
local i, s = 1, find(view, "{", 1, true)
while s do
local t, p = sub(view, s + 1, s + 1), s + 2
if t == "{" then
local e = find(view, "}}", p, true)
if e then
local z, w = escaped(view, s)
if i < s - w then
c[j] = "___[#___+1]=[=[\n"
c[j+1] = sub(view, i, s - 1 - w)
c[j+2] = "]=]\n"
j=j+3
end
if z then
i = s
else
c[j] = "___[#___+1]=template.escape("
c[j+1] = trim(sub(view, p, e - 1))
c[j+2] = ")\n"
j=j+3
s, i = e + 1, e + 2
end
end
elseif t == "*" then
local e = find(view, "*}", p, true)
if e then
local z, w = escaped(view, s)
if i < s - w then
c[j] = "___[#___+1]=[=[\n"
c[j+1] = sub(view, i, s - 1 - w)
c[j+2] = "]=]\n"
j=j+3
end
if z then
i = s
else
c[j] = "___[#___+1]=template.output("
c[j+1] = trim(sub(view, p, e - 1))
c[j+2] = ")\n"
j=j+3
s, i = e + 1, e + 2
end
end
elseif t == "%" then
local e = find(view, "%}", p, true)
if e then
local z, w = escaped(view, s)
if z then
if i < s - w then
c[j] = "___[#___+1]=[=[\n"
c[j+1] = sub(view, i, s - 1 - w)
c[j+2] = "]=]\n"
j=j+3
end
i = s
else
local n = e + 2
if sub(view, n, n) == "\n" then
n = n + 1
end
local r = rpos(view, s - 1)
if i <= r then
c[j] = "___[#___+1]=[=[\n"
c[j+1] = sub(view, i, r)
c[j+2] = "]=]\n"
j=j+3
end
c[j] = trim(sub(view, p, e - 1))
c[j+1] = "\n"
j=j+2
s, i = n - 1, n
end
end
elseif t == "(" then
local e = find(view, ")}", p, true)
if e then
local z, w = escaped(view, s)
if i < s - w then
c[j] = "___[#___+1]=[=[\n"
c[j+1] = sub(view, i, s - 1 - w)
c[j+2] = "]=]\n"
j=j+3
end
if z then
i = s
else
local f = sub(view, p, e - 1)
local x = find(f, ",", 2, true)
if x then
c[j] = "___[#___+1]=include([=["
c[j+1] = trim(sub(f, 1, x - 1))
c[j+2] = "]=],"
c[j+3] = trim(sub(f, x + 1))
c[j+4] = ")\n"
j=j+5
else
c[j] = "___[#___+1]=include([=["
c[j+1] = trim(f)
c[j+2] = "]=])\n"
j=j+3
end
s, i = e + 1, e + 2
end
end
elseif t == "[" then
local e = find(view, "]}", p, true)
if e then
local z, w = escaped(view, s)
if i < s - w then
c[j] = "___[#___+1]=[=[\n"
c[j+1] = sub(view, i, s - 1 - w)
c[j+2] = "]=]\n"
j=j+3
end
if z then
i = s
else
c[j] = "___[#___+1]=include("
c[j+1] = trim(sub(view, p, e - 1))
c[j+2] = ")\n"
j=j+3
s, i = e + 1, e + 2
end
end
elseif t == "-" then
local e = find(view, "-}", p, true)
if e then
local x, y = find(view, sub(view, s, e + 1), e + 2, true)
if x then
local z, w = escaped(view, s)
if z then
if i < s - w then
c[j] = "___[#___+1]=[=[\n"
c[j+1] = sub(view, i, s - 1 - w)
c[j+2] = "]=]\n"
j=j+3
end
i = s
else
y = y + 1
x = x - 1
if sub(view, y, y) == "\n" then
y = y + 1
end
local b = trim(sub(view, p, e - 1))
if b == "verbatim" or b == "raw" then
if i < s - w then
c[j] = "___[#___+1]=[=[\n"
c[j+1] = sub(view, i, s - 1 - w)
c[j+2] = "]=]\n"
j=j+3
end
c[j] = "___[#___+1]=[=["
c[j+1] = sub(view, e + 2, x)
c[j+2] = "]=]\n"
j=j+3
else
if sub(view, x, x) == "\n" then
x = x - 1
end
local r = rpos(view, s - 1)
if i <= r then
c[j] = "___[#___+1]=[=[\n"
c[j+1] = sub(view, i, r)
c[j+2] = "]=]\n"
j=j+3
end
c[j] = 'blocks["'
c[j+1] = b
c[j+2] = '"]=include[=['
c[j+3] = sub(view, e + 2, x)
c[j+4] = "]=]\n"
j=j+5
end
s, i = y - 1, y
end
end
end
elseif t == "#" then
local e = find(view, "#}", p, true)
if e then
local z, w = escaped(view, s)
if i < s - w then
c[j] = "___[#___+1]=[=[\n"
c[j+1] = sub(view, i, s - 1 - w)
c[j+2] = "]=]\n"
j=j+3
end
if z then
i = s
else
e = e + 2
if sub(view, e, e) == "\n" then
e = e + 1
end
s, i = e - 1, e
end
end
end
s = find(view, "{", s + 1, true)
end
s = sub(view, i)
if s and s ~= "" then
c[j] = "___[#___+1]=[=[\n"
c[j+1] = s
c[j+2] = "]=]\n"
j=j+3
end
c[j] = "return layout and include(layout,setmetatable({view=table.concat(___),blocks=blocks},{__index=context})) or table.concat(___)"
return concat(c)
end
function template.render(view, context, key, plain)
assert(view, "view was not provided for template.render(view, context, key, plain).")
return template.print(template.compile(view, key, plain)(context))
end
return template | apache-2.0 |
osgcc/ryzom | ryzom/common/data_common/r2/r2_ui_contextual_commands_new.lua | 3 | 11236 | ----------------------------
-- CONTEXTUAL COMMANDS UI --
----------------------------
-- Code in this file manage the update of the contextual toolbar &
-- contextual menu for the current selected instance, depending on the vailable options
r2.ContextualCommands = r2.newToolbar()
r2.ContextualCommands.MenuCommands={}
r2.ContextualCommands.CurrentMenuInstance = nil -- for now, will always be equal to CurrentInstance, or nil if menu hasn't been displayed yet
r2.ContextualCommands.CurrentMenu = nil
------------
-- PUBLIC --
------------
local newCommands = {}
----------------------------------------------------------------------------
-- Update the toolbar content, avoiding to resetup it if there where no changes
function r2.ContextualCommands:update()
-- TODO nico : report this behavior in the base class
if self.CurrentInstance then
table.clear(newCommands)
if not self.CurrentInstance.Ghost then
self.CurrentInstance:getAvailableCommands(newCommands)
end
if isEqual(newCommands, self.CurrentCommands) then
return -- commands remains unchanged, no need to update the ui
end
end
-- if one of the command is highlighted, let it highlighted after the toolbar has been rebuilt
local highlightedCommand
for index, button in pairs(self.IndexToButton) do
if button == r2.ToolUI:getActiveToolUI() then
debugInfo("highlighted command found")
highlightedCommand = self.CurrentCommands[index]
break
end
end
self:setupToolbar(self.CurrentInstance)
-- if one command was highlighted, highlight it again in new toolbar
if highlightedCommand then
for index, command in pairs(self.CurrentCommands) do
if command == highlightedCommand then
debugInfo("re-highlighting command")
r2.ToolUI:setActiveToolUI(self.IndexToButton[index])
break
end
end
end
-- for now, if menu is displayed then toolbar must be, too
if self.CurrentMenuInstance then
-- update menu
if self.CurrentMenu.active then
self:setupMenu(self.CurrentMenuInstance, self.CurrentMenu)
end
end
-- remove current context help ->
disableContextHelp()
end
----------------------------------------------------------------------------
-- Special function called by the framework when the "r2ed_context_command" action is triggered
-- Like other action (defined in actions.xml), this action can have been triggered by a key assigned to it in the 'keys' window
function r2:execContextCommand(commandId)
if not r2.ContextualCommands.CurrentInstance then return end
-- see in list of current commands if there is a command with the good id
for key, command in pairs(r2.ContextualCommands.CurrentCommands) do
if command.Id == commandId then
command.DoCommand(r2.ContextualCommands.CurrentInstance)
return
end
end
end
----------------------------------------------------------------------------
-- called by the ui when it wants to display the tooltip for one of the contextual commands
function r2:updateContextualCommandTooltip(index)
local command = r2.ContextualCommands.ToolbarCommands[index + 1]
assert(command)
local keyName = ucstring(runExpr(string.format("getKey('r2ed_context_command', 'commandId=%s')", command.Id)))
if keyName == i18n.get("uiNotAssigned") then
-- no associated key
setContextHelpText(i18n.get(command.TextId))
else
setContextHelpText(concatUCString(i18n.get(command.TextId), " (", keyName, ")"))
end
end
local commands = {} -- to avoid reallocs
----------------------------------------------------------------------------
-- Setup a contextual menu for the given instance
-- passing nil just hides the toolbar
function r2.ContextualCommands:setupMenu(instance, menu)
-- TMP (test of menu exported methods)
--if menu then
-- local rm = menu:getRootMenu()
-- debugInfo("****************************")
-- debugInfo("Num line " .. tostring(rm:getNumLine()))
-- for i = 0, rm:getNumLine() -1 do
-- debugInfo("Id for line " .. tostring(i) .. " is " .. tostring(rm:getLineId(i)))
-- end
-- debugInfo("Line with id 'dynamic_content_start' has index " .. tostring(rm:getLineFromId('dynamic_content_start')))
-- debugInfo("Line 6 is separator = " .. tostring(rm:isSeparator(6)))
-- rm:addLine(ucstring("toto"), "lua", "debugInfo('pouet')", "toto")
-- rm:addSeparator()
-- rm:addLine(ucstring("tutu"), "lua", "debugInfo('pouet')", "tutu")
-- rm:addLine(ucstring("titi"), "lua", "debugInfo('pouet')", "titi")
-- local titiIndex = rm:getLineFromId('titi')
-- rm:addSeparatorAtIndex(titiIndex)
-- rm:addLine(ucstring("bidon"), "lua", "debugInfo('pouet')", "titi")
-- debugInfo("################################")
-- end
self.CurrentMenuInstance = instance
self.CurrentMenu = menu
table.clear(self.MenuCommands)
if not instance then return end
-- delete entries for dynamic content
local menuRoot = menu:getRootMenu()
local startLine = menuRoot:getLineFromId("dynamic_content_start")
local endLine = menuRoot:getLineFromId("dynamic_content_end")
assert(startLine ~= -1 and endLine ~= -1)
for lineToDel = endLine - 1, startLine + 1, -1 do
menuRoot:removeLine(lineToDel)
end
-- retrieve dynamic commands
table.clear(commands)
if not instance.Ghost then
instance:getAvailableCommands(commands)
end
local currentLine = startLine + 1
local currentActivityLine = 0
local commandIndex = 1
local activityAdded = false
local activityMenuIndex = menuRoot:getLineFromId("activities")
local activityMenu
if activityMenuIndex ~= -1 then
activityMenu = menuRoot:getSubMenu(activityMenuIndex)
end
if activityMenu then
activityMenu:reset()
end
for commandIndex, command in pairs(commands) do
if command.ShowInMenu then
local destNode
local line
if command.IsActivity then
destNode = activityMenu
line = currentActivityLine
activityAdded = true
else
line = currentLine
destNode = menuRoot
end
destNode:addLineAtIndex(line, i18n.get(command.TextId), "lua",
"r2.ContextualCommands:runMenuCommand(" .. tostring(table.getn(self.MenuCommands) + 1) .. ")", "dyn_command_" .. tostring(commandIndex))
-- if there's a bitmap, build a group with the buitmap in it, and add to menu
if command.ButtonBitmap and command.ButtonBitmap ~= "" then
local smallIcon = nlfile.getFilenameWithoutExtension(command.ButtonBitmap) ..
"_small." .. nlfile.getExtension(command.ButtonBitmap)
local menuButton = createGroupInstance("r2_menu_button", "", { bitmap = smallIcon, })
if menuButton then
destNode:setUserGroupLeft(line, menuButton)
assert(destNode:getUserGroupLeft(line) == menuButton)
-- TMP (test for menu exported lua methods)
-- menuButton = createGroupInstance("r2_menu_button", "", { bitmap = smallIcon, })
-- menuRoot:setUserGroupRight(currentLine, menuButton)
-- assert(menuRoot:getUserGroupRight(currentLine) == menuButton)
end
end
local keyNameGroup = createGroupInstance("r2_keyname", "", { id = command.Id })
if keyNameGroup then
local keyName = ucstring(runExpr(string.format("getKey('r2ed_context_command', 'commandId=%s')", command.Id)))
if keyName == i18n.get("uiNotAssigned") then
-- no associated key
keyNameGroup:find("t").uc_hardtext = keyName
else
keyNameGroup:find("t").uc_hardtext = concatUCString(ucstring("(") , keyName, ucstring(")"))
end
destNode:setUserGroupRight(line, keyNameGroup)
end
table.insert(self.MenuCommands, command)
if command.IsActivity then
currentActivityLine = currentActivityLine + 1
else
currentLine = currentLine + 1
end
end
end
end
----------------------------------------------------------------------------
function r2.ContextualCommands:runMenuCommand(index)
assert(self.CurrentMenuInstance)
assert(self.MenuCommands[index] ~= nil)
-- do actual call
self.MenuCommands[index].DoCommand(self.CurrentInstance)
end
----------------------------------------------------------------------------
-- Hightlight the button of the last triggered command
function r2.ContextualCommands:highlightCurrentCommandButton()
if self.LastTriggeredCommandIndex then
r2.ToolUI:setActiveToolUI(self:getButton(self.LastTriggeredCommandIndex - 1))
end
end
----------------------------------------------------------------------------
-- Hightlight the button of the last triggered command
function r2.ContextualCommands:highlightCommandButton(commandId)
r2.ToolUI:setActiveToolUI(self.IndexToButton[self.CommandIdToIndex[commandId]])
end
-------------------------------------------------------------------
-- PRIVATE :IMPLEMENT METHODS REQUIRED BY r2_ui_toolbar_base.lua --
-------------------------------------------------------------------
-- return a reference on the toolbar
function r2.ContextualCommands:getToolbar()
return getUI("ui:interface:r2ed_contextual_toolbar_new")
end
-- return the max number of command that the toolbar may contains
function r2.ContextualCommands:getMaxNumCommands()
return tonumber(getDefine("r2ed_max_num_contextual_buttons"))
end
-- get a button from its index in the toolbar
function r2.ContextualCommands:getButton(buttonIndex)
if self.ButtonList == nil then
self.ButtonList = self:getToolbar():find("buttons")
end
return self.ButtonList["b" .. tostring(buttonIndex)]
end
-- setup a button from a command in the toolbar
function r2.ContextualCommands:setupButton(button, commandDesc, buttonIndex)
assert(button)
button.active = true
-- buld filenames for the 'normal', 'over' & 'pushed" textures
local icon = commandDesc.ButtonBitmap
local iconOver = nlfile.getFilenameWithoutExtension(icon) ..
"_over." .. nlfile.getExtension(icon)
local iconPushed = nlfile.getFilenameWithoutExtension(icon) ..
"_pushed." .. nlfile.getExtension(icon)
local selectedGroup = button:find("selected")
local unselectedGroup = button:find("unselected")
local selectedButton = selectedGroup:find("button")
local unselectedButton = unselectedGroup:find("button")
selectedGroup.active = false
unselectedGroup.active = true
selectedButton.texture = icon
selectedButton.texture_over = iconOver
selectedButton.texture_pushed = iconPushed
selectedButton.parent.Env.Toolbar = self
unselectedButton.texture = icon
unselectedButton.texture_over = iconOver
unselectedButton.texture_pushed = iconPushed
unselectedButton.parent.Env.Toolbar = self
selectedButton.onclick_l = "lua"
selectedButton.params_l = "r2.runBaseToolbarCommand(getUICaller().parent.Env.Toolbar, " .. tostring(buttonIndex) .. ")"
unselectedButton.onclick_l = "lua"
unselectedButton.params_l = selectedButton.params_l
button.child_resize_wmargin = select(commandDesc.Separator == true, 8, 0)
end
-- retrieve a command list for the given instance
function r2.ContextualCommands:getAvailableCommands(instance, dest)
--inspect(instance)
table.clear(dest)
if not instance.Ghost then
instance:getAvailableCommands(dest)
end
end
| agpl-3.0 |
golden1232004/torch7 | test/test_sharedmem.lua | 58 | 2639 | require 'torch'
local tester = torch.Tester()
local tests = {}
local function createSharedMemStorage(name, size, storageType)
local storageType = storageType or 'FloatStorage'
local shmName = name or os.tmpname():gsub('/','_')
local isShared = true
local isSharedMem = true
local nElements = size or torch.random(10000, 20000)
local storage = torch[storageType](shmName, isShared, nElements, isSharedMem)
return storage, shmName
end
function tests.createSharedMemFile()
local storage, shmName = createSharedMemStorage()
-- check that file is at /dev/shm
tester:assert(paths.filep('/dev/shm/' .. shmName),
'Shared memory file does not exist')
-- collect storage and make sure that file is gone
storage = nil
collectgarbage()
collectgarbage()
tester:assert(not paths.filep('/dev/shm/' .. shmName),
'Shared memory file still exists')
end
function tests.checkContents()
local storage, shmName = createSharedMemStorage()
local tensor = torch.FloatTensor(storage, 1, torch.LongStorage{storage:size()})
tensor:copy(torch.rand(storage:size()))
local sharedFile = torch.DiskFile('/dev/shm/'..shmName, 'r'):binary()
for i = 1, storage:size() do
tester:assert(sharedFile:readFloat() == storage[i], 'value is not correct')
end
sharedFile:close()
end
function tests.testSharing()
-- since we are going to cast numbers into double (lua default)
-- we specifically generate double storage
local storage, shmName = createSharedMemStorage(nil, nil, 'DoubleStorage')
local shmFileName = '/dev/shm/' .. shmName
local tensor = torch.DoubleTensor(storage, 1, torch.LongStorage{storage:size()})
tensor:copy(torch.rand(storage:size()))
local tensorCopy = tensor.new():resizeAs(tensor):copy(tensor)
-- access the same shared memory file as regular mapping from same process
local storage2 = torch.DoubleStorage(shmFileName, true, storage:size())
local tensor2 = torch.DoubleTensor(storage2, 1,
torch.LongStorage{storage2:size()})
local tensor2Copy = tensor2.new():resizeAs(tensor2):copy(tensor2)
tester:assertTensorEq(tensorCopy, tensor2Copy, 0, 'contents don\'t match')
-- fill tensor 1 with a random value and read from 2
local rval = torch.uniform()
tensor:fill(rval)
for i = 1, tensor2:size(1) do
tester:asserteq(tensor2[i], rval, 'content is wrong')
end
-- fill tensor 2 with a random value and read from 1
local rval = torch.uniform()
tensor2:fill(rval)
for i = 1, tensor:size(1) do
tester:asserteq(tensor[i], rval, 'content is wrong')
end
end
tester:add(tests)
tester:run()
| bsd-3-clause |
m-creations/openwrt | feeds/luci/applications/luci-app-diag-devinfo/luasrc/model/cbi/luci_diag/mactodevinfo.lua | 61 | 1058 | -- Copyright 2009 Daniel Dickinson
-- Licensed to the public under the Apache License 2.0.
m = Map("mactodevinfo", luci.i18n.translate("MAC Device Info Overrides"), translate("Override the information returned by the MAC to Device Info Script (mac-to-devinfo) for a specified range of MAC Addresses"))
s = m:section(TypedSection, "mactodevinfo", translate("MAC Device Override"), translate("MAC range and information used to override system and IEEE databases"))
s.addremove = true
s.anonymous = true
v = s:option(Value, "name", translate("Name"))
v.optional = true
v = s:option(Value, "maclow", translate("Beginning of MAC address range"))
v.optional = false
v = s:option(Value, "machigh", translate("End of MAC address range"))
v.optional = false
v = s:option(Value, "vendor", translate("Vendor"))
v.optional = false
v = s:option(Value, "devtype", translate("Device Type"))
v.optional = false
v = s:option(Value, "model", translate("Model"))
v.optional = false
v = s:option(Value, "ouiowneroverride", translate("OUI Owner"))
v.optional = true
return m
| gpl-2.0 |
jozadaquebatista/textadept | properties.lua | 1 | 7042 | -- Copyright 2007-2015 Mitchell mitchell.att.foicica.com. See LICENSE.
local buffer = buffer
-- Multiple Selection and Virtual Space
buffer.multiple_selection = true
buffer.additional_selection_typing = true
--buffer.multi_paste = buffer.MULTIPASTE_EACH
--buffer.virtual_space_options = buffer.VS_RECTANGULARSELECTION +
-- buffer.VS_USERACCESSIBLE
buffer.rectangular_selection_modifier = buffer.MOD_ALT
buffer.mouse_selection_rectangular_switch = true
--buffer.additional_carets_blink = false
--buffer.additional_carets_visible = false
-- Scrolling.
buffer:set_x_caret_policy(buffer.CARET_SLOP, 20)
buffer:set_y_caret_policy(buffer.CARET_SLOP + buffer.CARET_STRICT +
buffer.CARET_EVEN, 1)
--buffer:set_visible_policy()
--buffer.h_scroll_bar = CURSES
--buffer.v_scroll_bar = false
if CURSES and not (WIN32 or LINUX or BSD) then buffer.v_scroll_bar = false end
--buffer.scroll_width =
--buffer.scroll_width_tracking = true
--buffer.end_at_last_line = false
-- Whitespace
buffer.view_ws = buffer.WS_INVISIBLE
--buffer.whitespace_size =
--buffer.extra_ascent =
--buffer.extra_descent =
-- Line Endings
buffer.view_eol = false
-- Caret and Selection Styles.
--buffer.sel_eol_filled = true
buffer.caret_line_visible = not CURSES and buffer ~= ui.command_entry
--buffer.caret_line_visible_always = true
--buffer.caret_period = 0
--buffer.caret_style = buffer.CARETSTYLE_BLOCK
--buffer.caret_width =
--buffer.caret_sticky = buffer.CARETSTICKY_ON
-- Margins.
--buffer.margin_left =
--buffer.margin_right =
-- Line Number Margin.
buffer.margin_type_n[0] = buffer.MARGIN_NUMBER
local width = 4 * buffer:text_width(buffer.STYLE_LINENUMBER, '9')
buffer.margin_width_n[0] = width + (not CURSES and 4 or 0)
-- Marker Margin.
buffer.margin_width_n[1] = not CURSES and 4 or 1
-- Fold Margin.
buffer.margin_width_n[2] = not CURSES and 12 or 1
buffer.margin_mask_n[2] = buffer.MASK_FOLDERS
-- Other Margins.
for i = 1, 4 do
buffer.margin_type_n[i] = buffer.MARGIN_SYMBOL
buffer.margin_sensitive_n[i] = true
buffer.margin_cursor_n[i] = buffer.CURSORARROW
if i > 2 then buffer.margin_width_n[i] = 0 end
end
-- Annotations.
buffer.annotation_visible = buffer.ANNOTATION_BOXED
-- Other.
buffer.buffered_draw = not CURSES and not OSX -- Quartz buffers drawing on OSX
--buffer.word_chars =
--buffer.whitespace_chars =
--buffer.punctuation_chars =
-- Tabs and Indentation Guides.
-- Note: tab and indentation settings apply to individual buffers.
buffer.tab_width = 2
buffer.use_tabs = false
--buffer.indent = 2
buffer.tab_indents = true
buffer.back_space_un_indents = true
buffer.indentation_guides = not CURSES and buffer.IV_LOOKBOTH or buffer.IV_NONE
-- Margin Markers.
buffer:marker_define(textadept.bookmarks.MARK_BOOKMARK, buffer.MARK_FULLRECT)
buffer:marker_define(textadept.run.MARK_WARNING, buffer.MARK_FULLRECT)
buffer:marker_define(textadept.run.MARK_ERROR, buffer.MARK_FULLRECT)
-- Arrow Folding Symbols.
--buffer:marker_define(buffer.MARKNUM_FOLDEROPEN, buffer.MARK_ARROWDOWN)
--buffer:marker_define(buffer.MARKNUM_FOLDER, buffer.MARK_ARROW)
--buffer:marker_define(buffer.MARKNUM_FOLDERSUB, buffer.MARK_EMPTY)
--buffer:marker_define(buffer.MARKNUM_FOLDERTAIL, buffer.MARK_EMPTY)
--buffer:marker_define(buffer.MARKNUM_FOLDEREND, buffer.MARK_EMPTY)
--buffer:marker_define(buffer.MARKNUM_FOLDEROPENMID, buffer.MARK_EMPTY)
--buffer:marker_define(buffer.MARKNUM_FOLDERMIDTAIL, buffer.MARK_EMPTY)
-- Plus/Minus Folding Symbols.
--buffer:marker_define(buffer.MARKNUM_FOLDEROPEN, buffer.MARK_MINUS)
--buffer:marker_define(buffer.MARKNUM_FOLDER, buffer.MARK_PLUS)
--buffer:marker_define(buffer.MARKNUM_FOLDERSUB, buffer.MARK_EMPTY)
--buffer:marker_define(buffer.MARKNUM_FOLDERTAIL, buffer.MARK_EMPTY)
--buffer:marker_define(buffer.MARKNUM_FOLDEREND, buffer.MARK_EMPTY)
--buffer:marker_define(buffer.MARKNUM_FOLDEROPENMID, buffer.MARK_EMPTY)
--buffer:marker_define(buffer.MARKNUM_FOLDERMIDTAIL, buffer.MARK_EMPTY)
-- Circle Tree Folding Symbols.
--buffer:marker_define(buffer.MARKNUM_FOLDEROPEN, buffer.MARK_CIRCLEMINUS)
--buffer:marker_define(buffer.MARKNUM_FOLDER, buffer.MARK_CIRCLEPLUS)
--buffer:marker_define(buffer.MARKNUM_FOLDERSUB, buffer.MARK_VLINE)
--buffer:marker_define(buffer.MARKNUM_FOLDERTAIL, buffer.MARK_LCORNERCURVE)
--buffer:marker_define(buffer.MARKNUM_FOLDEREND,
-- buffer.MARK_CIRCLEPLUSCONNECTED)
--buffer:marker_define(buffer.MARKNUM_FOLDEROPENMID,
-- buffer.MARK_CIRCLEMINUSCONNECTED)
--buffer:marker_define(buffer.MARKNUM_FOLDERMIDTAIL, buffer.MARK_TCORNERCURVE)
-- Box Tree Folding Symbols.
buffer:marker_define(buffer.MARKNUM_FOLDEROPEN, buffer.MARK_BOXMINUS)
buffer:marker_define(buffer.MARKNUM_FOLDER, buffer.MARK_BOXPLUS)
buffer:marker_define(buffer.MARKNUM_FOLDERSUB, buffer.MARK_VLINE)
buffer:marker_define(buffer.MARKNUM_FOLDERTAIL, buffer.MARK_LCORNER)
buffer:marker_define(buffer.MARKNUM_FOLDEREND, buffer.MARK_BOXPLUSCONNECTED)
buffer:marker_define(buffer.MARKNUM_FOLDEROPENMID,
buffer.MARK_BOXMINUSCONNECTED)
buffer:marker_define(buffer.MARKNUM_FOLDERMIDTAIL, buffer.MARK_TCORNER)
--buffer:marker_enable_highlight(true)
-- Indicators.
local INDIC_BRACEMATCH = textadept.editing.INDIC_BRACEMATCH
buffer.indic_style[INDIC_BRACEMATCH] = buffer.INDIC_BOX
buffer:brace_highlight_indicator(not CURSES, INDIC_BRACEMATCH)
local INDIC_HIGHLIGHT = textadept.editing.INDIC_HIGHLIGHT
buffer.indic_style[INDIC_HIGHLIGHT] = buffer.INDIC_ROUNDBOX
if not CURSES then buffer.indic_under[INDIC_HIGHLIGHT] = true end
-- Autocompletion.
--buffer.auto_c_separator =
--buffer.auto_c_cancel_at_start = false
--buffer.auto_c_fill_ups = '('
buffer.auto_c_choose_single = true
--buffer.auto_c_ignore_case = true
--buffer.auto_c_case_insensitive_behaviour =
-- buffer.CASEINSENSITIVEBEHAVIOUR_IGNORECASE
buffer.auto_c_multi = buffer.MULTIAUTOC_EACH
--buffer.auto_c_auto_hide = false
--buffer.auto_c_drop_rest_of_word = true
--buffer.auto_c_type_separator =
--buffer.auto_c_max_height =
--buffer.auto_c_max_width =
-- Call Tips.
buffer.call_tip_use_style = buffer.tab_width *
buffer:text_width(buffer.STYLE_CALLTIP, ' ')
--buffer.call_tip_position = true
-- Folding.
buffer.property['fold'] = '1'
--buffer.property['fold.by.indentation'] = '1'
--buffer.property['fold.line.comments'] = '1'
--buffer.property['fold.on.zero.sum.lines'] = '1'
buffer.automatic_fold = buffer.AUTOMATICFOLD_SHOW + buffer.AUTOMATICFOLD_CLICK +
buffer.AUTOMATICFOLD_CHANGE
buffer.fold_flags = not CURSES and buffer.FOLDFLAG_LINEAFTER_CONTRACTED or 0
-- Line Wrapping.
buffer.wrap_mode = buffer.WRAP_NONE
--buffer.wrap_visual_flags = buffer.WRAPVISUALFLAG_MARGIN
--buffer.wrap_visual_flags_location = buffer.WRAPVISUALFLAGLOC_END_BY_TEXT
--buffer.wrap_indent_mode = buffer.WRAPINDENT_SAME
--buffer.wrap_start_indent =
-- Long Lines.
--if buffer ~= ui.command_entry then
-- buffer.edge_mode = not CURSES and buffer.EDGE_LINE or buffer.EDGE_BACKGROUND
-- buffer.edge_column = 80
--end
| mit |
slowglass/Restacker | libs/LibAddonMenu-2.0/controls/editbox.lua | 5 | 6493 | --[[editboxData = {
type = "editbox",
name = "My Editbox", -- or string id or function returning a string
getFunc = function() return db.text end,
setFunc = function(text) db.text = text doStuff() end,
tooltip = "Editbox's tooltip text.", -- or string id or function returning a string (optional)
isMultiline = true, --boolean (optional)
isExtraWide = true, --boolean (optional)
width = "full", --or "half" (optional)
disabled = function() return db.someBooleanSetting end, --or boolean (optional)
warning = "May cause permanent awesomeness.", -- or string id or function returning a string (optional)
requiresReload = false, -- boolean, if set to true, the warning text will contain a notice that changes are only applied after an UI reload and any change to the value will make the "Apply Settings" button appear on the panel which will reload the UI when pressed (optional)
default = defaults.text, -- default value or function that returns the default value (optional)
reference = "MyAddonEditbox" -- unique global reference to control (optional)
} ]]
local widgetVersion = 14
local LAM = LibStub("LibAddonMenu-2.0")
if not LAM:RegisterWidget("editbox", widgetVersion) then return end
local wm = WINDOW_MANAGER
local function UpdateDisabled(control)
local disable
if type(control.data.disabled) == "function" then
disable = control.data.disabled()
else
disable = control.data.disabled
end
if disable then
control.label:SetColor(ZO_DEFAULT_DISABLED_COLOR:UnpackRGBA())
control.editbox:SetColor(ZO_DEFAULT_DISABLED_MOUSEOVER_COLOR:UnpackRGBA())
else
control.label:SetColor(ZO_DEFAULT_ENABLED_COLOR:UnpackRGBA())
control.editbox:SetColor(ZO_DEFAULT_ENABLED_COLOR:UnpackRGBA())
end
--control.editbox:SetEditEnabled(not disable)
control.editbox:SetMouseEnabled(not disable)
end
local function UpdateValue(control, forceDefault, value)
if forceDefault then --if we are forcing defaults
value = LAM.util.GetDefaultValue(control.data.default)
control.data.setFunc(value)
control.editbox:SetText(value)
elseif value then
control.data.setFunc(value)
--after setting this value, let's refresh the others to see if any should be disabled or have their settings changed
LAM.util.RequestRefreshIfNeeded(control)
else
value = control.data.getFunc()
control.editbox:SetText(value)
end
end
local MIN_HEIGHT = 24
local HALF_WIDTH_LINE_SPACING = 2
function LAMCreateControl.editbox(parent, editboxData, controlName)
local control = LAM.util.CreateLabelAndContainerControl(parent, editboxData, controlName)
local container = control.container
control.bg = wm:CreateControlFromVirtual(nil, container, "ZO_EditBackdrop")
local bg = control.bg
bg:SetAnchorFill()
if editboxData.isMultiline then
control.editbox = wm:CreateControlFromVirtual(nil, bg, "ZO_DefaultEditMultiLineForBackdrop")
control.editbox:SetHandler("OnMouseWheel", function(self, delta)
if self:HasFocus() then --only set focus to new spots if the editbox is currently in use
local cursorPos = self:GetCursorPosition()
local text = self:GetText()
local textLen = text:len()
local newPos
if delta > 0 then --scrolling up
local reverseText = text:reverse()
local revCursorPos = textLen - cursorPos
local revPos = reverseText:find("\n", revCursorPos+1)
newPos = revPos and textLen - revPos
else --scrolling down
newPos = text:find("\n", cursorPos+1)
end
if newPos then --if we found a new line, then scroll, otherwise don't
self:SetCursorPosition(newPos)
end
end
end)
else
control.editbox = wm:CreateControlFromVirtual(nil, bg, "ZO_DefaultEditForBackdrop")
end
local editbox = control.editbox
editbox:SetText(editboxData.getFunc())
editbox:SetMaxInputChars(3000)
editbox:SetHandler("OnFocusLost", function(self) control:UpdateValue(false, self:GetText()) end)
editbox:SetHandler("OnEscape", function(self) self:LoseFocus() control:UpdateValue(false, self:GetText()) end)
editbox:SetHandler("OnMouseEnter", function() ZO_Options_OnMouseEnter(control) end)
editbox:SetHandler("OnMouseExit", function() ZO_Options_OnMouseExit(control) end)
local MIN_WIDTH = (parent.GetWidth and (parent:GetWidth() / 10)) or (parent.panel.GetWidth and (parent.panel:GetWidth() / 10)) or 0
control.label:ClearAnchors()
container:ClearAnchors()
control.label:SetAnchor(TOPLEFT, control, TOPLEFT, 0, 0)
container:SetAnchor(BOTTOMRIGHT, control, BOTTOMRIGHT, 0, 0)
if control.isHalfWidth then
container:SetAnchor(BOTTOMRIGHT, control, BOTTOMRIGHT, 0, 0)
end
if editboxData.isExtraWide then
container:SetAnchor(BOTTOMLEFT, control, BOTTOMLEFT, 0, 0)
else
container:SetWidth(MIN_WIDTH * 3.2)
end
if editboxData.isMultiline then
container:SetHeight(MIN_HEIGHT * 3)
else
container:SetHeight(MIN_HEIGHT)
end
if control.isHalfWidth ~= true and editboxData.isExtraWide ~= true then
control:SetHeight(container:GetHeight())
else
control:SetHeight(container:GetHeight() + control.label:GetHeight())
end
editbox:ClearAnchors()
editbox:SetAnchor(TOPLEFT, container, TOPLEFT, 2, 2)
editbox:SetAnchor(BOTTOMRIGHT, container, BOTTOMRIGHT, -2, -2)
if editboxData.warning ~= nil or editboxData.requiresReload then
control.warning = wm:CreateControlFromVirtual(nil, control, "ZO_Options_WarningIcon")
if editboxData.isExtraWide then
control.warning:SetAnchor(BOTTOMRIGHT, control.bg, TOPRIGHT, 2, 0)
else
control.warning:SetAnchor(TOPRIGHT, control.bg, TOPLEFT, -5, 0)
end
control.UpdateWarning = LAM.util.UpdateWarning
control:UpdateWarning()
end
control.UpdateValue = UpdateValue
control:UpdateValue()
if editboxData.disabled ~= nil then
control.UpdateDisabled = UpdateDisabled
control:UpdateDisabled()
end
LAM.util.RegisterForRefreshIfNeeded(control)
LAM.util.RegisterForReloadIfNeeded(control)
return control
end
| mit |
Native-Software/Krea | CoronaGameEditor/bin/Release/Lua Repository/object.lua | 3 | 15978 | --- This module is provided as it by Native-Software for use into a Krea project.
-- @author Frederic Raimondi
-- @copyright Native-Software 2012 - All Rights Reserved.
-- @release 1.0
-- @description Object is a generic class to create a corona display object.
-- <br>Changing the content of this file is at your own risk.
-- As the software Krea uses this file to auto-generate code, it can create errors during generation if you change his content.</br>
module("object", package.seeall)
---
-- Members of the Object Instance
-- @class table
-- @name Fields
-- @field name The name of the object instance
-- @field object The Corona display object of the object instance
-- @field displayGroupParent The display group where is stored the display object
-- @field params The table params used to create the object instance
-- @field type The display object type of the object instance
-- @field xOrigin The x origin location of the object instance
-- @field yOrigin The y origin location of the object instance
-- @field hasBody Boolean that indicates whether the display object has a physics body or not
Object = {}
Object.__index = Object
---
-- @description Create a new Object Instance
-- @return Return a new Object Instance
-- @param params Lua Table containing the params
-- @usage Usage to create a Rectangle:
-- <ul>
-- <li><code>local params = {}
-- <br>params.name = "name"
-- <br>params.type = "RECTANGLE"
-- <br>params.isRounded = true
-- <br>params.cornerRadius = 5
-- <br>params.x = -50
-- <br>params.y = background.contentWidth *(0.5)
-- <br>params.width = 100
-- <br>params.height = 10
-- <br>params.displayGroupParent = layer1
-- <br>params.alpha = 0.1
-- <br>params.backColor = { R = 0,G = 0,B = 250}
-- <br>params.strokeColor = { R = 0,G = 0,B = 250}
-- <br>params.strokeWidth = 2
-- <li> local rectangleInstance = require("object").Object.create(params)</code></li>
-- </ul>
-- <br>Usage to create a Circle:
-- <ul>
-- <li><code>local params = {}
-- <br>params.name = "name"
-- <br>params.type = "CIRCLE"
-- <br>params.x = -50
-- <br>params.y = background.contentWidth *(0.5)
-- <br>params.radius = 100
-- <br>params.displayGroupParent = layer1
-- <br>params.alpha = 0.1
-- <br>params.backColor = { R = 0,G = 0,B = 250}
-- <br>params.strokeColor = { R = 0,G = 0,B = 250}
-- <br>params.strokeWidth = 2
-- <li> local circleInstance = require("object").Object.create(params)</code></li>
-- </ul>
-- <br>Usage to create a Line:
-- <ul>
-- <li><code>local params = {}
-- <br>params.name = "name"
-- <br>params.type = "LINE"
-- <br>params.x1 = -50
-- <br>params.y1 = 100
-- <br>params.x2 = -200
-- <br>params.y2 = 100
-- <br>params.displayGroupParent = layer1
-- <br>params.alpha = 0.1
-- <br>params.backColor = { R = 0,G = 0,B = 250}
-- <br>params.strokeWidth = 2
-- <li> local lineInstance = require("object").Object.create(params)</code></li>
-- </ul>
-- <br>Usage to create an Image:
-- <ul>
-- <li><code>local params = {}
-- <br>params.name = "name"
-- <br>params.type = "IMAGE"
-- <br>params.x = -50
-- <br>params.y = background.contentWidth *(0.5)
-- <br>params.width = 100
-- <br>params.height = 10
-- <br>params.displayGroupParent = layer1
-- <br>params.alpha = 0.1
-- <br>params.pathImage = "objet.png"
-- <li> local imageInstance = require("object").Object.create(params)</code></li>
-- </ul>
-- <br>Usage to create a Sprite:
-- <ul>
-- <li><code>local params = {}
-- <br>params.name = "name"
-- <br>params.type = "SPRITE"
-- <br>params.x = -50
-- <br>params.y = background.contentWidth *(0.5)
-- <br>params.spriteSet = spriteSet
-- <br>params.displayGroupParent = layer1
-- <br>params.alpha = 0.1
-- <li> local spriteInstance = require("object").Object.create(params)</code></li>
-- </ul>
-- <br>Usage to create a Curve:
-- <ul>
-- <li><code>local params = {}
-- <br>params.name = "name"
-- <br>params.type = "CURVE"
-- <br>params.tabPoints = {x1,y1,x2,y2,...}
-- <br>params.displayGroupParent = layer1
-- <br>params.alpha = 0.1
-- <br>params.strokeColor = { R = 0,G = 0,B = 250}
-- <br>params.strokeWidth = 2
-- <li> local curveInstance = require("object").Object.create(params)</code></li>
-- </ul>
-- <br>Usage to create a Text:
-- <ul>
-- <li><code>local params = {}
-- <br>params.name = "name"
-- <br>params.type = "TEXT"
-- <br>params.x = -50
-- <br>params.y = background.contentWidth *(0.5)
-- <br>params.displayGroupParent = layer1
-- <br>params.text = "text"
-- <br>params.alpha = 0.1
-- <br>params.textColor = { R = 0,G = 0,B = 250}
-- <br>params.textSize = 2
-- <li> local curveInstance = require("object").Object.create(params)</code></li>
-- </ul>
function Object.create(params)
--Init attributes of instance
local object = {}
setmetatable(object,Object)
--Init attributes
object.name = params.name
object.displayGroupParent = params.displayGroupParent
object.params = params
object.type = params.type
object.isStarted = false
object.listEvents = {}
object.isHandledByTilesMap = params.isHandledByTilesMap
object.entityParent = params.entityParent
object.autoPlay = params.autoPlay
local xDest = params.x
local yDest =params.y
--Check if pathImage initalized
if(params.type == "IMAGE") then
--Create obj from an image
object.object = display.newImageRect(params.pathImage,params.width,
params.height)
object.object:setReferencePoint(display.TopLeftReferencePoint)
object.object.x = xDest
object.object.y = yDest
elseif(params.type == "SPRITE") then
-- Create a Sprite From spriteSet
object.object = sprite.newSprite(params.spriteSet)
object.object:setReferencePoint(display.TopLeftReferencePoint)
object.object.x = xDest - (object.object.contentWidth/2) *(1-params.scale)
object.object.y = yDest - (object.object.contentHeight/2) *(1 -params.scale)
if(params.scale) then
object.object:scale(params.scale,params.scale)
end
object.currentSequence = params.sequenceName
object.firstFrameIndex = params.firstFrameIndex
object.object:prepare(object.currentSequence)
if(object.firstFrameIndex) then
object.object.currentFrame = object.firstFrameIndex
end
elseif(params.type == "RECTANGLE") then
if(params.isRounded == true) then
--Create a rounded rect with expected colors
object.object = display.newRoundedRect(params.x,params.y,params.width,
params.height,params.cornerRadius)
else
--Create a rect with expected colors
object.object = display.newRect(params.x,params.y,params.width,
params.height)
end
if(params.backColor) then
object.object:setFillColor(params.backColor.R,params.backColor.G,params.backColor.B)
end
if(params.strokeColor) then
object.object:setStrokeColor(params.strokeColor.R,params.strokeColor.G,params.strokeColor.B)
end
if(params.strokeWidth) then
object.object.strokeWidth = params.strokeWidth
end
if(params.gradient) then
local g = graphics.newGradient(params.gradient[1],params.gradient[2],params.gradient[3])
object.object:setFillColor(g)
end
object.object:setReferencePoint(display.TopLeftReferencePoint)
object.object.x = xDest
object.object.y = yDest
elseif(params.type == "CIRCLE") then
--Create a Circle with expected colors
object.object = display.newCircle(params.x + params.radius
,params.y +params.radius
,params.radius)
if(params.backColor) then
object.object:setFillColor(params.backColor.R,params.backColor.G,params.backColor.B)
end
if(params.strokeColor) then
object.object:setStrokeColor(params.strokeColor.R,params.strokeColor.G,params.strokeColor.B)
end
if(params.strokeWidth) then
object.object.strokeWidth = params.strokeWidth
end
elseif(params.type == "CURVE" or params.type == "LINE") then
if(#params.tabPoints >3) then
--Create a first line
object.object = display.newLine(params.tabPoints[1],
params.tabPoints[2],
params.tabPoints[3],
params.tabPoints[4])
object.object:setReferencePoint(display.TopLeftReferencePoint)
for i = 5, #params.tabPoints, 2 do
object.object:append(params.tabPoints[i],params.tabPoints[i+1])
end
if(params.backColor) then
object.object:setColor(params.backColor.R,params.backColor.G,params.backColor.B)
end
if(params.strokeWidth) then
object.object.width = params.strokeWidth
end
object.object:setReferencePoint(display.TopLeftReferencePoint)
end
elseif(params.type == "TEXT") then
local finalText = rosetta:getString(params.text)
if(finalText == nil or finalText =="NO STRING") then finalText = params.text end
if(params.textFont and params.textFont ~= "DEFAULT") then
local onSimulator = system.getInfo( "environment" ) == "simulator" or system.getInfo("platformName") == "Android"
local platformVersion = system.getInfo( "platformVersion" )
local olderVersion = tonumber(string.sub( platformVersion, 1, 1 )) < 4
local fontName = params.textFont
local fontSize = params.textSize
-- if on older device (and not on simulator) ...
if not onSimulator and olderVersion then
if string.sub( platformVersion, 1, 3 ) ~= "3.2" then
fontName = native.systemFont
fontSize = 22
end
end
object.object = display.newText(finalText,params.x,params.y,params.width,params.height,fontName,fontSize)
else
object.object = display.newText(finalText,params.x,params.y,params.width,params.height,native.systemFont,params.textSize)
end
object.text = finalText
if(params.textColor) then
object.object:setTextColor(params.textColor.R, params.textColor.G, params.textColor.B)
end
if(params.gradient) then
local g = graphics.newGradient(params.gradient[1],params.gradient[2],params.gradient[3])
object.object:setTextColor(g)
end
object.object:setReferencePoint(display.TopLeftReferencePoint)
object.object.x = xDest
object.object.y = yDest
end
if(params.alpha) then
object.object.alpha = params.alpha
end
if(params.blendMode) then
object.object.blendMode = params.blendMode
end
if(params.indexInGroup) then
object.displayGroupParent:insert(params.indexInGroup,object.object)
else
object.displayGroupParent:insert(object.object)
end
object.object.getInstance = function()
return object
end
object.object:setReferencePoint(display.CenterReferencePoint)
object.xOrigin = object.object.x
object.yOrigin = object.object.y
if(params.rotation) then
object.object.rotation = params.rotation
end
object.isDraggable = params.isDraggable
object.dragMaxForce = params.dragMaxForce
object.dragDamping = params.dragDamping
object.dragFrequency = params.dragFrequency
object.dragBody = params.dragBody
object.isLocked = false
object.hasBody = false
return object
end
---
-- @description Clone the instance of this object
-- @return Object The new clone of the object
-- @usage Usage:
-- <ul>
-- <li><code>objectInstance:clone()</code></li>
-- </ul>
function Object:clone(insertCloneAtEndOfGroup)
if(insertCloneAtEndOfGroup) then
self.params.indexInGroup = nil
else
local index = self:getIndexInGroup()
self.params.indexInGroup = index +1
end
local obj = Object.create(self.params)
if(self.hasBody == true) then
local body = require("body"..string.lower(obj.name)).startBody(obj)
end
obj.currentSequence = self.currentSequence
if(self.pathFollow) then
local params = self.pathFollow.params
params.targetObject = obj
obj.pathFollow = require("pathfollow").PathFollow.create(params)
end
return obj
end
function Object:getIndexInGroup()
if(self.displayGroupParent) then
for i = 1,self.displayGroupParent.numChildren do
local child = self.displayGroupParent[i]
if(child == self.object) then
return i
end
end
end
return 1
end
---
-- @description Clean the current object Instance
-- @usage Usage:
-- <ul>
-- <li><code>objectInstance:clean()</li>
-- <li>objectInstance = nil</code></li>
-- </ul>
function Object:clean()
if(not self.isDestroyed) then
self.isDestroyed = true
if(self.onDelete) then
self.onDelete()
end
if(self.pathFollow) then
self.pathFollow:pause()
self.pathFollow = nil
end
--Init attributes
self.name = nil
self.displayGroupParent = nil
self.params = nil
self.isStarted = nil
self.listEvents = nil
if(self.object.removeSelf) then
self.object:removeSelf()
end
end
end
function Object:createEventListener(event)
if(self.object) then
table.insert(self.listEvents,event)
self.object:addEventListener(event.eventType,event.handle)
end
end
function Object:removeEventListener(eventName)
if(self.object) then
for i = 1,#self.listEvents do
local child = self.listEvents[i]
if(child) then
if(child.eventName == eventName) then
table.remove(self.listEvents,i)
self.object:removeEventListener(child.eventType,child.handle)
child = nil
return
end
end
end
end
end
function Object:createPhysics(mode,params)
if(self.object) then
if(params) then
physics.addBody(self.object,mode,params)
else
physics.addBody(self.object,mode)
end
end
end
---
-- @description Set the object behaviour at start Interaction
-- @param handle Handle function
-- @usage Usage:
-- <ul>
-- <li><code>objectInstance:setOnStartBehaviour(handle)</code></li>
-- </ul>
function Object:setOnStartBehaviour(handle)
self.onStart = handle
end
---
-- @description Set the object behaviour at pause Interaction
-- @param handle Handle function
-- @usage Usage:
-- <ul>
-- <li><code>objectInstance:setOnPauseBehaviour(handle)</code></li>
-- </ul>
function Object:setOnPauseBehaviour(handle)
self.onPause = handle
end
---
-- @description Set the object behaviour at clean
-- @param handle Handle function
-- @usage Usage:
-- <ul>
-- <li><code>objectInstance:setOnDeleteBehaviour(handle)</code></li>
-- </ul>
function Object:setOnDeleteBehaviour(handle)
self.onDelete = handle
end
---
-- @description Start the interactions of the object
-- @usage Usage:
-- <ul>
-- <li><code>objectInstance:startInteractions()</code></li>
-- </ul>
function Object:startInteractions()
if(self.isLocked == false) then
if(self.object.removeSelf) then
self.object.isBodyActive = true
end
if(self.isStarted == false) then
if(self.onStart) then self.onStart()end
self.isStarted = true
if(self.isDraggable == true and self.dragBody) then
self.object:addEventListener("touch",self.dragBody)
end
if(self.type == "SPRITE") then
if(self.autoPlay == true) then
self.object:play()
end
end
if(self.pathFollow) then
self.pathFollow:start()
end
end
self:updateDisplay()
end
end
---
-- @description Update the display of the current display object. Example: To update the text content of a text object once the current language has been changed.
-- @usage Usage:
-- <ul>
-- <li><code>objectInstance:updateDisplay()</code></li>
-- </ul>
function Object:updateDisplay()
--Actualise the text of the object
if(self.type == "TEXT") then
local finalText = rosetta:getString(self.object.text)
if(finalText == nil or finalText =="NO STRING") then finalText = self.object.text end
self.object.text = finalText
end
end
---
-- @description Pause the interactions of the object
-- @usage Usage:
-- <ul>
-- <li><code>objectInstance:pauseInteractions()</code></li>
-- </ul>
function Object:pauseInteractions()
if(self.object.removeSelf) then
self.object.isBodyActive = false
end
if(self.isStarted == true) then
if(self.onPause) then self.onPause() end
self.isStarted = false
if(self.isDraggable == true and self.dragBody) then
self.object:removeEventListener("touch",self.dragBody)
end
if(self.type == "SPRITE") then
if(self.currentSequence) then
self.object:pause()
end
end
if(self.pathFollow) then
self.pathFollow:pause()
end
end
end
| gpl-2.0 |
ImagicTheCat/vRP | vrp/modules/group.lua | 1 | 10789 | -- https://github.com/ImagicTheCat/vRP
-- MIT license (see LICENSE or vrp/vRPShared.lua)
if not vRP.modules.group then return end
local lang = vRP.lang
-- this module define the group/permission system (per character)
-- multiple groups can be set to the same player, but the gtype config option can be used to set some groups as unique
local Group = class("Group", vRP.Extension)
-- SUBCLASS
Group.User = class("User")
function Group.User:hasGroup(name)
return self.cdata.groups[name] ~= nil
end
-- return map of groups
function Group.User:getGroups()
return self.cdata.groups
end
function Group.User:addGroup(name)
if not self:hasGroup(name) then
local groups = self:getGroups()
local cfg = vRP.EXT.Group.cfg
local ngroup = cfg.groups[name]
if ngroup then
if ngroup._config and ngroup._config.gtype ~= nil then
-- copy group list to prevent iteration while removing
local _groups = {}
for k,v in pairs(groups) do
_groups[k] = v
end
for k,v in pairs(_groups) do -- remove all groups with the same gtype
local kgroup = cfg.groups[k]
if kgroup and kgroup._config and ngroup._config and kgroup._config.gtype == ngroup._config.gtype then
self:removeGroup(k)
end
end
end
-- add group
groups[name] = true
if ngroup._config and ngroup._config.onjoin then
ngroup._config.onjoin(self) -- call join callback
end
-- trigger join event
local gtype = nil
if ngroup._config then
gtype = ngroup._config.gtype
end
vRP:triggerEvent("playerJoinGroup", self, name, gtype)
end
end
end
function Group.User:removeGroup(name)
local groups = self:getGroups()
local cfg = vRP.EXT.Group.cfg
local group = cfg.groups[name]
if group and group._config and group._config.onleave then
group._config.onleave(self) -- call leave callback
end
-- trigger leave event
local gtype = nil
if group and group._config then
gtype = group._config.gtype
end
groups[name] = nil -- remove reference
vRP:triggerEvent("playerLeaveGroup", self, name, gtype)
end
-- get user group by type
-- return group name or nil
function Group.User:getGroupByType(gtype)
local groups = self:getGroups()
local cfg = vRP.EXT.Group.cfg
for k,v in pairs(groups) do
local kgroup = cfg.groups[k]
if kgroup then
if kgroup._config and kgroup._config.gtype and kgroup._config.gtype == gtype then
return k
end
end
end
end
-- check if the user has a specific permission
function Group.User:hasPermission(perm)
local fchar = string.sub(perm,1,1)
if fchar == "!" then -- special function permission
local _perm = string.sub(perm,2,string.len(perm))
local params = splitString(_perm,".")
if #params > 0 then
local fperm = vRP.EXT.Group.func_perms[params[1]]
if fperm then
return fperm(self, params) or false
else
return false
end
end
else -- regular plain permission
local cfg = vRP.EXT.Group.cfg
local groups = self:getGroups()
-- precheck negative permission
local nperm = "-"..perm
for name in pairs(groups) do
local group = cfg.groups[name]
if group then
for l,w in pairs(group) do -- for each group permission
if l ~= "_config" and w == nperm then return false end
end
end
end
-- check if the permission exists
for name in pairs(groups) do
local group = cfg.groups[name]
if group then
for l,w in pairs(group) do -- for each group permission
if l ~= "_config" and w == perm then return true end
end
end
end
end
return false
end
-- check if the user has a specific list of permissions (all of them)
function Group.User:hasPermissions(perms)
for _,perm in pairs(perms) do
if not self:hasPermission(perm) then
return false
end
end
return true
end
-- PRIVATE METHODS
-- menu: group_selector
local function menu_group_selector(self)
local function m_select(menu, group_name)
local user = menu.user
user:addGroup(group_name)
user:closeMenu(menu)
end
vRP.EXT.GUI:registerMenuBuilder("group_selector", function(menu)
menu.title = menu.data.name
menu.css.header_color = "rgba(255,154,24,0.75)"
for k,group_name in pairs(menu.data.groups) do
if k ~= "_config" then
local title = self:getGroupTitle(group_name)
if title then
menu:addOption(title, m_select, nil, group_name)
end
end
end
end)
end
-- menu: admin users user
local function menu_admin_users_user(self)
local function m_groups(menu, value, mod, index)
local user = menu.user
local tuser = vRP.users[menu.data.id]
local groups = ""
if tuser and tuser:isReady() then
for group in pairs(tuser.cdata.groups) do
groups = groups..group.." "
end
end
menu:updateOption(index, nil, lang.admin.users.user.groups.description({groups}))
end
local function m_addgroup(menu)
local user = menu.user
local tuser = vRP.users[menu.data.id]
if tuser then
local group = user:prompt(lang.admin.users.user.group_add.prompt(),"")
tuser:addGroup(group)
end
end
local function m_removegroup(menu)
local user = menu.user
local tuser = vRP.users[menu.data.id]
if tuser then
local group = user:prompt(lang.admin.users.user.group_remove.prompt(),"")
tuser:removeGroup(group)
end
end
vRP.EXT.GUI:registerMenuBuilder("admin.users.user", function(menu)
local user = menu.user
local tuser = vRP.users[menu.data.id]
if tuser then
menu:addOption(lang.admin.users.user.groups.title(), m_groups, lang.admin.users.user.groups.description())
if user:hasPermission("player.group.add") then
menu:addOption(lang.admin.users.user.group_add.title(), m_addgroup)
end
if user:hasPermission("player.group.remove") then
menu:addOption(lang.admin.users.user.group_remove.title(), m_removegroup)
end
end
end)
end
-- METHODS
function Group:__construct()
vRP.Extension.__construct(self)
self.cfg = module("cfg/groups")
self.func_perms = {}
-- register not fperm (negate another fperm)
self:registerPermissionFunction("not", function(user, params)
return not user:hasPermission("!"..table.concat(params, ".", 2))
end)
-- register group fperm
self:registerPermissionFunction("group", function(user, params)
local group = params[2]
if group then
return user:hasGroup(group)
end
return false
end)
-- menu
menu_group_selector(self)
menu_admin_users_user(self)
-- identity gtypes display
vRP.EXT.GUI:registerMenuBuilder("identity", function(menu)
local tuser = vRP.users_by_cid[menu.data.cid]
if tuser then
for gtype, title in pairs(self.cfg.identity_gtypes) do
local group_name = tuser:getGroupByType(gtype)
if group_name then
local gtitle = self:getGroupTitle(group_name)
if gtitle then
menu:addOption(title, nil, gtitle)
end
end
end
end
end)
-- task: group count display
if next(self.cfg.count_display_permissions) then
Citizen.CreateThread(function()
while true do
Citizen.Wait(self.cfg.count_display_interval*1000)
-- display
local content = ""
for _, dperm in ipairs(self.cfg.count_display_permissions) do
local count = #self:getUsersByPermission(dperm[1])
local img = dperm[2]
content = content.."<div><img src=\""..img.."\" />"..count.."</div>"
end
vRP.EXT.GUI.remote.setDivContent(-1, "group_count_display", content)
end
end)
end
end
-- return users list
function Group:getUsersByGroup(name)
local users = {}
for _,user in pairs(vRP.users) do
if user:isReady() and user:hasGroup(name) then
table.insert(users, user)
end
end
return users
end
-- return users list
function Group:getUsersByPermission(perm)
local users = {}
for _,user in pairs(vRP.users) do
if user:isReady() and user:hasPermission(perm) then
table.insert(users, user)
end
end
return users
end
-- return title or nil
function Group:getGroupTitle(group_name)
local group = self.cfg.groups[group_name]
if group and group._config then
return group._config.title
end
end
-- register a special permission function
-- name: name of the permission -> "!name.[...]"
-- callback(user, params)
--- params: params (strings) of the permissions, ex "!name.param1.param2" -> ["name", "param1", "param2"]
--- should return true or false/nil
function Group:registerPermissionFunction(name, callback)
if self.func_perms[name] then
self:log("WARNING: re-registered permission function \""..name.."\"")
end
self.func_perms[name] = callback
end
-- EVENT
Group.event = {}
function Group.event:playerSpawn(user, first_spawn)
if first_spawn then
-- init group selectors
for k,v in pairs(self.cfg.selectors) do
local gcfg = v._config
if gcfg then
local x = gcfg.x
local y = gcfg.y
local z = gcfg.z
local menu
local function enter(user)
if user:hasPermissions(gcfg.permissions or {}) then
menu = user:openMenu("group_selector", {name = k, groups = v})
end
end
local function leave(user)
if menu then
user:closeMenu(menu)
end
end
local ment = clone(gcfg.map_entity)
ment[2].title = k
ment[2].pos = {x,y,z-1}
vRP.EXT.Map.remote._addEntity(user.source, ment[1], ment[2])
user:setArea("vRP:gselector:"..k,x,y,z,1,1.5,enter,leave)
end
end
-- group count display
if next(self.cfg.count_display_permissions) then
if self.cfg.display then
vRP.EXT.GUI.remote.setDiv(user.source, "group_count_display", self.cfg.count_display_css, "")
end
end
end
-- call group onspawn callback at spawn
local groups = user:getGroups()
for name in pairs(groups) do
local group = self.cfg.groups[name]
if group and group._config and group._config.onspawn then
group._config.onspawn(user)
end
end
end
function Group.event:characterLoad(user)
if not user.cdata.groups then -- init groups table
user.cdata.groups = {}
end
-- add config user forced groups
local groups = self.cfg.users[user.id]
if groups then
for _,group in ipairs(groups) do
user:addGroup(group)
end
end
-- add default groups
for _, group in ipairs(self.cfg.default_groups) do
user:addGroup(group)
end
end
vRP:registerExtension(Group)
| mit |
GraphicGame/quick-ejoy2d | examples/asset/particle.lua | 22 | 6848 | return {
{
component = {
{id = 3},
{name = "fire"},
{name = "ice"}
},
export = "fire",
type = "animation",
id = 0,
{
{ {
index = 0
}, {
color = 0xffffffff,
index = 1,
add = 0x00,
mat = {1024,0,0,2048,2208,80}
}},
{ {
index = 0
}, {
color = 0xffffffff,
index = 1,
add = 0x00,
mat = {1024,0,0,2048,2152,78}
}},
{ {
index = 0
}, {
color = 0xffffffff,
index = 1,
add = 0x00,
mat = {1024,0,0,2048,2097,76}
}},
{ {
index = 0
}, {
color = 0xffffffff,
index = 1,
add = 0x00,
mat = {1024,0,0,2048,2042,74}
}},
{ {
index = 0
}, {
color = 0xffffffff,
index = 1,
add = 0x00,
mat = {1024,0,0,2048,1986,72}
}},
{ {
index = 0
}, {
color = 0xffffffff,
index = 1,
add = 0x00,
mat = {1024,0,0,2048,1931,70}
}},
{ {
index = 0
}, {
color = 0xffffffff,
index = 1,
add = 0x00,
mat = {1024,0,0,2048,1876,69}
}},
{ {
index = 0
}, {
color = 0xffffffff,
index = 1,
add = 0x00,
mat = {1024,0,0,2048,1820,67}
}},
{ {
index = 0
}, {
color = 0xffffffff,
index = 1,
add = 0x00,
mat = {1024,0,0,2048,1765,65}
}},
{ {
index = 0
}, {
color = 0xffffffff,
index = 1,
add = 0x00,
mat = {1024,0,0,2048,1710,63}
}},
{ {
index = 0
}, {
color = 0xffffffff,
index = 1,
add = 0x00,
mat = {1024,0,0,2048,1654,61}
}, {
color = 0xffffffff,
index = 2,
add = 0x00,
mat = {1024,0,0,1024,-672,688}
}},
{ {
index = 0
}, {
color = 0xffffffff,
index = 1,
add = 0x00,
mat = {1024,0,0,2048,1599,59}
}, {
color = 0xffffffff,
index = 2,
add = 0x00,
mat = {955,0,0,1024,-661,852}
}},
{ {
index = 0
}, {
color = 0xffffffff,
index = 1,
add = 0x00,
mat = {1024,0,0,2048,1544,58}
}, {
color = 0xffffffff,
index = 2,
add = 0x00,
mat = {887,0,0,1024,-650,1016}
}},
{ {
index = 0
}, {
color = 0xffffffff,
index = 1,
add = 0x00,
mat = {1024,0,0,2048,1488,56}
}, {
color = 0xffffffff,
index = 2,
add = 0x00,
mat = {819,0,0,1024,-640,1180}
}},
{ {
index = 0
}, {
color = 0xffffffff,
index = 1,
add = 0x00,
mat = {1024,0,0,2048,1433,54}
}, {
color = 0xffffffff,
index = 2,
add = 0x00,
mat = {750,0,0,1024,-629,1344}
}},
{ {
index = 0
}, {
color = 0xffffffff,
index = 1,
add = 0x00,
mat = {1024,0,0,2048,1378,52}
}, {
color = 0xffffffff,
index = 2,
add = 0x00,
mat = {682,0,0,1024,-618,1508}
}},
{ {
index = 0
}, {
color = 0xffffffff,
index = 1,
add = 0x00,
mat = {1024,0,0,2048,1322,50}
}, {
color = 0xffffffff,
index = 2,
add = 0x00,
mat = {614,0,0,1024,-608,1672}
}},
{ {
index = 0
}, {
color = 0xffffffff,
index = 1,
add = 0x00,
mat = {1024,0,0,2048,1267,48}
}, {
color = 0xffffffff,
index = 2,
add = 0x00,
mat = {546,0,0,1024,-597,1836}
}},
{ {
index = 0
}, {
color = 0xffffffff,
index = 1,
add = 0x00,
mat = {1024,0,0,2048,1212,47}
}, {
color = 0xffffffff,
index = 2,
add = 0x00,
mat = {477,0,0,1024,-586,2000}
}},
{ {
index = 0
}, {
color = 0xffffffff,
index = 1,
add = 0x00,
mat = {1024,0,0,2048,1157,45}
}, {
color = 0xffffffff,
index = 2,
add = 0x00,
mat = {409,0,0,1024,-576,2164}
}},
{ {
index = 0
}, {
color = 0xffffffff,
index = 1,
add = 0x00,
mat = {1024,0,0,2048,1101,43}
}, {
color = 0xffffffff,
index = 2,
add = 0x00,
mat = {341,0,0,1024,-565,2328}
}},
{ {
index = 0
}, {
color = 0xffffffff,
index = 1,
add = 0x00,
mat = {1024,0,0,2048,1046,41}
}, {
color = 0xffffffff,
index = 2,
add = 0x00,
mat = {273,0,0,1024,-554,2492}
}},
{ {
index = 0
}, {
color = 0xffffffff,
index = 1,
add = 0x00,
mat = {1024,0,0,2048,991,39}
}, {
color = 0xffffffff,
index = 2,
add = 0x00,
mat = {204,0,0,1024,-544,2656}
}},
{ {
index = 0
}, {
color = 0xffffffff,
index = 1,
add = 0x00,
mat = {1024,0,0,2048,935,37}
}},
{ {
index = 0
}, {
color = 0xffffffff,
index = 1,
add = 0x00,
mat = {1024,0,0,2048,880,36}
}},
{ {
index = 0
}, {
color = 0xffffffff,
index = 1,
add = 0x00,
mat = {1024,0,0,2048,825,34}
}},
{ {
index = 0
}, {
color = 0xffffffff,
index = 1,
add = 0x00,
mat = {1024,0,0,2048,769,32}
}},
{ {
index = 0
}, {
color = 0xffffffff,
index = 1,
add = 0x00,
mat = {1024,0,0,2048,714,30}
}},
{ {
index = 0
}, {
color = 0xffffffff,
index = 1,
add = 0x00,
mat = {1024,0,0,2048,659,28}
}},
{ {
index = 0
}, {
color = 0xffffffff,
index = 1,
add = 0x00,
mat = {1024,0,0,2048,603,26}
}},
{ {
index = 0
}, {
color = 0xffffffff,
index = 1,
add = 0x00,
mat = {1024,0,0,2048,548,25}
}},
{ {
index = 0
}, {
color = 0xffffffff,
index = 1,
add = 0x00,
mat = {1024,0,0,2048,493,23}
}},
{ {
index = 0
}, {
color = 0xffffffff,
index = 1,
add = 0x00,
mat = {1024,0,0,2048,437,21}
}},
{ {
index = 0
}, {
color = 0xffffffff,
index = 1,
add = 0x00,
mat = {1024,0,0,2048,382,19}
}},
{ {
index = 0
}, {
color = 0xffffffff,
index = 1,
add = 0x00,
mat = {1024,0,0,2048,327,17}
}},
{ {
index = 0
}, {
color = 0xffffffff,
index = 1,
add = 0x00,
mat = {1024,0,0,2048,272,16}
}}
}
},
{
{
tex = 1,
src = {3,3,3,107,239,107,239,3},
screen = {-1968,-3199.99,-1968,-1535.99,1808,-1535.99,1808,-3199.99}
},
type = "picture",
id = 3
},
{
{
tex = 1,
src = {3,111,3,175,67,175,67,111},
screen = {-512,-512,-512,512,512,512,512,-512}
},
type = "picture",
id = 4
},
{
{
tex = 1,
src = {3,179,3,243,66,243,66,179},
screen = {-504,-512,-504,512,504,512,504,-512}
},
type = "picture",
id = 5
}
} | mit |
cbeck88/cegui-mirror-two | cegui/src/ScriptModules/Lua/support/tolua++bin/lua/doit.lua | 14 | 1915 | -- Generate binding code
-- Written by Waldemar Celes
-- TeCGraf/PUC-Rio
-- Jul 1998
-- Last update: Apr 2003
-- $Id$
-- This code is free software; you can redistribute it and/or modify it.
-- The software provided hereunder is on an "as is" basis, and
-- the author has no obligation to provide maintenance, support, updates,
-- enhancements, or modifications.
function parse_extra()
for k,v in ipairs(_extra_parameters or {}) do
local b,e,name,value = string.find(v, "^([^=])=(.*)$")
if b then
_extra_parameters[name] = value
else
_extra_parameters[v] = true
end
end
end
function doit ()
-- define package name, if not provided
if not flags.n then
if flags.f then
flags.n = gsub(flags.f,"%..*$","")
_,_,flags.n = string.find(flags.n, "([^/\\]*)$")
else
error("#no package name nor input file provided")
end
end
-- parse table with extra paramters
parse_extra()
-- do this after setting the package name
if flags['L'] then
dofile(flags['L'])
end
-- add cppstring
if not flags['S'] then
_basic['string'] = 'cppstring'
_basic['std::string'] = 'cppstring'
_basic_ctype.cppstring = 'const char*'
end
-- proccess package
local p = Package(flags.n,flags.f)
if flags.p then
return -- only parse
end
if flags.o then
local st,msg = writeto(flags.o)
if not st then
error('#'..msg)
end
end
p:decltype()
if flags.P then
p:print()
elseif flags.k then
output('-----------------------------------------------\n')
output('-- LuaDoc generated with tolua++\n')
output("\n")
p:output_luadoc()
output("return nil")
else
p:preamble()
p:supcode()
p:register()
push(p)
post_output_hook(p)
pop()
end
if flags.o then
writeto()
end
-- write header file
if not flags.P then
if flags.H then
local st,msg = writeto(flags.H)
if not st then
error('#'..msg)
end
p:header()
writeto()
end
end
end
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.