view Bar.lua @ 50:c3c64e2def50

Assorted cleanup for hide/show grid, action ID labels, draggable resizing, etc
author Flick <flickerstreak@gmail.com>
date Tue, 22 Apr 2008 20:37:44 +0000
parents c54c481ad0ed
children c964fb84560c
line wrap: on
line source
local ReAction = ReAction
local L = ReAction.L
local _G = _G
local CreateFrame = CreateFrame
local InCombatLockdown = InCombatLockdown
local floor = math.floor
local min = math.min
local format = string.format
local GameTooltip = GameTooltip



-- update ReAction revision if this file is newer
local revision = tonumber(("$Revision$"):match("%d+"))
if revision > ReAction.revision then
  Reaction.revision = revision
end

------ BAR CLASS ------
local Bar = { _classID = {} }

local function Constructor( self, name, config )
  self.name, self.config = name, config

  if type(config) ~= "table" then
    error("ReAction.Bar: config table required")
  end

  local f = CreateFrame("Frame",nil,config.parent or UIParent,"SecureStateDriverTemplate")
  f:SetFrameStrata("MEDIUM")
  config.width = config.width or 480
  config.height = config.height or 40
  f:SetWidth(config.width)
  f:SetWidth(config.height)

  self.frame = f
  self:RefreshLayout()
  self:ApplyAnchor()
  f:Show()
end

function Bar:Destroy()
  local f = self.frame
  f:UnregisterAllEvents()
  f:Hide()
  f:SetParent(UIParent)
  f:ClearAllPoints()
  self.labelString = nil
  self.controlFrame = nil
  self.frame = nil
  self.config = nil
end

function Bar:RefreshLayout()
  ReAction:CallMethodOnAllModules("RefreshBar", self)
end

function Bar:ApplyAnchor()
  local f, config = self.frame, self.config
  f:SetWidth(config.width)
  f:SetHeight(config.height)
  local anchor = config.anchor
  if anchor then
    local anchorTo
    if config.anchorTo then
      anchorTo = ReAction:GetBar(config.anchorTo) or _G[config.anchorTo]
    end
    f:SetPoint(anchor, anchorTo, config.relativePoint, config.x or 0, config.y or 0)
  else
    f:SetPoint("CENTER")
  end
end

function Bar:GetFrame()
  return self.frame
end

function Bar:GetSize()
  return self.frame:GetWidth() or 200, self.frame:GetHeight() or 200
end

function Bar:SetSize(w,h)
  self.config.width = w
  self.config.height = h
end

function Bar:GetButtonSize()
  local w = self.config.btnWidth or 32
  local h = self.config.btnHeight or 32
  -- TODO: get from modules?
  return w,h
end

function Bar:SetButtonSize(w,h)
  if w > 0 and h > 0 then
    self.config.btnWidth = w
    self.config.btnHeight = h
  end
end

function Bar:GetButtonGrid()
  local cfg = self.config
  local r = cfg.btnRows or 1
  local c = cfg.btnColumns or 1
  local s = cfg.spacing or 4
  return r,c,s
end

function Bar:SetButtonGrid(r,c,s)
  if r > 0 and c > 0 and s > 0 then
    local cfg = self.config
    cfg.btnRows = r
    cfg.btnColumns = c
    cfg.spacing = s
  end
end

function Bar:GetName()
  return self.name
end

function Bar:SetName(name)
  self.name = name
  if self.controlLabelString then
    self.controlLabelString:SetText(self.name)
  end
end

function Bar:PlaceButton(f, idx, baseW, baseH)
  local r, c, s = self:GetButtonGrid()
  local bh, bw = self:GetButtonSize()
  local row, col = floor((idx-1)/c), mod((idx-1),c) -- zero-based
  local x, y = col*bw + (col+0.5)*s, row*bh + (row+0.5)*s
  local scale = bw/baseW

  f:ClearAllPoints()
  f:SetPoint("TOPLEFT",x/scale,-y/scale)
  f:SetScale(scale)
--  f:Show()
end







--
-- Bar config overlay
--
local StoreExtents, RecomputeButtonSize, RecomputeButtonSpacing, RecomputeGrid, ClampToButtons, HideGameTooltip, CreateControls

do
  -- upvalue some of these for small OnUpdate performance boost
  local GetSize       = Bar.GetSize
  local GetButtonSize = Bar.GetButtonSize
  local GetButtonGrid = Bar.GetButtonGrid
  local SetSize       = Bar.SetSize
  local SetButtonSize = Bar.SetButtonSize
  local SetButtonGrid = Bar.SetButtonGrid
  local ApplyAnchor   = Bar.ApplyAnchor

  StoreExtents = function(bar)
    local f = bar.frame
    local point, relativeTo, relativePoint, x, y = f:GetPoint(1)
    relativeTo = relativeTo or f:GetParent()
    local anchorTo
    for name, b in pairs(ReAction.bars) do
      if b then
        if b:GetFrame() == relativeTo then
          anchorTo = name
          break
        end
      end
    end
    anchorTo = anchorTo or relativeTo:GetName()
    local c = bar.config
    c.anchor = point
    c.anchorTo = anchorTo
    c.relativePoint = relativePoint
    c.x = x
    c.y = y
    c.width, c.height = f:GetWidth(), f:GetHeight()
  end

  RecomputeButtonSize = function(bar)
    local w, h = GetSize(bar)
    local bw, bh = GetButtonSize(bar)
    local r, c, s = GetButtonGrid(bar)

    local scaleW = (floor(w/c) - s) / bw
    local scaleH = (floor(h/r) - s) / bh
    local scale = min(scaleW, scaleH)

    SetButtonSize(bar, scale * bw, scale * bh, s)
  end

  RecomputeButtonSpacing = function(bar)
    local w, h = GetSize(bar)
    local bw, bh = GetButtonSize(bar)
    local r, c, s = GetButtonGrid(bar)

    SetButtonGrid(bar,r,c,min(floor(w/c) - bw, floor(h/r) - bh))
  end

  RecomputeGrid = function(bar)
    local w, h = GetSize(bar)
    local bw, bh = GetButtonSize(bar)
    local r, c, s = GetButtonGrid(bar)

    SetButtonGrid(bar, floor(h/(bh+s)), floor(w/(bw+s)), s)
  end

  ClampToButtons = function(bar)
    local bw, bh = GetButtonSize(bar)
    local r, c, s = GetButtonGrid(bar)
    SetSize(bar, (bw+s)*c + 1, (bh+s)*r + 1)
  end

  HideGameTooltip = function()
    GameTooltip:Hide()
  end

  CreateControls = function(bar)
    local f = bar.frame

    f:SetMovable(true)
    f:SetResizable(true)
    f:SetClampedToScreen(true)

    -- buttons on the bar should be direct children of the bar frame.
    -- The control elements need to float on top of this, which we could
    -- do with SetFrameLevel() or Raise(), but it's more reliable to do it
    -- via frame nesting, hence good old foo's appearance here.
    local foo = CreateFrame("Frame",nil,f)
    foo:SetAllPoints()

    local control = CreateFrame("Button", nil, foo)
    control:EnableMouse(true)
    control:SetToplevel(true)
    control:SetPoint("TOPLEFT", -4, 4)
    control:SetPoint("BOTTOMRIGHT", 4, -4)
    control:SetBackdrop({
      edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
      tile = true,
      tileSize = 16,
      edgeSize = 16,
      insets = { left = 0, right = 0, top = 0, bottom = 0 },
    })

    -- textures
    local bgTex = control:CreateTexture(nil,"BACKGROUND")
    bgTex:SetTexture(0.7,0.7,1.0,0.2)
    bgTex:SetPoint("TOPLEFT",4,-4)
    bgTex:SetPoint("BOTTOMRIGHT",-4,4)
    local hTex = control:CreateTexture(nil,"HIGHLIGHT")
    hTex:SetTexture(0.7,0.7,1.0,0.2)
    hTex:SetPoint("TOPLEFT",4,-4)
    hTex:SetPoint("BOTTOMRIGHT",-4,4)
    hTex:SetBlendMode("ADD")

    -- label
    local label = control:CreateFontString(nil,"OVERLAY","GameFontNormalLarge")
    label:SetAllPoints()
    label:SetJustifyH("CENTER")
    label:SetShadowColor(0,0,0,1)
    label:SetShadowOffset(2,-2)
    label:SetTextColor(1,1,1,1)
    label:SetText(bar:GetName())
    label:Show()
    bar.controlLabelString = label  -- so that bar:SetName() can update it

    local StopResize = function()
      f:StopMovingOrSizing()
      f.isMoving = false
      f:SetScript("OnUpdate",nil)
      StoreExtents(bar)
      ClampToButtons(bar)
      ApplyAnchor(bar)
    end

    -- edge drag handles
    for _, point in pairs({"LEFT","TOP","RIGHT","BOTTOM"}) do
      local edge = CreateFrame("Frame",nil,control)
      edge:EnableMouse(true)
      edge:SetWidth(8)
      edge:SetHeight(8)
      if point == "TOP" or point == "BOTTOM" then
        edge:SetPoint(point.."LEFT")
        edge:SetPoint(point.."RIGHT")
      else
        edge:SetPoint("TOP"..point)
        edge:SetPoint("BOTTOM"..point)
      end
      local tex = edge:CreateTexture(nil,"HIGHLIGHT")
      tex:SetTexture(1.0,0.82,0,0.7)
      tex:SetBlendMode("ADD")
      tex:SetAllPoints()
      edge:RegisterForDrag("LeftButton")
      edge:SetScript("OnMouseDown",
        function()
          local bw, bh = GetButtonSize(bar)
          local r, c, s = GetButtonGrid(bar)
          f:SetMinResize( bw+s+1, bh+s+1 )
          f:StartSizing(point)
          f:SetScript("OnUpdate", 
            function()
              RecomputeGrid(bar)
              bar:RefreshLayout()
            end
          )
        end
      )
      edge:SetScript("OnMouseUp", StopResize)
      edge:SetScript("OnEnter",
        function()
          GameTooltip:SetOwner(f, "ANCHOR_"..point)
          GameTooltip:AddLine(L["Drag to add/remove buttons"])
          GameTooltip:Show()
        end
      )
      edge:SetScript("OnLeave", HideGameTooltip)
      edge:Show()
    end

    -- corner drag handles, again nested in an anonymous frame so that they are on top
    local foo2 = CreateFrame("Frame",nil,control)
    foo2:SetAllPoints(true)
    for _, point in pairs({"BOTTOMLEFT","TOPLEFT","BOTTOMRIGHT","TOPRIGHT"}) do
      local corner = CreateFrame("Frame",nil,foo2)
      corner:EnableMouse(true)
      corner:SetWidth(12)
      corner:SetHeight(12)
      corner:SetPoint(point)
      local tex = corner:CreateTexture(nil,"HIGHLIGHT")
      tex:SetTexture(1.0,0.82,0,0.7)
      tex:SetBlendMode("ADD")
      tex:SetAllPoints()
      corner:RegisterForDrag("LeftButton","RightButton")
      local updateTooltip = function()
        local size, size2 = bar:GetButtonSize()
        local rows, cols, spacing = bar:GetButtonGrid()
        size = (size == size2) and tostring(size) or format("%dx%d",size,size2)
        GameTooltipTextRight4:SetText(size)
        GameTooltipTextRight5:SetText(tostring(spacing))
      end
      corner:SetScript("OnMouseDown",
        function(_,btn)
          local bw, bh = GetButtonSize(bar)
          local r, c, s = GetButtonGrid(bar)
          if btn == "LeftButton" then -- button resize
            f:SetMinResize( (s+12)*c+1, (s+12)*r+1 )
            f:SetScript("OnUpdate", 
              function()
                RecomputeButtonSize(bar)
                bar:RefreshLayout()
                updateTooltip()
              end
            )
          elseif btn == "RightButton" then -- spacing resize
            f:SetMinResize( bw*c, bh*r )
            f:SetScript("OnUpdate", 
              function()
                RecomputeButtonSpacing(bar)
                bar:RefreshLayout()
                updateTooltip()
              end
            )
          end
          f:StartSizing(point)
        end
      )
      corner:SetScript("OnMouseUp",StopResize)
      corner:SetScript("OnEnter",
        function()
          GameTooltip:SetOwner(f, "ANCHOR_"..point)
          GameTooltip:AddLine(L["Drag to resize buttons"])
          GameTooltip:AddLine(L["Right-click-drag"])
          GameTooltip:AddLine(L["to change spacing"])
          local size, size2 = bar:GetButtonSize()
          local rows, cols, spacing = bar:GetButtonGrid()
          size = (size == size2) and tostring(size) or format("%dx%d",size,size2)
          GameTooltip:AddDoubleLine(L["Size:"], size)
          GameTooltip:AddDoubleLine(L["Spacing:"], tostring(spacing))
          GameTooltip:Show()
        end
      )
      corner:SetScript("OnLeave", 
        function()
          GameTooltip:Hide()
          f:SetScript("OnUpdate",nil)
        end
      )

    end

    control:RegisterForDrag("LeftButton")
    control:RegisterForClicks("RightButtonDown")
    
    control:SetScript("OnDragStart",
      function()
        f:StartMoving()
        f.isMoving = true
        -- TODO: snap indicator update install
      end
    )

    control:SetScript("OnDragStop",
      function()
        f:StopMovingOrSizing()
        f.isMoving = false
        f:SetScript("OnUpdate",nil)
        -- TODO: snap frame here
        StoreExtents(bar)
      end
    )

    control:SetScript("OnEnter",
      function()
        -- add bar type and status information to name
        local name = bar.name
        for _, m in ReAction:IterateModules() do
          --[[
          local suffix = safecall(m,"GetBarNameModifier",bar)
          if suffix then
            name = ("%s %s"):format(name,suffix)
          end
          --]]
        end
        
        GameTooltip:SetOwner(f, "ANCHOR_TOPRIGHT")
        GameTooltip:AddLine(name)
        GameTooltip:AddLine(L["Drag to move"])
        --GameTooltip:AddLine(L["Shift-drag for sticky mode"])
        GameTooltip:AddLine(L["Right-click for options"])
        GameTooltip:Show()
      end
    )

    control:SetScript("OnLeave", HideGameTooltip)

    control:SetScript("OnClick",
      function()
        bar:ShowMenu()
      end
    )

    return control
  end
end


local OpenMenu, CloseMenu
do
  -- Looking for a lightweight AceConfig3-struct-compatible 
  -- replacement for Dewdrop, encapsulate here
  -- Considering Blizzard's EasyMenu/UIDropDownMenu, but that's
  -- a bit tricky to convert from AceConfig3-struct
  local Dewdrop = AceLibrary("Dewdrop-2.0")
  OpenMenu = function(frame, opts)
    Dewdrop:Open(frame, "children", opts, "cursorX", true, "cursorY", true)
  end
  CloseMenu = function(frame)
    if Dewdrop:GetOpenedParent() == frame then
      Dewdrop:Close()
    end
  end
end


function Bar:ShowControls(show)
  if show then
    if not self.controlFrame then
      self.controlFrame = CreateControls(self)
    end
    self.controlFrame:Show()
  elseif self.controlFrame then
    CloseMenu(self.controlFrame)
    self.controlFrame:Hide()
  end
end

function Bar:ShowMenu()
  if not self.menuOpts then
    self.menuOpts = {
      type = "group",
      args = {
        openConfig = {
          type = "execute",
          name = L["Layout..."],
          desc = L["Open the layout editor for this bar"],
          func = function() CloseMenu(self.controlFrame); ReAction:CallModuleMethod("ConfigUI","LaunchLayoutEditor",self) end,
          disabled = InCombatLockdown,
          order = 1
        },
        delete = {
          type = "execute",
          name = L["Delete Bar"],
          desc = L["Remove the bar from the current profile"],
          confirm = L["Are you sure you want to remove this bar?"],
          func = function() ReAction:EraseBar(self) end,
          order = 2
        },
      }
    }
  end
  OpenMenu(self.controlFrame, self.menuOpts)
end



------ Export as a class-factory ------
ReAction.Bar = {
  new = function(self, ...)
    local x = { }
    for k,v in pairs(Bar) do
      x[k] = v
    end
    Constructor(x, ...)
    return x
  end
}