# Ark Attribute Tools: edit a mesh's attributes (bevel weights, custom edge attributes...) quickly.
# Install: Edit > Preferences > Add-ons > (top right arrow) Install from Disk > this file, then enable it.
#
# Quick Attributes window: a floating glass window drawn inside the 3D Viewport (no title bar).
#   Open it from the sidebar (N) > "Attributes" tab > "Quick Attributes", or F3 > "Quick Attributes".
#   - drag the handle (dots at top left) to move it; the pin locks it where it is; the x closes it;
#     the chevron folds it down to its header;
#   - one row per attribute of the active mesh: eye (overlay on/off), colour (click: colour picker),
#     name (click selects, double click renames: modifiers reading the old name follow),
#     value (drag it, or click without dragging to type; Shift = fine, Ctrl = snap; Esc cancels),
#     type (click: change type / domain), wrench (blue when a modifier uses it: opens the Modifiers tab
#     with only those modifiers expanded);
#   - drag the thin lines between the name / value / type columns to resize them, double click to reset;
#   - footer: + / - add or remove an attribute, "Selection" lists only attributes set on the selection,
#     "On top" draws the coloured overlay through the mesh.
# Values apply to the selected elements of the attribute's domain (Edit Mode), or the last Edit Mode
# selection in Object Mode. A mixed selection shows its average with a "~".
# Overlay: elements with a non-zero value are drawn in the attribute's colour in Edit Mode, like the blue
# sharp edges. Look settings (blur, opacity, overlay width / depth offset) are in the add-on's preferences.

bl_info = {
    "name": "Attribute Tools",
    "author": "Shey",
    "version": (2, 0, 0),
    "blender": (4, 2, 0),
    "location": "3D Viewport > Sidebar (N) > Attributes > Quick Attributes",
    "description": "Floating window to set, rename, retype and show mesh attributes of the selection",
    "category": "Mesh",
}

import base64
import colorsys
import math
import time
import types
import zlib

import blf
import bmesh
import bpy
import gpu
import numpy as np
from bpy.props import BoolProperty, CollectionProperty, EnumProperty, FloatProperty, FloatVectorProperty, IntProperty, StringProperty
from gpu_extras.batch import batch_for_shader
from mathutils import Matrix

# Types the window edits, and the bmesh layer group for each
SUPPORTED_TYPES = {"FLOAT": "float", "INT": "int", "BOOLEAN": "bool"}
DOMAIN_LABELS = {"POINT": "Vertex", "EDGE": "Edge", "FACE": "Face", "CORNER": "Corner"}
DISPLAY_KEY = "ark_attribute_display"   # per mesh: {attribute name: {"color": [r, g, b, a], "show": 0/1}}

_syncing = False        # true while the item values are written from the mesh (no write back)
_draw_handle = None
_window_handle = None
_batch_cache = {}       # (mesh pointer, attribute, colour, domain) -> batches, cleared on any change


# ---------------------------------------------------------------------------------------------------
# Preferences (window place / look, overlay look). Falls back to defaults when not installed as add-on.

DEFAULTS = dict(
    qa_left=80.0, qa_top=90.0, qa_pinned=False, qa_collapsed=False,
    qa_name_w=0.0, qa_value_w=0.0, qa_type_w=0.0,
    glass_blur=0.0, glass_opacity=0.77, glass_color=(0.0, 0.0, 0.0), glass_radius=8.03, max_rows=12,
    text_color=(0.95, 0.95, 0.96, 1.0), text_size=12.19, row_height=27.0, icon_size=13.18,
    overlay_all=True, overlay_edit_mode=True, overlay_object_mode=True,
    outline=True, outline_width=1.12, outline_color=(0x10 / 255, 0x10 / 255, 0x10 / 255, 0x99 / 255),
    accent_color=(0x10 / 255, 0x3B / 255, 0x93 / 255), modifier_color=(0x0F / 255, 0x40 / 255, 0xA5 / 255),
    control_radius=5.15, pad_left=6.0, pad_right=6.0, pad_top=3.0, pad_bottom=6.48,
    overlay_on_top=True, overlay_offset=0.05, overlay_line_width=3.0,
)
_fallback_prefs = types.SimpleNamespace(**DEFAULTS)


def prefs():
    addon = bpy.context.preferences.addons.get(__name__)
    return addon.preferences if addon and addon.preferences else _fallback_prefs


def redraw_update(self, context):
    mark_dirty()
    tag_redraw()


class ARK_AttributePreferences(bpy.types.AddonPreferences):
    bl_idname = __name__

    qa_left: FloatProperty(default=DEFAULTS["qa_left"], options={'HIDDEN'})
    qa_top: FloatProperty(default=DEFAULTS["qa_top"], options={'HIDDEN'})
    qa_pinned: BoolProperty(default=False, options={'HIDDEN'})
    qa_collapsed: BoolProperty(default=False, options={'HIDDEN'})
    qa_name_w: FloatProperty(default=0.0, options={'HIDDEN'})    # 0 = automatic width
    qa_value_w: FloatProperty(default=0.0, options={'HIDDEN'})
    qa_type_w: FloatProperty(default=0.0, options={'HIDDEN'})
    glass_blur: FloatProperty(name="Background Blur", default=DEFAULTS["glass_blur"], min=0.0, max=12.0,
                              subtype='PIXEL', update=redraw_update)
    glass_opacity: FloatProperty(name="Background Opacity", default=DEFAULTS["glass_opacity"], min=0.0, max=1.0,
                                 subtype='FACTOR', update=redraw_update)
    glass_color: FloatVectorProperty(name="Background Colour", default=DEFAULTS["glass_color"], subtype='COLOR_GAMMA',
                                     size=3, min=0.0, max=1.0, update=redraw_update)
    glass_radius: FloatProperty(name="Corner Radius", default=DEFAULTS["glass_radius"], min=0.0, max=30.0,
                                subtype='PIXEL', update=redraw_update)
    text_color: FloatVectorProperty(name="Text Colour", default=DEFAULTS["text_color"], subtype='COLOR_GAMMA',
                                    size=4, min=0.0, max=1.0, update=redraw_update)
    outline: BoolProperty(name="Outline", default=DEFAULTS["outline"], update=redraw_update)
    outline_width: FloatProperty(name="Outline Thickness", default=DEFAULTS["outline_width"], min=0.0, max=10.0,
                                 subtype='PIXEL', update=redraw_update)
    outline_color: FloatVectorProperty(name="Outline Colour", default=DEFAULTS["outline_color"], subtype='COLOR_GAMMA',
                                       size=4, min=0.0, max=1.0, update=redraw_update)
    accent_color: FloatVectorProperty(name="Accent Colour", description="Slider fill, active row and lit buttons",
                                      default=DEFAULTS["accent_color"], subtype='COLOR_GAMMA', size=3, min=0.0, max=1.0,
                                      update=redraw_update)
    modifier_color: FloatVectorProperty(name="Modifier Colour", description="Wrench of attributes a modifier uses",
                                        default=DEFAULTS["modifier_color"], subtype='COLOR_GAMMA', size=3, min=0.0, max=1.0,
                                        update=redraw_update)
    control_radius: FloatProperty(name="Control Radius", description="Corner radius of sliders, colour swatches and buttons",
                                  default=DEFAULTS["control_radius"], min=0.0, max=12.0, subtype='PIXEL', update=redraw_update)
    pad_left: FloatProperty(name="Left", default=DEFAULTS["pad_left"], min=0.0, max=60.0, subtype='PIXEL', update=redraw_update)
    pad_right: FloatProperty(name="Right", default=DEFAULTS["pad_right"], min=0.0, max=60.0, subtype='PIXEL', update=redraw_update)
    pad_top: FloatProperty(name="Top", default=DEFAULTS["pad_top"], min=0.0, max=60.0, subtype='PIXEL', update=redraw_update)
    pad_bottom: FloatProperty(name="Bottom", default=DEFAULTS["pad_bottom"], min=0.0, max=60.0, subtype='PIXEL', update=redraw_update)
    text_size: FloatProperty(name="Text Size", default=DEFAULTS["text_size"], min=6.0, max=32.0, update=redraw_update)
    row_height: FloatProperty(name="Row Height", default=DEFAULTS["row_height"], min=14.0, max=60.0,
                              subtype='PIXEL', update=redraw_update)
    icon_size: FloatProperty(name="Icon Size", description="Pixel size of the biggest icon (the pin); the others keep their size from the SVG files",
                             default=DEFAULTS["icon_size"], min=4.0, max=64.0, subtype='PIXEL', update=redraw_update)
    overlay_all: BoolProperty(name="Show Colours", description="Show or hide every coloured attribute at once",
                              default=True, update=redraw_update)
    overlay_edit_mode: BoolProperty(name="In Edit Mode", default=True, update=redraw_update,
                                    description="Show the coloured attributes in Edit Mode")
    overlay_object_mode: BoolProperty(name="In Object Mode", default=DEFAULTS["overlay_object_mode"], update=redraw_update,
                                      description="Also show the coloured attributes of the selected meshes in Object Mode "
                                                  "(display only)")
    max_rows: IntProperty(name="Rows Before Scrolling", default=DEFAULTS["max_rows"], min=3, max=60, update=redraw_update)
    overlay_on_top: BoolProperty(name="Overlay On Top", description="Draw the coloured elements through the mesh",
                                 default=DEFAULTS["overlay_on_top"], update=redraw_update)
    overlay_offset: FloatProperty(name="Overlay Depth Offset",
                                  description="Pulls the coloured elements toward the view so faces don't hide them "
                                              "(fraction of their distance)",
                                  default=DEFAULTS["overlay_offset"], min=0.0, max=0.05, precision=4, update=redraw_update)
    overlay_line_width: FloatProperty(name="Overlay Line Width", default=DEFAULTS["overlay_line_width"], min=1.0, max=10.0,
                                      update=redraw_update)

    def draw(self, context):
        col = self.layout.column()
        col.prop(self, "glass_blur")
        col.prop(self, "glass_opacity")
        col.prop(self, "glass_color")
        col.prop(self, "glass_radius")
        col.prop(self, "text_color")
        col.prop(self, "text_size")
        col.prop(self, "row_height")
        col.prop(self, "icon_size")
        col.prop(self, "max_rows")
        col.separator()
        col.prop(self, "overlay_on_top")
        col.prop(self, "overlay_offset")
        col.prop(self, "overlay_line_width")


# ---------------------------------------------------------------------------------------------------
# Mesh access

def active_mesh_object(context=None):
    context = context or bpy.context
    obj = getattr(context, "active_object", None) or context.view_layer.objects.active
    return obj if obj and obj.type == 'MESH' else None


def is_user_attribute(attr):
    # Hidden (".select_vert"...) and position stay out of the list
    return not attr.name.startswith(".") and attr.name != "position" and attr.data_type in SUPPORTED_TYPES


def bm_elements(bm, domain):
    if domain == "POINT":
        return bm.verts
    if domain == "EDGE":
        return bm.edges
    if domain == "FACE":
        return bm.faces
    return None


def bm_layer(bm, domain, data_type, name):
    group = SUPPORTED_TYPES[data_type]
    if domain == "CORNER":
        return getattr(bm.loops.layers, group).get(name)
    return getattr(bm_elements(bm, domain).layers, group).get(name)


def selected_bm_items(bm, domain):
    """Selected vertices / edges / faces, or the corners of the selected faces."""
    if domain == "CORNER":
        return [loop for face in bm.faces if face.select for loop in face.loops]
    return [elem for elem in bm_elements(bm, domain) if elem.select]


def selected_indices(mesh, domain):
    """Object Mode: indices of the elements selected when Edit Mode was left."""
    if domain == "POINT":
        return [v.index for v in mesh.vertices if v.select]
    if domain == "EDGE":
        return [e.index for e in mesh.edges if e.select]
    if domain == "FACE":
        return [p.index for p in mesh.polygons if p.select]
    return [i for p in mesh.polygons if p.select for i in p.loop_indices]


def read_selection(obj, name, domain, data_type):
    """Values of the attribute on the selected elements."""
    mesh = obj.data
    if obj.mode == 'EDIT':
        bm = bmesh.from_edit_mesh(mesh)
        layer = bm_layer(bm, domain, data_type, name)
        if layer is None:
            return []
        return [item[layer] for item in selected_bm_items(bm, domain)]
    attr = mesh.attributes.get(name)
    if attr is None:
        return []
    return [attr.data[i].value for i in selected_indices(mesh, domain)]


def write_selection(obj, name, domain, data_type, value):
    mesh = obj.data
    if obj.mode == 'EDIT':
        bm = bmesh.from_edit_mesh(mesh)
        layer = bm_layer(bm, domain, data_type, name)
        if layer is None:
            return
        for item in selected_bm_items(bm, domain):
            item[layer] = value
        bmesh.update_edit_mesh(mesh, loop_triangles=False, destructive=False)
    else:
        attr = mesh.attributes.get(name)
        if attr is None:
            return
        for i in selected_indices(mesh, domain):
            attr.data[i].value = value
        mesh.update()
    mark_dirty()


# ---------------------------------------------------------------------------------------------------
# Display settings (colour, eye), kept on the mesh so they save with the .blend

def default_color(name):
    hue = (zlib.crc32(name.encode()) % 360) / 360.0
    r, g, b = colorsys.hsv_to_rgb(hue, 0.75, 1.0)
    return [r, g, b, 0.3]


# Attributes Blender draws itself: their colour is the theme's and their eye is Blender's overlay toggle,
# so the two drawings never fight over the same edges
BUILTIN_DISPLAY = {
    "sharp_edge": ("sharp", "show_edge_sharp"),
    "crease_edge": ("crease", "show_edge_crease"),
    "bevel_weight_edge": ("bevel", "show_edge_bevel_weight"),
}


def view3d_overlays():
    for window in bpy.context.window_manager.windows:
        for area in window.screen.areas:
            if area.type == 'VIEW_3D':
                yield area.spaces.active.overlay


def get_display(mesh, name):
    if name in BUILTIN_DISPLAY:
        theme_key, overlay_key = BUILTIN_DISPLAY[name]
        try:
            c = getattr(bpy.context.preferences.themes[0].view_3d, theme_key)
            color = [c[0], c[1], c[2], 1.0]
        except (AttributeError, IndexError):
            color = default_color(name)
        overlay = next(view3d_overlays(), None)
        return color, bool(getattr(overlay, overlay_key, True))
    store = mesh.get(DISPLAY_KEY)
    entry = store.get(name) if store else None
    if entry is None:
        return default_color(name), True
    return list(entry.get("color", default_color(name))), bool(entry.get("show", 1))


def set_display(mesh, name, color=None, show=None):
    if name in BUILTIN_DISPLAY:
        if show is not None:
            for overlay in view3d_overlays():
                setattr(overlay, BUILTIN_DISPLAY[name][1], bool(show))
        return
    if DISPLAY_KEY not in mesh:
        mesh[DISPLAY_KEY] = {}
    store = mesh[DISPLAY_KEY]
    current_color, current_show = get_display(mesh, name)
    store[name] = {
        "color": list(color) if color is not None else current_color,
        "show": int(show if show is not None else current_show),
    }
    mark_dirty()


def rename_display(mesh, old, new):
    store = mesh.get(DISPLAY_KEY)
    if store and old in store:
        store[new] = store[old].to_dict()
        del store[old]


# ---------------------------------------------------------------------------------------------------
# Modifiers using an attribute (string settings holding its name, Geometry Nodes attribute inputs)

def modifier_name_slots(mod):
    """(setter, value) for every setting of the modifier that names an attribute."""
    slots = []
    for prop in mod.bl_rna.properties:
        if prop.type == 'STRING' and not prop.is_readonly and prop.identifier not in {"name", "show_expanded"}:
            identifier = prop.identifier
            slots.append((lambda v, m=mod, k=identifier: setattr(m, k, v), getattr(mod, identifier)))
    if mod.type == 'NODES':
        for key in mod.keys():
            if key.endswith("_attribute_name"):
                slots.append((lambda v, m=mod, k=key: m.__setitem__(k, v), mod[key]))
    return slots


def modifier_uses(mod, name):
    return any(value == name for _setter, value in modifier_name_slots(mod))


def objects_using_mesh(mesh):
    return [obj for obj in bpy.data.objects if obj.type == 'MESH' and obj.data == mesh]


# ---------------------------------------------------------------------------------------------------
# Items: one per attribute, refreshed from the mesh by a timer

def item_value_update(self, context):
    if _syncing:
        return
    obj = active_mesh_object(context)
    if not obj:
        return
    value = {"FLOAT": self.value, "INT": self.int_value, "BOOLEAN": self.bool_value}[self.data_type]
    write_selection(obj, self.attr_name, self.domain, self.data_type, value)
    self.mixed = False
    self.on_selection = bool(value)


def item_display_update(self, context):
    if _syncing:
        return
    obj = active_mesh_object(context)
    if obj:
        set_display(obj.data, self.attr_name, color=self.color, show=self.show)
        tag_redraw()


def item_name_update(self, context):
    global _syncing
    if _syncing or self.name == self.attr_name:
        return
    obj = active_mesh_object(context)
    if not obj or not self.name:
        restore_name(self)
        return
    mesh = obj.data
    attr = mesh.attributes.get(self.attr_name)
    if attr is None or mesh.attributes.get(self.name) is not None:
        restore_name(self)   # gone, or the new name is taken
        return
    old, new = self.attr_name, self.name
    attr.name = new
    # Every modifier that read the old name now reads the new one
    for user in objects_using_mesh(mesh):
        for mod in user.modifiers:
            for setter, value in modifier_name_slots(mod):
                if value == old:
                    setter(new)
    rename_display(mesh, old, new)
    _syncing = True
    self.attr_name = new
    _syncing = False
    mark_dirty()


def restore_name(item):
    global _syncing
    _syncing = True
    item.name = item.attr_name
    _syncing = False


class ARK_AttributeItem(bpy.types.PropertyGroup):
    # "name" is what the window shows and edits; attr_name is the real one
    name: StringProperty(update=item_name_update)
    attr_name: StringProperty()
    domain: StringProperty()
    data_type: StringProperty()
    value: FloatProperty(name="Value", soft_min=0.0, soft_max=1.0, precision=3, update=item_value_update)
    int_value: IntProperty(name="Value", update=item_value_update)
    bool_value: BoolProperty(name="Value", update=item_value_update)
    mixed: BoolProperty()
    on_selection: BoolProperty()
    color: FloatVectorProperty(name="Color", subtype='COLOR', size=4, min=0.0, max=1.0, update=item_display_update)
    show: BoolProperty(name="Show", default=True, update=item_display_update)


def sync_items(context=None):
    """Mirror the active mesh's attributes and selection values into the item list. Returns True if changed."""
    global _syncing
    context = context or bpy.context
    wm = context.window_manager
    items = wm.ark_attribute_items
    obj = active_mesh_object(context)

    rows = []
    if obj:
        for attr in obj.data.attributes:
            if is_user_attribute(attr):
                rows.append((attr.name, attr.domain, attr.data_type))

    changed = False
    _syncing = True
    try:
        if [(i.attr_name, i.domain, i.data_type) for i in items] != rows:
            items.clear()
            for name, domain, data_type in rows:
                item = items.add()
                item.name = item.attr_name = name
                item.domain, item.data_type = domain, data_type
            wm.ark_attribute_index = min(wm.ark_attribute_index, max(len(items) - 1, 0))
            changed = True
        for item in items:
            values = read_selection(obj, item.attr_name, item.domain, item.data_type) if obj else []
            numbers = [float(v) for v in values]
            mean = sum(numbers) / len(numbers) if numbers else 0.0
            mixed = bool(numbers) and (max(numbers) - min(numbers)) > 1e-6
            on_selection = any(numbers)
            color, show = get_display(obj.data, item.attr_name)
            new_state = (round(mean, 6), mixed, on_selection, tuple(round(c, 4) for c in color), show)
            old_state = (round(item_number(item), 6), item.mixed, item.on_selection,
                         tuple(round(c, 4) for c in item.color), item.show)
            if new_state != old_state:
                if item.data_type == "FLOAT":
                    item.value = mean
                elif item.data_type == "INT":
                    item.int_value = int(round(mean))
                else:
                    item.bool_value = mean >= 0.5
                item.mixed, item.on_selection = mixed, on_selection
                item.color, item.show = color, show
                changed = True
    finally:
        _syncing = False
    return changed


def item_number(item):
    if item.data_type == "FLOAT":
        return item.value
    return float(item.int_value if item.data_type == "INT" else item.bool_value)


def tag_redraw():
    for window in bpy.context.window_manager.windows:
        for area in window.screen.areas:
            if area.type == 'VIEW_3D':
                area.tag_redraw()


def sync_timer():
    try:
        if sync_items():
            tag_redraw()
    except Exception:
        pass   # a mode switch in progress; next tick
    return 0.25


# ---------------------------------------------------------------------------------------------------
# Operators

DOMAIN_ITEMS = [(k, v, "") for k, v in DOMAIN_LABELS.items()]
TYPE_ITEMS = [("FLOAT", "Float", "A number (0 to 1 for weights)"),
              ("INT", "Integer", "A whole number"),
              ("BOOLEAN", "Boolean", "On / off")]


def active_item(context):
    wm = context.window_manager
    items = wm.ark_attribute_items
    return items[wm.ark_attribute_index] if 0 <= wm.ark_attribute_index < len(items) else None


class ARK_OT_attribute_add(bpy.types.Operator):
    """Add an attribute to the active mesh"""
    bl_idname = "ark.attribute_add"
    bl_label = "Add Attribute"
    bl_options = {'REGISTER', 'UNDO'}

    name: StringProperty(name="Name", default="bevel_soft")
    domain: EnumProperty(name="Domain", items=DOMAIN_ITEMS, default="EDGE")
    data_type: EnumProperty(name="Type", items=TYPE_ITEMS, default="FLOAT")

    @classmethod
    def poll(cls, context):
        return active_mesh_object(context) is not None

    def invoke(self, context, event):
        return context.window_manager.invoke_props_dialog(self)

    def execute(self, context):
        mesh = active_mesh_object(context).data
        if not self.name or mesh.attributes.get(self.name):
            self.report({'WARNING'}, f'"{self.name}" is empty or already used')
            return {'CANCELLED'}
        mesh.attributes.new(self.name, self.data_type, self.domain)
        sync_items(context)
        names = [i.attr_name for i in context.window_manager.ark_attribute_items]
        if self.name in names:
            context.window_manager.ark_attribute_index = names.index(self.name)
        mark_dirty()
        return {'FINISHED'}


class ARK_OT_attribute_remove(bpy.types.Operator):
    """Remove the selected attribute from the mesh"""
    bl_idname = "ark.attribute_remove"
    bl_label = "Remove Attribute"
    bl_options = {'REGISTER', 'UNDO'}

    @classmethod
    def poll(cls, context):
        return active_mesh_object(context) is not None and active_item(context) is not None

    def execute(self, context):
        mesh = active_mesh_object(context).data
        item = active_item(context)
        attr = mesh.attributes.get(item.attr_name)
        if attr:
            mesh.attributes.remove(attr)
        store = mesh.get(DISPLAY_KEY)
        if store and item.attr_name in store:
            del store[item.attr_name]
        sync_items(context)
        mark_dirty()
        return {'FINISHED'}


class ARK_OT_attribute_convert(bpy.types.Operator):
    """Change the selected attribute's type or domain (values are converted)"""
    bl_idname = "ark.attribute_convert"
    bl_label = "Change Attribute Type"
    bl_options = {'REGISTER', 'UNDO'}

    domain: EnumProperty(name="Domain", items=DOMAIN_ITEMS)
    data_type: EnumProperty(name="Type", items=TYPE_ITEMS)

    @classmethod
    def poll(cls, context):
        return active_mesh_object(context) is not None and active_item(context) is not None

    def invoke(self, context, event):
        item = active_item(context)
        self.domain, self.data_type = item.domain, item.data_type
        return context.window_manager.invoke_props_dialog(self)

    def execute(self, context):
        obj = active_mesh_object(context)
        mesh = obj.data
        name = active_item(context).attr_name
        was_edit = obj.mode == 'EDIT'
        # The converter works on Object Mode data
        if was_edit:
            bpy.ops.object.mode_set(mode='OBJECT')
        try:
            mesh.attributes.active = mesh.attributes[name]
            bpy.ops.geometry.attribute_convert(mode='GENERIC', domain=self.domain, data_type=self.data_type)
        finally:
            if was_edit:
                bpy.ops.object.mode_set(mode='EDIT')
        sync_items(context)
        mark_dirty()
        return {'FINISHED'}


class ARK_OT_attribute_focus_modifiers(bpy.types.Operator):
    """Open the Modifiers tab: expand the modifiers using the selected attribute, collapse the others"""
    bl_idname = "ark.attribute_focus_modifiers"
    bl_label = "Show Modifiers Using It"

    @classmethod
    def poll(cls, context):
        return active_mesh_object(context) is not None and active_item(context) is not None

    def execute(self, context):
        obj = active_mesh_object(context)
        name = active_item(context).attr_name
        used = 0
        for mod in obj.modifiers:
            mod.show_expanded = modifier_uses(mod, name)
            used += mod.show_expanded
        for window in context.window_manager.windows:
            for area in window.screen.areas:
                if area.type == 'PROPERTIES':
                    try:
                        area.spaces.active.context = 'MODIFIER'
                    except TypeError:
                        pass
                    area.tag_redraw()
        self.report({'INFO'}, f'{used} modifier(s) use "{name}"' if used else f'No modifier uses "{name}"')
        return {'FINISHED'}


# ---------------------------------------------------------------------------------------------------
# Quick Attributes window: drawn in one 3D Viewport (POST_PIXEL), driven by a pass-through modal operator.
# Sizes are in UI-scaled pixels; the blur reads the viewport pixels behind the window each redraw.

# Unscaled sizes, refreshed from the sidebar settings (Text Size, Row Height, Icon Size) by qa_apply_sizes
FONT, FONT_SMALL = 13.0, 10.5
HEAD_H, ROW_H, FOOT_H, PAD = 28.0, 24.0, 26.0, 6.0
EYE_W, SWATCH_W, WRENCH_W = 22.0, 33.0, 24.0
SWATCH_SIZE = (25.0, 17.0)
NAME_MIN, VALUE_MIN, TYPE_MIN = 40.0, 50.0, 18.0


def qa_apply_sizes(p):
    global FONT, FONT_SMALL, HEAD_H, ROW_H, FOOT_H, EYE_W, SWATCH_W, WRENCH_W, SWATCH_SIZE
    FONT = p.text_size
    FONT_SMALL = p.text_size * 0.82
    ROW_H = p.row_height
    HEAD_H = ROW_H + 4.0
    FOOT_H = ROW_H + 2.0
    icon = 11.667 * p.icon_size / ICON_REF    # the wrench, the widest row icon
    EYE_W = icon + 4.0
    WRENCH_W = icon + 6.0
    # Colour swatch keeps a 25 x 17 shape, shrunk if the rows are short
    h = min(17.0, ROW_H - 6.0)
    SWATCH_SIZE = (h * 25.0 / 17.0, h)
    SWATCH_W = SWATCH_SIZE[0] + 8.0

_qa = {"open": False, "area": 0, "hover": None, "drag": None, "edit": None, "scroll": 0, "last_click": (None, 0.0)}

_qa_shader = None
_qa_dummy = None

ROUND_RECT_VERT = """
void main()
{
    local = pos - rect.xy;
    gl_Position = mvp * vec4(pos, 0.0, 1.0);
}
"""

ROUND_RECT_FRAG = """
void main()
{
    vec2 size = rect.zw;
    vec2 q = abs(local - size * 0.5) - (size * 0.5 - vec2(radius));
    float d = length(max(q, 0.0)) + min(max(q.x, q.y), 0.0) - radius;
    float coverage = clamp(0.5 - d, 0.0, 1.0);
    vec4 c = color;
    if (use_tex == 3) {
        // Outline: a band `blur` pixels wide just inside the rounded edge
        coverage *= clamp(0.5 + d + blur, 0.0, 1.0);
    }
    else if (use_tex == 2) {
        // Icon: the texture is an alpha mask, tinted with color
        c.a *= texture(tex, local / size).a;
    }
    else if (use_tex == 1) {
        // Gaussian blur of the captured viewport, then the glass tint over it
        int r = int(min(ceil(blur * 1.5), 18.0));
        float sigma = max(blur * 0.75, 0.01);
        vec3 sum = vec3(0.0);
        float total = 0.0;
        vec2 lo = vec2(0.5) / size;
        vec2 hi = vec2(1.0) - lo;
        for (int i = -r; i <= r; i++) {
            for (int j = -r; j <= r; j++) {
                float w = exp(-float(i * i + j * j) / (2.0 * sigma * sigma));
                sum += texture(tex, clamp((local + vec2(float(i), float(j))) / size, lo, hi)).rgb * w;
                total += w;
            }
        }
        c = vec4(mix(sum / total, color.rgb, color.a), 1.0);
    }
    FragColor = vec4(c.rgb, c.a * coverage);
}
"""


def qa_shader():
    global _qa_shader, _qa_dummy
    if _qa_shader is None:
        info = gpu.types.GPUShaderCreateInfo()
        info.push_constant('MAT4', "mvp")
        info.push_constant('VEC4', "rect")
        info.push_constant('VEC4', "color")
        info.push_constant('FLOAT', "radius")
        info.push_constant('FLOAT', "blur")
        info.push_constant('INT', "use_tex")
        info.sampler(0, 'FLOAT_2D', "tex")
        info.vertex_in(0, 'VEC2', "pos")
        interface = gpu.types.GPUStageInterfaceInfo("ark_qa_interface")
        interface.smooth('VEC2', "local")
        info.vertex_out(interface)
        info.fragment_out(0, 'VEC4', "FragColor")
        info.vertex_source(ROUND_RECT_VERT)
        info.fragment_source(ROUND_RECT_FRAG)
        _qa_shader = gpu.shader.create_from_info(info)
        _qa_dummy = gpu.types.GPUTexture((1, 1), format='RGBA8')
    return _qa_shader


def draw_round_rect(x, y, w, h, radius, color, tex=None, blur=0.0, mode=None):
    if w <= 0 or h <= 0:
        return
    gpu.state.blend_set('ALPHA')   # blf.draw turns blending off
    shader = qa_shader()
    batch = batch_for_shader(shader, 'TRIS', {"pos": ((x, y), (x + w, y), (x + w, y + h), (x, y + h))},
                             indices=((0, 1, 2), (0, 2, 3)))
    shader.bind()
    shader.uniform_float("mvp", gpu.matrix.get_projection_matrix() @ gpu.matrix.get_model_view_matrix())
    shader.uniform_float("rect", (x, y, w, h))
    shader.uniform_float("color", color)
    shader.uniform_float("radius", min(radius, w * 0.5, h * 0.5))
    shader.uniform_float("blur", blur)
    shader.uniform_int("use_tex", mode if mode is not None else (1 if tex else 0))
    shader.uniform_sampler("tex", tex or _qa_dummy)
    batch.draw(shader)


# The window's icons (user's 3x SVGs rasterized at 4x their 1x size; alpha masks, zlib + base64), drawn tinted.
ICON_DATA = {
    "CHEVRON_DOWN": (31, 17, 7.667, 4.333, "eNpjYEAGuvbsDLhBwf//Z3nwyf7/fwKXfOZ/MDjBhVU2Cyj17TSQOIRNPgko8dWG6wSQOsyBKfsPJMvAwAOS34suHw2VxS4f/ff//+82EDZEng1d1gnG4zkLlN+OkA9BkWVg4AfLs8Bk/6DKQuU3QuT9MGSR5f1+////0wndnxB5ZgZHoN5fHpihJACSn8bQBJT1xBbGQhf//3/EoPHkrhP2GBJa8z+DAQDkUX/f"),
    "CHEVRON_RIGHT": (17, 31, 4.333, 7.667, "eNpjYEADJVdXcKMIfPv//xAXssCJ/0ARTiQB6QdAkb0c+EXugkTYkETEQSLbUURugERYkEREQCIbUUSugESYkUQEQSKrUUTOo4vwgUWYkEVOAUUWIZvMcx0o4o8kEPoXKKCF4If8+f//XwSC74fO/00Z3+Pn//9/0PmBxPO9fv3//zcUyQPv0PgMt///CUGJW8V6V9TYBwALToCe"),
    "CLOSE": (28, 28, 7.0, 7.0, "eNp10rEKwjAQBuBzaBeHSjrYgouzKIKDk7Pv5O4sPoFugtBJitDJ1aFIO1bF3aHi5nYmpaVN7noQEv6PC+EIQHstL5sOE4sgGsIbcU9RJIgBxIi4M1HcZLqF/lNuBx2dVGZnGxh04pIoNshEjXQ0qImEamSowh5HAP5Dxh+5QptOsOjkulTNFH27HA1eRV9ktRKHnqJ0kTPo3RUJGFGsCCjWRLBJBuqkoUkN9DN5SIT26qnCkwUhpRLX8JMXumRK41z9zxUeXWa6k2s2hz+oQOLU"),
    "EYE_OPEN": (44, 31, 11.0, 7.667, "eNpjYMAE0pYqDEQAycQNt/6DwMOdJZp4VXqf+Y8M7qXiVKm65z86uGKPXWk+RPpxr6sDEBSfgHCnY1HJvwViUBgjTER3I0REGV2pFMRHE5iQBf2/g8Q+WaMqVXkEVpqHZoLJJ7CwF7KY8guw2EQMl7lDHB2AEJGBmHoeizdaIIrdYHyhmxABV7gKQx4Yi/s1RM4Cyj8I4Z6BckXnfv7/f68RlNcIkXyjCOYthIZ7LTSWX6O40QQqe0sAyKmBxRHUmpVQ7jOoO95D+QcYGMLh8SkJllKD8/Mhas/D+EsY3sLlIFJBcP4ciMA2uIDZVTiTBzlEEaF9GC6gpPUGxlSFpAu4VDBE7R0YPxIYlh+g7AiIXDWUewTCFYApDQPxnOFuh4AFYN51UQgvEioLTSqJEN4nQaji6M0H9lZxQzlbIZLTYBHZCeF3Y0kPNtDAZYaLrIWI6GEo5boClrjGhxDiPADJPiLoatdDxBWQxVjmgQVvowgycEDsOyqMZkIhWPh9NJKQ7kmw2AJMX7hC8svNdH4I3wfqiTJseV4dFt37F7bO3ApNXm99sRcQTJFX0YqS1xXcuAspr+kP4Qo/rYnlJFD66URWzd6xpDnJFlMKACmqDts="),
    "EYE_CLOSED": (44, 17, 11.0, 4.333, "eNpjYEAHHIIyKrLCnAyEALthfPdMCJiQasGNRyWT68SZyGBaCDsupRrNM9FBjwV2pQFg2f4YTSk+Bm4JteAOMD8Vi9G8xSCZWiMkIa0ikFCTJLpSgUagcLcRmqhSHciT8qiCwm1AwTJeDNtYk0GKlZCF+FqBQjFYfeEClJmIZDJXPVAgAkfoWM8AelgcxmMrByqNxBnq1kDZLmFoDOQDOfmMuKMIFJgtEL+AnF/Dji/mU4Aq6kAqfEC6+PCmEpjN+qCYFCGQpNgqgKr8GEJnzpwkTzD9cTfNnFnCINc3WZOBMBAumanJAABQKmT4"),
    "MINUS": (31, 4, 7.667, 1.0, "eNpjkHfACUwYGDr/4wEXOU/hk/4v7XUPt+SXDgYANZZebQ=="),
    "MODIFIER": (47, 47, 11.667, 11.667, "eNpjYGBgCNl6YF0KA5FA5+5/EHgeQZRqvff/oaCACNVcz//DQRFh5eX/kUAhQeXX/pOk/v9/ktS/QVNfgl/5iv8kqXdAV04gfKZiqC/Hq34GaeoZ5/4nzf2zsJuv6l9ZmRKgSpR644nvoMxLNTKE3YMMfi/RIkn9/38TWFE1zMGv/v95ZZLM//9UijT1N4VJU7+HNP/+j0UL0IX4lX/kx6v+S3MDECxACGSiKQ9EVv3ZHCJYDxc5i6Z8NbLZFjDRKrgYauzyIpttiRCHq09HUe6H6RIIKIGKzkNRXgdX/c0K1ZUVEOFzKIIz4corsBdfN1HEZv/HXV6WgYTvowh14FEOdv8zFJFifMoZCv//34QiEI5XOUNYvQAKXxCuvJ+oumE/zuSBFSQg4imNCOUsDxG5OZoI9ckI4/8SoZ7pJJL6EMLqZd4j1P/xI6zeCzmH+BNWb/8VqbjzIKze8DaS+e5EhE/eR7jy7zpEqOcveQpTn01cy8K7+zRI9S5RFFEApB879g=="),
    "PINNED": (48, 48, 12.0, 12.0, "eNpjYCANOM7II0n9q///55Ki/vV/0jQ4fidRg8MPoIaFjINJg/N/bH7gWfyshAQbeE4AxSYTrQGs/P//WTic6YwWrDzH/kPALBw2OKFo4Dn+HwbsiHAS1DFgEM2Az4Y6NNP//4/EG6xXQcqP/idKPYPT+/8T0EzHq56BywJDOV71aF7F71/syvGrx1SOVz0W5fjUo3sVDOaTZDoQTCNNOS4NOJVj14BH+f///aQpx6Lh6H/8oB0tpRFQ/r8JVb3wS/zKq9Hdo/cen/IqoAqBtQcO9AnDNRh/xq28AijPf/Y/avli8R2XclCpxQNW/n8DkpNMVxyAARTlxUA5XmjK2oA9abj+QCjPQY4dHOoZbL/AlBcCedzwdLsYV1q1hmrIB+XqwzDl301wJm7TjzDHIJR/s8KT1wze/f+fCqQ5iFPOwKD9Gqx8L5HKgTEKUr4HpvyLNRE1DxvxpoPBJrjptkTVbL9JMh2unljlDO+I9yoYpIHy0Xlk0wEEOf9i"),
    "PLUS": (31, 31, 7.667, 7.667, "eNpjYEAGpuHiDLiB7v//2/FIZ/z//xmPdOb//19GpSmXTjiABG79//8Xmb9T4PV/fKDkPF7pSIkGJLDl//9fyPy40SihuXTi//9P8UjzX3oejyoCAIBUuYk="),
    "UNPINNED": (48, 48, 12.0, 12.0, "eNpjYCANOM7II0n9q///55Ki/vV/0jQ4fidRg8MPoIaFjINJg/N/bH7gWfyshAQbeE4AxSYTrQGs/P//WTic6YwWrDzH/kPALBw2OKFo4DkO5J1x+wIk7RgI2wA2/Qw/gwOQimTAZ0Md3PSzAkAWPvXgYL0KUn4Uphy/egan9/8nQE2/KMRAWD0DlwWqckLqYeF+Caqc4ff//9EkKCeoHqz8Olw5IfUQ5aIMRKoHe/UaknKQfxfiVn4MXTnDIzwpCGz6dTHUdPsdpwaw22+LEpv3IMoliM2suJTj0gBKYrckcOfueWilFlDotQQDcXkPCIRfAoW68OaM+ShCeu+BQucPQMGeTCw2XDhwoB+RUow//0cGc7HYgFq+WHxH0YAWIuBQ+v9/A5KQ6QqYcw6ApOag2gCUfYmqHgl4Yi0g1+BUz+CBRUMqUGgxriB0x4ikDKDAdxOiC3mQ6d+siK4VCCpH1UCEcmiszoG5/YstwXrH6RukfM4CKbcmoqJyApdvRJoOLR+ay4hXDip//hPjVRh4D1ZOlNsh4fgClC2QTQcAzMC/JA=="),
    "HANDLE": (30, 12, 10.0, 4.0, "eNr7//8/Axj8x8b4T4EswxAE/2kWGgCVkke5"),
    "SHOW_EDIT": (56, 56, 14.0, 14.0, "eNoTKmxAAvmCDFiAEBY1iQ0oIB6bPmxqqlHFqrDpw6amAQ1g04dNDbLaBjwAWc1Q1ocrXIayPnLiHS0NVWPTV4NFDVqaTSAiXYPVCIRXIkQqw/mx6cOlBpe/8IXPqL5RfSNdXwmwMiJHn0ZOtio5+gi5ezDqEyKifnfacBENrLMnpn7fdREDbCWmfr+IBRBTzuPSRyh8hpM+VJCpSp6+hgIy9eWTpy9bldrxTkz9jk0fMfU7Nn3E1O/Y9BGTR+mtbxuWfEuMPqd1GOWEAwAV7OkJ"),
    "SHOW_OBJECT": (56, 56, 14.0, 14.0, "eNoTbZ2GBBjwAGR1TcJF08jRNy1/Ann6+qeRp4+ganwmjOobXPrCbvzHA26E4dKHVxtQI7I+ZPv/EwC43D2qb1TfqL5RfaP6hp8+cusVatRjo+2CoamPnHYrue1kctvlwml9pOvrSxUEALzq1g8="),
}
# All icons share one scale (file proportions kept): Icon Size is the pin's drawn size; it is 12 px at 1x (36 px 3x file)
ICON_REF = 12.0
_icon_textures = {}


def icon_texture(name):
    tex = _icon_textures.get(name)
    if tex is None:
        w, h, _one_w, _one_h, packed = ICON_DATA[name]
        alpha = zlib.decompress(base64.b64decode(packed))
        pixels = []
        for a in alpha:
            pixels += (1.0, 1.0, 1.0, a / 255.0)
        tex = gpu.types.GPUTexture((w, h), format='RGBA8', data=gpu.types.Buffer('FLOAT', w * h * 4, pixels))
        _icon_textures[name] = tex
    return tex


def icon_size(name, s):
    """Drawn size of an icon: its 1x design size times the Icon Size setting."""
    _w, _h, one_w, one_h, _packed = ICON_DATA[name]
    k = prefs().icon_size / ICON_REF * s
    return one_w * k, one_h * k


def draw_icon(name, cx, cy, s, color):
    w, h = icon_size(name, s)
    draw_round_rect(cx - w * 0.5, cy - h * 0.5, w, h, 0.0, color, tex=icon_texture(name), mode=2)


def draw_circle(cx, cy, r, color):
    draw_round_rect(cx - r, cy - r, r * 2, r * 2, r, color)


def draw_lines(coords, color, width, mode='LINES'):
    gpu.state.blend_set('ALPHA')
    shader = gpu.shader.from_builtin('POLYLINE_UNIFORM_COLOR')
    batch = batch_for_shader(shader, mode, {"pos": [(c[0], c[1], 0.0) for c in coords]})
    shader.bind()
    shader.uniform_float("viewportSize", gpu.state.viewport_get()[2:])
    shader.uniform_float("lineWidth", width)
    shader.uniform_float("color", color)
    batch.draw(shader)


def arc(cx, cy, r, a0, a1, steps=16):
    return [(cx + r * math.cos(a0 + (a1 - a0) * t / steps), cy + r * math.sin(a0 + (a1 - a0) * t / steps))
            for t in range(steps + 1)]


def draw_text(x, y, text, color, size):
    blf.size(0, size)
    blf.color(0, *color)
    blf.position(0, x, y, 0)
    blf.draw(0, text)


def text_width(text, size):
    blf.size(0, size)
    return blf.dimensions(0, text)[0]


def text_baseline(y, h, size):
    blf.size(0, size)
    return y + (h - blf.dimensions(0, "0")[1]) * 0.5


def accent_color():
    # Accent Colour setting: slider fill, active row, lit buttons
    c = prefs().accent_color
    return (c[0], c[1], c[2], 1.0)


def text_colors(p):
    # Text, dimmed text, and the ink used for faint fills (hover, tracks): all from the Text Colour setting
    t = tuple(p.text_color)
    return t, (t[0], t[1], t[2], t[3] * 0.5), (t[0], t[1], t[2])


def type_label(item):
    return DOMAIN_LABELS.get(item.domain, item.domain)[0] + SUPPORTED_TYPES[item.data_type][0].upper()


def value_label(item):
    if item.data_type == "FLOAT":
        text = f"{item.value:.3f}"
    else:
        text = str(item.int_value)
    return ("~ " + text) if item.mixed else text


class QALayout:
    """Every clickable rect of the window, in region pixels (y up). Shared by drawing and hit tests."""

    def __init__(self, context, region):
        p = prefs()
        qa_apply_sizes(p)
        s = context.preferences.system.ui_scale
        wm = context.window_manager
        items = wm.ark_attribute_items
        self.s = s
        self.has_mesh = active_mesh_object(context) is not None
        self.rows_all = [i for i, it in enumerate(items) if not wm.ark_attribute_selection_only or it.on_selection]

        names = [items[i].name for i in self.rows_all] or ["Select a mesh"]
        name_auto = min(max(max(text_width(n, FONT * s) for n in names) + 14 * s, 96 * s), 260 * s)
        type_auto = text_width("WW", FONT_SMALL * s) + 10 * s
        self.col_w = [p.qa_name_w * s or name_auto, p.qa_value_w * s or 130 * s, p.qa_type_w * s or type_auto]
        inner = EYE_W * s + SWATCH_W * s + sum(self.col_w) + WRENCH_W * s

        # The footer's content sets the narrowest the window can get
        fh = FOOT_H * s - 4 * s
        sel_w = text_width("Selection", FONT_SMALL * s) + 14 * s
        on_top_w = text_width("On top", FONT_SMALL * s) + 14 * s
        foot_min = 2 * (fh + 2 * s) + sel_w + on_top_w + 8 * s + 2 * fh + 2 * s + 20 * s
        pl, pr, pt, pb = p.pad_left * s, p.pad_right * s, p.pad_top * s, p.pad_bottom * s
        self.w = max(inner, foot_min, 200 * s) + pl + pr

        visible = min(len(self.rows_all), p.max_rows)
        _qa["scroll"] = max(0, min(_qa["scroll"], len(self.rows_all) - visible))
        self.rows = self.rows_all[_qa["scroll"]:_qa["scroll"] + visible]
        self.collapsed = p.qa_collapsed
        list_h = 0 if self.collapsed else max(len(self.rows), 1) * ROW_H * s
        foot_h = 0 if self.collapsed else FOOT_H * s + 2 * s
        self.h = pt + HEAD_H * s + list_h + foot_h + pb

        self.x = max(0.0, min(p.qa_left, region.width - self.w))
        top = max(0.0, min(p.qa_top, region.height - self.h))
        self.y = region.height - top - self.h
        x, y, w, h = self.x, self.y, self.w, self.h

        # Header: handle, title, then show-all eye / chevron / pin / close on the right
        hy = y + h - pt - HEAD_H * s
        bs = HEAD_H * s - 6 * s
        self.header = (x, hy, w, HEAD_H * s)
        self.grip = (x + pl, hy, icon_size("HANDLE", s)[0] + 8 * s, HEAD_H * s)
        self.close = (x + w - pr - bs, hy + 3 * s, bs, bs)
        self.pin = (self.close[0] - bs - 2 * s, hy + 3 * s, bs, bs)
        self.collapse = (self.pin[0] - bs - 2 * s, hy + 3 * s, bs, bs)
        self.show_all = (self.collapse[0] - bs - 2 * s, hy + 3 * s, bs, bs)

        # Rows
        self.row_rects = []
        cx = [x + pl, 0, 0, 0, 0, 0]
        cx[1] = cx[0] + EYE_W * s
        cx[2] = cx[1] + SWATCH_W * s
        cx[3] = cx[2] + self.col_w[0]
        cx[4] = cx[3] + self.col_w[1]
        cx[5] = cx[4] + self.col_w[2]
        self.cols = cx
        ry = hy
        for index in ([] if self.collapsed else self.rows):
            ry -= ROW_H * s
            rh = ROW_H * s
            self.row_rects.append({
                "index": index, "row": (cx[0], ry, cx[5] + WRENCH_W * s - cx[0], rh),
                "eye": (cx[0], ry, EYE_W * s, rh), "swatch": (cx[1], ry, SWATCH_W * s, rh),
                "name": (cx[2], ry, self.col_w[0], rh), "value": (cx[3] + 3 * s, ry + 3 * s, self.col_w[1] - 6 * s, rh - 6 * s),
                "type": (cx[4], ry, self.col_w[2], rh), "wrench": (cx[5], ry, WRENCH_W * s, rh),
            })
        self.list_rect = (x, hy - list_h, w, list_h)
        # Column dividers sit on the right edge of the name / value / type columns
        self.dividers = [cx[3], cx[4], cx[5]]

        # Footer: mode toggles and filters on the left, - / + on the right (before the resize corner)
        fy = y + pb
        self.show_edit = (x + pl, fy, fh, fh)
        self.show_object = (self.show_edit[0] + fh + 2 * s, fy, fh, fh)
        self.sel_only = (self.show_object[0] + fh + 6 * s, fy, sel_w, fh)
        self.on_top = (self.sel_only[0] + sel_w + 2 * s, fy, on_top_w, fh)
        self.add = (x + w - pr - 8 * s - fh, fy, fh, fh)
        self.remove = (self.add[0] - fh - 2 * s, fy, fh, fh)
        self.edge = 5 * s    # grab distance of the resize edges

    def contains(self, mx, my):
        return self.x <= mx <= self.x + self.w and self.y <= my <= self.y + self.h

    def hit(self, mx, my):
        if not self.contains(mx, my):
            return None
        inside = lambda r: r[0] <= mx <= r[0] + r[2] and r[1] <= my <= r[1] + r[3]
        # Resize: right edge = width, bottom edge = rows shown, corner = both
        right = mx >= self.x + self.w - self.edge
        bottom = my <= self.y + self.edge and not self.collapsed
        if right or bottom:
            return ("resize", right, bottom)
        for key in ("close", "pin", "collapse", "show_all"):
            if inside(getattr(self, key)):
                return (key,)
        if inside(self.header):
            return ("grip",)
        if self.collapsed:
            return ("body",)
        lx, ly, lw, lh = self.list_rect
        if ly <= my <= ly + lh:
            for col, dx in enumerate(self.dividers):
                if abs(mx - dx) <= 3 * self.s:
                    return ("divider", col)
        for row in self.row_rects:
            if inside(row["row"]):
                for key in ("eye", "swatch", "name", "value", "type", "wrench"):
                    r = row[key]
                    if r[0] <= mx <= r[0] + r[2] and row["row"][1] <= my <= row["row"][1] + row["row"][3]:
                        return (key, row["index"])
        for key in ("show_edit", "show_object", "add", "remove", "sel_only", "on_top"):
            if inside(getattr(self, key)):
                return (key,)
        return ("body",)


def qa_capture(x, y, w, h):
    """Texture of the viewport pixels behind the window (None if the framebuffer can't be read)."""
    try:
        vx, vy, vw, vh = gpu.state.viewport_get()
        ix, iy = int(max(x, 0)), int(max(y, 0))
        iw, ih = int(min(w, vw - ix)), int(min(h, vh - iy))
        if iw < 4 or ih < 4:
            return None
        fb = gpu.state.active_framebuffer_get()
        buffer = fb.read_color(vx + ix, vy + iy, iw, ih, 4, 0, 'FLOAT')
        buffer.dimensions = iw * ih * 4
        return gpu.types.GPUTexture((iw, ih), format='RGBA16F', data=buffer)
    except Exception:
        return None


def bool_halves(rect, s):
    """Enable / Disable buttons inside a boolean value cell."""
    x, y, w, h = rect
    half = (w - 2 * s) * 0.5
    return (x, y, half, h), (x + half + 2 * s, y, half, h)


def draw_quick_window():
    context = bpy.context
    area = context.area
    if not _qa["open"] or area is None or area.as_pointer() != _qa["area"]:
        return
    region = context.region
    p = prefs()
    L = QALayout(context, region)
    s = L.s
    items = context.window_manager.ark_attribute_items
    text, dim, ink = text_colors(p)
    accent = accent_color()
    hover = _qa["hover"]
    edit = _qa["edit"]
    drag = _qa["drag"]
    obj = active_mesh_object(context)
    font = FONT * s
    small = FONT_SMALL * s

    gpu.state.blend_set('ALPHA')
    radius = p.glass_radius * s
    cr = p.control_radius * s    # sliders, swatches, buttons, highlights
    tex = qa_capture(L.x, L.y, L.w, L.h) if p.glass_blur > 0 else None
    glass = (*p.glass_color, p.glass_opacity)
    if tex:
        draw_round_rect(L.x, L.y, L.w, L.h, radius, glass, tex=tex, blur=p.glass_blur * s)
    else:
        draw_round_rect(L.x, L.y, L.w, L.h, radius, glass)
    if p.outline and p.outline_width > 0:
        draw_round_rect(L.x, L.y, L.w, L.h, radius, tuple(p.outline_color), blur=p.outline_width * s, mode=3)
    hover_fill = (*ink, 0.07)

    # Header
    gx, gy, gw, gh = L.grip
    draw_icon("HANDLE", gx + gw * 0.5, gy + gh * 0.5, s, dim if not p.qa_pinned else (*dim[:3], dim[3] * 0.4))
    draw_text(gx + gw + 2 * s, text_baseline(gy, gh, font), "Quick Attributes", text, font)
    for key in ("show_all", "collapse", "pin", "close"):
        bx, by, bw, bh = getattr(L, key)
        if hover == (key,):
            draw_round_rect(bx, by, bw, bh, cr, hover_fill)
        cx, cy = bx + bw * 0.5, by + bh * 0.5
        if key == "close":
            draw_icon("CLOSE", cx, cy, s, text)
        elif key == "collapse":
            draw_icon("CHEVRON_RIGHT" if p.qa_collapsed else "CHEVRON_DOWN", cx, cy, s, text)
        elif key == "show_all":
            draw_icon("EYE_OPEN" if p.overlay_all else "EYE_CLOSED", cx, cy, s, text if p.overlay_all else dim)
        else:
            draw_icon("PINNED" if p.qa_pinned else "UNPINNED", cx, cy, s, text if p.qa_pinned else dim)

    if L.collapsed:
        gpu.state.blend_set('NONE')
        return

    # Rows
    if not L.rows:
        message = "Select a mesh" if not L.has_mesh else ("Nothing set on the selection" if context.window_manager.ark_attribute_selection_only else "No attributes")
        lx, ly, lw, lh = L.list_rect
        draw_text(L.cols[0] + 4 * s, text_baseline(ly, lh, font), message, dim, font)
    active_index = context.window_manager.ark_attribute_index
    for row in L.row_rects:
        i = row["index"]
        item = items[i]
        rx, ry, rw, rh = row["row"]
        if i == active_index:
            draw_round_rect(rx, ry + 1 * s, rw, rh - 2 * s, cr, (*accent[:3], 0.22))

        # Eye
        ex, ey, ew, eh = row["eye"]
        if hover == ("eye", i):
            draw_round_rect(ex + 1 * s, ey + 2 * s, ew - 2 * s, eh - 4 * s, cr, hover_fill)
        draw_icon("EYE_OPEN" if item.show else "EYE_CLOSED", ex + ew * 0.5, ey + eh * 0.5, s, text if item.show else dim)

        # Colour swatch: 25 x 17, every corner rounded
        sx, sy, sw, sh = row["swatch"]
        bw, bh = SWATCH_SIZE[0] * s, SWATCH_SIZE[1] * s
        draw_round_rect(sx + (sw - bw) * 0.5, sy + (sh - bh) * 0.5, bw, bh, cr,
                        (item.color[0], item.color[1], item.color[2], 1.0))

        # Name
        nx, ny, nw, nh = row["name"]
        if edit and edit["kind"] == "name" and edit["index"] == i:
            draw_edit_field((nx + 2 * s, ny + 3 * s, nw - 6 * s, nh - 6 * s), edit, text, accent, s)
        else:
            blf.enable(0, blf.CLIPPING)
            blf.clipping(0, nx, ny, nx + nw - 6 * s, ny + nh)
            draw_text(nx + 5 * s, text_baseline(ny, nh, font), item.name,
                      text if item.on_selection or not obj or obj.mode != 'EDIT' else dim, font)
            blf.disable(0, blf.CLIPPING)

        # Value
        vx, vy, vw, vh = row["value"]
        if edit and edit["kind"] == "value" and edit["index"] == i:
            draw_edit_field(row["value"], edit, text, accent, s)
        elif item.data_type == "BOOLEAN":
            # Two buttons: the lit one is the selection's state (neither when mixed)
            for half, label, lit in zip(bool_halves(row["value"], s), ("Enable", "Disable"),
                                        (item.bool_value and not item.mixed, not item.bool_value and not item.mixed)):
                hx, hy, hw, hh = half
                hovered = hover == ("value", i) and hx <= _qa.get("mouse", (0, 0))[0] <= hx + hw
                draw_round_rect(hx, hy, hw, hh, cr, (*accent[:3], 0.9) if lit else (*ink, 0.14 if hovered else 0.08))
                blf.enable(0, blf.CLIPPING)
                blf.clipping(0, hx, hy, hx + hw, hy + hh)
                draw_text(hx + (hw - text_width(label, small)) * 0.5, text_baseline(hy, hh, small), label, text, small)
                blf.disable(0, blf.CLIPPING)
        else:
            draw_round_rect(vx, vy, vw, vh, cr, (*ink, 0.14 if hover == ("value", i) else 0.09))
            if item.data_type == "FLOAT":
                fill = vw * max(0.0, min(1.0, item.value))
                if fill > 0.5:
                    draw_round_rect(vx, vy, fill, vh, min(cr, fill * 0.5), (*accent[:3], 0.9))
            label = value_label(item)
            draw_text(vx + (vw - text_width(label, font)) * 0.5, text_baseline(vy, vh, font), label, text, font)

        # Type
        tx, ty, tw, th = row["type"]
        if hover == ("type", i):
            draw_round_rect(tx + 2 * s, ty + 3 * s, tw - 4 * s, th - 6 * s, cr, hover_fill)
        label = type_label(item)
        draw_text(tx + (tw - text_width(label, small)) * 0.5, text_baseline(ty, th, small), label, dim, small)

        # Wrench: the Modifier blue when a modifier reads this attribute
        wx, wy, ww, wh = row["wrench"]
        used = obj is not None and any(modifier_uses(m, item.attr_name) for m in obj.modifiers)
        if hover == ("wrench", i):
            draw_round_rect(wx + 2 * s, wy + 2 * s, ww - 4 * s, wh - 4 * s, cr, hover_fill)
        draw_icon("MODIFIER", wx + ww * 0.5, wy + wh * 0.5, s, (*p.modifier_color, 1.0) if used else (*dim[:3], dim[3] * 0.6))

    # Column dividers: shown on hover / while dragging
    lx, ly, lw, lh = L.list_rect
    for col, dx in enumerate(L.dividers):
        if hover == ("divider", col) or (drag and drag["kind"] == "column" and drag["col"] == col):
            draw_lines([(dx, ly + 2 * s), (dx, ly + lh - 2 * s)], accent, 1.5 * s)

    # Footer
    for key, icon, on in (("show_edit", "SHOW_EDIT", p.overlay_edit_mode), ("show_object", "SHOW_OBJECT", p.overlay_object_mode)):
        bx, by, bw, bh = getattr(L, key)
        draw_round_rect(bx, by, bw, bh, cr, (*accent[:3], 0.9) if on else (*ink, 0.13 if hover == (key,) else 0.07))
        draw_icon(icon, bx + bw * 0.5, by + bh * 0.5, s, text)
    for key, icon in (("remove", "MINUS"), ("add", "PLUS")):
        bx, by, bw, bh = getattr(L, key)
        draw_round_rect(bx, by, bw, bh, cr, (*ink, 0.13 if hover == (key,) else 0.07))
        draw_icon(icon, bx + bw * 0.5, by + bh * 0.5, s, text)
    for key, label, on in (("sel_only", "Selection", context.window_manager.ark_attribute_selection_only),
                           ("on_top", "On top", p.overlay_on_top)):
        bx, by, bw, bh = getattr(L, key)
        draw_round_rect(bx, by, bw, bh, cr, (*accent[:3], 0.9) if on else (*ink, 0.13 if hover == (key,) else 0.07))
        draw_text(bx + 7 * s, text_baseline(by, bh, small), label, text, small)

    # Resize corner (three dots), and the edge being hovered / dragged
    for i in range(3):
        for j in range(3 - i):
            draw_circle(L.x + L.w - 4 * s - i * 3.5 * s, L.y + 4 * s + j * 3.5 * s, 0.9 * s, dim)
    resize = hover if hover and hover[0] == "resize" else (("resize", drag["right"], drag["bottom"]) if drag and drag["kind"] == "resize" else None)
    if resize:
        if resize[1]:
            draw_lines([(L.x + L.w - 1 * s, L.y + radius), (L.x + L.w - 1 * s, L.y + L.h - radius)], accent, 2 * s)
        if resize[2]:
            draw_lines([(L.x + radius, L.y + 1 * s), (L.x + L.w - radius, L.y + 1 * s)], accent, 2 * s)

    gpu.state.blend_set('NONE')



def draw_edit_field(rect, edit, text, accent, s):
    x, y, w, h = rect
    cr = prefs().control_radius * s
    draw_round_rect(x, y, w, h, cr, accent)
    draw_round_rect(x + 1.2 * s, y + 1.2 * s, w - 2.4 * s, h - 2.4 * s, max(cr - 1.2 * s, 0.0), (1.0, 1.0, 1.0, 0.92))
    base = text_baseline(y, h, FONT * s)
    tx = x + 5 * s
    blf.enable(0, blf.CLIPPING)
    blf.clipping(0, x, y, x + w - 2 * s, y + h)
    if edit["all"] and edit["text"]:
        draw_round_rect(tx - 1 * s, y + 3 * s, text_width(edit["text"], FONT * s) + 2 * s, h - 6 * s, 2 * s, (*accent[:3], 0.45))
    draw_text(tx, base, edit["text"], (0.05, 0.05, 0.07, 1.0), FONT * s)
    blf.disable(0, blf.CLIPPING)
    if not edit["all"]:
        cursor = tx + text_width(edit["text"][:edit["cursor"]], FONT * s)
        draw_lines([(cursor, y + 4 * s), (cursor, y + h - 4 * s)], (0.05, 0.05, 0.07, 1.0), 1.2 * s)


# --- Window input ---------------------------------------------------------------------------------

def qa_find_region(context):
    for area in context.window.screen.areas:
        if area.as_pointer() == _qa["area"]:
            for region in area.regions:
                if region.type == 'WINDOW':
                    return area, region
    return None, None


def qa_close():
    _qa.update(open=False, drag=None, edit=None, hover=None)
    tag_redraw()


def qa_set_active(context, index):
    context.window_manager.ark_attribute_index = index


def qa_begin_edit(kind, index, text):
    _qa["edit"] = {"kind": kind, "index": index, "text": text, "cursor": len(text), "all": True}


def qa_commit_edit(context):
    edit = _qa["edit"]
    _qa["edit"] = None
    items = context.window_manager.ark_attribute_items
    if not edit or edit["index"] >= len(items):
        return
    item = items[edit["index"]]
    if edit["kind"] == "name":
        name = edit["text"].strip()
        if name and name != item.name:
            item.name = name
            bpy.ops.ed.undo_push(message="Rename Attribute")
        return
    raw = edit["text"].strip().replace(",", ".")   # AZERTY keypads type commas
    try:
        number = float(raw)
    except ValueError:
        return
    if item.data_type == "FLOAT":
        item.value = number
    else:
        item.int_value = int(round(number))
    bpy.ops.ed.undo_push(message="Set Attribute")


def qa_edit_event(context, event):
    edit = _qa["edit"]
    if event.type in {'MOUSEMOVE', 'INBETWEEN_MOUSEMOVE', 'TIMER', 'TIMER_REPORT'} or event.type.startswith("TIMER"):
        return {'PASS_THROUGH'}
    if event.value not in {'PRESS', 'NOTHING'} and event.type != 'TEXTINPUT':
        return {'RUNNING_MODAL'}
    text, cursor = edit["text"], edit["cursor"]
    if event.type in {'RET', 'NUMPAD_ENTER'} or (event.type in {'LEFTMOUSE', 'RIGHTMOUSE'} and event.value == 'PRESS'):
        qa_commit_edit(context)
    elif event.type == 'ESC':
        _qa["edit"] = None
    elif event.type == 'BACK_SPACE':
        if edit["all"]:
            edit.update(text="", cursor=0, all=False)
        elif cursor > 0:
            n = 1
            if event.ctrl:
                n = cursor - len(text[:cursor].rstrip("_ .").rstrip("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"))
            edit.update(text=text[:cursor - max(n, 1)] + text[cursor:], cursor=cursor - max(n, 1))
    elif event.type == 'DEL':
        if edit["all"]:
            edit.update(text="", cursor=0, all=False)
        else:
            edit["text"] = text[:cursor] + text[cursor + 1:]
    elif event.type == 'LEFT_ARROW':
        edit.update(cursor=0 if edit["all"] else max(0, cursor - 1), all=False)
    elif event.type == 'RIGHT_ARROW':
        edit.update(cursor=len(text) if edit["all"] else min(len(text), cursor + 1), all=False)
    elif event.type == 'HOME':
        edit.update(cursor=0, all=False)
    elif event.type == 'END':
        edit.update(cursor=len(text), all=False)
    elif event.ctrl and event.type == 'A':
        edit["all"] = True
    elif event.ctrl and event.type == 'C':
        context.window_manager.clipboard = text
    elif event.ctrl and event.type == 'V':
        paste = context.window_manager.clipboard.splitlines()[0] if context.window_manager.clipboard else ""
        if edit["all"]:
            edit.update(text=paste, cursor=len(paste), all=False)
        else:
            edit.update(text=text[:cursor] + paste + text[cursor:], cursor=cursor + len(paste))
    elif event.unicode and event.unicode.isprintable() and not event.ctrl:
        if edit["all"]:
            edit.update(text=event.unicode, cursor=1, all=False)
        else:
            edit.update(text=text[:cursor] + event.unicode + text[cursor:], cursor=cursor + 1)
    return {'RUNNING_MODAL'}


def qa_press(context, hit, mx, my, L, region):
    p = prefs()
    wm = context.window_manager
    items = wm.ark_attribute_items
    kind = hit[0]
    if kind == "close":
        qa_close()
    elif kind == "pin":
        p.qa_pinned = not p.qa_pinned
    elif kind == "collapse":
        p.qa_collapsed = not p.qa_collapsed
    elif kind == "grip":
        if not p.qa_pinned:
            _qa["drag"] = {"kind": "move", "dx": mx - L.x, "dy": (region.height - my) - (region.height - L.y - L.h)}
    elif kind == "resize":
        _qa["drag"] = {"kind": "resize", "right": hit[1], "bottom": hit[2], "x0": mx, "y0": my,
                       "w0": L.col_w[1], "rows0": max(len(L.rows), 1), "s": L.s}
    elif kind == "divider":
        col = hit[1]
        _qa["drag"] = {"kind": "column", "col": col, "x0": mx, "w0": L.col_w[col], "s": L.s}
    elif kind == "eye":
        items[hit[1]].show = not items[hit[1]].show
    elif kind == "swatch":
        qa_set_active(context, hit[1])
        if items[hit[1]].attr_name not in BUILTIN_DISPLAY:   # Blender's colours live in the theme
            bpy.ops.wm.call_panel(name=ARK_PT_quick_color.__name__, keep_open=True)
    elif kind == "name":
        qa_set_active(context, hit[1])
    elif kind == "value":
        qa_set_active(context, hit[1])
        item = items[hit[1]]
        if item.data_type == "BOOLEAN":
            row = next(r for r in L.row_rects if r["index"] == hit[1])
            enable, _disable = bool_halves(row["value"], L.s)
            item.bool_value = mx <= enable[0] + enable[2] + L.s
            bpy.ops.ed.undo_push(message="Set Attribute")
        else:
            row = next(r for r in L.row_rects if r["index"] == hit[1])
            _qa["drag"] = {"kind": "value", "index": hit[1], "x0": mx, "v0": item_number(item),
                           "w": row["value"][2], "moved": False, "s": L.s}
    elif kind == "type":
        qa_set_active(context, hit[1])
        bpy.ops.ark.attribute_convert('INVOKE_DEFAULT')
    elif kind == "wrench":
        qa_set_active(context, hit[1])
        bpy.ops.ark.attribute_focus_modifiers()
    elif kind == "add":
        bpy.ops.ark.attribute_add('INVOKE_DEFAULT')
    elif kind == "remove":
        if active_item(context):
            bpy.ops.ark.attribute_remove()
    elif kind == "sel_only":
        wm.ark_attribute_selection_only = not wm.ark_attribute_selection_only
    elif kind == "on_top":
        p.overlay_on_top = not p.overlay_on_top
    elif kind == "show_all":
        p.overlay_all = not p.overlay_all
    elif kind == "show_edit":
        p.overlay_edit_mode = not p.overlay_edit_mode
    elif kind == "show_object":
        p.overlay_object_mode = not p.overlay_object_mode


def qa_drag_event(context, event, mx, my, region):
    drag = _qa["drag"]
    p = prefs()
    items = context.window_manager.ark_attribute_items
    if event.type in {'MOUSEMOVE', 'INBETWEEN_MOUSEMOVE'}:
        if drag["kind"] == "move":
            p.qa_left = mx - drag["dx"]
            p.qa_top = (region.height - my) - drag["dy"]
        elif drag["kind"] == "resize":
            # Extra width goes to the value column; height is counted in rows
            if drag["right"]:
                p.qa_value_w = max(VALUE_MIN, (drag["w0"] + mx - drag["x0"]) / drag["s"])
            if drag["bottom"]:
                p.max_rows = max(3, drag["rows0"] + int(round((drag["y0"] - my) / (ROW_H * drag["s"]))))
        elif drag["kind"] == "column":
            minimum = (NAME_MIN, VALUE_MIN, TYPE_MIN)[drag["col"]]
            width = max(minimum, (drag["w0"] + mx - drag["x0"]) / drag["s"])
            setattr(p, ("qa_name_w", "qa_value_w", "qa_type_w")[drag["col"]], width)
        elif drag["index"] < len(items):
            dx = mx - drag["x0"]
            if abs(dx) > 3 * drag["s"]:
                drag["moved"] = True
            if drag["moved"]:
                item = items[drag["index"]]
                if item.data_type == "FLOAT":
                    value = drag["v0"] + dx / max(drag["w"], 1.0) * (0.1 if event.shift else 1.0)
                    value = max(min(0.0, drag["v0"]), min(max(1.0, drag["v0"]), value))
                    if event.ctrl:
                        step = 0.01 if event.shift else 0.1
                        value = round(value / step) * step
                    item.value = value
                else:
                    item.int_value = int(round(drag["v0"] + dx / (12 * drag["s"])))
        tag_redraw()
        return {'RUNNING_MODAL'}
    if event.type == 'LEFTMOUSE' and event.value == 'RELEASE':
        _qa["drag"] = None
        if drag["kind"] == "value" and drag["index"] < len(items):
            item = items[drag["index"]]
            if drag["moved"]:
                bpy.ops.ed.undo_push(message="Set Attribute")
            else:
                text = f"{item.value:.3f}".rstrip("0").rstrip(".") if item.data_type == "FLOAT" else str(item.int_value)
                qa_begin_edit("value", drag["index"], text)
        tag_redraw()
        return {'RUNNING_MODAL'}
    if event.type in {'ESC', 'RIGHTMOUSE'} and event.value == 'PRESS':
        if drag["kind"] == "value" and drag["index"] < len(items):
            item = items[drag["index"]]
            if item.data_type == "FLOAT":
                item.value = drag["v0"]
            else:
                item.int_value = int(drag["v0"])
        _qa["drag"] = None
        tag_redraw()
    return {'RUNNING_MODAL'}


def qa_event(context, event):
    area, region = qa_find_region(context)
    if region is None:
        return {'PASS_THROUGH'}   # other workspace: the window waits there
    mx, my = event.mouse_x - region.x, event.mouse_y - region.y
    if _qa["edit"]:
        result = qa_edit_event(context, event)
        area.tag_redraw()
        return result
    if _qa["drag"]:
        return qa_drag_event(context, event, mx, my, region)
    L = QALayout(context, region)
    hit = L.hit(mx, my)
    if event.type in {'MOUSEMOVE', 'INBETWEEN_MOUSEMOVE'}:
        _qa["mouse"] = (mx, my)
        if hit and hit[0] == "value":
            area.tag_redraw()   # Enable / Disable hover follows the mouse inside the cell
        if hit != _qa["hover"]:
            _qa["hover"] = hit
            area.tag_redraw()
        return {'PASS_THROUGH'}
    if hit is None:
        return {'PASS_THROUGH'}
    if event.type in {'WHEELUPMOUSE', 'WHEELDOWNMOUSE'}:
        _qa["scroll"] += -1 if event.type == 'WHEELUPMOUSE' else 1
        area.tag_redraw()
        return {'RUNNING_MODAL'}
    if event.type == 'LEFTMOUSE' and event.value in {'PRESS', 'DOUBLE_CLICK'}:
        # Blender only sends DOUBLE_CLICK when nobody took the first press, so double clicks are timed here
        now = time.monotonic()
        double = event.value == 'DOUBLE_CLICK' or (_qa["last_click"][0] == hit and now - _qa["last_click"][1] < 0.4)
        _qa["last_click"] = (None, 0.0) if double else (hit, now)
        if double and hit[0] == "name":
            qa_begin_edit("name", hit[1], context.window_manager.ark_attribute_items[hit[1]].name)
        elif double and hit[0] == "divider":
            setattr(prefs(), ("qa_name_w", "qa_value_w", "qa_type_w")[hit[1]], 0.0)
        else:
            qa_press(context, hit, mx, my, L, region)
        tag_redraw()
        return {'RUNNING_MODAL'}
    if event.type == 'LEFTMOUSE':
        return {'RUNNING_MODAL'}
    if event.type == 'F2' and event.value == 'PRESS' and hit[0] in {"eye", "swatch", "name", "value", "type", "wrench"}:
        qa_begin_edit("name", hit[1], context.window_manager.ark_attribute_items[hit[1]].name)
        tag_redraw()
        return {'RUNNING_MODAL'}
    if event.type == 'RIGHTMOUSE':
        return {'RUNNING_MODAL'}
    return {'PASS_THROUGH'}


class ARK_OT_quick_attributes(bpy.types.Operator):
    """Open or close the Quick Attributes window in this 3D Viewport"""
    bl_idname = "ark.quick_attributes"
    bl_label = "Quick Attributes"

    @classmethod
    def poll(cls, context):
        return context.area is not None and context.area.type == 'VIEW_3D'

    def invoke(self, context, event):
        if _qa["open"]:
            qa_close()
            return {'FINISHED'}
        _qa.update(open=True, area=context.area.as_pointer(), drag=None, edit=None, hover=None)
        sync_items(context)
        context.window_manager.modal_handler_add(self)
        tag_redraw()
        return {'RUNNING_MODAL'}

    def modal(self, context, event):
        if not _qa["open"]:
            return {'FINISHED'}
        try:
            return qa_event(context, event)
        except Exception as error:   # never leave the viewport stuck behind a broken handler
            _qa.update(drag=None, edit=None)
            print("Quick Attributes:", error)
            return {'PASS_THROUGH'}


class ARK_PT_quick_color(bpy.types.Panel):
    # Popover opened by a row's colour swatch
    bl_label = "Attribute Colour"
    bl_space_type = 'VIEW_3D'
    bl_region_type = 'HEADER'
    bl_ui_units_x = 9

    def draw(self, context):
        item = active_item(context)
        if item:
            self.layout.label(text=item.name)
            self.layout.template_color_picker(item, "color", value_slider=True)
            self.layout.prop(item, "color", index=3, text="Opacity", slider=True)
            self.layout.prop(item, "color", text="")


@bpy.app.handlers.persistent
def qa_load_pre(*_args):
    _qa.update(open=False, drag=None, edit=None, hover=None)


# ---------------------------------------------------------------------------------------------------
# Sidebar: opens the window, plus the overlay settings

class ARK_PT_attributes_view3d(bpy.types.Panel):
    bl_label = "Attributes"
    bl_space_type = 'VIEW_3D'
    bl_region_type = 'UI'
    bl_category = "Attributes"

    def draw(self, context):
        layout = self.layout
        layout.operator(ARK_OT_quick_attributes.bl_idname, icon='WINDOW',
                        text="Close Quick Attributes" if _qa["open"] else "Quick Attributes", depress=_qa["open"])
        p = prefs()
        if not isinstance(p, bpy.types.AddonPreferences):
            return
        layout.label(text="Overlay")
        col = layout.column(align=True)
        col.prop(p, "overlay_all")
        row = col.row(align=True)
        row.prop(p, "overlay_edit_mode", toggle=True)
        row.prop(p, "overlay_object_mode", toggle=True)
        col.prop(p, "overlay_on_top")
        col.prop(p, "overlay_offset", text="Depth Offset")
        col.prop(p, "overlay_line_width", text="Line Width")
        layout.label(text="Window (Opacity 0 + Blur 0 = fully clear)")
        col = layout.column(align=True)
        col.prop(p, "glass_color", text="Background")
        col.prop(p, "glass_opacity", text="Opacity")
        col.prop(p, "glass_blur", text="Blur")
        col.prop(p, "glass_radius", text="Corner Radius")
        col = layout.column(align=True)
        col.prop(p, "outline")
        sub = col.column(align=True)
        sub.active = p.outline
        sub.prop(p, "outline_width", text="Thickness")
        sub.prop(p, "outline_color", text="")
        col = layout.column(align=True)
        col.prop(p, "accent_color", text="Accent")
        col.prop(p, "modifier_color", text="Modifier")
        col.prop(p, "control_radius")
        layout.label(text="Padding")
        grid = layout.grid_flow(row_major=True, columns=2, even_columns=True, align=True)
        grid.prop(p, "pad_left")
        grid.prop(p, "pad_right")
        grid.prop(p, "pad_top")
        grid.prop(p, "pad_bottom")
        col = layout.column(align=True)
        col.prop(p, "text_color", text="Text")
        col.prop(p, "text_size")
        col.prop(p, "row_height")
        col.prop(p, "icon_size")


# ---------------------------------------------------------------------------------------------------
# Viewport overlay: elements with a non-zero value, in the attribute's colour (Edit Mode)

@bpy.app.handlers.persistent
def mark_dirty(*_args):
    _batch_cache.clear()


def overlay_geometry(obj, name, domain, data_type):
    """World-space (kind, coords) of the elements where the attribute is non-zero. Edit Mode reads the bmesh;
    Object Mode reads the mesh data (display only)."""
    matrix = obj.matrix_world
    mesh = obj.data
    if obj.mode == 'EDIT':
        bm = bmesh.from_edit_mesh(mesh)
        layer = bm_layer(bm, domain, data_type, name)
        if layer is None:
            return None, []
        if domain == "EDGE":
            return 'LINE', [matrix @ v.co for e in bm.edges if e[layer] and not e.hide for v in e.verts]
        if domain == "POINT":
            return 'POINT', [matrix @ v.co for v in bm.verts if v[layer] and not v.hide]
        coords = []
        for face in bm.faces:
            if face.hide:
                continue
            if domain == "FACE" and not face[layer]:
                continue
            if domain == "CORNER" and not any(loop[layer] for loop in face.loops):
                continue
            verts = [matrix @ v.co for v in face.verts]
            for i in range(1, len(verts) - 1):
                coords += [verts[0], verts[i], verts[i + 1]]
        return 'FACE', coords

    attr = mesh.attributes.get(name)
    if attr is None or len(attr.data) == 0:
        return None, []
    values = np.zeros(len(attr.data), dtype=np.float32 if data_type == "FLOAT" else np.int32 if data_type == "INT" else bool)
    attr.data.foreach_get("value", values)
    on = values != 0
    co = np.zeros(len(mesh.vertices) * 3, dtype=np.float32)
    mesh.vertices.foreach_get("co", co)
    m = np.array(matrix, dtype=np.float32)
    co = co.reshape(-1, 3) @ m[:3, :3].T + m[:3, 3]
    if domain == "EDGE":
        ev = np.zeros(len(mesh.edges) * 2, dtype=np.int32)
        mesh.edges.foreach_get("vertices", ev)
        return 'LINE', co[ev.reshape(-1, 2)[on].ravel()].tolist()
    if domain == "POINT":
        return 'POINT', co[on].tolist()
    mesh.calc_loop_triangles()
    tris = mesh.loop_triangles
    tv = np.zeros(len(tris) * 3, dtype=np.int32)
    tris.foreach_get("vertices", tv)
    if domain == "FACE":
        poly = np.zeros(len(tris), dtype=np.int32)
        tris.foreach_get("polygon_index", poly)
        keep = on[poly]
    else:
        loops = np.zeros(len(tris) * 3, dtype=np.int32)
        tris.foreach_get("loops", loops)
        keep = on[loops.reshape(-1, 3)].any(axis=1)
    return 'FACE', co[tv.reshape(-1, 3)[keep].ravel()].tolist()


def build_batches(obj, name, domain, data_type):
    kind, coords = overlay_geometry(obj, name, domain, data_type)
    if not coords:
        return []
    shader = gpu.shader.from_builtin({'LINE': 'POLYLINE_UNIFORM_COLOR', 'POINT': 'POINT_UNIFORM_COLOR',
                                      'FACE': 'UNIFORM_COLOR'}[kind])
    primitive = {'LINE': 'LINES', 'POINT': 'POINTS', 'FACE': 'TRIS'}[kind]
    return [(shader, batch_for_shader(shader, primitive, {"pos": coords}), kind)]



def depth_offset_projection(rv3d, offset):
    """Projection that pulls everything toward the view by `offset` of its distance (same screen place),
    so lines lying on faces win the depth test instead of sinking into concave corners."""
    if rv3d.is_perspective:
        pull = Matrix.Diagonal((1.0 - offset, 1.0 - offset, 1.0 - offset, 1.0))
    else:
        pull = Matrix.Translation((0.0, 0.0, offset * rv3d.view_distance * 4.0))
    return rv3d.window_matrix @ pull


def overlay_objects(context, p):
    """Meshes whose attributes are drawn: the ones in Edit Mode, or the selected ones in Object Mode."""
    if not p.overlay_all:
        return []
    if context.mode == 'EDIT_MESH':
        return [o for o in context.objects_in_mode if o.type == 'MESH'] if p.overlay_edit_mode else []
    if context.mode == 'OBJECT' and p.overlay_object_mode:
        objects = [o for o in context.selected_objects if o.type == 'MESH' and o.visible_get()]
        active = active_mesh_object(context)
        if active and active not in objects and active.visible_get():
            objects.append(active)
        return objects
    return []


def draw_overlay():
    context = bpy.context
    space = context.space_data
    overlay = getattr(space, "overlay", None)
    if overlay is not None and not overlay.show_overlays:
        return
    p = prefs()
    objects = overlay_objects(context, p)
    if not objects:
        return
    s = context.preferences.system.ui_scale
    region = context.region
    theme = context.preferences.themes[0].view_3d
    wire = theme.wire_edit if context.mode == 'EDIT_MESH' else theme.wire
    wire = (wire[0], wire[1], wire[2], 1.0)
    on_top = p.overlay_on_top or getattr(space.shading, "show_xray", False)
    gpu.state.blend_set('ALPHA')
    gpu.state.depth_test_set('NONE' if on_top else 'LESS_EQUAL')
    gpu.state.depth_mask_set(False)
    gpu.matrix.push_projection()
    if not on_top:
        gpu.matrix.load_projection_matrix(depth_offset_projection(context.region_data, p.overlay_offset))
    try:
        active = active_item(context)
        active_name = active.attr_name if active else ""
        for obj in objects:
            mesh = obj.data
            # Blender draws its own; the active attribute is drawn last so it wins where colours overlap
            attrs = [a for a in mesh.attributes if is_user_attribute(a) and a.name not in BUILTIN_DISPLAY]
            attrs.sort(key=lambda a: a.name == active_name)
            for attr in attrs:
                color, show = get_display(mesh, attr.name)
                if not show:
                    continue
                key = (obj.as_pointer(), obj.mode, attr.name, attr.domain, attr.data_type)
                batches = _batch_cache.get(key)
                if batches is None:
                    try:
                        batches = build_batches(obj, attr.name, attr.domain, attr.data_type)
                    except Exception as error:
                        print("Ark attribute overlay:", error)
                        batches = []
                    _batch_cache[key] = batches
                for shader, batch, kind in batches:
                    shader.bind()
                    if kind == 'LINE':
                        # Wide colour band, then the thin wire on top of it, like Blender's sharp / crease edges
                        shader.uniform_float("viewportSize", (region.width, region.height))
                        shader.uniform_float("lineWidth", p.overlay_line_width * s)
                        shader.uniform_float("color", color)
                        batch.draw(shader)
                        shader.uniform_float("lineWidth", 1.0 * s)
                        shader.uniform_float("color", wire)
                    elif kind == 'POINT':
                        gpu.state.point_size_set(8.0 * s)
                        shader.uniform_float("color", color)
                    else:
                        shader.uniform_float("color", (color[0], color[1], color[2], color[3] * 0.6))
                    batch.draw(shader)
    finally:
        gpu.matrix.pop_projection()
        gpu.state.depth_mask_set(True)
        gpu.state.depth_test_set('NONE')
        gpu.state.blend_set('NONE')



# ---------------------------------------------------------------------------------------------------

classes = (
    ARK_AttributePreferences,
    ARK_AttributeItem,
    ARK_OT_attribute_add,
    ARK_OT_attribute_remove,
    ARK_OT_attribute_convert,
    ARK_OT_attribute_focus_modifiers,
    ARK_OT_quick_attributes,
    ARK_PT_quick_color,
    ARK_PT_attributes_view3d,
)


def register():
    global _draw_handle, _window_handle
    for cls in classes:
        bpy.utils.register_class(cls)
    bpy.types.WindowManager.ark_attribute_items = CollectionProperty(type=ARK_AttributeItem)
    bpy.types.WindowManager.ark_attribute_index = IntProperty()
    bpy.types.WindowManager.ark_attribute_selection_only = BoolProperty(
        name="Only on selection", description="List only the attributes set (non-zero) on the selected elements",
        update=lambda self, context: tag_redraw())
    bpy.app.timers.register(sync_timer, persistent=True)
    bpy.app.handlers.depsgraph_update_post.append(mark_dirty)
    bpy.app.handlers.undo_post.append(mark_dirty)
    bpy.app.handlers.redo_post.append(mark_dirty)
    bpy.app.handlers.load_pre.append(qa_load_pre)
    _draw_handle = bpy.types.SpaceView3D.draw_handler_add(draw_overlay, (), 'WINDOW', 'POST_VIEW')
    _window_handle = bpy.types.SpaceView3D.draw_handler_add(draw_quick_window, (), 'WINDOW', 'POST_PIXEL')


def unregister():
    global _draw_handle, _window_handle, _qa_shader
    qa_load_pre()
    for handle in (_draw_handle, _window_handle):
        if handle:
            bpy.types.SpaceView3D.draw_handler_remove(handle, 'WINDOW')
    _draw_handle = _window_handle = None
    _qa_shader = None
    _icon_textures.clear()
    for handlers, func in ((bpy.app.handlers.depsgraph_update_post, mark_dirty), (bpy.app.handlers.undo_post, mark_dirty),
                           (bpy.app.handlers.redo_post, mark_dirty), (bpy.app.handlers.load_pre, qa_load_pre)):
        if func in handlers:
            handlers.remove(func)
    if bpy.app.timers.is_registered(sync_timer):
        bpy.app.timers.unregister(sync_timer)
    del bpy.types.WindowManager.ark_attribute_items
    del bpy.types.WindowManager.ark_attribute_index
    del bpy.types.WindowManager.ark_attribute_selection_only
    for cls in reversed(classes):
        bpy.utils.unregister_class(cls)


if __name__ == "__main__":
    register()
