Skip to content

Internal Retina display is not listed on MacDisplayJNA #3404

Closed

Description

@dyorgio

Internal Retina display doesn't use DisplayPort, so doesn't work using IOPortTransportStateDisplayPort service.

There is 2 ways to get info about it: for M1-M2 and for M3-M4-M5.

I did a version using Claude Opus 4.8 that works on my machine, but its envolves "syntetic" EDID (because internal Retina display doesn't have EPROM with theses informations).

What do you think about this implementation? I looked at and to me appears a lot of AI slop, but works (brings 3 displays on my setup (2 external 1 retina).

/*
 * Copyright 2016-2026 The OSHI Project Contributors
 * SPDX-License-Identifier: MIT
 */
package oshi.hardware.platform.mac;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sun.jna.Pointer;
import com.sun.jna.platform.mac.CoreFoundation;
import com.sun.jna.platform.mac.CoreFoundation.CFDataRef;
import com.sun.jna.platform.mac.CoreFoundation.CFDictionaryRef;
import com.sun.jna.platform.mac.CoreFoundation.CFIndex;
import com.sun.jna.platform.mac.CoreFoundation.CFNumberRef;
import com.sun.jna.platform.mac.CoreFoundation.CFStringRef;
import com.sun.jna.platform.mac.CoreFoundation.CFTypeRef;
import com.sun.jna.platform.mac.IOKit.IOIterator;
import com.sun.jna.platform.mac.IOKit.IORegistryEntry;
import com.sun.jna.platform.mac.IOKitUtil;
import com.sun.jna.ptr.LongByReference;

import oshi.annotation.concurrent.Immutable;
import oshi.hardware.Display;
import oshi.hardware.common.AbstractDisplay;

/**
 * A Display
 */
@Immutable
final class MacDisplayJNA extends AbstractDisplay {

    private static final Logger LOG = LoggerFactory.getLogger(MacDisplayJNA.class);

    private static final CoreFoundation CF = CoreFoundation.INSTANCE;

    /** IOKit registry plane used for the tree walk. */
    private static final String IOSERVICE_PLANE = "IOService";

    /** kCFNumberSInt64Type, as the CFIndex expected by CFNumberGetValue. */
    private static final CFIndex K_CF_NUMBER_SINT64 = new CFIndex(4);

    /**
     * Framebuffer node class names across Apple Silicon generations:
     * "AppleCLCD2" on M1/M2, "IOMobileFramebufferShim" on M3 and newer.
     */
    private static final String[] FRAMEBUFFER_NODES = { "IOMobileFramebufferShim", "AppleCLCD2" };

    /**
     * Constructor for MacDisplayJNA.
     *
     * @param edid a byte array representing a display EDID
     */
    MacDisplayJNA(byte[] edid) {
        super(edid);
        LOG.debug("Initialized MacDisplayJNA");
    }

    /**
     * Gets Display Information
     *
     * @return An array of Display objects representing monitors, etc.
     */
    public static List<Display> getDisplays() {
        List<Display> displays = new ArrayList<>();
        // Intel: real EDID exposed under IODisplayConnect.
        displays.addAll(getDisplaysFromService("IODisplayConnect", "IODisplayEDID", "IOService"));
        // Apple Silicon: walk the framebuffer tree (IOMobileFramebufferShim on M3+, AppleCLCD2 on
        // M1/M2). External panels expose a real EDID; the built-in panel has none, so we synthesize
        // one from DisplayAttributes/ProductAttributes. IOServiceMatching returns nothing for these
        // display classes, so the tree must be walked from the root.
        displays.addAll(getAppleSiliconDisplays());

        return displays;
    }

    /**
     * Helper method to get displays from a specific IOKit service via service matching. Used for the
     * Intel path, where IODisplayConnect exposes a real EDID byte array.
     *
     * @param serviceName    The IOKit service name to search for
     * @param edidKeyName    The key name for the EDID property
     * @param childEntryName The name of the child entry to search in, or null to search directly in the service
     * @return List of Display objects found using this service
     */
    private static List<Display> getDisplaysFromService(String serviceName, String edidKeyName, String childEntryName) {
        List<Display> displays = new ArrayList<>();

        IOIterator serviceIterator = IOKitUtil.getMatchingServices(serviceName);
        if (serviceIterator != null) {
            CFStringRef cfEdid = CFStringRef.createCFString(edidKeyName);
            IORegistryEntry sdService = serviceIterator.next();

            while (sdService != null) {
                IORegistryEntry propertySource = null;
                try {
                    propertySource = childEntryName == null ? sdService : sdService.getChildEntry(childEntryName);
                    if (propertySource != null) {
                        CFTypeRef edidRaw = propertySource.createCFProperty(cfEdid);
                        if (edidRaw != null) {
                            CFDataRef edid = new CFDataRef(edidRaw.getPointer());
                            try {
                                int length = edid.getLength();
                                Pointer p = edid.getBytePtr();
                                displays.add(new MacDisplayJNA(p.getByteArray(0, length)));
                            } finally {
                                edid.release();
                            }
                        }
                        if (childEntryName != null) {
                            propertySource.release();
                        }
                    }
                } finally {
                    sdService.release();
                    sdService = serviceIterator.next();
                }
            }
            serviceIterator.release();
            cfEdid.release();
        }
        return displays;
    }

    /**
     * Discovers every Apple Silicon display by walking the IORegistry for framebuffer nodes.
     *
     * @return List of Display objects (internal + external)
     */
    private static List<Display> getAppleSiliconDisplays() {
        List<Display> displays = new ArrayList<>();
        IORegistryEntry root = IOKitUtil.getRoot();
        if (root != null) {
            try {
                collectFramebuffers(root, displays);
            } catch (RuntimeException e) {
                LOG.warn("Failed to enumerate Apple Silicon displays from the framebuffer tree", e);
            } finally {
                root.release();
            }
        }
        return displays;
    }

    /**
     * Recursively walks the IOService plane collecting framebuffer nodes and turning each into a
     * Display (real EDID when present, synthesized EDID otherwise).
     */
    private static void collectFramebuffers(IORegistryEntry entry, List<Display> out) {
        if (isFramebufferNode(entry.getName())) {
            // The parent is the display nub: disp0 (built-in) or dispext0/1/... (external). We search
            // that whole subtree for the EDID / DisplayAttributes, wherever they happen to live.
            IORegistryEntry nub = entry.getParentEntry(IOSERVICE_PLANE);
            try {
                IORegistryEntry searchRoot = nub != null ? nub : entry;
                byte[] edid = readEdid(searchRoot);
                if (edid != null) {
                    out.add(new MacDisplayJNA(edid));
                }
            } finally {
                if (nub != null) {
                    nub.release();
                }
            }
        }
        IOIterator children = entry.getChildIterator(IOSERVICE_PLANE);
        if (children != null) {
            try {
                IORegistryEntry child = children.next();
                while (child != null) {
                    try {
                        collectFramebuffers(child, out);
                    } finally {
                        child.release();
                    }
                    child = children.next();
                }
            } finally {
                children.release();
            }
        }
    }

    private static boolean isFramebufferNode(String name) {
        if (name != null) {
            for (String fb : FRAMEBUFFER_NODES) {
                if (fb.equals(name)) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * Returns a 128-byte EDID for the display rooted at the given nub: the real IODisplayEDID/EDID
     * if the panel exposes one (typically external displays), otherwise an EDID synthesized from
     * DisplayAttributes -> ProductAttributes (the built-in panel). Returns null for framebuffer
     * pipes with no connected/identified display, so unused dispext* nodes are skipped.
     */
    private static byte[] readEdid(IORegistryEntry searchRoot) {
        byte[] real = readEdidData(searchRoot, "IODisplayEDID");
        if (real == null) {
            real = readEdidData(searchRoot, "EDID");
        }
        if (real != null && real.length >= 128) {
            return real;
        }
        return synthesizeFromDisplayAttributes(searchRoot);
    }

    private static byte[] readEdidData(IORegistryEntry searchRoot, String key) {
        CFStringRef k = CFStringRef.createCFString(key);
        CFTypeRef raw = searchProperty(searchRoot, k);
        k.release();
        if (raw == null) {
            return null;
        }
        try {
            CFDataRef data = new CFDataRef(raw.getPointer());
            int len = data.getLength();
            return len > 0 ? data.getBytePtr().getByteArray(0, len) : null;
        } finally {
            raw.release();
        }
    }

    private static byte[] synthesizeFromDisplayAttributes(IORegistryEntry searchRoot) {
        CFStringRef k = CFStringRef.createCFString("DisplayAttributes");
        CFTypeRef raw = searchProperty(searchRoot, k);
        k.release();
        if (raw == null) {
            return null;
        }
        try {
            CFDictionaryRef attrs = new CFDictionaryRef(raw.getPointer());
            // CFDictionaryGetValue returns a borrowed reference: do NOT release `product`.
            CFDictionaryRef product = cfDictGetDictionary(attrs, "ProductAttributes");
            if (product == null) {
                return null;
            }
            return buildEdid(cfDictGetLong(product, "LegacyManufacturerID"),
                    cfDictGetString(product, "ManufacturerID"), cfDictGetLong(product, "ProductID"),
                    cfDictGetLong(product, "SerialNumber"), cfDictGetLong(product, "WeekOfManufacture"),
                    cfDictGetLong(product, "YearOfManufacture"), cfDictGetString(product, "ProductName"),
                    cfDictGetString(product, "AlphanumericSerialNumber"));
        } finally {
            raw.release();
        }
    }

    /**
     * Depth-first search for a property in an entry and its descendants. Returns the first match
     * (Create rule: caller must release). Used because the EDID/DisplayAttributes may sit on the
     * framebuffer node, the display nub, or a DCPAV proxy depending on the chip/macOS version.
     */
    private static CFTypeRef searchProperty(IORegistryEntry entry, CFStringRef key) {
        CFTypeRef value = entry.createCFProperty(key);
        if (value != null) {
            return value;
        }
        IOIterator children = entry.getChildIterator(IOSERVICE_PLANE);
        if (children != null) {
            try {
                IORegistryEntry child = children.next();
                while (child != null) {
                    try {
                        CFTypeRef childValue = searchProperty(child, key);
                        if (childValue != null) {
                            return childValue;
                        }
                    } finally {
                        child.release();
                    }
                    child = children.next();
                }
            } finally {
                children.release();
            }
        }
        return null;
    }

    // ---------------------------------------------------------------------
    // CFDictionary helpers. These are the only JNA-version-sensitive lines;
    // adapt CFDictionaryGetValue / CFNumberGetValue signatures if needed.
    // ---------------------------------------------------------------------

    private static CFDictionaryRef cfDictGetDictionary(CFDictionaryRef dict, String key) {
        CFStringRef k = CFStringRef.createCFString(key);
        try {
            Pointer v = CF.CFDictionaryGetValue(dict, k);
            return v == null ? null : new CFDictionaryRef(v);
        } finally {
            k.release();
        }
    }

    private static String cfDictGetString(CFDictionaryRef dict, String key) {
        CFStringRef k = CFStringRef.createCFString(key);
        try {
            Pointer v = CF.CFDictionaryGetValue(dict, k);
            return v == null ? null : new CFStringRef(v).stringValue();
        } finally {
            k.release();
        }
    }

    private static Long cfDictGetLong(CFDictionaryRef dict, String key) {
        CFStringRef k = CFStringRef.createCFString(key);
        try {
            Pointer v = CF.CFDictionaryGetValue(dict, k);
            if (v == null) {
                return null;
            }
            CFNumberRef num = new CFNumberRef(v);
            LongByReference out = new LongByReference();
            CF.CFNumberGetValue(num, K_CF_NUMBER_SINT64, out);
            return out.getValue();
        } finally {
            k.release();
        }
    }

    // ---------------------------------------------------------------------
    // EDID 1.4 synthesis (128 bytes) from ProductAttributes fields.
    // ---------------------------------------------------------------------

    private static byte[] buildEdid(Long legacyManufacturerId, String manufacturerId, Long productId, Long serialNumber,
            Long week, Long year, String productName, String alphanumericSerial) {
        byte[] e = new byte[128];

        // Fixed header pattern (00 FF FF FF FF FF FF 00)
        e[0] = 0x00;
        e[1] = (byte) 0xFF;
        e[2] = (byte) 0xFF;
        e[3] = (byte) 0xFF;
        e[4] = (byte) 0xFF;
        e[5] = (byte) 0xFF;
        e[6] = (byte) 0xFF;
        e[7] = 0x00;

        // Manufacturer ID (bytes 8-9, big-endian, 3 x 5-bit packed). Prefer the numeric
        // LegacyManufacturerID; otherwise PNP-encode the 3-letter ManufacturerID string.
        int mfg = legacyManufacturerId != null ? legacyManufacturerId.intValue() : encodePnpId(manufacturerId);
        e[8] = (byte) ((mfg >> 8) & 0xFF);
        e[9] = (byte) (mfg & 0xFF);

        // Product code (bytes 10-11, little-endian)
        int pid = productId != null ? productId.intValue() : 0;
        e[10] = (byte) (pid & 0xFF);
        e[11] = (byte) ((pid >> 8) & 0xFF);

        // Serial number (bytes 12-15, little-endian)
        long sn = serialNumber != null ? serialNumber : 0L;
        e[12] = (byte) (sn & 0xFF);
        e[13] = (byte) ((sn >> 8) & 0xFF);
        e[14] = (byte) ((sn >> 16) & 0xFF);
        e[15] = (byte) ((sn >> 24) & 0xFF);

        // Week / year of manufacture (year stored as value - 1990)
        e[16] = (byte) (week != null ? (week & 0xFF) : 0);
        e[17] = (byte) (year != null ? ((year - 1990) & 0xFF) : 0);

        // EDID version 1.4
        e[18] = 0x01;
        e[19] = 0x04;

        // Basic display params: digital input, DisplayPort; sane gamma/feature defaults.
        e[20] = (byte) 0xA5;
        e[21] = 0x00; // H image size (cm) unknown
        e[22] = 0x00; // V image size (cm) unknown
        e[23] = 0x78; // gamma 2.2
        e[24] = 0x0A; // feature support

        // Chromaticity (25-34) and established timings (35-37) left zeroed: parser-safe.
        // Standard timing descriptors (38-53): 0x01 0x01 = unused slots.
        for (int i = 38; i <= 53; i++) {
            e[i] = 0x01;
        }

        // Four 18-byte descriptors. Use text descriptors so EdidUtil prints name and serial.
        writeTextDescriptor(e, 54, 0xFC, productName);        // Monitor name
        writeTextDescriptor(e, 72, 0xFF, alphanumericSerial); // Display serial number
        // Descriptors at 90 and 108 left zeroed (treated as unused/unspecified).

        e[126] = 0x00; // number of extension blocks

        // Checksum: sum of all 128 bytes must be 0 (mod 256).
        int sum = 0;
        for (int i = 0; i < 127; i++) {
            sum += e[i] & 0xFF;
        }
        e[127] = (byte) ((256 - (sum % 256)) % 256);

        return e;
    }

    /**
     * Writes an EDID display descriptor of the given type (0xFC name, 0xFF serial, 0xFE text) with
     * up to 13 ASCII chars, 0x0A-terminated and 0x20-padded per the EDID spec.
     */
    private static void writeTextDescriptor(byte[] e, int off, int type, String text) {
        e[off] = 0x00;
        e[off + 1] = 0x00;
        e[off + 2] = 0x00;
        e[off + 3] = (byte) type;
        e[off + 4] = 0x00;
        byte[] t = (text == null ? "" : text).getBytes(StandardCharsets.US_ASCII);
        int n = Math.min(13, t.length);
        for (int i = 0; i < n; i++) {
            e[off + 5 + i] = t[i];
        }
        if (n < 13) {
            e[off + 5 + n] = 0x0A;
            for (int i = n + 1; i < 13; i++) {
                e[off + 5 + i] = 0x20;
            }
        }
    }

    /**
     * Packs a 3-letter manufacturer code (e.g. "APP") into the 15-bit EDID representation.
     * Returns 0 when the id is not exactly three A-Z letters (common for internal panels that
     * expose an OUI-style ManufacturerID such as "00-10-fa" instead).
     */
    private static int encodePnpId(String id) {
        if (id == null) {
            return 0;
        }
        String s = id.trim().toUpperCase();
        if (s.length() != 3) {
            return 0;
        }
        int v = 0;
        for (int i = 0; i < 3; i++) {
            int c = s.charAt(i) - 'A' + 1;
            if (c < 1 || c > 26) {
                return 0;
            }
            v = (v << 5) | c;
        }
        return v & 0x7FFF; // bit 15 must be 0
    }
}

Activity

  1. dbwiddis commented on Jun 18, 2026

    @dbwiddis
    Member

    Thanks for the report! Funny thing, while I use an M2 (personal) and M3 (work) I'm almost always docked and never noticed the lack of the retina display.

    I'm ok with a synthesized EDID in principle (we do something similar for CPUID on non-root Linux) but that comes with some baggage (we spend a lot of time encoding it just to decode it later; there's no signal to the user that it's fake).

    I'm thinking we have three options:

    1. Expose a "raw" vs. "synthetic" boolean (or enum) on the API. Not my favorite but a minimal requirement. I don't like this.
    2. Expose the synthetic bit in one of the spare descriptor slots you're not otherwise using (you have bytes 54-71 and 72-89 for name and serial, you could use one of the next two slots) and document it (probably the easiest approach without changing API, I'd be ok with this.). And add an "isEdidSynthetic" helper on EdidUtil to parse whatever magic number (probably text like SYNTHETICEDID, but bytes are numbers!) we put in that descriptor. Better than option 1, and easier, but I'd prefer option 3 below.
    3. Create a new class that takes either an EDID or a list of fields as its constructor. For all the other implementations, initialize the class with the edid and lazily populate the fields with EdidUtil when it's asked for. For the Retina Display, use the constructor with fields, and just leave EDID blank/empty array (probably breaks downstream users, don't like), or an array of 128 zeroes (invalid parsing, probably breaks downstream users, don't like), or synthesize it lazily (doesn't get around the encode-to-decode waste, but it's not that big a deal and it keeps compatibility), keeping that "isSynthetic" helper signal.

    Generally speaking:

    • don't touch existing code (it looks like you're doing the framebuffer walk for existing displays where we already have the EDID. We should only use this for displays we don't already have.
    • the code should mostly live in EdidUtil
    • you'll need to do an FFM port for parity
    • lots of improvements you can make in your code, but let's get to the PR stage first. :)
  2. added
    new feature
    PR welcome
    compatibility
    on Jun 18, 2026
  3. dbwiddis commented on Jun 27, 2026

    @dbwiddis
    Member

    Thanks again for the detailed report and the prototype. It gave a clear target to develop an API for this, and I've now added the groundwork so it can be done cleanly against a real API instead of hand-rolling EDID bytes. I also dug into the IORegistry side to reduce the guesswork.

    The enabling work is merged

    The enabling PR #3415 is merged. It adds a small public API for exactly this case:

    • Display.getDisplayInfo() returns a new DisplayInfo interface (manufacturer ID, product ID, serial, week/year, version, digital flag, size in cm, preferred resolution, model, product serial), and Display.isEdidSynthetic() tells callers whether the EDID was reported by the display or synthesized.
    • EdidUtil gained the inverse of its existing parsers: newEdidTemplate(), setManufacturerID/setProductID/setSerialNo/setWeek/setYear/setVersion/setDigital/setHcm/setVcm/setPreferredResolution/setModel, setProductSerialNumber, generic setDescriptor/setDescriptorText for all four descriptor slots, and updateChecksum().

    So the synthesis path is now: populate a byte[] with EdidUtil, build a DisplayInfo, and mark it synthetic. The result re-parses through EdidUtil like any real EDID.

    Enumeration: match the base class, not a hardcoded subclass

    Your prototype looks up IOMobileFramebufferShim/AppleCLCD2 by name. That works, but the leaf class name drifts across macOS versions, and it turns out the premise that service matching "returns nothing" is not the case. On my M2 Max (macOS 26):

    • IOServiceMatching("IOMobileFramebuffer"), the base class, returns every framebuffer node directly. No root tree walk, no hardcoded subclass list.
    • The current leaf class here is IOMobileFramebufferShim, and AppleCLCD2 does not exist on this release at all (the older write-ups all reference AppleCLCD2). Matching the base class covers both.
    • DisplayAttributes sits directly on the framebuffer node, so the recursive property search is not needed.
    • The SoC exposes several framebuffer pipes (5 on this machine, for one display), but only the ones backing a live display carry DisplayAttributes, so checking for that dictionary is also what filters out the idle pipes.

    If anyone can confirm on an older release where the leaf class is AppleCLCD2 that it is still reached by matching the base class, that would be useful; if not, matching both class names is a cheap safety net.

    One enumeration for every display, replacing the Apple Silicon service matching

    Because this finds every display (internal and external both carry DisplayAttributes), on Apple Silicon it can replace the existing IOPortTransportStateDisplayPort path entirely; we just read the EDID from a different source. For each framebuffer node, read a real EDID if the node exposes one and synthesize from DisplayAttributes otherwise. Keep the Intel IODisplayConnect path as it is: it returns nothing on Apple Silicon, and IOMobileFramebuffer returns nothing on Intel, so the two coexist safely.

    I'm traveling without an external monitor for a bit, so I can't verify the external case myself. The rule there: if an external node exposes a real EDID, use it; if it only exposes DisplayAttributes, it will be synthesized and flagged through isEdidSynthetic(). Reading the true external EDID reliably can require the private IOAVServiceCopyEDID (external displays are DCPAVServiceProxy nodes and the IODisplayEDID/EDID property is frequently absent, especially over HDMI), so if the framebuffer property turns out to be missing in practice, fully faithful external EDID is a later refinement.

    Mapping DisplayAttributes to EDID fields

    ProductAttributes is sparse and a couple of fields need translating. Real example from my built-in panel:

    ProductAttributes = { "ManufacturerID"="00-10-fa", "LegacyManufacturerID"=1552, "ProductID"=53000704963649 }
    
    • Manufacturer ID: decode LegacyManufacturerID, a packed 16-bit value, as the standard EDID three 5-bit letters. 1552 decodes to "APP" (Apple). setManufacturerID requires exactly three A to Z letters, so the OUI-style "00-10-fa" string is the wrong source; use the decoded LegacyManufacturerID.
    • Product ID: setProductID takes an unsigned 16-bit hex value (0 to FFFF) and rejects anything larger. The reported value here is 53000704963649, so mask to 16 bits: & 0xFFFF gives 0x3441.
    • Sparse fields: name, serial, week, and year are often absent (as above). Pass what is present, default the rest, and rely on isEdidSynthetic() to signal it is partial. Preferred resolution and physical size are not in ProductAttributes; CoreGraphics (CGDisplayPixelsWide/High, CGDisplayScreenSize of the display) is a reasonable source for those.

    Sample

    This is a sketch against the new API, converted from a unified-enumeration approach. I've exercised the IOKit enumeration and the field decode on my M2, but not the full path against real external displays, so treat it as a starting point rather than finished code:

    // Apple Silicon: one enumeration for every display, replacing the old
    // IOPortTransportStateDisplayPort path. Match the STABLE base class
    // IOMobileFramebuffer (the leaf class name varies by macOS version:
    // IOMobileFramebufferShim on current releases, AppleCLCD2 on older ones).
    // Each SoC exposes several framebuffer pipes; only the ones backing a live
    // display carry a DisplayAttributes dictionary, so that check also filters
    // out the idle pipes.
    private static List<Display> getAppleSiliconDisplays() {
        List<Display> displays = new ArrayList<>();
        IOIterator iter = IOKitUtil.getMatchingServices("IOMobileFramebuffer");
        if (iter == null) {
            return displays;
        }
        CFStringRef cfEdid = CFStringRef.createCFString("EDID");
        CFStringRef cfAttrs = CFStringRef.createCFString("DisplayAttributes");
        try {
            for (IORegistryEntry fb = iter.next(); fb != null; fb = iter.next()) {
                try {
                    // 1. Prefer a real EDID when the node exposes one.
                    CFTypeRef edid = fb.createCFProperty(cfEdid);
                    if (edid != null) {
                        CFDataRef data = new CFDataRef(edid.getPointer());
                        displays.add(new MacDisplayJNA(data.getBytePtr().getByteArray(0, data.getLength())));
                        edid.release();
                        continue;
                    }
                    // 2. Otherwise read DisplayAttributes, on the node or (fallback)
                    //    on its parent in the IODeviceTree plane, and synthesize.
                    CFTypeRef attrs = fb.createCFProperty(cfAttrs);
                    if (attrs == null) {
                        IORegistryEntry parent = fb.getParentEntry("IODeviceTree");
                        if (parent != null) {
                            attrs = parent.createCFProperty(cfAttrs);
                            parent.release();
                        }
                    }
                    if (attrs != null) {
                        DisplayInfo info = synthesize(new CFDictionaryRef(attrs.getPointer()));
                        attrs.release();
                        if (info != null) {
                            displays.add(new MacDisplayJNA(info)); // add a MacDisplayJNA(DisplayInfo) ctor -> super(info)
                        }
                    }
                } finally {
                    fb.release();
                }
            }
        } finally {
            iter.release();
            cfEdid.release();
            cfAttrs.release();
        }
        return displays;
    }
    
    // Map ProductAttributes onto a synthetic DisplayInfo using the new oshi.hardware API.
    private static DisplayInfo synthesize(CFDictionaryRef attrs) {
        CFDictionaryRef p = cfDictGetDictionary(attrs, "ProductAttributes");
        if (p == null) {
            return null;
        }
        // LegacyManufacturerID is a packed 16-bit value; decode to three EDID letters (1552 -> "APP").
        String manufacturer = decodeManufacturer(cfDictGetLong(p, "LegacyManufacturerID", 0));
        if (manufacturer == null) {
            return null; // not three A-Z letters; nothing usable to synthesize
        }
        // EDID product code is 16-bit; the reported value can be far larger, so mask it.
        String product = Integer.toHexString((int) (cfDictGetLong(p, "ProductID", 0) & 0xFFFF));
        int week = (int) cfDictGetLong(p, "WeekOfManufacture", 0);
        int year = (int) cfDictGetLong(p, "YearOfManufacture", 1990);
        String model = cfDictGetString(p, "ProductName", "");                  // often absent on the built-in
        String serialDescriptor = cfDictGetString(p, "AlphanumericSerialNumber", "");
        String resolution = mainDisplayResolution();  // from CoreGraphics, e.g. "3456x2234"
    
        // Bytes 12-15 (numeric serial): the built-in panel reports 0. An arbitrary numeric
        // serial does not always round-trip through the string-based setSerialNo, so use
        // zeros here and carry the human-readable serial in the descriptor above.
        return new DisplayInfoImpl(manufacturer, product, "00000000", (byte) week, year, "1.4",
                true, 0, 0, resolution, model, serialDescriptor);
    }
    
    // Inverse of EdidUtil.getManufacturerID: three 5-bit letters (1=A .. 26=Z) packed into 15 bits.
    private static String decodeManufacturer(long packed) {
        int v = (int) packed;
        int[] codes = { (v >> 10) & 0x1F, (v >> 5) & 0x1F, v & 0x1F };
        StringBuilder sb = new StringBuilder(3);
        for (int code : codes) {
            if (code < 1 || code > 26) {
                return null;
            }
            sb.append((char) ('A' - 1 + code));
        }
        return sb.toString();
    }

    That reuses the cfDictGetDictionary/cfDictGetLong/cfDictGetString helpers from your prototype (with a default-value argument), needs a MacDisplayJNA(DisplayInfo) constructor that calls super(info), and a small mainDisplayResolution() helper over CoreGraphics. DisplayInfoImpl is the concrete implementation of the new DisplayInfo interface.

    I'm traveling and can't get to this for at least a week or so. As the original reporter you're probably best positioned to submit a PR to close this out. A PR with JNA (oshi-core) and FFM (oshi-core-ffm) parity against the new API would be great.

    For reference, the IORegistry mechanics are well documented by the Asahi Linux display-controller reverse-engineering, Alin Panaitiu's (Lunar) "Decoding monitor EDID on macOS" notes, and the BetterDisplay/MonitorControl source; the EDID field encoding is the VESA E-EDID spec.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    PR welcomecompatibilitynew feature

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions