promotional bannermobile promotional banner

LibMasterAddons

A lightweight framework for building WoW Classic addons

LibMasterAddons

A lightweight framework for building WoW Classic addons.

Embeddable LibStub library: an addon container with dependency injection and client detection, services for logging, locales, timers, player names, chat output and version checks, and a complete UI toolkit that draws every window in two styles. Register models, services and views and build features instead of boilerplate.

Players never install it themselves. Every addon ships its own copy, and LibStub hands the newest loaded copy to all of them.

Supported clients: Classic Era, Season of Discovery, Anniversary, WoW Forever, TBC, Wrath, Titan Reforged, Cataclysm and Mists of Pandaria Classic.


Embedding

The whole library is one compiled file. Copy LibMasterAddons-<version>.lua from the package into your libs folder and load it after LibStub:

## OptionalDeps: LibMasterAddons
## X-Embeds: LibMasterAddons

libs\LibStub.lua
libs\CallbackHandler-1.0.lua
libs\LibDataBroker-1.1.lua
libs\LibDBIcon-1.0.lua
libs\LibMasterAddons-1.1.17.lua
MyAddon.lua

LibDataBroker and LibDBIcon are only needed for the minimap button. The version in the file name keeps the copies of different addons apart, so an update is a new file and one changed TOC line.

The Classic style takes its list background and row highlight from textures\forever\forever-professions.png in your addon folder.


Quick start

local MasterAddons = LibStub("LibMasterAddons-1.0");

local addon = MasterAddons:CreateAddon({
    id = "MyAddon",                 -- folder and TOC name
    name = "My Addon",
    shortcut = "|cffDA8CFF[MA]|r ", -- prefix of window titles and chat lines
    storagePrefix = "MA",           -- MA_Settings, MA_Frames, MA_Logs
});

-- SavedVariables are available from here on
addon:OnLoaded(function()
    addon:ApplySettingsDefaults({ sound = true, minimapButton = { hide = false } });
    addon:GetService("startup");
end);

_G.myAddon = addon;

ApplySettingsDefaults fills MA_Settings key by key, nested tables included, and keeps every value the player already set. The container also gives you:

addon.version                       -- from the TOC
addon.devMode                       -- true while the TOC still says 0.0.1
addon.inCombat                      -- kept current by the container
addon:GetSavedTable("Data")         -- MA_Data, created when missing
addon:HandleEvent("BAG_UPDATE", function(bagId) ... end)
addon:OnCombatStart(function() window:Hide(); end)
addon:OnCombatEnd(function() window:Show(); end)
addon:SplitString("a,b,,c", ",")    -- { "a", "b", "c" }
addon:TrimString("  text  ")        -- "text"
addon:CountTable({ a = 1, b = 2 })  -- 2
addon:GenerateString(10)            -- random id

Every event handler and hook runs on its own: an error is logged and the handlers after it still run, and in dev mode it also reaches the error handler of the game. An event the client does not know is logged instead of raising, so one event list works on every client.

Client detection

if (addon.isSod) then ... end
if (addon.isWrathAtLeast) then ... end   -- Wrath, Cata and MoP
local id = addon.expansionId;            -- 1 to 5, Season of Discovery = 102

The flags are isVanilla, isSod, isBcc, isWrath, isCata and isMop with isBccAtLeast up to isMopAtLeast, plus isForever and isRetail for the clients on the modern engine, where every classic flag is false.

Missing Classic functions

WoW Forever lacks many Classic globals. addon.compat maps each of them to its modern replacement and is the plain global on every other client, without writing anything into _G:

local name, link = self.addon.compat.GetItemInfo(itemId);
self.addon.compat.SendChatMessage(text, "GUILD");

Dependency injection

The heart of the library. You register three kinds of building blocks by name and the container wires them together, without globals or load order juggling.

Kind Register Resolve Lives
Service addon:CreateService(name) addon:GetService(name) One lazy singleton per addon
View addon:CreateView(name) addon:NewView(name) A fresh instance per call
Model addon:CreateModel(name[, data]) addon:GetModel(name) One shared table

Registration order does not matter, and nothing runs until something asks for it. Every service, view and class model starts with these members, so you ask for what you need when you need it instead of passing references around:

self.addon            -- the addon container
self:GetService(name) -- resolve a service
self:GetModel(name)   -- resolve a model
self:HandleEvent(...) -- register a game event (services only)

Services

The first GetService call creates the service and runs Initialize once, the place for constants, storage and events. Services call each other freely, because they are resolved at call time.

local PriceService = _G.myAddon:CreateService("price");

function PriceService:Initialize()
    self.MaxAge = 3600;
    self.prices = self.addon:GetSavedTable("Prices");
    self:HandleEvent("AUCTION_HOUSE_SHOW", function()
        self:GetService("chat"):Write("ScanStarted");
        self:Scan();
    end);
end

function PriceService:GetPrice(itemId)
    local entry = self.prices[itemId];
    if (entry and time() - entry.timestamp <= self.MaxAge) then
        return entry.price;
    end
end

A service under a built-in name replaces the built-in one for your addon only, other addons keep the original. With extend it builds on it instead: methods you leave out come from the library, which stays reachable as self.base.

local PlayerService = _G.myAddon:CreateService("player", { extend = true });

function PlayerService:Initialize()
    self.base.Initialize(self);
    self.alts = self.addon:GetSavedTable("Alts");
end

Views

A view can exist more than once, for example one list per tab:

local ListView = _G.myAddon:CreateView("list");

function ListView:Setup(parent, filterType)
    self.filterType = filterType;
    self.frame = self:GetService("ui"):CreatePanel(parent);
end

local requests = _G.myAddon:NewView("list");
local offers = _G.myAddon:NewView("list");
requests:Setup(window, "request");
offers:Setup(window, "offer");

Views have no HandleEvent on purpose: a service owns the events and calls into its views, so views come and go freely.

Models

A model created with a table stores it as is:

_G.myAddon:CreateModel("profession-icons", {
    [171] = "Interface\\Icons\\Trade_BrewPoison",
    [164] = "Interface\\Icons\\Trade_BlackSmithing",
});

local icon = _G.myAddon:GetModel("profession-icons")[171];

Without a table you get a class model with the injected members, for data built at runtime. The locales model below is one.


Built-in services

Log

A persistent log by day in <storagePrefix>_Logs, kept for 7 days, with a ready log window to copy and clear it. A format that does not fit its values never raises, the text and the values are logged as they are.

self.addon:Log("SyncService", "SendData", "sent %d skills to %s", count, playerName);

addon.logsView = addon.logsView or addon:NewView("logs");
addon.logsView:Show();                  -- e.g. for /myaddon logs

addon:GetService("log"):GetLogText();   -- the whole log as text, newest day first

Locale

Add a model named locales whose Create returns one table per language:

local LocalesModel = _G.myAddon:CreateModel("locales");

function LocalesModel:Create()
    return {
        ["en"] = { ["ItemsFound"] = "%d items found" },
        ["de"] = { ["ItemsFound"] = "%d Gegenstände gefunden" },
    };
end
local locale = self:GetService("locale");
locale:Get("ItemsFound", 12);   -- "12 items found"
locale:GetBare("Unknown");      -- nil, where Get returns "Unknown"
locale:Has("ItemsFound");       -- true

A key is looked up in the client language (zhCN before zh), then in English, then in the texts the library ships in ten languages for its own windows and controls. So a missing translation shows English and a missing key shows itself. Without format arguments a text comes back untouched, so placeholders like %player% survive.

Timer

Countdowns, waits and debounces on named handles, without an OnUpdate handler of your own:

local timer = self:GetService("timer");

timer:Start("scan", 30, function(secondsLeft)   -- now and then every second
    button:SetText(timer:FormatTime(secondsLeft));
end);
timer:Stop("scan");

timer:Wait("refresh", 5, function() self:Refresh(); end);
timer:Debounce(self, "filterTimer", 0.3, function() self:Filter(); end);

Wait replaces a pending wait of the same name. Debounce keeps its handle in self.filterTimer, so every view instance debounces on its own, and CancelDebounce drops it. FormatTime(180000) gives "2d 2h 0m", with true as second argument the zero parts are left out, and 0 is a green "Ready".

Player

Names are keyed as Name-Realm everywhere. The service knows the own character and takes care of the WoW Forever specifics: surnames, linked realms with numbered names and whispers that fail with the own realm attached.

local player = self:GetService("player");

player.current;                   -- own name with realm
player:GetLongName(sender);       -- a name from a message, ready to use as a key
player:GetShortName(name);        -- without realm
player:GetWhisperTarget(name);    -- what to whisper
player:IsIgnored(name);           -- on the ignore list of the player

The own name is read again at login, because a fresh WoW Forever login does not know it before. When it differs, OnCurrentPlayerChanged tells an extending service.

Chat and version

local chat = self:GetService("chat");
chat:Write("ItemsFound", 12);   -- translated, the addon shortcut in front
chat:WriteBare("Scan done");    -- as it is

The version service compares the own version with the ones other players send and tells the player once per session that theirs is outdated: CheckAndNotify(sender, version). It sends through your own transport, a message model version-broadcast-message and a message service with SendToPlayer.


UI service

The complete toolkit behind the Master addon windows. Every factory draws in one of two styles, so your views need no code for them:

  • Flat: purple and gold gradient borders, flat buttons, a purple hover glow and striped rows.
  • Classic: the window art of the game with portrait ring, red buttons and the tab art of the game, on WoW Forever the frame of its own windows.

Style and window scale are one setting for every addon built on the library. A new install starts in the Classic style, the Master addons let each player pick once in a dialog that previews both, and every options page carries both controls in its first row. The scale starts with the one of ElvUI when ElvUI is loaded.

Windows

local ui = self:GetService("ui");

-- name, width, height, title, prefix the title with addon.shortcut, resizable
local window = ui:CreateView("main", 800, 500, "My Addon", true, true);
ui:CreateFlatCloseButton(window, function() window:Hide(); end):SetPoint("TOPRIGHT", -12, -8);
ui:SetViewPortrait(window, "Interface\\Icons\\INV_Misc_Book_09");

Windows move, resize from every edge and corner and come back when they leave the screen. Position and size are stored per name in <storagePrefix>_Frames. Optional arguments after resizable are minWidth, minHeight and the allowed resize directions. The portrait shows in the Classic style, by default the IconTexture of your TOC, and the close button takes the corner there on its own. CreateToolView takes the same arguments for small helper windows without portrait, CreateOverlayView(name, width, height, title) builds a mini window over the game world.

Tabs

local content = ui:CreatePanel(window);
content:SetPoint("TOPLEFT", 12, -70);
content:SetPoint("BOTTOMRIGHT", -12, 12);

local strip = ui:CreateTabStrip(window, content);
local guildTab = strip:AddTab("Guild", function() self:ShowGuild(); end);
local offersTab = strip:AddTab("Offers", function() self:ShowOffers(); end);
strip:SetActive(guildTab);
strip:SetBadge(offersTab, 3);   -- counter behind the caption
strip:Layout();

The tabs sit on the top border of the content frame. When they no longer fit, arrows appear and the mouse wheel scrolls them, ScrollToTab brings one into view. An optional config table sets tabWidth, tabGap, activeHeight, inactiveHeight, sideInset, leftInset and glowTexture.

Dropdowns

local dropdown = ui:CreateDropdown(window, 200, {
    { value = 0,   text = "All professions" },
    { value = 333, text = "Enchanting", dot = { 0, 1, 0 } },
    { value = 755, text = "Jewelcrafting", tooltip = "Known by two alts" },
}, function(value, text)
    self:Filter(value);
end);

dropdown:SetValue(333);
dropdown:GetValue();          -- 333
dropdown:SetItems(newItems);

dot draws a small colored marker at the end of the row, tooltip explains an item while it is hovered. Item text may carry escape sequences such as an icon, and opening a dropdown closes any other one.

Controls

ui:CreateButton(window, "Apply", function() self:Apply(); end);         -- button of the game
ui:CreateFlatButton(window, "Cancel", function() window:Hide(); end);   -- styled button
ui:CreateFlatSquareButton(box, "+", function() self:Add(); end, 18);    -- small square button
ui:CreateHeaderIconButton(window, "Interface\\Icons\\INV_Misc_Note_01",
    "Settings", function() self:OpenSettings(); end);                   -- icon with tooltip

local search = ui:CreateEditBox(window, 200);   -- Enter and Escape clear the focus
search:SetPlaceholder("Search");
local quantity = ui:CreateNumberEditBox(window, 60);

ui:BindTooltip(button, "Scan the auction house");
ui:BindTooltip(button, function() return self.isScanning and "Scanning..." or nil; end);

In the Classic style, square buttons with +, -, x, < or > become icon buttons. BindTooltip hooks the scripts instead of replacing them, takes an anchor as third argument and shows nothing when the function returns nil or an empty string.

Lists

local panel, content = ui:CreateScrollFrame(window);
panel:SetPoint("TOPLEFT", 12, -70);
panel:SetPoint("BOTTOMRIGHT", -12, 12);

for index, entry in ipairs(entries) do
    local row = ui:CreatePanel(content);
    row:SetHeight(20);
    ui:SetRowColor(row, index);   -- striped rows
    ui:AttachHoverGlow(row);      -- hover highlight
end

The second argument of AttachHoverGlow lists child frames that keep the highlight alive, row.hoverGlowDisabled = true turns it off for rows without a click action.

Settings pages

local page = ui:CreateOptionsPanel();   -- title, window style and scale
ui:CreateOptionsCheckbox(page, "Play a sound", settings.sound, function(checked)
    settings.sound = checked;
end):SetPoint("TOPLEFT", 16, -100);
ui:CreateOptionsNumberBox(page, "Keep prices for", "days", settings.days, 2, function(value)
    settings.days = value;
end):SetPoint("TOPLEFT", 16, -130);
ui:RegisterOptionsPanel(page);

local settingsWindow = ui:CreateOptionsWindow("settings", 700, 500, "Settings", { { panel = page } });
settingsWindow:ShowPage(1);

The pages register in the interface options of every client, and CreateOptionsWindow hosts them in a window of their own with one tab per page. CreateOptionsDropdown and CreateOptionsSlider complete the set.

Minimap button

ui:CreateMinimapIcon({
    icon = "Interface\\Icons\\INV_Misc_Book_09",
    overlayText = "MA",
    onClick = function(button)
        if (button == "LeftButton") then
            self.addon.mainView:Toggle();
        end
    end,
    onTooltip = { "My Addon", "|cff999999Left Click:|r toggle the window" },
    onHidden = function() minimapCheckbox:SetChecked(false); end,
});

ui:SetMinimapIconShown(false);

Ctrl and right click hides the button, position and hide state persist in <storagePrefix>_Settings.minimapButton. onTooltip also takes a function that fills the tooltip.


Compatibility

LibMasterAddons-1.0 is the API contract: members are only added, never removed or changed in meaning. A breaking change would ship as a new major that loads side by side.

Feedback

Comments on the CurseForge project page are welcome.

LibMasterAddons Team

profile avatar
  • 2
    Followers
  • 7
    Projects
  • 1.3M
    Downloads

More from KurkidentronView all