Refactor for documentation

This commit is contained in:
Eduardo Bart 2012-06-25 19:13:30 -03:00
parent 2c7ae6e521
commit 98a1b611bf
106 changed files with 654 additions and 780 deletions

5
.gitignore vendored
View File

@ -17,8 +17,9 @@ Makefile
*~
*.kate-swap
CMakeLists.txt.user*
items.xml
items.otb
*.xml
*.otb
*.otbm
*.log
/modules/myconfig.otml
/modules/myotclientrc.lua

5
TODO
View File

@ -76,3 +76,8 @@ terminate rework of ui events propagation (for Key events)
* lua engine
make possible to bind non LuaObject derived classes on lua engine (for usage with Point,Rect,Color,Size)
review usage of x,y/width,height in lua instead of point/size
* modules system
use one isolated environment for each module

View File

@ -47,4 +47,4 @@ if g_resources.fileExists("/otclientrc.lua") then
dofile("/otclientrc.lua")
end
g_things.loadOtb('/items.otb')
g_things.loadOtb('/lalal.otb')

View File

@ -1,7 +1,7 @@
Client = {}
function Client.reloadScripts()
reloadModules()
g_modules.reloadModules()
dofile '/otclientrc'
local message = tr('All modules and scripts were reloaded.')
TextMessage.displayEventAdvance(message)
@ -17,18 +17,18 @@ function Client.init()
else
-- window size
local size = { width = 800, height = 600 }
size = Settings.getSize('window-size', size)
size = g_settings.getSize('window-size', size)
g_window.resize(size)
-- window position, default is the screen center
local displaySize = g_window.getDisplaySize()
local defaultPos = { x = (displaySize.width - size.width)/2,
y = (displaySize.height - size.height)/2 }
local pos = Settings.getPoint('window-pos', defaultPos)
local pos = g_settings.getPoint('window-pos', defaultPos)
g_window.move(pos)
-- window maximized?
local maximized = Settings.getBoolean('window-maximized', false)
local maximized = g_settings.getBoolean('window-maximized', false)
if maximized then g_window.maximize() end
end
@ -47,8 +47,8 @@ end
function Client.terminate()
-- save window configs
Settings.set('window-size', g_window.getUnmaximizedSize())
Settings.set('window-pos', g_window.getUnmaximizedPos())
Settings.set('window-maximized', g_window.isMaximized())
g_settings.set('window-size', g_window.getUnmaximizedSize())
g_settings.set('window-pos', g_window.getUnmaximizedPos())
g_settings.set('window-maximized', g_window.isMaximized())
Client = nil
end

View File

@ -5,7 +5,7 @@ local background
-- public functions
function Background.init()
background = displayUI('background.otui')
background = g_ui.displayUI('background.otui')
background:lower()
local clientVersionLabel = background:getChildById('clientVersionLabel')
@ -15,7 +15,7 @@ function Background.init()
'Built on ' .. g_app.getBuildDate())
if not g_game.isOnline() then
Effects.fadeIn(clientVersionLabel, 1500)
g_effects.fadeIn(clientVersionLabel, 1500)
end
connect(g_game, { onGameStart = Background.hide })
@ -26,7 +26,7 @@ function Background.terminate()
disconnect(g_game, { onGameStart = Background.hide })
disconnect(g_game, { onGameEnd = Background.show })
Effects.cancelFade(background:getChildById('clientVersionLabel'))
g_effects.cancelFade(background:getChildById('clientVersionLabel'))
background:destroy()
background = nil

View File

@ -40,7 +40,7 @@ local function tryLogin(charInfo, tries)
end })
-- save last used character
Settings.set('lastUsedCharacter', charInfo.characterName)
g_settings.set('lastUsedCharacter', charInfo.characterName)
end
local function updateWait(timeStart, timeEnd)
@ -92,7 +92,7 @@ end
local function onLoginWait(message, time)
CharacterList.destroyLoadBox()
waitingWindow = displayUI('waitinglist.otui')
waitingWindow = g_ui.loadUI('waitinglist.otui')
local label = waitingWindow:getChildById('infoLabel')
label:setText(message)
@ -134,7 +134,7 @@ end
-- public functions
function CharacterList.init()
charactersWindow = displayUI('characterlist.otui')
charactersWindow = g_ui.displayUI('characterlist.otui')
charactersWindow:hide()
characterList = charactersWindow:getChildById('characterList')
charactersWindow.onKeyPress = onCharactersWindowKeyPress
@ -196,7 +196,7 @@ function CharacterList.create(characters, premDays)
local worldHost = characterInfo[3]
local worldIp = characterInfo[4]
local label = createWidget('CharacterListLabel', characterList)
local label = g_ui.createWidget('CharacterListLabel', characterList)
label:setText(characterName .. ' (' .. worldName .. ')')
label:setPhantom(false)
label.characterName = characterName
@ -205,7 +205,7 @@ function CharacterList.create(characters, premDays)
connect(label, { onDoubleClick = function () CharacterList.doLogin() return true end } )
if i == 1 or Settings.get('lastUsedCharacter') == characterName then
if i == 1 or g_settings.get('lastUsedCharacter') == characterName then
focusLabel = label
end
end

View File

@ -11,8 +11,8 @@ local function clearAccountFields()
enterGame:getChildById('accountNameTextEdit'):clearText()
enterGame:getChildById('accountPasswordTextEdit'):clearText()
enterGame:getChildById('accountNameTextEdit'):focus()
Settings.remove('account')
Settings.remove('password')
g_settings.remove('account')
g_settings.remove('password')
end
local function onError(protocol, message, connectionError)
@ -34,9 +34,9 @@ end
local function onCharacterList(protocol, characters, premDays)
if enterGame:getChildById('rememberPasswordBox'):isChecked() then
Settings.set('account', g_crypt.encrypt(G.account))
Settings.set('password', g_crypt.encrypt(G.password))
Settings.set('autologin', enterGame:getChildById('autoLoginBox'):isChecked())
g_settings.set('account', g_crypt.encrypt(G.account))
g_settings.set('password', g_crypt.encrypt(G.password))
g_settings.set('autologin', enterGame:getChildById('autoLoginBox'):isChecked())
else
clearAccountFields()
end
@ -47,9 +47,9 @@ local function onCharacterList(protocol, characters, premDays)
CharacterList.create(characters, premDays)
CharacterList.show()
local lastMotdNumber = Settings.getNumber("motd")
local lastMotdNumber = g_settings.getNumber("motd")
if G.motdNumber and G.motdNumber ~= lastMotdNumber then
Settings.set("motd", motdNumber)
g_settings.set("motd", motdNumber)
local motdBox = displayInfoBox(tr('Message of the day'), G.motdMessage)
connect(motdBox, { onOk = CharacterList.show })
CharacterList.hide()
@ -58,21 +58,21 @@ end
-- public functions
function EnterGame.init()
enterGame = displayUI('entergame.otui')
enterGame = g_ui.displayUI('entergame.otui')
enterGameButton = TopMenu.addLeftButton('enterGameButton', tr('Login') .. ' (Ctrl + G)', 'login.png', EnterGame.openWindow)
motdButton = TopMenu.addLeftButton('motdButton', tr('Message of the day'), 'motd.png', EnterGame.displayMotd)
motdButton:hide()
Keyboard.bindKeyDown('Ctrl+G', EnterGame.openWindow)
g_keyboard.bindKeyDown('Ctrl+G', EnterGame.openWindow)
if G.motdNumber then
motdButton:show()
end
local account = g_crypt.decrypt(Settings.get('account'))
local password = g_crypt.decrypt(Settings.get('password'))
local host = Settings.get('host')
local port = Settings.get('port')
local autologin = Settings.getBoolean('autologin')
local account = g_crypt.decrypt(g_settings.get('account'))
local password = g_crypt.decrypt(g_settings.get('password'))
local host = g_settings.get('host')
local port = g_settings.get('port')
local autologin = g_settings.getBoolean('autologin')
enterGame:getChildById('accountNameTextEdit'):setText(account)
enterGame:getChildById('accountPasswordTextEdit'):setText(password)
@ -93,7 +93,7 @@ function EnterGame.init()
end
function EnterGame.terminate()
Keyboard.unbindKeyDown('Ctrl+G')
g_keyboard.unbindKeyDown('Ctrl+G')
enterGame:destroy()
enterGame = nil
enterGameButton:destroy()
@ -128,8 +128,8 @@ function EnterGame.doLogin()
G.port = tonumber(enterGame:getChildById('serverPortTextEdit'):getText())
EnterGame.hide()
Settings.set('host', G.host)
Settings.set('port', G.port)
g_settings.set('host', G.host)
g_settings.set('port', G.port)
local protocolLogin = ProtocolLogin.create()
protocolLogin.onError = onError

View File

@ -21,9 +21,9 @@ end
local function onLocaleComboBoxOptionChange(self, optionText, optionData)
if Locales.setLocale(optionData) then
Settings.set('locale', optionData)
g_settings.set('locale', optionData)
sendLocale(currentLocale.name)
reloadModules()
g_modules.reloadModules()
end
end
@ -45,17 +45,17 @@ function Locales.init()
Locales.installLocales('locales')
local userLocaleName = Settings.get('locale', 'false')
local userLocaleName = g_settings.get('locale', 'false')
if userLocaleName ~= 'false' and Locales.setLocale(userLocaleName) then
pdebug('Using configured locale: ' .. userLocaleName)
else
pdebug('Using default locale: ' .. defaultLocaleName)
Locales.setLocale(defaultLocaleName)
Settings.set('locale', defaultLocaleName)
g_settings.set('locale', defaultLocaleName)
end
addEvent( function()
localeComboBox = createWidget('ComboBox', rootWidget:recursiveGetChildById('rightButtonsPanel'))
localeComboBox = g_ui.createWidget('ComboBox', rootWidget:recursiveGetChildById('rightButtonsPanel'))
for key,value in pairs(installedLocales) do
localeComboBox:addOption(value.languageName, value.name)
end

View File

@ -5,7 +5,7 @@ local moduleManagerButton
local moduleList
function ModuleManager.init()
moduleManagerWindow = displayUI('modulemanager.otui')
moduleManagerWindow = g_ui.displayUI('modulemanager.otui')
moduleManagerWindow:hide()
moduleList = moduleManagerWindow:getChildById('moduleList')
connect(moduleList, { onChildFocusChange = function(self, focusedChild)
@ -13,8 +13,8 @@ function ModuleManager.init()
ModuleManager.updateModuleInfo(focusedChild:getText())
end })
Keyboard.bindKeyPress('Up', function() moduleList:focusPreviousChild(KeyboardFocusReason) end, moduleManagerWindow)
Keyboard.bindKeyPress('Down', function() moduleList:focusNextChild(KeyboardFocusReason) end, moduleManagerWindow)
g_keyboard.bindKeyPress('Up', function() moduleList:focusPreviousChild(KeyboardFocusReason) end, moduleManagerWindow)
g_keyboard.bindKeyPress('Down', function() moduleList:focusNextChild(KeyboardFocusReason) end, moduleManagerWindow)
moduleManagerButton = TopMenu.addLeftButton('moduleManagerButton', tr('Module Manager'), 'modulemanager.png', ModuleManager.toggle)
@ -61,7 +61,7 @@ function ModuleManager.listModules()
local modules = g_modules.getModules()
for i,module in ipairs(modules) do
local label = createWidget('ModuleListLabel', moduleList)
local label = g_ui.createWidget('ModuleListLabel', moduleList)
label:setText(module:getName())
label:setOn(module:isLoaded())
end
@ -146,7 +146,7 @@ function ModuleManager.unloadCurrentModule()
end
function ModuleManager.reloadAllModules()
g_modules.reloadModules()
g_modules.g_modules.reloadModules()
ModuleManager.refreshLoadedModules()
ModuleManager.show()
end

View File

@ -20,7 +20,7 @@ local generalPanel
local graphicsPanel
local function setupGraphicsEngines()
local enginesRadioGroup = RadioGroup.create()
local enginesRadioGroup = UIRadioGroup.create()
local ogl1 = graphicsPanel:getChildById('opengl1')
local ogl2 = graphicsPanel:getChildById('opengl2')
enginesRadioGroup:addWidget(ogl1)
@ -56,32 +56,32 @@ function Options.init()
-- load options
for k,v in pairs(options) do
if type(v) == 'boolean' then
Settings.setDefault(k, v)
Options.setOption(k, Settings.getBoolean(k))
g_settings.setDefault(k, v)
Options.setOption(k, g_settings.getBoolean(k))
end
end
Keyboard.bindKeyDown('Ctrl+D', Options.toggle)
Keyboard.bindKeyDown('Ctrl+F', function() Options.toggleOption('fullscreen') end)
g_keyboard.bindKeyDown('Ctrl+D', Options.toggle)
g_keyboard.bindKeyDown('Ctrl+F', function() Options.toggleOption('fullscreen') end)
optionsWindow = displayUI('options.otui')
optionsWindow = g_ui.displayUI('options.otui')
optionsWindow:hide()
optionsButton = TopMenu.addLeftButton('optionsButton', tr('Options') .. ' (Ctrl+D)', 'options.png', Options.toggle)
optionsTabBar = optionsWindow:getChildById('optionsTabBar')
optionsTabBar:setContentWidget(optionsWindow:getChildById('optionsTabContent'))
generalPanel = loadUI('general.otui')
generalPanel = g_ui.loadUI('general.otui')
optionsTabBar:addTab(tr('General'), generalPanel)
graphicsPanel = loadUI('graphics.otui')
graphicsPanel = g_ui.loadUI('graphics.otui')
optionsTabBar:addTab(tr('Graphics'), graphicsPanel)
setupGraphicsEngines()
end
function Options.terminate()
Keyboard.unbindKeyDown('Ctrl+D')
Keyboard.unbindKeyDown('Ctrl+F')
g_keyboard.unbindKeyDown('Ctrl+D')
g_keyboard.unbindKeyDown('Ctrl+F')
optionsWindow:destroy()
optionsWindow = nil
optionsButton:destroy()
@ -135,7 +135,7 @@ function Options.setOption(key, value)
GameInterface.getLeftPanel():setOn(value)
end)
end
Settings.set(key, value)
g_settings.set(key, value)
options[key] = value
end

View File

@ -9,8 +9,8 @@ local skinComboBox
-- private functions
local function onSkinComboBoxOptionChange(self, optionText, optionData)
if Skins.setSkin(optionText) then
Settings.set('skin', optionText)
reloadModules()
g_settings.set('skin', optionText)
g_modules.reloadModules()
end
end
@ -29,17 +29,17 @@ function Skins.init()
g_resources.addToSearchPath(getSkinPath(defaultSkinName), 0)
end
local userSkinName = Settings.get('skin', 'false')
local userSkinName = g_settings.get('skin', 'false')
if userSkinName ~= 'false' and Skins.setSkin(userSkinName) then
pdebug('Using configured skin: ' .. userSkinName)
else
pdebug('Using default skin: ' .. defaultSkinName)
Skins.setSkin(defaultSkinName)
Settings.set('skin', defaultSkinName)
g_settings.set('skin', defaultSkinName)
end
addEvent( function()
skinComboBox = createWidget('ComboBox', rootWidget:recursiveGetChildById('rightButtonsPanel'))
skinComboBox = g_ui.createWidget('ComboBox', rootWidget:recursiveGetChildById('rightButtonsPanel'))
for key,value in pairs(installedSkins) do
skinComboBox:addOption(value.name)
end

View File

@ -34,9 +34,9 @@ function debugContainersItems()
function UIItem:onHoverChange(hovered)
if hovered then
local item = self:getItem()
if item then ToolTip.display(item:getId()) end
if item then g_tooltip.display(item:getId()) end
else
ToolTip.hide()
g_tooltip.hide()
end
end
end

View File

@ -107,7 +107,7 @@ end
-- public functions
function Terminal.init()
terminalWindow = displayUI('terminal.otui')
terminalWindow = g_ui.displayUI('terminal.otui')
terminalWindow:setVisible(false)
local poped = false
@ -128,16 +128,16 @@ function Terminal.init()
end
terminalButton = TopMenu.addLeftButton('terminalButton', tr('Terminal') .. ' (Ctrl + T)', 'terminal.png', Terminal.toggle)
Keyboard.bindKeyDown('Ctrl+T', Terminal.toggle)
g_keyboard.bindKeyDown('Ctrl+T', Terminal.toggle)
commandHistory = Settings.getList('terminal-history')
commandHistory = g_settings.getList('terminal-history')
commandTextEdit = terminalWindow:getChildById('commandTextEdit')
Keyboard.bindKeyPress('Up', function() navigateCommand(1) end, commandTextEdit)
Keyboard.bindKeyPress('Down', function() navigateCommand(-1) end, commandTextEdit)
Keyboard.bindKeyDown('Tab', completeCommand, commandTextEdit)
Keyboard.bindKeyDown('Enter', doCommand, commandTextEdit)
Keyboard.bindKeyDown('Escape', Terminal.hide, terminalWindow)
g_keyboard.bindKeyPress('Up', function() navigateCommand(1) end, commandTextEdit)
g_keyboard.bindKeyPress('Down', function() navigateCommand(-1) end, commandTextEdit)
g_keyboard.bindKeyDown('Tab', completeCommand, commandTextEdit)
g_keyboard.bindKeyDown('Enter', doCommand, commandTextEdit)
g_keyboard.bindKeyDown('Escape', Terminal.hide, terminalWindow)
terminalBuffer = terminalWindow:getChildById('terminalBuffer')
g_logger.setOnLog(onLog)
@ -145,8 +145,8 @@ function Terminal.init()
end
function Terminal.terminate()
Settings.setList('terminal-history', commandHistory)
Keyboard.unbindKeyDown('Ctrl+T')
g_settings.setList('terminal-history', commandHistory)
g_keyboard.unbindKeyDown('Ctrl+T')
g_logger.setOnLog(nil)
terminalButton:destroy()
terminalButton = nil
@ -184,7 +184,7 @@ function Terminal.addLine(text, color)
end
-- create new line label
local label = createWidget('TerminalLabel', terminalBuffer)
local label = g_ui.createWidget('TerminalLabel', terminalBuffer)
label:setId('terminalLabel' .. numLines)
label:setText(text)
label:setColor(color)

View File

@ -15,7 +15,7 @@ local function addButton(id, description, icon, callback, panel, toggle)
class = 'TopButton'
end
local button = createWidget(class, panel)
local button = g_ui.createWidget(class, panel)
button:setId(id)
button:setTooltip(description)
button:setIcon(resolvepath(icon, 3))
@ -28,7 +28,7 @@ function TopMenu.init()
connect(g_game, { onGameStart = TopMenu.showGameButtons,
onGameEnd = TopMenu.hideGameButtons })
topMenu = displayUI('topmenu.otui')
topMenu = g_ui.displayUI('topmenu.otui')
leftButtonsPanel = topMenu:getChildById('leftButtonsPanel')
rightButtonsPanel = topMenu:getChildById('rightButtonsPanel')

View File

@ -1,3 +1,5 @@
-- @docconsts @{
AnchorNone = 0
AnchorTop = 1
AnchorBottom = 2
@ -169,6 +171,31 @@ KeyNumpad7 = 148
KeyNumpad8 = 149
KeyNumpad9 = 150
SpeakSay = 1
SpeakWhisper = 2
SpeakYell = 3
SpeakBroadcast = 4
SpeakPrivate = 5
SpeakPrivateRed = 6
SpeakPrivatePlayerToNpc = 7
SpeakPrivateNpcToPlayer = 8
SpeakChannelYellow = 9
SpeakChannelWhite = 10
SpeakChannelRed = 11
SpeakChannelOrange = 12
SpeakMonsterSay = 13
SpeakMonsterYell = 14
FightOffensive = 1
FightBalanced = 2
FightDefensive = 3
DontChase = 0
ChaseOpponent = 1
-- @}
KeyCodeDescs = {
[KeyUnknown] = 'Unknown',
[KeyEscape] = 'Escape',
@ -287,26 +314,3 @@ KeyCodeDescs = {
[KeyNumpad8] = 'Numpad8',
[KeyNumpad9] = 'Numpad9'
}
SpeakSay = 1
SpeakWhisper = 2
SpeakYell = 3
SpeakBroadcast = 4
SpeakPrivate = 5
SpeakPrivateRed = 6
SpeakPrivatePlayerToNpc = 7
SpeakPrivateNpcToPlayer = 8
SpeakChannelYellow = 9
SpeakChannelWhite = 10
SpeakChannelRed = 11
SpeakChannelOrange = 12
SpeakMonsterSay = 13
SpeakMonsterYell = 14
FightOffensive = 1
FightBalanced = 2
FightDefensive = 3
DontChase = 0
ChaseOpponent = 1

View File

@ -6,8 +6,9 @@ Module
reloadable: false
@onLoad: |
dofiles 'ext'
dofiles 'math'
dofile 'math'
dofile 'string'
dofile 'table'
dofile 'const'
dofile 'util'
@ -17,5 +18,3 @@ Module
dofile 'mouse'
dofiles 'ui'
dofiles 'widgets'

View File

@ -1,6 +0,0 @@
function os.execute(command)
local f = assert(io.popen(command, 'r'))
local data = assert(f:read('*a'))
f:close()
print(data)
end

View File

@ -1,45 +0,0 @@
function string.split(s, delim)
local start = 1
local results = {}
while true do
local pos = string.find(s, delim, start, true)
if not pos then
break
end
table.insert(results, string.sub(s, start, pos-1))
start = pos + string.len(delim)
end
table.insert(results, string.sub(s, start))
table.removevalue(results, '')
return results
end
function string.starts(s, start)
return string.sub(s, 1, #start) == start
end
function string.trim(s)
return string.match(s, '^%s*(.*%S)') or ''
end
function string.explode(str, sep, limit)
if(type(sep) ~= 'string' or tostring(str):len() == 0 or sep:len() == 0) then
return {}
end
local i, pos, tmp, t = 0, 1, "", {}
for s, e in function() return string.find(str, sep, pos) end do
tmp = str:sub(pos, s - 1):trim()
table.insert(t, tmp)
pos = e + 1
i = i + 1
if(limit ~= nil and i == limit) then
break
end
end
tmp = str:sub(pos):trim()
table.insert(t, tmp)
return t
end

View File

@ -1,73 +1,36 @@
rootWidget = g_ui.getRootWidget()
-- @docvars @{
importStyle = g_ui.importStyle
importFont = g_fonts.importFont
setDefaultFont = g_fonts.setDefaultFont
-- root widget
rootWidget = g_ui.getRootWidget()
-- G is used as a global table to save variables in memory between reloads
G = G or {}
function loadUI(otui, parent)
local otuiFilePath = resolvepath(otui, 2)
return g_ui.loadUI(otuiFilePath, parent)
end
-- @}
function displayUI(otui, parent)
parent = parent or rootWidget
local otuiFilePath = resolvepath(otui, 2)
return g_ui.loadUI(otuiFilePath, parent)
end
function createWidget(stylename, parent)
if type(parent) == 'string' then
parent = rootWidget:recursiveGetChildById(parent)
end
local widget = g_ui.createWidgetFromStyle(stylename, parent)
return widget
end
-- @docfuncs @{
function scheduleEvent(callback, delay)
local event = g_eventDispatcher.scheduleEvent(callback, delay)
local event = g_dispatcher.scheduleEvent(callback, delay)
-- must hold a reference to the callback, otherwise it would be collected
event._callback = callback
return event
end
function addEvent(callback, front)
local event = g_eventDispatcher.addEvent(callback, front)
local event = g_dispatcher.addEvent(callback, front)
-- must hold a reference to the callback, otherwise it would be collected
event._callback = callback
return event
end
function cycleEvent(callback, front)
local event = g_eventDispatcher.cycleEvent(callback, front)
local event = g_dispatcher.cycleEvent(callback, front)
-- must hold a reference to the callback, otherwise it would be collected
event._callback = callback
return event
end
function periodicalEvent(eventFunc, conditionFunc, delay, autoRepeatDelay)
delay = delay or 30
autoRepeatDelay = autoRepeatDelay or delay
local func
func = function()
if conditionFunc and not conditionFunc() then
func = nil
return
end
eventFunc()
scheduleEvent(func, delay)
end
scheduleEvent(function()
func()
end, autoRepeatDelay)
end
function removeEvent(event)
if event then
event:cancel()
@ -75,13 +38,4 @@ function removeEvent(event)
end
end
function reloadModule(name)
local module = g_modules.getModule(name)
if module then
module:reload()
end
end
function reloadModules()
g_modules.reloadModules()
end
-- @}

View File

@ -1,4 +1,5 @@
Keyboard = {}
-- @docclass
g_keyboard = {}
-- private functions
function translateKeyCombo(keyCombo)
@ -95,14 +96,14 @@ local function connectKeyPressEvent(widget)
end
-- public functions
function Keyboard.bindKeyDown(keyComboDesc, callback, widget)
function g_keyboard.bindKeyDown(keyComboDesc, callback, widget)
widget = widget or rootWidget
connectKeyDownEvent(widget)
local keyComboDesc = retranslateKeyComboDesc(keyComboDesc)
widget.boundKeyDownCombos[keyComboDesc] = callback
end
function Keyboard.bindKeyPress(keyComboDesc, callback, widget, autoRepeatDelay)
function g_keyboard.bindKeyPress(keyComboDesc, callback, widget, autoRepeatDelay)
autoRepeatDelay = autoRepeatDelay or 500
widget = widget or rootWidget
connectKeyPressEvent(widget)
@ -111,7 +112,7 @@ function Keyboard.bindKeyPress(keyComboDesc, callback, widget, autoRepeatDelay)
widget:setAutoRepeatDelay(math.min(autoRepeatDelay, widget:getAutoRepeatDelay()))
end
function Keyboard.unbindKeyDown(keyComboDesc, widget)
function g_keyboard.unbindKeyDown(keyComboDesc, widget)
widget = widget or rootWidget
if widget.boundKeyDownCombos == nil then return end
local keyComboDesc = retranslateKeyComboDesc(keyComboDesc)
@ -120,7 +121,7 @@ function Keyboard.unbindKeyDown(keyComboDesc, widget)
end
end
function Keyboard.unbindKeyPress(keyComboDesc, widget)
function g_keyboard.unbindKeyPress(keyComboDesc, widget)
widget = widget or rootWidget
if widget.boundKeyPressCombos == nil then return end
local keyComboDesc = retranslateKeyComboDesc(keyComboDesc)
@ -129,18 +130,18 @@ function Keyboard.unbindKeyPress(keyComboDesc, widget)
end
end
function Keyboard.getModifiers()
function g_keyboard.getModifiers()
return g_window.getKeyboardModifiers()
end
function Keyboard.isCtrlPressed()
function g_keyboard.isCtrlPressed()
return bit32.band(g_window.getKeyboardModifiers(), KeyboardCtrlModifier) ~= 0
end
function Keyboard.isAltPressed()
function g_keyboard.isAltPressed()
return bit32.band(g_window.getKeyboardModifiers(), KeyboardAltModifier) ~= 0
end
function Keyboard.isShiftPressed()
function g_keyboard.isShiftPressed()
return bit32.band(g_window.getKeyboardModifiers(), KeyboardShiftModifier) ~= 0
end

10
modules/corelib/math.lua Normal file
View File

@ -0,0 +1,10 @@
-- @docclass math
function math.round(num, idp)
local mult = 10^(idp or 0)
if num >= 0 then
return math.floor(num * mult + 0.5) / mult
else
return math.ceil(num * mult - 0.5) / mult
end
end

View File

@ -1 +0,0 @@
Color = {}

View File

@ -1,8 +0,0 @@
function math.round(num, idp)
local mult = 10^(idp or 0)
if num >= 0 then
return math.floor(num * mult + 0.5) / mult
else
return math.ceil(num * mult - 0.5) / mult
end
end

View File

@ -1 +0,0 @@
Point = {}

View File

@ -1 +0,0 @@
Rect = {}

View File

@ -1 +0,0 @@
Size = {}

View File

@ -1,37 +1,38 @@
Mouse = {}
-- @docclass
g_mouse = {}
local cursorChanged = false
function Mouse.setTargetCursor()
function g_mouse.setTargetCursor()
g_window.setMouseCursor('/cursors/targetcursor.png', {x=9,y=9})
cursorChanged = true
end
function Mouse.setHorizontalCursor()
function g_mouse.setHorizontalCursor()
g_window.setMouseCursor('/cursors/horizontal.png', {x=9,y=4})
cursorChanged = true
end
function Mouse.setVerticalCursor()
function g_mouse.setVerticalCursor()
g_window.setMouseCursor('/cursors/vertical.png', {x=4,y=9})
cursorChanged = true
end
function Mouse.restoreCursor()
function g_mouse.restoreCursor()
g_window.restoreMouseCursor()
cursorChanged = false
end
function Mouse.isCursorChanged()
function g_mouse.isCursorChanged()
return cursorChanged
end
function Mouse.isPressed(button)
function g_mouse.isPressed(button)
if not button then button = MouseLeftButton end
return g_window.isMouseButtonPressed(button)
end
function Mouse.bindAutoPress(widget, callback)
function g_mouse.bindAutoPress(widget, callback)
connect(widget, { onMousePress = function(widget, mousePos, mouseButton)
callback()
periodicalEvent(function()
@ -43,7 +44,7 @@ function Mouse.bindAutoPress(widget, callback)
end })
end
function Mouse.bindPressMove(widget, callback)
function g_mouse.bindPressMove(widget, callback)
connect(widget, { onMouseMove = function(widget, mousePos, mouseMoved)
if widget:isPressed() then
callback(mousePos, mouseMoved)

View File

@ -1,12 +1,13 @@
Settings = {}
-- @docclass
g_settings = {}
Settings.exists = g_configs.exists
Settings.setNode = g_configs.setNode
Settings.mergeNode = g_configs.mergeNode
Settings.getNode = g_configs.getNode
Settings.remove = g_configs.remove
Settings.setList = g_configs.setList
Settings.getList = g_configs.getList
g_settings.exists = g_configs.exists
g_settings.setNode = g_configs.setNode
g_settings.mergeNode = g_configs.mergeNode
g_settings.getNode = g_configs.getNode
g_settings.remove = g_configs.remove
g_settings.setList = g_configs.setList
g_settings.getList = g_configs.getList
local function convertSettingValue(value)
if type(value) == 'table' then
@ -28,55 +29,55 @@ local function convertSettingValue(value)
end
end
function Settings.set(key, value)
function g_settings.set(key, value)
g_configs.set(key, convertSettingValue(value))
end
function Settings.setDefault(key, value)
if Settings.exists(key) then return false end
Settings.set(key, value)
function g_settings.setDefault(key, value)
if g_settings.exists(key) then return false end
g_settings.set(key, value)
return true
end
function Settings.get(key, default)
if not Settings.exists(key) and default ~= nil then
Settings.set(key, default)
function g_settings.get(key, default)
if not g_settings.exists(key) and default ~= nil then
g_settings.set(key, default)
end
return g_configs.get(key)
end
function Settings.getString(key, default)
return Settings.get(key, default)
function g_settings.getString(key, default)
return g_settings.get(key, default)
end
function Settings.getInteger(key, default)
return tonumber(Settings.get(key, default))
function g_settings.getInteger(key, default)
return tonumber(g_settings.get(key, default))
end
function Settings.getNumber(key, default)
return tonumber(Settings.get(key, default))
function g_settings.getNumber(key, default)
return tonumber(g_settings.get(key, default))
end
function Settings.getBoolean(key, default)
return toboolean(Settings.get(key, default))
function g_settings.getBoolean(key, default)
return toboolean(g_settings.get(key, default))
end
function Settings.getPoint(key, default)
return topoint(Settings.get(key, default))
function g_settings.getPoint(key, default)
return topoint(g_settings.get(key, default))
end
function Settings.getRect(key, default)
return torect(Settings.get(key, default))
function g_settings.getRect(key, default)
return torect(g_settings.get(key, default))
end
function Settings.getSize(key, default)
return tosize(Settings.get(key, default))
function g_settings.getSize(key, default)
return tosize(g_settings.get(key, default))
end
function Settings.getColor(key, default)
return tocolor(Settings.get(key, default))
function g_settings.getColor(key, default)
return tocolor(g_settings.get(key, default))
end
function Settings.getColor(key, default)
return tocolor(Settings.get(key, default))
function g_settings.getColor(key, default)
return tocolor(g_settings.get(key, default))
end

View File

@ -0,0 +1,47 @@
-- @docclass string
function string:split(delim)
local start = 1
local results = {}
while true do
local pos = string.find(self, delim, start, true)
if not pos then
break
end
table.insert(results, string.sub(self, start, pos-1))
start = pos + string.len(delim)
end
table.insert(results, string.sub(self, start))
table.removevalue(results, '')
return results
end
function string:starts(start)
return string.sub(self, 1, #start) == start
end
function string:trim()
return string.match(self, '^%s*(.*%S)') or ''
end
function string:explode(sep, limit)
if(type(sep) ~= 'string' or tostring(self):len() == 0 or sep:len() == 0) then
return {}
end
local i, pos, tmp, t = 0, 1, "", {}
for s, e in function() return string.find(self, sep, pos) end do
tmp = self:sub(pos, s - 1):trim()
table.insert(t, tmp)
pos = e + 1
i = i + 1
if(limit ~= nil and i == limit) then
break
end
end
tmp = self:sub(pos):trim()
table.insert(t, tmp)
return t
end

View File

@ -1,3 +1,5 @@
-- @docclass table
function table.dump(t, depth)
if not depth then depth = 0 end
for k,v in pairs(t) do

View File

@ -1,6 +1,7 @@
Effects = {}
-- @docclass
g_effects = {}
function Effects.fadeIn(widget, time, elapsed)
function g_effects.fadeIn(widget, time, elapsed)
if not elapsed then elapsed = 0 end
if not time then time = 300 end
widget:setOpacity(math.min(elapsed/time, 1))
@ -8,14 +9,14 @@ function Effects.fadeIn(widget, time, elapsed)
if elapsed < time then
removeEvent(widget.fadeEvent)
widget.fadeEvent = scheduleEvent(function()
Effects.fadeIn(widget, time, elapsed + 30)
g_effects.fadeIn(widget, time, elapsed + 30)
end, 30)
else
widget.fadeEvent = nil
end
end
function Effects.fadeOut(widget, time, elapsed)
function g_effects.fadeOut(widget, time, elapsed)
if not elapsed then elapsed = 0 end
if not time then time = 300 end
elapsed = math.max((1 - widget:getOpacity()) * time, elapsed)
@ -23,14 +24,14 @@ function Effects.fadeOut(widget, time, elapsed)
widget:setOpacity(math.max((time - elapsed)/time, 0))
if elapsed < time then
widget.fadeEvent = scheduleEvent(function()
Effects.fadeOut(widget, time, elapsed + 30)
g_effects.fadeOut(widget, time, elapsed + 30)
end, 30)
else
widget.fadeEvent = nil
end
end
function Effects.cancelFade(widget)
function g_effects.cancelFade(widget)
removeEvent(widget.fadeEvent)
widget.fadeEvent = nil
end

View File

@ -1,4 +1,5 @@
ToolTip = {}
-- @docclass
g_tooltip = {}
-- private variables
local toolTipLabel
@ -21,13 +22,13 @@ end
local function onWidgetHoverChange(widget, hovered)
if hovered then
if widget.tooltip and not Mouse.isPressed() then
ToolTip.display(widget.tooltip)
if widget.tooltip and not g_mouse.isPressed() then
g_tooltip.display(widget.tooltip)
currentHoveredWidget = widget
end
else
if widget == currentHoveredWidget then
ToolTip:hide()
g_tooltip.hide()
currentHoveredWidget = nil
end
end
@ -40,12 +41,12 @@ local function onWidgetStyleApply(widget, styleName, styleNode)
end
-- public functions
function ToolTip.init()
function g_tooltip.init()
connect(UIWidget, { onStyleApply = onWidgetStyleApply,
onHoverChange = onWidgetHoverChange})
addEvent(function()
toolTipLabel = createWidget('UILabel', rootWidget)
toolTipLabel = g_ui.createWidget('UILabel', rootWidget)
toolTipLabel:setId('toolTip')
toolTipLabel:setBackgroundColor('#111111cc')
toolTipLabel:setTextAlign(AlignCenter)
@ -54,7 +55,7 @@ function ToolTip.init()
end)
end
function ToolTip.terminate()
function g_tooltip.terminate()
disconnect(UIWidget, { onStyleApply = onWidgetStyleApply,
onHoverChange = onWidgetHoverChange })
@ -62,10 +63,10 @@ function ToolTip.terminate()
toolTipLabel:destroy()
toolTipLabel = nil
ToolTip = nil
g_tooltip = nil
end
function ToolTip.display(text)
function g_tooltip.display(text)
if text == nil then return end
if not toolTipLabel then return end
@ -75,14 +76,17 @@ function ToolTip.display(text)
toolTipLabel:show()
toolTipLabel:raise()
toolTipLabel:enable()
Effects.fadeIn(toolTipLabel, 100)
g_effects.fadeIn(toolTipLabel, 100)
moveToolTip(toolTipLabel)
end
function ToolTip.hide()
Effects.fadeOut(toolTipLabel, 100)
function g_tooltip.hide()
g_effects.fadeOut(toolTipLabel, 100)
end
-- @docclass UIWidget @{
-- UIWidget extensions
function UIWidget:setTooltip(text)
self.tooltip = text
@ -92,5 +96,7 @@ function UIWidget:getTooltip()
return self.tooltip
end
ToolTip.init()
connect(g_app, { onTerminate = ToolTip.terminate })
-- @}
g_tooltip.init()
connect(g_app, { onTerminate = g_tooltip.terminate })

View File

@ -1,3 +1,4 @@
-- @docclass
UIButton = extends(UIWidget)
function UIButton.create()

View File

@ -1,3 +1,4 @@
-- @docclass
UICheckBox = extends(UIWidget)
function UICheckBox.create()

View File

@ -1,3 +1,4 @@
-- @docclass
UIComboBox = extends(UIWidget)
function UIComboBox.create()
@ -36,7 +37,7 @@ function UIComboBox:addOption(text, data)
end
function UIComboBox:onMousePress(mousePos, mouseButton)
local menu = createWidget(self:getStyleName() .. 'PopupMenu')
local menu = g_ui.createWidget(self:getStyleName() .. 'PopupMenu')
menu:setId(self:getId() .. 'PopupMenu')
for i,v in ipairs(self.options) do
menu:addOption(v.text, function() self:setCurrentOption(v.text) end)

View File

@ -1,3 +1,4 @@
-- @docclass
UILabel = extends(UIWidget)
function UILabel.create()

View File

@ -1,5 +1,6 @@
if not UIWindow then dofile 'uiwindow' end
-- @docclass
UIMessageBox = extends(UIWindow)
MessageBoxOk = 1
@ -15,7 +16,7 @@ function UIMessageBox.display(title, message, flags)
messagebox:setStyle('MessageBoxWindow')
messagebox:setText(title)
local messageLabel = createWidget('MessageBoxLabel', messagebox)
local messageLabel = g_ui.createWidget('MessageBoxLabel', messagebox)
messageLabel:setText(message)
messageLabel:resizeToText()
@ -23,7 +24,7 @@ function UIMessageBox.display(title, message, flags)
messagebox:setHeight(math.max(messageLabel:getHeight() + 64, messagebox:getHeight()))
-- setup messagebox first button
local buttonRight = createWidget('MessageBoxRightButton', messagebox)
local buttonRight = g_ui.createWidget('MessageBoxRightButton', messagebox)
if flags == MessageBoxOk then
buttonRight:setText('Ok')

View File

@ -1,3 +1,4 @@
-- @docclass
UIMiniWindow = extends(UIWindow)
function UIMiniWindow.create()
@ -77,7 +78,7 @@ function UIMiniWindow:onSetup()
local oldParent = self:getParent()
local settings = Settings.getNode('MiniWindows')
local settings = g_settings.getNode('MiniWindows')
if settings then
local selfSettings = settings[self:getId()]
if selfSettings then
@ -215,7 +216,7 @@ end
function UIMiniWindow:setSettings(data)
if not self.save then return end
local settings = Settings.getNode('MiniWindows')
local settings = g_settings.getNode('MiniWindows')
if not settings then
settings = {}
end
@ -229,7 +230,7 @@ function UIMiniWindow:setSettings(data)
settings[id][key] = value
end
Settings.setNode('MiniWindows', settings)
g_settings.setNode('MiniWindows', settings)
end
function UIMiniWindow:saveParentPosition(parentId, position)

View File

@ -1,3 +1,4 @@
-- @docclass
UIMiniWindowContainer = extends(UIWidget)
function UIMiniWindowContainer.create()

View File

@ -1,3 +1,4 @@
-- @docclass
UIPopupMenu = extends(UIWidget)
local currentMenu
@ -33,7 +34,7 @@ function UIPopupMenu:onGeometryChange()
end
function UIPopupMenu:addOption(optionName, optionCallback)
local optionWidget = createWidget(self:getStyleName() .. 'Button', self)
local optionWidget = g_ui.createWidget(self:getStyleName() .. 'Button', self)
local lastOptionWidget = self:getLastChild()
optionWidget.onClick = function(self)
optionCallback()
@ -45,7 +46,7 @@ function UIPopupMenu:addOption(optionName, optionCallback)
end
function UIPopupMenu:addSeparator()
createWidget(self:getStyleName() .. 'Separator', self)
g_ui.createWidget(self:getStyleName() .. 'Separator', self)
end
function UIPopupMenu:onDestroy()

View File

@ -1,3 +1,4 @@
-- @docclass
UIProgressBar = extends(UIWidget)
function UIProgressBar.create()

View File

@ -1,24 +1,25 @@
RadioGroup = newclass()
-- @docclass
UIRadioGroup = newclass()
function RadioGroup.create()
local radiogroup = RadioGroup.internalCreate()
function UIRadioGroup.create()
local radiogroup = UIRadioGroup.internalCreate()
radiogroup.widgets = {}
return radiogroup
end
function RadioGroup:destroy()
function UIRadioGroup:destroy()
for k,widget in pairs(self.widgets) do
widget.onClick = nil
end
self.widgets = {}
end
function RadioGroup:addWidget(widget)
function UIRadioGroup:addWidget(widget)
table.insert(self.widgets, widget)
widget.onClick = function(widget) self:selectWidget(widget) end
end
function RadioGroup:removeWidget(widget)
function UIRadioGroup:removeWidget(widget)
if self.selectedWidget == widget then
self:selectWidget(nil)
end
@ -26,7 +27,7 @@ function RadioGroup:removeWidget(widget)
table.removevalue(self.widgets, widget)
end
function RadioGroup:selectWidget(selectedWidget)
function UIRadioGroup:selectWidget(selectedWidget)
if selectedWidget == self.selectedWidget then return end
local previousSelectedWidget = self.selectedWidget

View File

@ -1,3 +1,4 @@
-- @docclass
UIResizeBorder = extends(UIWidget)
function UIResizeBorder.create()
@ -10,22 +11,22 @@ end
function UIResizeBorder:onHoverChange(hovered)
if hovered then
if Mouse.isCursorChanged() or Mouse.isPressed() then return end
if g_mouse.isCursorChanged() or g_mouse.isPressed() then return end
if self:getWidth() > self:getHeight() then
Mouse.setVerticalCursor()
g_mouse.setVerticalCursor()
self.vertical = true
else
Mouse.setHorizontalCursor()
g_mouse.setHorizontalCursor()
self.vertical = false
end
self.hovering = true
if not self:isPressed() then
Effects.fadeIn(self)
g_effects.fadeIn(self)
end
else
if not self:isPressed() and self.hovering then
Mouse.restoreCursor()
Effects.fadeOut(self)
g_mouse.restoreCursor()
g_effects.fadeOut(self)
self.hovering = false
end
end
@ -64,8 +65,8 @@ end
function UIResizeBorder:onMouseRelease(mousePos, mouseButton)
if not self:isHovered() then
Mouse.restoreCursor()
Effects.fadeOut(self)
g_mouse.restoreCursor()
g_effects.fadeOut(self)
self.hovering = false
end
end

View File

@ -1,3 +1,4 @@
-- @docclass
UIScrollArea = extends(UIWidget)
-- public functions

View File

@ -1,3 +1,4 @@
-- @docclass
UIScrollBar = extends(UIWidget)
-- private functions
@ -101,9 +102,9 @@ end
function UIScrollBar:onSetup()
self.setupDone = true
signalcall(self.onValueChange, self, self.value)
Mouse.bindAutoPress(self:getChildById('decrementButton'), function() self:decrement() end)
Mouse.bindAutoPress(self:getChildById('incrementButton'), function() self:increment() end)
Mouse.bindPressMove(self:getChildById('sliderButton'), function(mousePos, mouseMoved) parseSliderPos(self, mousePos) end)
g_mouse.bindAutoPress(self:getChildById('decrementButton'), function() self:decrement() end)
g_mouse.bindAutoPress(self:getChildById('incrementButton'), function() self:increment() end)
g_mouse.bindPressMove(self:getChildById('sliderButton'), function(mousePos, mouseMoved) parseSliderPos(self, mousePos) end)
updateSlider(self)
end

View File

@ -1,3 +1,4 @@
-- @docclass
UISpinBox = extends(UITextEdit)
function UISpinBox.create()

View File

@ -1,3 +1,4 @@
-- @docclass
UISplitter = extends(UIWidget)
function UISplitter.create()
@ -9,22 +10,22 @@ end
function UISplitter:onHoverChange(hovered)
if hovered then
if Mouse.isCursorChanged() or Mouse.isPressed() then return end
if g_mouse.isCursorChanged() or g_mouse.isPressed() then return end
if self:getWidth() > self:getHeight() then
Mouse.setVerticalCursor()
g_mouse.setVerticalCursor()
self.vertical = true
else
Mouse.setHorizontalCursor()
g_mouse.setHorizontalCursor()
self.vertical = false
end
self.hovering = true
if not self:isPressed() then
Effects.fadeIn(self)
g_effects.fadeIn(self)
end
else
if not self:isPressed() and self.hovering then
Mouse.restoreCursor()
Effects.fadeOut(self)
g_mouse.restoreCursor()
g_effects.fadeOut(self)
self.hovering = false
end
end
@ -64,8 +65,8 @@ end
function UISplitter:onMouseRelease(mousePos, mouseButton)
if not self:isHovered() then
Mouse.restoreCursor()
Effects.fadeOut(self)
g_mouse.restoreCursor()
g_effects.fadeOut(self)
self.hovering = false
end
end

View File

@ -1,3 +1,4 @@
-- @docclass
UITabBar = extends(UIWidget)
-- private functions
@ -28,11 +29,11 @@ end
function UITabBar:addTab(text, panel)
if panel == nil then
panel = createWidget(self:getStyleName() .. 'Panel')
panel = g_ui.createWidget(self:getStyleName() .. 'Panel')
panel:setId('tabPanel')
end
local tab = createWidget(self:getStyleName() .. 'Button', self)
local tab = g_ui.createWidget(self:getStyleName() .. 'Button', self)
panel.isTab = true
tab.tabPanel = panel
tab.tabBar = self

View File

@ -1,3 +1,5 @@
-- @docclass UIWidget
function UIWidget:setMargin(...)
local params = {...}
if #params == 1 then

View File

@ -1,3 +1,4 @@
-- @docclass
UIWindow = extends(UIWidget)
function UIWindow.create()

View File

@ -1,3 +1,5 @@
-- @docfuncs @{
function print(...)
local msg = ""
for i,v in ipairs({...}) do
@ -26,9 +28,13 @@ function fatal(msg)
g_logger.log(LogFatal, msg)
end
function exit()
g_app.exit()
end
exit = g_app.exit
quit = g_app.exit
function quit()
g_app.quit()
end
function connect(object, signalsAndSlots, pushFront)
for signal,slot in pairs(signalsAndSlots) do
@ -151,6 +157,7 @@ function toboolean(str)
end
local oldtonumber = tonumber
function tonumber(v)
if v == nil then return 0 end
return oldtonumber(v)
@ -174,3 +181,5 @@ end
function tr(s)
return s
end
-- @}

View File

@ -1,3 +1,5 @@
-- @docconsts @{
SkullNone = 0
SkullYellow = 1
SkullGreen = 2
@ -64,3 +66,5 @@ GameTrucatedPingOpcode = 20
GameReverseCreatureStack = 21
OTSERV_RSA = "109120132967399429278860960508995541528237502902798129123468757937266291492576446330739696001110603907230888610072655818825358503429057592827629436413108566029093628212635953836686562675849720620786279431090218017681061521755056710823876476444260558147179707119674283982419152118103759076030616683978566631413"
-- @}

View File

@ -1,3 +1,7 @@
-- @docclass Creature
-- @docconsts @{
SkullNone = 0
SkullYellow = 1
SkullGreen = 2
@ -23,6 +27,8 @@ EmblemGreen = 1
EmblemRed = 2
EmblemBlue = 3
-- @}
function getSkullImagePath(skullId)
if skullId == SkullYellow then
return 'icons/skull_yellow.png'

View File

@ -1,3 +1,5 @@
-- @docclass Player
function Player:isPartyLeader()
local shield = self:getShield()
return (shield == ShieldWhiteYellow or

View File

@ -1,3 +1,4 @@
-- @docclass
ProtocolLogin = extends(Protocol)
-- private functions

View File

@ -36,10 +36,10 @@ table.insert(lifeBarColors, {percentAbove = -1, color = '#4F0000' } )
-- public functions
function Battle.init()
battleWindow = displayUI('battle.otui', GameInterface.getRightPanel())
battleWindow = g_ui.loadUI('battle.otui', GameInterface.getRightPanel())
battleButton = TopMenu.addGameToggleButton('battleButton', tr('Battle') .. ' (Ctrl+B)', 'battle.png', Battle.toggle)
battleButton:setOn(true)
Keyboard.bindKeyDown('Ctrl+B', Battle.toggle)
g_keyboard.bindKeyDown('Ctrl+B', Battle.toggle)
battlePanel = battleWindow:recursiveGetChildById('battlePanel')
@ -49,7 +49,7 @@ function Battle.init()
hideSkullsButton = battleWindow:recursiveGetChildById('hideSkulls')
hidePartyButton = battleWindow:recursiveGetChildById('hideParty')
mouseWidget = createWidget('UIButton')
mouseWidget = g_ui.createWidget('UIButton')
mouseWidget:setVisible(false)
mouseWidget:setFocusable(false)
@ -65,7 +65,7 @@ function Battle.init()
end
function Battle.terminate()
Keyboard.unbindKeyDown('Ctrl+B')
g_keyboard.unbindKeyDown('Ctrl+B')
battlePanel = nil
lastBattleButtonTargeted = nil
lastBattleButtonFollowed = nil
@ -191,7 +191,7 @@ function Battle.addCreature(creature)
local creatureId = creature:getId()
if battleButtonsByCreaturesList[creatureId] == nil then
local battleButton = displayUI('battleButton.otui', battlePanel)
local battleButton = g_ui.loadUI('battleButton.otui', battlePanel)
local creatureWidget = battleButton:getChildById('creature')
local labelWidget = battleButton:getChildById('label')
local lifeBarWidget = battleButton:getChildById('lifeBar')
@ -264,7 +264,7 @@ function Battle.onMouseRelease(self, mousePosition, mouseButton)
GameInterface.createThingMenu(mousePosition, nil, nil, self.creature)
return true
elseif mouseButton == MouseLeftButton then
if Keyboard.isShiftPressed() then
if g_keyboard.isShiftPressed() then
g_game.look(self.creature)
else
if self.isTarget then

View File

@ -5,18 +5,18 @@ local bugTextEdit
local HOTKEY = 'Ctrl+Z'
function BugReport.init()
importStyle 'bugreport.otui'
g_ui.importStyle('bugreport.otui')
bugReportWindow = createWidget('BugReportWindow', rootWidget)
bugReportWindow = g_ui.createWidget('BugReportWindow', rootWidget)
bugReportWindow:hide()
bugTextEdit = bugReportWindow:getChildById('bugTextEdit')
Keyboard.bindKeyDown(HOTKEY, BugReport.show)
g_keyboard.bindKeyDown(HOTKEY, BugReport.show)
end
function BugReport.terminate()
Keyboard.unbindKeyDown(HOTKEY)
g_keyboard.unbindKeyDown(HOTKEY)
bugReportWindow:destroy()
bugReportWindow = nil
bugTextEdit = nil

View File

@ -43,7 +43,7 @@ end
function CombatControls.init()
combatControlsButton = TopMenu.addGameToggleButton('combatControlsButton', tr('Combat Controls'), 'combatcontrols.png', CombatControls.toggle)
combatControlsButton:setOn(true)
combatControlsWindow = loadUI('combatcontrols.otui', GameInterface.getRightPanel())
combatControlsWindow = g_ui.loadUI('combatcontrols.otui', GameInterface.getRightPanel())
fightOffensiveBox = combatControlsWindow:recursiveGetChildById('fightOffensiveBox')
fightBalancedBox = combatControlsWindow:recursiveGetChildById('fightBalancedBox')
@ -51,7 +51,7 @@ function CombatControls.init()
chaseModeButton = combatControlsWindow:recursiveGetChildById('chaseModeBox')
safeFightButton = combatControlsWindow:recursiveGetChildById('safeFightBox')
fightModeRadioGroup = RadioGroup.create()
fightModeRadioGroup = UIRadioGroup.create()
fightModeRadioGroup:addWidget(fightOffensiveBox)
fightModeRadioGroup:addWidget(fightBalancedBox)
fightModeRadioGroup:addWidget(fightDefensiveBox)

View File

@ -162,19 +162,19 @@ end
local function onChannelList(channelList)
if channelsWindow then channelsWindow:destroy() end
channelsWindow = displayUI('channelswindow.otui')
channelsWindow = g_ui.displayUI('channelswindow.otui')
local channelListPanel = channelsWindow:getChildById('channelList')
channelsWindow.onEnter = doChannelListSubmit
channelsWindow.onDestroy = function() channelsWindow = nil end
Keyboard.bindKeyPress('Down', function() channelListPanel:focusNextChild(KeyboardFocusReason) end, channelsWindow)
Keyboard.bindKeyPress('Up', function() channelListPanel:focusPreviousChild(KeyboardFocusReason) end, channelsWindow)
g_keyboard.bindKeyPress('Down', function() channelListPanel:focusNextChild(KeyboardFocusReason) end, channelsWindow)
g_keyboard.bindKeyPress('Up', function() channelListPanel:focusPreviousChild(KeyboardFocusReason) end, channelsWindow)
for k,v in pairs(channelList) do
local channelId = v[1]
local channelName = v[2]
if #channelName > 0 then
local label = createWidget('ChannelListLabel', channelListPanel)
local label = g_ui.createWidget('ChannelListLabel', channelListPanel)
label.channelId = channelId
label:setText(channelName)
@ -202,7 +202,7 @@ function Console.init()
onGameStart = onGameStart,
onGameEnd = Console.clear })
consolePanel = displayUI('console.otui', GameInterface.getBottomPanel())
consolePanel = g_ui.loadUI('console.otui', GameInterface.getBottomPanel())
consoleTextEdit = consolePanel:getChildById('consoleTextEdit')
consoleContentPanel = consolePanel:getChildById('consoleContentPanel')
consoleTabBar = consolePanel:getChildById('consoleTabBar')
@ -212,12 +212,12 @@ function Console.init()
Console.addTab(tr('Default'), true)
Console.addTab(tr('Server Log'), false)
Keyboard.bindKeyPress('Shift+Up', function() navigateMessageHistory(1) end, consolePanel)
Keyboard.bindKeyPress('Shift+Down', function() navigateMessageHistory(-1) end, consolePanel)
Keyboard.bindKeyPress('Tab', function() consoleTabBar:selectNextTab() end, consolePanel)
Keyboard.bindKeyPress('Shift+Tab', function() consoleTabBar:selectPrevTab() end, consolePanel)
Keyboard.bindKeyDown('Enter', Console.sendCurrentMessage, consolePanel)
Keyboard.bindKeyPress('Ctrl+A', function() consoleTextEdit:clearText() end, consolePanel)
g_keyboard.bindKeyPress('Shift+Up', function() navigateMessageHistory(1) end, consolePanel)
g_keyboard.bindKeyPress('Shift+Down', function() navigateMessageHistory(-1) end, consolePanel)
g_keyboard.bindKeyPress('Tab', function() consoleTabBar:selectNextTab() end, consolePanel)
g_keyboard.bindKeyPress('Shift+Tab', function() consoleTabBar:selectPrevTab() end, consolePanel)
g_keyboard.bindKeyDown('Enter', Console.sendCurrentMessage, consolePanel)
g_keyboard.bindKeyPress('Ctrl+A', function() consoleTextEdit:clearText() end, consolePanel)
-- apply buttom functions after loaded
consolePanel:getChildById('nextChannelButton').onClick = function() consoleTabBar:selectNextTab() end
@ -225,9 +225,9 @@ function Console.init()
consoleTabBar.onTabChange = Console.onTabChange
-- tibia like hotkeys
Keyboard.bindKeyDown('Ctrl+O', g_game.requestChannels)
Keyboard.bindKeyDown('Ctrl+E', Console.removeCurrentTab)
Keyboard.bindKeyDown('Ctrl+H', Console.openHelp)
g_keyboard.bindKeyDown('Ctrl+O', g_game.requestChannels)
g_keyboard.bindKeyDown('Ctrl+E', Console.removeCurrentTab)
g_keyboard.bindKeyDown('Ctrl+H', Console.openHelp)
end
function Console.terminate()
@ -247,9 +247,9 @@ function Console.terminate()
end
channels = {}
Keyboard.unbindKeyDown('Ctrl+O')
Keyboard.unbindKeyDown('Ctrl+E')
Keyboard.unbindKeyDown('Ctrl+H')
g_keyboard.unbindKeyDown('Ctrl+O')
g_keyboard.unbindKeyDown('Ctrl+E')
g_keyboard.unbindKeyDown('Ctrl+H')
if channelsWindow then
channelsWindow:destroy()
@ -382,7 +382,7 @@ function Console.addTabText(text, speaktype, tab, creatureName)
local panel = consoleTabBar:getTabPanel(tab)
local consoleBuffer = panel:getChildById('consoleBuffer')
local label = createWidget('ConsoleLabel', consoleBuffer)
local label = g_ui.createWidget('ConsoleLabel', consoleBuffer)
label:setId('consoleLabel' .. panel:getChildCount())
label:setText(text)
label:setColor(speaktype.color)
@ -397,7 +397,7 @@ end
function Console.popupMenu(mousePos, mouseButton, creatureName, text)
if mouseButton == MouseRightButton then
local menu = createWidget('PopupMenu')
local menu = g_ui.createWidget('PopupMenu')
if creatureName then
if creatureName ~= g_game.getCharacterName() then
menu:addOption(tr('Message to ' .. creatureName), function () g_game.openPrivateChannel(creatureName) end)

View File

@ -14,7 +14,7 @@ local function onContainerOpen(container, previousContainer)
previousContainer.window = nil
previousContainer.itemsPanel = nil
else
containerWindow = createWidget('ContainerWindow', GameInterface.getRightPanel())
containerWindow = g_ui.createWidget('ContainerWindow', GameInterface.getRightPanel())
end
containerWindow:setId('container' .. container:getId())
local containerPanel = containerWindow:getChildById('contentsPanel')
@ -42,7 +42,7 @@ local function onContainerOpen(container, previousContainer)
containerPanel:destroyChildren()
for slot=0,container:getCapacity()-1 do
local itemWidget = createWidget('Item', containerPanel)
local itemWidget = g_ui.createWidget('Item', containerPanel)
itemWidget:setId('item' .. slot)
itemWidget:setItem(container:getItem(slot))
itemWidget:setMargin(3)
@ -74,7 +74,7 @@ local function onContainerRemoveItem(container, slot, item)
end
function Containers.init()
importStyle 'container.otui'
g_ui.importStyle('container.otui')
connect(Container, { onOpen = onContainerOpen,
onClose = onContainerClose,

View File

@ -35,7 +35,7 @@ function HealthBar.init()
connect(g_game, { onGameEnd = HealthBar.offline })
healthBarWindow = displayUI('healthbar.otui', GameInterface.getRightPanel())
healthBarWindow = g_ui.loadUI('healthbar.otui', GameInterface.getRightPanel())
healthBarButton = TopMenu.addGameToggleButton('healthBarButton', tr('Health Bar'), 'healthbar.png', HealthBar.toggle)
healthBarButton:setOn(true)
healthBar = healthBarWindow:recursiveGetChildById('healthBar')
@ -127,7 +127,7 @@ function HealthBar.toggleIcon(bitChanged)
if icon then
icon:destroy()
else
icon = createWidget('ConditionWidget', content)
icon = g_ui.createWidget('ConditionWidget', content)
icon:setId(Icons[bitChanged].id)
icon:setImageSource(Icons[bitChanged].path)
icon:setTooltip(Icons[bitChanged].tooltip)

View File

@ -34,11 +34,11 @@ local hotkeyColors = {
-- public functions
function HotkeysManager.init()
hotkeysWindow = displayUI('hotkeys_manager.otui')
hotkeysWindow = g_ui.displayUI('hotkeys_manager.otui')
hotkeysWindow:setVisible(false)
hotkeysButton = TopMenu.addGameButton('hotkeysButton', tr('Hotkeys') .. ' (Ctrl+K)', '/game_hotkeys/icon.png', HotkeysManager.toggle)
Keyboard.bindKeyDown('Ctrl+K', HotkeysManager.toggle)
g_keyboard.bindKeyDown('Ctrl+K', HotkeysManager.toggle)
currentHotkeysList = hotkeysWindow:getChildById('currentHotkeys')
currentItemPreview = hotkeysWindow:getChildById('itemPreview')
@ -53,7 +53,7 @@ function HotkeysManager.init()
useOnTarget = hotkeysWindow:getChildById('useOnTarget')
useWith = hotkeysWindow:getChildById('useWith')
itemWidget = createWidget('UIItem')
itemWidget = g_ui.createWidget('UIItem')
itemWidget:setVirtual(true)
itemWidget:setVisible(false)
itemWidget:setFocusable(false)
@ -66,7 +66,7 @@ function HotkeysManager.init()
end
function HotkeysManager.load()
local hotkeySettings = Settings.getNode('HotkeysManager')
local hotkeySettings = g_settings.getNode('HotkeysManager')
local hasCombos = false
if hotkeySettings ~= nil then
@ -79,7 +79,7 @@ function HotkeysManager.load()
-- add default F keys combos
if not hasCombos then
for i=1,12 do
HotkeysManager.addKeyCombo(nil, 'F' .. i, nil)
HotkeysManager.addKeyCombo(nil, 'F' .. i)
end
end
end
@ -95,13 +95,13 @@ function HotkeysManager.save()
value = child.value})
end
Settings.setNode('HotkeysManager', hotkeySettings)
g_settings.setNode('HotkeysManager', hotkeySettings)
end
function HotkeysManager.terminate()
hotkeysManagerLoaded = false
Keyboard.unbindKeyDown('Ctrl+K')
g_keyboard.unbindKeyDown('Ctrl+K')
HotkeysManager.save()
currentHotkeysList = nil
@ -179,20 +179,20 @@ function HotkeysManager.onChooseItemMouseRelease(self, mousePosition, mouseButto
HotkeysManager:show()
end
Mouse.restoreCursor()
g_mouse.restoreCursor()
self:ungrabMouse()
self:destroy()
end
function HotkeysManager.startChooseItem()
local mouseGrabberWidget = createWidget('UIWidget')
local mouseGrabberWidget = g_ui.createWidget('UIWidget')
mouseGrabberWidget:setVisible(false)
mouseGrabberWidget:setFocusable(false)
connect(mouseGrabberWidget, { onMouseRelease = HotkeysManager.onChooseItemMouseRelease })
mouseGrabberWidget:grabMouse()
Mouse.setTargetCursor()
g_mouse.setTargetCursor()
HotkeysManager:hide()
end
@ -210,7 +210,7 @@ end
function HotkeysManager.addHotkey()
local widget
messageBox = createWidget('MainWindow', rootWidget)
messageBox = g_ui.createWidget('MainWindow', rootWidget)
messageBox:grabKeyboard()
messageBox:setId('assignWindow')
messageBox:setText(tr('Button Assign'))
@ -218,13 +218,13 @@ function HotkeysManager.addHotkey()
messageBox:setHeight(140)
messageBox:setDragable(false)
widget = createWidget('Label', messageBox)
widget = g_ui.createWidget('Label', messageBox)
widget:setText(tr('Please, press the key you wish to add onto your hotkeys manager'))
widget:resizeToText()
widget:addAnchor(AnchorHorizontalCenter, 'parent', AnchorHorizontalCenter)
widget:addAnchor(AnchorTop, 'parent', AnchorTop)
widget = createWidget('Label', messageBox)
widget = g_ui.createWidget('Label', messageBox)
widget:setId('comboPreview')
widget:setText(tr('Current hotkey to add: %s', 'none'))
widget.keyCombo = ''
@ -233,7 +233,7 @@ function HotkeysManager.addHotkey()
widget:addAnchor(AnchorTop, 'prev', AnchorBottom)
widget:setMarginTop(20)
widget = createWidget('Button', messageBox)
widget = g_ui.createWidget('Button', messageBox)
widget:setId('cancelButton')
widget:setText(tr('Cancel'))
widget:setWidth(64)
@ -244,7 +244,7 @@ function HotkeysManager.addHotkey()
self:getParent():destroy()
end
widget = createWidget('Button', messageBox)
widget = g_ui.createWidget('Button', messageBox)
widget:setId('addButton')
widget:setText(tr('Add'))
widget:setWidth(64)
@ -263,7 +263,7 @@ end
function HotkeysManager.addKeyCombo(messageBox, keyCombo, keySettings)
local label = nil
if currentHotkeysList:getChildById(keyCombo) == nil then
local label = createWidget('HotkeyListLabel', currentHotkeysList)
local label = g_ui.createWidget('HotkeyListLabel', currentHotkeysList)
label:setId(keyCombo)
label:setColor(hotkeyColors.text)
label:setText(keyCombo..': ')
@ -286,7 +286,7 @@ function HotkeysManager.addKeyCombo(messageBox, keyCombo, keySettings)
HotkeysManager.checkSelectedHotkey(label)
hotkeyList[keyCombo] = label
Keyboard.bindKeyPress(keyCombo, function () HotkeysManager.call(keyCombo) end, nil, 350)
g_keyboard.bindKeyPress(keyCombo, function () HotkeysManager.call(keyCombo) end, nil, 350)
end
if messageBox then
@ -430,7 +430,7 @@ end
function HotkeysManager.removeHotkey()
if hotkeyLabelSelectedOnList ~= nil then
hotkeyList[hotkeyLabelSelectedOnList.keyCombo] = nil
Keyboard.unbindKeyPress(hotkeyLabelSelectedOnList.keyCombo)
g_keyboard.unbindKeyPress(hotkeyLabelSelectedOnList.keyCombo)
hotkeyLabelSelectedOnList:destroy()
end
end

View File

@ -19,10 +19,12 @@ local function onLeftPanelVisibilityChange(leftPanel, visible)
end
function GameInterface.init()
g_ui.importStyle('styles/countwindow.otui')
connect(g_game, { onGameStart = GameInterface.show }, true)
connect(g_game, { onGameEnd = GameInterface.hide }, true)
gameRootPanel = displayUI('gameinterface.otui')
gameRootPanel = g_ui.displayUI('gameinterface.otui')
gameRootPanel:hide()
gameRootPanel:lower()
@ -38,34 +40,34 @@ function GameInterface.init()
logoutButton = TopMenu.addRightButton('logoutButton', 'Logout', '/images/logout.png', GameInterface.tryLogout)
logoutButton:hide()
Keyboard.bindKeyPress('Up', function() g_game.walk(North) end, gameRootPanel, WALK_AUTO_REPEAT_DELAY)
Keyboard.bindKeyPress('Right', function() g_game.walk(East) end, gameRootPanel, WALK_AUTO_REPEAT_DELAY)
Keyboard.bindKeyPress('Down', function() g_game.walk(South) end, gameRootPanel, WALK_AUTO_REPEAT_DELAY)
Keyboard.bindKeyPress('Left', function() g_game.walk(West) end, gameRootPanel, WALK_AUTO_REPEAT_DELAY)
Keyboard.bindKeyPress('Numpad8', function() g_game.walk(North) end, gameRootPanel, WALK_AUTO_REPEAT_DELAY)
Keyboard.bindKeyPress('Numpad9', function() g_game.walk(NorthEast) end, gameRootPanel, WALK_AUTO_REPEAT_DELAY)
Keyboard.bindKeyPress('Numpad6', function() g_game.walk(East) end, gameRootPanel, WALK_AUTO_REPEAT_DELAY)
Keyboard.bindKeyPress('Numpad3', function() g_game.walk(SouthEast) end, gameRootPanel, WALK_AUTO_REPEAT_DELAY)
Keyboard.bindKeyPress('Numpad2', function() g_game.walk(South) end, gameRootPanel, WALK_AUTO_REPEAT_DELAY)
Keyboard.bindKeyPress('Numpad1', function() g_game.walk(SouthWest) end, gameRootPanel, WALK_AUTO_REPEAT_DELAY)
Keyboard.bindKeyPress('Numpad4', function() g_game.walk(West) end, gameRootPanel, WALK_AUTO_REPEAT_DELAY)
Keyboard.bindKeyPress('Numpad7', function() g_game.walk(NorthWest) end, gameRootPanel, WALK_AUTO_REPEAT_DELAY)
Keyboard.bindKeyPress('Ctrl+Up', function() g_game.turn(North) end, gameRootPanel, WALK_AUTO_REPEAT_DELAY)
Keyboard.bindKeyPress('Ctrl+Right', function() g_game.turn(East) end, gameRootPanel, WALK_AUTO_REPEAT_DELAY)
Keyboard.bindKeyPress('Ctrl+Down', function() g_game.turn(South) end, gameRootPanel, WALK_AUTO_REPEAT_DELAY)
Keyboard.bindKeyPress('Ctrl+Left', function() g_game.turn(West) end, gameRootPanel, WALK_AUTO_REPEAT_DELAY)
Keyboard.bindKeyPress('Ctrl+Numpad8', function() g_game.turn(North) end, gameRootPanel, WALK_AUTO_REPEAT_DELAY)
Keyboard.bindKeyPress('Ctrl+Numpad6', function() g_game.turn(East) end, gameRootPanel, WALK_AUTO_REPEAT_DELAY)
Keyboard.bindKeyPress('Ctrl+Numpad2', function() g_game.turn(South) end, gameRootPanel, WALK_AUTO_REPEAT_DELAY)
Keyboard.bindKeyPress('Ctrl+Numpad4', function() g_game.turn(West) end, gameRootPanel, WALK_AUTO_REPEAT_DELAY)
Keyboard.bindKeyPress('Escape', function() g_game.cancelAttackAndFollow() end, gameRootPanel, WALK_AUTO_REPEAT_DELAY)
Keyboard.bindKeyPress('Ctrl+=', function() gameMapPanel:zoomIn() end, gameRootPanel, 250)
Keyboard.bindKeyPress('Ctrl+-', function() gameMapPanel:zoomOut() end, gameRootPanel, 250)
Keyboard.bindKeyDown('Ctrl+Q', GameInterface.tryLogout, gameRootPanel)
Keyboard.bindKeyDown('Ctrl+L', GameInterface.tryLogout, gameRootPanel)
Keyboard.bindKeyDown('Ctrl+W', function() g_map.cleanTexts() TextMessage.clearMessages() end, gameRootPanel)
g_keyboard.bindKeyPress('Up', function() g_game.walk(North) end, gameRootPanel, WALK_AUTO_REPEAT_DELAY)
g_keyboard.bindKeyPress('Right', function() g_game.walk(East) end, gameRootPanel, WALK_AUTO_REPEAT_DELAY)
g_keyboard.bindKeyPress('Down', function() g_game.walk(South) end, gameRootPanel, WALK_AUTO_REPEAT_DELAY)
g_keyboard.bindKeyPress('Left', function() g_game.walk(West) end, gameRootPanel, WALK_AUTO_REPEAT_DELAY)
g_keyboard.bindKeyPress('Numpad8', function() g_game.walk(North) end, gameRootPanel, WALK_AUTO_REPEAT_DELAY)
g_keyboard.bindKeyPress('Numpad9', function() g_game.walk(NorthEast) end, gameRootPanel, WALK_AUTO_REPEAT_DELAY)
g_keyboard.bindKeyPress('Numpad6', function() g_game.walk(East) end, gameRootPanel, WALK_AUTO_REPEAT_DELAY)
g_keyboard.bindKeyPress('Numpad3', function() g_game.walk(SouthEast) end, gameRootPanel, WALK_AUTO_REPEAT_DELAY)
g_keyboard.bindKeyPress('Numpad2', function() g_game.walk(South) end, gameRootPanel, WALK_AUTO_REPEAT_DELAY)
g_keyboard.bindKeyPress('Numpad1', function() g_game.walk(SouthWest) end, gameRootPanel, WALK_AUTO_REPEAT_DELAY)
g_keyboard.bindKeyPress('Numpad4', function() g_game.walk(West) end, gameRootPanel, WALK_AUTO_REPEAT_DELAY)
g_keyboard.bindKeyPress('Numpad7', function() g_game.walk(NorthWest) end, gameRootPanel, WALK_AUTO_REPEAT_DELAY)
g_keyboard.bindKeyPress('Ctrl+Up', function() g_game.turn(North) end, gameRootPanel, WALK_AUTO_REPEAT_DELAY)
g_keyboard.bindKeyPress('Ctrl+Right', function() g_game.turn(East) end, gameRootPanel, WALK_AUTO_REPEAT_DELAY)
g_keyboard.bindKeyPress('Ctrl+Down', function() g_game.turn(South) end, gameRootPanel, WALK_AUTO_REPEAT_DELAY)
g_keyboard.bindKeyPress('Ctrl+Left', function() g_game.turn(West) end, gameRootPanel, WALK_AUTO_REPEAT_DELAY)
g_keyboard.bindKeyPress('Ctrl+Numpad8', function() g_game.turn(North) end, gameRootPanel, WALK_AUTO_REPEAT_DELAY)
g_keyboard.bindKeyPress('Ctrl+Numpad6', function() g_game.turn(East) end, gameRootPanel, WALK_AUTO_REPEAT_DELAY)
g_keyboard.bindKeyPress('Ctrl+Numpad2', function() g_game.turn(South) end, gameRootPanel, WALK_AUTO_REPEAT_DELAY)
g_keyboard.bindKeyPress('Ctrl+Numpad4', function() g_game.turn(West) end, gameRootPanel, WALK_AUTO_REPEAT_DELAY)
g_keyboard.bindKeyPress('Escape', function() g_game.cancelAttackAndFollow() end, gameRootPanel, WALK_AUTO_REPEAT_DELAY)
g_keyboard.bindKeyPress('Ctrl+=', function() gameMapPanel:zoomIn() end, gameRootPanel, 250)
g_keyboard.bindKeyPress('Ctrl+-', function() gameMapPanel:zoomOut() end, gameRootPanel, 250)
g_keyboard.bindKeyDown('Ctrl+Q', GameInterface.tryLogout, gameRootPanel)
g_keyboard.bindKeyDown('Ctrl+L', GameInterface.tryLogout, gameRootPanel)
g_keyboard.bindKeyDown('Ctrl+W', function() g_map.cleanTexts() TextMessage.clearMessages() end, gameRootPanel)
Keyboard.bindKeyDown('Ctrl+.', function()
g_keyboard.bindKeyDown('Ctrl+.', function()
if gameMapPanel:isKeepAspectRatioEnabled() then
gameMapPanel:setKeepAspectRatio(false)
else
@ -141,7 +143,7 @@ function GameInterface.onMouseGrabberRelease(self, mousePosition, mouseButton)
end
GameInterface.selectedThing = nil
Mouse.restoreCursor()
g_mouse.restoreCursor()
self:ungrabMouse()
return true
end
@ -170,18 +172,18 @@ function GameInterface.startUseWith(thing)
GameInterface.selectedType = 'use'
GameInterface.selectedThing = thing
mouseGrabberWidget:grabMouse()
Mouse.setTargetCursor()
g_mouse.setTargetCursor()
end
function GameInterface.startTradeWith(thing)
GameInterface.selectedType = 'trade'
GameInterface.selectedThing = thing
mouseGrabberWidget:grabMouse()
Mouse.setTargetCursor()
g_mouse.setTargetCursor()
end
function GameInterface.createThingMenu(menuPosition, lookThing, useThing, creatureThing)
local menu = createWidget('PopupMenu')
local menu = g_ui.createWidget('PopupMenu')
if lookThing then
menu:addOption(tr('Look'), function() g_game.look(lookThing) end)
@ -191,9 +193,9 @@ function GameInterface.createThingMenu(menuPosition, lookThing, useThing, creatu
if useThing:isContainer() then
if useThing:getParentContainer() then
menu:addOption(tr('Open'), function() g_game.open(useThing, useThing:getParentContainer()) end)
menu:addOption(tr('Open in new window'), function() g_game.open(useThing, nil) end)
menu:addOption(tr('Open in new window'), function() g_game.open(useThing) end)
else
menu:addOption(tr('Open'), function() g_game.open(useThing, nil) end)
menu:addOption(tr('Open'), function() g_game.open(useThing) end)
end
else
if useThing:isMultiUse() then
@ -303,7 +305,7 @@ function GameInterface.createThingMenu(menuPosition, lookThing, useThing, creatu
end
function GameInterface.processMouseAction(menuPosition, mouseButton, autoWalk, lookThing, useThing, creatureThing, multiUseThing)
local keyboardModifiers = Keyboard.getModifiers()
local keyboardModifiers = g_keyboard.getModifiers()
if autoWalk and keyboardModifiers == KeyboardNoModifier and mouseButton == MouseLeftButton then
-- todo auto walk
@ -323,7 +325,7 @@ function GameInterface.processMouseAction(menuPosition, mouseButton, autoWalk, l
g_game.open(useThing, useThing:getParentContainer())
return true
else
g_game.open(useThing, nil)
g_game.open(useThing)
return true
end
elseif useThing:isMultiUse() then
@ -348,7 +350,7 @@ function GameInterface.processMouseAction(menuPosition, mouseButton, autoWalk, l
g_game.open(multiUseThing, multiUseThing:getParentContainer())
return true
else
g_game.open(multiUseThing, nil)
g_game.open(multiUseThing)
return true
end
elseif multiUseThing:isMultiUse() then
@ -374,16 +376,16 @@ function GameInterface.processMouseAction(menuPosition, mouseButton, autoWalk, l
end
function GameInterface.moveStackableItem(item, toPos)
if Keyboard.isCtrlPressed() then
if g_keyboard.isCtrlPressed() then
g_game.move(item, toPos, item:getCount())
return
elseif Keyboard.isShiftPressed() then
elseif g_keyboard.isShiftPressed() then
g_game.move(item, toPos, 1)
return
end
local count = item:getCount()
local countWindow = createWidget('CountWindow', rootWidget)
local countWindow = g_ui.createWidget('CountWindow', rootWidget)
local spinbox = countWindow:getChildById('countSpinBox')
local scrollbar = countWindow:getChildById('countScrollBar')
spinbox:setMaximum(count)

View File

@ -5,8 +5,6 @@ Module
website: www.otclient.info
@onLoad: |
importStyle 'styles/countwindow.otui'
dofile 'widgets/uigamemap'
dofile 'widgets/uiitem'

View File

@ -16,13 +16,13 @@ function UIGameMap:onDragEnter(mousePos)
if not thing then return false end
self.currentDragThing = thing
Mouse.setTargetCursor()
g_mouse.setTargetCursor()
return true
end
function UIGameMap:onDragLeave(droppedWidget, mousePos)
self.currentDragThing = nil
Mouse.restoreCursor()
g_mouse.restoreCursor()
return true
end
@ -57,8 +57,8 @@ function UIGameMap:onMouseRelease(mousePosition, mouseButton)
if tile == nil then return false end
if Options.getOption('classicControl') and
((Mouse.isPressed(MouseLeftButton) and mouseButton == MouseRightButton) or
(Mouse.isPressed(MouseRightButton) and mouseButton == MouseLeftButton)) then
((g_mouse.isPressed(MouseLeftButton) and mouseButton == MouseRightButton) or
(g_mouse.isPressed(MouseRightButton) and mouseButton == MouseLeftButton)) then
local tile = self:getTile(mousePosition)
g_game.look(tile:getTopLookThing())
self.cancelNextRelease = true

View File

@ -6,14 +6,14 @@ function UIItem:onDragEnter(mousePos)
self:setBorderWidth(1)
self.currentDragThing = item
Mouse.setTargetCursor()
g_mouse.setTargetCursor()
return true
end
function UIItem:onDragLeave(droppedWidget, mousePos)
if self:isVirtual() then return false end
self.currentDragThing = nil
Mouse.restoreCursor()
g_mouse.restoreCursor()
self:setBorderWidth(0)
return true
end
@ -68,8 +68,8 @@ function UIItem:onMouseRelease(mousePosition, mouseButton)
if not item or not self:containsPoint(mousePosition) then return false end
if Options.getOption('classicControl') and
((Mouse.isPressed(MouseLeftButton) and mouseButton == MouseRightButton) or
(Mouse.isPressed(MouseRightButton) and mouseButton == MouseLeftButton)) then
((g_mouse.isPressed(MouseLeftButton) and mouseButton == MouseRightButton) or
(g_mouse.isPressed(MouseRightButton) and mouseButton == MouseLeftButton)) then
g_game.look(item)
self.cancelNextRelease = true
return true

View File

@ -11,9 +11,9 @@ function Inventory.init()
onFreeCapacityChange = Inventory.onFreeCapacityChange })
connect(g_game, { onGameStart = Inventory.refresh })
Keyboard.bindKeyDown('Ctrl+I', Inventory.toggle)
g_keyboard.bindKeyDown('Ctrl+I', Inventory.toggle)
inventoryWindow = displayUI('inventory.otui', GameInterface.getRightPanel())
inventoryWindow = g_ui.loadUI('inventory.otui', GameInterface.getRightPanel())
inventoryPanel = inventoryWindow:getChildById('contentsPanel')
inventoryButton = TopMenu.addGameToggleButton('inventoryButton', tr('Inventory') .. ' (Ctrl+I)', 'inventory.png', Inventory.toggle)
inventoryButton:setOn(true)
@ -26,7 +26,7 @@ function Inventory.terminate()
onFreeCapacityChange = Inventory.onFreeCapacityChange })
disconnect(g_game, { onGameStart = Inventory.refresh })
Keyboard.unbindKeyDown('Ctrl+I')
g_keyboard.unbindKeyDown('Ctrl+I')
inventoryWindow:destroy()
inventoryButton:destroy()

View File

@ -34,12 +34,12 @@ end
-- public functions
function Minimap.init()
connect(g_game, { onGameStart = Minimap.reset })
Keyboard.bindKeyDown('Ctrl+M', Minimap.toggle)
g_keyboard.bindKeyDown('Ctrl+M', Minimap.toggle)
minimapButton = TopMenu.addGameToggleButton('minimapButton', tr('Minimap') .. ' (Ctrl+M)', 'minimap.png', Minimap.toggle)
minimapButton:setOn(true)
minimapWindow = loadUI('minimap.otui', GameInterface.getRightPanel())
minimapWindow = g_ui.loadUI('minimap.otui', GameInterface.getRightPanel())
minimapWidget = minimapWindow:recursiveGetChildById('minimap')
minimapWidget:setAutoViewMode(false)
@ -72,7 +72,7 @@ end
function Minimap.terminate()
disconnect(g_game, { onGameStart = Minimap.reset })
Keyboard.unbindKeyDown('Ctrl+M')
g_keyboard.unbindKeyDown('Ctrl+M')
minimapButton:destroy()
minimapWindow:destroy()

View File

@ -142,11 +142,11 @@ local function refreshTradeItems()
if radioItems then
radioItems:destroy()
end
radioItems = RadioGroup.create()
radioItems = UIRadioGroup.create()
local currentTradeItems = tradeItems[getCurrentTradeType()]
for key,item in pairs(currentTradeItems) do
local itemBox = createWidget('NPCItemBox', itemsPanel)
local itemBox = g_ui.createWidget('NPCItemBox', itemsPanel)
itemBox.item = item
local name = item.name
@ -262,7 +262,7 @@ end
-- public functions
function NPCTrade.init()
npcWindow = displayUI('npctrade.otui')
npcWindow = g_ui.displayUI('npctrade.otui')
npcWindow:setVisible(false)
itemsPanel = npcWindow:recursiveGetChildById('itemsPanel')
@ -286,7 +286,7 @@ function NPCTrade.init()
buyTab = npcWindow:getChildById('buyTab')
sellTab = npcWindow:getChildById('sellTab')
radioTabs = RadioGroup.create()
radioTabs = UIRadioGroup.create()
radioTabs:addWidget(buyTab)
radioTabs:addWidget(sellTab)
radioTabs:selectWidget(buyTab)
@ -403,7 +403,7 @@ end
function NPCTrade.itemPopup(self, mousePosition, mouseButton)
if mouseButton == MouseRightButton then
local menu = createWidget('PopupMenu')
local menu = g_ui.createWidget('PopupMenu')
menu:addOption(tr('Look'), function() return g_game.inspectNpcTrade(self:getItem()) end)
menu:display(mousePosition)
return true

View File

@ -135,7 +135,7 @@ function Outfit.create(creature, outfitList)
outfits = outfitList
Outfit.destroy()
outfitWindow = displayUI('outfit.otui')
outfitWindow = g_ui.displayUI('outfit.otui')
--outfitWindow:lock()
outfit = outfitCreature:getOutfit()
@ -152,7 +152,7 @@ function Outfit.create(creature, outfitList)
for j=0,6 do
for i=0,18 do
local colorBox = createWidget('ColorBox', colorBoxPanel)
local colorBox = g_ui.createWidget('ColorBox', colorBoxPanel)
local outfitColor = getOufitColor(j*19 + i)
colorBox:setImageColor(outfitColor)
colorBox:setId('colorBox' .. j*19+i)

View File

@ -3,7 +3,7 @@ PlayerTrade = {}
local tradeWindow
local function createTrade()
tradeWindow = createWidget('TradeWindow', GameInterface.getRightPanel())
tradeWindow = g_ui.createWidget('TradeWindow', GameInterface.getRightPanel())
tradeWindow.onClose = function()
g_game.rejectTrade()
tradeWindow:hide()
@ -32,7 +32,7 @@ local function fillTrade(name, items, counter)
label:setText(name)
for index,item in ipairs(items) do
local itemWidget = createWidget('Item', tradeContainer)
local itemWidget = g_ui.createWidget('Item', tradeContainer)
itemWidget:setItem(item)
itemWidget:setVirtual(true)
itemWidget:setMargin(1)
@ -57,7 +57,7 @@ local function onGameCloseTrade()
end
function PlayerTrade.init()
importStyle 'tradewindow.otui'
g_ui.importStyle('tradewindow.otui')
connect(g_game, { onOwnTrade = onGameOwnTrade,
onCounterTrade = onGameCounterTrade,

View File

@ -7,13 +7,13 @@ local questLineWindow
local function onGameQuestLog(quests)
QuestLog.destroyWindows()
questLogWindow = createWidget('QuestLogWindow', rootWidget)
questLogWindow = g_ui.createWidget('QuestLogWindow', rootWidget)
local questList = questLogWindow:getChildById('questList')
for i,questEntry in pairs(quests) do
local id, name, completed = unpack(questEntry)
local questLabel = createWidget('QuestLabel', questList)
local questLabel = g_ui.createWidget('QuestLabel', questList)
questLabel:setOn(completed)
questLabel:setText(name)
questLabel.onDoubleClick = function()
@ -31,7 +31,7 @@ local function onGameQuestLine(questId, questMissions)
if questLogWindow then questLogWindow:hide() end
if questLineWindow then questLineWindow:destroy() end
questLineWindow = createWidget('QuestLineWindow', rootWidget)
questLineWindow = g_ui.createWidget('QuestLineWindow', rootWidget)
local missionList = questLineWindow:getChildById('missionList')
local missionDescription = questLineWindow:getChildById('missionDescription')
@ -43,7 +43,7 @@ local function onGameQuestLine(questId, questMissions)
for i,questMission in pairs(questMissions) do
local name, description = unpack(questMission)
local missionLabel = createWidget('MissionLabel', missionList)
local missionLabel = g_ui.createWidget('MissionLabel', missionList)
missionLabel:setText(name)
missionLabel.description = description
end
@ -55,8 +55,8 @@ local function onGameQuestLine(questId, questMissions)
end
function QuestLog.init()
importStyle 'questlogwindow.otui'
importStyle 'questlinewindow.otui'
g_ui.importStyle('questlogwindow.otui')
g_ui.importStyle('questlinewindow.otui')
questLogButton = TopMenu.addGameButton('questLogButton', tr('Quest Log'), 'questlog.png', function() g_game.requestQuestLog() end)

View File

@ -47,7 +47,7 @@ function RuleViolation.loadReasons()
local actions = g_game.getGMActions()
for reason, actionFlags in pairs(actions) do
local label = createWidget('RVListLabel', reasonsTextList)
local label = g_ui.createWidget('RVListLabel', reasonsTextList)
label:setText(rvreasons[reason])
label.reasonId = reason
label.actionFlags = actionFlags
@ -59,13 +59,13 @@ end
function RuleViolation.init()
connect(g_game, { onGMActions = RuleViolation.loadReasons })
ruleViolationWindow = displayUI('ruleviolation.otui')
ruleViolationWindow = g_ui.displayUI('ruleviolation.otui')
ruleViolationWindow:setVisible(false)
reasonsTextList = ruleViolationWindow:getChildById('reasonList')
actionsTextList = ruleViolationWindow:getChildById('actionList')
Keyboard.bindKeyDown('Ctrl+Y', RuleViolation.show)
g_keyboard.bindKeyDown('Ctrl+Y', RuleViolation.show)
if g_game.isOnline() then
RuleViolation.loadReasons()
@ -108,7 +108,7 @@ function RuleViolation.onSelectReason(reasonLabel, focused)
for actionBaseFlag = 0, #rvactions do
actionFlagString = rvactions[actionBaseFlag]
if bit32.band(reasonLabel.actionFlags, math.pow(2, actionBaseFlag)) > 0 then
local label = createWidget('RVListLabel', actionsTextList)
local label = g_ui.createWidget('RVListLabel', actionsTextList)
label:setText(actionFlagString)
label.actionId = actionBaseFlag
end

View File

@ -23,11 +23,11 @@ local ITEM_SHADERS = {
local shadersPanel
function Shaders.init()
importStyle 'shaders.otui'
g_ui.importStyle('shaders.otui')
Keyboard.bindKeyDown(HOTKEY, Shaders.toggle)
g_keyboard.bindKeyDown(HOTKEY, Shaders.toggle)
shadersPanel = createWidget('ShadersPanel', GameInterface.getMapPanel())
shadersPanel = g_ui.createWidget('ShadersPanel', GameInterface.getMapPanel())
shadersPanel:hide()
local mapComboBox = shadersPanel:getChildById('mapComboBox')
@ -56,7 +56,7 @@ function Shaders.init()
end
function Shaders.terminate()
Keyboard.unbindKeyDown(HOTKEY)
g_keyboard.unbindKeyDown(HOTKEY)
shadersPanel:destroy()
shadersPanel = nil
end

View File

@ -35,10 +35,10 @@ function Skills.init()
onSkillChange = Skills.onSkillChange
})
skillsWindow = displayUI('skills.otui', GameInterface.getRightPanel())
skillsWindow = g_ui.loadUI('skills.otui', GameInterface.getRightPanel())
skillsButton = TopMenu.addGameToggleButton('skillsButton', tr('Skills') .. ' (Ctrl+S)', 'skills.png', Skills.toggle)
skillsButton:setOn(true)
Keyboard.bindKeyDown('Ctrl+S', Skills.toggle)
g_keyboard.bindKeyDown('Ctrl+S', Skills.toggle)
Skills.refresh()
end
@ -56,7 +56,7 @@ function Skills.terminate()
onSkillChange = Skills.onSkillChange
})
Keyboard.unbindKeyDown('Ctrl+S')
g_keyboard.unbindKeyDown('Ctrl+S')
skillsButton:destroy()
skillsButton = nil
skillsWindow:destroy()

View File

@ -1,7 +1,7 @@
TextBooks = {}
local function onGameEditText(id, itemId, maxLength, text, writter, time)
local textWindow = createWidget('TextWindow', rootWidget)
local textWindow = g_ui.createWidget('TextWindow', rootWidget)
local writeable = (maxLength ~= #text) and maxLength > 0
local textItem = textWindow:getChildById('textItem')
@ -50,7 +50,7 @@ local function onGameEditText(id, itemId, maxLength, text, writter, time)
end
local function onGameEditList(id, doorId, text)
local textWindow = createWidget('TextWindow', rootWidget)
local textWindow = g_ui.createWidget('TextWindow', rootWidget)
local textEdit = textWindow:getChildById('text')
local description = textWindow:getChildById('description')
@ -70,7 +70,7 @@ local function onGameEditList(id, doorId, text)
end
function TextBooks.init()
importStyle 'textwindow.otui'
g_ui.importStyle('textwindow.otui')
connect(g_game, { onEditText = onGameEditText })
connect(g_game, { onEditList = onGameEditList })

View File

@ -1,7 +1,7 @@
TextMessage = {}
-- require styles
importStyle 'textmessage.otui'
g_ui.importStyle('textmessage.otui')
-- private variables
local MessageTypes = {
@ -49,7 +49,7 @@ local function displayMessage(msgtype, msg, time)
end
local function createTextMessageLabel(id, parent, class)
local label = createWidget(class, parent)
local label = g_ui.createWidget(class, parent)
label:setFont('verdana-11px-rounded')
label:setId(id)
return label
@ -61,7 +61,7 @@ function TextMessage.init()
onTextMessage = TextMessage.display,
onGameStart = TextMessage.clearMessages })
centerTextMessagePanel = createWidget('Panel', GameInterface.getMapPanel())
centerTextMessagePanel = g_ui.createWidget('Panel', GameInterface.getMapPanel())
centerTextMessagePanel:setId('centerTextMessagePanel')
local layout = UIVerticalLayout.create(centerTextMessagePanel)

View File

@ -12,9 +12,9 @@ function VipList.init()
onVipStateChange = VipList.onVipStateChange })
Keyboard.bindKeyDown('Ctrl+P', VipList.toggle)
g_keyboard.bindKeyDown('Ctrl+P', VipList.toggle)
vipWindow = displayUI('viplist.otui', GameInterface.getRightPanel())
vipWindow = g_ui.loadUI('viplist.otui', GameInterface.getRightPanel())
vipButton = TopMenu.addGameToggleButton('vipListButton', tr('VIP list') .. ' (Ctrl+P)', 'viplist.png', VipList.toggle)
vipButton:setOn(true)
@ -22,7 +22,7 @@ function VipList.init()
end
function VipList.terminate()
Keyboard.unbindKeyDown('Ctrl+P')
g_keyboard.unbindKeyDown('Ctrl+P')
disconnect(g_game, { onGameEnd = VipList.clear,
onAddVip = VipList.onAddVip,
onVipStateChange = VipList.onVipStateChange })
@ -62,7 +62,7 @@ function VipList.onMiniWindowClose()
end
function VipList.createAddWindow()
addVipWindow = displayUI('addvip.otui')
addVipWindow = g_ui.displayUI('addvip.otui')
end
function VipList.destroyAddWindow()
@ -79,7 +79,7 @@ end
function VipList.onAddVip(id, name, online)
local vipList = vipWindow:getChildById('contentsPanel')
local label = createWidget('VipListLabel', nil)
local label = g_ui.createWidget('VipListLabel')
label:setId('vip' .. id)
label:setText(name)
@ -136,7 +136,7 @@ function VipList.onVipListMousePress(widget, mousePos, mouseButton)
local vipList = vipWindow:getChildById('contentsPanel')
local menu = createWidget('PopupMenu')
local menu = g_ui.createWidget('PopupMenu')
menu:addOption(tr('Add new VIP'), function() VipList.createAddWindow() end)
menu:display(mousePos)
@ -148,7 +148,7 @@ function VipList.onVipListLabelMousePress(widget, mousePos, mouseButton)
local vipList = vipWindow:getChildById('contentsPanel')
local menu = createWidget('PopupMenu')
local menu = g_ui.createWidget('PopupMenu')
menu:addOption(tr('Add new VIP'), function() VipList.createAddWindow() end)
menu:addOption(tr('Remove %s', widget:getText()), function() if widget then g_game.removeVip(widget:getId():sub(4)) vipList:removeChild(widget) end end)
menu:addSeparator()

View File

@ -1,4 +1,4 @@
-- this file is loaded after all modules are loaded and initialized
-- you can place any custom user code here
Keyboard.bindKeyDown('Ctrl+Shift+R', Client.reloadScripts)
g_keyboard.bindKeyDown('Ctrl+Shift+R', Client.reloadScripts)

View File

@ -47,7 +47,7 @@ void exitSignalHandler(int sig)
case SIGINT:
if(!signaled) {
signaled = true;
g_eventDispatcher.addEvent(std::bind(&Application::close, &g_app));
g_dispatcher.addEvent(std::bind(&Application::close, &g_app));
}
break;
}
@ -155,7 +155,7 @@ void Application::terminate()
g_lua.terminate();
// flush remaining dispatcher events
g_eventDispatcher.flush();
g_dispatcher.flush();
// terminate graphics
m_foreground = nullptr;
@ -182,7 +182,7 @@ void Application::run()
g_clock.update();
// show the application only after we draw some frames
g_eventDispatcher.scheduleEvent([] { g_window.show(); }, 10);
g_dispatcher.scheduleEvent([] { g_window.show(); }, 10);
while(!m_stopping) {
@ -281,7 +281,7 @@ void Application::poll()
//g_particleManager.update();
Connection::poll();
g_eventDispatcher.poll();
g_dispatcher.poll();
}
void Application::close()

View File

@ -25,7 +25,7 @@
#include <framework/core/clock.h>
#include "timer.h"
EventDispatcher g_eventDispatcher;
EventDispatcher g_dispatcher;
void EventDispatcher::flush()

View File

@ -26,7 +26,7 @@
#include "clock.h"
#include "scheduledevent.h"
// @bindsingleton g_eventDispatcher
// @bindsingleton g_dispatcher
class EventDispatcher
{
public:
@ -44,6 +44,6 @@ private:
std::priority_queue<ScheduledEventPtr, std::vector<ScheduledEventPtr>, lessScheduledEvent> m_scheduledEventList;
};
extern EventDispatcher g_eventDispatcher;
extern EventDispatcher g_dispatcher;
#endif

View File

@ -54,7 +54,7 @@ void Logger::log(Fw::LogLevel level, const std::string& message)
if(m_onLog) {
// schedule log callback, because this callback can run lua code that may affect the current state
g_eventDispatcher.addEvent([=] {
g_dispatcher.addEvent([=] {
if(m_onLog)
m_onLog(level, outmsg, now);
});

View File

@ -42,7 +42,7 @@ AnimatedTexture::AnimatedTexture(int width, int height, int channels, int numFra
m_framesDelay[i] = framesDelay[i];
}
m_currentFrame = -1;
g_eventDispatcher.scheduleEvent(std::bind(&AnimatedTexture::processAnimation, this), 0);
g_dispatcher.scheduleEvent(std::bind(&AnimatedTexture::processAnimation, this), 0);
}
AnimatedTexture::~AnimatedTexture()
@ -71,6 +71,6 @@ void AnimatedTexture::processAnimation()
// continue to animate only if something still referencing this texture
if(self.use_count() > 1)
g_eventDispatcher.scheduleEvent(std::bind(&AnimatedTexture::processAnimation, self), m_framesDelay[m_currentFrame]);
g_dispatcher.scheduleEvent(std::bind(&AnimatedTexture::processAnimation, self), m_framesDelay[m_currentFrame]);
}
*/

View File

@ -594,7 +594,8 @@ void Application::registerLuaFunctions()
g_lua.bindSingletonFunction("g_ui", "getStyle", &UIManager::getStyle, &g_ui);
g_lua.bindSingletonFunction("g_ui", "getStyleClass", &UIManager::getStyleClass, &g_ui);
g_lua.bindSingletonFunction("g_ui", "loadUI", &UIManager::loadUI, &g_ui);
g_lua.bindSingletonFunction("g_ui", "createWidgetFromStyle", &UIManager::createWidgetFromStyle, &g_ui);
g_lua.bindSingletonFunction("g_ui", "displayUI", &UIManager::displayUI, &g_ui);
g_lua.bindSingletonFunction("g_ui", "createWidget", &UIManager::createWidget, &g_ui);
g_lua.bindSingletonFunction("g_ui", "createWidgetFromOTML", &UIManager::createWidgetFromOTML, &g_ui);
g_lua.bindSingletonFunction("g_ui", "getRootWidget", &UIManager::getRootWidget, &g_ui);
g_lua.bindSingletonFunction("g_ui", "getDraggingWidget", &UIManager::getDraggingWidget, &g_ui);
@ -634,10 +635,10 @@ void Application::registerLuaFunctions()
g_lua.bindSingletonFunction("g_sounds", "getCurrentMusic", &SoundManager::getCurrentMusic, &g_sounds);
// EventDispatcher
g_lua.registerSingletonClass("g_eventDispatcher");
g_lua.bindSingletonFunction("g_eventDispatcher", "addEvent", &EventDispatcher::addEvent, &g_eventDispatcher);
g_lua.bindSingletonFunction("g_eventDispatcher", "scheduleEvent", &EventDispatcher::scheduleEvent, &g_eventDispatcher);
g_lua.bindSingletonFunction("g_eventDispatcher", "cycleEvent", &EventDispatcher::cycleEvent, &g_eventDispatcher);
g_lua.registerSingletonClass("g_dispatcher");
g_lua.bindSingletonFunction("g_dispatcher", "addEvent", &EventDispatcher::addEvent, &g_dispatcher);
g_lua.bindSingletonFunction("g_dispatcher", "scheduleEvent", &EventDispatcher::scheduleEvent, &g_dispatcher);
g_lua.bindSingletonFunction("g_dispatcher", "cycleEvent", &EventDispatcher::cycleEvent, &g_dispatcher);
// ResourceManager
g_lua.registerSingletonClass("g_resources");

View File

@ -96,8 +96,12 @@ namespace luabinder
LuaCppFunction bind_fun_specializer(const F& f) {
enum { N = std::tuple_size<Tuple>::value };
return [=](LuaInterface* lua) -> int {
if(lua->stackSize() != N)
throw LuaBadNumberOfArgumentsException(N, lua->stackSize());
while(lua->stackSize() != N) {
if(lua->stackSize() < N)
g_lua.pushNil();
else
g_lua.pop();
}
Tuple tuple;
pack_values_into_tuple<N>::call(tuple, lua);
return expand_fun_arguments<N,Ret>::call(tuple, f, lua);

View File

@ -127,7 +127,7 @@ void Connection::write(uint8* buffer, uint16 size)
auto weakSelf = ConnectionWeakPtr(shared_from_this());
// wait 1 ms to do the real send
m_sendEvent = g_eventDispatcher.scheduleEvent([=] {
m_sendEvent = g_dispatcher.scheduleEvent([=] {
if(!weakSelf.lock())
return;
//m_writeTimer.cancel();

View File

@ -119,7 +119,7 @@ bool UIGridLayout::internalUpdate()
if(m_fitChildren && preferredHeight != parentWidget->getHeight()) {
// must set the preferred height later
g_eventDispatcher.addEvent([=] {
g_dispatcher.addEvent([=] {
parentWidget->setHeight(preferredHeight);
});
}

View File

@ -85,7 +85,7 @@ bool UIHorizontalLayout::internalUpdate()
if(m_fitChildren && preferredWidth != parentWidget->getWidth()) {
// must set the preferred width later
g_eventDispatcher.addEvent([=] {
g_dispatcher.addEvent([=] {
parentWidget->setWidth(preferredWidth);
});
}

View File

@ -65,7 +65,7 @@ void UILayout::updateLater()
return;
auto self = asUILayout();
g_eventDispatcher.addEvent([self] {
g_dispatcher.addEvent([self] {
self->m_updateScheduled = false;
self->update();
});

View File

@ -214,7 +214,7 @@ void UIManager::updateHoveredWidget()
if(m_hoverUpdateScheduled)
return;
g_eventDispatcher.addEvent([this] {
g_dispatcher.addEvent([this] {
if(!m_rootWidget)
return;
@ -278,11 +278,11 @@ void UIManager::onWidgetDestroy(const UIWidgetPtr& widget)
if(m_checkEvent && !m_checkEvent->isExecuted())
return;
m_checkEvent = g_eventDispatcher.scheduleEvent([this] {
m_checkEvent = g_dispatcher.scheduleEvent([this] {
g_lua.collectGarbage();
UIWidgetList backupList = m_destroyedWidgets;
m_destroyedWidgets.clear();
g_eventDispatcher.scheduleEvent([backupList] {
g_dispatcher.scheduleEvent([backupList] {
g_lua.collectGarbage();
for(const UIWidgetPtr& widget : backupList) {
if(widget->getUseCount() != 1)
@ -404,7 +404,7 @@ UIWidgetPtr UIManager::loadUI(const std::string& file, const UIWidgetPtr& parent
}
}
UIWidgetPtr UIManager::createWidgetFromStyle(const std::string& styleName, const UIWidgetPtr& parent)
UIWidgetPtr UIManager::createWidget(const std::string& styleName, const UIWidgetPtr& parent)
{
OTMLNodePtr node = OTMLNode::create(styleName);
try {

View File

@ -49,7 +49,8 @@ public:
std::string getStyleClass(const std::string& styleName);
UIWidgetPtr loadUI(const std::string& file, const UIWidgetPtr& parent);
UIWidgetPtr createWidgetFromStyle(const std::string& styleName, const UIWidgetPtr& parent);
UIWidgetPtr displayUI(const std::string& file) { return loadUI(file, m_rootWidget); }
UIWidgetPtr createWidget(const std::string& styleName, const UIWidgetPtr& parent);
UIWidgetPtr createWidgetFromOTML(const OTMLNodePtr& widgetNode, const UIWidgetPtr& parent);
void setMouseReceiver(const UIWidgetPtr& widget) { m_mouseReceiver = widget; }

View File

@ -86,7 +86,7 @@ bool UIVerticalLayout::internalUpdate()
if(m_fitChildren && preferredHeight != parentWidget->getHeight()) {
// must set the preferred width later
g_eventDispatcher.addEvent([=] {
g_dispatcher.addEvent([=] {
parentWidget->setHeight(preferredHeight);
});
}

View File

@ -505,7 +505,7 @@ void UIWidget::applyStyle(const OTMLNodePtr& styleNode)
if(m_firstOnStyle) {
auto self = asUIWidget();
g_eventDispatcher.addEvent([self] {
g_dispatcher.addEvent([self] {
self->callLuaField("onSetup");
});
// always focus new child
@ -832,7 +832,7 @@ bool UIWidget::setRect(const Rect& rect)
// avoid massive update events
if(!m_updateEventScheduled) {
UIWidgetPtr self = asUIWidget();
g_eventDispatcher.addEvent([self, oldRect]() {
g_dispatcher.addEvent([self, oldRect]() {
self->m_updateEventScheduled = false;
if(oldRect != self->getRect())
self->onGeometryChange(oldRect, self->getRect());
@ -1318,7 +1318,7 @@ void UIWidget::updateStyle()
if(m_loadingStyle && !m_updateStyleScheduled) {
UIWidgetPtr self = asUIWidget();
g_eventDispatcher.addEvent([self] {
g_dispatcher.addEvent([self] {
self->m_updateStyleScheduled = false;
self->updateStyle();
});

View File

@ -53,7 +53,7 @@ void AnimatedText::startAnimation()
// schedule removal
auto self = asAnimatedText();
g_eventDispatcher.scheduleEvent([self]() { g_map.removeThing(self); }, Otc::ANIMATED_TEXT_DURATION);
g_dispatcher.scheduleEvent([self]() { g_map.removeThing(self); }, Otc::ANIMATED_TEXT_DURATION);
}
void AnimatedText::setColor(int color)

View File

@ -368,7 +368,7 @@ void Creature::nextWalkUpdate()
// schedules next update
if(m_walking) {
auto self = asCreature();
m_walkUpdateEvent = g_eventDispatcher.scheduleEvent([self] {
m_walkUpdateEvent = g_dispatcher.scheduleEvent([self] {
self->m_walkUpdateEvent = nullptr;
self->nextWalkUpdate();
}, m_walkAnimationInterval / 32);
@ -492,7 +492,7 @@ void Creature::setShieldTexture(const std::string& filename, bool blink)
if(blink && !m_shieldBlink) {
auto self = asCreature();
g_eventDispatcher.scheduleEvent([self]() {
g_dispatcher.scheduleEvent([self]() {
self->updateShield();
}, SHIELD_BLINK_TICKS);
}
@ -512,7 +512,7 @@ void Creature::addTimedSquare(uint8 color)
// schedule removal
auto self = asCreature();
g_eventDispatcher.scheduleEvent([self]() {
g_dispatcher.scheduleEvent([self]() {
self->removeTimedSquare();
}, VOLATILE_SQUARE_DURATION);
}
@ -523,7 +523,7 @@ void Creature::updateShield()
if(m_shield != Otc::ShieldNone && m_shieldBlink) {
auto self = asCreature();
g_eventDispatcher.scheduleEvent([self]() {
g_dispatcher.scheduleEvent([self]() {
self->updateShield();
}, SHIELD_BLINK_TICKS);
}

View File

@ -41,7 +41,7 @@ void Effect::startAnimation()
// schedule removal
auto self = asEffect();
g_eventDispatcher.scheduleEvent([self]() { g_map.removeThing(self); }, Otc::EFFECT_TICKS_PER_FRAME * getAnimationPhases());
g_dispatcher.scheduleEvent([self]() { g_map.removeThing(self); }, Otc::EFFECT_TICKS_PER_FRAME * getAnimationPhases());
}
void Effect::setId(uint32 id)

View File

@ -1,238 +0,0 @@
/*
* Copyright (c) 2010-2012 OTClient <https://github.com/edubart/otclient>
*
* 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.
*/
#include "itemloader.h"
#include <framework/core/resourcemanager.h>
#include <framework/core/filestream.h>
#define TIXML_USE_STL // use STL strings instead.
#include <framework/thirdparty/tinyxml.h>
ItemLoader g_itemLoader;
ItemLoader::~ItemLoader()
{
m_items.clear();
}
ItemDataPtr ItemLoader::getType(uint16 id) const
{
for (const ItemDataPtr &it : m_items) {
if (it->id == id)
return it;
}
return nullptr;
}
void ItemLoader::addType(uint16 id, ItemDataPtr type)
{
if (getType(id))
return;
m_items.push_back(type);
}
bool ItemLoader::loadOtb(const std::string &name)
{
FileStreamPtr fin = g_resources.openFile(name);
if (!fin) {
g_logger.error(stdext::format("failed to open file '%s'", name));
return false;
}
fin->getU32(); // skip version
uint32 type;
uint8 node = fin->readNode(node, type);
fin->getU32(); // skip flags...
if (fin->getU8() == 0x01) { // version
fin->getU8(); // skip length.
dwMajorVersion = fin->getU32();
dwMinorVersion = fin->getU32();
dwBuildNumber = fin->getU32();
}
uint16 lastId = 99;
ItemDataPtr newItem;
while ((node = fin->readNode(node, type))) {
if (!(newItem = ItemDataPtr(new ItemData))) {
g_logger.error("failed to read new item from OTB");
return false;
}
newItem->group = (ItemGroup)type;
fin->getU32(); // skip flags
ItemAttrib attr;
while ((attr = (ItemAttrib)fin->getU8())) {
uint16 dsize = fin->getU16();
switch (attr) {
case ServerId: {
if (dsize != sizeof(uint16)) {
g_logger.error("Invalid data size");
return false;
}
uint16 serverId = fin->getU16();
if (serverId > 20000 && serverId < 20100) {
serverId -= 20000;
} else if (lastId > 99 && lastId != serverId - 1) {
static ItemDataPtr dummyItemType(new ItemData);
while (lastId != serverId - 1) {
dummyItemType->id = ++lastId;
addType(lastId, dummyItemType);
}
}
newItem->id = serverId;
lastId = serverId;
break;
} case ClientId: {
newItem->clientId = fin->getU16();
break;
} case Speed: {
fin->getU16(); // skip speed
break;
} case Light2: {
if (!fin->seek(dsize)) {
g_logger.error(stdext::format("fail to skip light block with size %d", dsize));
return false;
}
} default: {
if (!fin->seek(dsize)) {
g_logger.error(stdext::format("fail to skip unknown data with size %d", dsize));
return false;
}
}
}
}
addType(newItem->id, newItem);
}
return true;
}
bool ItemLoader::loadXML(const std::string &name)
{
TiXmlDocument doc(name.c_str());
if (!doc.LoadFile()) {
g_logger.error(stdext::format("failed to load xml '%s'", name));
return false;
}
TiXmlElement* root = doc.FirstChildElement();
if (!root) {
g_logger.error("invalid xml root");
return false;
}
if (root->ValueTStr() != "items") {
g_logger.error("invalid xml tag name, should be 'items'");
return false;
}
for (TiXmlElement *element = root->FirstChildElement(); element; element = element->NextSiblingElement()) {
if (element->ValueTStr() != "item")
continue;
std::string name = element->Attribute("id");
if (name.empty())
continue;
uint16 id = stdext::unsafe_cast<uint16>(element->Attribute("id"));
uint16 idEx = 0;
if (!id) {
bool found = false;
// fallback into reading fromid and toid
uint16 fromid = stdext::unsafe_cast<uint16>(element->Attribute("fromid"));
uint16 toid = stdext::unsafe_cast<uint16>(element->Attribute("toid"));
ItemDataPtr iType;
for (int __id = fromid; __id < toid; ++__id) {
if (!(iType = getType(__id)))
continue;
iType->name = name;
idEx = iType->id == fromid ? fromid : toid;
found = true;
}
if (!found)
continue;
}
ItemDataPtr iType = getType(id);
if (!iType) {
iType = ItemDataPtr(new ItemData);
iType->id = idEx ? idEx : id;
iType->name = name;
addType(iType->id, iType);
}
iType->name = name;
for (TiXmlElement *attr = element->FirstChildElement(); attr; attr = attr->NextSiblingElement()) {
if (attr->ValueTStr() != "attribute")
continue;
std::string key = attr->Attribute("key");
std::string value = attr->Attribute("value");
if (key == "type") {
if (value == "magicfield")
iType->group = IsMagicField;
else if (value == "key")
iType->group = IsKey;
else if (value == "depot")
iType->isDepot = true;
else if (value == "teleport")
iType->group = IsTeleport;
else if (value == "bed")
iType->isBed = true;
else if (value == "door")
iType->group = IsDoor;
} else if (key == "name") {
iType->name = value;
} else if (key == "description") {
iType->description = value;
} else if (key == "weight") {
iType->weight = stdext::unsafe_cast<double>(stdext::unsafe_cast<double>(value) / 100.f);
} else if (key == "containerSize") {
int containerSize = stdext::unsafe_cast<int>(value);
if (containerSize)
iType->containerSize = containerSize;
iType->group = IsContainer;
} else if (key == "writeable") {
if (!value.empty())
iType->group = IsWritable;
} else if (key == "maxTextLen") {
iType->maxTextLength = stdext::unsafe_cast<int>(value);
} else if (key == "charges") {
iType->charges = stdext::unsafe_cast<int>(value);
}
}
}
doc.Clear();
return true;
}

View File

@ -185,7 +185,7 @@ void LocalPlayer::terminateWalk()
if(m_autoWalking) {
if(m_autoWalkEndEvent)
m_autoWalkEndEvent->cancel();
m_autoWalkEndEvent = g_eventDispatcher.scheduleEvent([self] {
m_autoWalkEndEvent = g_dispatcher.scheduleEvent([self] {
self->m_autoWalking = false;
}, 100);
}

View File

@ -286,6 +286,9 @@ bool Map::loadOtcm(const std::string& fileName)
{
try {
FileStreamPtr fin = g_resources.openFile(fileName);
if(!fin)
stdext::throw_exception("unable to open file");
fin->cache();
uint32 signature = fin->getU32();
@ -617,7 +620,7 @@ void Map::setCentralPosition(const Position& centralPosition)
// this fixes local player position when the local player is removed from the map,
// the local player is removed from the map when there are too many creatures on his tile,
// so there is no enough stackpos to the server send him
g_eventDispatcher.addEvent([this] {
g_dispatcher.addEvent([this] {
LocalPlayerPtr localPlayer = g_game.getLocalPlayer();
if(!localPlayer || localPlayer->getPosition() == m_centralPosition)
return;

Some files were not shown because too many files have changed in this diff Show More