feat(settings): retail Settings window, with Interface Options on top

Ports retail's Blizzard_Settings_Shared (Settings, categories, canvas and
vertical layouts, the setting controls, key binding rows, SettingsPanel,
SettingsInbound) as the one options window. Addons of both eras land in
it: newer addons register through the Settings API, and the 3.3.5
InterfaceOptions_AddCategory API (Ace3's AddToBlizOptions) now registers
a canvas category. Its panel protocol maps onto the window's: okay on
commit (Close, Apply, Escape), default and refresh where the window
calls OnDefault / OnRefresh, cancel only when the window closes without
a commit. A panel's name is its category ID, as Ace3 and newer addons
set it. The old InterfaceOptionsFrame* names alias the window's frames
so addons that restyle or overlay them keep working.

ClassicAPI's own pages are vertical layouts of Settings controls (cvar
and proxy settings, key binding rows, a ClassicAPI number box for
settings that take any number), so the window's search finds them. They
are the window's game categories, at the root of its first tab, which
reads ClassicAPI; addons go on the AddOns tab.

C_SettingsUtil.OpenSettingsPanel and NotifySettingsLoaded fire
SETTINGS_PANEL_OPEN and SETTINGS_LOADED through the engine's event
dispatcher (Event::Custom::FireValues), passing the category ID as
given. Also: slider:SetEnabled, Enum.BindingSet, C_CVar.GetCVar /
GetCVarDefault / RegisterCVar, C_KeyBindings.GetBindingIndex and its
two context answers, and retail's CvarUtil, BindingUtil, MinimalSlider,
DropdownWithSteppers and ColorPickerFrame:SetupColorPickerAndShow.

Engine changes the window needs:
- CVAR_UPDATE(cvarName, value) for every change of a cvar Lua can see,
  from a hook on CVar::Set (0x0063DF50). 1.12 fires CVAR_UPDATE only
  from Script_SetCVar with a caller's token. The change is queued and
  fired at the head of the next UI frame, never inside the setter: the
  engine sets cvars mid-way through its own work while a script runs
  further up the stack.
- Script SetParent (0x007A1550) shows a frame that is shown under a
  visible parent, as 3.3.5's CSimpleFrame::SetParent does; 1.12's
  (0x0076AB10) re-shows only a frame that was visible before. The key
  binding rows move their buttons onto an input blocker and back after
  the blocker is hidden.
- The child walks of the frame show (0x0076AE10) and hide (0x0076AD50)
  run on a copy of the child list and skip a child that has left. Each
  child runs its OnShow / OnHide inside the walk, and 1.12 (and 3.3.5,
  and 4.3.4) read the next node only afterwards, from a node a
  reparenting script may have freed. Auctionator's options page opens
  another page from its OnShow, and the window takes the first out of
  its canvas with SetParent(nil) while the canvas is being shown.

1.12 specifics in the port:
- ToggleGameMenu() without an argument is the Escape handler and can
  SpellStopCasting or ClearTarget, so closing returns to the game menu
  through ShowUIPanel(GameMenuFrame).
- StaticPopup_EscapePressed runs OnCancel(data, "clicked"), so button2
  is always the dialogs' no-op choice. Only Turtle's StaticPopup has
  button3 / OnAlt; stock 1.12 shows two buttons.
- The layout-cache reader (0x4905e0) replaces a movable or resizable
  frame's anchors and size from a saved record, so the window is
  neither: it has no drag or size handle.
- A $parent name under an unnamed frame takes the nearest named
  ancestor's name, so pooled rows avoid templates that anchor slices by
  name (UIPanelButtonTemplate2, InputBoxTemplate).
- GetChecked returns 1 or nil, GetBinding has no category, and
  GetBindingText is FrameXML Lua that needs the "KEY_" prefix.
- The slider rounds every value to its step in single-precision floats,
  and the rounding does not settle, so a value set from a setting does
  not report back as a change.
- Retail's Options and control atlases do not exist; the controls use
  1.12's checkbox, slider, dropdown and spellbook page arrows, the
  frames the tooltip backdrop.

Retail's strings are added in all eight locales. Not ported yet: the
Keybindings category.
This commit is contained in:
Brues
2026-11-15 02:55:21 -06:00
parent d3f0674b1a
commit fc544b2d2c
64 changed files with 8985 additions and 1031 deletions
+16 -8
View File
@@ -59,7 +59,7 @@ In the Frame rows, a name that starts with `:` is a method of the widget that th
| [Animation](docs/API.md#animation) | `region:CreateAnimationGroup`, `region:GetAnimationGroups`, `region:StopAnimating`, `SetMaxAnimFramerate`, `GetMaxAnimFramerate`, `AnimationGroup` and `Animation` / `Alpha` / `Translation` / `Scale` / `Rotation` / `Path` / `ControlPoint` methods |
| [AuctionHouse](docs/API.md#auctionhouse) | `C_AuctionHouse.PostItem`, `CanCancelAuction` |
| [AutoComplete](docs/API.md#autocomplete) | `C_AutoComplete.GetAutoCompleteResults`, `C_AutoComplete.IsRecognizedName`, `C_AutoComplete.GetAutoCompletePresenceID`, `C_AutoComplete.GetAutoCompleteRealms` |
| [Bindings](docs/API.md#bindings) | `SetBindingSpell`, `SetBindingItem`, `SetBindingMacro`, `SetBindingClick`, `SetOverrideBinding`, `SetOverrideBindingSpell`, `SetOverrideBindingItem`, `SetOverrideBindingMacro`, `SetOverrideBindingClick`, `ClearOverrideBindings`, `GetBindingAction` (`checkOverride`), `GetBindingByKey`, `IsModifiedClick`, `GetModifiedClick`, `SetModifiedClick`, `GetNumModifiedClickActions`, `GetModifiedClickAction` |
| [Bindings](docs/API.md#bindings) | `SetBindingSpell`, `SetBindingItem`, `SetBindingMacro`, `SetBindingClick`, `SetOverrideBinding`, `SetOverrideBindingSpell`, `SetOverrideBindingItem`, `SetOverrideBindingMacro`, `SetOverrideBindingClick`, `ClearOverrideBindings`, `GetBindingAction` (`checkOverride`), `GetBindingByKey`, `IsModifiedClick`, `GetModifiedClick`, `SetModifiedClick`, `GetNumModifiedClickActions`, `GetModifiedClickAction`, `C_KeyBindings.GetBindingIndex`, `C_KeyBindings.GetBindingContextForAction`, `C_KeyBindings.GetCustomBindingType` |
| [Chat](docs/API.md#chat) | `GetCurrentChatEvent`, `GetCurrentChatGUID`, `IsChatAFK`, `IsChatDND`, `SendSystemMessage` |
| [ChatBubbles](docs/API.md#chatbubbles) | `C_ChatBubbles.GetAllChatBubbles` |
| [Class](docs/API.md#class) | `FillLocalizedClassList` |
@@ -68,7 +68,7 @@ In the Frame rows, a name that starts with `:` is a method of the widget that th
| [Combat](docs/API.md#combat) | `InCombatLockdown`, `StartAttack`, `StopAttack` |
| [CombatLog](docs/API.md#combatlog) | `CombatLogGetCurrentEventInfo`, `COMBATLOG_OBJECT_*` (constants) |
| [Console](docs/API.md#console) | `CalculateStringEditDistance`, `ConsoleAddMessage`, `ConsoleEcho`, `ConsoleExec`, `ConsoleGetAllCommands`, `ConsoleGetColorFromType`, `ConsoleGetFontHeight`, `ConsoleIsActive`, `ConsolePrintAllMatchingCommands`, `SetConsoleKey` |
| [CVar](docs/API.md#cvar) | `C_CVar.AreCVarsLoaded`, `C_CVar.DoesCVarExist`, `C_CVar.GetCVarBitfield`, `C_CVar.GetCVarBool`, `C_CVar.GetCVarInfo`, `C_CVar.RemoveTempCVar`, `C_CVar.SetCVar`, `C_CVar.SetCVarBitfield`, `C_CVar.SetTempCVar`, `GetCVar`, `GetCVarDefault` |
| [CVar](docs/API.md#cvar) | `C_CVar.AreCVarsLoaded`, `C_CVar.DoesCVarExist`, `C_CVar.GetCVar`, `C_CVar.GetCVarBitfield`, `C_CVar.GetCVarBool`, `C_CVar.GetCVarDefault`, `C_CVar.GetCVarInfo`, `C_CVar.RegisterCVar`, `C_CVar.RemoveTempCVar`, `C_CVar.SetCVar`, `C_CVar.SetCVarBitfield`, `C_CVar.SetTempCVar`, `GetCVar`, `GetCVarDefault` |
| [Cursor](docs/API.md#cursor) | `CursorHasMacro`, `GetCursorInfo` |
| [Container](docs/API.md#container) | `C_Container.AutoStoreItem`, `C_Container.CalculateTotalNumberOfFreeBagSlots`, `C_Container.GetContainerItemCharges`, `C_Container.GetContainerItemDurability`, `C_Container.GetContainerItemID`, `C_Container.GetContainerItemInfo`, `C_Container.GetContainerItemEquipmentSetInfo`, `C_Container.GetContainerItemQuestInfo`, `C_Container.GetContainerItemRepairCost`, `C_Container.GetContainerFreeSlots`, `C_Container.GetContainerNumFreeSlots`, `C_Container.GetBackpackAutosortDisabled`, `C_Container.GetBankAutosortDisabled`, `C_Container.GetItemCooldown`, `C_Container.GetSortBagsRightToLeft`, `C_Container.HasContainerItem`, `C_Container.IsContainerFiltered`, `C_Container.IsContainerItemOpenable`, `C_Container.MoveItem`, `C_Container.PlayerHasHearthstone`, `C_Container.SetBackpackAutosortDisabled`, `C_Container.SetBagPortraitTexture`, `C_Container.SetBankAutosortDisabled`, `C_Container.SetItemSearch`, `C_Container.SetSortBagsRightToLeft`, `C_Container.SortBags`, `C_Container.SortBankBags`, `C_Container.SwapItems`, `C_Container.UseHearthstone`, `GetItemCooldown`, `SetBagPortraitTexture` |
| [Creature](docs/API.md#creature) | `C_CreatureInfo.GetCreatureID`, `C_CreatureInfo.GetCreatureInfoByID`, `C_CreatureInfo.RequestLoadCreatureByID`, `C_CreatureInfo.GetRaceInfo`, `C_CreatureInfo.GetClassInfo`, `C_CreatureInfo.GetCreatureFamilyInfo`, `C_CreatureInfo.GetCreatureFamilyIDs`, `C_CreatureInfo.GetFactionInfo`, `C_CreatureInfo.GetCreatureTypeInfo`, `C_CreatureInfo.GetCreatureTypeIDs` |
@@ -88,7 +88,7 @@ In the Frame rows, a name that starts with `:` is a method of the widget that th
| [Frame: Texture](docs/API.md#texturesetrotationangle--cx-cy) | `:SetRotation` / `:GetRotation`, `:SetVertexOffset` / `:GetVertexOffset`, `:SetColorTexture`, `:SetAtlas` / `:GetAtlas`, `:ResetTexCoord`, `:SetSpriteSheetCell`, `:SetTexture` wrap modes, `:SetHorizTile` / `:GetHorizTile`, `:SetVertTile` / `:GetVertTile`, `:SetDesaturation` / `:GetDesaturation`, `IsDesaturateSupported`, `:SetMask`, `frame:CreateMaskTexture`, `:AddMaskTexture` / `:RemoveMaskTexture`, `:GetNumMaskTextures`, `:GetMaskTexture` |
| [Frame: EditBox](docs/API.md#editboxsetcursorpositionposition) | `:SetCursorPosition` / `:GetCursorPosition`, `:GetUTF8CursorPosition`, `:ClearHighlightText`, `:SetHighlightColor` / `:GetHighlightColor`, `:HasFocus`, `GetCurrentKeyBoardFocus`, `:HasText`, `:ClearHistory`, `:Enable` / `:Disable` / `:IsEnabled`, `:SetCountInvisibleLetters` / `:IsCountInvisibleLetters`, `:IsInIMECompositionMode` |
| [Frame: StatusBar](docs/API.md#statusbarsetreversefillisreversefill--statusbargetreversefill) | `:SetReverseFill` / `:GetReverseFill`, `:SetRotatesTexture` / `:GetRotatesTexture`, `:SetFillStyle` / `:GetFillStyle`, `:SetColorFill`, `:SetStatusBarDesaturated` / `:IsStatusBarDesaturated`, `:SetStatusBarDesaturation` / `:GetStatusBarDesaturation`, `:SetTimerDuration` / `:GetTimerDuration`, `:SetValue` / `:SetMinMaxValues` with `interpolation`, `:GetInterpolatedValue`, `:IsInterpolating`, `:SetToTargetValue` |
| [Frame: Slider](docs/API.md#sliderenable--sliderdisable--sliderisenabled) | `:Enable` / `:Disable` / `:IsEnabled` |
| [Frame: Slider](docs/API.md#sliderenable--sliderdisable--slidersetenabledenabled--sliderisenabled) | `:Enable` / `:Disable` / `:SetEnabled` / `:IsEnabled` |
| [Frame: Cooldown](docs/API.md#createframecooldown--name-parent-template) | `CreateFrame("Cooldown")`, `:SetCooldown`, `:SetCooldownDuration`, `:SetCooldownFromExpirationTime`, `:Clear`, `:GetCooldownTimes`, `:GetCooldownDuration`, `:GetCooldownDisplayDuration`, `:Pause` / `:Resume`, `:SetPaused` / `:IsPaused`, `:SetReverse` / `:GetReverse`, `:SetDrawEdge` / `:GetDrawEdge`, `:SetDrawSwipe` / `:GetDrawSwipe`, `:SetDrawBling` / `:GetDrawBling`, `:SetSwipeColor`, `:SetEdgeColor`, `:SetSwipeTexture`, `:SetEdgeTexture`, `:SetBlingTexture`, `:SetRotation` / `:GetRotation`, `:SetHideCountdownNumbers` / `:GetHideCountdownNumbers`, `:GetCountdownFontString`, `:SetCountdownAbbrevThreshold` / `:GetCountdownAbbrevThreshold`, `:SetCountdownMillisecondsThreshold` / `:GetCountdownMillisecondsThreshold`, `:SetMinimumCountdownDuration` / `:GetMinimumCountdownDuration`, `OnCooldownDone`, `CooldownFrame_Set`, `CooldownFrame_Clear`, `CooldownFrame_SetDisplayAsPercentage` |
| [Frame: ModelScene](docs/API.md#modelscene) | `CreateFrame("ModelScene")`, `<ModelScene>` (`drawLayer`, `fogNear`, `fogFar`, `<FogColor>`, `<ViewInsets>`), `:CreateActor`, `:GetNumActors`, `:GetActorAtIndex`, `:SetCameraPosition` / `:GetCameraPosition`, `:SetCameraOrientationByYawPitchRoll`, `:SetCameraOrientationByAxisVectors`, `:GetCameraForward`, `:GetCameraRight`, `:GetCameraUp`, `:SetCameraFieldOfView` / `:GetCameraFieldOfView`, `:SetCameraNearClip` / `:GetCameraNearClip`, `:SetCameraFarClip` / `:GetCameraFarClip`, `:SetViewInsets` / `:GetViewInsets`, `:SetViewTranslation` / `:GetViewTranslation`, `:Project3DPointTo2D`, `"FollowCamera"` (`:SetFollowActor` / `:GetFollowActor`), `:SetLightType` / `:GetLightType`, `:SetLightVisible` / `:IsLightVisible`, `:SetLightDirection` / `:GetLightDirection`, `:SetLightPosition` / `:GetLightPosition`, `:SetLightAmbientColor` / `:GetLightAmbientColor`, `:SetLightDiffuseColor` / `:GetLightDiffuseColor`, `:SetFogColor` / `:GetFogColor`, `:SetFogNear` / `:GetFogNear`, `:SetFogFar` / `:GetFogFar`, `:ClearFog`, `:SetDrawLayer` / `:GetDrawLayer`, `:SetPaused`, `:GetSceneTime`, `:After`, `:NewTimer`, `:NewTicker`, `:SetAllowOverlappedModels` / `:GetAllowOverlappedModels`, `:SetGroundTerrain` / `:GetGroundTerrain`, `:SetWorldModel`, `:SetWorldModelByMapID`, `:ClearWorldModel`, `:SetWorldTerrain`, `:ClearWorldTerrain`, `:SetPlayWorldModelSounds` / `:GetPlayWorldModelSounds`, `:TraceSegment`, `:GetLiquidAtPoint`, `:SweepCollider`, `:SetSoundListenerActor` / `:GetSoundListenerActor`, `:GetActorAtCursor`, `:GetCursorRay`, `:GetActorsInRadius`, `:SetMoveMarker` / `:ClearMoveMarker` / `:GetMoveMarker`, `OnActorEnter` / `OnActorLeave` |
| [Frame: ModelSceneActor](docs/API.md#actorsetmodelbycreaturedisplayiddisplayid--useactiveplayercustomizations) | `:SetModelByCreatureDisplayID`, `:SetModelByPath`, `:SetModelByUnit`, `:SetModelByUnitCreatureDisplayID`, `:GetModelUnitGUID`, `:Dress`, `:Undress`, `:UndressSlot`, `:TryOn`, `:DressPlayerSlot`, `:IsSlotAllowed` / `:IsSlotVisible`, `:GetItemTransmogInfo`, `:GetItemTransmogInfoList`, `:SetItemTransmogInfo`, `:SetSheathed` / `:GetSheathed`, `:SetSheathedCategory`, `:UseUnitSheatheCategory`, `:SetAutoDress` / `:GetAutoDress`, `:IsGeoReady`, `:ClearModel`, `:IsLoaded`, `:GetModelPath`, `:SetPosition` / `:GetPosition`, `:SetYaw` / `:GetYaw`, `:SetPitch` / `:GetPitch`, `:SetRoll` / `:GetRoll`, `:SetScale` / `:GetScale`, `:SetUseCenterForOrigin` / `:IsUsingCenterForOrigin`, `:GetActiveBoundingBox`, `:GetMaxBoundingBox`, `:Show` / `:Hide` / `:SetShown` / `:IsShown` / `:IsVisible`, `:SetAlpha` / `:GetAlpha`, `:SetAnimation` / `:GetAnimation`, `:GetAnimationVariation`, `:SetAnimationBlendOperation` / `:GetAnimationBlendOperation`, `:SetPaused` / `:GetPaused`, `:SetSpellVisualKit` / `:GetSpellVisualKit`, `:ApplySpellVisualKit`, `:PlayAnimationKit` / `:StopAnimationKit`, `:AttachToMount`, `:DetachFromMount`, `:CalculateMountScale`, `:GetAttachmentPosition`, `:AttachToActor`, `:DetachFromActor`, `:PlaySpellVisual`, `:StopSpellVisual`, `:PlaySound`, `:SetPlayAnimationSounds` / `:GetPlayAnimationSounds`, `:SetShadowShown` / `:IsShadowShown`, `:SetHighlight` / `:IsHighlighted`, `:SetSelectionCircle` / `:ClearSelectionCircle` / `:GetSelectionCircle`, `:SetNameText` / `:ClearNameText` / `:GetNameText`, `:GetNamePosition`, `:SetMovementEnabled` / `:IsMovementEnabled`, `:StartMovingForward`, `:StartMovingBackward`, `:StopMoving`, `:StartStrafingLeft`, `:StartStrafingRight`, `:StopStrafing`, `:StartTurningLeft`, `:StartTurningRight`, `:StopTurning`, `:Jump`, `:StartPitchingUp`, `:StartPitchingDown`, `:StopPitching`, `:IsFalling`, `:IsSwimming`, `:MoveTo`, `:SetWalking` / `:IsWalking`, `:GetCameraPivotHeight`, `OnLoad`, `OnUpdate`, `OnModelLoading`, `OnModelLoaded`, `OnModelCleared`, `OnAnimFinished`, `OnSpellVisualImpact`, `OnMoveFinished`, `<Actor>` templates |
@@ -127,6 +127,7 @@ In the Frame rows, a name that starts with `:` is a method of the widget that th
| [PlayerInfo](docs/API.md#playerinfo) | `C_PlayerInfo.CanUseItem`, `C_PlayerInfo.GetClass`, `C_PlayerInfo.GetName`, `C_PlayerInfo.GetRace`, `C_PlayerInfo.GetSex`, `C_PlayerInfo.GUIDIsCreature`, `C_PlayerInfo.GUIDIsGameObject`, `C_PlayerInfo.GUIDIsPet`, `C_PlayerInfo.GUIDIsPlayer`, `C_PlayerInfo.IsConnected` |
| [Profiling](docs/API.md#profiling) | `GetAddOnCPUUsage`, `GetAddOnMemoryUsage`, `GetEventCPUUsage`, `GetFrameCPUUsage`, `GetFunctionCPUUsage`, `GetScriptCPUUsage`, `ResetCPUUsage`, `UpdateAddOnCPUUsage`, `UpdateAddOnMemoryUsage` |
| [Quest](docs/API.md#quest) | `C_QuestLog.GetInfo`, `C_QuestLog.GetNumQuestObjectives`, `C_QuestLog.GetQuestDetails`, `C_QuestLog.GetQuestLogTitle`, `C_QuestLog.GetHeaderIndexForQuest`, `C_QuestLog.GetLogIndexForQuestID`, `C_QuestLog.GetQuestIDForLogIndex`, `C_QuestLog.GetTitleForQuestID`, `C_QuestLog.IsOnQuest`, `C_QuestLog.IsQuestDataCachedByID`, `C_QuestLog.IsUnitOnQuest`, `C_QuestLog.RequestLoadQuestByID`, `GetQuestLogCompletionText`, `GetQuestLogLeaderBoardID` (Turtle WoW only: `C_QuestLog.GetAllCompletedQuestIDs`, `C_QuestLog.IsQuestFlaggedCompleted`, `GetQuestsCompleted`, `QueryQuestsCompleted`) |
| [SettingsUtil](docs/API.md#settingsutil) | `C_SettingsUtil.NotifySettingsLoaded`, `C_SettingsUtil.OpenSettingsPanel` |
| [Sound](docs/API.md#sound) | `C_Sound.GetRecentSoundFiles`, `C_Sound.GetSoundScaledVolume`, `C_Sound.IsPlaying`, `C_Sound.PlayItemSound`, `C_Sound.PlaySound`, `C_Sound.PlaySoundWithOptions`, `C_Sound.PlayVocalErrorSound`, `MuteSoundFile`, `PlaySound`, `PlaySoundFile`, `StopSound`, `UnmuteSoundFile` |
| [Spell](docs/API.md#spell) | `C_Spell.CancelSpellByID`, `C_Spell.CastAtCursor`, `C_Spell.CastAtUnit`, `C_Spell.CastingInfo`, `C_Spell.ChannelInfo`, `C_Spell.DoesSpellExist`, `C_Spell.GetSchoolString`, `C_Spell.GetSpellCastCount`, `C_Spell.GetSpellCooldown`, `C_Spell.GetSpellDescription`, `C_Spell.GetSpellDispelType`, `C_Spell.GetSpellEffectInfo`, `C_Spell.GetSpellEffectMechanics`, `C_Spell.GetSpellInfo`, `C_Spell.GetSpellLevelInfo`, `C_Spell.GetSpellLink`, `C_Spell.GetSpellLossOfControlCooldown`, `C_Spell.GetSpellMechanicByID`, `C_Spell.GetSpellName`, `C_Spell.GetSpellPowerCost`, `C_Spell.GetSpellRadius`, `C_Spell.GetSpellReagents`, `C_Spell.GetSpellRequiredTargetLevel`, `C_Spell.GetSpellSubtext`, `C_Spell.GetSpellTexture`, `C_Spell.IsAutoAttackSpell`, `C_Spell.IsCurrentSpell`, `C_Spell.IsNextMeleeSpell`, `C_Spell.IsRangedAutoAttackSpell`, `C_Spell.IsSelfBuff`, `C_Spell.IsSpellHarmful`, `C_Spell.IsSpellHelpful`, `C_Spell.IsSpellInRange`, `C_Spell.IsSpellPassive`, `C_Spell.IsSpellUsable`, `C_Spell.ResetsMeleeSwing`, `C_Spell.SpellHasRange`, `C_Spell.UnitCastingInfo`, `C_Spell.UnitChannelInfo`, `CanDualWield`, `CancelSpellByName`, `CancelUnitBuff`, `CastSpellByID`, `CastSpellNoToggle`, `GetCraftSpellID`, `GetCritChance`, `GetRangedCritChance`, `GetSpellBaseCooldown`, `GetSpellBonusDamage`, `GetSpellBonusHealing`, `GetSpellInfo`, `GetSpellLink`, `GetSpellRadius`, `GetSpellRequiredTargetLevel`, `GetSpellSchool`, `IsAttackSpell`, `IsAutoRepeatSpell`, `IsConsumableSpell`, `IsHarmfulSpell`, `IsHelpfulSpell`, `IsPassiveSpell`, `IsPlayerSpell`, `IsSpellKnown`, `IsUsableSpell`, `SpellHasRange`, `UnitCastingDuration`, `UnitChannelDuration` |
| [SpellActivationOverlay](docs/API.md#spellactivationoverlay) | `C_SpellActivationOverlay.IsSpellOverlayed`, `IsSpellOverlayed` |
@@ -219,7 +220,8 @@ for what each command does, and
Each setting is saved in `WTF\Config.wtf`. Read and write them with `GetCVar`
/ `SetCVar` or `/console`. Click a group name for the full rules. To change
these settings, the player cache and the ClassicAPI key bindings in the game,
open the game menu and click AddOn Options, then ClassicAPI.
open the game menu and click AddOn Options. The Settings window opens on
its ClassicAPI tab.
| Group | CVar | Default | What it does |
|-------|------|---------|--------------|
@@ -296,6 +298,7 @@ when launching with `-console`), not as Lua functions. See the
| `COMBAT_LOG_EVENT` | `timestamp, subevent, hideCaster, sourceGUID, sourceName, sourceFlags, sourceRaidFlags, destGUID, destName, destFlags, destRaidFlags, ...` ([details](docs/API.md#combat_log_event_unfiltered--combat_log_event-events)) |
| `COMBAT_LOG_EVENT_UNFILTERED` | same as `COMBAT_LOG_EVENT` |
| `CURSOR_CHANGED` | `isDefault, newCursorType, oldCursorType, oldCursorVirtualID` |
| `CVAR_UPDATE` | `cvarName, value` — fires for every cvar change ([details](docs/API.md#cvar_update-event-fires-for-every-change)) |
| `DYNAMIC_GOSSIP_POI_UPDATED` | *(none)* |
| `EQUIPMENT_SETS_CHANGED` | *(none)* |
| `EQUIPMENT_SWAP_PENDING` | `setID` |
@@ -340,6 +343,8 @@ when launching with `-console`), not as Lua functions. See the
| `QUEST_REMOVED` | `questID` |
| `QUEST_TURNED_IN` | `questID, xpReward, moneyReward` |
| `SELF_RES_SPELL_CHANGED` | *(none)* |
| `SETTINGS_LOADED` | *(none)* |
| `SETTINGS_PANEL_OPEN` | `openToCategoryID, scrollToElementName` |
| `SOUNDKIT_FINISHED` | `soundHandle` (only for sounds played with `runFinishCallback`) |
| `SPELL_ACTIVATION_OVERLAY_SHOW` | `spellID, texture, locationType, scale, r, g, b` ([details](docs/API.md#spell_activation_overlay_show--spell_activation_overlay_hide-events)) |
| `SPELL_ACTIVATION_OVERLAY_HIDE` | `spellID` (`nil` hides every alert) |
@@ -395,6 +400,7 @@ when launching with `-console`), not as Lua functions. See the
| Item quality | `LE_ITEM_QUALITY_POOR` … `LE_ITEM_QUALITY_WOWTOKEN` |
| Unit stat | `LE_UNIT_STAT_STRENGTH` … `LE_UNIT_STAT_SPIRIT` |
| Addon security | `Enum.AddOnSecurityStatus.{Secure,Insecure,Banned,NotAvailable}` |
| Binding set | `Enum.BindingSet.{Default,Account,Character,Current}` (0–3) |
| Power type | `Enum.PowerType.{HealthCost,None,Mana,Rage,Focus,Energy,Happiness}` |
| Inventory type | `Enum.InventoryType.Index*Type` (0–34, e.g. `IndexHeadType`=1 … `IndexRelicType`=28) |
| Item class | `Enum.ItemClass.{Consumable,Container,Weapon,Gem,Armor,Reagent,Projectile,Tradegoods,ItemEnhancement,Recipe,Quiver,Questitem,Key,Miscellaneous,…}` (0–19) |
@@ -480,11 +486,13 @@ functions but that consumer code still expects to find as globals —
(`ContinueOnAddOnLoaded` and more), `FormattingUtil` (`GetMoneyString`,
`FormatLargeNumber` and more), `FrameUtil`, `DataProvider`, `CircularBuffer`,
`EasingUtil`, `ScriptAnimationUtil`, `Interpolator`, `EnumUtil`, `StringUtil`, `AnchorUtil`,
`GridLayoutUtil`, and the layout frame templates (`VerticalLayoutFrame`,
`GridLayoutUtil`, the layout frame templates (`VerticalLayoutFrame`,
`HorizontalLayoutFrame`, `ResizeLayoutFrame`, `GridLayoutFrame`,
`StaticGridLayoutFrame`). It also holds the conditional slash
commands and `SecureCmdOptionParse`, the parser that reads `[conditions]`
and `@unit` for them.
`StaticGridLayoutFrame`), and the retail Settings window (`Settings`,
`SettingsPanel`) with the `InterfaceOptions_AddCategory` functions on
top. It also holds the conditional slash commands and
`SecureCmdOptionParse`, the parser that reads `[conditions]` and `@unit`
for them.
**You don't have to install the addon manually** — the DLL embeds
the contents of [`src/embed/AddOns/!!!ClassicAPI/`](src/embed/AddOns/!!!ClassicAPI/) and
+187 -27
View File
@@ -83,6 +83,9 @@ build instructions.
- [Function keys F13 to F24](#function-keys-f13-to-f24)
- [Modified clicks](#modified-clicks)
- [`ActionButtonUseKeyDown`](#actionbuttonusekeydown)
- [`Enum.BindingSet`](#enumbindingset)
- [`C_KeyBindings.GetBindingIndex(action)`](#c_keybindingsgetbindingindexaction)
- [`C_KeyBindings.GetBindingContextForAction(action)` / `C_KeyBindings.GetCustomBindingType(bindingIndex)`](#c_keybindingsgetbindingcontextforactionaction--c_keybindingsgetcustombindingtypebindingindex)
- [CharacterList](#characterlist)
- [`GetSavedCharacterOrder(realm)` / `SetSavedCharacterOrder(realm, order)` — GlueXML only](#getsavedcharacterorderrealm--setsavedcharacterorderrealm-order--gluexml-only)
@@ -200,6 +203,7 @@ build instructions.
- [CVar](#cvar)
- [`GetCVar(name)`](#getcvarname)
- [`GetCVarDefault(name)`](#getcvardefaultname)
- [`C_CVar.GetCVar(name)` / `C_CVar.GetCVarDefault(name)` / `C_CVar.RegisterCVar(name [, value])`](#c_cvargetcvarname--c_cvargetcvardefaultname--c_cvarregistercvarname--value)
- [`C_CVar.SetCVar(name [, value])`](#c_cvarsetcvarname--value)
- [`C_CVar.GetCVarInfo(name)`](#c_cvargetcvarinfoname)
- [`C_CVar.DoesCVarExist(name)`](#c_cvardoescvarexistname)
@@ -255,6 +259,7 @@ build instructions.
- [`ACTION_USABLE_CHANGED` event](#action_usable_changed-event)
- [`COMBAT_LOG_EVENT_UNFILTERED` / `COMBAT_LOG_EVENT` events](#combat_log_event_unfiltered--combat_log_event-events)
- [`CURSOR_CHANGED` event](#cursor_changed-event)
- [`CVAR_UPDATE` event (fires for every change)](#cvar_update-event-fires-for-every-change)
- [`EQUIPMENT_SETS_CHANGED` event](#equipment_sets_changed-event)
- [`EQUIPMENT_SWAP_PENDING` event](#equipment_swap_pending-event)
- [`EQUIPMENT_SWAP_FINISHED` event](#equipment_swap_finished-event)
@@ -281,6 +286,8 @@ build instructions.
- [`QUEST_REMOVED` event](#quest_removed-event)
- [`QUEST_TURNED_IN` event](#quest_turned_in-event)
- [`SELF_RES_SPELL_CHANGED` event](#self_res_spell_changed-event)
- [`SETTINGS_LOADED` event](#settings_loaded-event)
- [`SETTINGS_PANEL_OPEN` event](#settings_panel_open-event)
- [`SOUNDKIT_FINISHED` event](#soundkit_finished-event)
- [`SPELL_ACTIVATION_OVERLAY_SHOW` / `SPELL_ACTIVATION_OVERLAY_HIDE` events](#spell_activation_overlay_show--spell_activation_overlay_hide-events)
- [`SPELL_ACTIVATION_OVERLAY_GLOW_SHOW` / `SPELL_ACTIVATION_OVERLAY_GLOW_HIDE` events](#spell_activation_overlay_glow_show--spell_activation_overlay_glow_hide-events)
@@ -355,6 +362,8 @@ build instructions.
- [`CreateFrame("Cooldown" [, name, parent, template])`](#createframecooldown--name-parent-template)
- [`frame:SetShown(shown)`](#framesetshownshown)
- [A frame moved to a new parent takes its children along](#a-frame-moved-to-a-new-parent-takes-its-children-along)
- [A shown frame moved under a visible parent becomes visible](#a-shown-frame-moved-under-a-visible-parent-becomes-visible)
- [`OnShow` and `OnHide` can move frames](#onshow-and-onhide-can-move-frames)
- [A ScrollFrame keeps clipping its content when it moves](#a-scrollframe-keeps-clipping-its-content-when-it-moves)
- [`fontstring:GetStringHeight()`](#fontstringgetstringheight)
- [`fontstring:GetUnboundedStringWidth()`](#fontstringgetunboundedstringwidth)
@@ -402,7 +411,7 @@ build instructions.
- [`editBox:SetCountInvisibleLetters(count)` / `editBox:IsCountInvisibleLetters()`](#editboxsetcountinvisibleletterscount--editboxiscountinvisibleletters)
- [`editBox:ClearHistory()`](#editboxclearhistory)
- [`editBox:Enable()` / `editBox:Disable()` / `editBox:IsEnabled()`](#editboxenable--editboxdisable--editboxisenabled)
- [`slider:Enable()` / `slider:Disable()` / `slider:IsEnabled()`](#sliderenable--sliderdisable--sliderisenabled)
- [`slider:Enable()` / `slider:Disable()` / `slider:SetEnabled(enabled)` / `slider:IsEnabled()`](#sliderenable--sliderdisable--slidersetenabledenabled--sliderisenabled)
- [`OnEnable` and `OnDisable` (scripts)](#onenable-and-ondisable-scripts)
- [`OnMinMaxChanged(self, min, max)` (script)](#onminmaxchangedself-min-max-script)
- [`statusBar:SetReverseFill(isReverseFill)` / `statusBar:GetReverseFill()`](#statusbarsetreversefillisreversefill--statusbargetreversefill)
@@ -1016,6 +1025,10 @@ build instructions.
- [`C_QuestLog.GetAllCompletedQuestIDs()`](#c_questloggetallcompletedquestids)
- [A turn-in always prints "*quest* completed."](#a-turn-in-always-prints-quest-completed)
- [SettingsUtil](#settingsutil)
- [`C_SettingsUtil.OpenSettingsPanel([openToCategoryID [, scrollToElementName]])`](#c_settingsutilopensettingspanelopentocategoryid--scrolltoelementname)
- [`C_SettingsUtil.NotifySettingsLoaded()`](#c_settingsutilnotifysettingsloaded)
- [Sound](#sound)
- [`PlaySound(soundKitID)` / `PlaySound(soundName)`](#playsoundsoundkitid--playsoundsoundname)
- [`C_Sound.PlaySound(soundKitID [, channel, forceNoDuplicates, runFinishCallback])`](#c_soundplaysoundsoundkitid--channel-forcenoduplicates-runfinishcallback)
@@ -2846,6 +2859,36 @@ common in PvP / heal-tank-while-killing-add scenarios.
The two bindings show in the TARGETING block of the keybind list, not at
the bottom.
### `Enum.BindingSet`
The sets of key bindings, for `LoadBindings`, `SaveBindings` and
`GetCurrentBindingSet`.
| Field | Value |
|---|---|
| `Default` | 0 |
| `Account` | 1 |
| `Character` | 2 |
| `Current` | 3 |
`GetCurrentBindingSet()` returns `Account` or `Character`.
### `C_KeyBindings.GetBindingIndex(action)`
Returns the index of the binding for `action`, the index that
`GetBinding(index)` takes. Returns `nil` when no binding has that action.
```lua
local index = C_KeyBindings.GetBindingIndex("INTERACTTARGET")
local action, key1, key2 = GetBinding(index)
```
### `C_KeyBindings.GetBindingContextForAction(action)` / `C_KeyBindings.GetCustomBindingType(bindingIndex)`
Both functions return `nil`. The client has one set of key bindings for all
actions, so no action has a binding context of its own. The client has no
custom binding types.
## CharacterList
### `GetSavedCharacterOrder(realm)` / `SetSavedCharacterOrder(realm, order)` — GlueXML only
@@ -4996,6 +5039,12 @@ it returns no values. If `name` is not a string or a number,
`GetCVarDefault` raises an error. `GetCVarDefault` works the same way on the
glue screens.
### `C_CVar.GetCVar(name)` / `C_CVar.GetCVarDefault(name)` / `C_CVar.RegisterCVar(name [, value])`
The same functions as [`GetCVar`](#getcvarname),
[`GetCVarDefault`](#getcvardefaultname) and `RegisterCVar`, under their
`C_CVar` names.
### `C_CVar.SetCVar(name [, value])`
Sets a cvar and saves it to Config.wtf, as `SetCVar` does. Returns `true`
@@ -6265,6 +6314,26 @@ Two holdings that look alike still count as a change: picking up one of
two identical stacks, dropping it, and picking up the other reports each
pickup separately.
### `CVAR_UPDATE` event (fires for every change)
```
CVAR_UPDATE: cvarName, value
```
Fires when the value of a cvar changes. `cvarName` is the name of the cvar,
and `value` is its new value as a string. The Settings window and
`CVarCallbackRegistry` use this event to keep their controls up to date.
- The event fires only when the value changes, and only for a cvar that
`GetCVar` can read.
- The event fires at the start of the next frame, not during the call that
changes the cvar. A script that sets a cvar sees the event after the
script ends.
- A cvar that changes more than one time in a frame fires one event.
`value` is the value that the cvar has when the event fires.
- `SetCVar(name, value, eventName)` fires a second `CVAR_UPDATE`, with
`eventName` in place of the cvar name.
### `EQUIPMENT_SETS_CHANGED` event
Fires (with no payload) after any mutation: `Create`, `Save`,
@@ -6825,6 +6894,22 @@ again when the player comes back to life. When it fires, read
[`C_DeathInfo.GetSelfResurrectOptions`](#c_deathinfogetselfresurrectoptions)
again. A change to an item option does not fire this event.
### `SETTINGS_LOADED` event
Fires one time, when the Settings window has registered all of its
settings. It has no payload.
### `SETTINGS_PANEL_OPEN` event
Fires when an addon asks the Settings window to open.
```
SETTINGS_PANEL_OPEN: openToCategoryID, scrollToElementName
```
- **`openToCategoryID`** (number or string, or nil) — the category to show.
- **`scrollToElementName`** (string or nil) — the setting to scroll to.
### `SOUNDKIT_FINISHED` event
Fires when a sound finishes playing.
@@ -8556,6 +8641,30 @@ child:GetFrameLevel() -- 22
`frame:SetFrameLevel(level)` moves only `frame`. The frames under it keep
the levels they have.
### A shown frame moved under a visible parent becomes visible
`frame:SetParent(parent)` makes `frame` visible when `frame` is shown and
`parent` is visible, or when `parent` is `nil`. A frame is shown when its
own `Show()` is in effect, even while a hidden parent keeps it from being
visible.
```lua
local holder = CreateFrame("Frame", nil, UIParent)
holder:Hide()
local button = CreateFrame("Button", nil, holder) -- shown, not visible
button:SetParent(UIParent)
button:IsVisible() -- true
```
`OnShow` runs when the frame becomes visible.
### `OnShow` and `OnHide` can move frames
When a frame is shown or hidden, its children are shown or hidden one at a
time, and each child runs its `OnShow` or `OnHide` before the next child.
These scripts can call `SetParent` on any frame, also on the child itself.
A child that is no longer under the frame when its turn comes is skipped.
### A ScrollFrame keeps clipping its content when it moves
A ScrollFrame's scroll child, and all the frames in it, stay clipped to the
@@ -9315,11 +9424,13 @@ Does nothing when the box has no history.
call `editBox:SetFocus()`.
- Each call runs the script, also when the box is already in that state.
### `slider:Enable()` / `slider:Disable()` / `slider:IsEnabled()`
### `slider:Enable()` / `slider:Disable()` / `slider:SetEnabled(enabled)` / `slider:IsEnabled()`
`slider:Disable()` stops the mouse from moving the slider and runs its
`OnDisable` script. `slider:Enable()` lets the mouse move it again and runs
its `OnEnable` script. `slider:IsEnabled()` returns `true` or `false`.
its `OnEnable` script. `slider:SetEnabled(enabled)` calls `Enable()` when
`enabled` is true, and `Disable()` when it is false or nil.
`slider:IsEnabled()` returns `true` or `false`.
- A disabled slider still runs its `OnMouseDown` and `OnMouseUp` scripts,
and `slider:SetValue()` still changes its value.
@@ -12754,20 +12865,19 @@ end
### `InterfaceOptionsFrame` and addon option panels
Later clients list addon option panels in the Interface Options window,
`InterfaceOptionsFrame`. An addon adds its panel with
`InterfaceOptions_AddCategory(panel)` (Ace3's `AddToBlizOptions` does this
for every Ace3 addon) and opens it with
`InterfaceOptionsFrame_OpenToCategory(panel)`. Without these two
functions, Ace3 addons stop while they initialize.
Addons add option panels to the Settings window in two ways. Older addons
call `InterfaceOptions_AddCategory(panel)`. Ace3's `AddToBlizOptions` does
this for every Ace3 addon. Newer addons call
`Settings.RegisterCanvasLayoutCategory` and `Settings.RegisterAddOnCategory`.
Both kinds of panel show in the same window, in its AddOns list.
```lua
local panel = CreateFrame("Frame")
panel.name = "MyAddon" -- required: the list entry
panel.okay = function(self) end -- optional: Okay pressed
panel.cancel = function(self) end -- optional: Cancel pressed
panel.default = function(self) end -- optional: Defaults pressed
panel.refresh = function(self) end -- optional: panel shown
panel.okay = function(self) end -- optional: the window commits
panel.cancel = function(self) end -- optional: the window closes without a commit
panel.default = function(self) end -- optional: defaults are set
panel.refresh = function(self) end -- optional: the window opens, or the panel shows
InterfaceOptions_AddCategory(panel)
local sub = CreateFrame("Frame")
@@ -12777,21 +12887,51 @@ InterfaceOptions_AddCategory(sub)
InterfaceOptionsFrame_OpenToCategory(panel) -- or the category's name
```
The window lists addon panels under AddOns; a category with children starts
collapsed. To open the window, click AddOn Options in the game menu (above
Key Bindings). When you close a window that you opened from the game menu, the
game menu opens again. Okay and Cancel call `okay` / `cancel` on every panel.
Escape does the same as Cancel. Defaults calls `default` on the panel shown.
`InterfaceOptionsFrame_Show()` toggles the window. The names match later
clients (`InterfaceOptionsFrameAddOns` with its `buttons`, `buttonHeight` and
`update` fields, the `InterfaceOptionsFrameAddOnsList` scroll frame,
`InterfaceOptionsFramePanelContainer.displayedPanel`,
`InterfaceOptionsListButtonTemplate`, `INTERFACEOPTIONS_ADDONCATEGORIES`),
because addons and libraries use them directly.
The name of a panel is also the ID of its category. Thus
`Settings.GetCategory("MyAddon")` and `Settings.OpenToCategory("MyAddon")`
find the panel. The `parent` field can name a category that an addon added
through either API. If the parent is not in the list yet, the panel shows at
the top level. The list sorts addon categories by name, so the `position`
argument has no effect.
This is the addon side only. The client's own settings stay in their own
windows, and the Categories list, which later clients fill with the game's
settings, exists but stays empty.
The window calls the panel functions at these times:
- **Close**, **Apply** and Escape commit. Then `okay` runs on every panel.
- `cancel` runs only when the window closes without a commit. That occurs
when you click Exit in the dialog about settings that are not applied, or
when an addon clicks `InterfaceOptionsFrameCancel`.
- **Defaults** opens a dialog. **All Settings** runs `default` on every
panel. **These Settings** runs `default` on the panel that shows. On a
client whose dialogs have only two buttons, the dialog has no These
Settings choice.
- `refresh` runs when the window opens and each time the panel shows.
The Defaults button shows above a list of settings, not above a panel. After
the window closes, the game menu opens. A panel can have its own `OnCommit`,
`OnDefault` or `OnRefresh` method. Then that method runs in place of `okay`,
`default` or `refresh`.
To open the window, click AddOn Options in the game menu (above Key
Bindings). `InterfaceOptionsFrame_Show()` opens or closes the window.
`InterfaceAddOnsList_Update()` builds the list again. The window shows its
Game and AddOns tabs only when both lists have categories.
The names of the earlier Interface Options window are parts of the Settings
window, because addons use these names directly:
| Name | Part of the Settings window |
|------|-----------------------------|
| `InterfaceOptionsFrame` | `SettingsPanel`, the window |
| `InterfaceOptionsFrameAddOns`, `InterfaceOptionsFrameCategories` | The category list. Its `buttons` table is empty. Its `update` field builds the list again. |
| `InterfaceOptionsFrameAddOnsList` | The scroll box of the category list |
| `InterfaceOptionsFrameAddOnsListScrollBar` | The scroll bar of the category list |
| `InterfaceOptionsFramePanelContainer` | The frame that holds the panel. Its `displayedPanel` field is the panel that shows. |
| `InterfaceOptionsFrameOkay` | The Close button |
| `InterfaceOptionsFrameCancel` | A hidden button. A click closes the window without a commit. |
| `InterfaceOptionsFrameDefaults` | A hidden button. A click sets the defaults of the category that shows. |
`INTERFACEOPTIONS_ADDONCATEGORIES` lists the panels that
`InterfaceOptions_AddCategory` added.
## Item
@@ -22331,6 +22471,26 @@ f:SetScript("OnEvent", function()
end)
```
## SettingsUtil
### `C_SettingsUtil.OpenSettingsPanel([openToCategoryID [, scrollToElementName]])`
Opens the Settings window. With a category ID, the window shows that
category. With `scrollToElementName` too, the list of settings scrolls to
the setting of that name. `Settings.OpenToCategory` calls this function.
The function fires `SETTINGS_PANEL_OPEN` with its two arguments, and the
window opens on that event. A category ID is the number that the category
gets, or the value that an addon puts in the `ID` field of the category.
Many addons set `ID` to the name of the category. Then the name opens the
category.
### `C_SettingsUtil.NotifySettingsLoaded()`
Fires `SETTINGS_LOADED`. The Settings window calls this function one time,
after `VARIABLES_LOADED` and `PLAYER_ENTERING_WORLD`. At that time, every
function that addons gave to `SettingsRegistrar:AddRegistrant` has run.
## Sound
Every sound the client plays comes from one table of sound entries. Each
+10 -2
View File
@@ -31,8 +31,16 @@ build uses the MSVC fastcall convention. Each `TValue` is **16 bytes** here
|--------|-----------------|---------------------------------------------|
| `+0x08`| `top` | `TValue *` — top of stack (next free slot) |
| `+0x0C`| `base` | `TValue *` — base of the current frame |
| `+0x10`| `ci` | `CallInfo *` — current call info |
| `+0x18`| `stack` | bottom of stack array |
| `+0x10`| `l_G` | `global_State *` |
| `+0x14`| `ci` | `CallInfo *` — current call info (`lua_getstack` `0x006FBAA0` reads it) |
| `+0x1C`| `stack` | bottom of stack array |
| `+0x20`| `stacksize` | |
| `+0x28`| `base_ci` | `CallInfo *` — first call info; `ci == base_ci` when no function runs |
The GC counters are `global_State` fields, at `l_G` (`L+0x10`):
| Offset | Field | Notes |
|--------|-----------------|---------------------------------------------|
| `+0x24`| `gcthreshold` | bytes; `lua_setgcthreshold` writes here |
| `+0x28`| `nblocks` | live byte count (read by `lua_getgccount`) |
+19
View File
@@ -1775,6 +1775,9 @@ enum Offsets {
CVAR_FLAG_ARCHIVE = 0x1,
CVAR_FLAG_STAGED = 0x2,
CVAR_FLAG_READ_ONLY = 0x4,
CVAR_FLAG_SCRIPT_VISIBLE = 0x80000000,
// The cvar's name string (docs/notes/cvar.md; `cvarlist` prints it).
OFF_CVAR_NAME = 0x14,
OFF_CVAR_CALLBACK = 0xBC,
OFF_CVAR_USERDATA = 0xC0,
// Console categories — the registrar's category argument, an index into
@@ -4385,6 +4388,16 @@ enum Offsets {
FUN_PLAYERMODEL_SHOW = 0x00505D00,
FUN_SIMPLEFRAME_HIDE = 0x0076AD50,
FUN_SIMPLEFRAME_SHOW = 0x0076AE10,
// The child loops of FUN_SIMPLEFRAME_HIDE and FUN_SIMPLEFRAME_SHOW. Each
// starts with `mov ebx, [esi+0x300]` (8B 9E 00 03 00 00, the head of
// OFF_FRAME_CHILD_LIST), calls each child's VTBL_FRAME_HIDE /
// VTBL_FRAME_SHOW, reads the next node only after the call
// (`mov ebx, [ebx+4]`), and leaves at the RESUME address, where nothing
// reads EBX before the function's `pop ebx`.
SITE_SIMPLEFRAME_HIDE_CHILD_WALK = 0x0076ADC9,
SITE_SIMPLEFRAME_HIDE_CHILD_WALK_RESUME = 0x0076ADF9,
SITE_SIMPLEFRAME_SHOW_CHILD_WALK = 0x0076AEB6,
SITE_SIMPLEFRAME_SHOW_CHILD_WALK_RESUME = 0x0076AEE0,
// The turn latch (SetRotation sets it, the next paint clears it) and the
// turn deadline in OS ms (now + 100 on a turn, 0 once Stand is armed).
OFF_PLAYERMODEL_TURNING = 0x3E8,
@@ -5005,6 +5018,12 @@ enum Offsets {
// caller), after storing the alpha byte (0x007690D2), both list heads and
// the base vtable (0x007692E5).
FUN_FRAME_SET_PARENT = 0x0076AB10,
// Script SetParent — `int __fastcall(lua_State *)`, the method table
// 0x0087C9B8's entry 4 (docs/raw_methods.txt). Reads the parent argument
// (nil, a name, or a frame table) and calls the object's vtable+0x14, which
// for a frame is FUN_FRAME_SET_PARENT (benilla-re ui/visibility
// "Reparenting by script").
FUN_SCRIPT_REGION_SET_PARENT = 0x007A1550,
// CSimpleFrame destructor body — `void __thiscall(frame)`, plain `ret`.
// Called or tail-called by the base vtable's slot-0 deleting destructor
// (0x00769380) and every derived frame class's destructor (16 call sites,
+9
View File
@@ -514,7 +514,16 @@ const Game::Doc::Function kGetBindingAction{"Returns the command bound to a key.
kGetBindingActionArgs, kGetBindingActionRets,
"BindingsGlobals"};
// The engine's binding sets (Offsets::BINDING_SET_*), as retail names them.
const Game::Lua::EnumIntegerEntry kBindingSet[] = {
{"Default", Offsets::BINDING_SET_DEFAULT},
{"Account", Offsets::BINDING_SET_ACCOUNT},
{"Character", Offsets::BINDING_SET_CHARACTER},
{"Current", Offsets::BINDING_SET_CURRENT},
};
void RegisterLuaFunctions() {
Game::Lua::RegisterIntegerEnum("Enum", "BindingSet", kBindingSet, "KeyBindings");
Game::Lua::RegisterGlobalFunction("GetBindingByKey", &Script_GetBindingByKey,
&kGetBindingByKey);
Game::Lua::RegisterGlobalFunction("SetBindingSpell", &Script_SetBindingSpell,
+134
View File
@@ -0,0 +1,134 @@
// This file is part of ClassicAPI.
//
// ClassicAPI is free software: you can redistribute it and/or modify it under the terms
// of the GNU General Public License as published by the Free Software Foundation, either
// version 3 of the License, or (at your option) any later version.
//
// ClassicAPI is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along with
// ClassicAPI. If not, see <https://www.gnu.org/licenses/>.
// `CVAR_UPDATE(cvarName, value)` whenever a cvar that Lua can see changes, as
// retail fires it. Retail's Settings window and CVarCallbackRegistry listen
// for it by the cvar's name.
//
// 1.12 fires CVAR_UPDATE (event 0x138) only from Script_SetCVar
// (FUN_00488C10), and only with the event token a caller passes as the third
// argument: `SetCVar(name, value, "TOKEN")` -> CVAR_UPDATE("TOKEN", value).
// That path stays as it is. The stock frames that listen (OptionsFrame,
// UIOptionsFrame, SoundOptionsFrame, TextStatusBar) key on upper-case tokens
// such as "SHOW_BUFF_DURATIONS", which no cvar name matches, so a fire by name
// is new to them; SoundOptionsFrame reloads its check boxes on any fire, which
// changes nothing. ReputationWatchBar (ReputationFrame.xml) is the one that
// keys on a cvar name: a fire for statusBarText now locks or unlocks the
// watched reputation's text, as that handler means to, and any other fire runs
// ReputationWatchBar_Update, as every UPDATE_FACTION already does.
//
// The hook is on CVar::Set (FUN_SET_CVAR_VALUE), which every write goes
// through: Script_SetCVar, C_CVar.SetCVar, the console `set` command and the
// engine's own writes. A change is fired at the head of the next UI frame,
// where no frame is mid-draw and no engine code is mid-way through its work.
// It is never fired inside the setter: the engine sets cvars from inside its
// own code while a script runs further up the stack, and a listener run
// there would run in the middle of engine code that does not expect a
// script. That a script is running somewhere does not make the setter's
// caller a script.
//
// Only a cvar that Lua can see (CVAR_FLAG_SCRIPT_VISIBLE) fires, only when its
// value text changed, and only while a frame listens, so the Config.wtf load
// and the cvar registrations at startup fire nothing.
//
// A cvar that changed fires once per frame, with the value it has when the
// event fires, not the value of each change. Retail fires inside the setter,
// so the value it gives is always the current one, and its listeners rely on
// that: the Settings window writes the value it is given back into its
// setting. A value from an earlier change of the same frame would be written
// back over the later one, change the cvar again and fire again, so two
// changes in one frame would swap the cvar between them every frame. The value
// is copied before the fire: a listener that sets the cvar frees the engine's
// string while the dispatcher still hands it to the listeners after it.
#include "event/Custom.h"
#include "tick/FrameTick.h"
#include "Game.h"
#include "Offsets.h"
#include <algorithm>
#include <cstdint>
#include <string>
#include <vector>
namespace CVar::Update {
namespace {
// CVar::Set — __thiscall(cvar, value, apply, setReset, setDefault, force),
// RET 0x14; declared __fastcall with the unused EDX so the hook matches it.
using Set_t = int(__fastcall *)(void *cvar, void *edx, const char *value, int apply, int setReset,
int setDefault, int force);
Set_t g_origSet = nullptr;
// Each cvar that changed since the last drain, once, in the order of its first
// change. A cvar record lives as long as the client: the engine never frees
// one.
std::vector<void *> g_pending;
int ListeningSlot() {
const int slot = Event::Custom::LookupByName("CVAR_UPDATE");
return Event::Custom::HasListeners(slot) ? slot : -1;
}
const char *ValueOf(void *cvar) {
const char *value = Game::Read<const char *>(cvar, Offsets::OFF_CVAR_VALUE_STR);
return value != nullptr ? value : "";
}
int __fastcall Set_h(void *cvar, void *edx, const char *value, int apply, int setReset,
int setDefault, int force) {
const bool visible =
(Game::Read<uint32_t>(cvar, Offsets::OFF_CVAR_FLAGS) & Offsets::CVAR_FLAG_SCRIPT_VISIBLE) != 0;
const int slot = visible ? ListeningSlot() : -1;
if (slot < 0)
return g_origSet(cvar, edx, value, apply, setReset, setDefault, force);
const std::string before = ValueOf(cvar);
const int result = g_origSet(cvar, edx, value, apply, setReset, setDefault, force);
if (before == ValueOf(cvar))
return result;
if (std::find(g_pending.begin(), g_pending.end(), cvar) == g_pending.end())
g_pending.push_back(cvar);
return result;
}
void Drain() {
if (g_pending.empty())
return;
std::vector<void *> changed;
changed.swap(g_pending);
const int slot = ListeningSlot();
if (slot < 0)
return;
for (void *cvar : changed) {
const std::string value = ValueOf(cvar);
Event::Custom::Fire(slot, "%s%s", Game::Read<const char *>(cvar, Offsets::OFF_CVAR_NAME),
value.c_str());
}
}
// A change queued under the old interface is not fired into the new one.
void PrepareForReload() { g_pending.clear(); }
const Game::HookAutoRegister _setHook{Offsets::FUN_SET_CVAR_VALUE, reinterpret_cast<void *>(&Set_h),
reinterpret_cast<void **>(&g_origSet)};
const Tick::FrameTick::AutoSubscribeBefore _tick{&Drain};
const Game::ReloadAutoRegister _reload{&PrepareForReload};
} // namespace
} // namespace CVar::Update
@@ -8,9 +8,6 @@
locales\locales.xml
FrameXML\InterfaceOptions.xml
FrameXML\InterfaceOptions.lua
SecureTemplates.xml
Compat.lua
Util\EnvironmentUtil.lua
@@ -38,6 +35,8 @@ Util\ExportUtil.lua
Util\ButtonStateBehavior.lua
Util\CallbackRegistry.lua
Util\GlobalCallbackRegistry.lua
Util\CvarUtil.lua
Util\BindingUtil.lua
Util\TemplateInfoCache.lua
Util\FrameFactory.lua
Util\DataProvider.lua
@@ -144,6 +143,15 @@ FrameXML\InputBoxTemplates.xml
FrameXML\SearchBoxTemplate.xml [ExcludeLoadGameType turtle]
FrameXML\ColorSwatch.lua
FrameXML\ColorSwatch.xml
FrameXML\ColorPickerFrame.lua
FrameXML\MinimalSlider.lua
FrameXML\MinimalSlider.xml
FrameXML\FontStyles.xml
FrameXML\SelectableButton.lua
FrameXML\SelectableButton.xml
FrameXML\ButtonGroup.lua
FrameXML\MinimalTab.lua
FrameXML\MinimalTab.xml
FrameXML\ScriptErrorsFrame.lua
FrameXML\ScriptErrorsFrame.xml
FrameXML\ModelScene\CameraRegistry.lua
@@ -174,6 +182,30 @@ Menu\Classic\MenuTemplates.lua
Menu\Classic\MenuTemplates.xml
Menu\MenuUtil.lua
Settings\Blizzard_SettingsRegistrar.lua
Settings\Blizzard_Settings.lua
Settings\Blizzard_Category.lua
Settings\Blizzard_CategoryList.lua
Settings\Blizzard_CategoryList.xml
Settings\Blizzard_SettingsList.lua
Settings\Blizzard_SettingsList.xml
Settings\Blizzard_Setting.lua
Settings\Blizzard_SettingControls.lua
Settings\Blizzard_SettingControls.xml
Settings\Blizzard_Keybindings.lua
Settings\Blizzard_Keybindings.xml
Settings\Blizzard_SettingsPanelTemplates.xml
Settings\Blizzard_SettingsPanel.lua
Settings\Blizzard_SettingsPanel.xml
Settings\Blizzard_Dialogs.lua
Settings\Blizzard_SettingsLayouts.lua
Settings\Blizzard_Registration.lua
Settings\Blizzard_SettingsInbound.lua
FrameXML\InterfaceOptions.lua
Options\Controls.lua
Options\Controls.xml
Options\Panel.lua
APIDocumentation\BaseAPIMixin.lua
+36
View File
@@ -8,6 +8,33 @@ end
C_Container.GetContainerNumSlots = GetContainerNumSlots
C_Container.PickupContainerItem = PickupContainerItem
C_CVar.GetCVar = GetCVar
C_CVar.GetCVarDefault = GetCVarDefault
C_CVar.RegisterCVar = RegisterCVar
C_KeyBindings = C_KeyBindings or {}
-- This client's binding list holds each action once.
function C_KeyBindings.GetBindingIndex(action)
for index = 1, GetNumBindings() do
if GetBinding(index) == action then
return index
end
end
return nil
end
-- This client has one binding context, so no action has a context of its
-- own.
function C_KeyBindings.GetBindingContextForAction(action)
return nil
end
-- This client has no custom binding types (retail's push-to-talk key).
function C_KeyBindings.GetCustomBindingType(bindingIndex)
return nil
end
C_ActionBar = C_ActionBar or {}
-- Retail answers per game type. This client always has a keyring.
@@ -43,3 +70,12 @@ end
function C_PlayerInfo.GetAlternateFormInfo()
return false, false
end
-- Retail marks the settings added in the current version as new. Nothing in
-- this client is new.
function IsNewSettingInCurrentVersion(variable)
return false
end
function MarkNewSettingAsSeen(variable)
end
@@ -0,0 +1,239 @@
-- Verbatim backport of retail's Blizzard_SharedXML/ButtonGroup.lua.
--[[
Required Elements - all buttons in the group need to inherit from SelectableButtonMixin
and have the OnClick handler defined in XML
]]
ButtonGroupBaseMixin = CreateFromMixins(CallbackRegistryMixin);
ButtonGroupBaseMixin:GenerateCallbackEvents(
{
"Selected",
"Unselected",
}
);
function ButtonGroupBaseMixin:Init()
CallbackRegistryMixin.OnLoad(self);
self.buttons = {};
end
function ButtonGroupBaseMixin:SetShown(shown)
for index, button in ipairs(self.buttons) do
button:SetShown(shown);
end
end
function ButtonGroupBaseMixin:AddButton(button)
self:AddInternal(button);
end
function ButtonGroupBaseMixin:AddButtons(buttons)
for buttonIndex, button in ipairs(buttons) do
self:AddInternal(button);
end
end
function ButtonGroupBaseMixin:AddInternal(button, func, group)
table.insert(self.buttons, button);
-- NOTE: The SelectableButton that this is intended to be used with doesn't actually care about the mouseButton argument.
local previousOnClickScript = button:GetScript("OnClick");
assert(not button.previousOnClickScript);
button.previousOnClickScript = previousOnClickScript;
button:SetScript("OnClick", function(o, mouseButton)
-- Only run our group's selection changed callback if the button object didn't have a mixin-OnClick method,
-- or if the OnClick method indicated that selection state actually changed.
local wasSelected = button:IsSelected();
if previousOnClickScript then
previousOnClickScript(button, mouseButton);
end
local isSelected = button:IsSelected();
local selectionChanged = wasSelected ~= isSelected;
if not previousOnClickScript or selectionChanged then
func(group, button, button:IsSelected());
end
end);
end
function ButtonGroupBaseMixin:RemoveButton(button)
self:RemoveInternal(button);
end
function ButtonGroupBaseMixin:RemoveButtons(buttons)
if buttons == self.buttons then
self:RemoveAllButtons();
else
for buttonIndex, button in ipairs(buttons) do
self:RemoveInternal(button);
end
end
end
function ButtonGroupBaseMixin:RemoveInternal(button)
tDeleteItem(self.buttons, button);
-- Restore the button's OnClick to whatever it used to be.
button:SetScript("OnClick", button.previousOnClickScript);
button.previousOnClickScript = nil;
end
function ButtonGroupBaseMixin:SetButtons(buttons)
self:RemoveAllButtons();
self:AddButtons(buttons);
end
function ButtonGroupBaseMixin:RemoveAllButtons()
for index, button in ipairs_reverse(self.buttons) do
self:RemoveInternal(button);
end
end
function ButtonGroupBaseMixin:GetButtons()
return self.buttons;
end
function ButtonGroupBaseMixin:Reset()
self:RemoveAllButtons();
self:UnregisterEvents();
self.callbacks = {};
end
function ButtonGroupBaseMixin:FindButtonByPredicate(pred)
for buttonIndex, button in ipairs(self.buttons) do
if pred(button) then
return button;
end
end
return nil;
end
function ButtonGroupBaseMixin:GetButtonsByPredicate(pred)
local buttons = {};
for buttonIndex, button in ipairs(self.buttons) do
if pred(button) then
table.insert(buttons, button);
end
end
return buttons;
end
function ButtonGroupBaseMixin:Unselect(button)
self:UnselectAtIndex(self:GetButtonIndex(button));
end
function ButtonGroupBaseMixin:Select(button)
self:SelectAtIndex(self:GetButtonIndex(button));
end
function ButtonGroupBaseMixin:SelectAtIndex(index)
self:SetSelectedAtIndex(index, true);
end
function ButtonGroupBaseMixin:UnselectAtIndex(index)
self:SetSelectedAtIndex(index, false);
end
local function SetButtonSelectedAndGetWasChanged(button, selected)
local wasSelected = button:IsSelected();
button:SetSelected(selected);
return wasSelected ~= button:IsSelected();
end
function ButtonGroupBaseMixin:SetSelectedAtIndex(index, selected)
local button = self:GetAtIndex(index);
if button then
if SetButtonSelectedAndGetWasChanged(button, selected) then
self:OnSelectionChange(button, selected);
end
end
end
function ButtonGroupBaseMixin:GetSelectedButtons()
return self:GetButtonsByPredicate(
function(button)
return button:IsSelected();
end
);
end
function ButtonGroupBaseMixin:GetButtonIndex(button)
return tIndexOf(self.buttons, button);
end
function ButtonGroupBaseMixin:GetAtIndex(index)
return self.buttons[index];
end
ButtonGroupMixin = CreateFromMixins(ButtonGroupBaseMixin);
function ButtonGroupMixin:OnSelectionChange(button, newSelected)
local event = newSelected and ButtonGroupBaseMixin.Event.Selected or ButtonGroupBaseMixin.Event.Unselected;
self:TriggerEvent(event, button, self:GetButtonIndex(button));
end
function ButtonGroupMixin:AddInternal(button)
ButtonGroupBaseMixin.AddInternal(self, button, self.OnSelectionChange, self);
end
function CreateButtonGroup()
return CreateAndInitFromMixin(ButtonGroupMixin);
end
RadioButtonGroupMixin = CreateFromMixins(ButtonGroupBaseMixin);
function RadioButtonGroupMixin:CanChangeSelection(button, newSelected)
return not (not newSelected and #self:GetSelectedButtons() == 1);
end
function RadioButtonGroupMixin:OnSelectionChange(button, newSelected)
-- Deselect everything that was selected
for selectedButtonIndex, selectedButton in ipairs(self:GetSelectedButtons()) do
if selectedButton ~= button then
selectedButton:SetSelected(false);
self:TriggerEvent(ButtonGroupBaseMixin.Event.Unselected, selectedButton, self:GetButtonIndex(selectedButton));
end
end
-- Select the new thing if appropriate
if newSelected then
self:TriggerEvent(ButtonGroupBaseMixin.Event.Selected, button, self:GetButtonIndex(button));
else
self:TriggerEvent(ButtonGroupBaseMixin.Event.Unselected, button, self:GetButtonIndex(button));
end
end
function RadioButtonGroupMixin:AddInternal(button)
button:SetSelectionChangeInterrupt(GenerateClosure(self.CanChangeSelection, self));
ButtonGroupBaseMixin.AddInternal(self, button, self.OnSelectionChange, self);
end
function RadioButtonGroupMixin:RemoveInternal(button)
button:SetSelectionChangeInterrupt(nil);
ButtonGroupBaseMixin.RemoveInternal(self, button);
end
DeselectableRadioButtonGroupMixin = CreateFromMixins(RadioButtonGroupMixin);
function DeselectableRadioButtonGroupMixin:CanChangeSelection(button, newSelected)
return true;
end
--[[
Required Elements - all buttons in the group need to inherit from SelectableButtonTemplate
and you CAN override the OnLoad, and OnClick handler if needed
]]--
function CreateRadioButtonGroup()
return CreateAndInitFromMixin(RadioButtonGroupMixin);
end
function CreateDeselectableRadioButtonGroup()
return CreateAndInitFromMixin(DeselectableRadioButtonGroupMixin);
end
@@ -0,0 +1,42 @@
-- Backport of the ColorPickerFrameMixin methods from Classic Era's
-- Blizzard_ColorPickerFrame/Classic/ColorPickerFrame.lua, added to this
-- client's own ColorPickerFrame.
--
-- Differences from the Classic Era source:
-- - This client's frame calls ColorPickerFrame.func when the color changes
-- and when OK is clicked, where Classic Era's calls swatchFunc. So
-- SetupColorPickerAndShow sets both.
-- - The previous values are also the argument the frame gives cancelFunc,
-- as this client's own callers expect.
-- - This client's frame has no stratum of its own, so it takes UIParent's
-- MEDIUM and opens behind the HIGH Settings window. It is put in the
-- DIALOG stratum that Classic Era's frame declares.
ColorPickerFrame:SetFrameStrata("DIALOG");
function ColorPickerFrame:GetColorAlpha()
return OpacitySliderFrame:GetValue();
end
function ColorPickerFrame:SetupColorPickerAndShow(info)
self.swatchFunc = info.swatchFunc;
self.func = info.swatchFunc;
self.hasOpacity = info.hasOpacity;
self.opacityFunc = info.opacityFunc;
self.opacity = info.opacity;
self.previousValues = { r = info.r, g = info.g, b = info.b, a = info.opacity };
self.cancelFunc = info.cancelFunc;
self.extraInfo = info.extraInfo;
ColorSwatch:SetColorTexture(info.r, info.g, info.b);
self:SetColorRGB(info.r, info.g, info.b);
self:Show();
end
function ColorPickerFrame:GetExtraInfo()
return self.extraInfo;
end
function ColorPickerFrame:GetPreviousValues()
return self.previousValues.r, self.previousValues.g, self.previousValues.b, self.previousValues.a;
end
@@ -0,0 +1,22 @@
<Ui xmlns="http://www.blizzard.com/wow/ui/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.blizzard.com/wow/ui/ ..\FrameXML\UI.xsd">
<!--
Font objects from retail's Blizzard_Fonts_Shared/Shared/FontStyles.xml that
1.12's Fonts.xml does not have. Retail builds them on its SystemFont
families; here each one inherits the 1.12 font with the same face and
size, so a localized client's own font files apply.
- GameFontHighlightHuge: retail's GameFontNormalHuge in white. 1.12's
GameFontNormalHuge is the same 20 px face.
- GameFontHighlightMedium: retail's SystemFont_Shadow_Med3 (14 px, with a
shadow) in white, so 1.12's GameFontNormal (which has the shadow) at
14 px.
-->
<Font name="GameFontHighlightHuge" inherits="GameFontNormalHuge" virtual="true">
<Color r="1.0" g="1.0" b="1.0"/>
</Font>
<Font name="GameFontHighlightMedium" inherits="GameFontNormal" virtual="true">
<FontHeight>
<AbsValue val="14"/>
</FontHeight>
<Color r="1.0" g="1.0" b="1.0"/>
</Font>
</Ui>
@@ -1,373 +1,201 @@
-- Backport of the Interface Options panel's addon side (InterfaceOptionsFrame,
-- InterfaceOptions_AddCategory, InterfaceOptionsFrame_OpenToCategory) to
-- vanilla 1.12 / Lua 5.0.
-- The Interface Options API of 3.3.5-era clients (InterfaceOptions_AddCategory,
-- InterfaceOptionsFrame_OpenToCategory and the InterfaceOptionsFrame names),
-- on top of the Settings window (Settings\Blizzard_SettingsPanel.lua).
--
-- Later clients list addon option panels in InterfaceOptionsFrame. Addons add
-- theirs with InterfaceOptions_AddCategory(panel) - Ace3's
-- AceConfigDialog:AddToBlizOptions does it for every Ace3 addon - and open them
-- with InterfaceOptionsFrame_OpenToCategory. Frame and list names match later
-- clients because addons reach for them directly (Zygor Guides Viewer 2.0
-- re-tints the frame's first region; LibBetterBlizzOptions-1.0 resizes the
-- lists through their `buttons` / `buttonHeight` / `update` fields).
-- Addons from both eras run here. Ace3's AceConfigDialog:AddToBlizOptions
-- calls InterfaceOptions_AddCategory whenever it exists; newer addons call
-- Settings.RegisterCanvasLayoutCategory when Settings and SettingsPanel
-- exist. Both land in the one Settings window: a panel added here is a
-- canvas category in the AddOns set.
--
-- Implementation differences from the modern source:
-- - Addon panels only. Vanilla's own options stay in UIOptionsFrame and
-- friends; the Categories list exists (empty, hidden) for code that
-- expects it.
-- - Panel protocol as on later clients: panel.name (required), panel.parent
-- (name of the category to nest under), and optional okay / cancel /
-- default / refresh, each called with the panel. Categories with children
-- start collapsed. Okay and Cancel call okay / cancel on every panel;
-- Defaults calls default on the one shown; Escape is Cancel.
-- - The game-menu entry is an extra AddOn Options button: the client's own
-- options keep their buttons, so the addon list gets one of its own.
-- Not "AddOns" - on later clients that button opens the addon list.
-- - Lua 5.0: no `...` expression or select().
-- The panel protocol of 3.3.5 maps onto the Settings window's own:
-- - panel.name (required) is the category's name and its ID, as Ace3 and
-- newer addons set it, so Settings.GetCategory(name) finds it.
-- - panel.parent names the category to nest under: a category added here
-- or through Settings, found by ID or by name. A panel whose parent is
-- not registered yet is listed at the top level.
-- - panel.okay runs when the window commits (Close and Apply), panel.default
-- when its defaults are set, panel.refresh when the window opens and when
-- the panel is shown. The panel keeps its own OnCommit, OnDefault or
-- OnRefresh if it has one.
-- - panel.cancel runs when the window closes without committing: the
-- discard dialog's Exit, or InterfaceOptionsFrameCancel. Close and Escape
-- commit, as on retail.
-- - The list sorts addon categories by name, so `position` has no effect.
--
-- The old window's names are the Settings window's frames, because addons
-- reach for them directly (Auctionator sets backdrops on InterfaceOptionsFrame,
-- InterfaceOptionsFrameAddOns and InterfaceOptionsFrameCategories and lays a
-- frame over InterfaceOptionsFrame; skins restyle all of them):
-- InterfaceOptionsFrame SettingsPanel
-- InterfaceOptionsFrameAddOns, ...Categories the category list
-- InterfaceOptionsFrameAddOnsList the list's ScrollBox
-- InterfaceOptionsFrameAddOnsListScrollBar the list's scroll bar
-- InterfaceOptionsFramePanelContainer the canvas a panel is shown in;
-- displayedPanel is that panel
-- InterfaceOptionsFrameOkay the Close button
-- InterfaceOptionsFrameCancel / ...Defaults hidden buttons: closing without
-- commit / defaults for the shown
-- category
-- The list has no fixed rows: its `buttons` table is empty, and its `update`
-- (also InterfaceAddOnsList_Update) rebuilds it. INTERFACEOPTIONS_ADDONCATEGORIES
-- lists the panels added here.
if InterfaceOptionsFrame then return end -- a real implementation wins
local categoryList = SettingsPanel:GetCategoryList();
local canvas = SettingsPanel:GetSettingsCanvas();
INTERFACEOPTIONS_ADDONCATEGORIES = INTERFACEOPTIONS_ADDONCATEGORIES or {}
local categories = INTERFACEOPTIONS_ADDONCATEGORIES
local BUTTON_HEIGHT = 18
local NUM_BUTTONS = 24
local function report(err)
local handler = geterrorhandler and geterrorhandler()
if handler then handler(err) end
end
local LIST_BACKDROP = {
bgFile = "Interface\\Tooltips\\UI-Tooltip-Background",
edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
tile = true, tileSize = 16, edgeSize = 16,
insets = { left = 5, right = 5, top = 5, bottom = 5 },
}
-- ---------------------------------------------------------------------------
-- Frame
-- ---------------------------------------------------------------------------
local frame = CreateFrame("Frame", "InterfaceOptionsFrame", UIParent)
frame:Hide()
frame:SetWidth(648)
frame:SetHeight(568)
frame:SetPoint("CENTER", UIParent, "CENTER", 0, 0)
frame:SetFrameStrata("DIALOG")
frame:SetToplevel(true)
frame:EnableMouse(true)
frame:SetMovable(true)
frame:SetClampedToScreen(true)
-- The background is the frame's first region: addons re-tint it through
-- InterfaceOptionsFrame:GetRegions().
local background = frame:CreateTexture(nil, "BACKGROUND")
background:SetTexture("Interface\\DialogFrame\\UI-DialogBox-Background")
background:SetPoint("TOPLEFT", frame, "TOPLEFT", 11, -12)
background:SetPoint("BOTTOMRIGHT", frame, "BOTTOMRIGHT", -12, 11)
frame:SetBackdrop({
edgeFile = "Interface\\DialogFrame\\UI-DialogBox-Border",
edgeSize = 32,
insets = { left = 11, right = 12, top = 12, bottom = 11 },
})
local header = frame:CreateTexture(nil, "ARTWORK")
header:SetTexture("Interface\\DialogFrame\\UI-DialogBox-Header")
header:SetWidth(360)
header:SetHeight(64)
header:SetPoint("TOP", frame, "TOP", 0, 12)
local title = frame:CreateFontString(nil, "ARTWORK", "GameFontNormal")
title:SetPoint("TOP", header, "TOP", 0, -14)
title:SetText(ADDON_OPTIONS)
frame:SetScript("OnMouseDown", function()
if arg1 == "LeftButton" then this:StartMoving() end
end)
frame:SetScript("OnMouseUp", function() this:StopMovingOrSizing() end)
-- A native center panel, as on later clients: ShowUIPanel swaps it with the
-- game menu, CloseAllWindows closes it, and closing returns to lastFrame.
UIPanelWindows["InterfaceOptionsFrame"] = { area = "center", pushable = 0, whileDead = 1 }
-- ---------------------------------------------------------------------------
-- Category lists and the panel container
-- ---------------------------------------------------------------------------
local function CreateList(name)
local list = CreateFrame("Frame", name, frame)
list:SetWidth(185)
list:SetPoint("TOPLEFT", frame, "TOPLEFT", 22, -40)
list:SetPoint("BOTTOMLEFT", frame, "BOTTOMLEFT", 22, 50)
list:SetBackdrop(LIST_BACKDROP)
list:SetBackdropColor(0, 0, 0, 0.5)
list:SetBackdropBorderColor(0.6, 0.6, 0.6)
list.buttonHeight = BUTTON_HEIGHT
list.buttons = {}
for i = 1, NUM_BUTTONS do
local button = CreateFrame("Button", name .. "Button" .. i, list, "InterfaceOptionsListButtonTemplate")
if i == 1 then
button:SetPoint("TOPLEFT", list, "TOPLEFT", 5, -8)
else
button:SetPoint("TOPLEFT", list.buttons[i - 1], "BOTTOMLEFT", 0, 0)
end
button:Hide()
list.buttons[i] = button
end
return list
end
-- Vanilla keeps its own options elsewhere; this list stays empty.
local gameList = CreateList("InterfaceOptionsFrameCategories")
gameList.update = function() end
gameList:Hide()
local addOnList = CreateList("InterfaceOptionsFrameAddOns")
local scroll = CreateFrame("ScrollFrame", "InterfaceOptionsFrameAddOnsList", addOnList, "FauxScrollFrameTemplate")
scroll:SetPoint("TOPLEFT", addOnList, "TOPLEFT", 0, -8)
scroll:SetPoint("BOTTOMRIGHT", addOnList, "BOTTOMRIGHT", -30, 8)
local container = CreateFrame("Frame", "InterfaceOptionsFramePanelContainer", frame)
container:SetPoint("TOPLEFT", addOnList, "TOPRIGHT", 16, 0)
container:SetPoint("BOTTOMRIGHT", frame, "BOTTOMRIGHT", -22, 50)
container:SetBackdrop(LIST_BACKDROP)
container:SetBackdropColor(0, 0, 0, 0.5)
container:SetBackdropBorderColor(0.6, 0.6, 0.6)
INTERFACEOPTIONS_ADDONCATEGORIES = {};
local panels = INTERFACEOPTIONS_ADDONCATEGORIES;
-- ---------------------------------------------------------------------------
-- Categories
-- ---------------------------------------------------------------------------
local function FindCategoryByName(categories, name)
for _, category in ipairs(categories) do
if category:GetName() == name then
return category;
end
local found = FindCategoryByName(category:GetSubcategories(), name);
if found then
return found;
end
end
end
-- By ID first, as Settings.GetCategory does, then by name: a category
-- registered through Settings keeps its counter ID unless the addon set it.
local function FindCategory(name)
for _, panel in ipairs(categories) do
if panel.name == name then return panel end
end
return Settings.GetCategory(name) or FindCategoryByName(SettingsPanel:GetAllCategories(), name);
end
local function HasChildren(panel)
for _, p in ipairs(categories) do
if p.parent == panel.name then return true end
end
end
-- Top-level categories in order, each followed by its children when expanded.
-- A child whose parent is not registered is listed at the top level.
local function VisibleCategories()
local out = {}
for _, panel in ipairs(categories) do
if not panel.parent or not FindCategory(panel.parent) then
table.insert(out, panel)
if not panel.collapsed then
for _, child in ipairs(categories) do
if child.parent == panel.name then table.insert(out, child) end
end
end
local function FindCategoryForFrame(categories, frame)
for _, category in ipairs(categories) do
local layout = SettingsPanel:GetLayout(category);
if layout and layout:GetLayoutType() == SettingsLayoutMixin.LayoutType.Canvas and layout:GetFrame() == frame then
return category;
end
local found = FindCategoryForFrame(category:GetSubcategories(), frame);
if found then
return found;
end
end
return out
end
function InterfaceAddOnsList_Update()
local entries = VisibleCategories()
local offset = FauxScrollFrame_GetOffset(scroll) or 0
local numButtons = table.getn(addOnList.buttons)
for i = 1, numButtons do
local button = addOnList.buttons[i]
local panel = entries[i + offset]
local text = getglobal(button:GetName() .. "Text")
local toggle = getglobal(button:GetName() .. "Toggle")
if panel then
button.element = panel
text:SetText(panel.name)
local isChild = panel.parent and FindCategory(panel.parent)
text:SetFontObject(isChild and GameFontHighlightSmall or GameFontNormal)
text:ClearAllPoints()
text:SetPoint("LEFT", button, "LEFT", isChild and 20 or 8, 0)
if toggle then
if HasChildren(panel) then
local tex = panel.collapsed and "Plus" or "Minus"
toggle:SetNormalTexture("Interface\\Buttons\\UI-" .. tex .. "Button-UP")
toggle:SetPushedTexture("Interface\\Buttons\\UI-" .. tex .. "Button-DOWN")
toggle:Show()
else
toggle:Hide()
end
end
if panel == container.displayedPanel then button:LockHighlight() else button:UnlockHighlight() end
button:Show()
else
button.element = nil
button:UnlockHighlight()
button:Hide()
-- A canvas callback that runs the panel's 3.3.5 one, looked up when it runs:
-- addons set okay / cancel / default / refresh before or after adding the
-- panel.
local function Forward(method)
return function(panel)
local fn = panel[method];
if type(fn) == "function" then
fn(panel);
end
end
FauxScrollFrame_Update(scroll, table.getn(entries), numButtons, BUTTON_HEIGHT)
end
addOnList.update = InterfaceAddOnsList_Update
scroll:SetScript("OnVerticalScroll", function()
FauxScrollFrame_OnVerticalScroll(BUTTON_HEIGHT, InterfaceAddOnsList_Update)
end)
-- The shown panel lives in container.displayedPanel, as on later clients:
-- addons read it there.
local function DisplayPanel(panel)
local shown = container.displayedPanel
if shown and shown ~= panel then shown:Hide() end
container.displayedPanel = panel
panel:SetParent(container)
panel:ClearAllPoints()
panel:SetPoint("TOPLEFT", container, "TOPLEFT", 4, -4)
panel:SetPoint("BOTTOMRIGHT", container, "BOTTOMRIGHT", -4, 4)
panel:Show()
if type(panel.refresh) == "function" then
local ok, err = pcall(panel.refresh, panel)
if not ok then report(err) end
end
InterfaceAddOnsList_Update()
end
function InterfaceOptionsListButton_OnClick(button)
if button and button.element then DisplayPanel(button.element) end
end
function InterfaceOptionsListButton_ToggleSubCategories(button)
local panel = button and button.element
if not panel then return end
panel.collapsed = not panel.collapsed
InterfaceAddOnsList_Update()
end
local OnCommit = Forward("okay");
local OnDefault = Forward("default");
local OnRefresh = Forward("refresh");
function InterfaceOptions_AddCategory(panel, addOn, position)
if type(panel) ~= "table" or type(panel.name) ~= "string" then
error("Usage: InterfaceOptions_AddCategory(panel [, addOn, position])", 2)
error("Usage: InterfaceOptions_AddCategory(panel [, addOn, position])", 2);
end
panel:Hide()
if panel.parent then
local parent = FindCategory(panel.parent)
if parent and parent.collapsed == nil then parent.collapsed = true end
end
if position and position >= 1 and position <= table.getn(categories) + 1 then
table.insert(categories, position, panel)
panel:Hide();
if panel.OnCommit == nil then panel.OnCommit = OnCommit; end
if panel.OnDefault == nil then panel.OnDefault = OnDefault; end
if panel.OnRefresh == nil then panel.OnRefresh = OnRefresh; end
local parent = panel.parent and FindCategory(panel.parent);
local category;
if parent then
category = Settings.RegisterCanvasLayoutSubcategory(parent, panel, panel.name);
else
table.insert(categories, panel)
category = Settings.RegisterCanvasLayoutCategory(panel, panel.name);
end
if panel.collapsed == nil and HasChildren(panel) then panel.collapsed = true end
if frame:IsShown() then InterfaceAddOnsList_Update() end
category.ID = panel.name;
Settings.RegisterAddOnCategory(category);
table.insert(panels, panel);
end
function InterfaceOptionsFrame_OpenToCategory(panel)
if type(panel) == "string" then panel = FindCategory(panel) end
if type(panel) ~= "table" then return end
local p = panel
while p and p.parent do
local parent = FindCategory(p.parent)
if parent then parent.collapsed = false end
p = parent
local category;
if type(panel) == "string" then
category = FindCategory(panel);
elseif type(panel) == "table" then
category = FindCategoryForFrame(SettingsPanel:GetAllCategories(), panel);
if not category and type(panel.name) == "string" then
category = FindCategory(panel.name);
end
end
if category then
Settings.OpenToCategory(category:GetID());
end
ShowUIPanel(frame)
DisplayPanel(panel)
end
function InterfaceOptionsFrame_Show()
if frame:IsShown() then HideUIPanel(frame) else ShowUIPanel(frame) end
if SettingsPanel:IsShown() then
SettingsPanel:Close();
else
SettingsPanel:Open();
end
end
frame:SetScript("OnShow", function()
if not container.displayedPanel and categories[1] then
DisplayPanel(categories[1])
else
InterfaceAddOnsList_Update()
end
end)
function InterfaceAddOnsList_Update()
categoryList:CreateCategories();
end
frame:SetScript("OnHide", function()
if this.lastFrame then
ShowUIPanel(this.lastFrame)
this.lastFrame = nil
end
end)
-- ---------------------------------------------------------------------------
-- Okay / Cancel / Defaults
-- ---------------------------------------------------------------------------
local function CallAll(method)
for _, panel in ipairs(categories) do
local fn = panel[method]
-- Closing without a commit gives each panel added here its cancel, before
-- the window hides, as the old window's Cancel did.
local ExitWithoutCommit = SettingsPanel.ExitWithoutCommit;
function SettingsPanel:ExitWithoutCommit()
for _, panel in ipairs(panels) do
local fn = panel.cancel;
if type(fn) == "function" then
local ok, err = pcall(fn, panel)
if not ok then report(err) end
local ok, err = pcall(fn, panel);
if not ok then CallErrorHandler(err); end
end
end
end
local function PanelButton(name, label, point, x)
local b = CreateFrame("Button", name, frame, "UIPanelButtonTemplate")
b:SetWidth(96)
b:SetHeight(22)
b:SetPoint(point, frame, point, x, 16)
b:SetText(label)
return b
end
PanelButton("InterfaceOptionsFrameCancel", CANCEL, "BOTTOMRIGHT", -16):SetScript("OnClick", function()
CallAll("cancel")
HideUIPanel(frame)
end)
PanelButton("InterfaceOptionsFrameOkay", OKAY, "BOTTOMRIGHT", -114):SetScript("OnClick", function()
CallAll("okay")
HideUIPanel(frame)
end)
PanelButton("InterfaceOptionsFrameDefaults", DEFAULTS, "BOTTOMLEFT", 22):SetScript("OnClick", function()
local panel = container.displayedPanel
if panel and type(panel.default) == "function" then
local ok, err = pcall(panel.default, panel)
if not ok then report(err) end
end
end)
-- Escape is Cancel, as on later clients: their ToggleGameMenu clicks
-- InterfaceOptionsFrameCancel right after dismissing a static popup.
-- Without this, Escape reaches CloseAllWindows, which closes the window
-- without calling any panel's cancel.
local ToggleGameMenu_Orig = ToggleGameMenu
function ToggleGameMenu(clicked)
if not clicked and frame:IsVisible() then
if not StaticPopup_EscapePressed() then InterfaceOptionsFrameCancel:Click() end
return
end
ToggleGameMenu_Orig(clicked)
ExitWithoutCommit(self);
end
-- ---------------------------------------------------------------------------
-- Game menu entry
-- The old window's names
-- ---------------------------------------------------------------------------
-- Goes right above Key Bindings. Stock anchors Key Bindings under Interface
-- Options and Turtle under its single Options button, so the new button takes
-- over whatever anchor Key Bindings has and Key Bindings moves under it.
--
-- The splice waits for the menu's first show. Other addons insert their own
-- buttons the same way -- ShaguTweaks anchors "Advanced Options" under
-- Interface Options and moves Key Bindings under it -- and they load after
-- us. Splicing at load time would claim the slot first, and the later addon
-- would anchor its button on the same spot as ours. By the first show every
-- addon has placed its buttons, so ours goes into the chain as it stands.
local menuButton = CreateFrame("Button", "GameMenuButtonAddOnOptions", GameMenuFrame, "GameMenuButtonTemplate")
menuButton:SetText(ADDON_OPTIONS)
local spliced
GameMenuFrame:HookScript("OnShow", function()
if spliced then return end
spliced = true
local point, relativeTo, relativePoint, x, y = GameMenuButtonKeybindings:GetPoint()
menuButton:SetPoint(point, relativeTo, relativePoint, x, y)
GameMenuButtonKeybindings:ClearAllPoints()
GameMenuButtonKeybindings:SetPoint(point, menuButton, relativePoint, x, y)
GameMenuFrame:SetHeight(GameMenuFrame:GetUnscaledHeight() + menuButton:GetUnscaledHeight() - y)
end)
menuButton:SetScript("OnClick", function()
PlaySound("igMainMenuOption")
ShowUIPanel(frame)
frame.lastFrame = GameMenuFrame
end)
InterfaceOptionsFrame = SettingsPanel;
InterfaceOptionsFrameAddOns = categoryList;
InterfaceOptionsFrameCategories = categoryList;
InterfaceOptionsFrameAddOnsList = categoryList.ScrollBox;
InterfaceOptionsFrameAddOnsListScrollBar = categoryList.ScrollBar;
InterfaceOptionsFramePanelContainer = canvas;
InterfaceOptionsFrameOkay = SettingsPanel.CloseButton;
categoryList.buttons = {};
categoryList.buttonHeight = 20;
categoryList.update = InterfaceAddOnsList_Update;
hooksecurefunc(SettingsPanel, "DisplayLayout", function(self, layout)
if layout and layout:GetLayoutType() == SettingsLayoutMixin.LayoutType.Canvas then
canvas.displayedPanel = layout:GetFrame();
else
canvas.displayedPanel = nil;
end
end);
local cancel = CreateFrame("Button", "InterfaceOptionsFrameCancel", SettingsPanel, "UIPanelButtonTemplate");
cancel:SetText(CANCEL);
cancel:Hide();
cancel:SetScript("OnClick", function()
SettingsPanel:ExitWithoutCommit();
end);
local defaults = CreateFrame("Button", "InterfaceOptionsFrameDefaults", SettingsPanel, "UIPanelButtonTemplate");
defaults:SetText(SETTINGS_DEFAULTS);
defaults:Hide();
defaults:SetScript("OnClick", function()
SettingsPanel:SetCurrentCategorySettingsToDefaults();
end);
@@ -1,63 +0,0 @@
<Ui xmlns="http://www.blizzard.com/wow/ui/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.blizzard.com/wow/ui/ ..\FrameXML\UI.xsd">
<!-- One row of the Interface Options category list (see InterfaceOptions.lua).
Named as on later clients: addons and libraries create extra rows from it
by name (LibBetterBlizzOptions-1.0). Handlers use vanilla's this/arg1. -->
<Button name="InterfaceOptionsListButtonTemplate" virtual="true">
<Size>
<AbsDimension x="175" y="18"/>
</Size>
<Layers>
<Layer level="OVERLAY">
<FontString name="$parentText" inherits="GameFontNormal" justifyH="LEFT">
<Size>
<AbsDimension x="150" y="18"/>
</Size>
<Anchors>
<Anchor point="LEFT">
<Offset>
<AbsDimension x="8" y="0"/>
</Offset>
</Anchor>
</Anchors>
</FontString>
</Layer>
</Layers>
<Frames>
<Button name="$parentToggle" hidden="true">
<Size>
<AbsDimension x="14" y="14"/>
</Size>
<Anchors>
<Anchor point="RIGHT">
<Offset>
<AbsDimension x="-6" y="0"/>
</Offset>
</Anchor>
</Anchors>
<Scripts>
<OnClick>InterfaceOptionsListButton_ToggleSubCategories(this:GetParent())</OnClick>
</Scripts>
<NormalTexture file="Interface\Buttons\UI-PlusButton-UP"/>
<PushedTexture file="Interface\Buttons\UI-PlusButton-DOWN"/>
<HighlightTexture file="Interface\Buttons\UI-PlusButton-Hilight" alphaMode="ADD"/>
</Button>
</Frames>
<Scripts>
<OnClick>InterfaceOptionsListButton_OnClick(this)</OnClick>
</Scripts>
<HighlightTexture file="Interface\QuestFrame\UI-QuestTitleHighlight" alphaMode="ADD">
<Anchors>
<Anchor point="TOPLEFT">
<Offset>
<AbsDimension x="0" y="1"/>
</Offset>
</Anchor>
<Anchor point="BOTTOMRIGHT">
<Offset>
<AbsDimension x="0" y="1"/>
</Offset>
</Anchor>
</Anchors>
</HighlightTexture>
</Button>
</Ui>
@@ -0,0 +1,249 @@
-- Backport of retail's Blizzard_SharedXML/Shared/Slider/MinimalSlider.lua.
--
-- Differences from the retail source:
-- - The bar is 1.12's OptionsSliderTemplate backdrop (see MinimalSlider.xml),
-- set here because the template has no atlas pieces.
-- - No SetObeyStepOnDrag: this client's slider always rounds its value to
-- the step.
-- - Thumb is the slider's thumb texture, read here: retail's template names
-- it with a parentKey.
-- - No narration: this client has none.
-- - SetValue does not report the value it sets. 1.12's slider rounds every
-- value to the step in single-precision floats, and the rounding does
-- not settle: a value that comes back through a setting rounds a hair
-- away again and fires OnValueChanged again, so the Settings slider and
-- its setting called each other until the stack ran out. When the value
-- the slider lands on is within rounding of the one asked for,
-- OnValueChanged updates the labels and steppers but does not trigger
-- the OnValueChanged event; the caller already has the value.
local STEPPER_DISABLED_ALPHA = 0.5;
local SLIDER_BACKDROP = {
bgFile = "Interface\\Buttons\\UI-SliderBar-Background",
edgeFile = "Interface\\Buttons\\UI-SliderBar-Border",
tile = true,
tileSize = 8,
edgeSize = 8,
insets = { left = 3, right = 3, top = 6, bottom = 6 },
};
MinimalSliderMixin = {};
function MinimalSliderMixin:OnLoad()
self:SetBackdrop(SLIDER_BACKDROP);
self.Thumb = self:GetThumbTexture();
end
function MinimalSliderMixin:Release()
self:SetScript("OnValueChanged", nil);
end
local function NoModification(value)
return value;
end
function CreateMinimalSliderFormatter(labelType, value)
local formatter = nil;
if value == nil then
formatter = NoModification;
elseif type(value) == "function" then
formatter = value;
else
-- Ignores the control value and returns the function argument instead.
formatter = function(v)
return value;
end;
end
return formatter;
end
MinimalSliderWithSteppersMixin = CreateFromMixins(CallbackRegistryMixin);
MinimalSliderWithSteppersMixin:GenerateCallbackEvents(
{
"OnValueChanged",
"OnInteractStart",
"OnInteractEnd",
}
);
MinimalSliderWithSteppersMixin.Label = EnumUtil.MakeEnum("Left", "Right", "Top", "Min", "Max");
local interactionFlags = {
Hover = 1,
Click = 2,
};
function MinimalSliderWithSteppersMixin:OnLoad()
CallbackRegistryMixin.OnLoad(self);
self.InteractionFlags = CreateFromMixins(FlagsMixin);
self.InteractionFlags:OnLoad();
local forward = false;
self.Back:SetScript("OnClick", GenerateClosure(self.OnStepperClicked, self, forward));
local backward = true;
self.Forward:SetScript("OnClick", GenerateClosure(self.OnStepperClicked, self, backward));
local function OnMouseDown(slider)
if slider:IsEnabled() then
self:SetInteractionFlag(interactionFlags.Click);
PlaySound(SOUNDKIT.IG_MAINMENU_OPTION_CHECKBOX_ON);
end
end
self.Slider:SetScript("OnMouseDown", OnMouseDown);
local function OnMouseUp(slider)
if slider:IsEnabled() then
self:ClearInteractionFlag(interactionFlags.Click);
end
end
self.Slider:SetScript("OnMouseUp", OnMouseUp);
local function OnEnter(slider)
if slider:IsEnabled() then
self:SetInteractionFlag(interactionFlags.Hover);
end
end
self.Slider:SetScript("OnEnter", OnEnter);
local function OnLeave(slider)
if slider:IsEnabled() then
self:ClearInteractionFlag(interactionFlags.Hover);
end
end
self.Slider:SetScript("OnLeave", OnLeave);
end
function MinimalSliderWithSteppersMixin:OnStepperClicked(forward)
local value = self.Slider:GetValue();
local step = self.Slider:GetValueStep();
if forward then
self.Slider:SetValue(value + step);
else
self.Slider:SetValue(value - step);
end
PlaySound(SOUNDKIT.IG_MAINMENU_OPTION_CHECKBOX_ON);
end
local function SetStepperButtonEnabled(button, enabled)
button:SetEnabled(enabled);
button:SetAlpha(enabled and 1.0 or STEPPER_DISABLED_ALPHA);
button:DesaturateHierarchy(enabled and 0 or 1);
end
function MinimalSliderWithSteppersMixin:UpdateStepperStates()
if not self:IsSliderEnabled() then
return;
end
local value = self.Slider:GetValue();
local minValue, maxValue = self.Slider:GetMinMaxValues();
local step = self.Slider:GetValueStep();
local atMin = value <= minValue + (step * 0.5);
local atMax = value >= maxValue - (step * 0.5);
SetStepperButtonEnabled(self.Back, not atMin);
SetStepperButtonEnabled(self.Forward, not atMax);
end
function MinimalSliderWithSteppersMixin:Init(value, minValue, maxValue, steps, formatters)
self.Slider:SetMinMaxValues(minValue, maxValue);
self.Slider:SetValueStep((maxValue - minValue) / steps);
self.Slider:SetValue(value);
self.formatters = formatters;
self:FormatValue(value);
self:UpdateStepperStates();
local function OnValueChanged(slider, value)
self:FormatValue(value);
self:UpdateStepperStates();
local requested = self.requestedValue;
if requested and math.abs(value - requested) <= slider:GetValueStep() * 0.001 then
return;
end
self:TriggerEvent(MinimalSliderWithSteppersMixin.Event.OnValueChanged, value);
end
self.Slider:SetScript("OnValueChanged", OnValueChanged);
end
function MinimalSliderWithSteppersMixin:SetInteractionFlag(flag)
local wasAnySet = self.InteractionFlags:IsAnySet();
self.InteractionFlags:Set(flag);
if not wasAnySet then
self:TriggerEvent(MinimalSliderWithSteppersMixin.Event.OnInteractStart);
end
end
function MinimalSliderWithSteppersMixin:ClearInteractionFlag(flag)
local wasAnySet = self.InteractionFlags:IsAnySet();
self.InteractionFlags:Clear(flag);
if wasAnySet and not self.InteractionFlags:IsAnySet() then
self:TriggerEvent(MinimalSliderWithSteppersMixin.Event.OnInteractEnd);
end
end
function MinimalSliderWithSteppersMixin:FormatValue(value)
if not self.formatters then
return;
end
for labelID, formatter in pairs(self.formatters) do
local label = self.Labels[labelID];
if label then
label:SetText(formatter(value));
label:Show();
end
end
end
local function ConfigureSlider(self, color, alpha)
self.Slider.Thumb:SetAlpha(alpha);
local r, g, b = color:GetRGB();
self.LeftText:SetVertexColor(r, g, b);
self.RightText:SetVertexColor(r, g, b);
self.TopText:SetVertexColor(r, g, b);
self.MinText:SetVertexColor(r, g, b);
self.MaxText:SetVertexColor(r, g, b);
end
function MinimalSliderWithSteppersMixin:SetEnabled(enabled)
self.sliderEnabled = enabled;
if enabled then
ConfigureSlider(self, NORMAL_FONT_COLOR, 1.0);
else
ConfigureSlider(self, GRAY_FONT_COLOR, .7);
end
self.Slider:SetEnabled(enabled);
if enabled then
self:UpdateStepperStates();
else
SetStepperButtonEnabled(self.Back, false);
SetStepperButtonEnabled(self.Forward, false);
end
end
function MinimalSliderWithSteppersMixin:SetValue(value)
self.requestedValue = value;
self.Slider:SetValue(value);
self.requestedValue = nil;
end
function MinimalSliderWithSteppersMixin:IsSliderEnabled()
return self.sliderEnabled ~= false;
end
function MinimalSliderWithSteppersMixin:Release()
self.Slider:Release();
for index, label in ipairs(self.Labels) do
label:Hide();
end
end
@@ -0,0 +1,90 @@
<Ui xmlns="http://www.blizzard.com/wow/ui/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.blizzard.com/wow/ui/ ..\FrameXML\UI.xsd">
<!--
Retail's Blizzard_SharedXML/Shared/Slider/MinimalSlider.xml.
Differences:
- The Minimal_SliderBar atlases are art this client does not have. The bar
is 1.12's OptionsSliderTemplate: its backdrop (set in
MinimalSliderMixin:OnLoad) and its thumb. The steppers are the
spellbook's page arrows.
- No obeyStepOnDrag key: this client's slider always rounds its value to
the step, so it obeys the step on a drag already.
- No NarrationSliderMixin: this client has no narration.
-->
<Slider name="MinimalSliderTemplate" orientation="HORIZONTAL" mixin="MinimalSliderMixin" enableMouse="true" virtual="true">
<Size x="200" y="17"/>
<HitRectInsets>
<AbsInset left="0" right="0" top="-10" bottom="-10"/>
</HitRectInsets>
<ThumbTexture file="Interface\Buttons\UI-SliderBar-Button-Horizontal">
<Size x="32" y="32"/>
</ThumbTexture>
<Scripts>
<OnLoad method="OnLoad"/>
</Scripts>
</Slider>
<Button name="MinimalSliderStepperTemplate" virtual="true">
<Size x="20" y="20"/>
<HighlightTexture file="Interface\Buttons\UI-Common-MouseHilight" alphaMode="ADD"/>
</Button>
<Frame name="MinimalSliderWithSteppersTemplate" mixin="MinimalSliderWithSteppersMixin" enableMouse="true" virtual="true">
<Size x="250" y="40"/>
<Frames>
<Slider parentKey="Slider" inherits="MinimalSliderTemplate">
<Anchors>
<Anchor point="LEFT" x="22"/>
<Anchor point="RIGHT" x="-22"/>
</Anchors>
</Slider>
<Button parentKey="Back" inherits="MinimalSliderStepperTemplate">
<Anchors>
<Anchor point="RIGHT" relativeKey="$parent.Slider" relativePoint="LEFT" x="-2"/>
</Anchors>
<NormalTexture file="Interface\Buttons\UI-SpellbookIcon-PrevPage-Up"/>
<PushedTexture file="Interface\Buttons\UI-SpellbookIcon-PrevPage-Down"/>
<DisabledTexture file="Interface\Buttons\UI-SpellbookIcon-PrevPage-Disabled"/>
</Button>
<Button parentKey="Forward" inherits="MinimalSliderStepperTemplate">
<Anchors>
<Anchor point="LEFT" relativeKey="$parent.Slider" relativePoint="RIGHT" x="2"/>
</Anchors>
<NormalTexture file="Interface\Buttons\UI-SpellbookIcon-NextPage-Up"/>
<PushedTexture file="Interface\Buttons\UI-SpellbookIcon-NextPage-Down"/>
<DisabledTexture file="Interface\Buttons\UI-SpellbookIcon-NextPage-Disabled"/>
</Button>
</Frames>
<Layers>
<Layer level="OVERLAY">
<FontString parentKey="LeftText" inherits="GameFontNormal" parentArray="Labels" hidden="true">
<Anchors>
<Anchor point="RIGHT" relativeKey="$parent.Slider" relativePoint="LEFT" x="-25"/>
</Anchors>
</FontString>
<FontString parentKey="RightText" inherits="GameFontNormal" parentArray="Labels" hidden="true">
<Anchors>
<Anchor point="LEFT" relativeKey="$parent.Slider" relativePoint="RIGHT" x="25"/>
</Anchors>
</FontString>
<FontString parentKey="TopText" inherits="GameFontNormal" parentArray="Labels" hidden="true">
<Anchors>
<Anchor point="BOTTOM" relativeKey="$parent.Slider" relativePoint="TOP" y="-9"/>
</Anchors>
</FontString>
<FontString parentKey="MinText" inherits="GameFontNormal" parentArray="Labels" hidden="true">
<Anchors>
<Anchor point="TOP" relativeKey="$parent.Slider" relativePoint="BOTTOMLEFT" y="6"/>
</Anchors>
</FontString>
<FontString parentKey="MaxText" inherits="GameFontNormal" parentArray="Labels" hidden="true">
<Anchors>
<Anchor point="TOP" relativeKey="$parent.Slider" relativePoint="BOTTOMRIGHT" y="6"/>
</Anchors>
</FontString>
</Layer>
</Layers>
<Scripts>
<OnLoad method="OnLoad"/>
</Scripts>
</Frame>
</Ui>
@@ -0,0 +1,75 @@
-- Backport of retail's Blizzard_SharedXML/Shared/Tabs/MinimalTab.lua.
--
-- The one difference: retail sets the three pieces from Options_Tab
-- atlases, which this client does not have. The tab is the tooltip backdrop
-- the Settings window frames its lists with, and UpdateAtlas colors it by
-- state: the selected tab is lighter with a gold edge, a hovered tab a little
-- lighter than the others.
local TAB_BACKDROP =
{
bgFile = "Interface\\Tooltips\\UI-Tooltip-Background",
edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
tile = true, tileSize = 16, edgeSize = 16,
insets = { left = 5, right = 5, top = 5, bottom = 5 },
};
MinimalTabMixin = {};
function MinimalTabMixin:OnLoad()
SelectableButtonMixin.OnLoad(self);
self:SetBackdrop(TAB_BACKDROP);
self.Text:SetText(self.tabText);
self:SetWidth(self.Text:GetStringWidth() + 40);
self:OnSelected(false);
end
function MinimalTabMixin:UpdateAtlas()
if self:IsSelected() then
self:SetBackdropColor(0.25, 0.25, 0.25, 0.9);
self:SetBackdropBorderColor(1, 0.82, 0);
elseif self.over then
self:SetBackdropColor(0.15, 0.15, 0.15, 0.8);
self:SetBackdropBorderColor(0.8, 0.8, 0.8);
else
self:SetBackdropColor(0, 0, 0, 0.5);
self:SetBackdropBorderColor(0.6, 0.6, 0.6);
end
end
function MinimalTabMixin:OnSelected(newSelected)
self:UpdateAtlas();
self.Text:SetPoint("CENTER", 0, 0);
if newSelected then
self.Text:SetFontObject("GameFontHighlightSmall");
else
self.Text:SetFontObject(self.over and "GameFontHighlightSmall" or "GameFontNormalSmall");
end
end
function MinimalTabMixin:OnEnter()
self.over = true;
self:UpdateAtlas();
if not self:IsSelected() then
self.Text:SetFontObject("GameFontHighlightSmall");
end
end
function MinimalTabMixin:OnLeave()
self.over = nil;
self:UpdateAtlas();
if not self:IsSelected() then
self.Text:SetFontObject("GameFontNormalSmall");
end
end
function MinimalTabMixin:OnEnable()
self:UpdateAtlas();
end
function MinimalTabMixin:OnDisable()
self:UpdateAtlas();
end
@@ -0,0 +1,29 @@
<Ui xmlns="http://www.blizzard.com/wow/ui/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.blizzard.com/wow/ui/ ..\FrameXML\UI.xsd">
<!--
Retail's Blizzard_SharedXML/Shared/Tabs/MinimalTab.xml. Retail draws the
tab with the Options_Tab atlases, which this client does not have. The tab
is drawn as the frames of the Settings window are: the tooltip backdrop,
set in MinimalTab.lua. The Left, Middle and Right textures keep retail's
keys and stay empty.
-->
<Button name="MinimalTabTemplate" inherits="SelectableButtonTemplate" mixin="MinimalTabMixin" virtual="true">
<Size x="100" y="37"/>
<Layers>
<Layer>
<Texture parentKey="Left"/>
<Texture parentKey="Right"/>
<Texture parentKey="Middle"/>
</Layer>
<Layer>
<FontString parentKey="Text" inherits="GameFontNormal"/>
</Layer>
</Layers>
<Scripts>
<OnLoad method="OnLoad"/>
<OnEnter method="OnEnter"/>
<OnLeave method="OnLeave"/>
<OnEnable method="OnEnable"/>
<OnDisable method="OnDisable"/>
</Scripts>
</Button>
</Ui>
@@ -0,0 +1,52 @@
-- Verbatim backport of retail's Blizzard_SharedXML/SelectableButton.lua.
SelectableButtonMixin = {};
function SelectableButtonMixin:OnLoad()
self.selected = false;
end
function SelectableButtonMixin:Reset()
self.CanChangeSelectionOverride = nil;
self.selected = false;
end
function SelectableButtonMixin:OnClick()
return self:SetSelected(not self:IsSelected());
end
function SelectableButtonMixin:CanChangeSelection(newSelected)
if self:IsSelected() == newSelected then
return false;
end
if self.SelectionChangeInterrupt then
return self.SelectionChangeInterrupt(self, newSelected);
end
return true;
end
function SelectableButtonMixin:SetSelectionChangeInterrupt(callback)
self.SelectionChangeInterrupt = callback;
end
function SelectableButtonMixin:IsSelected()
return not not self.selected;
end
function SelectableButtonMixin:SetSelected(newSelected)
if self:CanChangeSelection(newSelected) then
self:SetSelectedState(newSelected);
self:OnSelected(newSelected);
end
end
function SelectableButtonMixin:OnSelected(newSelected)
-- Derive
end
function SelectableButtonMixin:SetSelectedState(newSelected)
-- Derive
self.selected = newSelected;
end
@@ -0,0 +1,9 @@
<Ui xmlns="http://www.blizzard.com/wow/ui/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.blizzard.com/wow/ui/ ..\FrameXML\UI.xsd">
<!-- Verbatim backport of retail's Blizzard_SharedXML/SelectableButton.xml. -->
<Button name="SelectableButtonTemplate" mixin="SelectableButtonMixin" virtual="true">
<Scripts>
<OnLoad method="OnLoad"/>
<OnClick method="OnClick"/>
</Scripts>
</Button>
</Ui>
@@ -11,6 +11,10 @@
-- - 1.12 FrameXML owns UIPanelCloseButton (its own OnClick), so
-- UIPanelCloseButtonDefaultAnchors inherits UIPanelCloseButtonNoScripts
-- and runs UIPanelCloseButton_OnClick itself.
-- - DropdownWithSteppersMixin has no gamepad cursor anchors: this client
-- has no gamepad navigation.
-- - 1.12's Button:IsEnabled returns 1 or 0, and 0 is true in Lua, so
-- DropdownWithSteppersMixin compares the dropdown's with 1.
function TruncatedTooltipScript_OnEnter(self)
local text = self.truncatedTooltipScriptText or self.Text;
@@ -305,3 +309,88 @@ end
function PanelResizeButtonMixin:SetOnResizeCallback(resizeCallback)
self.resizeCallback = resizeCallback;
end
DropdownWithSteppersMixin = {};
function DropdownWithSteppersMixin:OnLoad()
self.IncrementButton:SetPoint("LEFT", self.Dropdown, "RIGHT", (self.incrementOffsetX or 4), 0);
self.IncrementButton:SetScript("OnClick", GenerateClosure(self.OnIncrementClicked, self));
self.DecrementButton:SetPoint("RIGHT", self.Dropdown, "LEFT", (self.decrementOffsetX or -5), 0);
self.DecrementButton:SetScript("OnClick", GenerateClosure(self.OnDecrementClicked, self));
local function OnUpdate(o, previousRadio, nextRadio, selections)
local canDecrement = previousRadio ~= nil;
local canIncrement = nextRadio ~= nil;
self:SetSteppersEnabled(canDecrement, canIncrement);
end
self.Dropdown:RegisterCallback(DropdownButtonMixin.Event.OnUpdate, OnUpdate);
end
function DropdownWithSteppersMixin:SetEnabled(enabled)
self.Dropdown:SetEnabled(enabled);
self:UpdateSteppers();
end
function DropdownWithSteppersMixin:OnIncrementClicked(button, buttonName, down)
self:Increment();
PlaySound(SOUNDKIT.IG_MAINMENU_OPTION_CHECKBOX_ON);
end
function DropdownWithSteppersMixin:OnDecrementClicked(button, buttonName, down)
self:Decrement();
PlaySound(SOUNDKIT.IG_MAINMENU_OPTION_CHECKBOX_ON);
end
function DropdownWithSteppersMixin:Increment()
self.Dropdown:Increment();
end
function DropdownWithSteppersMixin:Decrement()
self.Dropdown:Decrement();
end
function DropdownWithSteppersMixin:HideSteppers()
self.DecrementButton:Hide();
self.IncrementButton:Hide();
end
function DropdownWithSteppersMixin:ShowSteppers()
self.DecrementButton:Show();
self.IncrementButton:Show();
end
function DropdownWithSteppersMixin:SetSteppersShown(shown)
self.DecrementButton:SetShown(shown);
self.IncrementButton:SetShown(shown);
end
function DropdownWithSteppersMixin:SetSteppersEnabled(canDecrement, canIncrement)
if self.Dropdown:IsEnabled() == 1 then
self.DecrementButton:SetEnabled(canDecrement);
self.IncrementButton:SetEnabled(canIncrement);
else
self.DecrementButton:SetEnabled(false);
self.IncrementButton:SetEnabled(false);
end
end
function DropdownWithSteppersMixin:UpdateSteppers()
if self.Dropdown:IsEnabled() == 1 then
local previousRadio, nextRadio, selections = self.Dropdown:CollectSelectionData();
local canDecrement = previousRadio ~= nil;
local canIncrement = nextRadio ~= nil;
self:SetSteppersEnabled(canDecrement, canIncrement);
else
self:SetSteppersEnabled(false, false);
end
end
DropdownWithSteppersAndLabelMixin = CreateFromMixins(DropdownWithSteppersMixin);
function DropdownWithSteppersAndLabelMixin:SetText(text)
self.Label:SetText(text);
end
@@ -13,6 +13,13 @@
- The resize grip is the chat frame's expand arrow, turned to point at
the corner.
- No FrameGlow, gamepad jump hints, TopTileStreaks or button bar.
- DarkMenuElementTemplate's hover is 1.12's dropdown highlight
(UI-QuestTitleHighlight), stretched over the row: the
common-dropdown-customize-mouseover atlas is art this client does not
have.
- The dropdown steppers are the spellbook's page arrows. Retail's
SteppersIncrementButtonTemplate and SteppersDecrementButtonTemplate
are atlases.
-->
<Script file="PortraitFrame.lua"/>
<Script file="SharedUIPanelTemplates.lua"/>
@@ -184,4 +191,63 @@
<NormalTexture file="Interface\ChatFrame\ChatFrameExpandArrow" rotation="-45"/>
<HighlightTexture file="Interface\ChatFrame\ChatFrameExpandArrow" rotation="-45" alphaMode="ADD"/>
</Button>
<Button name="DarkMenuElementTemplate" inherits="ResizeLayoutFrame" virtual="true">
<Size x="1" y="20"/>
<KeyValues>
<KeyValue key="widthPadding" value="14" type="number"/>
</KeyValues>
<Frames>
<Frame parentKey="HighlightBGTex" alpha="0" setAllPoints="true">
<KeyValues>
<KeyValue key="ignoreInLayout" value="true" type="boolean"/>
</KeyValues>
<Layers>
<Layer level="BACKGROUND">
<Texture file="Interface\QuestFrame\UI-QuestTitleHighlight" alphaMode="ADD" setAllPoints="true"/>
</Layer>
</Layers>
</Frame>
</Frames>
</Button>
<Button name="SteppersIncrementButtonTemplate" motionScriptsWhileDisabled="true" virtual="true">
<Size x="24" y="24"/>
<NormalTexture file="Interface\Buttons\UI-SpellbookIcon-NextPage-Up"/>
<PushedTexture file="Interface\Buttons\UI-SpellbookIcon-NextPage-Down"/>
<DisabledTexture file="Interface\Buttons\UI-SpellbookIcon-NextPage-Disabled"/>
<HighlightTexture file="Interface\Buttons\UI-Common-MouseHilight" alphaMode="ADD"/>
</Button>
<Button name="SteppersDecrementButtonTemplate" motionScriptsWhileDisabled="true" virtual="true">
<Size x="24" y="24"/>
<NormalTexture file="Interface\Buttons\UI-SpellbookIcon-PrevPage-Up"/>
<PushedTexture file="Interface\Buttons\UI-SpellbookIcon-PrevPage-Down"/>
<DisabledTexture file="Interface\Buttons\UI-SpellbookIcon-PrevPage-Disabled"/>
<HighlightTexture file="Interface\Buttons\UI-Common-MouseHilight" alphaMode="ADD"/>
</Button>
<Frame name="DropdownWithSteppersTemplate" mixin="DropdownWithSteppersMixin" virtual="true">
<Size x="223" y="38"/>
<Frames>
<Button parentKey="IncrementButton" inherits="SteppersIncrementButtonTemplate"/>
<Button parentKey="DecrementButton" inherits="SteppersDecrementButtonTemplate"/>
</Frames>
<Scripts>
<OnLoad method="OnLoad"/>
</Scripts>
</Frame>
<!-- See DropdownWithSteppersTemplate for dropdown requirements. -->
<Frame name="DropdownWithSteppersAndLabelTemplate" inherits="DropdownWithSteppersTemplate" mixin="DropdownWithSteppersAndLabelMixin" virtual="true">
<Layers>
<Layer level="ARTWORK">
<FontString parentKey="Label" inherits="GameFontHighlightMedium">
<Anchors>
<Anchor point="RIGHT" relativeKey="$parent.DecrementButton" relativePoint="LEFT" x="-34"/>
</Anchors>
</FontString>
</Layer>
</Layers>
</Frame>
</Ui>
@@ -3,6 +3,8 @@
-- Implementation differences from the retail source:
-- - Lua 5.0 has no `...` as an expression; the proxy mixin forwards its
-- varargs through unpack(arg).
-- - 1.12's Button:IsEnabled returns 1 or 0, and 0 is true in Lua, so the
-- open and mouse wheel gates compare it with 1.
local function AssertIntrinsicMessage(frame)
return string.format("%s element is not a DropdownButton.", frame:GetDebugName());
@@ -112,7 +114,7 @@ function DropdownButtonMixin:OnMouseDown_Intrinsic()
end
function DropdownButtonMixin:OpenMenu()
if not self:IsEnabled() then
if self:IsEnabled() ~= 1 then
return;
end
@@ -159,7 +161,7 @@ function DropdownButtonMixin:OnMouseWheel_Intrinsic(delta)
return;
end
if not self:IsEnabled() then
if self:IsEnabled() ~= 1 then
return;
end
@@ -370,6 +372,20 @@ function DropdownButtonMixin:HasAnyRadioDescriptions()
end);
end
function DropdownButtonMixin:HasOnlyRadioDescriptions()
local foundRadio = false;
local foundCheckbox = MenuUtil.TraverseMenu(self:GetMenuDescription(), function(description)
if description:IsCheckbox() then
return true;
elseif description:IsRadio() then
foundRadio = true;
end
return false;
end);
return foundRadio and (not foundCheckbox);
end
function DropdownButtonMixin:Increment()
local previousRadio, nextRadio, selections = CollectSelectionData(self:GetMenuDescription());
self:Pick(nextRadio, MenuInputContext.MouseWheel);
+13 -1
View File
@@ -702,6 +702,14 @@ do
return self.isRadio;
end
function MenuElementDescriptionProxyMixin:SetCheckbox(isCheckbox)
self.isCheckbox = isCheckbox;
end
function MenuElementDescriptionProxyMixin:IsCheckbox()
return self.isCheckbox;
end
function MenuElementDescriptionProxyMixin:SetIsSelected(isSelected)
self.isSelected = isSelected;
end
@@ -873,6 +881,10 @@ do
self.responder = callback;
end
function MenuElementDescriptionProxyMixin:HasResponder()
return self.responder ~= nil;
end
function MenuElementDescriptionProxyMixin:HookResponder(callback)
if self.responder then
hooksecurefunc(self, "responder", callback);
@@ -927,7 +939,7 @@ do
never cause the menu to close.
]]--
local response = nil;
local willRespond = self.responder ~= nil;
local willRespond = self:HasResponder();
if willRespond then
-- Use the default response if it exists. This is supplied by checkbox and radio descriptions.
local descriptionResponse = securecallfunction(SecureGetDefaultResponse, self, menuInputContext, menuInputButtonName);
@@ -7,6 +7,8 @@
-- so the auto-hide button turns it on itself.
-- - Lua 5.0 has no `...` as an expression and no `#` operator; varargs
-- go through the implicit `arg` table and lengths come from table.getn.
-- - No narration: this client has none, so the highlight buttons get no
-- narration functions.
local SetPropagateMouseMotion = function(frame, propagate)
frame:SetPropagateMouseMotion(propagate);
@@ -288,6 +290,7 @@ function MenuTemplates.CreateCheckbox(text, isSelected, onSelect, data)
local elementDescription = CreateButtonDescription(data);
elementDescription:SetSoundKit(GetCheckboxSoundKit);
elementDescription:AddInitializer(Initializer);
elementDescription:SetCheckbox(true);
elementDescription:SetIsSelected(isSelected);
elementDescription:SetResponder(onSelect);
elementDescription:SetResponse(MenuResponse.Refresh);
@@ -308,8 +311,90 @@ function MenuTemplates.CreateRadio(text, isSelected, onSelect, data)
return elementDescription;
end
-- Attach text here instead of the template for content sizing calculations fixes if other pieces get attached elsewhere.
local function CreateHighlightButtonText(button)
local fontString = button:AttachFontString();
fontString:SetPoint("TOPLEFT", 14, 0);
fontString:SetSize(200, 20);
fontString:SetFontObject("GameFontNormal");
fontString:SetJustifyH("LEFT");
fontString:SetMaxLines(1);
button.Text = fontString;
end
local function SetHighlightButtonFinalInitializer(button, _description, menu)
button.owningMenu = menu;
end
function MenuTemplates.CreateHighlightButton(text, onSelect, data, onEnter)
local optionDescription = CreateMenuElementDescription("WowMenuDropdownHighlightButtonTemplate");
local truncated = false;
local function OnEnter(button)
button.HighlightBGTex:SetAlpha(0.15);
if truncated then
local description = button:GetElementDescription();
MenuUtil.ShowTooltipEx(button, description:GetTooltipFrame(), function(tooltip)
GameTooltip_SetTitle(tooltip, text);
end);
end
if onEnter then
onEnter(data);
end
end
local function OnLeave(button)
button.HighlightBGTex:SetAlpha(0);
local description = button:GetElementDescription();
MenuUtil.HideTooltipEx(button, description:GetTooltipFrame());
end
optionDescription:AddInitializer(function(button, description, _menu)
button:SetScript("OnClick", function(_button, buttonName)
description:Pick(MenuInputContext.MouseButton, buttonName);
end);
if optionDescription:CanOpenSubmenu() then
MenuVariants.CreateSubmenuArrow(button);
end
CreateHighlightButtonText(button);
-- This button template is modified in Languages.lua to hide the text and display
-- a texture for each locale, so we need to redisplay the text. We don't have to worry
-- about that texture here because it is managed by the compositor.
button.Text:Show();
button.Text:SetTextToFit(text);
button.Text:SetWidth(button.Text:GetWidth() + 15);
button.HighlightBGTex:SetAlpha(0);
if description:IsEnabled() then
button.Text:SetTextColor(VERY_LIGHT_GRAY_COLOR:GetRGB());
else
button.Text:SetTextColor(DISABLED_FONT_COLOR:GetRGB());
end
truncated = button.Text:IsTruncated();
button:Layout();
end);
optionDescription:SetFinalInitializer(SetHighlightButtonFinalInitializer);
optionDescription:SetResponder(onSelect);
optionDescription:SetOnEnter(OnEnter);
optionDescription:SetOnLeave(OnLeave);
optionDescription:SetData(data);
return optionDescription;
end
function MenuTemplates.CreateHighlightRadio(text, isSelected, onSelect, data, onEnter)
local optionDescription = CreateMenuElementDescription("WowMenuDropdownHighlightRadioTemplate");
local optionDescription = CreateMenuElementDescription("WowMenuDropdownHighlightButtonTemplate");
local truncated = false;
@@ -348,16 +433,18 @@ function MenuTemplates.CreateHighlightRadio(text, isSelected, onSelect, data, on
description:Pick(MenuInputContext.MouseButton, buttonName);
end);
CreateHighlightButtonText(button);
-- This button template is modified in Languages.lua to hide the text and display
-- a texture for each locale, so we need to redisplay the text. We don't have to worry
-- about that texture here because it is managed by the compositor.
button.Text:Show();
button.Text:SetTextToFit(text);
button.Text:SetWidth(button.Text:GetUnscaledWidth() + 10);
-- Give enough room should any icon be added to the far right the spacing is fine between them.
button.Text:SetWidth(button.Text:GetWidth() + 45);
button.HighlightBGTex:SetAlpha(0);
local fontColor = nil;
if description:IsSelected() then
button.Text:SetTextColor(NORMAL_FONT_COLOR:GetRGBA());
elseif description:IsEnabled() then
@@ -371,6 +458,7 @@ function MenuTemplates.CreateHighlightRadio(text, isSelected, onSelect, data, on
button:Layout();
end);
optionDescription:SetFinalInitializer(SetHighlightButtonFinalInitializer);
optionDescription:SetIsSelected(isSelected);
optionDescription:SetResponder(onSelect);
optionDescription:SetOnEnter(OnEnter);
@@ -1,8 +1,9 @@
<Ui xmlns="http://www.blizzard.com/wow/ui/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.blizzard.com/wow/ui/
..\FrameXML\UI.xsd">
<!-- From retail's Blizzard_Menu/MenuTemplates.xml. WowStyle2DropdownTemplate,
WowStyle2IconButtonTemplate and WowMenuDropdownHighlightRadioTemplate are not
here yet: they draw Mainline atlases that need their own 1.12 art. -->
<!-- From retail's Blizzard_Menu/MenuTemplates.xml. WowStyle2DropdownTemplate
and WowStyle2IconButtonTemplate are not here: they draw Mainline atlases
that need their own 1.12 art. The highlight button's art is
DarkMenuElementTemplate's (FrameXML/SharedUIPanelTemplates.xml). -->
<Button name="WowMenuAutoHideButtonTemplate" propagateMouseInput="Motion" virtual="true">
<Layers>
<Layer>
@@ -10,4 +11,5 @@
</Layer>
</Layers>
</Button>
<Button name="WowMenuDropdownHighlightButtonTemplate" inherits="DarkMenuElementTemplate" motionScriptsWhileDisabled="true" virtual="true"/>
</Ui>
@@ -235,6 +235,13 @@ function MenuUtil.CreateRadio(text, isSelected, setSelected, data)
return ConfigureTextButton(text, elementDescription);
end
-- looks good with WowStyle2DropdownTemplate, immitates the Settings menu
function MenuUtil.CreateHighlightButton(text, data, onEnter)
--assert(type(text) == "string");
local elementDescription = MenuTemplates.CreateHighlightButton(text, data, onEnter);
return ConfigureTextButton(text, elementDescription);
end
-- looks good with WowStyle2DropdownTemplate, immitates the Settings menu
function MenuUtil.CreateHighlightRadio(text, isSelected, setSelected, data, onEnter)
--assert(type(text) == "string");
@@ -267,6 +274,7 @@ MenuUtilPrivate.Inserters =
CreateTitle = MenuUtil.CreateTitle,
CreateCheckbox = MenuUtil.CreateCheckbox,
CreateRadio = MenuUtil.CreateRadio,
CreateHighlightButton = MenuUtil.CreateHighlightButton,
CreateHighlightRadio = MenuUtil.CreateHighlightRadio,
CreateDivider = MenuUtil.CreateDivider,
CreateSpacer = MenuUtil.CreateSpacer,
@@ -0,0 +1,69 @@
-- ClassicAPI's own Settings control: a number box, for the settings that take
-- any number (a range in yards, a size, a time). Retail's Settings has no such
-- control, and a slider would put a limit on these values that the settings do
-- not have. It is built the way retail builds its controls: on
-- SettingsListElementTemplate and SettingsControlMixin, so it has the row's
-- label, tooltip, indent, parent predicates and search like every other
-- control.
--
-- The box writes when Enter is pressed or it loses the focus. Escape puts the
-- current value back. Text that is not a number is not written.
ClassicAPISettingsNumberBoxControlMixin = CreateFromMixins(SettingsControlMixin);
function ClassicAPISettingsNumberBoxControlMixin:OnLoad()
SettingsControlMixin.OnLoad(self);
Mixin(self.EditBox, DefaultTooltipMixin);
DefaultTooltipMixin.OnLoad(self.EditBox);
self.EditBox:SetScript("OnEnterPressed", function(editBox)
editBox:ClearFocus();
end);
self.EditBox:SetScript("OnEscapePressed", function(editBox)
self:SetValue(self:GetSetting():GetValue());
editBox:ClearFocus();
end);
self.EditBox:SetScript("OnEditFocusGained", function(editBox)
editBox:HighlightText();
end);
self.EditBox:SetScript("OnEditFocusLost", function(editBox)
editBox:HighlightText(0, 0);
local value = tonumber(editBox:GetText());
local setting = self:GetSetting();
if value and value ~= setting:GetValue() then
setting:SetValue(value);
end
self:SetValue(setting:GetValue());
end);
end
function ClassicAPISettingsNumberBoxControlMixin:Init(initializer)
SettingsControlMixin.Init(self, initializer);
self:SetValue(self:GetSetting():GetValue());
self.EditBox:SetTooltipFunc(GenerateClosure(Settings.InitTooltip, initializer:GetName(), initializer:GetTooltip()));
self:EvaluateState();
end
function ClassicAPISettingsNumberBoxControlMixin:SetValue(value)
self.EditBox:SetText(value ~= nil and tostring(value) or "");
end
function ClassicAPISettingsNumberBoxControlMixin:EvaluateState()
SettingsListElementMixin.EvaluateState(self);
local enabled = self:IsEnabled();
if enabled then
self.EditBox:Enable();
else
self.EditBox:Disable();
end
self:DisplayEnabled(enabled);
end
function ClassicAPISettingsNumberBoxControlMixin:Release()
self.EditBox:ClearFocus();
SettingsControlMixin.Release(self);
end
@@ -0,0 +1,50 @@
<Ui xmlns="http://www.blizzard.com/wow/ui/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.blizzard.com/wow/ui/ ..\FrameXML\UI.xsd">
<!--
ClassicAPI's number box control; see Controls.lua.
The box is 1.12's InputBoxTemplate art with its slices found by key.
InputBoxTemplate itself anchors its middle slice to $parentLeft and
$parentRight, and a pooled row has no name of its own, so every box
would take the same names and anchor to the last box made.
-->
<Frame name="ClassicAPISettingsNumberBoxControlTemplate" inherits="SettingsListElementTemplate" mixin="ClassicAPISettingsNumberBoxControlMixin" virtual="true">
<Size x="280" y="26"/>
<Frames>
<EditBox parentKey="EditBox" autoFocus="false" enableMouse="true">
<Size x="70" y="20"/>
<Anchors>
<Anchor point="LEFT" relativePoint="CENTER" x="-74" y="0"/>
</Anchors>
<Layers>
<Layer level="BACKGROUND">
<Texture parentKey="Left" file="Interface\Common\Common-Input-Border">
<Size x="8" y="20"/>
<Anchors>
<Anchor point="LEFT" x="-5" y="0"/>
</Anchors>
<TexCoords left="0" right="0.0625" top="0" bottom="0.625"/>
</Texture>
<Texture parentKey="Right" file="Interface\Common\Common-Input-Border">
<Size x="8" y="20"/>
<Anchors>
<Anchor point="RIGHT" x="0" y="0"/>
</Anchors>
<TexCoords left="0.9375" right="1.0" top="0" bottom="0.625"/>
</Texture>
<Texture parentKey="Middle" file="Interface\Common\Common-Input-Border">
<Size x="10" y="20"/>
<Anchors>
<Anchor point="LEFT" relativeKey="$parent.Left" relativePoint="RIGHT"/>
<Anchor point="RIGHT" relativeKey="$parent.Right" relativePoint="LEFT"/>
</Anchors>
<TexCoords left="0.0625" right="0.9375" top="0" bottom="0.625"/>
</Texture>
</Layer>
</Layers>
<FontString inherits="ChatFontNormal"/>
</EditBox>
</Frames>
<Scripts>
<OnLoad method="OnLoad"/>
</Scripts>
</Frame>
</Ui>
+208 -586
View File
@@ -1,667 +1,289 @@
-- ClassicAPI's own entry in the AddOn Options window
-- (FrameXML\InterfaceOptions.lua): a ClassicAPI page with one page under it
-- for each feature. Every cvar that ClassicAPI registers has a control here,
-- and so do the player cache and ClassicAPI's key bindings.
-- ClassicAPI's own pages in the Settings window, one for each feature, at the
-- top of the window's first tab. Every cvar that ClassicAPI registers has a
-- control here, and so do the player cache and ClassicAPI's key bindings.
--
-- Each control reads and writes exactly one setting, and writes it only when
-- the player uses that control. So the pages have no okay, cancel or default:
-- Okay, Cancel and Escape only close the window, and Defaults does nothing
-- here. A page reads its settings again each time it is shown. A key binding
-- saves at once into the binding set in use (account or character).
-- The pages are built the way retail builds its own game settings: each one
-- is a vertical layout of Settings controls, so the window's search finds
-- them, registered as a game category. They have no group, so the list shows
-- no group header above them, and their group comes first, so the window
-- opens on the first of them.
-- A cvar that the window shows as it is gets a cvar setting. A cvar whose
-- value the control reads another way (the soft-target enable cvars, a choice
-- of numbers) gets a proxy setting, as retail does for the same cvars. A
-- setting that takes any number gets ClassicAPI's number box
-- (Options\Controls.lua).
--
-- A page's controls scroll under its heading in a ScrollBox, so a page holds
-- as many as its feature has. Dropdowns and number boxes sit on the same row
-- as their label.
-- The settings write when the player uses a control, as retail's cvar settings
-- do, and Defaults puts back each cvar's default. A key binding changes at
-- once and is saved when the window closes.
--
-- Every string is a global: the client's own (KEY_BOUND, NOT_BOUND), or one
-- from locales\enUS.lua - retail's GlobalStrings key where retail has the
-- string (ENABLE_INTERACT_TEXT and the like), a CLASSICAPI_ one where it
-- does not.
-- The pages are registered once the client has loaded its variables and
-- bindings (SettingsRegistrar), as retail registers its own.
--
-- Lua 5.0: no `...` expression or select().
local ARC_CHOICES = {
{ value = 0, text = CLASSICAPI_DIRECTION_FRONT },
{ value = 1, text = CLASSICAPI_DIRECTION_CONE },
{ value = 2, text = CLASSICAPI_DIRECTION_ANY },
}
local FORCE_CHOICES = {
{ value = 0, text = CLASSICAPI_LOOSE_TARGET_FOLLOWS_NONE },
{ value = 1, text = CLASSICAPI_LOOSE_TARGET_FOLLOWS_ENEMY },
{ value = 2, text = CLASSICAPI_LOOSE_TARGET_FOLLOWS_FRIEND },
}
-- ---------------------------------------------------------------------------
-- Settings: get / set over one cvar or the player cache
-- ---------------------------------------------------------------------------
-- On for any nonzero number.
local function CVarSetting(cvar)
return {
get = function() return (tonumber(GetCVar(cvar)) or 0) ~= 0 end,
set = function(value) SetCVar(cvar, value and "1" or "0") end,
}
end
local function NumberCVarSetting(cvar)
return {
get = function() return tonumber(GetCVar(cvar)) end,
set = function(value) SetCVar(cvar, tostring(value)) end,
}
end
-- Every string is a global: the client's own, or one from locales\enUS.lua -
-- retail's GlobalStrings key where retail has the string
-- (ENABLE_INTERACT_TEXT and the like), a CLASSICAPI_ one where it does not.
-- The soft-target enable cvars: 0 off, 1 gamepad, 2 keyboard and mouse,
-- 3 always. 1.12 has no gamepad, so 2 and 3 are on.
local function SoftTargetSetting(cvar)
return {
get = function() return (tonumber(GetCVar(cvar)) or 0) >= 2 end,
set = function(value) SetCVar(cvar, value and "3" or "0") end,
}
end
local rememberSetting = {
get = function() return C_PlayerCache.IsEnabled() and true or false end,
set = function(value) C_PlayerCache.SetEnabled(value) end,
}
-- ---------------------------------------------------------------------------
-- Pages
-- ---------------------------------------------------------------------------
-- Row labels line up with the checkbox labels; row controls start at
-- CONTROL_X.
local LABEL_X = 48
local CONTROL_X = 200
-- pfUI's Interface Options skin finds the controls and the page scroll bars
-- by these names.
local numControls = 0
local function NextName()
numControls = numControls + 1
return "ClassicAPIOptionsControl" .. numControls
end
local numScrollBars = 0
local function NextScrollBarName()
numScrollBars = numScrollBars + 1
return "ClassicAPIOptionsScrollBar" .. numScrollBars
end
local function RefreshControls(page)
page.updating = true
for _, control in ipairs(page.controls) do
control:Update()
-- 3 always. This client has no gamepad, so 2 and 3 are on.
local function RegisterSoftTargetSetting(category, variable, cvar, name)
local function GetValue()
return (tonumber(GetCVar(cvar)) or 0) >= 2;
end
page.updating = nil
end
-- The controls go on `page.content`, the one frame in the page's ScrollBox,
-- `page.y` down from its top. The clipping of the ScrollBox also keeps the
-- mouse off the controls that are scrolled out of view.
-- `title` is the heading, the category name when nil.
local function NewPage(name, parent, title, subtitle)
local page = CreateFrame("Frame")
page.name = name
page.parent = parent
page.controls = {}
local heading = page:CreateFontString(nil, "ARTWORK", "GameFontNormalLarge")
heading:SetPoint("TOPLEFT", page, "TOPLEFT", 16, -16)
heading:SetText(title or name)
local top = -40
if subtitle then
local text = page:CreateFontString(nil, "ARTWORK", "GameFontHighlightSmall")
text:SetPoint("TOPLEFT", heading, "BOTTOMLEFT", 0, -8)
text:SetPoint("RIGHT", page, "RIGHT", -32, 0)
text:SetJustifyH("LEFT")
text:SetText(subtitle)
top = -64
local function SetValue(value)
SetCVar(cvar, value and "3" or "0");
end
local scrollBox = CreateFrame("Frame", nil, page, "WowScrollBox")
scrollBox:SetPoint("TOPLEFT", page, "TOPLEFT", 0, top)
scrollBox:SetPoint("BOTTOMRIGHT", page, "BOTTOMRIGHT", -20, 8)
scrollBox:EnableMouseWheel(true)
local scrollBar = CreateFrame("EventFrame", NextScrollBarName(), page, "MinimalScrollBar")
scrollBar:SetPoint("TOPLEFT", scrollBox, "TOPRIGHT", 4, 0)
scrollBar:SetPoint("BOTTOMLEFT", scrollBox, "BOTTOMRIGHT", 4, 0)
local content = CreateFrame("Frame", nil, scrollBox)
content:SetHeight(1)
content.scrollable = true
ScrollUtil.InitScrollBoxWithScrollBar(scrollBox, scrollBar, CreateScrollBoxLinearView())
ScrollUtil.AddManagedScrollBarVisibilityBehavior(scrollBox, scrollBar)
page.scrollBox = scrollBox
page.content = content
page.y = 0
page.refresh = RefreshControls
InterfaceOptions_AddCategory(page)
return page
local defaultValue = (tonumber(GetCVarDefault(cvar)) or 0) >= 2;
return Settings.RegisterProxySetting(category, variable, Settings.VarType.Boolean, name, defaultValue, GetValue, SetValue);
end
-- Moves `page.y` down past a row and makes the content that tall. The
-- ScrollBox measures it again on its next update (a hidden page's waits for
-- the page to be shown).
local function Grow(page, height)
page.y = page.y - height
page.content:SetHeight(8 - page.y)
page.scrollBox:FullUpdate(ScrollBoxConstants.UpdateQueued)
local function AddHeader(layout, text)
layout:AddInitializer(CreateSettingsListSectionHeaderInitializer(text));
end
local function AddControl(page, control, setting, height)
control.setting = setting
table.insert(page.controls, control)
Grow(page, height)
local function AddCVarCheckbox(category, cvar, name, tooltip)
local _, initializer = Settings.SetupCVarCheckbox(category, cvar, name, tooltip);
return initializer;
end
local function AddHeader(page, text)
local header = page.content:CreateFontString(nil, "ARTWORK", "GameFontHighlight")
header:SetPoint("TOPLEFT", page.content, "TOPLEFT", 16, page.y - 6)
header:SetText(text)
Grow(page, 24)
local function AddNumberBox(category, cvar, name, tooltip)
local setting = Settings.RegisterCVarSetting(category, cvar, Settings.VarType.Number, name);
local initializer = Settings.CreateControlInitializer("ClassicAPISettingsNumberBoxControlTemplate", setting, nil, tooltip);
SettingsPanel:GetLayout(category):AddInitializer(initializer);
return initializer;
end
local function AddRowLabel(page, label)
local text = page.content:CreateFontString(nil, "ARTWORK", "GameFontNormalSmall")
text:SetPoint("TOPLEFT", page.content, "TOPLEFT", LABEL_X, page.y - 10)
text:SetText(label)
end
local function SetTooltip(frame, tooltip)
frame:SetScript("OnEnter", function()
GameTooltip:SetOwner(this, "ANCHOR_RIGHT")
GameTooltip:SetText(tooltip, nil, nil, nil, nil, 1)
end)
frame:SetScript("OnLeave", function() GameTooltip:Hide() end)
end
-- `enabledIf`, when given, greys the checkbox out while it returns false.
local function AddCheckbox(page, label, tooltip, setting, enabledIf)
local check = CreateFrame("CheckButton", NextName(), page.content, "OptionsCheckButtonTemplate")
check:SetPoint("TOPLEFT", page.content, "TOPLEFT", 16, page.y)
local text = getglobal(check:GetName() .. "Text")
text:SetText(label)
check.tooltipText = tooltip
check:SetScript("OnClick", function()
this.setting.set(this:GetChecked() and true or false)
RefreshControls(page)
end)
check.Update = function(self)
self:SetChecked(self.setting.get())
if not enabledIf or enabledIf() then
self:Enable()
text:SetTextColor(NORMAL_FONT_COLOR.r, NORMAL_FONT_COLOR.g, NORMAL_FONT_COLOR.b)
else
self:Disable()
text:SetTextColor(GRAY_FONT_COLOR.r, GRAY_FONT_COLOR.g, GRAY_FONT_COLOR.b)
-- `choices` is a list of { value, text }, or a function that returns one.
local function AddDropdown(category, cvar, name, tooltip, choices)
local function GetOptions()
local container = Settings.CreateControlTextContainer();
local list = type(choices) == "function" and choices() or choices;
for _, choice in ipairs(list) do
container:Add(choice[1], choice[2]);
end
return container:GetData();
end
AddControl(page, check, setting, 30)
local _, initializer = Settings.SetupCVarDropdown(category, cvar, Settings.VarType.Number, GetOptions, name, tooltip);
return initializer;
end
-- `choices` is a list of { value = ..., text = ... }, or a function that
-- returns one. A value with no choice shows as the number itself.
local function AddDropDown(page, label, tooltip, setting, choices)
AddRowLabel(page, label)
local function List()
if type(choices) == "function" then return choices() end
return choices
end
-- The template's art has a 16 pixel margin on the left.
local dropdown = CreateFrame("Frame", NextName(), page.content, "UIDropDownMenuTemplate")
dropdown:SetPoint("TOPLEFT", page.content, "TOPLEFT", CONTROL_X - 16, page.y)
UIDropDownMenu_SetWidth(150, dropdown)
dropdown:EnableMouse(true)
SetTooltip(dropdown, tooltip)
local function Initialize()
local selected = setting.get()
for _, choice in ipairs(List()) do
local info = {}
info.text = choice.text
info.value = choice.value
info.checked = choice.value == selected and 1 or nil
info.func = function()
UIDropDownMenu_SetSelectedValue(dropdown, this.value)
setting.set(this.value)
end
UIDropDownMenu_AddButton(info)
end
end
dropdown.Update = function(self)
UIDropDownMenu_Initialize(self, Initialize)
local selected = setting.get()
UIDropDownMenu_SetSelectedValue(self, selected)
local text = tostring(selected or "")
for _, choice in ipairs(List()) do
if choice.value == selected then text = choice.text end
end
UIDropDownMenu_SetText(text, self)
end
AddControl(page, dropdown, setting, 32)
local function FormatHundredths(value)
return string.format("%.2f", value);
end
-- Writes when Enter is pressed or the box loses focus; Escape puts the
-- current value back. Text that is not a number is not written.
local function AddNumberBox(page, label, tooltip, setting)
AddRowLabel(page, label)
local box = CreateFrame("EditBox", NextName(), page.content, "InputBoxTemplate")
box:SetPoint("TOPLEFT", page.content, "TOPLEFT", CONTROL_X + 6, page.y - 6)
box:SetWidth(70)
box:SetHeight(20)
box:SetAutoFocus(false)
SetTooltip(box, tooltip)
local function ShowValue(self)
self:SetText(tostring(setting.get() or ""))
end
box:SetScript("OnEnterPressed", function() this:ClearFocus() end)
box:SetScript("OnEscapePressed", function()
ShowValue(this)
this:ClearFocus()
end)
box:SetScript("OnEditFocusLost", function()
this:HighlightText(0, 0)
local value = tonumber(this:GetText())
if value and value ~= setting.get() then
setting.set(value)
end
ShowValue(this)
end)
box.Update = ShowValue
AddControl(page, box, setting, 32)
local function AddSlider(category, cvar, name, tooltip, minValue, maxValue, step, formatter)
local options = Settings.CreateSliderOptions(minValue, maxValue, step);
options:SetLabelFormatter(MinimalSliderWithSteppersMixin.Label.Right, formatter);
local _, initializer = Settings.SetupCVarSlider(category, cvar, options, name, tooltip);
return initializer;
end
local function AddSlider(page, label, tooltip, setting, minValue, maxValue, step)
local slider = CreateFrame("Slider", NextName(), page.content, "OptionsSliderTemplate")
slider:SetPoint("TOPLEFT", page.content, "TOPLEFT", 24, page.y - 20)
slider:SetWidth(200)
slider:SetMinMaxValues(minValue, maxValue)
slider:SetValueStep(step)
slider.tooltipText = tooltip
getglobal(slider:GetName() .. "Text"):SetText(label)
getglobal(slider:GetName() .. "Low"):SetText(minValue)
getglobal(slider:GetName() .. "High"):SetText(maxValue)
local value = slider:CreateFontString(nil, "ARTWORK", "GameFontHighlightSmall")
value:SetPoint("LEFT", slider, "RIGHT", 8, 0)
local function Format(v)
if step < 1 then return string.format("%.2f", v) end
return v
end
slider:SetScript("OnValueChanged", function()
local v = math.floor(this:GetValue() / step + 0.5) * step
value:SetText(Format(v))
if not page.updating and v ~= setting.get() then
setting.set(v)
end
end)
slider.Update = function(self)
local v = setting.get() or minValue
self:SetValue(v)
value:SetText(Format(v))
end
AddControl(page, slider, setting, 56)
local function AddKeybinding(layout, action)
local bindingIndex = C_KeyBindings.GetBindingIndex(action);
local initializer = CreateKeybindingEntryInitializer(bindingIndex, true);
initializer:AddSearchTags(GetBindingName(action));
layout:AddInitializer(initializer);
return initializer;
end
-- ---------------------------------------------------------------------------
-- Key bindings
-- ---------------------------------------------------------------------------
local ARC_CHOICES = {
{ 0, CLASSICAPI_DIRECTION_FRONT },
{ 1, CLASSICAPI_DIRECTION_CONE },
{ 2, CLASSICAPI_DIRECTION_ANY },
};
-- A key binding row, as on retail's settings pages: the binding's name, then
-- a button for each of its two keys. Left click a button and press a key, a
-- mouse button or the wheel to bind it there; Escape cancels. Right click a
-- button to unbind its key.
--
-- While a button listens, `listener` covers the screen above the window and
-- takes every key, click and wheel turn, as retail's KeybindListener and its
-- input blocker do. A left or right click on it cancels. The binding itself
-- is 1.12's Key Bindings window's: the same chord order, the same check for
-- an action that loses its last key, the same put-back when SetBinding
-- refuses a key.
--
-- Messages go on the page's output line, under its controls.
local LISTEN_BUTTONS = {
MiddleButton = "BUTTON3",
Button4 = "BUTTON4",
Button5 = "BUTTON5",
}
-- Keys that only modify another key, as the Key Bindings window skips them.
local IGNORED_KEYS = { UNKNOWN = true, SHIFT = true, CTRL = true, ALT = true }
local listener = CreateFrame("Button", nil, UIParent)
listener:SetAllPoints(UIParent)
listener:SetFrameStrata("FULLSCREEN_DIALOG")
listener:EnableMouse(true)
listener:EnableMouseWheel(true)
listener:EnableKeyboard(true)
listener:RegisterForClicks("LeftButtonUp", "RightButtonUp", "MiddleButtonUp", "Button4Up", "Button5Up")
listener:Hide()
local function BindingName(action)
return GetBindingText(action, "BINDING_NAME_")
end
-- GetBindingKey's keys as a list: a row's button `i` shows keys[i].
local function BindingKeys(action)
return { GetBindingKey(action) }
end
local function StopListening()
local row = listener.row
if not row then return end
listener.row = nil
listener:Hide()
row.page.output:SetText("")
RefreshControls(row.page)
end
local function StartListening(row, index)
-- A number box that keeps the focus would take the key instead.
for _, control in ipairs(row.page.controls) do
if control.ClearFocus then control:ClearFocus() end
end
listener.row = row
listener.index = index
listener:Show()
row.page.output:SetText(format(SETTINGS_BIND_KEY_TO_COMMAND_OR_CANCEL, BindingName(row.action), GetBindingText("ESCAPE", "KEY_")))
RefreshControls(row.page)
end
-- 1.12's chord order: ALT-CTRL-SHIFT-key.
local function Chord(key)
if IsShiftKeyDown() then key = "SHIFT-" .. key end
if IsControlKeyDown() then key = "CTRL-" .. key end
if IsAltKeyDown() then key = "ALT-" .. key end
return key
end
local function Bind(key)
if IGNORED_KEYS[key] then return end
local chord = Chord(key)
local current = GetBindingAction(chord)
if current == "SCREENSHOT" then
Screenshot()
return
end
local row, index = listener.row, listener.index
StopListening()
if key == "ESCAPE" and current == "TOGGLEGAMEMENU" then return end
local action = row.action
local message = KEY_BOUND
if current ~= "" and current ~= action then
local old1, old2 = GetBindingKey(current)
if (not old1 or old1 == chord) and (not old2 or old2 == chord) then
message = format(KEY_UNBOUND_ERROR, BindingName(current))
end
end
-- Unbind both keys, then bind them back in order with the new key in
-- the slot that was clicked.
local keys = BindingKeys(action)
for i = 1, 2 do
if keys[i] then SetBinding(keys[i]) end
end
for i = 1, 2 do
local bind = (i == index) and chord or keys[i]
if bind and not SetBinding(bind, action) then
if keys[i] then SetBinding(keys[i], action) end
message = KEYBINDINGFRAME_MOUSEWHEEL_ERROR
end
end
SaveBindings(GetCurrentBindingSet())
RefreshControls(row.page)
row.page.output:SetText(message)
end
listener:SetScript("OnKeyDown", function() Bind(arg1) end)
listener:SetScript("OnMouseWheel", function()
Bind(arg1 > 0 and "MOUSEWHEELUP" or "MOUSEWHEELDOWN")
end)
listener:SetScript("OnClick", function()
local button = LISTEN_BUTTONS[arg1]
if button then Bind(button) else StopListening() end
end)
local function Unbind(row, index)
local key = BindingKeys(row.action)[index]
if key then
SetBinding(key)
SaveBindings(GetCurrentBindingSet())
end
GameTooltip:Hide()
row.page.output:SetText("")
RefreshControls(row.page)
end
-- The page's output line, made with its first key binding row. It takes the
-- bottom of the page from the ScrollBox.
local function EnsureOutput(page)
if page.output then return end
local output = page:CreateFontString(nil, "ARTWORK", "GameFontNormalSmall")
output:SetPoint("BOTTOMLEFT", page, "BOTTOMLEFT", 16, 12)
output:SetPoint("RIGHT", page, "RIGHT", -16, 0)
output:SetJustifyH("LEFT")
page.scrollBox:SetPoint("BOTTOMRIGHT", page, "BOTTOMRIGHT", -20, 30)
page.output = output
page:SetScript("OnHide", function()
if listener.row and listener.row.page == this then StopListening() end
this.output:SetText("")
end)
end
local function AddKeybinding(page, action)
EnsureOutput(page)
AddRowLabel(page, BindingName(action))
local row = { page = page, action = action, buttons = {} }
for i = 1, 2 do
local button = CreateFrame("Button", NextName(), page.content, "UIPanelButtonTemplate2")
button:SetWidth(86)
button:SetHeight(22)
if i == 1 then
button:SetPoint("TOPLEFT", page.content, "TOPLEFT", CONTROL_X, page.y - 5)
else
button:SetPoint("LEFT", row.buttons[1], "RIGHT", 0, 0)
end
button:SetTextFontObject(GameFontHighlightSmall)
button:SetHighlightFontObject(GameFontHighlightSmall)
button:RegisterForClicks("LeftButtonUp", "RightButtonUp")
button.index = i
button:SetScript("OnClick", function()
if arg1 == "RightButton" then
Unbind(row, this.index)
else
StartListening(row, this.index)
end
end)
button:SetScript("OnEnter", function()
local key = BindingKeys(action)[this.index]
if not key then return end
GameTooltip:SetOwner(this, "ANCHOR_RIGHT")
GameTooltip:SetText(format(KEY_BINDING_NAME_AND_KEY, BindingName(action), GetBindingText(key, "KEY_")),
HIGHLIGHT_FONT_COLOR.r, HIGHLIGHT_FONT_COLOR.g, HIGHLIGHT_FONT_COLOR.b)
GameTooltip:AddLine(KEY_BINDING_TOOLTIP, NORMAL_FONT_COLOR.r, NORMAL_FONT_COLOR.g, NORMAL_FONT_COLOR.b, 1)
GameTooltip:Show()
end)
button:SetScript("OnLeave", function() GameTooltip:Hide() end)
row.buttons[i] = button
end
row.Update = function(self)
local keys = BindingKeys(action)
for i, button in ipairs(self.buttons) do
if keys[i] then
button:SetText(GetBindingText(keys[i], "KEY_"))
button:SetAlpha(1)
else
button:SetText(NORMAL_FONT_COLOR_CODE .. NOT_BOUND .. FONT_COLOR_CODE_CLOSE)
button:SetAlpha(0.8)
end
if listener.row == self and listener.index == i then
button:LockHighlight()
else
button:UnlockHighlight()
end
end
end
AddControl(page, row, nil, 32)
end
-- ---------------------------------------------------------------------------
-- ClassicAPI
-- ---------------------------------------------------------------------------
local version = GetAddOnMetadata("!!!ClassicAPI", "Version")
local main = NewPage("ClassicAPI", nil, "ClassicAPI " .. version, CLASSICAPI_OPTIONS_ABOUT)
local FORCE_CHOICES = {
{ 0, CLASSICAPI_LOOSE_TARGET_FOLLOWS_NONE },
{ 1, CLASSICAPI_LOOSE_TARGET_FOLLOWS_ENEMY },
{ 2, CLASSICAPI_LOOSE_TARGET_FOLLOWS_FRIEND },
};
-- ---------------------------------------------------------------------------
-- Interact Key
-- ---------------------------------------------------------------------------
local interact = NewPage(CLASSICAPI_INTERACT_KEY, main.name)
local function RegisterInteractKey()
local category, layout = Settings.RegisterVerticalLayoutCategory(CLASSICAPI_INTERACT_KEY);
Settings.RegisterCategory(category);
AddCheckbox(interact, ENABLE_INTERACT_TEXT, OPTION_TOOLTIP_ENABLE_INTERACT, SoftTargetSetting("SoftTargetInteract"))
AddKeybinding(interact, "INTERACTTARGET")
AddKeybinding(interact, "INTERACTMOUSEOVER")
AddDropDown(interact, CLASSICAPI_INTERACT_DIRECTION, CLASSICAPI_INTERACT_DIRECTION_TOOLTIP, NumberCVarSetting("SoftTargetInteractArc"), ARC_CHOICES)
AddNumberBox(interact, CLASSICAPI_INTERACT_RANGE, CLASSICAPI_RANGE_TOOLTIP, NumberCVarSetting("SoftTargetInteractRange"))
AddCheckbox(interact, CLASSICAPI_STRICT_INTERACT_RANGE, CLASSICAPI_STRICT_INTERACT_RANGE_TOOLTIP, CVarSetting("SoftTargetInteractRangeIsHard"))
local interactIcon = CVarSetting("SoftTargetIconInteract")
AddCheckbox(interact, CLASSICAPI_INTERACT_ICON, CLASSICAPI_INTERACT_ICON_TOOLTIP, interactIcon)
-- The object icon is drawn only while the interact icon is on.
AddCheckbox(interact, CLASSICAPI_GAME_OBJECT_ICON, CLASSICAPI_GAME_OBJECT_ICON_TOOLTIP, CVarSetting("SoftTargetIconGameObject"), interactIcon.get)
Settings.CreateCheckbox(category, RegisterSoftTargetSetting(category, "PROXY_ENABLE_INTERACT", "SoftTargetInteract", ENABLE_INTERACT_TEXT), OPTION_TOOLTIP_ENABLE_INTERACT);
AddKeybinding(layout, "INTERACTTARGET");
AddKeybinding(layout, "INTERACTMOUSEOVER");
AddDropdown(category, "SoftTargetInteractArc", CLASSICAPI_INTERACT_DIRECTION, CLASSICAPI_INTERACT_DIRECTION_TOOLTIP, ARC_CHOICES);
AddNumberBox(category, "SoftTargetInteractRange", CLASSICAPI_INTERACT_RANGE, CLASSICAPI_RANGE_TOOLTIP);
AddCVarCheckbox(category, "SoftTargetInteractRangeIsHard", CLASSICAPI_STRICT_INTERACT_RANGE, CLASSICAPI_STRICT_INTERACT_RANGE_TOOLTIP);
AddHeader(interact, CLASSICAPI_ALL_SOFT_TARGET_ICONS)
AddCheckbox(interact, CLASSICAPI_LOW_PRIORITY_ICONS, CLASSICAPI_LOW_PRIORITY_ICONS_TOOLTIP, CVarSetting("SoftTargetLowPriorityIcons"))
AddNumberBox(interact, CLASSICAPI_ICON_SIZE, CLASSICAPI_ICON_SIZE_TOOLTIP, NumberCVarSetting("SoftTargetNameplateSize"))
local interactIcon, interactIconInitializer = Settings.SetupCVarCheckbox(category, "SoftTargetIconInteract", CLASSICAPI_INTERACT_ICON, CLASSICAPI_INTERACT_ICON_TOOLTIP);
-- The object icon is drawn only while the interact icon is on.
local gameObjectIcon = AddCVarCheckbox(category, "SoftTargetIconGameObject", CLASSICAPI_GAME_OBJECT_ICON, CLASSICAPI_GAME_OBJECT_ICON_TOOLTIP);
gameObjectIcon:SetParentInitializer(interactIconInitializer, function() return interactIcon:GetValue(); end);
AddHeader(layout, CLASSICAPI_ALL_SOFT_TARGET_ICONS);
AddCVarCheckbox(category, "SoftTargetLowPriorityIcons", CLASSICAPI_LOW_PRIORITY_ICONS, CLASSICAPI_LOW_PRIORITY_ICONS_TOOLTIP);
AddNumberBox(category, "SoftTargetNameplateSize", CLASSICAPI_ICON_SIZE, CLASSICAPI_ICON_SIZE_TOOLTIP);
end
-- ---------------------------------------------------------------------------
-- Action Targeting
-- ---------------------------------------------------------------------------
local targeting = NewPage(CLASSICAPI_ACTION_TARGETING, main.name)
local function RegisterActionTargeting()
local category, layout = Settings.RegisterVerticalLayoutCategory(CLASSICAPI_ACTION_TARGETING);
Settings.RegisterCategory(category);
AddHeader(targeting, CLASSICAPI_ENEMIES)
AddCheckbox(targeting, ACTION_TARGETING_OPTION, OPTION_TOOLTIP_ACTION_TARGETING, SoftTargetSetting("SoftTargetEnemy"))
AddDropDown(targeting, CLASSICAPI_ENEMY_DIRECTION, CLASSICAPI_UNIT_DIRECTION_TOOLTIP, NumberCVarSetting("SoftTargetEnemyArc"), ARC_CHOICES)
AddNumberBox(targeting, CLASSICAPI_ENEMY_RANGE, CLASSICAPI_RANGE_TOOLTIP, NumberCVarSetting("SoftTargetEnemyRange"))
AddCheckbox(targeting, CLASSICAPI_ENEMY_ICON, CLASSICAPI_ENEMY_ICON_TOOLTIP, CVarSetting("SoftTargetIconEnemy"))
AddHeader(layout, CLASSICAPI_ENEMIES);
Settings.CreateCheckbox(category, RegisterSoftTargetSetting(category, "PROXY_ACTION_TARGETING", "SoftTargetEnemy", ACTION_TARGETING_OPTION), OPTION_TOOLTIP_ACTION_TARGETING);
AddDropdown(category, "SoftTargetEnemyArc", CLASSICAPI_ENEMY_DIRECTION, CLASSICAPI_UNIT_DIRECTION_TOOLTIP, ARC_CHOICES);
AddNumberBox(category, "SoftTargetEnemyRange", CLASSICAPI_ENEMY_RANGE, CLASSICAPI_RANGE_TOOLTIP);
AddCVarCheckbox(category, "SoftTargetIconEnemy", CLASSICAPI_ENEMY_ICON, CLASSICAPI_ENEMY_ICON_TOOLTIP);
AddHeader(targeting, CLASSICAPI_FRIENDS)
AddCheckbox(targeting, CLASSICAPI_FRIEND_TARGETING, CLASSICAPI_FRIEND_TARGETING_TOOLTIP, SoftTargetSetting("SoftTargetFriend"))
AddDropDown(targeting, CLASSICAPI_FRIEND_DIRECTION, CLASSICAPI_UNIT_DIRECTION_TOOLTIP, NumberCVarSetting("SoftTargetFriendArc"), ARC_CHOICES)
AddNumberBox(targeting, CLASSICAPI_FRIEND_RANGE, CLASSICAPI_RANGE_TOOLTIP, NumberCVarSetting("SoftTargetFriendRange"))
AddCheckbox(targeting, CLASSICAPI_FRIEND_ICON, CLASSICAPI_FRIEND_ICON_TOOLTIP, CVarSetting("SoftTargetIconFriend"))
AddHeader(layout, CLASSICAPI_FRIENDS);
Settings.CreateCheckbox(category, RegisterSoftTargetSetting(category, "PROXY_FRIEND_TARGETING", "SoftTargetFriend", CLASSICAPI_FRIEND_TARGETING), CLASSICAPI_FRIEND_TARGETING_TOOLTIP);
AddDropdown(category, "SoftTargetFriendArc", CLASSICAPI_FRIEND_DIRECTION, CLASSICAPI_UNIT_DIRECTION_TOOLTIP, ARC_CHOICES);
AddNumberBox(category, "SoftTargetFriendRange", CLASSICAPI_FRIEND_RANGE, CLASSICAPI_RANGE_TOOLTIP);
AddCVarCheckbox(category, "SoftTargetIconFriend", CLASSICAPI_FRIEND_ICON, CLASSICAPI_FRIEND_ICON_TOOLTIP);
AddHeader(targeting, CLASSICAPI_WHEN_YOU_HAVE_A_TARGET)
AddCheckbox(targeting, CLASSICAPI_KEEP_ACTION_TARGETING, CLASSICAPI_KEEP_ACTION_TARGETING_TOOLTIP, CVarSetting("SoftTargetWithLocked"))
AddCheckbox(targeting, CLASSICAPI_PREFER_YOUR_TARGET, CLASSICAPI_PREFER_YOUR_TARGET_TOOLTIP, CVarSetting("SoftTargetMatchLocked"))
AddDropDown(targeting, CLASSICAPI_LOOSE_TARGET_FOLLOWS, CLASSICAPI_LOOSE_TARGET_FOLLOWS_TOOLTIP, NumberCVarSetting("SoftTargetForce"), FORCE_CHOICES)
AddHeader(layout, CLASSICAPI_WHEN_YOU_HAVE_A_TARGET);
AddCVarCheckbox(category, "SoftTargetWithLocked", CLASSICAPI_KEEP_ACTION_TARGETING, CLASSICAPI_KEEP_ACTION_TARGETING_TOOLTIP);
AddCVarCheckbox(category, "SoftTargetMatchLocked", CLASSICAPI_PREFER_YOUR_TARGET, CLASSICAPI_PREFER_YOUR_TARGET_TOOLTIP);
AddDropdown(category, "SoftTargetForce", CLASSICAPI_LOOSE_TARGET_FOLLOWS, CLASSICAPI_LOOSE_TARGET_FOLLOWS_TOOLTIP, FORCE_CHOICES);
end
-- ---------------------------------------------------------------------------
-- Combat
-- ---------------------------------------------------------------------------
local combat = NewPage(COMBAT_LABEL, main.name)
local function RegisterCombat()
local category, layout = Settings.RegisterVerticalLayoutCategory(COMBAT_LABEL);
Settings.RegisterCategory(category);
AddHeader(combat, CLASSICAPI_ACTION_BARS)
AddCheckbox(combat, ACTION_BUTTON_USE_KEY_DOWN, OPTION_TOOLTIP_ACTION_BUTTON_USE_KEY_DOWN, CVarSetting("ActionButtonUseKeyDown"))
AddCheckbox(combat, COUNTDOWN_FOR_COOLDOWNS_TEXT, OPTION_TOOLTIP_COUNTDOWN_FOR_COOLDOWNS, CVarSetting("countdownForCooldowns"))
AddHeader(layout, CLASSICAPI_ACTION_BARS);
AddCVarCheckbox(category, "ActionButtonUseKeyDown", ACTION_BUTTON_USE_KEY_DOWN, OPTION_TOOLTIP_ACTION_BUTTON_USE_KEY_DOWN);
AddCVarCheckbox(category, "countdownForCooldowns", COUNTDOWN_FOR_COOLDOWNS_TEXT, OPTION_TOOLTIP_COUNTDOWN_FOR_COOLDOWNS);
AddHeader(combat, CLASSICAPI_CASTING_AND_ATTACKING)
AddCheckbox(combat, CLASSICAPI_AUTO_STAND, CLASSICAPI_AUTO_STAND_TOOLTIP, CVarSetting("autoStand"))
AddCheckbox(combat, CLASSICAPI_AUTO_DISMOUNT, CLASSICAPI_AUTO_DISMOUNT_TOOLTIP, CVarSetting("autoDismount"))
AddCheckbox(combat, CLASSICAPI_AUTO_UNSHIFT, CLASSICAPI_AUTO_UNSHIFT_TOOLTIP, CVarSetting("autoUnshift"))
AddCheckbox(combat, STOP_AUTO_ATTACK, OPTION_TOOLTIP_STOP_AUTO_ATTACK, CVarSetting("stopAutoAttackOnTargetChange"))
AddHeader(layout, CLASSICAPI_CASTING_AND_ATTACKING);
AddCVarCheckbox(category, "autoStand", CLASSICAPI_AUTO_STAND, CLASSICAPI_AUTO_STAND_TOOLTIP);
AddCVarCheckbox(category, "autoDismount", CLASSICAPI_AUTO_DISMOUNT, CLASSICAPI_AUTO_DISMOUNT_TOOLTIP);
AddCVarCheckbox(category, "autoUnshift", CLASSICAPI_AUTO_UNSHIFT, CLASSICAPI_AUTO_UNSHIFT_TOOLTIP);
AddCVarCheckbox(category, "stopAutoAttackOnTargetChange", STOP_AUTO_ATTACK, OPTION_TOOLTIP_STOP_AUTO_ATTACK);
end
-- ---------------------------------------------------------------------------
-- Bags and Items
-- ---------------------------------------------------------------------------
local bags = NewPage(CLASSICAPI_BAGS_AND_ITEMS, main.name)
local function RegisterBags()
local category, layout = Settings.RegisterVerticalLayoutCategory(CLASSICAPI_BAGS_AND_ITEMS);
Settings.RegisterCategory(category);
AddCheckbox(bags, CLASSICAPI_SORT_BAGS_RIGHT_TO_LEFT, CLASSICAPI_SORT_BAGS_RIGHT_TO_LEFT_TOOLTIP, CVarSetting("sortBagsRightToLeft"))
AddCheckbox(bags, CLASSICAPI_IGNORE_BACKPACK, CLASSICAPI_IGNORE_BACKPACK_TOOLTIP, CVarSetting("backpackAutosortDisabled"))
AddCheckbox(bags, CLASSICAPI_IGNORE_BANK, CLASSICAPI_IGNORE_BANK_TOOLTIP, CVarSetting("bankAutosortDisabled"))
AddCheckbox(bags, CLASSICAPI_HIDE_EQUIPMENT_SETS, CLASSICAPI_HIDE_EQUIPMENT_SETS_TOOLTIP, CVarSetting("dontShowEquipmentSetsOnItems"))
AddCVarCheckbox(category, "sortBagsRightToLeft", CLASSICAPI_SORT_BAGS_RIGHT_TO_LEFT, CLASSICAPI_SORT_BAGS_RIGHT_TO_LEFT_TOOLTIP);
AddCVarCheckbox(category, "backpackAutosortDisabled", CLASSICAPI_IGNORE_BACKPACK, CLASSICAPI_IGNORE_BACKPACK_TOOLTIP);
AddCVarCheckbox(category, "bankAutosortDisabled", CLASSICAPI_IGNORE_BANK, CLASSICAPI_IGNORE_BANK_TOOLTIP);
AddCVarCheckbox(category, "dontShowEquipmentSetsOnItems", CLASSICAPI_HIDE_EQUIPMENT_SETS, CLASSICAPI_HIDE_EQUIPMENT_SETS_TOOLTIP);
AddHeader(bags, LOOT)
AddKeybinding(bags, "AOELOOT")
AddHeader(layout, LOOT);
AddKeybinding(layout, "AOELOOT");
end
-- ---------------------------------------------------------------------------
-- Interface
-- ---------------------------------------------------------------------------
local interface = NewPage(CLASSICAPI_INTERFACE, main.name)
local function RegisterInterface()
local category, layout = Settings.RegisterVerticalLayoutCategory(CLASSICAPI_INTERFACE);
Settings.RegisterCategory(category);
-- The label ends with some of the cursors the setting shows. The DLL serves
-- each image at its Interface\Cursor path, and the markup stays out of the
-- translated string.
local expandedCursorIcons = ""
for _, name in ipairs({ "RepairNPC", "Innkeeper", "StableMaster", "Quest", "QuestTurnIn", "Fishing" }) do
expandedCursorIcons = expandedCursorIcons .. " |TInterface\\Cursor\\" .. name .. ":16|t"
-- The label ends with one of the cursors the setting shows, all the row has
-- room for, and the tooltip opens with several. The DLL serves each image
-- at its Interface\Cursor path, and the markup stays out of the translated
-- strings.
local function CursorIcon(name)
return "|TInterface\\Cursor\\" .. name .. ":16|t";
end
local expandedCursorIcons = "";
for _, name in ipairs({ "RepairNPC", "Innkeeper", "StableMaster", "Quest", "QuestTurnIn", "Fishing" }) do
expandedCursorIcons = expandedCursorIcons .. CursorIcon(name) .. " ";
end
AddHeader(layout, CLASSICAPI_CURSOR);
local cursors = AddCVarCheckbox(category, "expandedCursors", CLASSICAPI_EXPANDED_CURSORS .. " " .. CursorIcon("RepairNPC"), expandedCursorIcons .. "\n" .. CLASSICAPI_EXPANDED_CURSORS_TOOLTIP);
cursors:AddSearchTags(CLASSICAPI_EXPANDED_CURSORS);
AddHeader(layout, CLASSICAPI_NAMEPLATES);
AddSlider(category, "nameplateSelectedAlpha", CLASSICAPI_TARGET_NAMEPLATE_ALPHA, CLASSICAPI_TARGET_NAMEPLATE_ALPHA_TOOLTIP, 0, 1, 0.05, FormatHundredths);
AddSlider(category, "nameplateNotSelectedAlpha", CLASSICAPI_OTHER_NAMEPLATE_ALPHA, CLASSICAPI_OTHER_NAMEPLATE_ALPHA_TOOLTIP, 0, 1, 0.05, FormatHundredths);
AddHeader(layout, CLASSICAPI_NUMBERS);
AddCVarCheckbox(category, "breakUpLargeNumbers", CLASSICAPI_SEPARATE_LARGE_NUMBERS, CLASSICAPI_SEPARATE_LARGE_NUMBERS_TOOLTIP);
AddHeader(layout, CLASSICAPI_MOTION);
AddNumberBox(category, "ShakeStrengthUI", CLASSICAPI_UI_SHAKE_STRENGTH, CLASSICAPI_UI_SHAKE_STRENGTH_TOOLTIP);
end
AddHeader(interface, CLASSICAPI_CURSOR)
AddCheckbox(interface, CLASSICAPI_EXPANDED_CURSORS .. expandedCursorIcons, CLASSICAPI_EXPANDED_CURSORS_TOOLTIP, CVarSetting("expandedCursors"))
AddHeader(interface, CLASSICAPI_NAMEPLATES)
AddSlider(interface, CLASSICAPI_TARGET_NAMEPLATE_ALPHA, CLASSICAPI_TARGET_NAMEPLATE_ALPHA_TOOLTIP, NumberCVarSetting("nameplateSelectedAlpha"), 0, 1, 0.05)
AddSlider(interface, CLASSICAPI_OTHER_NAMEPLATE_ALPHA, CLASSICAPI_OTHER_NAMEPLATE_ALPHA_TOOLTIP, NumberCVarSetting("nameplateNotSelectedAlpha"), 0, 1, 0.05)
AddHeader(interface, CLASSICAPI_NUMBERS)
AddCheckbox(interface, CLASSICAPI_SEPARATE_LARGE_NUMBERS, CLASSICAPI_SEPARATE_LARGE_NUMBERS_TOOLTIP, CVarSetting("breakUpLargeNumbers"))
AddHeader(interface, CLASSICAPI_MOTION)
AddNumberBox(interface, CLASSICAPI_UI_SHAKE_STRENGTH, CLASSICAPI_UI_SHAKE_STRENGTH_TOOLTIP, NumberCVarSetting("ShakeStrengthUI"))
-- ---------------------------------------------------------------------------
-- Social
-- ---------------------------------------------------------------------------
local social = NewPage(SOCIAL_LABEL, main.name)
local function RegisterSocial()
local category, layout = Settings.RegisterVerticalLayoutCategory(SOCIAL_LABEL);
Settings.RegisterCategory(category);
-- C_AutoComplete reads these; the addon that shows the names does the rest.
AddHeader(social, CLASSICAPI_NAME_SUGGESTIONS)
AddCheckbox(social, CLASSICAPI_RECENT_WHISPERS_FIRST, CLASSICAPI_RECENT_WHISPERS_FIRST_TOOLTIP, CVarSetting("autoCompleteResortNamesOnRecency"))
AddCheckbox(social, CLASSICAPI_MATCH_INSIDE_NAMES, CLASSICAPI_MATCH_INSIDE_NAMES_TOOLTIP, CVarSetting("autoCompleteWhenEditingFromCenter"))
AddCheckbox(social, CLASSICAPI_MATCH_THE_COMMAND, CLASSICAPI_MATCH_THE_COMMAND_TOOLTIP, CVarSetting("autoCompleteUseContext"))
-- C_AutoComplete reads these; the addon that shows the names does the rest.
AddHeader(layout, CLASSICAPI_NAME_SUGGESTIONS);
AddCVarCheckbox(category, "autoCompleteResortNamesOnRecency", CLASSICAPI_RECENT_WHISPERS_FIRST, CLASSICAPI_RECENT_WHISPERS_FIRST_TOOLTIP);
AddCVarCheckbox(category, "autoCompleteWhenEditingFromCenter", CLASSICAPI_MATCH_INSIDE_NAMES, CLASSICAPI_MATCH_INSIDE_NAMES_TOOLTIP);
AddCVarCheckbox(category, "autoCompleteUseContext", CLASSICAPI_MATCH_THE_COMMAND, CLASSICAPI_MATCH_THE_COMMAND_TOOLTIP);
end
-- ---------------------------------------------------------------------------
-- Text To Speech
-- ---------------------------------------------------------------------------
local tts = NewPage(TEXT_TO_SPEECH, main.name)
local function RegisterTextToSpeech()
local category = Settings.RegisterVerticalLayoutCategory(TEXT_TO_SPEECH);
Settings.RegisterCategory(category);
AddDropDown(tts, TEXT_TO_SPEECH_VOICE_OPTION, TEXT_TO_SPEECH_VOICE_OPTION, NumberCVarSetting("ttsVoice"), function()
local choices = {}
for _, voice in ipairs(C_VoiceChat.GetTtsVoices()) do
table.insert(choices, { value = voice.voiceID, text = voice.name })
end
return choices
end)
AddSlider(tts, TEXT_TO_SPEECH_ADJUST_RATE, TEXT_TO_SPEECH_ADJUST_RATE, NumberCVarSetting("ttsSpeed"), -10, 10, 1)
AddSlider(tts, TEXT_TO_SPEECH_ADJUST_VOLUME, TEXT_TO_SPEECH_ADJUST_VOLUME, NumberCVarSetting("ttsVolume"), 0, 100, 1)
AddDropdown(category, "ttsVoice", TEXT_TO_SPEECH_VOICE_OPTION, TEXT_TO_SPEECH_VOICE_OPTION, function()
local choices = {};
for _, voice in ipairs(C_VoiceChat.GetTtsVoices()) do
table.insert(choices, { voice.voiceID, voice.name });
end
return choices;
end);
AddSlider(category, "ttsSpeed", TEXT_TO_SPEECH_ADJUST_RATE, TEXT_TO_SPEECH_ADJUST_RATE, -10, 10, 1);
AddSlider(category, "ttsVolume", TEXT_TO_SPEECH_ADJUST_VOLUME, TEXT_TO_SPEECH_ADJUST_VOLUME, 0, 100, 1);
end
-- ---------------------------------------------------------------------------
-- Advanced
-- ---------------------------------------------------------------------------
local advanced = NewPage(CLASSICAPI_ADVANCED, main.name)
local function RegisterAdvanced()
local category = Settings.RegisterVerticalLayoutCategory(CLASSICAPI_ADVANCED);
Settings.RegisterCategory(category);
AddCheckbox(advanced, CLASSICAPI_REMEMBER_PLAYERS, CLASSICAPI_REMEMBER_PLAYERS_TOOLTIP, rememberSetting)
AddNumberBox(advanced, CLASSICAPI_COMBAT_LOG_RETENTION, CLASSICAPI_COMBAT_LOG_RETENTION_TOOLTIP, NumberCVarSetting("combatLogRetentionTime"))
AddCheckbox(advanced, CLASSICAPI_SCRIPT_PROFILE, CLASSICAPI_SCRIPT_PROFILE_TOOLTIP, CVarSetting("scriptProfile"))
local function GetRemember()
return C_PlayerCache.IsEnabled() and true or false;
end
local function SetRemember(value)
C_PlayerCache.SetEnabled(value);
end
local remember = Settings.RegisterProxySetting(category, "PROXY_CLASSICAPI_REMEMBER_PLAYERS", Settings.VarType.Boolean, CLASSICAPI_REMEMBER_PLAYERS, false, GetRemember, SetRemember);
Settings.CreateCheckbox(category, remember, CLASSICAPI_REMEMBER_PLAYERS_TOOLTIP);
AddNumberBox(category, "combatLogRetentionTime", CLASSICAPI_COMBAT_LOG_RETENTION, CLASSICAPI_COMBAT_LOG_RETENTION_TOOLTIP);
AddCVarCheckbox(category, "scriptProfile", CLASSICAPI_SCRIPT_PROFILE, CLASSICAPI_SCRIPT_PROFILE_TOOLTIP);
end
SettingsRegistrar:AddRegistrant(function()
Settings.GetOrCreateSettingsGroup(nil, 1);
RegisterInteractKey();
RegisterActionTargeting();
RegisterCombat();
RegisterBags();
RegisterInterface();
RegisterSocial();
RegisterTextToSpeech();
RegisterAdvanced();
end);
@@ -0,0 +1,138 @@
-- Verbatim backport of retail's Blizzard_Settings_Shared/Blizzard_Category.lua.
SettingsCategoryMixin = {};
local idCounter = CreateCounter();
local securecallfunction = securecallfunction;
function SettingsCategoryMixin:Init(name)
self.subcategories = {};
self.ID = idCounter();
self.order = self.ID;
self:SetName(name);
end
function SettingsCategoryMixin:GetID()
return self.ID;
end
function SettingsCategoryMixin:GetName()
return self.name;
end
function SettingsCategoryMixin:SetName(name)
self.name = name;
end
function SettingsCategoryMixin:GetOrder()
return self.order;
end
function SettingsCategoryMixin:SetOrder(order)
self.order = order;
end
local function SecureGetQualifiedName(category)
local parentCategory = category:GetParentCategory();
if parentCategory then
return SETTINGS_SUBCATEGORY_FMT:format(category:GetName(), parentCategory:GetName());
end
return category:GetName();
end
function SettingsCategoryMixin:GetQualifiedName()
return securecallfunction(SecureGetQualifiedName, self);
end
local function SecureGetParentCategory(category)
return category.parentCategory;
end
function SettingsCategoryMixin:GetParentCategory()
return securecallfunction(SecureGetParentCategory, self);
end
function SettingsCategoryMixin:SetParentCategory(category)
self.parentCategory = category;
end
function SettingsCategoryMixin:HasParentCategory()
return self:GetParentCategory() ~= nil;
end
function SettingsCategoryMixin:SetCategorySet(categorySet)
self.categorySet = categorySet;
end
local function SecureGetCategorySet(category)
if category.categorySet then
return category.categorySet;
end
local parentCategory = category:GetParentCategory();
if parentCategory then
return parentCategory:GetCategorySet();
end
end
function SettingsCategoryMixin:GetCategorySet()
return securecallfunction(SecureGetCategorySet, self);
end
local function SecureGetSubcategories(category)
return category.subcategories;
end
function SettingsCategoryMixin:GetSubcategories()
return securecallfunction(SecureGetSubcategories, self);
end
function SettingsCategoryMixin:HasSubcategories()
return #self.subcategories > 0;
end
function SettingsCategoryMixin:CreateSubcategory(name, description)
local subcategory = Settings.CreateCategory(name, description);
subcategory:SetParentCategory(self);
table.insert(self.subcategories, subcategory);
return subcategory;
end
function SettingsCategoryMixin:SetCategoryTutorialInfo(tooltip, callback)
self.tutorial = {
tooltip = tooltip,
callback = callback,
};
end
local function SecureGetCategoryTutorialInfo(category)
return category.tutorial;
end
function SettingsCategoryMixin:GetCategoryTutorialInfo()
return securecallfunction(SecureGetCategoryTutorialInfo, self);
end
function SettingsCategoryMixin:SetExpanded(expanded)
self.expanded = expanded;
end
local function SecureIsExpanded(category)
return category.expanded;
end
function SettingsCategoryMixin:IsExpanded()
return securecallfunction(SecureIsExpanded, self);
end
local function SecureShouldSortAlphabetically(category)
return category.shouldSortAlphabetically;
end
function SettingsCategoryMixin:ShouldSortAlphabetically()
return securecallfunction(SecureShouldSortAlphabetically, self);
end
function SettingsCategoryMixin:SetShouldSortAlphabetically(should)
self.shouldSortAlphabetically = should;
end
@@ -0,0 +1,483 @@
-- Backport of retail's Blizzard_Settings_Shared/Blizzard_CategoryList.lua.
--
-- Differences from the retail source:
-- - Retail draws the group headers, the selected and hovered rows and the
-- expand toggle with atlases this client does not have. The rows use the
-- quest log's title highlights, the toggle uses the client's plus and
-- minus buttons, and a group header is a dark band (see below).
-- - No gamepad navigation and no narration: those systems do not exist
-- here.
-- - No "new" tags: nothing in this client is new, so the rows have no
-- NewFeature label to refresh.
-- - A game category registered without a group goes in a group with no
-- header. Retail puts it in the AddOns group, whose header would then
-- show on the game tab; retail's own game categories always name a group.
-- - GetOrCreateGroup sorts the groups by order every time, and takes a new
-- order for a group that exists. Retail sorts only when it makes a group,
-- and creates its game groups before any addon category exists; here the
-- addons' categories can come first. Groups of the same order keep the
-- order they were made in: table.sort is not stable, and a sort on every
-- call would move them each time a category is added.
local securecallfunction = securecallfunction;
local g_selectionBehavior;
-- The art that stands in for retail's Options_List_Active and
-- Options_List_Hover atlases.
local ROW_SELECTED_TEXTURE = "Interface\\QuestFrame\\UI-QuestLogTitleHighlight";
local ROW_HOVER_TEXTURE = "Interface\\QuestFrame\\UI-QuestTitleHighlight";
local function CreateHeaderInitializer(label, headerIndex)
local initializer = CreateFromMixins(ScrollBoxFactoryInitializerMixin);
initializer:Init("SettingsCategoryListHeaderTemplate");
initializer.data = { label = label, headerIndex = headerIndex };
return initializer;
end
local function CreateSpacerInitializer()
local initializer = CreateFromMixins(ScrollBoxFactoryInitializerMixin);
initializer:Init("SettingsCategoryListSpacerTemplate");
return initializer;
end
local CategoryButtonInitializerMixin = CreateFromMixins(ScrollBoxFactoryInitializerMixin);
local function CreateCategoryButtonInitializer(category, indent, categoryData)
local initializer = CreateFromMixins(CategoryButtonInitializerMixin);
initializer:Init("SettingsCategoryListButtonTemplate");
initializer.data = { category = category, indent = indent or 0, groupText = categoryData and categoryData.groupText };
return initializer;
end
SettingsCategoryListHeaderMixin = {};
-- Retail picks one of three Options_CategoryHeader atlases by headerIndex.
-- The band is the same for every header here.
function SettingsCategoryListHeaderMixin:Init(initializer)
self.Label:SetText(initializer.data.label);
self.Background:SetColorTexture(0, 0, 0, 0.5);
end
SettingsCategoryListButtonMixin = CreateFromMixins(ButtonStateBehaviorMixin);
function SettingsCategoryListButtonMixin:OnLoad()
self.Toggle:SetScript("OnClick", function(button, buttonName, down)
local initializer = self:GetElementData();
local category = initializer.data.category;
self:SetExpanded(not category:IsExpanded());
end);
end
function SettingsCategoryListButtonMixin:UpdateStateInternal(selected)
if selected then
self.Label:SetFontObject("GameFontHighlight");
self.Texture:SetTexture(ROW_SELECTED_TEXTURE);
self.Texture:Show();
else
local initializer = self:GetElementData();
local category = initializer.data.category;
local fontObject;
if category:HasParentCategory() then
fontObject = "GameFontHighlight";
else
fontObject = "GameFontNormal";
end
self.Label:SetFontObject(fontObject);
if self.over then
self.Texture:SetTexture(ROW_HOVER_TEXTURE);
self.Texture:Show();
else
self.Texture:Hide();
end
end
end
function SettingsCategoryListButtonMixin:OnButtonStateChanged()
self:UpdateStateInternal(g_selectionBehavior:IsSelected(self));
end
function SettingsCategoryListButtonMixin:Init(initializer)
local category = initializer.data.category;
self.Label:SetText(category:GetName());
self.Toggle:SetShown(category:HasSubcategories());
self:SetExpanded(category:IsExpanded());
self:SetSelected(g_selectionBehavior:IsSelected(self));
end
function SettingsCategoryListButtonMixin:SetSelected(selected)
self:UpdateStateInternal(selected);
end
-- Retail's toggle atlases are an open and a closed arrow; here the toggle
-- is a minus when the category is expanded and a plus when it is not.
function SettingsCategoryListButtonMixin:SetExpanded(expanded)
local initializer = self:GetElementData();
initializer.data.category:SetExpanded(expanded);
if expanded then
self.Toggle:SetNormalTexture("Interface\\Buttons\\UI-MinusButton-UP");
self.Toggle:SetPushedTexture("Interface\\Buttons\\UI-MinusButton-DOWN");
else
self.Toggle:SetNormalTexture("Interface\\Buttons\\UI-PlusButton-UP");
self.Toggle:SetPushedTexture("Interface\\Buttons\\UI-PlusButton-DOWN");
end
end
SettingsCategoryListMixin = CreateFromMixins(CallbackRegistryMixin);
SettingsCategoryListMixin:GenerateCallbackEvents(
{
"OnCategoryActivated",
"OnCategorySelected",
"OnCategoriesUpdated",
}
);
function SettingsCategoryListMixin:OnLoad()
CallbackRegistryMixin.OnLoad(self);
self.allCategories = {};
self.groups = {};
self.categorySet = Settings.CategorySet.Game;
local function Factory(factory, elementData)
local function Initializer(button, elementData)
elementData:InitFrame(button);
if elementData:IsTemplate("SettingsCategoryListButtonTemplate") then
local function SelectCategory()
if not g_selectionBehavior:IsSelected(button) then
g_selectionBehavior:Select(button);
self:TriggerEvent(SettingsCategoryListMixin.Event.OnCategorySelected, elementData.data.category);
PlaySound(SOUNDKIT.IG_MAINMENU_OPTION_CHECKBOX_ON);
end
end
button:SetScript("OnClick", SelectCategory);
local function OnToggle(button, buttonName, down)
self:CreateCategories();
end;
button.Toggle:RegisterCallback("OnClick", OnToggle, self);
end
end
elementData:Factory(factory, Initializer);
end
local function IndentCalculator(elementData)
return elementData.data and elementData.data.indent or 0;
end
-- The scroll box is anchored -50 so that the "new" label can appear without
-- being clipped. This offset moves the contents back into the desired position.
local leftPad = 50;
local pad = 0;
local spacing = 2;
local view = CreateScrollBoxListLinearView(pad, pad, leftPad, pad, spacing);
view:SetElementFactory(Factory);
view:SetElementIndentCalculator(IndentCalculator);
ScrollUtil.InitScrollBoxListWithScrollBar(self.ScrollBox, self.ScrollBar, view);
local scrollBoxAnchorsWithBar =
{
CreateAnchor("TOPLEFT", -leftPad, 0),
CreateAnchor("BOTTOMRIGHT", -16, 0);
};
local scrollBoxAnchorsWithoutBar =
{
scrollBoxAnchorsWithBar[1],
CreateAnchor("BOTTOMRIGHT", 0, 0);
};
ScrollUtil.AddManagedScrollBarVisibilityBehavior(self.ScrollBox, self.ScrollBar, scrollBoxAnchorsWithBar, scrollBoxAnchorsWithoutBar);
local function OnSelectionChanged(o, elementData, selected)
local button = self.ScrollBox:FindFrame(elementData);
if button then
button:SetSelected(selected);
end
if selected then
self.ScrollBox:ScrollToElementData(elementData, ScrollBoxConstants.AlignNearest);
end
end;
g_selectionBehavior = ScrollUtil.AddSelectionBehavior(self.ScrollBox);
g_selectionBehavior:RegisterCallback(SelectionBehaviorMixin.Event.OnSelectionChanged, OnSelectionChanged, self);
end
function SettingsCategoryListMixin:GetAllCategories()
return self.allCategories;
end
function SettingsCategoryListMixin:GetOrCreateGroup(groupText, order)
local index, tbl = FindInTableIf(self.groups, function(tbl)
return tbl.groupText == groupText;
end);
if not index then
tbl = {groupText=groupText, order=order or 10, categories={}, creationIndex=#self.groups + 1};
table.insert(self.groups, tbl);
elseif order then
tbl.order = order;
end
local function Sorter(lhs, rhs)
if lhs.order ~= rhs.order then
return lhs.order < rhs.order;
end
return lhs.creationIndex < rhs.creationIndex;
end
table.sort(self.groups, Sorter);
return tbl;
end
local function FindCategoryMatchingCategoryID(categoryID, category)
if category:GetID() == categoryID then
return category;
end
if category.subcategories then
for index, subcategory in ipairs(category.subcategories) do
local foundCategory = FindCategoryMatchingCategoryID(categoryID, subcategory);
if foundCategory then
return foundCategory;
end
end
end
return nil;
end
function SettingsCategoryListMixin:GetCategory(categoryID)
for _, tbl in ipairs(self.groups) do
for _, category in ipairs(tbl.categories) do
local foundCategory = securecallfunction(FindCategoryMatchingCategoryID, categoryID, category);
if foundCategory then
return foundCategory;
end
end
end
return nil;
end
local SETTING_GROUP_ADDONS = "AddOns";
function SettingsCategoryListMixin:AddCategoryInternal(category, group, addOn)
local hasParentCategory = securecallfunction(SettingsCategoryMixin.HasParentCategory, category);
if hasParentCategory then
-- FIXME Will replace when we're not building the whole category list on insert/removal.
self:CreateCategories();
return;
end
if group == nil and addOn then
group = SETTING_GROUP_ADDONS;
end
local tbl = self:GetOrCreateGroup(group);
tbl.categorySet = addOn and Settings.CategorySet.AddOns or Settings.CategorySet.Game;
category:SetCategorySet(tbl.categorySet);
local categories = tbl.categories;
table.insert(categories, category);
table.sort(categories, function(lhs, rhs)
return lhs:GetOrder() < rhs:GetOrder();
end);
self.allCategories = {};
for index, groupTbl in ipairs(self.groups) do
tAppendAll(self.allCategories, groupTbl.categories);
end
self:CreateCategories();
end
function SettingsCategoryListMixin:AddCategory(category, groupText, addon)
self:AddCategoryInternal(category, groupText, addon);
end
function SettingsCategoryListMixin:GetCurrentCategory()
return self.currentCategory;
end
function SettingsCategoryListMixin:FindCategoryElementData(category)
return self.ScrollBox:FindElementDataByPredicate(function(elementData)
-- Spacer has no data.
return elementData.data and (elementData.data.category == category);
end);
end
function SettingsCategoryListMixin:SetCurrentCategory(category)
self.currentCategory = category;
-- Ensure that our current category list set contains the category, otherwise select the required set.
self:SetCategorySet(category:GetCategorySet());
-- All parent categories in the hierarchy must be expanded. If a parent category was expanded or the current category
-- was already expanded, require the categories to be recreated. The latter is expected if the category was expanded
-- explicitly via OpenToCategory().
local recreateCategories = false;
local parentCategory = category:GetParentCategory();
while parentCategory ~= nil do
if not parentCategory:IsExpanded() then
parentCategory:SetExpanded(true);
recreateCategories = true;
end
parentCategory = parentCategory:GetParentCategory();
end
if recreateCategories or category:IsExpanded() then
self:CreateCategories();
end
-- Under normal circumstances we always expect the category to be found, however this can fail to be found
-- when initializing the settings categories for the first time.
local found = self:FindCategoryElementData(category);
if found then
g_selectionBehavior:SelectElementData(found);
end
return self:GetCategorySet();
end
function SettingsCategoryListMixin:SetCategorySet(categorySet)
assert(EnumUtil.IsValid(Settings.CategorySet, categorySet));
if self.categorySet ~= categorySet then
self.categorySet = categorySet;
self:CreateCategories();
end
end
function SettingsCategoryListMixin:GetCategorySet()
return self.categorySet;
end
local function SortCategoriesByName(lhs, rhs)
return strcmputf8i(lhs:GetName(), rhs:GetName()) < 0;
end
local function CreateSection(currentCategory, elementList, categories, canSort, indent, categoryData)
if canSort then
table.sort(categories, SortCategoriesByName);
end
for index, category in ipairs(categories) do
if not category.redirectCategory then
local initializer = CreateCategoryButtonInitializer(category, indent, categoryData);
table.insert(elementList, initializer);
if category == currentCategory then
g_selectionBehavior:SelectElementData(initializer);
end
if category:IsExpanded() then
canSort = category:ShouldSortAlphabetically();
CreateSection(currentCategory, elementList, category:GetSubcategories(), canSort, indent + 10, categoryData);
end
end
end
end
local function CreateGroup(currentCategory, elementList, categories, categorySet, headerCounter, groupText)
if categorySet == Settings.CategorySet.Game then
if groupText then
local headerIndex = ((headerCounter() - 1) % 3) + 1;
table.insert(elementList, CreateHeaderInitializer(groupText, headerIndex));
end
end
local categoryData = { groupText = groupText };
local canSort = categorySet == Settings.CategorySet.AddOns;
local indent = 0;
CreateSection(currentCategory, elementList, categories, canSort, indent, categoryData);
end
function SettingsCategoryListMixin:GenerateElementList()
local currentCategory = self:GetCurrentCategory();
local headerCounter = CreateCounter();
local categorySet = self:GetCategorySet();
local elementList = {};
local createSpacer = false;
for index, tbl in ipairs(self.groups) do
local groupText = tbl.groupText;
if tbl.categorySet == categorySet then
local categories = tbl.categories;
if createSpacer then
table.insert(elementList, CreateSpacerInitializer());
end
CreateGroup(currentCategory, elementList, categories, categorySet, headerCounter, groupText);
createSpacer = true;
end
end
return elementList;
end
function SettingsCategoryListMixin:CreateCategories()
self.elementList = self:GenerateElementList();
local categoryTotal = 0;
for _, elementData in ipairs(self.elementList) do
if elementData.data and elementData.data.category then
categoryTotal = categoryTotal + 1;
end
end
local categoryIndex = 0;
for _, elementData in ipairs(self.elementList) do
local categoryData = elementData.data;
if categoryData and categoryData.category then
categoryIndex = categoryIndex + 1;
categoryData.categoryIndex = categoryIndex;
categoryData.categoryTotal = categoryTotal;
end
end
local dataProvider = CreateDataProvider(self.elementList);
self.ScrollBox:SetDataProvider(dataProvider, ScrollBoxConstants.RetainScrollPosition);
self:TriggerEvent(self.Event.OnCategoriesUpdated);
end
function SettingsCategoryListMixin:GetFirstCategoryButton()
return self.ScrollBox:FindFrameByPredicate(function(button, elementData)
return elementData.frameTemplate == "SettingsCategoryListButtonTemplate";
end);
end
function SettingsCategoryListMixin:GetSelectedCategoryButton()
for _, elementData in ipairs(g_selectionBehavior:GetSelectedElementData()) do
if elementData.frameTemplate == "SettingsCategoryListButtonTemplate" then
return self.ScrollBox:FindFrame(elementData);
end
end
end
function SettingsCategoryListMixin:EnumerateCategoryButtons()
local frames = self.ScrollBox:GetFrames();
local index = 0;
local function Iterator()
while index < #frames do
index = index + 1;
local frame = frames[index];
local elementData = frame:GetElementData();
if elementData.frameTemplate == "SettingsCategoryListButtonTemplate" then
return frame;
end
end
end
return Iterator;
end
@@ -0,0 +1,89 @@
<Ui xmlns="http://www.blizzard.com/wow/ui/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.blizzard.com/wow/ui/ ..\FrameXML\UI.xsd">
<!--
Retail's Blizzard_Settings_Shared/Blizzard_CategoryList.xml.
Differences:
- The header band and the row highlight fill their frame: retail sizes
them from atlases this client does not have (Blizzard_CategoryList.lua
sets the art). The row highlight blends additively, as the quest log
draws the same art.
- No NewFeature label on the rows: nothing in this client is new.
- The toggle's textures have no names. 1.12 names a `$parent` region under
an unnamed frame after the nearest named ancestor, so every pooled row
would claim the same SettingsPanel... globals.
-->
<Frame name="SettingsCategoryListSpacerTemplate" virtual="true">
<Size y="18"/>
</Frame>
<Frame name="SettingsCategoryListTemplate" mixin="SettingsCategoryListMixin" virtual="true">
<Frames>
<Frame parentKey="ScrollBox" inherits="WowScrollBoxList">
<Anchors>
<!--Note this is overwritten by the managed scroll bar visibility behavior in OnLoad.-->
<Anchor point="TOPLEFT" x="-50" y="0"/>
<Anchor point="BOTTOMRIGHT"/>
</Anchors>
</Frame>
<EventFrame parentKey="ScrollBar" inherits="MinimalScrollBar">
<Anchors>
<Anchor point="TOPLEFT" relativeKey="$parent.ScrollBox" relativePoint="TOPRIGHT" x="0" y="2"/>
<Anchor point="BOTTOMLEFT" relativeKey="$parent.ScrollBox" relativePoint="BOTTOMRIGHT" x="-1" y="7"/>
</Anchors>
</EventFrame>
</Frames>
<Scripts>
<OnLoad method="OnLoad"/>
</Scripts>
</Frame>
<Frame name="SettingsCategoryListHeaderTemplate" mixin="SettingsCategoryListHeaderMixin" virtual="true">
<Size x="175" y="30"/>
<Layers>
<Layer level="ARTWORK">
<Texture parentKey="Background" setAllPoints="true"/>
</Layer>
<Layer level="OVERLAY">
<FontString parentKey="Label" inherits="GameFontHighlightMedium" justifyH="LEFT">
<Anchors>
<Anchor point="LEFT" x="20" y="-1"/>
</Anchors>
</FontString>
</Layer>
</Layers>
</Frame>
<Button name="SettingsCategoryListButtonTemplate" mixin="SettingsCategoryListButtonMixin" virtual="true">
<Size x="175" y="20"/>
<Frames>
<EventButton parentKey="Toggle" hidden="true">
<Size x="22" y="22"/>
<Anchors>
<Anchor point="LEFT" x="9"/>
</Anchors>
<NormalTexture file="Interface\Buttons\UI-MinusButton-UP"/>
<PushedTexture file="Interface\Buttons\UI-MinusButton-DOWN"/>
<HighlightTexture file="Interface\Buttons\UI-PlusButton-Hilight" alphaMode="ADD"/>
</EventButton>
</Frames>
<Layers>
<Layer level="BACKGROUND">
<Texture parentKey="Texture" alphaMode="ADD" setAllPoints="true"/>
</Layer>
<Layer level="ARTWORK">
<FontString parentKey="Label" inherits="GameFontNormal" justifyH="LEFT">
<Anchors>
<Anchor point="TOPLEFT" x="36" y="1"/>
<Anchor point="BOTTOMRIGHT" y="1"/>
</Anchors>
</FontString>
</Layer>
</Layers>
<Scripts>
<OnLoad method="OnLoad"/>
<OnEnter method="OnEnter"/>
<OnLeave method="OnLeave"/>
<OnMouseDown method="OnMouseDown"/>
<OnMouseUp method="OnMouseUp"/>
</Scripts>
</Button>
</Ui>
@@ -0,0 +1,57 @@
-- Backport of retail's Blizzard_Settings_Shared/Blizzard_Dialogs.lua.
--
-- Differences from the retail source:
-- - 1.12's StaticPopup has OnAccept for button1, OnCancel for button2 and,
-- on clients whose StaticPopup has a third button (Turtle's), OnAlt for
-- button3, which it shows between the other two. It has no
-- OnButton1..3 or selectCallbackByIndex, and Escape runs OnCancel as if
-- button2 was clicked. So button2 is always the choice that changes
-- nothing: the discard dialog's Apply and Exit is its button3. With the
-- third button both dialogs show retail's three choices in retail's
-- order. A client without it shows only the first two: the defaults
-- dialog then has no These Settings choice, and the discard dialog has no
-- Apply and Exit (the window's own Apply button still applies).
-- - No timed revert dialog: no revertable settings are ported (see
-- Blizzard_SettingsPanel.lua).
-- - No key binding reset dialog: there is no Keybindings category yet.
local function DefineGameSettingsApplyDefaultsDialog()
StaticPopupDialogs["GAME_SETTINGS_APPLY_DEFAULTS"] = {
text = CONFIRM_RESET_INTERFACE_SETTINGS,
button1 = ALL_SETTINGS,
button3 = CURRENT_SETTINGS,
button2 = CANCEL,
OnAccept = function()
SettingsPanel:SetAllSettingsToDefaults();
end,
OnAlt = function()
SettingsPanel:SetCurrentCategorySettingsToDefaults();
end,
OnCancel = function() end,
hideOnEscape = 1,
whileDead = 1,
timeout = 0,
}
end
local function DefineGameSettingsConfirmDiscardDialog()
StaticPopupDialogs["GAME_SETTINGS_CONFIRM_DISCARD"] = {
text = SETTINGS_CONFIRM_DISCARD,
button1 = SETTINGS_UNAPPLIED_EXIT,
button3 = SETTINGS_UNAPPLIED_APPLY_AND_EXIT,
button2 = SETTINGS_UNAPPLIED_CANCEL,
OnAccept = function()
SettingsPanel:ExitWithoutCommit();
end,
OnAlt = function()
SettingsPanel:ExitWithCommit();
end,
OnCancel = function() end,
hideOnEscape = 1,
whileDead = 1,
timeout = 0,
}
end
DefineGameSettingsApplyDefaultsDialog();
DefineGameSettingsConfirmDiscardDialog();
@@ -0,0 +1,463 @@
-- Backport of retail's Blizzard_Settings_Shared/Blizzard_Keybindings.lua.
--
-- Differences from the retail source:
-- - 1.12 sends a key to a frame only when the frame takes keyboard input,
-- so the listener turns keyboard input on while it listens. It has no
-- gamepad script: this client has no gamepad.
-- - 1.12 offers a key to the frames from the top stratum down, and an edit
-- box with the focus takes every key it is offered. A click does not take
-- the focus from a box. So the listener is in the FULLSCREEN_DIALOG
-- stratum, above the Settings window, and clears the focus when it starts
-- to listen: a number box on the same page would take the key otherwise.
-- - 1.12's GetBinding returns the action and its two keys, with no category
-- between them.
-- - 1.12 has no GetBindingFromClick, so the listener asks GetBindingAction
-- for the key chord the press makes.
-- - Binding text goes through 1.12's GetBindingText with the "KEY_" prefix
-- (see Util\BindingUtil.lua).
-- - No custom binding buttons: this client has no push-to-talk key, and
-- C_KeyBindings.GetCustomBindingType is always nil. So there is no
-- CustomBindingManager, SaveAllCustomBindings or Mac input dialog.
-- - A binding row lights the action button that the binding uses, found by
-- the 1.12 button names (ActionButton, MultiBar...Button,
-- PetActionButton, ShapeshiftButton). Retail finds retail's bars.
-- - The label takes no mouse, so a cut-off name shows no tooltip: 1.12 font
-- strings have no scripts.
-- - No "new" tag and no gamepad navigation.
KeybindListener = CreateFrame("Button");
KeybindListener:SetFrameStrata("FULLSCREEN_DIALOG");
function KeybindListener:OnKeyDown(key)
self:ProcessInput(key);
end
function KeybindListener:OnClick(key)
end
function KeybindListener:OnMouseWheel(delta)
self:OnKeyDown(delta > 0 and "MOUSEWHEELUP" or "MOUSEWHEELDOWN");
end
function KeybindListener:OnForwardMouseWheel(delta)
if self:IsListening() then
self:OnMouseWheel(delta);
return true;
end
return false;
end
function KeybindListener:SetListening(listen)
self:EnableKeyboard(listen);
if listen then
local focus = GetCurrentKeyBoardFocus();
if focus then
focus:ClearFocus();
end
self:SetScript("OnKeyDown", self.OnKeyDown);
self:SetScript("OnClick", self.OnClick);
self:SetScript("OnMouseWheel", self.OnMouseWheel);
else
self:SetScript("OnKeyDown", nil);
self:SetScript("OnClick", nil);
self:SetScript("OnMouseWheel", nil);
end
end
function KeybindListener:StartListening(action, slotIndex)
self.pending = { action = action, slotIndex = slotIndex };
self:SetListening(true);
EventRegistry:TriggerEvent("KeybindListener.StartedListening", action, slotIndex);
end
function KeybindListener:StopListening()
if not self:IsListening() then
return;
end
local oldAction, oldSlotIndex = nil;
if self.pending then
oldAction = self.pending.action;
oldSlotIndex = self.pending.slotIndex;
end
self.pending = nil;
self:SetListening(false);
EventRegistry:TriggerEvent("KeybindListener.StoppedListening", oldAction, oldSlotIndex);
end
function KeybindListener:IsListening()
return self.pending ~= nil;
end
local function ClearBindingsForKeys(bindingContext, ...)
for i = 1, select("#", ...) do
local key = select(i, ...);
if key then
SetBinding(key, nil, bindingContext);
end
end
end
local function GetBindingFromClick(input)
return GetBindingAction(CreateKeyChordStringUsingMetaKeyState(GetConvertedKeyOrButton(input)));
end
function KeybindListener:ProcessInput(input)
local pending = self.pending;
if not pending then
return false;
end
local currentAction = GetBindingFromClick(input);
if currentAction == "SCREENSHOT" then
RunBinding("SCREENSHOT");
return false;
end
local action = pending.action;
if input == "ESCAPE" and currentAction == "TOGGLEGAMEMENU" then
self:StopListening();
return false;
end
local key = GetConvertedKeyOrButton(input);
if IsKeyPressIgnoredForBinding(key) then
return false;
end
self:StopListening();
local bindingContext = C_KeyBindings.GetBindingContextForAction(action);
-- Unbind the current action
local slotIndex = pending.slotIndex;
local key1, key2 = GetBindingKey(action, nil, bindingContext);
ClearBindingsForKeys(bindingContext, key1, key2);
local newKey = CreateKeyChordStringUsingMetaKeyState(key);
local unbindUnconflicted, unbindSlotIndex, unbindAction = self:UnbindKey(newKey, action);
local rebindSuccess = self:RebindKeysInOrder(newKey, slotIndex, action, key1, key2);
if not unbindUnconflicted then
EventRegistry:TriggerEvent("KeybindListener.UnbindFailed", action, unbindAction, unbindSlotIndex);
elseif not rebindSuccess then
EventRegistry:TriggerEvent("KeybindListener.RebindFailed", action);
else
EventRegistry:TriggerEvent("KeybindListener.RebindSuccess", action);
end
return true;
end
function KeybindListener:UnbindKey(newKey, action)
local bindingContext = C_KeyBindings.GetBindingContextForAction(action);
local conflicted, conflictedSlotIndex;
local oldAction = GetBindingAction(newKey, nil, bindingContext);
if oldAction ~= "" and oldAction ~= action then
local key1, key2 = GetBindingKey(oldAction, nil, bindingContext);
if key1 == newKey and key2 then
conflicted = true;
conflictedSlotIndex = 1;
elseif (not key1 or key1 == newKey) and (not key2 or key2 == newKey) then
conflicted = true;
conflictedSlotIndex = 2;
end
end
SetBinding(newKey, nil, bindingContext);
return not conflicted, conflictedSlotIndex, oldAction;
end
function KeybindListener:Commit()
SaveBindings(GetCurrentBindingSet());
end
function KeybindListener:ClearActionPrimaryBinding()
if not self:IsListening() then
return;
end
local action = self.pending.action;
local bindingContext = C_KeyBindings.GetBindingContextForAction(action);
local key1, key2 = GetBindingKey(action, nil, bindingContext);
if key1 then
SetBinding(key1, nil, bindingContext);
end
if key2 then
SetBinding(key2, action, bindingContext);
end
end
function KeybindListener:SetBinding(newKey, action, oldKey)
local bindingContext = C_KeyBindings.GetBindingContextForAction(action);
local failed = nil;
if not SetBinding(newKey, action, bindingContext) then
if oldKey then
SetBinding(oldKey, action, bindingContext);
end
failed = true;
end
return not failed;
end
function KeybindListener:RebindKeysInOrder(key, slotIndex, action, ...)
local failed = nil;
for i = 1, select("#", ...) do
local currentKey = select(i, ...);
local keyToBind = (i == slotIndex) and key or currentKey;
if keyToBind then
if not self:SetBinding(keyToBind, action, currentKey) then
failed = true;
end
end
end
return not failed;
end
function KeybindListener:ResetBindingsToDefault()
PlaySound(SOUNDKIT.IG_MAINMENU_OPTION_CHECKBOX_ON);
self:StopListening();
LoadBindings(Enum.BindingSet.Default);
SaveBindings(GetCurrentBindingSet());
end
KeyBindingFrameBindingTemplateMixin = {};
local KeyBindingFrameBindingTemplateEvents = {
"UPDATE_BINDINGS",
};
function KeyBindingFrameBindingTemplateMixin:OnLoad()
self.cbrHandles = Settings.CreateCallbackHandleContainer();
end
function KeyBindingFrameBindingTemplateMixin:OnShow()
FrameUtil.RegisterFrameForEvents(self, KeyBindingFrameBindingTemplateEvents);
end
function KeyBindingFrameBindingTemplateMixin:OnHide()
FrameUtil.UnregisterFrameForEvents(self, KeyBindingFrameBindingTemplateEvents);
end
function KeyBindingFrameBindingTemplateMixin:OnEvent(event)
if event == "UPDATE_BINDINGS" then
self:RenewBindings();
end
end
function KeyBindingFrameBindingTemplateMixin:OnHighlightBinding(showHighlight)
self.Highlight:SetShown(showHighlight);
end
function KeyBindingFrameBindingTemplateMixin:DetermineHighlightFrame()
local bindingIndex = self.initializer.data.bindingIndex;
local action = GetBinding(bindingIndex);
local actionButton = string.match(action, "^ACTIONBUTTON(%d+)");
if actionButton then
return _G["ActionButton" .. actionButton];
end
local multiActionBar, multiActionButton = string.match(action, "^MULTIACTIONBAR(%d+)BUTTON(%d+)");
if multiActionBar and multiActionButton then
local bars = {
"MultiBarBottomLeft",
"MultiBarBottomRight",
"MultiBarRight",
"MultiBarLeft",
};
local bar = bars[tonumber(multiActionBar)];
if bar then
return _G[bar .. "Button" .. multiActionButton];
end
end
local petActionButton = string.match(action, "^BONUSACTIONBUTTON(%d+)");
if petActionButton then
return _G["PetActionButton" .. petActionButton];
end
local stanceActionButton = string.match(action, "^SHAPESHIFTBUTTON(%d+)");
if stanceActionButton then
return _G["ShapeshiftButton" .. stanceActionButton];
end
return nil;
end
function KeyBindingFrameBindingTemplateMixin:OnEnter()
local highlightFrame = self:DetermineHighlightFrame();
if highlightFrame then
self.highlightFrame = highlightFrame;
highlightFrame:EnableDrawLayer("HIGHLIGHT");
end
end
function KeyBindingFrameBindingTemplateMixin:OnLeave()
if self.highlightFrame then
self.highlightFrame:DisableDrawLayer("HIGHLIGHT");
self.highlightFrame = nil;
end
end
function KeyBindingFrameBindingTemplateMixin:UpdateBindingState(initializer)
local bindingIndex = initializer.data.bindingIndex;
local action, binding1, binding2 = GetBinding(bindingIndex);
for index, button in ipairs(self.Buttons) do
button:SetSelected(initializer.selectedIndex == index);
end
BindingButtonTemplate_SetupBindingButton(binding1, self.Button1);
BindingButtonTemplate_SetupBindingButton(binding2, self.Button2);
end
function KeyBindingFrameBindingTemplateMixin:Init(initializer)
self.initializer = initializer;
local bindingIndex = initializer.data.bindingIndex;
local action = GetBinding(bindingIndex);
local bindingName = GetBindingName(action);
local labelIndent = (initializer.data.search and 37) or 37;
self.Label:SetPoint("LEFT", labelIndent, 0);
self.Label:SetText(bindingName);
self.Button1:SetParent(self);
self.Button2:SetParent(self);
self.Button1:Show();
self.Button2:Enable();
local function InitializeKeyBindingButtonTooltip(index)
local key = select(index, GetBindingKey(action));
if key then
Settings.InitTooltip(KEY_BINDING_NAME_AND_KEY:format(bindingName, GetBindingText(key, "KEY_")), KEY_BINDING_TOOLTIP);
end
end
for index, button in ipairs(self.Buttons) do
button:SetScript("OnClick", function(button, buttonName, down)
if buttonName == "LeftButton" then
local oldSelected = initializer.selectedIndex == index;
KeybindListener:StopListening();
if not oldSelected then
initializer.selectedIndex = index;
button:SetSelected(true);
KeybindListener:StartListening(action, index);
end
elseif buttonName == "RightButton" then
local unbindKey = select(index, GetBindingKey(action));
if unbindKey then
SetBinding(unbindKey, nil, C_KeyBindings.GetBindingContextForAction(action));
SettingsTooltip:Hide();
SettingsPanel:ClearOutputText();
end
else
KeybindListener:ProcessInput(buttonName);
return;
end
end);
button:SetTooltipFunc(GenerateClosure(InitializeKeyBindingButtonTooltip, index));
button:SetCustomTooltipAnchoring(button, "ANCHOR_RIGHT", 0, 0);
end
self.cbrHandles:RegisterCallback(EventRegistry, "Settings.ReparentBindingsToInputBlocker", self.ReparentBindingsToInputBlocker, self);
self.cbrHandles:RegisterCallback(EventRegistry, "Settings.UnparentBindingsToInputBlocker", self.UnparentBindingsToInputBlocker, self);
self.cbrHandles:RegisterCallback(EventRegistry, "Settings.UpdateKeybinds", self.RenewBindings, self);
self:UpdateBindingState(initializer);
if self.highlightHandle then
self.highlightHandle:Unregister();
end
self.highlightHandle = ActionButtonBindingHighlightCallbackRegistry:RegisterCallbackWithHandle(action, self.OnHighlightBinding, self);
end
function KeyBindingFrameBindingTemplateMixin:ReparentBindingsToInputBlocker(inputBlocker)
if self:IsShown() then
if self.Button1:IsShown() then
self.Button1:SetParent(inputBlocker);
end
if self.Button2:IsShown() then
self.Button2:SetParent(inputBlocker);
end
end
end
function KeyBindingFrameBindingTemplateMixin:UnparentBindingsToInputBlocker(inputBlocker)
self.Button1:SetParent(self);
self.Button2:SetParent(self);
end
function KeyBindingFrameBindingTemplateMixin:Release()
self.Button1:SetParent(self);
self.Button2:SetParent(self);
self.cbrHandles:Unregister();
end
function KeyBindingFrameBindingTemplateMixin:RenewBindings()
self:ClearSelections();
self:UpdateBindingState(self.initializer);
end
function KeyBindingFrameBindingTemplateMixin:ClearSelections()
self.initializer.selectedIndex = nil;
for index, button in ipairs(self.Buttons) do
button:SetSelected(false);
end
end
function CreateKeybindingEntryInitializer(bindingIndex, search)
local data = {bindingIndex = bindingIndex, search = search};
local initializer = Settings.CreateElementInitializer("KeyBindingFrameBindingTemplate", data);
local oldMatchesSearchTags = initializer.MatchesSearchTags;
initializer.GetBindingText = function(self, bindingIndex, actionIndex)
local action, binding1, binding2 = GetBinding(bindingIndex);
if actionIndex == 1 then
return GetBindingText(binding1, "KEY_");
else
return GetBindingText(binding2, "KEY_");
end
end;
initializer.MatchesSearchTags = function(self, words)
local result = oldMatchesSearchTags(self, words);
if result then
return result;
end
local bindingIndex = self.data.bindingIndex;
for actionIndex = 1, 2 do
local bindingText = self:GetBindingText(bindingIndex, actionIndex):upper();
for _, word in ipairs(words) do
local first, last = string.find(bindingText, word, nil, true);
if first and last then
return last - first;
end
end
end
return nil;
end;
return initializer;
end
KeyBindingButtonMixin = CreateFromMixins(DefaultTooltipMixin);
function KeyBindingButtonMixin:SetSelected(selected)
self.SelectedHighlight:SetShown(selected);
self:GetHighlightTexture():SetAlpha(selected and 0 or 1);
end
function KeyBindingButtonMixin:OnLoad()
self:RegisterForClicks("AnyUp");
end
@@ -0,0 +1,88 @@
<Ui xmlns="http://www.blizzard.com/wow/ui/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.blizzard.com/wow/ui/ ..\FrameXML\UI.xsd">
<!--
Retail's Blizzard_Settings_Shared/Blizzard_Keybindings.xml.
Differences:
- A binding button is 1.12's panel button (UIPanelButtonTemplate).
Retail's UIMenuButtonStretchTemplate and its UI-Silver-Button art do not
exist here. 1.12's Key Bindings window uses UIPanelButtonTemplate2, but
that template anchors its middle slice by the name $parentLeft, and a
pooled row has no name of its own. The selected key shows the panel
button's highlight.
- The label takes no mouse: 1.12 font strings have no scripts, so a cut-off
binding name shows no tooltip.
- No NewFeature label, because nothing in this client is new.
-->
<Button name="KeyBindingFrameBindingButtonTemplate" inherits="UIPanelButtonTemplate" mixin="KeyBindingButtonMixin" virtual="true">
<Layers>
<Layer level="OVERLAY">
<Texture parentKey="SelectedHighlight" file="Interface\Buttons\UI-Panel-Button-Highlight" alphaMode="ADD" setAllPoints="true" hidden="true">
<TexCoords left="0" right="0.625" top="0" bottom="0.6875"/>
</Texture>
</Layer>
</Layers>
<Scripts>
<OnLoad method="OnLoad"/>
</Scripts>
<NormalFont inherits="GameFontHighlightSmall"/>
<DisabledFont inherits="GameFontDisableSmall"/>
<HighlightFont inherits="GameFontHighlightSmall"/>
</Button>
<Button name="KeyBindingFrameBindingButtonTemplateWithLabel" inherits="KeyBindingFrameBindingButtonTemplate" virtual="true">
<Layers>
<Layer level="BACKGROUND">
<FontString parentKey="KeyLabel" inherits="GameFontNormalSmall">
<Anchors>
<Anchor point="BOTTOMLEFT" relativePoint="TOPLEFT" x="4" y="5" />
</Anchors>
</FontString>
</Layer>
</Layers>
</Button>
<Frame name="KeyBindingFrameBindingTemplate" mixin="KeyBindingFrameBindingTemplateMixin" enableMouse="true" virtual="true">
<Size x="560" y="25"/>
<Layers>
<Layer level="BACKGROUND">
<FontString parentKey="Label" inherits="GameFontNormal" wordwrap="false" justifyH="LEFT">
<Size x="170" y="24"/>
</FontString>
<Texture parentKey="Highlight" hidden="true">
<Anchors>
<Anchor point="TOPLEFT"/>
<Anchor point="BOTTOMRIGHT" x="-5"/>
</Anchors>
<Color a="0.1" r="1" g="1" b="1"/>
</Texture>
</Layer>
</Layers>
<Frames>
<Button parentKey="Button1" parentArray="Buttons" inherits="KeyBindingFrameBindingButtonTemplate">
<KeyValues>
<KeyValue key="SlotIndex" value="1" type="number"/>
</KeyValues>
<Size x="160" y="22"/>
<Anchors>
<Anchor point="LEFT" relativePoint="CENTER" x="-80"/>
</Anchors>
</Button>
<Button parentKey="Button2" parentArray="Buttons" inherits="KeyBindingFrameBindingButtonTemplate">
<KeyValues>
<KeyValue key="SlotIndex" value="2" type="number"/>
</KeyValues>
<Size x="160" y="22"/>
<Anchors>
<Anchor point="LEFT" relativeKey="$parent.Button1" relativePoint="RIGHT"/>
</Anchors>
</Button>
</Frames>
<Scripts>
<OnLoad method="OnLoad"/>
<OnShow method="OnShow"/>
<OnHide method="OnHide"/>
<OnEvent method="OnEvent"/>
<OnEnter method="OnEnter"/>
<OnLeave method="OnLeave"/>
</Scripts>
</Frame>
</Ui>
@@ -0,0 +1,61 @@
-- Backport of retail's Blizzard_Settings_Shared/Blizzard_Registration.lua,
-- with the two other places retail joins the Settings window to the game's
-- UI: the Escape handler (retail registers SettingsPanel_EscapePressed in
-- Blizzard_SettingsDefinitions_Frame/Interface.lua) and the game menu entry
-- (Blizzard_GameMenu).
--
-- Differences from the retail source:
-- - 1.12 has no RegisterUIPanel. A panel's attributes are its entry in
-- UIPanelWindows, which ShowUIPanel reads. 1.12's panel manager has no
-- checkFit attribute.
-- - This file loads only on the game screen, so the glue-screen test is gone.
-- - 1.12 has no game menu Escape handlers. Escape reaches ToggleGameMenu,
-- so ToggleGameMenu closes the window, after any dialog over it, the way
-- retail's handler order does.
-- - The game menu entry is an AddOn Options button: the client keeps its
-- own option buttons, which open its own option windows.
UIPanelWindows["SettingsPanel"] =
{
area = "center",
pushable = 0,
whileDead = 1,
};
local ToggleGameMenu_Orig = ToggleGameMenu;
function ToggleGameMenu(clicked)
if not clicked and SettingsPanel:IsShown() then
if not StaticPopup_EscapePressed() then
SettingsPanel_EscapePressed();
end
return;
end
ToggleGameMenu_Orig(clicked);
end
-- Goes right above Key Bindings. Stock anchors Key Bindings under Interface
-- Options and Turtle under its single Options button, so the new button takes
-- over whatever anchor Key Bindings has and Key Bindings moves under it.
--
-- The splice waits for the menu's first show. Other addons insert their own
-- buttons the same way -- ShaguTweaks anchors "Advanced Options" under
-- Interface Options and moves Key Bindings under it -- and they load after
-- us. Splicing at load time would claim the slot first, and the later addon
-- would anchor its button on the same spot as ours. By the first show every
-- addon has placed its buttons, so ours goes into the chain as it stands.
local menuButton = CreateFrame("Button", "GameMenuButtonAddOnOptions", GameMenuFrame, "GameMenuButtonTemplate");
menuButton:SetText(ADDON_OPTIONS);
local spliced;
GameMenuFrame:HookScript("OnShow", function()
if spliced then return end
spliced = true;
local point, relativeTo, relativePoint, x, y = GameMenuButtonKeybindings:GetPoint();
menuButton:SetPoint(point, relativeTo, relativePoint, x, y);
GameMenuButtonKeybindings:ClearAllPoints();
GameMenuButtonKeybindings:SetPoint(point, menuButton, relativePoint, x, y);
GameMenuFrame:SetHeight(GameMenuFrame:GetUnscaledHeight() + menuButton:GetUnscaledHeight() - y);
end);
menuButton:SetScript("OnClick", function()
PlaySound("igMainMenuOption");
SettingsPanel:Open();
end);
@@ -0,0 +1,447 @@
-- Verbatim backport of retail's Blizzard_Settings_Shared/Blizzard_Setting.lua.
local function GetOrCallDefaultValue(defaultValue)
if type(defaultValue) == "function" then
return defaultValue();
end
return defaultValue;
end
local function GetDefaultValueType(defaultValue)
return type(GetOrCallDefaultValue(defaultValue));
end
local function GetOrCallName(name)
if type(name) == "function" then
return name();
end
return name;
end
local function GetNameType(name)
return type(GetOrCallName(name));
end
local function EnsureVariableTypeIsValid(variableType, defaultValue)
if variableType == nil then
assert(defaultValue ~= nil);
variableType = GetDefaultValueType(defaultValue);
end
return variableType;
end
local function ErrorIfInvalidSettingArguments(name, variable, variableType, defaultValue)
local nameType = GetNameType(name);
if nameType ~= "string" then
error(string.format("'name' for variable '%s' requires string type or a function that returns a string.", variable));
end
if type(variable) ~= "string" then
error(string.format("'variable' for '%s' requires string type.", name));
end
if type(variableType) ~= "string" then
error(string.format("'variableType' for '%s', '%s' requires string type.", name, variable));
end
if (defaultValue ~= nil) then
local defaultVariableType = GetDefaultValueType(defaultValue);
if defaultVariableType ~= variableType then
error(string.format("'defaultValue' argument for '%s', '%s' variable type '%s' doesn't match default value type '%s'.", name, variable, variableType, defaultVariableType));
end
end
end
local function ErrorIfInvalidVariableType(name, value, variableType)
if type(value) ~= variableType then
error(string.format("SetValue '%s' requires '%s' type, not '%s' type.", name, variableType, type(value)));
end
end
local function ValuesApproximatelyEqual(v1, v2)
if type(v1) == "number" and type(v2) == "number" then
return ApproximatelyEqual(v1, v2);
end
return v1 == v2;
end
SettingMixin = {};
function SettingMixin:Init(name, variable, variableType)
self.name = name;
self.variable = variable;
self.variableType = variableType;
self.commitFlags = Settings.CommitFlag.None;
self.ignoreApplyOverride = nil;
end
function SettingMixin:GetName()
return self:GetNameDerived();
end
function SettingMixin:GetVariable()
return self.variable;
end
function SettingMixin:GetVariableType()
return self.variableType;
end
function SettingMixin:GetValue()
if self.pendingValue ~= nil then
return self.pendingValue;
end
local currentValue = self:GetValueDerived();
return currentValue;
end
-- 'immediate' is expected when committing applyable values or forcing
-- a value such as in cases like choosing defaults or reassigning a value
-- in the process of doing a revert.
function SettingMixin:SetValue(value, immediate)
-- Stops reentrancy. For example, assigning a cvar setting triggers a CVAR_UPDATE
-- event that causes the settings system to try and update this setting.
if self:IsLocked() then
return;
end
if immediate or not (self:HasCommitFlag(Settings.CommitFlag.Apply)) then
self:ApplyValue(value);
else
local currentValue = self:GetValueDerived();
if ValuesApproximatelyEqual(currentValue, value) then
-- Discard the pending value to return it to it's original state.
self:ClearPendingValue();
else
-- The value is pending write by the commit step.
self:SetPendingValue(value);
end
-- Notify so that controls can display this value.
self:TriggerValueChanged(value);
end
end
function SettingMixin:ApplyValue(value)
self:ClearPendingValue();
local currentValue = self:GetValueDerived();
if currentValue ~= value then
ErrorIfInvalidVariableType(self.name, value, self.variableType);
self:SetLocked(true);
self:SetValueDerived(value);
self:SetLocked(false);
end
self:TriggerValueChanged(value);
end
function SettingMixin:SetValueToDefault()
local defaultValue = self:GetDefaultValueDerived();
if defaultValue == nil then
return false;
end
self:ApplyValue(defaultValue);
return true;
end
function SettingMixin:Commit()
if self.pendingValue ~= nil then
self:ApplyValue(self.pendingValue);
else
assertsafe(false, "Tried to commit setting '%s' without a pending value.", self.name);
end
end
function SettingMixin:SetPendingValue(value)
self.pendingValue = value;
end
function SettingMixin:ClearPendingValue()
self.pendingValue = nil;
self.lockPendingValue = false;
end
-- Revert discards the pending value and then notifies listeners to read
-- the current value again.
function SettingMixin:Revert()
if self.lockPendingValue then
return false;
end
self:ClearPendingValue();
self:NotifyUpdate();
end
-- Informs any listeners the value changed and it's current value needs to be read again.
-- This is only called externally in cases where the underlying value changed was a source other than the
-- setting object. A good example here is the Self Highlight option in unit popups, where the set of options
-- described on the setting is less granular than that displayed in the popup context menu. The context menu
-- changes the underlying cvars that then need to be reevaluated by the setting.
function SettingMixin:NotifyUpdate()
local currentValue = self:GetValueDerived();
self:TriggerValueChanged(currentValue);
end
-- If a dependent setting has its value changed, any value changed callbacks may
-- try to revert other settings with the intention of obtaining a new valid display value.
-- It doesn't distinguish between reinitialization and a value being changed due to the commit step.
-- This is called at the beginning of the commit process to ensure all settings have their
-- pending values retained until the commit is done.
function SettingMixin:LockPendingValue()
self.lockPendingValue = true;
end
function SettingMixin:GetCommitOrder()
return self.commitOrder or 0;
end
function SettingMixin:SetCommitOrder(order)
self.commitOrder = order;
end
function SettingMixin:SetCommitFlags(...)
for index = 1, select("#", ...) do
self:AddCommitFlag(select(index, ...));
end
end
function SettingMixin:AddCommitFlag(flag)
self.commitFlags = bit.bor(self.commitFlags, flag);
end
function SettingMixin:RemoveCommitFlag(flag)
if self:HasCommitFlag(flag) then
self.commitFlags = bit.bxor(self.commitFlags, flag);
end
end
function SettingMixin:HasCommitFlag(flag)
return bit.band(self.commitFlags, flag) > 0;
end
function SettingMixin:SetIgnoreApplyOverride(state)
self.ignoreApplyOverride = state;
end
function SettingMixin:UpdateIgnoreApplyFlag()
if self.ignoreApplyOverride == true then
self:AddCommitFlag(Settings.CommitFlag.IgnoreApply);
elseif self.ignoreApplyOverride == false then
self:RemoveCommitFlag(Settings.CommitFlag.IgnoreApply);
end
end
function SettingMixin:IsModified()
if self.pendingValue == nil then
return false;
end
local currentValue = self:GetValueDerived();
local equal = ValuesApproximatelyEqual(currentValue, self.pendingValue);
return not equal;
end
function SettingMixin:GetDefaultValue()
return self:GetDefaultValueDerived();
end
function SettingMixin:SetLocked(locked)
self.locked = locked;
end
function SettingMixin:IsLocked()
return self.locked;
end
function SettingMixin:TriggerValueChanged(value)
SettingsCallbackRegistry:TriggerEvent(self.variable, self, value);
end
function SettingMixin:SetValueChangedCallback(callback)
Settings.SetOnValueChangedCallback(self.variable, function(_, setting, value)
callback(setting, value);
end);
end
CVarSettingMixin = CreateFromMixins(SettingMixin);
function CVarSettingMixin:Init(name, cvar, variableType)
ErrorIfInvalidSettingArguments(name, cvar, variableType);
SettingMixin.Init(self, name, cvar, variableType);
local cvarAccessor = CreateCVarAccessor(cvar, variableType);
self.GetValueDerived = function(self)
local value = cvarAccessor:GetValue();
return self:TransformValue(value);
end;
self.SetValueDerived = function(self, value)
value = self:TransformValue(value);
cvarAccessor:SetValue(value);
end
self.GetNameDerived = function(self)
return securecallfunction(GetOrCallName, name);
end;
self.GetDefaultValueDerived = function(self)
local value = cvarAccessor:GetDefaultValue();
return self:TransformValue(value);
end
-- SetValue is deliberately type strict. ConvertValueInternal is exposed for the
-- settings system to convert cvar values to the expected type.
self.ConvertValueInternal = function(self, value)
return cvarAccessor:ConvertValue(value);
end
end
function CVarSettingMixin:TransformValue(value)
if self.valueTransformer then
return self.valueTransformer(value);
end
return value;
end
do
-- Add additional transforms as necessary so it's not necessary to create ProxySettings just
-- to remap inbound and outbound values. May be moved to SettingMixin if other setting types
-- can take advantage of this. See VoiceVADSensitivity as an example for another transform.
local function NegateBoolean(value)
return not value;
end
function CVarSettingMixin:NegateBoolean()
assert(self.variableType == Settings.VarType.Boolean);
self.valueTransformer = NegateBoolean;
end
end
ProxySettingMixin = CreateFromMixins(SettingMixin);
do
local function SecureGetValueDerived(setting)
return setting.getValue();
end
local function SecureSetValueDerived(setting, value)
setting.setValue(value);
end
function ProxySettingMixin:Init(name, variable, variableType, defaultValue, getValue, setValue)
variableType = EnsureVariableTypeIsValid(variableType, defaultValue);
ErrorIfInvalidSettingArguments(name, variable, variableType, defaultValue);
SettingMixin.Init(self, name, variable, variableType);
self.getValue = getValue;
self.setValue = setValue;
self.GetValueDerived = function(self)
return securecallfunction(SecureGetValueDerived, self);
end;
self.SetValueDerived = function(self, value)
securecallfunction(SecureSetValueDerived, self, value);
end;
self.GetNameDerived = function(self)
return securecallfunction(GetOrCallName, name);
end;
self.GetDefaultValueDerived = function(self)
return securecallfunction(GetOrCallDefaultValue, defaultValue);
end;
end
end
ModifiedClickSettingMixin = CreateFromMixins(SettingMixin);
function ModifiedClickSettingMixin:Init(name, modifier, defaultValue)
SettingMixin.Init(self, name, modifier, Settings.VarType.String);
self.GetValueDerived = function(self)
return GetModifiedClick(modifier);
end;
self.SetValueDerived = function(self, value)
SetModifiedClick(modifier, value);
end;
self.GetNameDerived = function(self)
return securecallfunction(GetOrCallName, name);
end;
self.GetDefaultValueDerived = function(self)
return securecallfunction(GetOrCallDefaultValue, defaultValue);
end;
self:SetCommitFlags(Settings.CommitFlag.SaveBindings);
end
AddOnSettingMixin = CreateFromMixins(SettingMixin);
--[[
'variable' uniquely identifies your setting and must not conflict with any addons. Prefixing this identifier
with your addon name is highly recommended.
'variableKey' is your value's key in your saved variable table.
'variableTbl' is your saved variable table hopefully defined in your addon's .toc.
]]--
do
local function SecureSetVariableTblDefaultValue(variableKey, variableTbl, defaultValue)
if variableTbl[variableKey] == nil then
variableTbl[variableKey] = defaultValue;
end
end
local function SecureGetValueDerived(setting)
return setting.variableTbl[setting.variableKey];
end
local function SecureSetValueDerived(setting, value)
setting.variableTbl[setting.variableKey] = value;
return value;
end
function AddOnSettingMixin:Init(name, variable, variableKey, variableTbl, variableType, defaultValue)
variableType = EnsureVariableTypeIsValid(variableType, defaultValue);
SettingMixin.Init(self, name, variable, variableType);
assert(type(variableTbl) == "table", "'variableTbl' argument must be a table.");
self.variableKey = variableKey;
self.variableTbl = variableTbl;
self.defaultValue = defaultValue;
--[[
The argument 'variableTbl' is passed in by the inbound attribute handler and is therefore secure.
However, any table access will taint execution and must be done through secure call wrappers.
]]--
securecallfunction(SecureSetVariableTblDefaultValue, variableKey, variableTbl, defaultValue);
self.GetValueDerived = function(self)
return securecallfunction(SecureGetValueDerived, self);
end;
self.SetValueDerived = function(self, value)
securecallfunction(SecureSetValueDerived, self, value);
end;
self.GetNameDerived = function(self)
return securecallfunction(GetOrCallName, name);
end;
self.GetDefaultValueDerived = function(self)
return securecallfunction(GetOrCallDefaultValue, defaultValue);
end;
end
end
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,221 @@
<Ui xmlns="http://www.blizzard.com/wow/ui/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.blizzard.com/wow/ui/ ..\FrameXML\UI.xsd">
<!--
Retail's Blizzard_Settings_Shared/Blizzard_SettingControls.xml.
Differences:
- No NewFeature labels, because nothing in this client is new.
- The checkbox is 1.12's (UI-CheckBox): the checkbox-minimal atlases are
art this client does not have.
- The dropdown is WowStyle1DropdownTemplate, 1.12's dropdown art, where
retail's is WowStyle2DropdownTemplate's atlases. Its label font is
GameFontHighlightMedium: this client has no GameFontHighlightMed2.
- The expandable section's bar is a dark fill with the quest log's
highlight on hover: the Options_ListExpand atlases are art this
client does not have.
-->
<Texture name="HoverBackgroundTemplate" virtual="true" hidden="true">
<Anchors>
<Anchor relativeKey="$parent.$parent" point="TOPLEFT" x="-10"/>
<Anchor relativeKey="$parent.$parent" point="BOTTOMRIGHT" x="-5"/>
</Anchors>
<Color a="0.1" r="1" g="1" b="1"/>
</Texture>
<Frame name="SettingsListSectionHeaderTemplate" mixin="SettingsListSectionHeaderMixin" virtual="true">
<Size y="45"/>
<Layers>
<Layer level="OVERLAY">
<FontString parentKey="Title" inherits="GameFontHighlightLarge" justifyH="LEFT" justifyV="TOP">
<Anchors>
<Anchor point="TOPLEFT" x="7" y="-16"/>
</Anchors>
</FontString>
</Layer>
</Layers>
<Scripts>
<OnLoad method="OnLoad"/>
<OnEvent method="OnEvent"/>
</Scripts>
</Frame>
<Frame name="SettingsAddOnDisabledLabelTemplate" virtual="true">
<Size y="30"/>
<Layers>
<Layer level="OVERLAY">
<FontString parentKey="Text" inherits="GameFontRed" text="ADDON_DISABLED" justifyH="LEFT" justifyV="TOP">
<Anchors>
<Anchor point="TOPLEFT" x="37" y="0"/>
</Anchors>
</FontString>
</Layer>
</Layers>
</Frame>
<Frame name="SettingsListElementTemplate" mixin="SettingsListElementMixin" virtual="true">
<Layers>
<Layer level="OVERLAY">
<FontString parentKey="Text" inherits="GameFontNormal" justifyH="LEFT" wordwrap="false"/>
</Layer>
</Layers>
<Frames>
<Frame parentKey="Tooltip" mixin="DefaultTooltipMixin">
<Anchors>
<Anchor point="TOPLEFT"/>
<Anchor point="BOTTOMRIGHT" relativePoint="BOTTOM" x="-80"/>
</Anchors>
<Layers>
<Layer level="BACKGROUND">
<Texture parentKey="HoverBackground" inherits="HoverBackgroundTemplate"/>
</Layer>
</Layers>
<Scripts>
<OnLoad method="OnLoad"/>
</Scripts>
</Frame>
</Frames>
</Frame>
<CheckButton name="SettingsCheckboxTemplate" mixin="SettingsCheckboxMixin" motionScriptsWhileDisabled="true" virtual="true">
<Size x="30" y="29"/>
<Layers>
<Layer level="BACKGROUND">
<Texture parentKey="HoverBackground" inherits="HoverBackgroundTemplate"/>
</Layer>
</Layers>
<Scripts>
<OnLoad method="OnLoad"/>
<OnEnter method="OnEnter"/>
<OnLeave method="OnLeave"/>
</Scripts>
<NormalTexture file="Interface\Buttons\UI-CheckBox-Up"/>
<PushedTexture file="Interface\Buttons\UI-CheckBox-Down"/>
<HighlightTexture file="Interface\Buttons\UI-CheckBox-Highlight" alphaMode="ADD"/>
<CheckedTexture file="Interface\Buttons\UI-CheckBox-Check"/>
<DisabledCheckedTexture file="Interface\Buttons\UI-CheckBox-Check-Disabled"/>
</CheckButton>
<!-- NOTE: Original template is a Frame, but this one is a Button -->
<Button name="SettingsColorSwatchTemplate" inherits="ColorSwatchTemplate" mixin="SettingsColorSwatchMixin" motionScriptsWhileDisabled="true" virtual="true">
<Scripts>
<OnLoad method="OnLoad"/>
<OnEnter method="OnEnter"/>
<OnLeave method="OnLeave"/>
</Scripts>
</Button>
<Frame name="SettingsCheckboxControlTemplate" inherits="SettingsListElementTemplate" mixin="SettingsCheckboxControlMixin" virtual="true">
<Size x="280" y="26"/>
<Scripts>
<OnLoad method="OnLoad"/>
</Scripts>
</Frame>
<Frame name="SettingsSliderControlTemplate" inherits="SettingsListElementTemplate" mixin="SettingsSliderControlMixin" virtual="true">
<Size x="280" y="26"/>
<Scripts>
<OnLoad method="OnLoad"/>
</Scripts>
</Frame>
<Frame name="SettingsDropdownControlTemplate" inherits="SettingsListElementTemplate" mixin="SettingsDropdownControlMixin" virtual="true">
<Size x="280" y="26"/>
<Scripts>
<OnLoad method="OnLoad"/>
<OnEvent method="OnEvent"/>
</Scripts>
</Frame>
<Frame name="SettingButtonControlTemplate" inherits="SettingsListElementTemplate" mixin="SettingsButtonControlMixin" virtual="true">
<Size x="280" y="26"/>
<Scripts>
<OnLoad method="OnLoad"/>
</Scripts>
</Frame>
<Frame name="SettingsColorSwatchControlTemplate" inherits="SettingsListElementTemplate" mixin="SettingsColorSwatchControlMixin" virtual="true">
<Size x="280" y="26"/>
<Scripts>
<OnLoad method="OnLoad"/>
</Scripts>
</Frame>
<Frame name="SettingsCheckboxWithButtonControlTemplate" inherits="SettingsListElementTemplate" mixin="SettingsCheckboxWithButtonControlMixin" virtual="true">
<Size x="280" y="26"/>
<Scripts>
<OnLoad method="OnLoad"/>
</Scripts>
</Frame>
<Frame name="SettingsCheckboxSliderControlTemplate" inherits="SettingsListElementTemplate" mixin="SettingsCheckboxSliderControlMixin" virtual="true">
<Size x="280" y="26"/>
<Scripts>
<OnLoad method="OnLoad"/>
</Scripts>
</Frame>
<Frame name="SettingsCheckboxDropdownControlTemplate" inherits="SettingsListElementTemplate" mixin="SettingsCheckboxDropdownControlMixin" virtual="true">
<Size x="280" y="26"/>
<Scripts>
<OnLoad method="OnLoad"/>
</Scripts>
</Frame>
<Frame name="SettingsCheckboxWithColorSwatchControlTemplate" inherits="SettingsListElementTemplate" mixin="SettingsCheckboxWithColorSwatchControlMixin" virtual="true">
<Size x="280" y="26"/>
<Scripts>
<OnLoad method="OnLoad"/>
</Scripts>
</Frame>
<Frame name="Metal2DropdownWithSteppersAndLabelTemplate" inherits="DropdownWithSteppersTemplate" mixin="DropdownWithSteppersAndLabelMixin" virtual="true">
<Frames>
<DropdownButton parentKey="Dropdown" inherits="WowStyle1DropdownTemplate">
<Anchors>
<Anchor point="CENTER"/>
</Anchors>
</DropdownButton>
</Frames>
<Layers>
<Layer level="ARTWORK">
<FontString parentKey="Label" inherits="GameFontHighlightMedium">
<Anchors>
<Anchor point="RIGHT" relativeKey="$parent.DecrementButton" relativePoint="LEFT" x="-34"/>
</Anchors>
</FontString>
</Layer>
</Layers>
</Frame>
<!-- Retained for ease of replacing all dropdown + stepper combos that are used across Settings-->
<Frame name="SettingsDropdownWithButtonsTemplate" inherits="Metal2DropdownWithSteppersAndLabelTemplate" virtual="true"/>
<EventFrame name="SettingsExpandableSectionTemplate" mixin="SettingsExpandableSectionMixin" virtual="true">
<Size y="25"/>
<Frames>
<Button parentKey="Button">
<Size y="30"/>
<Anchors>
<Anchor point="TOPLEFT" x="0" y="0"/>
<Anchor point="TOPRIGHT" x="-20" y="0"/>
</Anchors>
<Layers>
<Layer level="BACKGROUND">
<Texture parentKey="Background" setAllPoints="true">
<Color r="0" g="0" b="0" a="0.5"/>
</Texture>
</Layer>
<Layer level="OVERLAY">
<FontString parentKey="Text" inherits="GameFontNormal" justifyH="CENTER">
<Anchors>
<Anchor point="LEFT" x="21" y="2"/>
</Anchors>
</FontString>
</Layer>
</Layers>
<HighlightTexture file="Interface\QuestFrame\UI-QuestTitleHighlight" alphaMode="ADD"/>
</Button>
</Frames>
<Scripts>
<OnLoad method="OnLoad"/>
</Scripts>
</EventFrame>
</Ui>
@@ -0,0 +1,728 @@
-- Backport of retail's Blizzard_Settings_Shared/Blizzard_Settings.lua.
--
-- Differences from the retail source:
-- - Binding text goes through 1.12's GetBindingText with the "KEY_"
-- prefix, which retail's GetBindingText uses by itself (see
-- Util\BindingUtil.lua).
-- - GetOrCreateSettingsGroup hands its order to the category list, which
-- sorts the groups again (Blizzard_CategoryList.lua).
--[[
Names native types for clarity of use as function arguments.
RegisterSetting(..., nil, "boolean", true);
RegisterSetting(..., Settings.VarType.Bool, Settings.Defaults.True)
--]]
Settings =
{
CannotDefault = nil,
};
Settings.VarType =
{
Boolean = "boolean",
String = "string",
Number = "number",
};
Settings.Default =
{
True = true,
False = false,
};
Settings.CategorySet = EnumUtil.MakeEnum("Game", "AddOns");
-- Used for adding different types of controls to SettingsControlTextContainerMixin.
Settings.ControlType = EnumUtil.MakeEnum("Radio", "Checkbox");
Settings.CommitFlag = FlagsUtil.MakeFlags(
"ClientRestart",
"GxRestart",
"UpdateWindow",
"SaveBindings",
"Revertable",
"Apply",
"IgnoreApply",
"KioskProtected",
"UIReload"
);
Settings.CommitFlag.None = 0;
SettingsCallbackRegistry = CreateFromMixins(CallbackRegistryMixin);
SettingsCallbackRegistry:SetUndefinedEventsAllowed(true);
SettingsCallbackRegistry:GenerateCallbackEvents(
{
"OnValueChanged",
}
);
SettingsCallbackRegistry:OnLoad();
SettingsSearchableElementMixin = {};
function SettingsSearchableElementMixin:AddSearchTags(...)
if not self.searchTags then
self.searchTags = {};
end
for index = 1, select("#", ...) do
local tag = select(index, ...);
if type(tag) == "string" and tag ~= "" then
table.insert(self.searchTags, tag:upper());
end
end
end
function SettingsSearchableElementMixin:MatchesSearchTags(words)
if self.searchTags then
for _, val1 in ipairs(words) do
for _, val2 in ipairs(self.searchTags) do
local first, last = string.find(val2, val1, nil, true);
if first and last then
return last - first;
end
end
end
end
return nil;
end
function SettingsSearchableElementMixin:SetSearchIgnoredInLayout(layout)
if not self.searchIgnoredLayouts then
self.searchIgnoredLayouts = {};
end
table.insert(self.searchIgnoredLayouts, layout);
end
function SettingsSearchableElementMixin:IsSearchIgnoredInLayout(layout)
if not self.searchIgnoredLayouts then
return false;
end
return tContains(self.searchIgnoredLayouts, layout);
end
function SettingsSearchableElementMixin:AddShownPredicate(func)
if not self.shownPredicates then
self.shownPredicates = {};
end
table.insert(self.shownPredicates, func);
end
function SettingsSearchableElementMixin:GetShownPredicates()
return self.shownPredicates;
end
function SettingsSearchableElementMixin:ShouldShow()
local prereqs = self:GetShownPredicates();
if prereqs then
for index, prereq in ipairs(prereqs) do
if not prereq() then
return false;
end
end
end
return true;
end
function Settings.CreateCategory(name)
local category = CreateFromMixins(SettingsCategoryMixin);
category:Init(name);
return category;
end
function Settings.AssignLayoutToCategory(category, layout)
SettingsInbound.AssignLayoutToCategory(category, layout);
end
function Settings.RegisterCategory(category, group)
local addon = false;
SettingsInbound.RegisterCategory(category, group, addon);
end
function Settings.RegisterAddOnCategory(category)
local addon = true;
local group = nil;
SettingsInbound.RegisterCategory(category, group, addon);
end
function Settings.SetKeybindingsCategory(category)
SettingsInbound.SetKeybindingsCategory(category);
end
function Settings.OpenToCategory(categoryID, scrollToElementName)
C_SettingsUtil.OpenSettingsPanel(categoryID, scrollToElementName);
end
function Settings.SafeLoadBindings(bindingSet)
if not C_Glue.IsOnGlueScreen() then
LoadBindings(bindingSet);
end
end
function Settings.RegisterVerticalLayoutCategory(name)
return SettingsInbound.RegisterVerticalLayoutCategory(name);
end
function Settings.RegisterVerticalLayoutSubcategory(parentCategory, name)
return SettingsInbound.RegisterVerticalLayoutSubcategory(parentCategory, name);
end
function Settings.RegisterCanvasLayoutCategory(frame, name)
return SettingsInbound.RegisterCanvasLayoutCategory(frame, name);
end
function Settings.RegisterCanvasLayoutSubcategory(parentCategory, frame, name)
return SettingsInbound.RegisterCanvasLayoutSubcategory(parentCategory, frame, name);
end
function Settings.RegisterInitializer(category, initializer)
SettingsInbound.RegisterInitializer(category, initializer);
end
function Settings.RegisterAddOnSetting(categoryTbl, variable, variableKey, variableTbl, variableType, name, defaultValue)
return SettingsInbound.CreateAddOnSetting(categoryTbl, name, variable, variableKey, variableTbl, variableType, defaultValue);
end
function Settings.RegisterProxySetting(categoryTbl, variable, variableType, name, defaultValue, getValue, setValue)
return SettingsInbound.CreateProxySetting(categoryTbl, name, variable, variableType, defaultValue, getValue, setValue);
end
function Settings.RegisterCVarSetting(categoryTbl, variable, variableType, name)
local setting = CreateAndInitFromMixin(CVarSettingMixin, name, variable, variableType);
SettingsInbound.RegisterSetting(categoryTbl, setting);
return setting;
end
function Settings.RegisterModifiedClickSetting(categoryTbl, variable, name, defaultValue)
local setting = CreateAndInitFromMixin(ModifiedClickSettingMixin, name, variable, defaultValue);
SettingsInbound.RegisterSetting(categoryTbl, setting);
return setting;
end
function Settings.AssignTutorialToCategory(category, tooltip, callback)
SettingsInbound.AssignTutorialToCategory(category, tooltip, callback);
end
function Settings.GetCategory(name)
return SettingsPanel:GetCategory(name);
end
function Settings.GetSetting(variable)
return SettingsPanel:GetSetting(variable);
end
function Settings.NotifyUpdate(variable)
local setting = Settings.GetSetting(variable);
if setting then
setting:NotifyUpdate();
end
end
function Settings.GetValue(variable)
local setting = Settings.GetSetting(variable);
if setting then
return setting:GetValue();
-- Uncomment to find any code accessing settings before they've been registered.
-- Unretrievable values are not necessarily an error, depend on race conditions, and need
-- to be evaluated on a case by case basis.
--else
-- error(string.format("Setting for variable '%s' did not exist.", variable))
end
return nil;
end
function Settings.SetValue(variable, value, force)
local setting = Settings.GetSetting(variable);
if setting then
setting:SetValue(value, force);
else
error(string.format("Setting for variable '%s' did not exist.", variable))
end
end
local SettingsControlTextContainerMixin = {};
function SettingsControlTextContainerMixin:Init()
self.data = {};
end
function SettingsControlTextContainerMixin:GetData()
return self.data;
end
local function CreateTextContainerData(value, label, tooltip, controlType)
return {text = label, label = label, tooltip = tooltip, value = value, controlType = controlType };
end
function SettingsControlTextContainerMixin:Add(value, label, tooltip)
local data = CreateTextContainerData(value, label, tooltip, Settings.ControlType.Radio);
table.insert(self.data, data);
return data;
end
function SettingsControlTextContainerMixin:AddCheckbox(value, label, tooltip)
local data = CreateTextContainerData(value, label, tooltip, Settings.ControlType.Checkbox);
table.insert(self.data, data);
return data;
end
function Settings.CreateControlTextContainer()
local container = CreateFromMixins(SettingsControlTextContainerMixin);
container:Init();
return container;
end
function Settings.GetCVarMask(cvar, enumGroup, enumValueOffset)
local bitOffset = enumValueOffset or 1;
local mask = 0;
for _, enumValue in pairs(enumGroup) do
if enumValue > 0 and GetCVarBitfield(cvar, enumValue) then
mask = bit.bor(mask, bit.lshift(1, enumValue - bitOffset));
end
end
return mask;
end
function Settings.WrapTooltipWithBinding(tooltipString, action)
return function()
local bindingKey = GetBindingKey(action);
if bindingKey and bindingKey ~= "" then
local bindingText = NORMAL_FONT_COLOR:WrapTextInColorCode(GetBindingText(bindingKey, "KEY_"));
return string.format("%s (%s)", tooltipString, bindingText);
end
return tooltipString;
end
end
function Settings.InitTooltip(name, tooltip)
GameTooltip_AddHighlightLine(SettingsTooltip, name);
if tooltip then
if type(tooltip) == "function" then
GameTooltip_AddNormalLine(SettingsTooltip, tooltip());
else
GameTooltip_AddNormalLine(SettingsTooltip, tooltip);
end
end
end
SettingsSliderOptionsMixin = {};
function SettingsSliderOptionsMixin:SetLabelFormatter(labelType, value)
if not self.formatters then
self.formatters = {};
end
self.formatters[labelType] = CreateMinimalSliderFormatter(labelType, value);
end
function Settings.CreateSliderOptions(minValue, maxValue, rate)
local options = CreateFromMixins(SettingsSliderOptionsMixin);
options.minValue = minValue or 0;
options.maxValue = maxValue or 1;
options.steps = (rate and (maxValue - minValue) / rate) or 100;
return options;
end
function Settings.CreateModifiedClickOptions(tooltips, mustChooseKey)
local function GetOptions(options)
local container = Settings.CreateControlTextContainer();
container:Add("ALT", ALT_KEY, tooltips[1]);
container:Add("CTRL", CTRL_KEY, tooltips[2]);
container:Add("SHIFT", SHIFT_KEY, tooltips[3]);
if not mustChooseKey then
container:Add("NONE", NONE_KEY, tooltips[4]);
end
return container:GetData();
end
return GetOptions;
end
function Settings.CreateSettingInitializerData(setting, options, tooltip)
local data =
{
setting = setting,
name = setting:GetName(),
options = options or {},
tooltip = tooltip,
};
return data;
end
function Settings.CreateElementInitializer(frameTemplate, data)
return SettingsInbound.CreateElementInitializer(frameTemplate, data);
end
function Settings.CreateSettingInitializer(frameTemplate, data)
local initializer = SettingsInbound.CreateSettingInitializer(frameTemplate, data);
-- Marks this as a countable setting for narration index calculation.
initializer.isSettingElement = true;
return initializer;
end
function Settings.CreatePanelInitializer(frameTemplate, data)
return SettingsInbound.CreatePanelInitializer(frameTemplate, data);
end
function Settings.CreateControlInitializer(frameTemplate, setting, options, tooltip)
local data = Settings.CreateSettingInitializerData(setting, options, tooltip);
return Settings.CreateSettingInitializer(frameTemplate, data);
end
function Settings.CreateCheckboxInitializer(setting, options, tooltip)
assert(setting:GetVariableType() == "boolean");
return Settings.CreateControlInitializer("SettingsCheckboxControlTemplate", setting, options, tooltip);
end
function Settings.CreateSliderInitializer(setting, options, tooltip)
assert((setting:GetVariableType() == "number") and (options ~= nil));
return Settings.CreateControlInitializer("SettingsSliderControlTemplate", setting, options, tooltip);
end
function Settings.CreateDropdownInitializer(setting, options, tooltip)
assert(options ~= nil);
return Settings.CreateControlInitializer("SettingsDropdownControlTemplate", setting, options, tooltip);
end
function Settings.CreateColorSwatchInitializer(setting, options, tooltip)
return Settings.CreateControlInitializer("SettingsColorSwatchControlTemplate", setting, options, tooltip);
end
local function AddInitializerToLayout(category, initializer)
local layout = SettingsPanel:GetLayout(category);
layout:AddInitializer(initializer);
end
function Settings.CreateCheckbox(category, setting, tooltip)
return Settings.CreateCheckboxWithOptions(category, setting, nil, tooltip);
end
function Settings.CreateCheckboxWithOptions(category, setting, options, tooltip)
local initializer = Settings.CreateCheckboxInitializer(setting, options, tooltip);
AddInitializerToLayout(category, initializer);
return initializer;
end
function Settings.CreateColorSwatch(category, setting, tooltip, options)
local initializer = Settings.CreateColorSwatchInitializer(setting, options, tooltip);
AddInitializerToLayout(category, initializer);
return initializer;
end
function Settings.CreateSlider(category, setting, options, tooltip)
local initializer = Settings.CreateSliderInitializer(setting, options, tooltip);
AddInitializerToLayout(category, initializer);
return initializer;
end
function Settings.CreateDropdown(category, setting, options, tooltip)
local initializer = Settings.CreateDropdownInitializer(setting, options, tooltip);
AddInitializerToLayout(category, initializer);
return initializer;
end
function Settings.CreateOptionsInitTooltip(setting, name, tooltip, options, initializer)
if initializer and initializer.noTooltip then
return function() end
end
local function InitTooltip()
Settings.InitTooltip(name, tooltip);
local optionData = type(options) == 'function' and options() or options;
local default = setting:GetDefaultValue();
local warningOption = nil;
local defaultOption = nil;
for _, option in ipairs(optionData) do
local isDefault = option.value == default;
if isDefault then
defaultOption = option;
end
if option.warning then
warningOption = option;
end
if option.tooltip or option.disabled then
GameTooltip_AddBlankLineToTooltip(SettingsTooltip);
local optionTooltip = nil;
local optionLabel = nil;
if option.disabled then
optionLabel = DISABLED_FONT_COLOR:WrapTextInColorCode(option.label);
else
optionLabel = HIGHLIGHT_FONT_COLOR:WrapTextInColorCode(option.label);
end
if option.tooltip then
if option.disabled then
optionTooltip = DISABLED_FONT_COLOR:WrapTextInColorCode(option.tooltip);
elseif isDefault and option.recommend then
optionTooltip = GREEN_FONT_COLOR:WrapTextInColorCode(option.tooltip);
else
optionTooltip = NORMAL_FONT_COLOR:WrapTextInColorCode(option.tooltip);
end
GameTooltip_AddDisabledLine(SettingsTooltip, string.format("%s: %s", optionLabel, optionTooltip));
else
GameTooltip_AddDisabledLine(SettingsTooltip, string.format("%s:", optionLabel));
end
if option.disabled then
GameTooltip_AddErrorLine(SettingsTooltip, option.disabled);
end
end
end
if defaultOption and defaultOption.recommend then
GameTooltip_AddBlankLineToTooltip(SettingsTooltip);
local coloredLabel = GREEN_FONT_COLOR:WrapTextInColorCode(defaultOption.label);
GameTooltip_AddHighlightLine(SettingsTooltip, string.format("%s: %s", VIDEO_OPTIONS_RECOMMENDED, coloredLabel));
end
if warningOption and warningOption.value == setting:GetValue() then
GameTooltip_AddBlankLineToTooltip(SettingsTooltip);
GameTooltip_AddNormalLine(SettingsTooltip, WARNING_FONT_COLOR:WrapTextInColorCode(warningOption.warning));
end
if setting:HasCommitFlag(Settings.CommitFlag.ClientRestart) then
GameTooltip_AddBlankLineToTooltip(SettingsTooltip);
GameTooltip_AddErrorLine(SettingsTooltip, VIDEO_OPTIONS_NEED_CLIENTRESTART);
end
if setting:HasCommitFlag(Settings.CommitFlag.UIReload) then
GameTooltip_AddBlankLineToTooltip(SettingsTooltip);
GameTooltip_AddErrorLine(SettingsTooltip, VIDEO_OPTIONS_NEED_UIRELOAD);
end
if initializer and initializer.additionalTooltipText then
GameTooltip_AddBlankLineToTooltip(SettingsTooltip);
GameTooltip_AddColoredLine(SettingsTooltip, initializer.additionalTooltipText, GREEN_FONT_COLOR);
end
end
return InitTooltip;
end
function Settings.CreateDropdownButton(rootDescription, optionData, isSelected, setSelected)
local optionDescription = rootDescription:CreateHighlightRadio(optionData.label, isSelected, setSelected, optionData, optionData.onEnter);
MenuUtil.SetElementText(optionDescription, optionData.text);
return optionDescription;
end
function Settings.CreateDropdownCheckbox(rootDescription, optionData, isSelected, setSelected)
local optionsDescription = rootDescription:CreateCheckbox(optionData.label, isSelected, setSelected, optionData);
MenuUtil.SetElementText(optionsDescription, optionData.text);
if optionData.displayCheckboxTooltip and optionData.tooltip then
optionsDescription:SetTooltip(function(tooltip, elementDescription)
GameTooltip_SetTitle(tooltip, optionData.label);
GameTooltip_AddNormalLine(tooltip, optionData.tooltip);
end);
end
-- Move checkboxes in options dropdowns a bit further from the left side of the dropdown than normal.
local function CheckBoxInitializer(frame, description, menu)
frame.leftTexture1:SetPoint("LEFT", frame, "LEFT", 4, 0);
end
optionsDescription:AddInitializer(CheckBoxInitializer);
return optionDescription;
end
function Settings.CreateDropdownOptionInserter(setting, optionsFunc, initializer)
local function Inserter(setting, rootDescription)
for index, optionData in ipairs(optionsFunc()) do
if optionData.controlType == Settings.ControlType.Radio then
local function IsSelected(optionData)
return setting:GetValue() == optionData.value;
end
local function SetSelected(optionData)
return setting:SetValue(optionData.value);
end
Settings.CreateDropdownButton(rootDescription, optionData, IsSelected, SetSelected);
elseif optionData.controlType == Settings.ControlType.Checkbox then
local function IsSelected(optionData)
local settingMask = setting:GetValue();
local optionMask = bit.lshift(1, optionData.value - (optionData.enumValueOffset or 1));
return bit.band(settingMask, optionMask) ~= 0;
end
local function SetSelected(optionData)
local settingMask = setting:GetValue();
local optionMask = bit.lshift(1, optionData.value - (optionData.enumValueOffset or 1));
local newMask = bit.bxor(settingMask, optionMask);
setting:SetValue(newMask);
end
Settings.CreateDropdownCheckbox(rootDescription, optionData, IsSelected, SetSelected);
else
assertsafe(false, "Unhandled control type %s for optionData.", tostring(optionData.controlType));
end
end
if initializer.customOptionHandler then
initializer.customOptionHandler(rootDescription);
end
end
return Inserter;
end
function Settings.InitDropdown(dropdown, setting, elementInserter, initTooltip, initializer)
-- The setting may have been backed by a lazy initializer that doesn't return correctly
-- the first time it is called, so it's called again.
local settingValue = setting:GetValue();
if settingValue == nil then
settingValue = setting:GetValue();
end
assertsafe(settingValue ~= nil, ("Missing value for setting '%s'"):format(setting:GetName()));
dropdown:SetDefaultText(CUSTOM);
if (initializer and initializer.customMenuGenerator) then
dropdown:SetupMenu(initializer.customMenuGenerator);
else
dropdown:SetupMenu(function(dropdown, rootDescription)
rootDescription:SetGridMode(MenuConstants.VerticalGridDirection);
elementInserter(setting, rootDescription);
end);
end
dropdown:SetTooltipFunc(initTooltip);
dropdown:SetDefaultTooltipAnchors();
dropdown:SetScript("OnEnter", function()
ButtonStateBehaviorMixin.OnEnter(dropdown);
DefaultTooltipMixin.OnEnter(dropdown);
end);
dropdown:SetScript("OnLeave", function()
ButtonStateBehaviorMixin.OnLeave(dropdown);
DefaultTooltipMixin.OnLeave(dropdown);
end);
end
function Settings.SetupCVarCheckbox(category, variable, label, tooltip)
local setting = Settings.RegisterCVarSetting(category, variable, "boolean", label);
local initializer = Settings.CreateCheckbox(category, setting, tooltip);
return setting, initializer;
end
function Settings.SetupCVarSlider(category, variable, options, label, tooltip)
local setting = Settings.RegisterCVarSetting(category, variable, "number", label);
local initializer = Settings.CreateSlider(category, setting, options, tooltip);
return setting, initializer;
end
function Settings.SetupCVarDropdown(category, variable, variableType, options, label, tooltip)
local setting = Settings.RegisterCVarSetting(category, variable, variableType, label);
local initializer = Settings.CreateDropdown(category, setting, options, tooltip);
return setting, initializer;
end
function Settings.SetupModifiedClickDropdown(category, variable, defaultKey, label, tooltips, tooltip, mustChooseKey)
local options = Settings.CreateModifiedClickOptions(tooltips, mustChooseKey);
local setting = Settings.RegisterModifiedClickSetting(category, variable, label, defaultKey);
local initializer = Settings.CreateDropdown(category, setting, options, tooltip);
return setting, initializer;
end
function Settings.SetupCVarColorSwatch(category, variable, label, tooltip)
local setting = Settings.RegisterCVarSetting(category, variable, "string", label);
local initializer = Settings.CreateColorSwatch(category, setting, tooltip);
return setting, initializer;
end
function Settings.CreateCVarAccessorClosures(cvar, variableType)
local cvarAccessor = CreateCVarAccessor(cvar, variableType);
local getValue = GenerateClosure(cvarAccessor.GetValue, cvarAccessor);
local setValue = GenerateClosure(cvarAccessor.SetValue, cvarAccessor);
local getDefaultValue = GenerateClosure(cvarAccessor.GetDefaultValue, cvarAccessor);
return getValue, setValue, getDefaultValue;
end
function Settings.SelectAccountBindings()
LoadBindings(Enum.BindingSet.Account);
SaveBindings(Enum.BindingSet.Account);
end
function Settings.SelectCharacterBindings()
-- Save the account settings so that they're correctly copied over to character.
SaveBindings(Enum.BindingSet.Account);
-- Load the character bindings.
LoadBindings(Enum.BindingSet.Character);
-- Save the copy of the character settings so that the current binding set is updated.
SaveBindings(Enum.BindingSet.Character);
end
function Settings.TryChangeBindingSet(checkbox)
if not checkbox:GetChecked() then
checkbox:SetChecked(true);
StaticPopup_Show("CONFIRM_DELETING_CHARACTER_SPECIFIC_BINDINGS");
return true;
end
Settings.SetValue("PROXY_CHARACTER_SPECIFIC_BINDINGS", true);
return false;
end
function Settings.GetOrCreateSettingsGroup(groupID, order)
SettingsPanel:GetOrCreateGroup(groupID, order);
end
function Settings.LoadAddOnCVarWatcher(cvar, loadFunc)
if Settings.GetValue(cvar) then
loadFunc();
else
local function OnValueChanged(o, setting, value)
-- Only load addons for CVars that are being turned on, not off, to avoid unnecessary loading.
if value then
loadFunc();
end
end
Settings.SetOnValueChangedCallback(cvar, OnValueChanged);
end
end
function Settings.SetOnValueChangedCallback(variable, callback, owner)
return SettingsCallbackRegistry:RegisterCallbackWithHandle(variable, callback, owner);
end
-- Alternative to listening for the SETTINGS_LOADED event.
function Settings.CallWhenRegistered(variable, callback, owner)
local setting = Settings.GetSetting(variable);
if setting then
callback(setting:GetValue());
else
local handle = nil;
local function OnInitialized(o, value)
if handle then
handle:Unregister();
end
callback(value);
end
handle = Settings.SetOnValueChangedCallback(variable, OnInitialized, owner);
end
end
function Settings.IsCommitInProgress()
return SettingsPanel:IsCommitInProgress();
end
SettingsCallbackHandleContainerMixin = CreateFromMixins(CallbackHandleContainerMixin);
function SettingsCallbackHandleContainerMixin:Init()
CallbackHandleContainerMixin.Init(self);
end
function SettingsCallbackHandleContainerMixin:SetOnValueChangedCallback(variable, callback, owner, ...)
self:AddHandle(Settings.SetOnValueChangedCallback(variable, callback, owner, ...));
end
function Settings.CreateCallbackHandleContainer()
local cbrHandles = CreateFromMixins(SettingsCallbackHandleContainerMixin);
cbrHandles:Init();
return cbrHandles;
end
@@ -0,0 +1,284 @@
-- Backport of retail's Blizzard_Settings_Shared/Blizzard_SettingsInbound.lua.
--
-- The one difference: 1.12 has no forbidden frames, so the attribute
-- delegate is a plain frame (no SetForbidden).
local select = select;
local error = error;
local type = type;
local securecallfunction = securecallfunction;
local unpack = unpack;
local CreateAndInitFromMixin = CreateAndInitFromMixin;
local CreateFromMixins = CreateFromMixins;
local PrivateSettingsCategoryMixin = CreateSecureMixinCopy(SettingsCategoryMixin);
local PrivateAddOnSettingMixin = CreateSecureMixinCopy(AddOnSettingMixin);
local PrivateProxySettingMixin = CreateSecureMixinCopy(ProxySettingMixin);
local PrivateSettingsListElementInitializer = CreateSecureMixinCopy(SettingsListElementInitializer);
local CreateVerticalLayout = CreateVerticalLayout;
local CreateCanvasLayout = CreateCanvasLayout;
local GenerateClosure = GenerateClosure;
local AttributeDelegate = CreateFrame("Frame");
local function ErrorIfFunctionArgs(...)
for i = 1, select("#", ...) do
if type(select(i, ...)) == "function" then
error("Function values are not allowed for settings APIs");
return nil;
end
end
return ...;
end
local function SecureUnpackArgs(argTable, expectedNumArgs)
return ErrorIfFunctionArgs(securecallfunction(unpack, argTable, 1, expectedNumArgs));
end
-- Allows function args, but only to be used if a function arg is explicitly expected (use SecureUnpackArgs by default in all other cases).
-- If a function is expected, ensure that it is wrapped in a closure prior to being assigned to the attribute so that taint is properly restored
-- before executing the wrapped function. This is also important to insecure references to secure functions from being washed of taint when
-- processed by the attribute handler.
local function UnpackArgs(argTable, expectedNumArgs)
return securecallfunction(unpack, argTable, 1, expectedNumArgs);
end
-- Pass in function args to have them automatically wrapped in a closure. These wrapped functions are returned back in the same order they were passed in
-- IMPORTANT: Pass ALL arguments to settings that could potentially be functions through here. This ensures that taint state is captured correctly, preventing taint-laundering exploits
local function SecureWrapFunctionArgs(...)
local wrappedArgs = {};
local numArgs = select("#", ...);
for i = 1, numArgs do
local arg = select(i, ...);
if type(arg) == "function" then
wrappedArgs[i] = GenerateClosure(arg);
else
wrappedArgs[i] = arg;
end
end
return unpack(wrappedArgs, 1, numArgs);
end
SettingsInbound = {};
SettingsInbound.AssignLayoutToCategoryAttribute = "assign-layout-to-category";
SettingsInbound.AssignTutorialToCategoryAttribute = "assign-tutorial-to-category";
SettingsInbound.CreateAddOnSettingAttribute = "create-add-on-setting";
SettingsInbound.CreateProxySettingAttribute = "create-proxy-setting";
SettingsInbound.CreateElementInitializerAttribute = "create-element-initializer";
SettingsInbound.CreateSettingInitializerAttribute = "create-setting-initializer";
SettingsInbound.CreatePanelInitializerAttribute = "create-panel-initializer";
SettingsInbound.OnSettingValueChangedAttribute = "on-setting-value-changed";
SettingsInbound.RegisterCanvasLayoutCategoryAttribute = "register-canvas-layout-category";
SettingsInbound.RegisterCanvasLayoutSubcategoryAttribute = "register-canvas-layout-subcategory";
SettingsInbound.RegisterCategoryAttribute = "register-category";
SettingsInbound.RegisterInitializerAttribute = "register-initializer";
SettingsInbound.RegisterSettingAttribute = "register-setting";
SettingsInbound.RegisterVerticalLayoutCategoryAttribute = "register-vertical-layout-category";
SettingsInbound.RegisterVerticalLayoutSubcategoryAttribute = "register-vertical-layout-subcategory";
SettingsInbound.RepairDisplayAttribute = "repair-display";
SettingsInbound.SetCurrentLayoutAttribute = "set-current-layout";
SettingsInbound.SetKeybindingsCategoryAttribute = "set-keybindings-category";
function SettingsInbound.RegisterCategory(category, group, addon)
AttributeDelegate:SetAttribute(SettingsInbound.RegisterCategoryAttribute, { category, group, addon, });
end
function SettingsInbound.RegisterVerticalLayoutCategory(name)
AttributeDelegate:SetAttribute(SettingsInbound.RegisterVerticalLayoutCategoryAttribute, name);
return AttributeDelegate:GetSecureAttributeResults();
end
function SettingsInbound.RegisterVerticalLayoutSubcategory(parentCategory, name)
AttributeDelegate:SetAttribute(SettingsInbound.RegisterVerticalLayoutSubcategoryAttribute, { parentCategory, name, });
return AttributeDelegate:GetSecureAttributeResults();
end
function SettingsInbound.RegisterCanvasLayoutCategory(frame, name)
AttributeDelegate:SetAttribute(SettingsInbound.RegisterCanvasLayoutCategoryAttribute, { frame, name, });
return AttributeDelegate:GetSecureAttributeResults();
end
function SettingsInbound.RegisterCanvasLayoutSubcategory(parentCategory, frame, name)
AttributeDelegate:SetAttribute(SettingsInbound.RegisterCanvasLayoutSubcategoryAttribute, { parentCategory, frame, name, });
return AttributeDelegate:GetSecureAttributeResults();
end
function SettingsInbound.AssignLayoutToCategory(category, layout)
AttributeDelegate:SetAttribute(SettingsInbound.AssignLayoutToCategoryAttribute, { category, layout, });
end
function SettingsInbound.SetKeybindingsCategory(category)
AttributeDelegate:SetAttribute(SettingsInbound.SetKeybindingsCategoryAttribute, category);
end
function SettingsInbound.CreateAddOnSetting(categoryTbl, name, variable, variableKey, variableTbl, variableType, defaultValue)
AttributeDelegate:SetAttribute(SettingsInbound.CreateAddOnSettingAttribute, { categoryTbl, name, variable, variableKey, variableTbl, variableType, defaultValue, });
return AttributeDelegate:GetSecureAttributeResults();
end
function SettingsInbound.CreateProxySetting(categoryTbl, nameValue, variable, variableType, defaultValue, getValue, setValue)
-- Function args must be wrapped. See comment above UnpackArgs.
nameValue, variable, variableType, defaultValue, getValue, setValue = SecureWrapFunctionArgs(nameValue, variable, variableType, defaultValue, getValue, setValue);
AttributeDelegate:SetAttribute(SettingsInbound.CreateProxySettingAttribute, { categoryTbl, nameValue, variable, variableType, defaultValue, getValue, setValue, });
return AttributeDelegate:GetSecureAttributeResults();
end
function SettingsInbound.RegisterSetting(categoryTbl, setting)
AttributeDelegate:SetAttribute(SettingsInbound.RegisterSettingAttribute, { categoryTbl, setting, });
end
local function SettingsInboundValueChangedCallback(unused_registrant, setting, value)
AttributeDelegate:SetAttribute(SettingsInbound.OnSettingValueChangedAttribute, { setting, value });
end
function SettingsInbound.RegisterOnSettingValueChanged(variable)
Settings.SetOnValueChangedCallback(variable, SettingsInboundValueChangedCallback, SettingsInbound);
end
function SettingsInbound.CreateElementInitializer(frameTemplate, data)
AttributeDelegate:SetAttribute(SettingsInbound.CreateElementInitializerAttribute, { frameTemplate, data, });
return AttributeDelegate:GetSecureAttributeResults();
end
function SettingsInbound.CreateSettingInitializer(frameTemplate, data)
AttributeDelegate:SetAttribute(SettingsInbound.CreateSettingInitializerAttribute, { frameTemplate, data, });
return AttributeDelegate:GetSecureAttributeResults();
end
function SettingsInbound.CreatePanelInitializer(frameTemplate, data)
AttributeDelegate:SetAttribute(SettingsInbound.CreatePanelInitializerAttribute, { frameTemplate, data, });
return AttributeDelegate:GetSecureAttributeResults();
end
function SettingsInbound.RegisterInitializer(category, initializer)
AttributeDelegate:SetAttribute(SettingsInbound.RegisterInitializerAttribute, { category, initializer, });
end
function SettingsInbound.RepairDisplay()
local dummy = true;
AttributeDelegate:SetAttribute(SettingsInbound.RepairDisplayAttribute, dummy);
end
function SettingsInbound.SetCurrentLayout(layout)
AttributeDelegate:SetAttribute(SettingsInbound.SetCurrentLayoutAttribute, layout);
end
function SettingsInbound.AssignTutorialToCategory(category, tooltip, callback)
-- Function args must be wrapped. See comment above UnpackArgs.
tooltip, callback = SecureWrapFunctionArgs(tooltip, callback);
AttributeDelegate:SetAttribute(SettingsInbound.AssignTutorialToCategoryAttribute, { category, tooltip, callback, });
end
function AttributeDelegate:OnAttributeChanged(name, value)
if name == SettingsInbound.RegisterCategoryAttribute then
local category, group, addon = SecureUnpackArgs(value, 3);
SettingsPanel:RegisterCategory(category, group, addon);
elseif name == SettingsInbound.RegisterVerticalLayoutCategoryAttribute then
local category = CreateAndInitFromMixin(PrivateSettingsCategoryMixin, value);
local layout = CreateVerticalLayout();
SettingsPanel:AssignLayoutToCategory(category, layout);
self:SetSecureAttributeResults(category, layout);
elseif name == SettingsInbound.RegisterVerticalLayoutSubcategoryAttribute then
local parentCategory, categoryName = SecureUnpackArgs(value);
-- Use PrivateSettingsCategoryMixin.CreateSubcategory to avoid taint.
local subcategory = securecallfunction(PrivateSettingsCategoryMixin.CreateSubcategory, parentCategory, categoryName);
local layout = CreateVerticalLayout();
SettingsPanel:AssignLayoutToCategory(subcategory, layout);
self:SetSecureAttributeResults(subcategory, layout);
elseif name == SettingsInbound.RegisterCanvasLayoutCategoryAttribute then
local frame, categoryName = SecureUnpackArgs(value);
local category = CreateAndInitFromMixin(PrivateSettingsCategoryMixin, categoryName);
local layout = CreateCanvasLayout(frame);
SettingsPanel:AssignLayoutToCategory(category, layout);
self:SetSecureAttributeResults(category, layout);
elseif name == SettingsInbound.RegisterCanvasLayoutSubcategoryAttribute then
local parentCategory, frame, categoryName = SecureUnpackArgs(value);
-- Use PrivateSettingsCategoryMixin.CreateSubcategory to avoid taint.
local subcategory = securecallfunction(PrivateSettingsCategoryMixin.CreateSubcategory, parentCategory, categoryName);
local layout = CreateCanvasLayout(frame);
SettingsPanel:AssignLayoutToCategory(subcategory, layout);
self:SetSecureAttributeResults(subcategory, layout);
elseif name == SettingsInbound.AssignLayoutToCategoryAttribute then
local category, layout = SecureUnpackArgs(value);
SettingsPanel:AssignLayoutToCategory(category, layout);
elseif name == SettingsInbound.SetKeybindingsCategoryAttribute then
SettingsPanel:SetKeybindingsCategory(value);
elseif name == SettingsInbound.CreateAddOnSettingAttribute then
local categoryTbl, settingName, variable, variableKey, variableTbl, variableType, defaultValue = SecureUnpackArgs(value);
local setting = CreateAndInitFromMixin(PrivateAddOnSettingMixin, settingName, variable, variableKey, variableTbl, variableType, defaultValue);
SettingsPanel:RegisterSetting(categoryTbl, setting);
self:SetSecureAttributeResults(setting);
elseif name == SettingsInbound.CreateProxySettingAttribute then
local categoryTbl, settingName, variable, variableType, defaultValue, getValue, setValue = UnpackArgs(value);
local setting = CreateAndInitFromMixin(PrivateProxySettingMixin, settingName, variable, variableType, defaultValue, getValue, setValue);
SettingsPanel:RegisterSetting(categoryTbl, setting);
self:SetSecureAttributeResults(setting);
elseif name == SettingsInbound.RegisterSettingAttribute then
local categoryTbl, setting = SecureUnpackArgs(value);
SettingsPanel:RegisterSetting(categoryTbl, setting);
elseif name == SettingsInbound.RegisterInitializerAttribute then
local category, initializer = SecureUnpackArgs(value);
SettingsPanel:RegisterInitializer(category, initializer);
elseif name == SettingsInbound.CreateElementInitializerAttribute then
local frameTemplate, data = SecureUnpackArgs(value);
local initializer = CreateFromMixins(SettingsListElementInitializer);
initializer:Init(frameTemplate, data);
self:SetSecureAttributeResults(initializer);
elseif name == SettingsInbound.CreateSettingInitializerAttribute then
local frameTemplate, data = SecureUnpackArgs(value);
local initializer = CreateFromMixins(PrivateSettingsListElementInitializer);
initializer:Init(frameTemplate, data);
local setting = securecallfunction(PrivateSettingsListElementInitializer.GetSetting, initializer);
if setting then
local settingName = securecallfunction(setting.GetName, setting);
initializer:AddSearchTags(settingName);
end
self:SetSecureAttributeResults(initializer);
elseif name == SettingsInbound.CreatePanelInitializerAttribute then
local frameTemplate, data = SecureUnpackArgs(value);
local initializer = CreateFromMixins(SettingsListPanelInitializer);
initializer:Init(frameTemplate, data);
local settings = data.settings;
if settings then
local tags = {};
for _, setting in pairs(settings) do
table.insert(tags, setting:GetName());
end
initializer:AddSearchTags(unpack(tags));
end
self:SetSecureAttributeResults(initializer);
elseif name == SettingsInbound.OnSettingValueChangedAttribute then
local setting, newValue = SecureUnpackArgs(value);
SettingsPanel:OnSettingValueChanged(setting, newValue);
elseif name == SettingsInbound.RepairDisplayAttribute then
SettingsPanel:RepairDisplay();
elseif name == SettingsInbound.SetCurrentLayoutAttribute then
SettingsPanel:SetCurrentLayout(value);
elseif name == SettingsInbound.AssignTutorialToCategoryAttribute then
local category, tooltip, callback = UnpackArgs(value);
if category then
category:SetCategoryTutorialInfo(tooltip, callback);
end
end
end
function AttributeDelegate:SetSecureAttributeResults(...)
self.secureAttributeResults = { ... };
end
function AttributeDelegate:GetSecureAttributeResults()
return unpack(self.secureAttributeResults);
end
AttributeDelegate:SetScript("OnAttributeChanged", AttributeDelegate.OnAttributeChanged);
@@ -0,0 +1,85 @@
-- Verbatim backport of retail's Blizzard_Settings_Shared/Blizzard_SettingsLayouts.lua.
SettingsLayoutMixin = {};
SettingsLayoutMixin.LayoutType = EnumUtil.MakeEnum("Vertical", "Canvas");
function SettingsLayoutMixin:Init(layoutType)
self.layoutType = layoutType;
end
function SettingsLayoutMixin:GetLayoutType()
return self.layoutType;
end
function SettingsLayoutMixin:IsVerticalLayout()
return self:GetLayoutType() == SettingsLayoutMixin.LayoutType.Vertical;
end
local SettingsVerticalLayoutMixin = CreateFromMixins(SettingsLayoutMixin);
function SettingsVerticalLayoutMixin:Init()
SettingsLayoutMixin.Init(self, SettingsLayoutMixin.LayoutType.Vertical)
self.initializers = {};
end
function SettingsVerticalLayoutMixin:GetInitializers()
return self.initializers;
end
function SettingsVerticalLayoutMixin:IsEmpty()
return #self.initializers == 0;
end
function SettingsVerticalLayoutMixin:AddInitializer(initializer)
table.insert(self.initializers, initializer);
return initializer;
end
function SettingsVerticalLayoutMixin:AddMirroredInitializer(initializer)
if not initializer then
-- If initializer is nil it probably means the base setting doesn't exist in this game mode
return;
end
initializer:SetSearchIgnoredInLayout(self);
return self:AddInitializer(initializer);
end
function SettingsVerticalLayoutMixin:EnumerateInitializers()
local iterator, tbl, index = next, self.initializers, nil;
local function Iterator(_, index)
return securecallfunction(iterator, tbl, index);
end
return Iterator, nil, index;
end
function CreateVerticalLayout()
return CreateAndInitFromMixin(SettingsVerticalLayoutMixin);
end
local SettingsCanvasLayoutMixin = CreateFromMixins(SettingsLayoutMixin);
function SettingsCanvasLayoutMixin:Init(frame)
SettingsLayoutMixin.Init(self, SettingsLayoutMixin.LayoutType.Canvas);
self.frame = frame;
self.anchorPoints = {};
end
function SettingsCanvasLayoutMixin:GetFrame()
return self.frame;
end
function SettingsCanvasLayoutMixin:AddAnchorPoint(p, x, y)
table.insert(self.anchorPoints, {p=p, x=x, y=y});
end
function SettingsCanvasLayoutMixin:GetAnchorPoints()
return self.anchorPoints;
end
function CreateCanvasLayout(frame)
return CreateAndInitFromMixin(SettingsCanvasLayoutMixin, frame);
end
@@ -0,0 +1,160 @@
-- Verbatim backport of retail's Blizzard_Settings_Shared/Blizzard_SettingsList.lua.
local securecallfunction = securecallfunction;
local pairs = pairs;
-- Matches a similar function reused in multiple places
local function EnumerateTaintedKeysTable(tableToIterate)
local pairsIterator, enumerateTable, initialIteratorKey = securecallfunction(pairs, tableToIterate);
local function IteratorFunction(tbl, key)
return securecallfunction(pairsIterator, tbl, key);
end
return IteratorFunction, enumerateTable, initialIteratorKey;
end
SettingsListSearchCategoryMixin = {};
function SettingsListSearchCategoryMixin:Init(initializer)
local data = initializer:GetData();
self.Title:SetText(data.category:GetQualifiedName());
end
function SettingsListSearchCategoryMixin:OnClick(button, buttonName, down)
local initializer = self:GetElementData();
local data = initializer:GetData();
local force = true;
SettingsPanel:SelectCategory(data.category, force);
end
function SettingsListSearchCategoryMixin:OnEnter()
self.MouseoverOverlay:Show();
end
function SettingsListSearchCategoryMixin:OnLeave()
self.MouseoverOverlay:Hide();
end
function CreateSettingsListSearchCategoryInitializer(category)
local data = {category = category};
return Settings.CreateElementInitializer("SettingsListSearchCategoryTemplate", data);
end
SettingsListMixin = CreateFromMixins(CallbackRegistryMixin);
SettingsListMixin:GenerateCallbackEvents(
{
"OnSettingsUpdated",
}
);
function SettingsListMixin:OnLoad()
CallbackRegistryMixin.OnLoad(self);
local verticalPad = 10;
local padLeft, padRight = 25, 0;
local spacing = 9;
local view = CreateScrollBoxListLinearView(verticalPad, verticalPad, padLeft, padRight, spacing);
local function Factory(factory, elementData)
local function Initializer(frame, elementData)
securecallfunction(elementData.InitFrame, elementData, frame);
end
securecallfunction(elementData.Factory, elementData, factory, Initializer);
end
local function Resetter(frame, elementData)
securecallfunction(elementData.Resetter, elementData, frame);
end
local function ExtentCalculator(dataIndex, elementData)
local extent = securecallfunction(elementData.GetExtent, elementData);
return extent or view:GetTemplateExtent(securecallfunction(elementData.GetTemplate, elementData));
end
view:SetElementFactory(Factory);
view:SetElementResetter(Resetter);
view:SetElementExtentCalculator(ExtentCalculator);
ScrollUtil.InitScrollBoxListWithScrollBar(self.ScrollBox, self.ScrollBar, view);
local scrollBoxAnchors =
{
CreateAnchor("TOPLEFT", self.Header, "BOTTOMLEFT", -15, -2),
CreateAnchor("BOTTOMRIGHT", -20, -2);
};
ScrollUtil.AddManagedScrollBarVisibilityBehavior(self.ScrollBox, self.ScrollBar, scrollBoxAnchors, scrollBoxAnchors);
ScrollUtil.AddResizableChildrenBehavior(self.ScrollBox);
end
function SettingsListMixin:SetInputBlockerShown(shown)
if shown then
self.ScrollBox.InputBlocker:SetFrameStrata("DIALOG");
self.ScrollBox.InputBlocker:Show();
else
self.ScrollBox.InputBlocker:Hide();
end
end
function SettingsListMixin:GetInputBlocker()
return self.ScrollBox.InputBlocker;
end
-- Used when a setting value change results in other settings needing to have their
-- visibility changed. For example, checking a bool setting may hide one child, but show
-- another.
function SettingsListMixin:RepairDisplay(layout)
-- The order isn't stored on the initializer itself because initializers can be mirrored in
-- another settings lists, namely Acessibility.
local order = {};
for index, initializer in layout:EnumerateInitializers() do
order[initializer] = index;
end
-- Remove what is no longer intended to be shown.
local dataProvider = self.ScrollBox:GetDataProvider();
local shown = {};
for index, initializer in dataProvider:ReverseEnumerate() do
if initializer:ShouldShow() then
shown[initializer] = true;
else
dataProvider:RemoveIndex(index);
end
end
-- Add any newly shown, out of position at the end. Will be corrected when sorted.
for index, initializer in EnumerateTaintedKeysTable(layout:GetInitializers()) do
if not shown[initializer] and initializer:ShouldShow() then
dataProvider:Insert(initializer);
end
end
-- Reorder and sort the list.
local function Comparator(e1, e2)
return order[e1] < order[e2];
end
dataProvider:SetSortComparator(Comparator);
dataProvider:ClearSortComparator();
end
function SettingsListMixin:Display(initializers)
local dataProvider = CreateDataProvider();
for key, initializer in EnumerateTaintedKeysTable(initializers) do
if initializer:ShouldShow() then
dataProvider:Insert(initializer);
end
end
securecallfunction(self.ScrollBox.SetDataProvider, self.ScrollBox, dataProvider);
self:TriggerEvent(self.Event.OnSettingsUpdated);
end
function SettingsListMixin:ScrollToElementByName(name)
self.ScrollBox:ScrollToElementDataByPredicate(function(elementData)
local data = securecallfunction(rawget, elementData, "data");
local elementName = securecallfunction(rawget, data, "name");
return elementName == name;
end, ScrollBoxConstants.AlignBegin);
end
@@ -0,0 +1,81 @@
<Ui xmlns="http://www.blizzard.com/wow/ui/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.blizzard.com/wow/ui/ ..\FrameXML\UI.xsd">
<!--
Retail's Blizzard_Settings_Shared/Blizzard_SettingsList.xml.
Differences:
- The divider under the title is a plain line: retail draws it with the
Options_HorizontalDivider atlas (630x1), which this client does not have.
- No tutorial button: this client has no help plates.
-->
<Frame name="SettingsListTemplate" mixin="SettingsListMixin" virtual="true">
<Frames>
<Frame parentKey="Header">
<Size y="50"/>
<Anchors>
<Anchor point="TOPLEFT"/>
<Anchor point="TOPRIGHT"/>
</Anchors>
<Layers>
<Layer level="ARTWORK">
<FontString parentKey="Title" inherits="GameFontHighlightHuge" justifyH="LEFT">
<Anchors>
<Anchor point="TOPLEFT" x="7" y="-22"/>
</Anchors>
</FontString>
<Texture parentKey="Divider">
<Size x="630" y="1"/>
<Anchors>
<Anchor point="TOP" y="-50"/>
</Anchors>
<Color r="0.5" g="0.5" b="0.5" a="0.6"/>
</Texture>
</Layer>
</Layers>
<Frames>
<Button parentKey="DefaultsButton" inherits="UIPanelButtonTemplate">
<Size x="96" y="22"/>
<Anchors>
<Anchor point="TOPRIGHT" x="-36" y="-16"/>
</Anchors>
</Button>
</Frames>
</Frame>
<Frame parentKey="ScrollBox" inherits="WowScrollBoxList">
<Frames>
<Button parentKey="InputBlocker" clipChildren="true" setAllPoints="true" hidden="true"/>
</Frames>
</Frame>
<EventFrame parentKey="ScrollBar" inherits="MinimalScrollBar">
<Anchors>
<Anchor point="TOPLEFT" relativeKey="$parent.ScrollBox" relativePoint="TOPRIGHT" x="0" y="-4"/>
<Anchor point="BOTTOMLEFT" relativeKey="$parent.ScrollBox" relativePoint="BOTTOMRIGHT" x="-1" y="7"/>
</Anchors>
</EventFrame>
</Frames>
<Scripts>
<OnLoad method="OnLoad"/>
</Scripts>
</Frame>
<Button name="SettingsListSearchCategoryTemplate" mixin="SettingsListSearchCategoryMixin" virtual="true">
<Size y="45"/>
<Layers>
<Layer level="BACKGROUND">
<Texture parentKey="MouseoverOverlay" hidden="true" alphaMode="ADD">
<Color r=".1" g=".1" b=".1" a="1"/>
</Texture>
</Layer>
<Layer level="ARTWORK">
<FontString parentKey="Title" inherits="GameFontNormalLarge" justifyH="LEFT" justifyV="TOP">
<Anchors>
<Anchor point="TOPLEFT" x="16" y="-16"/>
</Anchors>
</FontString>
</Layer>
</Layers>
<Scripts>
<OnClick method="OnClick"/>
<OnEnter method="OnEnter"/>
<OnLeave method="OnLeave"/>
</Scripts>
</Button>
</Ui>
@@ -0,0 +1,922 @@
-- Backport of retail's Blizzard_Settings_Shared/Blizzard_SettingsPanel.lua.
--
-- Differences from the retail source:
-- - This file loads only on the game screen, so the glue-screen branches
-- are gone.
-- - No gamepad navigation, no help-plate tutorials and no kiosk mode: those
-- systems do not exist here.
-- - No Keybindings category yet. Closing the window saves the key bindings
-- to the set in use, where retail saves them to the set its Keybindings
-- category picks. Defaults does not reset the key bindings: on retail it
-- does so because the Keybindings category is one of the settings it
-- resets.
-- - No timed revert prompt: retail asks within 8 seconds whether to keep a
-- revertable (graphics) setting. No such settings are ported, and a
-- setting an addon flags revertable commits like any other.
-- - A commit that needs the UI reloaded calls ReloadUI. 1.12 has no
-- UpdateWindow, so the window-update flag does nothing.
-- - The Close, Apply and Defaults buttons are 1.12's UIPanelButtonTemplate,
-- which has no Text key, so their labels go through SetText.
-- - Retail draws the frames around the category list and the settings with
-- the Options_InnerFrame atlas, which this client does not have. Each is a
-- frame with the tooltip backdrop the earlier Interface Options window
-- used, CategoryListBorder and ContainerBorder (see below).
-- - Retail hides the Game and AddOns tabs while no addon has a category.
-- Here the tabs show only while both sets have a category, so a game
-- category registered without ClassicAPI's pages leaves no empty tab. A
-- category registered later shows them the next time the window opens.
-- - When the window closes it returns to the game menu, as retail's does.
-- Retail calls ToggleGameMenu; 1.12's ToggleGameMenu, called without an
-- argument, is the Escape key's handler and can stop a cast or clear the
-- target, so the window shows the game menu itself.
-- - wipe is ClassicAPI.wipe, so an addon's own global wipe cannot
-- replace it.
local wipe = ClassicAPI.wipe;
local function CallDefaultOnFrame(frame)
if frame.OnDefault then
frame:OnDefault();
end
end
local function CallRefreshOnFrame(frame)
if frame.OnRefresh then
frame:OnRefresh();
end
end
local securecallfunction = securecallfunction;
local pairs = pairs;
local reservedVariables = {};
-- The art that stands in for retail's Options_InnerFrame atlas.
local INNER_FRAME_BACKDROP =
{
bgFile = "Interface\\Tooltips\\UI-Tooltip-Background",
edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
tile = true, tileSize = 16, edgeSize = 16,
insets = { left = 5, right = 5, top = 5, bottom = 5 },
};
-- Retail's atlas sits at the window's (17, -64), 12 above the tops of the list
-- and the settings, which start at -76. The border keeps that 12 above them
-- and stands off their other edges by the backdrop's inset, so no row or
-- setting is drawn under the border.
local function CreateInnerFrameBorder(panel, frame)
local border = CreateFrame("Frame", nil, panel);
border:SetFrameLevel(panel:GetFrameLevel());
border:SetPoint("TOPLEFT", frame, "TOPLEFT", -5, 12);
border:SetPoint("BOTTOMRIGHT", frame, "BOTTOMRIGHT", 5, -5);
border:SetBackdrop(INNER_FRAME_BACKDROP);
border:SetBackdropColor(0, 0, 0, 0.5);
border:SetBackdropBorderColor(0.6, 0.6, 0.6);
return border;
end
-- Matches a similar function reused in multiple places
local function EnumerateTaintedKeysTable(tableToIterate)
local pairsIterator, enumerateTable, initialIteratorKey = securecallfunction(pairs, tableToIterate);
local function IteratorFunction(tbl, key)
return securecallfunction(pairsIterator, tbl, key);
end
return IteratorFunction, enumerateTable, initialIteratorKey;
end
local function SortTableByCommitOrder(tbl)
-- Commit order is necessary under rare circumstances where we need to guarantee that
-- a particular option is changed before another. This is necessary in at least two cases:
-- 1) Applying the display mode setting prior to the resolution setting
-- 2) Applying child graphic settings prior to the graphics or raid graphics setting.
table.sort(tbl, function(lhs, rhs)
return lhs:GetCommitOrder() < rhs:GetCommitOrder();
end);
end
SettingsPanelMixin = {};
function SettingsPanel_EscapePressed()
if SettingsPanel:IsShown() then
SettingsPanel:Close();
return true;
end
return false;
end
function SettingsPanelMixin:OnLoad()
self.settings = {};
self.categoryLayouts = {};
self.modified = {};
self.NineSlice.Text:SetText(SETTINGS_TITLE);
self.tabsGroup = CreateRadioButtonGroup();
self.tabsGroup:AddButtons({self.GameTab, self.AddOnsTab});
self.tabsGroup:SelectAtIndex(1);
self.tabsGroup:RegisterCallback(ButtonGroupBaseMixin.Event.Selected, self.OnTabSelected, self);
self:SetParent(GetAppropriateTopLevelParent());
self.CategoryListBorder = CreateInnerFrameBorder(self, self:GetCategoryList());
self.ContainerBorder = CreateInnerFrameBorder(self, self.Container);
local function closePanel()
self:Close();
end
self.CloseButton:SetText(SETTINGS_CLOSE);
self.CloseButton:SetScript("OnClick", closePanel);
self.onCloseCallback = closePanel;
self.ApplyButton:SetText(SETTINGS_APPLY);
self.ApplyButton:SetScript("OnClick", function(button, buttonName, down)
self:Commit();
end);
local settingsList = self:GetSettingsList();
settingsList.Header.DefaultsButton:SetText(SETTINGS_DEFAULTS);
settingsList.Header.DefaultsButton:SetScript("OnClick", function(button, buttonName, down)
StaticPopup_Show("GAME_SETTINGS_APPLY_DEFAULTS");
end);
self.SearchBox:HookScript("OnTextChanged", GenerateClosure(self.OnSearchTextChanged, self));
self:GetCategoryList():RegisterCallback(SettingsCategoryListMixin.Event.OnCategoryActivated, self.ActivateCategory, self);
self:GetCategoryList():RegisterCallback(SettingsCategoryListMixin.Event.OnCategorySelected, self.SelectCategory, self);
settingsList.ScrollBox:SetScript("OnMouseWheel", function(scrollBox, delta)
if not KeybindListener:OnForwardMouseWheel(delta) then
ScrollControllerMixin.OnMouseWheel(scrollBox, delta);
end
end);
self.Container.SettingsCanvas:SetScript("OnMouseWheel", nop);
EventRegistry:RegisterCallback("KeybindListener.StoppedListening", self.OnKeybindStoppedListening, self);
EventRegistry:RegisterCallback("KeybindListener.StartedListening", self.OnKeybindStartedListening, self);
EventRegistry:RegisterCallback("KeybindListener.UnbindFailed", self.OnKeybindUnbindFailed, self);
EventRegistry:RegisterCallback("KeybindListener.RebindFailed", self.OnKeybindRebindFailed, self);
EventRegistry:RegisterCallback("KeybindListener.RebindSuccess", self.OnKeybindRebindSuccess, self);
CVarCallbackRegistry:RegisterCallbackForAllCVarUpdates(self.OnCVarChanged, self);
self:RegisterEvent("SETTINGS_PANEL_OPEN");
self:RegisterEvent("UPDATE_BINDINGS");
end
function SettingsPanelMixin:OnTabSelected(tab, tabIndex)
self:GetCategoryList():SetCategorySet(tab.categorySet);
PlaySound(SOUNDKIT.IG_CHARACTER_INFO_TAB);
end
function SettingsPanelMixin:OnCVarChanged(cvar, cvarValue)
-- This handler is intended only for cvar updates originating from the console or through the cvar script api.
-- If the cvar was changed through the settings api, as recommended, this value will already be updated.
local setting = self:GetSetting(cvar);
if not setting then
return;
end
-- There are cases where a cvar value cannot always be retrieved. For example, output audio device will not be
-- retrievable if the sound system is in the process of reinitializing. Skip handling if this occurs.
if setting:GetValue() == nil then
return;
end
-- The value is forced because the setting will always evaluate the current state of this
-- cvar as unchanged due to the source of the value being the cvar that was just modified.
-- This won't produce a recursive overflow because when setting the value legimately through
-- the settings api, or through the controls, the setting will temporarily reject any changes
-- to it's value.
local force = true;
-- Value is converted from the cvar string representation into a format the setting expects. Note
-- this is done manually because we normally are strict about the value being the correct type.
local value = securecallfunction(setting.ConvertValueInternal, setting, cvarValue);
securecallfunction(setting.SetValue, setting, value, force);
end
function SettingsPanelMixin:OnEvent(event, ...)
if event == "SETTINGS_PANEL_OPEN" then
local openToCategoryID, scrollToElementName = ...;
if openToCategoryID ~= nil then
self:OpenToCategory(openToCategoryID, scrollToElementName);
else
self:Open();
end
elseif event == "UPDATE_BINDINGS" then
self:RenewKeybinds();
end
end
function SettingsPanelMixin:OnShow()
-- Ensure that the current category is reinitialized because any
-- initializers with show or enable predicates need to be reevaluated.
local force = true;
self:SelectFirstCategory(force);
-- Checks for if there are categories to show on both tabs
local categories = self:GetCategoryList();
local hasGame = false;
local hasAddOns = false;
for _, category in ipairs(categories.allCategories) do
if category.categorySet == Settings.CategorySet.AddOns then
hasAddOns = true;
else
hasGame = true;
end
end
local showTabs = hasGame and hasAddOns;
self.GameTab:SetShown(showTabs);
self.AddOnsTab:SetShown(showTabs);
self.NineSlice.Text:SetText(SETTINGS_TITLE);
UpdateMicroButtons();
self:CheckApplyButton();
self:CallRefreshOnCanvases();
self:CheckTutorials();
end
function SettingsPanelMixin:CheckTutorials()
end
function SettingsPanelMixin:Flush()
KeybindListener:StopListening();
self:ClearOutputText();
self:ClearSearchBox();
self:WipeModifiedTable();
end
function SettingsPanelMixin:OnHide()
self:Flush();
UpdateMicroButtons();
SaveBindings(GetCurrentBindingSet());
EventRegistry:TriggerEvent("SettingsPanel.OnHide");
end
function SettingsPanelMixin:Commit(unrevertable)
self:CommitCanvases();
self:CommitSettings(unrevertable);
self:CommitBindings();
self:WipeModifiedTable();
end
function SettingsPanelMixin:Close(skipTransitionBackToOpeningPanel)
if self:HasUnappliedSettings() then
StaticPopup_Show("GAME_SETTINGS_CONFIRM_DISCARD");
else
self:ExitWithCommit(skipTransitionBackToOpeningPanel);
end
end
function SettingsPanelMixin:ExitWithoutCommit()
local settings = {};
for setting, record in pairs(self.modified) do
-- The settings under affect of IgnoreApply flag shouldn't be in the self.modified table after having been applied
-- Needs bug investigation
if (securecallfunction(setting.HasCommitFlag, setting, Settings.CommitFlag.Revertable) or securecallfunction(setting.HasCommitFlag, setting, Settings.CommitFlag.Apply)) and not securecallfunction(setting.HasCommitFlag, setting, Settings.CommitFlag.IgnoreApply) then
--store the setting we want to revert and do it outside of this loop so we can avoid any invalid key errors
table.insert(settings, setting);
end
end
for i, setting in ipairs(settings) do
securecallfunction(setting.Revert, setting);
end
self:Flush();
self:TransitionBackOpeningPanel();
end
function SettingsPanelMixin:ExitWithCommit(skipTransitionBackToOpeningPanel)
local unrevertable = true;
self:Commit(unrevertable);
if skipTransitionBackToOpeningPanel then
HideUIPanel(self);
else
self:TransitionBackOpeningPanel();
end
end
function SettingsPanelMixin:TransitionBackOpeningPanel()
HideUIPanel(self);
ShowUIPanel(GameMenuFrame);
end
function SettingsPanelMixin:Open()
self:WipeModifiedTable();
ShowUIPanel(SettingsPanel);
end
function SettingsPanelMixin:OpenToCategory(categoryID, scrollToElementName)
self:Open();
local categoryTbl = self:GetCategoryList():GetCategory(categoryID);
if categoryTbl then
categoryTbl:SetExpanded(true);
self:ActivateCategory(categoryTbl);
if scrollToElementName then
self:GetSettingsList():ScrollToElementByName(scrollToElementName);
end
end
return categoryTbl ~= nil;
end
function SettingsPanelMixin:SetKeybindingsCategory(category)
self.keybindingsCategory = category;
end
function SettingsPanelMixin:CommitBindings()
SaveBindings(GetCurrentBindingSet());
end
function SettingsPanelMixin:IsCommitInProgress()
return self.isCommitInProgress;
end
function SettingsPanelMixin:CommitSettings(unrevertable)
local saveBindings = false;
local gxRestart = false;
local uiReload = false;
local settings = {};
for setting, record in pairs(self.modified) do
table.insert(settings, setting);
setting:LockPendingValue();
end
SortTableByCommitOrder(settings);
if #settings > 0 then
self.isCommitInProgress = true;
for index, setting in ipairs(settings) do
saveBindings = saveBindings or securecallfunction(setting.HasCommitFlag, setting, Settings.CommitFlag.SaveBindings);
gxRestart = gxRestart or securecallfunction(setting.HasCommitFlag, setting, Settings.CommitFlag.GxRestart);
uiReload = uiReload or securecallfunction(setting.HasCommitFlag, setting, Settings.CommitFlag.UIReload);
securecallfunction(setting.Commit, setting);
end
self.isCommitInProgress = nil;
end
self:FinalizeCommit(saveBindings, gxRestart, uiReload);
end
function SettingsPanelMixin:FinalizeCommit(saveBindings, gxRestart, uiReload)
if saveBindings then
SaveBindings(GetCurrentBindingSet());
end
if gxRestart then
RestartGx();
end
if uiReload then
ReloadUI();
end
end
function SettingsPanelMixin:SetIsSettingDefaults(isSettingDefaults)
self.isSettingDefaults = isSettingDefaults;
end
function SettingsPanelMixin:CheckIsSettingDefaults()
return self.isSettingDefaults;
end
function SettingsPanelMixin:SetAllSettingsToDefaults()
self:SetIsSettingDefaults(true);
local saveBindings = false;
local gxRestart = false;
local uiReload = false;
local settings = {};
for setting, category in pairs(self.settings) do
table.insert(settings, setting);
end
SortTableByCommitOrder(settings);
for index, setting in ipairs(settings) do
if securecallfunction(setting.SetValueToDefault, setting) then
saveBindings = saveBindings or securecallfunction(setting.HasCommitFlag, setting, Settings.CommitFlag.SaveBindings);
gxRestart = gxRestart or securecallfunction(setting.HasCommitFlag, setting, Settings.CommitFlag.GxRestart);
uiReload = uiReload or securecallfunction(setting.HasCommitFlag, setting, Settings.CommitFlag.UIReload);
end
end
self:CallDefaultOnCanvases();
self:WipeModifiedTable();
self:CheckApplyButton();
self:FinalizeCommit(saveBindings, gxRestart, uiReload);
EventRegistry:TriggerEvent("Settings.Defaulted");
self:SetIsSettingDefaults(false);
end
function SettingsPanelMixin:SetCurrentCategorySettingsToDefaults()
self:SetIsSettingDefaults(true);
local saveBindings = false;
local gxRestart = false;
local uiReload = false;
local settings = {};
local currentCategory = self:GetCurrentCategory();
for setting, category in pairs(self.settings) do
if category == currentCategory then
table.insert(settings, setting);
end
end
SortTableByCommitOrder(settings);
for index, setting in ipairs(settings) do
if securecallfunction(setting.SetValueToDefault, setting) then
saveBindings = saveBindings or securecallfunction(setting.HasCommitFlag, setting, Settings.CommitFlag.SaveBindings);
gxRestart = gxRestart or securecallfunction(setting.HasCommitFlag, setting, Settings.CommitFlag.GxRestart);
uiReload = uiReload or securecallfunction(setting.HasCommitFlag, setting, Settings.CommitFlag.UIReload);
end
self.modified[setting] = nil;
end
for _, category in ipairs(self:GetAllCategories()) do
if category == currentCategory then
local layout = self:GetLayout(category);
local layoutType = layout:GetLayoutType();
if layoutType == SettingsLayoutMixin.LayoutType.Canvas then
local frame = layout:GetFrame();
securecallfunction(CallDefaultOnFrame, frame);
end
end
end
self:FinalizeCommit(saveBindings, gxRestart, uiReload);
self:CheckApplyButton();
EventRegistry:TriggerEvent("Settings.CategoryDefaulted", currentCategory);
self:SetIsSettingDefaults(false);
end
function SettingsPanelMixin:HasUnappliedSettings()
for setting in pairs(self.modified) do
if securecallfunction(setting.HasCommitFlag, setting, Settings.CommitFlag.Apply) and not securecallfunction(setting.HasCommitFlag, setting, Settings.CommitFlag.IgnoreApply) then
return true;
end
end
return false;
end
function SettingsPanelMixin:CheckApplyButton()
self:SetApplyButtonEnabled(self:HasUnappliedSettings());
end
function SettingsPanelMixin:ForEachCanvas(func)
local function CallOnCanvases(index, category, func)
local layout = self:GetLayout(category);
if layout:GetLayoutType() == SettingsLayoutMixin.LayoutType.Canvas then
xpcall(func, CallErrorHandler, layout:GetFrame());
end
local subcategories = securecallfunction(category.GetSubcategories, category);
secureexecuterange(subcategories, CallOnCanvases, func);
end
local allCategories = securecallfunction(self.GetAllCategories, self);
secureexecuterange(allCategories, CallOnCanvases, func);
end
function SettingsPanelMixin:SetApplyButtonEnabled(enabled)
self.ApplyButton:SetEnabled(enabled);
self.ApplyButton:SetShown(enabled);
end
function SettingsPanelMixin:WipeModifiedTable()
wipe(self.modified);
self:CheckApplyButton();
end
function SettingsPanelMixin:CommitCanvases()
self:ForEachCanvas(function(frame)
if frame.OnCommit then
frame:OnCommit();
end
end);
end
function SettingsPanelMixin:CallDefaultOnCanvases()
self:ForEachCanvas(function(frame)
CallDefaultOnFrame(frame);
end);
end
function SettingsPanelMixin:CallRefreshOnCanvases()
self:ForEachCanvas(function(frame)
CallRefreshOnFrame(frame);
end);
end
function SettingsPanelMixin:FindInitializersMatchingSearchText(searchText)
searchText = searchText:upper();
local words = { searchText };
for word in string.gmatch(searchText, "([^, ]+)") do
table.insert(words, word);
end
-- Score is the number of matching characters.
local scoredInitializers = {};
local function ParseCategory(category, parentCategory)
local layout = self:GetLayout(category);
local redirectCategory = category.redirectCategory or category;
if layout:IsVerticalLayout() then
for _, initializer in layout:EnumerateInitializers() do
if not initializer:IsSearchIgnoredInLayout(layout) and initializer:ShouldShow() then
local score = initializer:MatchesSearchTags(words);
if score then
if not scoredInitializers[score] then
scoredInitializers[score] = {};
end
table.insert(scoredInitializers[score], { initializer = initializer, category = redirectCategory });
end
end
end
end
end
for _, category in ipairs(self:GetAllCategories()) do
ParseCategory(category);
for _, subcategory in EnumerateTaintedKeysTable(category:GetSubcategories()) do
ParseCategory(subcategory, category);
end
end
local matchScores = GetKeysArray(scoredInitializers);
table.sort(matchScores, function(a, b) return a > b end);
-- Shuffle all of the initializers that are now ordered by match score into their respective category.
local scoredInitializersList = {};
local initializerLists = {};
local found = {};
for _, score in ipairs(matchScores) do
for _, match in ipairs(scoredInitializers[score]) do
local category = match.category;
local list = scoredInitializersList[category];
if not list then
list = {};
scoredInitializersList[category] = list;
table.insert(initializerLists, list);
end
if not found[category] then
found[category] = true;
table.insert(list, CreateSettingsListSearchCategoryInitializer(category));
end
table.insert(list, match.initializer);
end
end
-- Flatten the category lists back into a single array.
local initializers = {};
for index, categoryList in ipairs(initializerLists) do
tAppendAll(initializers, categoryList);
end
return initializers;
end
function SettingsPanelMixin:OnSearchTextChanged()
local initializing = (self.searchText == nil);
local text = self.SearchBox:GetText();
if text == self.searchText then
return;
end
self.searchText = text;
if initializing then
return;
end
local hasText = self.SearchBox:HasText();
if not hasText then
self:DisplayCategory(self:GetCurrentCategory());
local settingsList = self:GetSettingsList();
settingsList.Header.DefaultsButton:Show();
elseif text and string.len(text) > 0 then
local initializers = self:FindInitializersMatchingSearchText(text);
local layout = CreateVerticalLayout();
local added = {};
for _, initializer in ipairs(initializers) do
local parentInitializer = initializer.parentInitializer;
if parentInitializer and not added[parentInitializer] then
added[parentInitializer] = true;
layout:AddInitializer(parentInitializer);
end
if not added[initializer] then
added[initializer] = true;
layout:AddInitializer(initializer);
end
end
local settingsList = self:GetSettingsList();
local searchSuccess = not layout:IsEmpty();
if not searchSuccess then
layout:AddInitializer(CreateSettingsListSectionHeaderInitializer(SETTINGS_SEARCH_NOTHING_FOUND));
end
settingsList.Header.Title:SetText(SETTINGS_SEARCH_RESULTS);
self:DisplayLayout(layout);
settingsList.Header.DefaultsButton:SetShown(not hasText);
end
end
function SettingsPanelMixin:ClearSearchBox()
self.SearchBox:SetText("");
end
local function ReserveVariable(setting)
local variable = setting:GetVariable();
if reservedVariables[variable] then
return false, variable;
end
reservedVariables[variable] = true;
return true, variable;
end
function SettingsPanelMixin:RegisterSetting(category, setting)
local success, variable = securecallfunction(ReserveVariable, setting);
if not success then
error(string.format("Setting variable '%s' was previously registered.", variable));
end
self.settings[setting] = category;
SettingsInbound.RegisterOnSettingValueChanged(variable);
end
function SettingsPanelMixin:RegisterInitializer(category, initializer)
local layout = self.categoryLayouts[category];
layout:AddInitializer(initializer);
end
function SettingsPanelMixin:AssignLayoutToCategory(category, layout)
self.categoryLayouts[category] = layout;
end
function SettingsPanelMixin:GetLayout(category)
return self.categoryLayouts[category];
end
function SettingsPanelMixin:GetSetting(variable)
for setting, category in pairs(self.settings) do
local settingVariable = securecallfunction(setting.GetVariable, setting);
if settingVariable == variable then
return setting;
end
end
return nil;
end
function SettingsPanelMixin:OnSettingValueChanged(setting, value)
assert(value ~= nil);
if not self:IsShown() then
return;
end
local isModified = securecallfunction(setting.IsModified, setting);
self.modified[setting] = isModified and setting or nil;
securecallfunction(setting.UpdateIgnoreApplyFlag, setting);
self:CheckApplyButton();
SettingsInbound.RepairDisplay();
end
function SettingsPanelMixin:RepairDisplay()
local layout = self.currentLayout;
if layout then
local layoutType = layout:GetLayoutType();
if layoutType == SettingsLayoutMixin.LayoutType.Vertical then
local settingsList = self:GetSettingsList();
securecallfunction(settingsList.RepairDisplay, settingsList, layout);
end
end
end
function SettingsPanelMixin:GetAllCategories()
return self:GetCategoryList():GetAllCategories();
end
function SettingsPanelMixin:RegisterCategory(category, group, addon)
self:GetCategoryList():AddCategory(category, group, addon);
end
function SettingsPanelMixin:GetCategory(categoryName)
return self:GetCategoryList():GetCategory(categoryName);
end
function SettingsPanelMixin:GetOrCreateGroup(group, order)
return self:GetCategoryList():GetOrCreateGroup(group, order);
end
function SettingsPanelMixin:SelectFirstCategory(force)
local categories = self:GetAllCategories();
if #categories > 0 then
self:SelectCategory(categories[1], force);
end
end
function SettingsPanelMixin:ActivateCategory(category, force)
self:SelectCategory(category, force);
end
function SettingsPanelMixin:SelectCategory(category, force)
if force or (self:GetCurrentCategory() ~= category) then
self:ClearSearchBox();
self:ClearOutputText();
self:ClearCurrentCategoryCanvas();
self:SetCurrentCategory(category);
self:DisplayCategory(category);
EventRegistry:TriggerEvent("Settings.CategoryChanged", category);
end
end
function SettingsPanelMixin:SetCurrentCategory(category)
local newMode = self:GetCategoryList():SetCurrentCategory(category);
self.tabsGroup:SelectAtIndex(newMode);
self:CheckApplyButton();
end
function SettingsPanelMixin:GetCategoryList()
return self.CategoryList;
end
function SettingsPanelMixin:GetSettingsList()
return self.Container.SettingsList;
end
function SettingsPanelMixin:GetSettingsCanvas()
return self.Container.SettingsCanvas;
end
function SettingsPanelMixin:DisplayCategory(category)
if not category then
return;
end
local settingsList = self:GetSettingsList();
settingsList.Header.Title:SetText(category:GetName());
local layout = self:GetLayout(category);
self:DisplayLayout(layout);
end
function SettingsPanelMixin:SetCurrentLayout(layout)
self.currentLayout = layout;
end
function SettingsPanelMixin:GetCurrentLayout()
return self.currentLayout;
end
function SettingsPanelMixin:ClearCurrentCategoryCanvas()
local currentCategory = self:GetCurrentCategory();
if not currentCategory then
return;
end
local layout = self:GetLayout(currentCategory);
if layout:GetLayoutType() == SettingsLayoutMixin.LayoutType.Canvas then
local frame = layout:GetFrame();
frame:SetParent(nil);
frame:ClearAllPoints();
frame:Hide();
end
end
function SettingsPanelMixin:DisplayLayout(layout)
if not layout then
return;
end
SettingsInbound.SetCurrentLayout(layout);
local settingsList = self:GetSettingsList();
local settingsCanvas = self:GetSettingsCanvas();
local layoutType = layout:GetLayoutType();
if layoutType == SettingsLayoutMixin.LayoutType.Vertical then
local initializers = layout:GetInitializers();
settingsList:Display(initializers);
settingsList:Show();
settingsCanvas:Hide();
elseif layoutType == SettingsLayoutMixin.LayoutType.Canvas then
local frame = layout:GetFrame();
frame:SetParent(settingsCanvas);
frame:ClearAllPoints();
local anchors = layout:GetAnchorPoints();
if #anchors > 0 then
for index, tbl in ipairs(anchors) do
frame:SetPoint(tbl.p, tbl.x, tbl.y);
end
else
frame:SetAllPoints(settingsCanvas);
end
frame:Show();
securecallfunction(CallRefreshOnFrame, frame);
settingsCanvas:Show();
settingsList:Hide();
end
end
function SettingsPanelMixin:GetCurrentCategory()
return self:GetCategoryList():GetCurrentCategory();
end
function SettingsPanelMixin:RenewKeybinds()
EventRegistry:TriggerEvent("Settings.UpdateKeybinds");
end
function SettingsPanelMixin:SetOutputText(text)
self.OutputText:SetText(text);
end
function SettingsPanelMixin:ClearOutputText()
self.OutputText:SetText(nil);
end
function SettingsPanelMixin:OnKeybindStoppedListening(action, slotIndex)
self:RenewKeybinds();
self.SearchBox:Enable();
self.InputBlocker:Hide();
self:GetSettingsList():SetInputBlockerShown(false);
self:SetOutputText(nil);
EventRegistry:TriggerEvent("Settings.UnparentBindingsToInputBlocker");
end
function SettingsPanelMixin:OnKeybindStartedListening(action, slotIndex)
self.SearchBox:Disable();
self.InputBlocker:Show();
self.InputBlocker:SetFrameStrata("DIALOG");
local settingsList = self:GetSettingsList();
settingsList:SetInputBlockerShown(true);
self:SetOutputText(SETTINGS_BIND_KEY_TO_COMMAND_OR_CANCEL:format(GetBindingName(action), GetBindingText("ESCAPE", "KEY_")));
EventRegistry:TriggerEvent("Settings.ReparentBindingsToInputBlocker", settingsList:GetInputBlocker());
end
function SettingsPanelMixin:OnKeybindUnbindFailed(action, unbindAction, unbindSlotIndex)
local errorFormat = unbindSlotIndex == 1 and PRIMARY_KEY_UNBOUND_ERROR or KEY_UNBOUND_ERROR;
self:SetOutputText(errorFormat:format(GetBindingName(unbindAction)));
end
function SettingsPanelMixin:OnKeybindRebindFailed(action)
self:SetOutputText(KEYBINDINGFRAME_MOUSEWHEEL_ERROR);
end
function SettingsPanelMixin:OnKeybindRebindSuccess(action)
self:SetOutputText(KEY_BOUND);
end
@@ -0,0 +1,127 @@
<Ui xmlns="http://www.blizzard.com/wow/ui/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.blizzard.com/wow/ui/ ..\FrameXML\UI.xsd">
<!--
Retail's Blizzard_Settings_Shared/Blizzard_SettingsPanel.xml.
Differences:
- No Options_InnerFrame texture: this client does not have the atlas.
Blizzard_SettingsPanel.lua frames the category list and the container
with a backdrop frame each in its place.
- The search box is ClassicAPISearchBoxTemplate, retail's SearchBoxTemplate
under the name it has everywhere: Turtle's FrameXML has its own
SearchBoxTemplate without retail's behavior.
- SettingsTooltip is a child of UIParent, as 1.12's GameTooltip is, so it
takes the UI scale the way retail's TopLevelParentScaleFrameTemplate
gives it. It does not inherit NarratableTooltipTemplate: this client has
no narration.
- The Game tab reads ClassicAPI: ClassicAPI's pages are the only game
settings this client has.
- The window is not movable or resizable. Retail marks it both but gives it
no drag or size handle. In 1.12 the two flags only let the client save the
window's position and size to layout-cache.txt and put them back at the
next login, which replaces its anchor and its height.
-->
<Frame name="SettingsPanel" mixin="SettingsPanelMixin" inherits="SettingsFrameTemplate" toplevel="true" hidden="true" enableMouse="true" frameStrata="HIGH">
<Size x="920" y="724"/>
<Anchors>
<Anchor point="CENTER"/>
</Anchors>
<Layers>
<Layer level="OVERLAY" textureSubLevel="2">
<FontString parentKey="OutputText" inherits="GameFontWhite">
<Anchors>
<Anchor point="BOTTOM" x="0" y="24"/>
</Anchors>
</FontString>
</Layer>
</Layers>
<Frames>
<Button parentKey="GameTab" inherits="MinimalTabTemplate">
<Size y="37"/>
<KeyValues>
<KeyValue key="tabText" value="ClassicAPI" type="string"/>
<KeyValue key="categorySet" value="Settings.CategorySet.Game" type="global"/>
</KeyValues>
<Anchors>
<Anchor point="TOPLEFT" x="32" y="-27"/>
</Anchors>
</Button>
<Button parentKey="AddOnsTab" inherits="MinimalTabTemplate">
<Size y="37"/>
<KeyValues>
<KeyValue key="tabText" value="SETTINGS_TAB_ADDONS" type="global"/>
<KeyValue key="categorySet" value="Settings.CategorySet.AddOns" type="global"/>
</KeyValues>
<Anchors>
<Anchor point="TOPLEFT" relativeKey="$parent.GameTab" relativePoint="TOPRIGHT" x="5"/>
</Anchors>
</Button>
<Button parentKey="CloseButton" inherits="UIPanelButtonTemplate">
<Size x="96" y="22"/>
<Anchors>
<Anchor point="BOTTOMRIGHT" x="-16" y="16"/>
</Anchors>
</Button>
<Button parentKey="ApplyButton" inherits="UIPanelButtonTemplate">
<Size x="96" y="22"/>
<Anchors>
<Anchor point="RIGHT" relativeKey="$parent.CloseButton" relativePoint="LEFT" x="-2" />
</Anchors>
</Button>
<Frame parentKey="CategoryList" inherits="SettingsCategoryListTemplate">
<Size x="199" y="569"/>
<Anchors>
<Anchor point="TOPLEFT" x="18" y="-76"/>
<Anchor point="BOTTOMLEFT" x="178" y="46"/>
</Anchors>
</Frame>
<Frame parentKey="Container">
<Anchors>
<Anchor point="TOPLEFT" relativeKey="$parent.CategoryList" relativePoint="TOPRIGHT" x="16"/>
<Anchor point="BOTTOMLEFT" relativeKey="$parent.CategoryList" relativePoint="BOTTOMRIGHT" x="16" y="1"/>
<Anchor point="RIGHT" x="-22"/>
</Anchors>
<Frames>
<Frame parentKey="SettingsCanvas" setAllPoints="true"/>
<Frame parentKey="SettingsList" inherits="SettingsListTemplate" setAllPoints="true"/>
</Frames>
</Frame>
<EditBox parentKey="SearchBox" inherits="ClassicAPISearchBoxTemplate" autoFocus="false" historyLines="1" bytes="64" frameLevel="5">
<Size x="350" y="22"/>
<Anchors>
<Anchor point="BOTTOMRIGHT" relativeKey="$parent.Container" relativePoint="TOPRIGHT" x="4" y="20"/>
</Anchors>
</EditBox>
<Frame parentKey="InputBlocker" setAllPoints="true" hidden="true">
<Frames>
<Button>
<Anchors>
<Anchor point="TOPLEFT" relativeKey="$parent.$parent.CategoryList"/>
<Anchor point="BOTTOMRIGHT" relativeKey="$parent.$parent.CategoryList"/>
</Anchors>
</Button>
<Button>
<Size y="120"/>
<Anchors>
<Anchor point="TOPLEFT"/>
<Anchor point="TOPRIGHT"/>
</Anchors>
</Button>
<Button>
<Size x="50"/>
<Anchors>
<Anchor point="TOPRIGHT"/>
<Anchor point="BOTTOMRIGHT" y="40"/>
</Anchors>
</Button>
</Frames>
</Frame>
</Frames>
<Scripts>
<OnLoad method="OnLoad"/>
<OnEvent method="OnEvent"/>
<OnShow method="OnShow"/>
<OnHide method="OnHide"/>
</Scripts>
</Frame>
<GameTooltip name="SettingsTooltip" inherits="SharedTooltipTemplate" parent="UIParent" frameStrata="TOOLTIP" hidden="true"/>
</Ui>
@@ -0,0 +1,55 @@
<Ui xmlns="http://www.blizzard.com/wow/ui/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.blizzard.com/wow/ui/ ..\FrameXML\UI.xsd">
<!--
Retail's Blizzard_Settings_Shared/Mainline/Blizzard_SettingsPanelTemplates.xml.
Retail draws the window with a FlatPanelBackgroundTemplate and a
NineSlice (layout ButtonFrameTemplateNoPortrait), which this client does
not have. The window is drawn the way FrameXML\SharedUIPanelTemplates.xml
draws ButtonFrameTemplate: the tooltip border as the frame's backdrop, a
dark title bar under the title and a dark fill below it. The fill (Bg) is
a texture of the window, under everything the window draws: as a child
frame it drew over the window's own regions, its output line among them.
The NineSlice frame stays, holding the title bar and the title, because
the panel sets its title through NineSlice.Text.
-->
<Frame name="SettingsFrameTemplate" virtual="true">
<Backdrop edgeFile="Interface\Tooltips\UI-Tooltip-Border">
<EdgeSize val="16"/>
</Backdrop>
<Layers>
<Layer level="BACKGROUND">
<Texture parentKey="Bg">
<Anchors>
<Anchor point="TOPLEFT" x="5" y="-24"/>
<Anchor point="BOTTOMRIGHT" x="-5" y="5"/>
</Anchors>
<Color r="0" g="0" b="0" a="0.75"/>
</Texture>
</Layer>
</Layers>
<Frames>
<Frame parentKey="NineSlice" useParentLevel="true" setAllPoints="true">
<Layers>
<Layer level="BACKGROUND">
<Texture>
<Anchors>
<Anchor point="TOPLEFT" x="5" y="-5"/>
<Anchor point="BOTTOMRIGHT" relativePoint="TOPRIGHT" x="-5" y="-24"/>
</Anchors>
<Color r="0.1" g="0.1" b="0.1" a="0.95"/>
</Texture>
</Layer>
<Layer level="OVERLAY">
<FontString parentKey="Text" inherits="GameFontNormal" wordwrap="false">
<Anchors>
<Anchor point="TOP" x="0" y="-6"/>
<Anchor point="LEFT" x="60"/>
<Anchor point="RIGHT" x="-60"/>
</Anchors>
</FontString>
</Layer>
</Layers>
</Frame>
<Button parentKey="ClosePanelButton" inherits="UIPanelCloseButtonDefaultAnchors"/>
</Frames>
</Frame>
</Ui>
@@ -0,0 +1,35 @@
-- Backport of retail's Blizzard_Settings_Shared/Blizzard_SettingsRegistrar.lua.
--
-- The one difference: this file loads only on the game screen, so the
-- glue-screen branch is gone.
local securecallfunction = securecallfunction;
SettingsRegistrar = {};
function SettingsRegistrar:OnLoad()
self.registrants = {};
local function Callback()
self.allowCallRegistrants = true;
local function CallRegistrant(index, registrant)
registrant();
end
secureexecuterange(self.registrants, CallRegistrant);
C_SettingsUtil.NotifySettingsLoaded();
end
EventUtil.ContinueAfterAllEvents(Callback, "VARIABLES_LOADED", "PLAYER_ENTERING_WORLD");
end
function SettingsRegistrar:AddRegistrant(registrant)
if self.allowCallRegistrants then
securecallfunction(registrant);
else
table.insert(self.registrants, registrant);
end
end
SettingsRegistrar:OnLoad();
@@ -96,3 +96,11 @@ function PetActionButtonUp(id)
end
end
end
-- Retail's binding-highlight registry (Blizzard_ActionBar/Shared/ActionButton.lua).
-- A Settings key binding row registers for its action on it. Retail's action
-- buttons trigger it while the cursor is over them; 1.12's action buttons do
-- not, so nothing triggers it here.
ActionButtonBindingHighlightCallbackRegistry = CreateFromMixins(CallbackRegistryMixin);
ActionButtonBindingHighlightCallbackRegistry:SetUndefinedEventsAllowed(true);
ActionButtonBindingHighlightCallbackRegistry:OnLoad();
@@ -0,0 +1,206 @@
-- Backport of retail's Blizzard_SharedXML/BindingUtil.lua.
--
-- Differences from the retail source:
-- - Binding names are globals: this client has no GetCurrentEnvironment.
-- - No META in a key chord: this client has no IsMetaKeyDown.
-- - Mouse buttons stop at Button5: this client binds five.
-- - Binding text goes through 1.12's GetBindingText with the "KEY_"
-- prefix. Retail's GetBindingText uses that prefix by itself; 1.12's,
-- from FrameXML, uses no prefix unless it is given one.
-- - No custom binding buttons (CustomBindingManager), no quick keybind
-- mode and no mouseover casting: this client has none of them.
BindingUtil = {};
local metaKeys =
{
LALT = 1,
RALT = 2,
LCTRL = 3,
RCTRL = 4,
LSHIFT = 5,
RSHIFT = 6,
LMETA = 7,
RMETA = 8,
ALT = 9,
CTRL = 10,
SHIFT = 11,
META = 12,
};
local ignoredKeys =
{
UNKNOWN = true,
BUTTON1 = true,
BUTTON2 = true,
};
local mouseButtonNameConversion =
{
LeftButton = "BUTTON1",
RightButton = "BUTTON2",
MiddleButton = "BUTTON3",
Button1 = "BUTTON1",
Button2 = "BUTTON2",
Button3 = "BUTTON3",
Button4 = "BUTTON4",
Button5 = "BUTTON5",
};
function GetConvertedKeyOrButton(keyOrButton)
return mouseButtonNameConversion[keyOrButton] or keyOrButton;
end
function IsMouseButton(button)
return mouseButtonNameConversion[button] ~= nil;
end
function IsLeftMouseButton(button)
return mouseButtonNameConversion[button] == "BUTTON1";
end
function IsRightMouseButton(button)
return mouseButtonNameConversion[button] == "BUTTON2";
end
function IsMiddleMouseButton(button)
return mouseButtonNameConversion[button] == "BUTTON3";
end
function IsMetaKey(key)
return metaKeys[key] ~= nil;
end
function IsKeyPressIgnoredForBinding(key)
return IsMetaKey(key) or ignoredKeys[key] == true;
end
local function KeyComparator(key1, key2)
local key1Priority = metaKeys[key1];
local key2Priority = metaKeys[key2];
if key1Priority and key2Priority then
return key1Priority < key2Priority;
end
return key1Priority ~= nil;
end
function CreateKeyChordStringFromTable(keys, preventSort)
if not preventSort then
table.sort(keys, KeyComparator);
end
return table.concat(keys, "-");
end
function CreateKeyChordString(key, ...)
return CreateKeyChordStringFromTable({ key, ... });
end
function CreateKeyChordStringUsingMetaKeyState(key)
local chord = {};
if IsAltKeyDown() then
table.insert(chord, "ALT");
end
if IsControlKeyDown() then
table.insert(chord, "CTRL");
end
if IsShiftKeyDown() then
table.insert(chord, "SHIFT");
end
if not IsMetaKey(key) then
table.insert(chord, key);
end
local preventSort = true;
return CreateKeyChordStringFromTable(chord, preventSort);
end
function GetBindingName(binding)
local bindingName = _G["BINDING_NAME_"..binding];
if ( bindingName ) then
return bindingName;
end
return binding;
end
function GetBindingKeyForAction(action, useNotBound, useParentheses)
local key = GetBindingKey(action);
if key then
key = GetBindingText(key, "KEY_");
elseif useNotBound then
key = NOT_BOUND;
end
if key and useParentheses then
return ("(%s)"):format(key);
end
return key;
end
-- Gets the key string for the action and formats it into keyStringFormat, then formats
-- that and the original text into bindingAvailableFormat and returns the resulting string.
-- NOTE: The argument ordering for bindingAvailableFormat should be original text and then binding string text.
-- NOTE: If there is no binding and useNotBound is set, then the NOT_BOUND string is formatted into the location
-- where the key string would normally appear, otherwise only the original text is returned.
function FormatBindingKeyIntoText(text, action, bindingAvailableFormat, keyStringFormat, useNotBound, useParentheses)
local bindingKey = GetBindingKeyForAction(action, useNotBound, useParentheses);
if bindingKey then
bindingAvailableFormat = bindingAvailableFormat or "%s %s";
keyStringFormat = keyStringFormat or "%s";
local keyString = keyStringFormat:format(bindingKey);
return bindingAvailableFormat:format(text, keyString);
end
return text;
end
function MicroButtonTooltipText(text, action)
local keyStringFormat = WrapTextInColor("(%s)", NORMAL_FONT_COLOR);
local bindingAvailableFormat = "%s %s";
return FormatBindingKeyIntoText(text, action, bindingAvailableFormat, keyStringFormat);
end
function BindingButtonTemplate_SetSelected(keyBindingButton, isSelected)
keyBindingButton.selectedHighlight:SetShown(isSelected);
keyBindingButton.isSelected = isSelected;
if isSelected then
keyBindingButton:GetHighlightTexture():SetAlpha(0);
else
keyBindingButton:GetHighlightTexture():SetAlpha(1);
end
return isSelected;
end
function BindingButtonTemplate_ToggleSelected(keyBindingButton)
return BindingButtonTemplate_SetSelected(keyBindingButton, not keyBindingButton.isSelected);
end
function BindingButtonTemplate_IsSelected(keyBindingButton)
return keyBindingButton.isSelected;
end
function BindingButtonTemplate_SetupBindingButton(binding, button)
local bindingText;
if binding then
bindingText = GetBindingText(binding, "KEY_");
end
if bindingText then
button:SetText(bindingText);
button:SetAlpha(1);
else
button:SetText(GRAY_FONT_COLOR:WrapTextInColorCode(NOT_BOUND));
button:SetAlpha(0.8);
end
return bindingText;
end
@@ -0,0 +1,259 @@
-- Backport of retail's Blizzard_SharedXMLBase/CvarUtil.lua.
--
-- Differences from the retail source:
-- - RegisterCVar, GetCVar, SetCVar and GetCVarDefault are the engine's own
-- globals here, so this file does not replace them with wrappers over
-- C_CVar. ResetTestCvars is gone: this client has no test cvars.
-- - GetCVarTable and the functions on it are gone: they store a table in a
-- cvar through C_EncodingUtil's CBOR and Base64, which this client does
-- not have.
-- - CVarCallbackRegistry caches a value without asking issecure: this
-- client has no taint, so every read is secure.
function SetCVarToDefault(name)
SetCVar(name, GetCVarDefault(name))
end
function GetCVarBitfield(name, index)
return C_CVar.GetCVarBitfield(name, index);
end
function SetCVarBitfield(name, index, value, scriptCVar)
return C_CVar.SetCVarBitfield(name, index, value, scriptCVar);
end
function GetCVarBool(name)
return C_CVar.GetCVarBool(name);
end
function GetCVarNumberOrDefault(name)
local number = tonumber(GetCVar(name));
return number or tonumber(GetCVarDefault(name));
end
-- Assumes every value stored in the cvar is of the same type. The purpose
-- of using this accessor is to add type strictness to avoid scenarios where
-- nil is implicitly converted to "0" or false and to relieve the callsites of
-- casting concerns.
CVarAccessorMixin = {};
function CVarAccessorMixin:Init(cvar, variableType)
if variableType == "boolean" then
self.ConvertValue = function(self, value)
return value and value ~= "0";
end;
elseif variableType == "number" then
self.ConvertValue = function(self, value)
return tonumber(value);
end;
elseif variableType == "string" then
self.ConvertValue = function(self, value)
return (value ~= nil) and tostring(value) or "";
end;
end
self.GetValue = function(self)
local rawValue = GetCVar(cvar);
return self:ConvertValue(rawValue);
end;
self.SetValue = function(self, value)
if type(value) ~= variableType then
error(string.format("SetValue requires '%s' type", variableType));
end
if type(value) == "boolean" then
SetCVar(cvar, value and "1" or "0");
else
SetCVar(cvar, tostring(value));
end
end;
self.GetDefaultValue = function(self)
local rawValue = GetCVarDefault(cvar);
return self:ConvertValue(rawValue);
end;
end
function CreateCVarAccessor(cvar, variableType)
if variableType ~= "number" and variableType ~= "boolean" and variableType ~= "string" then
error(string.format("CreateCVarAccessor requires 'number', 'boolean' or 'string' type. Provided '%s' type.", variableType));
end
return CreateAndInitFromMixin(CVarAccessorMixin, cvar, variableType);
end
CVarCallbackRegistry = CreateFromMixins(CallbackRegistryMixin);
CVarCallbackRegistry:GenerateCallbackEvents(
{
"OnCVarChanged",
}
);
function CVarCallbackRegistry:OnLoad()
CallbackRegistryMixin.OnLoad(self);
self.cachable = {};
self.cvarValueCache = {};
self:SetScript("OnEvent", self.OnEvent);
self:RegisterEvent("CVAR_UPDATE");
end
function CVarCallbackRegistry:OnEvent(event, ...)
if event == "CVAR_UPDATE" then
local cvar, value = ...;
if self.cachable[cvar] then
self.cvarValueCache[cvar] = value;
end
self:TriggerEvent(CVarCallbackRegistry.Event.OnCVarChanged, cvar, value);
self:TriggerEvent(cvar, value);
end
end
function CVarCallbackRegistry:GetCVarValue(cvar)
local value = self.cvarValueCache[cvar];
if value == nil then
value = GetCVar(cvar);
if self.cachable[cvar] then
self.cvarValueCache[cvar] = value;
end
end
return value;
end
function CVarCallbackRegistry:GetCVarValueBool(cvar)
local value = self:GetCVarValue(cvar);
return (value ~= nil) and value ~= "0";
end
function CVarCallbackRegistry:GetCVarBitfieldIndex(cvar, index)
local value = self:GetCVarValue(cvar);
-- Index is decremented going into C++.
index = index - 1;
-- Must match CVAR_ARRAY_BITS_STORED_PER_BYTE
local bitsPerByte = 6;
local totalBits = (#value - 1) * bitsPerByte;
if index >= totalBits then
return false;
end
-- byteIndex is offset by 1 in C++, and add another 1 to account for 1-based index in lua.
local byteIndex = 2 + math.floor(index / bitsPerByte);
local byte = string.byte(value, byteIndex);
if not byte then
return false
end
local bitIndex = index % bitsPerByte;
local shiftedBitIndex = bit.lshift(1, bitIndex);
return bit.band(byte, shiftedBitIndex) ~= 0;
end
function CVarCallbackRegistry:GetCVarNumberOrDefault(cvar)
local number = tonumber(self:GetCVarValue(cvar));
return number or tonumber(GetCVarDefault(cvar));
end
function CVarCallbackRegistry:SetCVarCachable(cvar)
self.cachable[cvar] = true;
end
function CVarCallbackRegistry:ClearCache(cvar)
self.cvarValueCache[cvar] = nil;
end
function CVarCallbackRegistry:GetCVarBitfieldDefault(cvar)
local value = GetCVarDefault(cvar);
local bitmask = 0;
local bitsPerByte = 6; -- CVAR_ARRAY_BITS_STORED_PER_BYTE
-- Process each data byte (skip version byte at index 1)
for byteIndex = 2, #value do
local byte = string.byte(value, byteIndex);
if not byte then
break;
end
-- Each byte stores 6 bits of data
for bitIndex = 0, bitsPerByte - 1 do
if bit.band(byte, bit.lshift(1, bitIndex)) ~= 0 then
local overallBitIndex = (byteIndex - 2) * bitsPerByte + bitIndex;
bitmask = bit.bor(bitmask, bit.lshift(1, overallBitIndex));
end
end
end
return bitmask;
end
function CVarCallbackRegistry:SetCVarBitfieldMask(cvar, mask)
local value = self:GetCVarValue(cvar);
local bitsPerByte = 6; -- CVAR_ARRAY_BITS_STORED_PER_BYTE
local maxStringSize = 256;
-- Extract the version from the existing value.
local version = string.byte(value, 1);
-- Start with version byte from existing value
local buffer = string.char(version);
-- Convert mask to individual bits and pack them into bytes
local currentMask = mask;
local byteIndex = 2; -- Start after version byte
while currentMask > 0 and byteIndex < maxStringSize do
local dataByte = 0;
-- Extract up to 6 bits for this byte
for bitIndex = 0, bitsPerByte - 1 do
if currentMask > 0 and bit.band(currentMask, 1) ~= 0 then
dataByte = bit.bor(dataByte, bit.lshift(1, bitIndex));
end
currentMask = bit.rshift(currentMask, 1);
end
-- Set bit 6 to maintain the format 0b01xxxxxx (bit 6 = 1, bit 7 = 0)
dataByte = bit.bor(dataByte, 0x40); -- 0x40 = 64 = 2^6
-- Make sure bit 7 is not set (should never happen with our logic)
dataByte = bit.band(dataByte, 0x7F); -- 0x7F = 127 = 2^7 - 1
buffer = buffer .. string.char(dataByte);
byteIndex = byteIndex + 1;
end
-- Remove trailing bytes that are just the padding value (0x40)
-- This matches the C++ logic that shortens the string by removing trailing padding
while #buffer > 1 do
local lastByte = string.byte(buffer, -1);
if lastByte == 0x40 then -- 64 = padding byte with no data bits set
buffer = string.sub(buffer, 1, -2);
else
break;
end
end
SetCVar(cvar, buffer);
end
-- NOTE: This will invoke the supplied callback for **ALL** CVar changes, as
-- if listening directly for the CVAR_UPDATE event.
--
-- You probably don't want this! Instead, call RegisterCallback("cvarName", func[, owner])
-- instead to only receive updates for individual CVars.
function CVarCallbackRegistry:RegisterCallbackForAllCVarUpdates(func, owner, ...)
return self:RegisterCallback(CVarCallbackRegistry.Event.OnCVarChanged, func, owner, ...);
end
CVarCallbackRegistry = Mixin(CreateFrame("Frame"), CVarCallbackRegistry);
CVarCallbackRegistry:OnLoad();
CVarCallbackRegistry:SetUndefinedEventsAllowed(true);
@@ -12,3 +12,11 @@ function CreateAndInitFromMixin(mixin, ...)
object:Init(unpack(arg))
return object
end
-- Retail copies the mixin with PrivateMixin so the copy carries no taint;
-- 1.12 has no taint, so the copy is a plain Mixin.
function CreateSecureMixinCopy(mixin)
local mixinCopy = Mixin({}, mixin)
setmetatable(mixinCopy, { __metatable = false })
return mixinCopy
end
@@ -233,3 +233,28 @@ TEXT_TO_SPEECH_ADJUST_VOLUME = "Sprechlautstärke";
TEXT_TO_SPEECH_VOICE_OPTION = "Stimmenauswahl";
TOTAL_MEM_KB_ABBR = "Speicher für Addons: %.0f KB";
TOTAL_MEM_MB_ABBR = "Speicher für Addons: %.2f MB";
ALL_SETTINGS = "Alle Einstell.";
ALT_KEY = "ALT-Taste";
CONFIRM_RESET_INTERFACE_SETTINGS = "Wollen Sie alle Interface- und Addon-Einstellungen zurücksetzen oder nur die Einstellungen für diese Kategorie oder dieses Addon?";
CTRL_KEY = "STRG-Taste";
CURRENT_SETTINGS = "Diese Einstell.";
CUSTOM = "Benutzer";
NONE_KEY = "Keine";
PRIMARY_KEY_UNBOUND_ERROR = "|cffff0000%s-Primäraktion ist jetzt nicht belegt!|r";
SETTINGS_APPLY = "Anwenden";
SETTINGS_CLOSE = "Schließen";
SETTINGS_CONFIRM_DISCARD = "Manche Einstellungen wurden noch nicht angewandt.\nMöchten Sie den Bereich wirklich verlassen?";
SETTINGS_DEFAULTS = "Standard";
SETTINGS_SEARCH_NOTHING_FOUND = "Keine Ergebnisse gefunden. Probiert es mit anderen Suchkriterien.";
SETTINGS_SEARCH_RESULTS = "Ergebnisse:";
SETTINGS_SUBCATEGORY_FMT = "%s (%s)";
SETTINGS_TAB_ADDONS = "Addons";
SETTINGS_TAB_GAME = "Spiel";
SETTINGS_TITLE = "Optionen";
SETTINGS_UNAPPLIED_APPLY_AND_EXIT = "Anwenden und verlassen";
SETTINGS_UNAPPLIED_CANCEL = "Abbrechen";
SETTINGS_UNAPPLIED_EXIT = "Verlassen";
SHIFT_KEY = "Umschalttaste";
VIDEO_OPTIONS_NEED_CLIENTRESTART = "Das Ändern dieser Option führt dazu, dass der Client neu gestartet werden muss";
VIDEO_OPTIONS_RECOMMENDED = "Empfohlen";
@@ -74,7 +74,6 @@ CLASSICAPI_MOTION = "Motion";
CLASSICAPI_NAME_SUGGESTIONS = "Name Suggestions";
CLASSICAPI_NAMEPLATES = "Nameplates";
CLASSICAPI_NUMBERS = "Numbers";
CLASSICAPI_OPTIONS_ABOUT = "Settings for the features that ClassicAPI adds to the game. Each option changes one setting, and the change applies at once.";
CLASSICAPI_OTHER_NAMEPLATE_ALPHA = "Other Nameplate Opacity";
CLASSICAPI_OTHER_NAMEPLATE_ALPHA_TOOLTIP = "The opacity of the nameplates of units that are not your target.";
CLASSICAPI_PREFER_YOUR_TARGET = "Prefer Your Target";
@@ -329,3 +328,28 @@ TEXT_TO_SPEECH_ADJUST_VOLUME = "Speech Volume";
TEXT_TO_SPEECH_VOICE_OPTION = "Voice Option";
TOTAL_MEM_KB_ABBR = "AddOn Memory: %.0f KB";
TOTAL_MEM_MB_ABBR = "AddOn Memory: %.2f MB";
ALL_SETTINGS = "All Settings";
ALT_KEY = "ALT key";
CONFIRM_RESET_INTERFACE_SETTINGS = "Do you want to reset all user interface and addon settings to their defaults, or only the settings for this category or addon?";
CTRL_KEY = "CTRL key";
CURRENT_SETTINGS = "These Settings";
CUSTOM = "Custom";
NONE_KEY = "None";
PRIMARY_KEY_UNBOUND_ERROR = "|cffff0000Primary Action %s is Now Unbound!|r";
SETTINGS_APPLY = "Apply";
SETTINGS_CLOSE = "Close";
SETTINGS_CONFIRM_DISCARD = "You have settings that have not been applied.\nAre you sure you wish to exit?";
SETTINGS_DEFAULTS = "Defaults";
SETTINGS_SEARCH_NOTHING_FOUND = "No results found. Try adjusting your search criteria.";
SETTINGS_SEARCH_RESULTS = "Results:";
SETTINGS_SUBCATEGORY_FMT = "%s (%s)";
SETTINGS_TAB_ADDONS = "AddOns";
SETTINGS_TAB_GAME = "Game";
SETTINGS_TITLE = "Options";
SETTINGS_UNAPPLIED_APPLY_AND_EXIT = "Apply and Exit";
SETTINGS_UNAPPLIED_CANCEL = "Cancel";
SETTINGS_UNAPPLIED_EXIT = "Exit";
SHIFT_KEY = "SHIFT key";
VIDEO_OPTIONS_NEED_CLIENTRESTART = "Changing this option requires a client restart";
VIDEO_OPTIONS_RECOMMENDED = "Recommended";
@@ -233,3 +233,28 @@ TEXT_TO_SPEECH_ADJUST_VOLUME = "Volumen de voz";
TEXT_TO_SPEECH_VOICE_OPTION = "Opción de voz";
TOTAL_MEM_KB_ABBR = "Memoria de addon: %.0f KB";
TOTAL_MEM_MB_ABBR = "Memoria de addon: %.2f MB";
ALL_SETTINGS = "Restablecer todo";
ALT_KEY = "Alt";
CONFIRM_RESET_INTERFACE_SETTINGS = "¿Quieres restablecer la configuración original de toda la interfaz y todos los addons? ¿O solo la de esta categoría o addon?";
CTRL_KEY = "Control";
CURRENT_SETTINGS = "Esta configuración";
CUSTOM = "Pers.";
NONE_KEY = "Nada";
PRIMARY_KEY_UNBOUND_ERROR = "|cffff0000La acción principal %s ya no está asignada.|r";
SETTINGS_APPLY = "Aplicar";
SETTINGS_CLOSE = "Cerrar";
SETTINGS_CONFIRM_DISCARD = "Tienes opciones de configuración sin aplicar.\n¿Seguro que quieres salir?";
SETTINGS_DEFAULTS = "Predeterm.";
SETTINGS_SEARCH_NOTHING_FOUND = "No se encontraron resultados. Intenta ajustar tus criterios de búsqueda.";
SETTINGS_SEARCH_RESULTS = "Resultados:";
SETTINGS_SUBCATEGORY_FMT = "%s (%s)";
SETTINGS_TAB_ADDONS = "Addons";
SETTINGS_TAB_GAME = "Juego";
SETTINGS_TITLE = "Opciones";
SETTINGS_UNAPPLIED_APPLY_AND_EXIT = "Aplicar y salir";
SETTINGS_UNAPPLIED_CANCEL = "Cancelar";
SETTINGS_UNAPPLIED_EXIT = "Salir";
SHIFT_KEY = "Mayús";
VIDEO_OPTIONS_NEED_CLIENTRESTART = "Cambiar esta opción requiere reiniciar el cliente.";
VIDEO_OPTIONS_RECOMMENDED = "Recomendado";
@@ -233,3 +233,28 @@ TEXT_TO_SPEECH_ADJUST_VOLUME = "Volume de la voix";
TEXT_TO_SPEECH_VOICE_OPTION = "Option vocale";
TOTAL_MEM_KB_ABBR = "Mémoire add-on : %.0f Ko";
TOTAL_MEM_MB_ABBR = "Mémoire add-on : %.2f Mo";
ALL_SETTINGS = "Tous les réglages";
ALT_KEY = "Touche ALT";
CONFIRM_RESET_INTERFACE_SETTINGS = "Voulez-vous réinitialiser tous les réglages de l'interface utilisateur et des add-ons, ou seulement les réglages de cette catégorie ou de cet add-on ?";
CTRL_KEY = "Touche CTRL";
CURRENT_SETTINGS = "Ces réglages";
CUSTOM = "Personnalisé";
NONE_KEY = "Aucune";
PRIMARY_KEY_UNBOUND_ERROR = "|cffff0000%s : aucune commande associée à l’action principale !|r";
SETTINGS_APPLY = "Appliquer";
SETTINGS_CLOSE = "Fermer";
SETTINGS_CONFIRM_DISCARD = "Certains paramètres n’ont pas été appliqués.\nSouhaitez-vous vraiment quitter ?";
SETTINGS_DEFAULTS = "Par défaut";
SETTINGS_SEARCH_NOTHING_FOUND = "Aucun résultat. Veuillez modifier votre critère de recherche.";
SETTINGS_SEARCH_RESULTS = "Résultats :";
SETTINGS_SUBCATEGORY_FMT = "%s (%s)";
SETTINGS_TAB_ADDONS = "Add-ons";
SETTINGS_TAB_GAME = "Jeu";
SETTINGS_TITLE = "Options";
SETTINGS_UNAPPLIED_APPLY_AND_EXIT = "Appliquer et fermer";
SETTINGS_UNAPPLIED_CANCEL = "Annuler";
SETTINGS_UNAPPLIED_EXIT = "Quitter";
SHIFT_KEY = "Touche MAJ";
VIDEO_OPTIONS_NEED_CLIENTRESTART = "Changer cette option nécessite de relancer le programme.";
VIDEO_OPTIONS_RECOMMENDED = "Recommandé";
@@ -20,3 +20,28 @@ SETTINGS_BIND_KEY_TO_COMMAND_OR_CANCEL = "\"%s\" 단축키 지정 또는 %s 눌
CLASSICAPI_CURSOR = "커서";
CLASSICAPI_EXPANDED_CURSORS = "확장 커서 표시";
CLASSICAPI_EXPANDED_CURSORS_TOOLTIP = "NPC나 물체를 가리키면 커서가 할 수 있는 행동을 보여줍니다. 예를 들어 수리는 모루, 퀘스트는 ! 또는 ?, 낚시찌는 낚싯바늘로 표시됩니다.";
ALL_SETTINGS = "모든 설정";
ALT_KEY = "ALT 키";
CONFIRM_RESET_INTERFACE_SETTINGS = "모든 인터페이스와 애드온 설정을 초기화하시겠습니까, 아니면 이 범주의 설정만 초기화하시겠습니까?";
CTRL_KEY = "CTRL 키";
CURRENT_SETTINGS = "현재 설정";
CUSTOM = "사용자 설정";
NONE_KEY = "없음";
PRIMARY_KEY_UNBOUND_ERROR = "|cffff0000주요 행동 %s의 단축키가 해제됩니다!|r";
SETTINGS_APPLY = "적용";
SETTINGS_CLOSE = "닫기";
SETTINGS_CONFIRM_DISCARD = "적용하지 않은 설정이 있습니다.\n정말로 나가시겠습니까?";
SETTINGS_DEFAULTS = "기본 설정";
SETTINGS_SEARCH_NOTHING_FOUND = "결과가 없습니다. 검색 조건을 조정해주시기 바랍니다.";
SETTINGS_SEARCH_RESULTS = "결과:";
SETTINGS_SUBCATEGORY_FMT = "%s (%s)";
SETTINGS_TAB_ADDONS = "애드온";
SETTINGS_TAB_GAME = "게임";
SETTINGS_TITLE = "설정";
SETTINGS_UNAPPLIED_APPLY_AND_EXIT = "적용 및 나가기";
SETTINGS_UNAPPLIED_CANCEL = "취소";
SETTINGS_UNAPPLIED_EXIT = "닫기";
SHIFT_KEY = "SHIFT 키";
VIDEO_OPTIONS_NEED_CLIENTRESTART = "이 설정을 변경하면 클라이언트를 다시 시작해야 합니다.";
VIDEO_OPTIONS_RECOMMENDED = "권장 설정";
@@ -76,7 +76,6 @@ CLASSICAPI_MOTION = "Движение";
CLASSICAPI_NAME_SUGGESTIONS = "Подсказки имен";
CLASSICAPI_NAMEPLATES = "Таблички с именами";
CLASSICAPI_NUMBERS = "Числа";
CLASSICAPI_OPTIONS_ABOUT = "Настройки возможностей, которые ClassicAPI добавляет в игру. Каждый параметр меняет одну настройку, и изменение применяется сразу.";
CLASSICAPI_OTHER_NAMEPLATE_ALPHA = "Непрозрачность чужих табличек";
CLASSICAPI_OTHER_NAMEPLATE_ALPHA_TOOLTIP = "Непрозрачность табличек с именами целей, которые не являются вашей целью.";
CLASSICAPI_PREFER_YOUR_TARGET = "Отдавать предпочтение вашей цели";
@@ -331,3 +330,28 @@ TEXT_TO_SPEECH_ADJUST_VOLUME = "Громкость речи";
TEXT_TO_SPEECH_VOICE_OPTION = "Выбор голоса";
TOTAL_MEM_KB_ABBR = "Память модификаций: %.0f КБ";
TOTAL_MEM_MB_ABBR = "Память модификаций: %.2f МБ";
ALL_SETTINGS = "Все параметры";
ALT_KEY = "ALT";
CONFIRM_RESET_INTERFACE_SETTINGS = "Вы хотите сбросить все настройки для пользовательского интерфейса и модификаций, или только настройки для этого раздела или модификации?";
CTRL_KEY = "CTRL";
CURRENT_SETTINGS = "Этот раздел";
CUSTOM = "Вручную";
NONE_KEY = "Нет";
PRIMARY_KEY_UNBOUND_ERROR = "|cffff0000Для основной команды \"%1$s\" не назначена клавиша!|r";
SETTINGS_APPLY = "Сохранить";
SETTINGS_CLOSE = "Закрыть";
SETTINGS_CONFIRM_DISCARD = "Вы не сохранили некоторые настройки.\nВы точно хотите выйти?";
SETTINGS_DEFAULTS = "По умолчанию";
SETTINGS_SEARCH_NOTHING_FOUND = "Ничего не найдено. Попробуйте изменить условия поиска.";
SETTINGS_SEARCH_RESULTS = "Результаты:";
SETTINGS_SUBCATEGORY_FMT = "%s (%s)";
SETTINGS_TAB_ADDONS = "Модификации";
SETTINGS_TAB_GAME = "Игра";
SETTINGS_TITLE = "Параметры";
SETTINGS_UNAPPLIED_APPLY_AND_EXIT = "Сохранить и выйти";
SETTINGS_UNAPPLIED_CANCEL = "Отмена";
SETTINGS_UNAPPLIED_EXIT = "Выйти";
SHIFT_KEY = "SHIFT";
VIDEO_OPTIONS_NEED_CLIENTRESTART = "Изменение этого параметра потребует перезапуска игры.";
VIDEO_OPTIONS_RECOMMENDED = "Рекомендуется";
@@ -76,7 +76,6 @@ CLASSICAPI_MOTION = "动态效果";
CLASSICAPI_NAME_SUGGESTIONS = "名称建议";
CLASSICAPI_NAMEPLATES = "姓名板";
CLASSICAPI_NUMBERS = "数字";
CLASSICAPI_OPTIONS_ABOUT = "ClassicAPI为游戏添加的功能设置。\n每个选项对应一项设置,修改后立即生效。";
CLASSICAPI_OTHER_NAMEPLATE_ALPHA = "其他姓名板不透明度";
CLASSICAPI_OTHER_NAMEPLATE_ALPHA_TOOLTIP = "非目标单位姓名板的不透明度。";
CLASSICAPI_PREFER_YOUR_TARGET = "优先你的目标";
@@ -331,3 +330,28 @@ TEXT_TO_SPEECH_ADJUST_VOLUME = "音量";
TEXT_TO_SPEECH_VOICE_OPTION = "语音设置";
TOTAL_MEM_KB_ABBR = "插件内存:%.0f KB";
TOTAL_MEM_MB_ABBR = "插件内存:%.2f MB";
ALL_SETTINGS = "所有设置";
ALT_KEY = "ALT键";
CONFIRM_RESET_INTERFACE_SETTINGS = "你想要将所有用户界面和插件设置重置为默认状态,还是只重置这个界面或插件的设置?";
CTRL_KEY = "CTRL键";
CURRENT_SETTINGS = "这些设置";
CUSTOM = "自定义";
NONE_KEY = "无";
PRIMARY_KEY_UNBOUND_ERROR = "|cffff0000主要动作 %s 现在没有绑定!|r";
SETTINGS_APPLY = "应用";
SETTINGS_CLOSE = "关闭";
SETTINGS_CONFIRM_DISCARD = "你尚有还未应用的设置。\n你确定要退出吗?";
SETTINGS_DEFAULTS = "默认设置";
SETTINGS_SEARCH_NOTHING_FOUND = "未发现结果。请修改你的搜索条件。";
SETTINGS_SEARCH_RESULTS = "搜寻结果:";
SETTINGS_SUBCATEGORY_FMT = "%s(%s)";
SETTINGS_TAB_ADDONS = "插件";
SETTINGS_TAB_GAME = "游戏";
SETTINGS_TITLE = "选项";
SETTINGS_UNAPPLIED_APPLY_AND_EXIT = "应用并退出";
SETTINGS_UNAPPLIED_CANCEL = "取消";
SETTINGS_UNAPPLIED_EXIT = "退出";
SHIFT_KEY = "SHIFT键";
VIDEO_OPTIONS_NEED_CLIENTRESTART = "更改此选项需要重新启动客户端";
VIDEO_OPTIONS_RECOMMENDED = "推荐";
@@ -233,3 +233,28 @@ TEXT_TO_SPEECH_ADJUST_VOLUME = "語音音量";
TEXT_TO_SPEECH_VOICE_OPTION = "聲音選項";
TOTAL_MEM_KB_ABBR = "插件記憶體:%.0f KB";
TOTAL_MEM_MB_ABBR = "插件記憶體:%.2f MB";
ALL_SETTINGS = "所有設定";
ALT_KEY = "ALT鍵";
CONFIRM_RESET_INTERFACE_SETTINGS = "你想要將所有使用者介面和插件的設定還原成預設值,或者僅還原此類別和插件的設定呢?";
CTRL_KEY = "CTRL鍵";
CURRENT_SETTINGS = "這些設定";
CUSTOM = "自訂";
NONE_KEY = "無";
PRIMARY_KEY_UNBOUND_ERROR = "|cffff0000%s主要行動已解除設定!|r";
SETTINGS_APPLY = "套用";
SETTINGS_CLOSE = "關閉";
SETTINGS_CONFIRM_DISCARD = "你有尚未套用的設定。\n你確定要離開嗎?";
SETTINGS_DEFAULTS = "預設值";
SETTINGS_SEARCH_NOTHING_FOUND = "搜尋不到,請更改搜尋條件。";
SETTINGS_SEARCH_RESULTS = "結果:";
SETTINGS_SUBCATEGORY_FMT = "%s(%s)";
SETTINGS_TAB_ADDONS = "插件";
SETTINGS_TAB_GAME = "遊戲";
SETTINGS_TITLE = "選項";
SETTINGS_UNAPPLIED_APPLY_AND_EXIT = "套用並退出";
SETTINGS_UNAPPLIED_CANCEL = "取消";
SETTINGS_UNAPPLIED_EXIT = "退出";
SHIFT_KEY = "SHIFT鍵";
VIDEO_OPTIONS_NEED_CLIENTRESTART = "改變這個選項需要重新啟動遊戲。";
VIDEO_OPTIONS_RECOMMENDED = "建議";
+128
View File
@@ -0,0 +1,128 @@
// This file is part of ClassicAPI.
//
// ClassicAPI is free software: you can redistribute it and/or modify it under the terms
// of the GNU General Public License as published by the Free Software Foundation, either
// version 3 of the License, or (at your option) any later version.
//
// ClassicAPI is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along with
// ClassicAPI. If not, see <https://www.gnu.org/licenses/>.
// A frame's show and hide survive a child that moves frames from its OnShow
// or OnHide.
//
// When a frame becomes visible, 1.12's FUN_SIMPLEFRAME_SHOW shows each child
// in turn (the child's VTBL_FRAME_SHOW), and each child runs its OnShow
// right there, before the walk goes on. The walk reads the next child from
// the current node only after that call. A script that reparents the current
// child unlinks and frees its node, so the walk then reads a freed node: the
// client crashed in the walk, and once returned to address 0. Hiding
// (FUN_SIMPLEFRAME_HIDE, OnHide) walks the same way. 3.3.5 and 4.3.4 do the
// same (CSimpleFrame::ShowThis / HideThis); retail's Settings window and the
// addons it hosts reparent frames from these scripts. Auctionator's options
// page opens another page from its OnShow, and the window takes the first
// page out of its canvas with SetParent(nil) while the canvas is still being
// shown.
//
// Each walk is replaced at its first instruction: the children are copied
// first, and each one is shown or hidden only if it is still a child of the
// frame when its turn comes. A child that left is skipped, as the engine
// would never have reached it; a child that arrived was shown by its own
// SetParent. The call per child is the engine's own vtable slot, with the
// child in ECX, in the engine's order. The sites are checked before they are
// written, so a client whose code differs there is left alone.
#include "Common.h"
#include "Game.h"
#include "Offsets.h"
#include <cstddef>
#include <cstdint>
#include <vector>
namespace Frame::ChildWalk {
namespace {
using Slot_t = void(__fastcall *)(void *self, void *edx);
void WalkChildren(void *frame, uintptr_t slot) {
// Most frames have a few children; a long list goes to the heap.
constexpr size_t kInline = 64;
void *inlineList[kInline];
std::vector<void *> heapList;
size_t count = 0;
Game::ForEachFrameListObject(frame, Offsets::OFF_FRAME_CHILD_LIST, [&](void *child) {
if (count < kInline) {
inlineList[count] = child;
} else {
if (heapList.empty())
heapList.assign(inlineList, inlineList + kInline);
heapList.push_back(child);
}
++count;
});
void *const *children = heapList.empty() ? inlineList : heapList.data();
for (size_t i = 0; i < count; ++i) {
void *child = children[i];
if (Game::Read<void *>(child, Offsets::OFF_REGION_PARENT) != frame)
continue;
Game::Read<Slot_t>(Game::Read<void *>(child, 0), slot)(child, nullptr);
}
}
void __cdecl ShowChildren(void *frame) { WalkChildren(frame, Offsets::VTBL_FRAME_SHOW); }
void __cdecl HideChildren(void *frame) { WalkChildren(frame, Offsets::VTBL_FRAME_HIDE); }
constexpr uintptr_t addrShowResume = Offsets::SITE_SIMPLEFRAME_SHOW_CHILD_WALK_RESUME;
constexpr uintptr_t addrHideResume = Offsets::SITE_SIMPLEFRAME_HIDE_CHILD_WALK_RESUME;
// Reached by the `call` written over the walk's first instruction, with the
// frame in ESI. The call's return address is dropped: the stub leaves at the
// walk's end instead. EAX, ECX and EDX are free there.
__declspec(naked) void ShowStub() {
__asm {
add esp, 4
push esi
call ShowChildren
add esp, 4
mov eax, addrShowResume
jmp eax
}
}
__declspec(naked) void HideStub() {
__asm {
add esp, 4
push esi
call HideChildren
add esp, 4
mov eax, addrHideResume
jmp eax
}
}
// `mov ebx, [esi+0x300]`
constexpr uint8_t kWalkStart[] = {0x8B, 0x9E, 0x00, 0x03, 0x00, 0x00};
static_assert(Offsets::OFF_FRAME_CHILD_LIST == 0x300, "kWalkStart encodes the child list offset");
// Runs on every glue and in-game registration (each /reload too): the glue
// screens show and hide frames through the same code. A site already written
// is recognized and left as it is.
void Apply() {
Common::ReplaceWithCall(Offsets::SITE_SIMPLEFRAME_SHOW_CHILD_WALK, kWalkStart, sizeof kWalkStart,
reinterpret_cast<const void *>(&ShowStub));
Common::ReplaceWithCall(Offsets::SITE_SIMPLEFRAME_HIDE_CHILD_WALK, kWalkStart, sizeof kWalkStart,
reinterpret_cast<const void *>(&HideStub));
}
const Game::ModuleAutoRegister _autoreg{&Apply};
const Game::GlueModuleAutoRegister _glueAutoreg{&Apply};
} // namespace
} // namespace Frame::ChildWalk
+69
View File
@@ -0,0 +1,69 @@
// This file is part of ClassicAPI.
//
// ClassicAPI is free software: you can redistribute it and/or modify it under the terms
// of the GNU General Public License as published by the Free Software Foundation, either
// version 3 of the License, or (at your option) any later version.
//
// ClassicAPI is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along with
// ClassicAPI. If not, see <https://www.gnu.org/licenses/>.
// `frame:SetParent(parent)` makes a shown frame visible under a visible
// parent, as 3.3.5's does.
//
// 1.12's CSimpleFrame::SetParent (FUN_FRAME_SET_PARENT) hides the frame
// first when it was visible, and shows it again afterwards only if it WAS
// visible and the new parent is visible or absent. 3.3.5's
// (CSimpleFrame.cpp:1677, wowdecomp) tests the shown flag instead:
// `if (shown && (!m_parent || m_parent->m_isVisible)) ShowThis()`. So a
// frame that is shown but invisible, because its old parent was hidden,
// stays invisible in 1.12 when it moves under a visible parent, and becomes
// visible in 3.3.5. Retail's Settings window reaches that case: it moves the
// key binding buttons onto an input blocker while a key is awaited, hides
// the blocker, and only then moves the buttons back to their row.
//
// The change is on Script SetParent only. The frame constructor calls
// FUN_FRAME_SET_PARENT directly, before the frame's XML and scripts are
// loaded, and the engine shows new frames itself later; showing them from
// there would change when their OnShow runs. After the script call, a frame
// that is shown, not visible, and under a visible parent (or none) gets the
// frame's own Show slot (VTBL_FRAME_SHOW), the call 3.3.5's ShowThis is, so
// a subclass such as a model builds its model as on any show.
#include "Game.h"
#include "Offsets.h"
#include <cstdint>
namespace Frame::ParentVisibility {
namespace {
using Script_t = int(__fastcall *)(void *L);
Script_t g_origSetParent = nullptr;
bool Flag(const void *frame, uintptr_t offset) { return Game::Read<uint32_t>(frame, offset) != 0; }
int __fastcall SetParent_h(void *L) {
void *frame = Game::Lua::ResolveFrame(L, 1, /*raiseError*/ false);
const int results = g_origSetParent(L);
if (frame == nullptr || !Flag(frame, Offsets::OFF_FRAME_SHOWN) || Flag(frame, Offsets::OFF_FRAME_VISIBLE))
return results;
const void *parent = Game::Read<void *>(frame, Offsets::OFF_REGION_PARENT);
if (parent != nullptr && !Flag(parent, Offsets::OFF_FRAME_VISIBLE))
return results;
using Slot_t = void(__fastcall *)(void *self, void *edx);
Game::Read<Slot_t>(Game::Read<void *>(frame, 0), Offsets::VTBL_FRAME_SHOW)(frame, nullptr);
return results;
}
const Game::HookAutoRegister _hook{Offsets::FUN_SCRIPT_REGION_SET_PARENT,
reinterpret_cast<void *>(&SetParent_h),
reinterpret_cast<void **>(&g_origSetParent)};
} // namespace
} // namespace Frame::ParentVisibility
+88
View File
@@ -0,0 +1,88 @@
// This file is part of ClassicAPI.
//
// ClassicAPI is free software: you can redistribute it and/or modify it under the terms
// of the GNU General Public License as published by the Free Software Foundation, either
// version 3 of the License, or (at your option) any later version.
//
// ClassicAPI is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along with
// ClassicAPI. If not, see <https://www.gnu.org/licenses/>.
// `C_SettingsUtil` — the C side of the Settings window, whose Lua is the
// embedded addon's port of Blizzard_Settings_Shared (Settings\).
//
// OpenSettingsPanel([openToCategoryID [, scrollToElementName]]) fires
// SETTINGS_PANEL_OPEN with its two arguments; SettingsPanel opens itself
// (to that category when one is given) on the event. Settings.OpenToCategory
// calls it.
// NotifySettingsLoaded() fires SETTINGS_LOADED. SettingsRegistrar calls it
// once every registrant has run, after VARIABLES_LOADED and
// PLAYER_ENTERING_WORLD.
//
// Retail documents openToCategoryID as a number, the category's counter ID.
// Addons set a category's ID to its name (Ace3, Auctionator) and pass that
// name, and the panel finds a category by comparing IDs, so the argument is
// passed through as given.
//
// Both events fire at once, inside the call, through the engine's event
// dispatcher (Event::Custom::FireValues).
#include "Game.h"
#include "event/Custom.h"
namespace Settings::Panel {
namespace {
// OpenSettingsPanel's arguments, which SETTINGS_PANEL_OPEN carries as its payload.
const Game::Doc::Field kOpenFields[] = {
Game::Doc::Opt("openToCategoryID", "number", nullptr,
"The category to show; a category whose ID is its name is given by name."),
Game::Doc::Opt("scrollToElementName", "string", nullptr,
"The setting the list scrolls to."),
};
const Game::Doc::Event kOpenDoc{"SettingsUtil",
"Fires when something asks the Settings window to open.",
kOpenFields};
const Event::Custom::AutoReserve kOpenEvent{"SETTINGS_PANEL_OPEN", &kOpenDoc};
const Game::Doc::Event kLoadedDoc{
"SettingsUtil", "Fires once the Settings window has registered all of its settings.", {}};
const Event::Custom::AutoReserve kLoadedEvent{"SETTINGS_LOADED", &kLoadedDoc};
const Game::Doc::Function kOpenSettingsPanel{
"Opens the Settings window, to a category when one is given.", kOpenFields, {}};
const Game::Doc::Function kNotifySettingsLoaded{
"Fires SETTINGS_LOADED; the Settings window calls it once its settings are registered.",
{},
{}};
int __fastcall Script_OpenSettingsPanel(void *L) {
// Exactly two payload values, nil where an argument is absent.
Game::Lua::SetTop(L, 2);
Event::Custom::FireValues(kOpenEvent.Slot(), L, 1, 2);
return 0;
}
int __fastcall Script_NotifySettingsLoaded(void *L) {
(void)L;
Event::Custom::Fire(kLoadedEvent.Slot(), "");
return 0;
}
void RegisterLuaFunctions() {
Game::Lua::RegisterTableFunction("C_SettingsUtil", "OpenSettingsPanel",
&Script_OpenSettingsPanel, &kOpenSettingsPanel);
Game::Lua::RegisterTableFunction("C_SettingsUtil", "NotifySettingsLoaded",
&Script_NotifySettingsLoaded, &kNotifySettingsLoaded);
}
const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions};
} // namespace
} // namespace Settings::Panel
+16 -1
View File
@@ -11,7 +11,9 @@
// You should have received a copy of the GNU General Public License along with
// ClassicAPI. If not, see <https://www.gnu.org/licenses/>.
// `slider:Enable()`, `slider:Disable()` and `slider:IsEnabled()`.
// `slider:Enable()`, `slider:Disable()`, `slider:SetEnabled(enabled)` and
// `slider:IsEnabled()`. SetEnabled is Enable or Disable by the truth of its
// argument, as retail's is.
//
// 4.3.4's Script Enable / Disable set or clear frame flag 0x400 and run
// OnEnable / OnDisable on every call, changed or not, unless the frame is
@@ -70,6 +72,12 @@ int __fastcall Script_Disable(void *L) {
return 0;
}
int __fastcall Script_SetEnabled(void *L) {
if (void *slider = ResolveSlider(L))
Frame::EnableScripts::RunOnEnableScript(slider, Game::Lua::ToBoolean(L, 2) == 0);
return 0;
}
int __fastcall Script_IsEnabled(void *L) {
void *slider = ResolveSlider(L);
if (slider == nullptr)
@@ -81,6 +89,7 @@ int __fastcall Script_IsEnabled(void *L) {
const Game::Lua::FrameMethodEntry g_methods[] = {
{"Enable", &Script_Enable},
{"Disable", &Script_Disable},
{"SetEnabled", &Script_SetEnabled},
{"IsEnabled", &Script_IsEnabled},
};
@@ -90,11 +99,17 @@ const Game::Doc::Field kIsEnabledRets[] = {
const Game::Doc::Function kEnable{"Enables the slider and runs its OnEnable script.", {}, {}};
const Game::Doc::Function kDisable{
"Disables the slider: the mouse no longer moves it. Runs its OnDisable script.", {}, {}};
const Game::Doc::Field kSetEnabledArgs[] = {
Game::Doc::Opt("enabled", "bool", "false", "True enables the slider, false disables it."),
};
const Game::Doc::Function kSetEnabled{
"Enables or disables the slider, as Enable() or Disable().", kSetEnabledArgs, {}};
const Game::Doc::Function kIsEnabled{"Returns whether the slider is enabled.", {}, kIsEnabledRets};
const Game::Doc::Method g_methodDocs[] = {
{"Enable", &kEnable},
{"Disable", &kDisable},
{"SetEnabled", &kSetEnabled},
{"IsEnabled", &kIsEnabled},
};