# EverlookDB Bar plugin guide (brief for an AI assistant)

You are helping me write a plugin for EverlookDB Bar, an info-bar addon for World of Warcraft: Forever.
Everything you need is in this brief. Follow it exactly: use only the functions it lists, with the
arguments it gives. If you are unsure whether a game API exists in this client, say so and offer a
fallback instead of guessing.

**Before writing any code, ask me what the plugin should show** (what value, where it comes from, what a
click should do, whether it needs settings). Then write the complete addon: the .toc file and the .lua
file, ready to drop into the AddOns folder, and tell me how to install and test it.

Human-readable version of this guide: https://everlookdb.com/ebar/plugins
This file: https://everlookdb.com/ebar/plugins.md

---

## 1. The client

- WoW Forever is Blizzard's realm type with Classic content (levels 1-60, the old world) running on the
  modern, retail-style game client: version 1.60.1, **interface number 16001**. The .toc must say
  `## Interface: 16001`.
- The addon API is the retail-style one, not Classic Era's: `C_Timer`, `C_Container`, `C_AddOns`,
  `C_Map`, `Settings`, `issecretvalue` and so on. Lua 5.1.
- The addon folder is `World of Warcraft\_forever_\Interface\AddOns\<AddonName>\`. The folder name must
  match the .toc file name. A new addon folder is only seen after restarting the game; after that,
  `/reload` picks up code changes.
- **Secret values.** Forever follows retail's combat rules: some API results (often unit, combat and
  cooldown data, especially in combat) come back as *secret values*. Addon code may display a secret
  value but must never compare it, do arithmetic on it, use it as a table key, or measure it. Check
  with `issecretvalue(v)` (guard with `local issecret = issecretvalue or function() return false end`).
  When a value is secret, either show it as it is (put it straight into `text`) or keep the last plain
  value you had.
- **Combat lockdown.** Protected actions (moving or showing secure frames, casting, using items, some
  Blizzard panels) are blocked in combat. Check `InCombatLockdown()` and wait for the
  `PLAYER_REGEN_ENABLED` event. Addons cannot use items or cast spells from a click on the bar.

## 2. What a plugin is

EverlookDB Bar shows **LibDataBroker-1.1 (LDB)** data objects, the same plugins Titan Panel, ChocolateBar,
Bazooka and ElvUI show. A plugin is one LDB data object made with `NewDataObject`. EverlookDB Bar's own
built-in plugins (XP, Performance, Location...) are plain LDB objects too.

For the few things LDB cannot express there is a small extra API, `EverlookBar.API` (version 1):
custom widgets drawn inside the button, settings in EverlookDB Bar's window, a shared ticker, and
placement.

EverlookDB Bar embeds LibStub, CallbackHandler-1.0 and LibDataBroker-1.1. With
`## Dependencies: EverlookBar` in the .toc, `LibStub("LibDataBroker-1.1")` is always available.

### Data object attributes EverlookDB Bar reads

| Attribute | Meaning |
|---|---|
| `type` | `"data source"` (shows its text; icon and text on, label off by default) or `"launcher"` (an icon you click; icon, label and text on by default) |
| `text` | the text on the bar. If `text` is nil: `value` and `suffix` (shown as "value suffix") |
| `label` | shown before the text, in grey, when the player turns Label on (Look button on the Plugins page) |
| `icon` | texture path or file ID |
| `iconCoords` | `{ left, right, top, bottom }`; default trims the icon border (0.08, 0.92, 0.08, 0.92) |
| `iconR`, `iconG`, `iconB` | icon tint, 0 to 1 |
| `OnClick(frame, button)` | `button` is `"LeftButton"`, `"RightButton"` or `"MiddleButton"`. Without `OnClick`, a right-click on your button opens the bar's settings |
| `OnTooltipShow(tooltip)` | fill the GameTooltip with `tooltip:AddLine` / `tooltip:AddDoubleLine`; EverlookDB Bar anchors and shows it, away from the bar's screen edge |
| `OnEnter(frame)`, `OnLeave(frame)` | show your own tooltip (for example LibQTip) |
| `tooltip` | your own tooltip frame: EverlookDB Bar anchors and shows it, and hides it on leave |

Only one tooltip path is used, in this order: `tooltip` frame, then `OnEnter`, then `OnTooltipShow`.
`OnLeave` is called in every case. The player decides per plugin whether icon, label and text show.

Updating: assign attributes on the object (`obj.text = "42"`). Writing the same value again does
nothing. EverlookDB Bar redraws a plugin at most once per frame however often you write, calls
`SetText` only when the text changed, and keeps a button's width steady when a number shrinks by a few
pixels. Still: write `text` when your value changes, never every frame.

## 3. EverlookBar.API, version 1 (full reference)

```lua
local API = EverlookBar and EverlookBar.API
if API and API.GetVersion() >= 1 then
	-- use it
end
```

Compatibility promise: `API.GetVersion()` only grows. A published function keeps its name, arguments
and meaning in every later version. Code written for version 1 keeps working.

- `API.GetVersion() -> number`: the API version, currently 1.
- `API.RegisterWidget(ldbName, spec) -> true`: draw something of your own inside your plugin's button
  (a mini bar, a meter, a row of icons). The widget sits after the icon; the text follows it.
  - `spec.width`: a number, or `function(dataobj, ldbName) -> number`. 0 hides the widget.
  - `spec.create(frame, dataobj, ldbName)`: called once, with an empty Frame inside the button, when the
    button is made (when the plugin is on a bar). Make your textures here.
  - `spec.update(frame, dataobj, ldbName)`: called every time the button redraws (an attribute of your
    data object changed, or you called `API.Refresh`). Keep it cheap: set sizes and colours, create nothing.
  - The widget's height follows the bar's row height (row height minus 10, between 4 and 30 pixels).
    Anchor textures to the frame's edges (`SetAllPoints`, `TOPLEFT`/`BOTTOMLEFT`) rather than fixed heights.
  - Other LDB displays (Titan and so on) ignore widgets and show your `text`, so keep `text` meaningful.
- `API.Refresh(ldbName)`: redraw your button on the next frame. Use it when your widget's data or width
  changed but no attribute of the data object did.
- `API.SetHidden(ldbName, hidden)`: hide (`true`) or show (`false`) your button without taking it off
  its bar. Returns `false` if EverlookDB Bar does not know that plugin yet.
- `API.Every(owner, interval, fn) -> task`: run `fn(task, now)` every `interval` seconds on Everlook
  Bar's single shared ticker (0.1 s resolution; smaller intervals become 0.1). `owner` is your LDB name:
  errors in `fn` are caught and shown on that button. The task starts active and first runs on the
  next tick. A task whose code fails 50 times is stopped until /reload.
  - `task:SetActive(bool)`: pause or resume (a paused task costs nothing; resuming runs it on the next tick).
  - `task:SetInterval(seconds)`: change the interval.
  - `task:Cancel()`: remove it for good.
- `API.RegisterSettings(owner, title, settings) -> get, set`: settings for your plugin. They appear in
  EverlookDB Bar's settings window (`/ebar`, Built-in page, under a heading with your `title`), the
  window's search box finds them, and they work from chat as `/ebar <owner>.<key> <value>`
  (for example `/ebar hearthbar.showhome off`). EverlookDB Bar saves the values.
  - `owner`: a short id of letters, digits and `_`, for example `"hearthbar"`.
  - `title`: the heading in the window.
  - `settings`: a list of `{ key, type, label, desc, default, onChange, ... }`:
    - `type = "bool"`;
    - `type = "number"` with `min`, `max`, `step`;
    - `type = "choice"` with `choices = { { value = "a", text = "A" }, ... }`;
    - `type = "color"` (the value is `{ r, g, b, a }`; add `hasAlpha = true` for an opacity slider);
    - `type = "string"`.
    - `onChange(value)` runs after the player changes it in the window or from chat (protected: an
      error is reported in chat and does not break the window).
  - Returns `get(key)` (the saved value, or the default) and `set(key, value)` (saves it; does not call
    `onChange`). `set` also keeps keys that are not listed settings, handy for a "placed once" flag.
  - Call it once, when your file loads.
- `API.Place(ldbName, bar, group, index) -> bool`: put a plugin on a bar. `bar` is 1 or more, `group`
  is `"left"`, `"center"` or `"right"`, `index` the position in the group (nil: last). Returns `false`
  if EverlookDB Bar does not know the plugin or has not loaded its saved settings yet: call it from
  `PLAYER_LOGIN` or later. Meant for a first-run default; never move a plugin the player placed.
- `API.GetPlacement(ldbName) -> bar, group, index, row`: where a plugin is, or nil when it is on no bar.
- `API.GetNumBars() -> number`: how many bars there are.

By default, plugins from other addons are **not** put on a bar: the player adds them on the Plugins
page of `/ebar` (or with `/ebar place <name> 1 right`), unless they turned on "Put plugins from other
addons on bar 1 when they appear". A plugin may place itself once on first run with `API.Place`.

## 4. Rules (follow every one)

1. **No OnUpdate scripts.** React to game events. For anything timed, use `API.Every` (one shared
   ticker) and pause the task with `task:SetActive(false)` when there is nothing to update.
2. **No garbage per update.** Do not create tables, closures or frames in event handlers, ticks or
   widget updates. Make them once and reuse them. Build strings only when the value changed.
3. **Write `text` only when the value changed.**
4. **Secret values:** never compare, do maths on, use as table keys, or measure a value that may be
   secret. Check with `issecretvalue`. Show it as it is, or keep the last plain value.
5. **Nothing protected in combat.** Check `InCombatLockdown()`; wait for `PLAYER_REGEN_ENABLED`.
6. **Tooltips stay small:** a title line, then the facts, then a grey hint line for clicks.
7. **Guard optional things:** game functions that might not exist in this client
   (`local f = C_Something and C_Something.Func or OldFunc`), and `EverlookBar.API` if EverlookDB Bar is
   only an optional dependency.
8. One LDB name per plugin, unique across all addons (prefix it with your addon name).
   `NewDataObject` returns nil when the name is taken.

## 5. Errors and testing

- EverlookDB Bar calls your `OnClick`, `OnTooltipShow`, `OnEnter`, `OnLeave`, widget `create`/`update`
  and `width`, and your `API.Every` tasks protected. When one fails, your button gets a small **red dot**
  in its top-right corner, chat says once "<name> had an error (the bar keeps running): <message>", and
  (with `OnTooltipShow`) the tooltip shows the error count and message. The rest of the bar keeps
  working. After 50 errors your plugin's code is not called again until /reload.
- Your own event frames are not protected by EverlookDB Bar: their errors go to the game's error
  handler (install BugSack and BugGrabber to read them).
- `/ebar plugins` lists every plugin, where it is and its error count. `/ebar perf` shows Everlook
  Bar's memory and CPU; turn on "Measure EverlookDB Bar's own time per plugin" (General page, or
  `/ebar profiling on`) to see the time per plugin.
- Plugin missing from the Plugins page: the addon is not enabled (AddOns button on the character
  screen), the .toc interface is not 16001 ("Load out of date AddOns"), the game was not restarted
  after adding the folder, the LDB name is already taken, or a Lua error stopped the file before
  `NewDataObject`.

## 6. Complete example: Hearth Bar

Where the Hearthstone takes you, and its cooldown as text plus a mini bar. Shows an LDB object,
tooltip, clicks, a widget, settings, the shared ticker, secret-value guards and first-run placement.

`HearthBar/HearthBar.toc`:

```
## Interface: 16001
## Title: Hearth Bar
## Notes: Your Hearthstone's home and cooldown on EverlookDB Bar.
## Author: you
## Version: 1.0.0
## Dependencies: EverlookBar

HearthBar.lua
```

`HearthBar/HearthBar.lua`:

```lua
-- Hearth Bar: where your Hearthstone takes you, and its cooldown as text and a mini bar.
local NAME = "HearthBar"       -- the LDB name: unique across all addons
local HEARTHSTONE = 6948       -- item ID
local WIDTH = 60               -- width of the cooldown bar in pixels

local API = EverlookBar.API
local getCooldown = (C_Container and C_Container.GetItemCooldown) or GetItemCooldown
local issecret = issecretvalue or function() return false end

local left, total = 0, 1       -- seconds of cooldown left, and the whole cooldown
local obj, task, get, set

-- Read the cooldown. In combat the values may be secret: then keep the last plain ones.
local function readCooldown()
	local start, duration = getCooldown(HEARTHSTONE)
	if start == nil or duration == nil or issecret(start) or issecret(duration) then return end
	if duration > 0 then
		left = math.max(0, start + duration - GetTime())
		total = duration
	else
		left, total = 0, 1
	end
end

local function update()
	readCooldown()
	if left > 0 then
		obj.text = string.format("%d:%02d", math.floor(left / 60), math.floor(left % 60))
	elseif get("showhome") then
		obj.text = GetBindLocation() or "Ready"
	else
		obj.text = "Ready"
	end
	if task then task:SetActive(left > 0) end -- tick only while there is a cooldown
end

obj = LibStub("LibDataBroker-1.1"):NewDataObject(NAME, {
	type = "data source",
	label = "Hearth",
	text = "",
	icon = "Interface\\Icons\\INV_Misc_Rune_01",
	OnTooltipShow = function(tip)
		tip:AddLine("Hearthstone")
		tip:AddDoubleLine("Home", GetBindLocation() or "?", 1, 1, 1, 1, 1, 1)
		if left > 0 then tip:AddDoubleLine("Ready in", SecondsToTime(left), 1, 1, 1, 1, 1, 1) end
		tip:AddLine("Right-click: show the inn or just Ready", 0.6, 0.6, 0.6)
	end,
	OnClick = function(_, button)
		if button == "RightButton" then
			set("showhome", not get("showhome"))
			update()
		end
	end,
})

get, set = API.RegisterSettings("hearthbar", "Hearth Bar", {
	{ key = "showhome", type = "bool", label = "Show the inn when the Hearthstone is ready", default = true,
		onChange = function() update() end },
	{ key = "bar", type = "bool", label = "Cooldown bar", default = true,
		desc = "A small bar that fills up while the Hearthstone cools down.",
		onChange = function() API.Refresh(NAME) end },
})

API.RegisterWidget(NAME, {
	width = function() return (left > 0 and get("bar")) and WIDTH or 0 end,
	create = function(f)
		f.bg = f:CreateTexture(nil, "BACKGROUND")
		f.bg:SetAllPoints()
		f.bg:SetColorTexture(1, 1, 1, 0.1)
		f.fill = f:CreateTexture(nil, "ARTWORK")
		f.fill:SetPoint("TOPLEFT")
		f.fill:SetPoint("BOTTOMLEFT")
		f.fill:SetColorTexture(0.35, 0.66, 1, 0.9)
	end,
	update = function(f)
		f.fill:SetWidth(math.max(0.01, WIDTH * (1 - left / total)))
	end,
})

-- One shared ticker, once a second, active only while the Hearthstone cools down.
task = API.Every(NAME, 1, update)

local events = CreateFrame("Frame")
events:RegisterEvent("PLAYER_LOGIN")
events:RegisterEvent("PLAYER_ENTERING_WORLD")
events:RegisterEvent("BAG_UPDATE_COOLDOWN")
events:RegisterEvent("HEARTHSTONE_BOUND")
events:SetScript("OnEvent", function(_, event)
	if event == "PLAYER_LOGIN" and not get("placed") then
		-- first run only: put it on bar 1, right group; after that the player decides
		if API.Place(NAME, 1, "right") then set("placed", true) end
	end
	update()
end)
```

## 7. Smallest possible plugin (no EverlookBar.API)

```lua
local obj = LibStub("LibDataBroker-1.1"):NewDataObject("MyHearth", {
	type = "data source",
	label = "Hearth",
	text = "?",
	icon = "Interface\\Icons\\INV_Misc_Rune_01",
	OnTooltipShow = function(tip)
		tip:AddLine("Hearthstone")
		tip:AddLine("Bound to " .. (GetBindLocation() or "?"), 1, 1, 1)
	end,
})
local f = CreateFrame("Frame")
f:RegisterEvent("PLAYER_ENTERING_WORLD")
f:RegisterEvent("HEARTHSTONE_BOUND")
f:SetScript("OnEvent", function() obj.text = GetBindLocation() or "?" end)
```

## 8. Making it work without EverlookDB Bar (publishing)

- Any licence is fine for your own code.
- To also run in Titan Panel, ChocolateBar, Bazooka or ElvUI without EverlookDB Bar: embed LibStub,
  CallbackHandler-1.0 and LibDataBroker-1.1 in a `Libs` folder (keep their licence files), list them
  in the .toc before your own file, replace `## Dependencies: EverlookBar` with
  `## OptionalDeps: EverlookBar`, and wrap every `EverlookBar.API` call in
  `local API = EverlookBar and EverlookBar.API; if API and API.GetVersion() >= 1 then ... end`,
  with a fallback for anything you rely on (for example `C_Timer.NewTicker` instead of `API.Every`,
  your own SavedVariables instead of `RegisterSettings`).
- Mark the upload for WoW Forever (interface 16001) on CurseForge or wherever you publish.

## 9. What to do now

Ask me what the plugin should show, then write the .toc and the .lua following this brief.
