Tk Source Code

Attachment Details
Login
Overview

Artifact ID: b46e855766f84ff474420e15e32c86c2fe3590474780204b117a8585ef232cf7
Ticket: 4af5ca1921122de63f37a99beefb2f5dbef72518
Date: 2026-05-19 19:35:31
User: anonymous
Artifact Attached: 63eee63d818f2ff209d61d1b6713c45cef1b4dc393d7f2159feb3aa89ce81518
Filename:pix.c
Description:
Content:
#include <tcl.h>
#include <tk.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include <stdio.h>

#ifndef TCL_SIZE_MAX
    #include <limits.h>
    typedef int Tcl_Size;
    # define Tcl_GetSizeIntFromObj Tcl_GetIntFromObj
    # define Tcl_NewSizeIntObj Tcl_NewIntObj
    # define TCL_SIZE_MAX      INT_MAX
    # define TCL_SIZE_MODIFIER ""
#endif

// gcc -shared -o lib9pix.dylib  -fPIC pix.c -I/usr/local/Cellar/tcl-tk/9.0.3/include/tcl-tk    -L/usr/local/Cellar/tcl-tk/9.0.3/lib    -DUSE_TCL_STUBS -DUSE_TK_STUBS -DMAC_OSX_TK=1 -ltclstub -ltkstub
// gcc -shared -o lib86pix.dylib -fPIC pix.c -I/usr/local/Cellar/tcl-tk@8/8.6.16/include/tcl-tk -L/usr/local/Cellar/tcl-tk@8/8.6.16/lib -DUSE_TCL_STUBS -DUSE_TK_STUBS -DMAC_OSX_TK=1 -ltclstub -ltkstub

// ---------------------------------------------------------
// 1. Data structures
// ---------------------------------------------------------

typedef struct PixImageInstance PixImageInstance;

// Equivalent to pixie.Image (RGBA flat buffer)
typedef struct {
    unsigned char *data;   // RGBA pixels, size = width * height * 4
    int            width;
    int            height;
} PixieImage;

typedef struct PixImageMaster {
    char* imageKey;
    PixieImage* image;          // Formerly void*, typed for RGBA→BGRA conversion
    int            width;
    int            height;
    char* name;
    Tcl_Interp* interp;
    Tk_ImageModel  tkMaster;
    bool           needUpdate;
    PixImageInstance* instances;
} PixImageMaster;

struct PixImageInstance {
    PixImageMaster* master;
    char* displayName;
    Tk_Window tkwin;
    int refCount;
    GC gc;
    Pixmap pixmap;
    void* convertedBuffer;
    int bufferWidth;
    int bufferHeight;
    PixImageInstance* nextInstance;
};

// ---------------------------------------------------------
// 2. Creation Functions (The ones you want to debug)
// ---------------------------------------------------------

static int pix_createProc(
    Tcl_Interp          *interp,
    const char          *imageName,
    Tcl_Size             objc,
    Tcl_Obj *const       objv[],
    const Tk_ImageType  *typePtr,
    Tk_ImageModel        masterPtr,
    void               **clientDataPtr
) {
    if (objc > 0) {
        if (objc != 2 || strcmp(Tcl_GetString(objv[0]), "-data") != 0) {
            Tcl_SetObjResult(interp, Tcl_NewStringObj("Usage: image create pix ?name? ?-data key?", -1));
            return TCL_ERROR;
        }
    }

    PixImageMaster *master = (PixImageMaster *)calloc(1, sizeof(PixImageMaster));
    if (master == NULL) return TCL_ERROR;

    if (objc == 2) {
        master->imageKey = strdup(Tcl_GetString(objv[1]));
    } else {
        master->imageKey = strdup("");
    }

    master->image = NULL;
    master->width = 100;  // Default value for the demo
    master->height = 100; // Default value for the demo
    master->name = strdup(imageName);
    master->interp = interp;
    master->tkMaster = masterPtr;
    master->needUpdate = false;
    master->instances = NULL;

    *clientDataPtr = (void *)master;

    return TCL_OK;
}

static void *pix_getProc(Tk_Window tkwin, void *masterData) {
    PixImageMaster *master = (PixImageMaster *)masterData;
    const char* displayName = Tk_DisplayName(tkwin);

    PixImageInstance *inst = master->instances;
    while (inst != NULL) {
        if (strcmp(inst->displayName, displayName) == 0) {
            inst->refCount++;
            return (void *)inst;
        }
        inst = inst->nextInstance;
    }

    PixImageInstance *instance = (PixImageInstance *)calloc(1, sizeof(PixImageInstance));
    if (instance == NULL) Tcl_Panic("pix(error): allocation error");

    instance->master = master;
    instance->tkwin = tkwin;
    instance->displayName = strdup(displayName);
    instance->refCount = 1;
    instance->pixmap = None;

    XGCValues gcValues;
    gcValues.graphics_exposures = False;
    instance->gc = Tk_GetGC(tkwin, GCGraphicsExposures, &gcValues);

    instance->nextInstance = master->instances;
    master->instances = instance;

    return (void *)instance;
}

// ---------------------------------------------------------
// 3. RGBA → BGRA conversion + backing-store pixmap management
// ---------------------------------------------------------

static void updateInstanceBuffer(PixImageInstance *inst, Display *display) {
    PixImageMaster *master = inst->master;

    if (!master->image || !master->image->data) return;

    int newWidth   = master->width;
    int newHeight  = master->height;
    int pixelCount = newWidth * newHeight;
    int bufferSize = pixelCount * 4;

    // Conditional reallocation (only if size changes)
    if (newWidth != inst->bufferWidth || newHeight != inst->bufferHeight) {
        if (inst->convertedBuffer) free(inst->convertedBuffer);

        inst->convertedBuffer = malloc(bufferSize);
        inst->bufferWidth     = newWidth;
        inst->bufferHeight    = newHeight;

        // The existing pixmap is invalid for the new size
        if (inst->pixmap != None) {
            Tk_FreePixmap(display, inst->pixmap);
            inst->pixmap = None;
        }
    }

    // RGBA → BGRA conversion (swap R and B channels)
    unsigned int *src = (unsigned int *)master->image->data;
    unsigned int *dst = (unsigned int *)inst->convertedBuffer;

    for (int i = 0; i < pixelCount; i++) {
        unsigned int rgba = src[i];
        dst[i] = (rgba & 0xFF00FF00u)
               | ((rgba & 0x000000FFu) << 16)
               | ((rgba & 0x00FF0000u) >> 16);
    }
}

// ---------------------------------------------------------
// 4. displayProc — rendering via backing-store (pixmap)
// ---------------------------------------------------------

static void pix_displayProc(
    void      *instanceData,
    Display   *display,
    Drawable   drawable,
    int        imageX,   int imageY,
    int        width,    int height,
    int        drawableX, int drawableY)
{
    PixImageInstance *inst   = (PixImageInstance *)instanceData;
    PixImageMaster   *master = inst->master;

    // Guards: missing master, missing image or empty key → nothing to display
    if (!master || !master->image || master->imageKey[0] == '\0') return;

    int needsUpdate = master->needUpdate || inst->pixmap == None;

    if (needsUpdate) {
        // 1. RGBA→BGRA conversion if the master signaled a change
        if (master->needUpdate) {
            updateInstanceBuffer(inst, display);
            master->needUpdate = false;   // reset centralized flag
        }

        // 2. Lazy creation of the pixmap (backing-store)
        if (inst->pixmap == None) {
            inst->pixmap = Tk_GetPixmap(
                display, drawable,
                inst->bufferWidth, inst->bufferHeight,
                Tk_Depth(inst->tkwin)
            );
        }

        // 3. Upload BGRA buffer to pixmap via temporary XImage
        if (inst->pixmap != None && inst->convertedBuffer) {
            XImage *ximage = XCreateImage(
                display,
                Tk_Visual(inst->tkwin),
                (unsigned)Tk_Depth(inst->tkwin),
                ZPixmap,
                0,
                (char *)inst->convertedBuffer,
                (unsigned)inst->bufferWidth,
                (unsigned)inst->bufferHeight,
                32,
                inst->bufferWidth * 4
            );

            if (ximage) {
                XPutImage(display, inst->pixmap, inst->gc, ximage,
                          0, 0, 0, 0,
                          (unsigned)inst->bufferWidth,
                          (unsigned)inst->bufferHeight);
                ximage->data = NULL;   // avoid double-free in XDestroyImage
                XDestroyImage(ximage);
            }
        }
    }

    // 4. Fast blit from backing-store to Tk drawable
    if (inst->pixmap != None) {
        fprintf(stderr, "[DEBUG] ---> pix_displayProc\n"); fflush(stderr);
        XCopyArea(display, inst->pixmap, drawable, inst->gc,
                  imageX, imageY,
                  (unsigned)width, (unsigned)height,
                  drawableX, drawableY);
        XFlush(display);
    }
}

static void pix_freeProc(void *instanceData, Display *display) {
    PixImageInstance *inst = (PixImageInstance *)instanceData;
    if (!inst) return;
    
    inst->refCount--;
    if (inst->refCount > 0) return;

    if (inst->displayName) free(inst->displayName);
    // GC freeing omitted to simplify the demo
    free(inst);
}

static void pix_deleteProc(void *masterData) {
    PixImageMaster *master = (PixImageMaster *)masterData;
    if (!master) return;

    if (master->imageKey) free(master->imageKey);
    if (master->name) free(master->name);
    free(master);
}

// ---------------------------------------------------------
// 4. draw_pix_surface — Tcl command
//
// Usage from Tcl:
//   pix::drawPixSurface <pixPhotoName> <width> <height>
//
// Without ptable (demo): provides a test RGBA image if none
// is attached to the master yet, otherwise reuses the existing one.
// ---------------------------------------------------------

static PixieImage *
makeTestImage(int w, int h)
{
    PixieImage *img = (PixieImage *)malloc(sizeof(PixieImage));
    if (!img) return NULL;

    img->width  = w;
    img->height = h;
    img->data   = (unsigned char *)malloc(w * h * 4);
    if (!img->data) { free(img); return NULL; }

    /* Red→blue gradient to visually check RGBA→BGRA conversion */
    for (int y = 0; y < h; y++) {
        for (int x = 0; x < w; x++) {
            int i = (y * w + x) * 4;
            img->data[i + 0] = (unsigned char)(255 * x / (w - 1)); /* R */
            img->data[i + 1] = 80;                                  /* G */
            img->data[i + 2] = (unsigned char)(255 * y / (h - 1)); /* B */
            img->data[i + 3] = 255;                                 /* A */
        }
    }
    return img;
}

int
draw_pix_surface(
    void          *clientData,
    Tcl_Interp    *interp,
    Tcl_Size       objc,
    Tcl_Obj *const objv[])
{
    const char          *pixPhotoName;
    const Tk_ImageType  *dummyImgType = NULL;
    PixImageMaster      *master;
    int             w = 100, h = 100;

    if (objc < 2 || objc > 4) {
        Tcl_WrongNumArgs(interp, 1, objv,
            "<pixPhoto> ?width? ?height?");
        return TCL_ERROR;
    }

    pixPhotoName = Tcl_GetString(objv[1]);

    /* Optional dimensions */
    if (objc >= 3 && Tcl_GetIntFromObj(interp, objv[2], &w) != TCL_OK)
        return TCL_ERROR;
    if (objc == 4 && Tcl_GetIntFromObj(interp, objv[3], &h) != TCL_OK)
        return TCL_ERROR;

    master = (PixImageMaster *)Tk_GetImageModelData(
        interp, pixPhotoName, &dummyImgType);

    if (!master) {
        Tcl_SetObjResult(interp,
            Tcl_NewStringObj("pix(error): Unknown pix photo", -1));
        return TCL_ERROR;
    }

    /*
     * Without ptable: creating a test image if the master does not have one.
     * In the real Nim code, this is where ptable.getImage(key) is called.
     */
    if (!master->image) {
        PixieImage *img = makeTestImage(w, h);
        if (!img) {
            Tcl_SetObjResult(interp,
                Tcl_NewStringObj("pix(error): image allocation failed", -1));
            return TCL_ERROR;
        }
        master->image  = img;
        master->width  = img->width;
        master->height = img->height;
        /* imageKey acts as a guard in displayProc — we populate it.
         * master->imageKey is a char* (strdup): we replace it properly. */
        free(master->imageKey);
        master->imageKey = strdup(pixPhotoName);
        if (!master->imageKey) {
            Tcl_SetObjResult(interp,
                Tcl_NewStringObj("pix(error): imageKey allocation failed", -1));
            return TCL_ERROR;
        }
    }

    /* Triggering refresh */
    master->needUpdate = true;

    Tk_ImageChanged(master->tkMaster,
                    0, 0,
                    master->width, master->height,
                    master->width, master->height);
    return TCL_OK;
}

// ---------------------------------------------------------
// 5. Tk Image Type Declaration
// ---------------------------------------------------------

static Tk_ImageType pixImageType = {
    "pix",             // name
    pix_createProc,    // createProc
    pix_getProc,       // getProc
    pix_displayProc,   // displayProc
    pix_freeProc,      // freeProc
    pix_deleteProc,    // deleteProc
    NULL,              // postscriptProc
    NULL,              // nextPtr
    NULL               // reserved
};

// ---------------------------------------------------------
// 5. Library Initialization (Entry Point)
// ---------------------------------------------------------

#ifdef __cplusplus
extern "C" {
#endif
DLLEXPORT int Pix_Init(Tcl_Interp *interp) {

    if (Tcl_InitStubs(interp, "8.6-", 0) == NULL) {
        return TCL_ERROR;
    }

    if (Tk_InitStubs(interp, "8.6-", 0) == NULL) {
        return TCL_ERROR;
    }

    Tk_CreateImageType(&pixImageType);

    if (Tcl_CreateObjCommand(interp, "pix::drawPixSurface",
            (Tcl_ObjCmdProc *)draw_pix_surface,
            NULL, NULL) == NULL) {
        return TCL_ERROR;
    }

    return TCL_OK;
}
#ifdef __cplusplus
}
#endif