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:
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
   100
   101
   102
   103
   104
   105
   106
   107
   108
   109
   110
   111
   112
   113
   114
   115
   116
   117
   118
   119
   120
   121
   122
   123
   124
   125
   126
   127
   128
   129
   130
   131
   132
   133
   134
   135
   136
   137
   138
   139
   140
   141
   142
   143
   144
   145
   146
   147
   148
   149
   150
   151
   152
   153
   154
   155
   156
   157
   158
   159
   160
   161
   162
   163
   164
   165
   166
   167
   168
   169
   170
   171
   172
   173
   174
   175
   176
   177
   178
   179
   180
   181
   182
   183
   184
   185
   186
   187
   188
   189
   190
   191
   192
   193
   194
   195
   196
   197
   198
   199
   200
   201
   202
   203
   204
   205
   206
   207
   208
   209
   210
   211
   212
   213
   214
   215
   216
   217
   218
   219
   220
   221
   222
   223
   224
   225
   226
   227
   228
   229
   230
   231
   232
   233
   234
   235
   236
   237
   238
   239
   240
   241
   242
   243
   244
   245
   246
   247
   248
   249
   250
   251
   252
   253
   254
   255
   256
   257
   258
   259
   260
   261
   262
   263
   264
   265
   266
   267
   268
   269
   270
   271
   272
   273
   274
   275
   276
   277
   278
   279
   280
   281
   282
   283
   284
   285
   286
   287
   288
   289
   290
   291
   292
   293
   294
   295
   296
   297
   298
   299
   300
   301
   302
   303
   304
   305
   306
   307
   308
   309
   310
   311
   312
   313
   314
   315
   316
   317
   318
   319
   320
   321
   322
   323
   324
   325
   326
   327
   328
   329
   330
   331
   332
   333
   334
   335
   336
   337
   338
   339
   340
   341
   342
   343
   344
   345
   346
   347
   348
   349
   350
   351
   352
   353
   354
   355
   356
   357
   358
   359
   360
   361
   362
   363
   364
   365
   366
   367
   368
   369
   370
   371
   372
   373
   374
   375
   376
   377
   378
   379
   380
   381
   382
   383
   384
   385
   386
   387
   388
   389
   390
   391
   392
   393
   394
   395
   396
   397
   398
   399
   400
   401
   402
   403
   404
   405
   406
   407
   408
   409
   410
   411
   412
   413
   414
   415
   416
   417
#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