File: gdiplus.cpp

package info (click to toggle)
mlterm 3.9.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye
  • size: 24,124 kB
  • sloc: ansic: 137,946; sh: 4,421; cpp: 2,929; objc: 2,683; makefile: 2,404; java: 2,171; perl: 1,201; xml: 45
file content (400 lines) | stat: -rw-r--r-- 10,009 bytes parent folder | download | duplicates (2)
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
/* -*- c-basic-offset:2; tab-width:2; indent-tabs-mode:nil -*- */

#include <stdio.h>
#include <unistd.h> /* STDOUT_FILENO */
#include <stdlib.h> /* mbstowcs_s */
#include <wchar.h>  /* wcslen */

extern "C" {
#include <pobl/bl_debug.h>
#include <pobl/bl_conf_io.h> /* bl_get_user_rc_path */
#include <pobl/bl_mem.h>
#if defined(__CYGWIN__) || defined(__MSYS__)
#include <pobl/bl_path.h> /* bl_conv_to_win32_path */
#endif
}

#include <pobl/bl_types.h> /* u_int32_t/u_int16_t */
#include <pobl/bl_def.h>   /* SSIZE_MAX, USE_WIN32API */

#ifdef USE_WIN32API
#include <fcntl.h> /* O_BINARY */
#endif

#define _WIN32_WINNT 0x0502 /* for SetDllDirectory */
#include <windows.h>
#include <gdiplus.h>

using namespace Gdiplus;

#if 0
#define __DEBUG
#endif

#ifndef IID_PPV_ARGS
/* IStream IID (objidl.h) */
static const IID __uuid_inst = {
    0x0000000c, 0x0000, 0x0000, {0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}};
#define IID_PPV_ARGS(iface) __uuid_inst, reinterpret_cast<void**>(iface)
#endif

#ifndef URL_MK_UNIFORM
#define URL_MK_UNIFORM 1
#endif

/* --- static functions --- */

#define BUILTIN_IMAGELIB /* Necessary to use create_cardinals_from_sixel() */
#include "../../common/c_imagelib.c"

static void help(void) {
  /* Don't output to stdout where mlterm waits for image data. */
  fprintf(stderr, "mlimgloader 0 [width] [height] [file path] stdout (-a)\n");
  fprintf(stderr, "  -a: keep aspect ratio.\n");
}

/* path: cygwin style path on cygwin/msys. win32 style path on win32. */
static u_int32_t *create_cardinals_from_file(const char *path, u_int width, u_int height,
                                             int keep_aspect) {
  u_int32_t *cardinal = NULL;

  if (strcasecmp(path + strlen(path) - 4, ".six") == 0 &&
      (cardinal = create_cardinals_from_sixel(path)) &&
      (width == 0 || height == 0)) {
    return cardinal;
  }

  Gdiplus::GdiplusStartupInput startup;
  ULONG_PTR token;

  if (Gdiplus::GdiplusStartup(&token, &startup, NULL) != Gdiplus::Ok) {
    return NULL;
  }

  /* MAX_PATH which is 260 (3+255+1+1) is defined in win32 alone. */
  wchar_t wpath[MAX_PATH];
#if defined(__CYGWIN__) || defined(__MSYS__)
  char winpath[MAX_PATH];
#endif
  HMODULE module;
  IBindCtx *ctx;
  IMoniker *moniker;
  IStream *stream = NULL;
  Gdiplus::Bitmap *bitmap;

  if (cardinal) {
    /* Resize sixel graphics */
    Gdiplus::Bitmap src(cardinal[0], cardinal[1], cardinal[0] * 4,
                        PixelFormat32bppARGB, (BYTE*)(cardinal + 2));
    if (!(bitmap = new Bitmap(width, height, PixelFormat32bppARGB))) {
      goto end1;
    }

    Graphics *graphics;
    if (!(graphics = Graphics::FromImage(bitmap))) {
      delete bitmap;

      goto end1;
    }

    Gdiplus::Rect rect(0, 0, width, height);
    graphics->DrawImage(&src, rect, 0, 0, cardinal[0], cardinal[1], UnitPixel);

    delete graphics;
    free(cardinal);
  } else {
    /* Image except sixel graphics */
    int hash = hash_path(path);

    if (strstr(path, "://")) {
      typedef HRESULT (*func)(IMoniker*, LPCWSTR, IMoniker**, DWORD);
      func create_url_moniker;

      SetDllDirectory("");
      if ((module = LoadLibrary("urlmon")) &&
          (create_url_moniker = (func)GetProcAddress(module, "CreateURLMonikerEx"))) {
        MultiByteToWideChar(CP_UTF8, 0, path, strlen(path) + 1, wpath, MAX_PATH);

        if ((*create_url_moniker)(NULL, wpath, &moniker, URL_MK_UNIFORM) == S_OK) {
          if (CreateBindCtx(0, &ctx) == S_OK) {
            if (moniker->BindToStorage(ctx, NULL, IID_PPV_ARGS(&stream)) != S_OK) {
              ctx->Release();
              moniker->Release();
            }
          } else {
            moniker->Release();
          }
        }

        if (!stream) {
          FreeLibrary(module);
        }
      }
    }
#if defined(__CYGWIN__) || defined(__MSYS__)
    /* In case win32 style path is specified on cygwin/msys. */
    else if (strchr(path, '/')) {
      /* cygwin style path => win32 style path. */
      if (bl_conv_to_win32_path(path, winpath, sizeof(winpath)) == 0) {
        path = winpath;
      }
    }
#endif

    char *dir;
    if (strcmp(path + strlen(path) - 4, ".gif") == 0 && /* Animation GIF */
#if defined(__CYGWIN__) || defined(__MSYS__)
      /* converted to win32 by bl_conv_to_win32_path */
        (!strstr(path, "mlterm\\anim") && (dir = bl_get_user_rc_path("mlterm/")))
#else
        (!strstr(path, "mlterm/anim") && (dir = bl_get_user_rc_path("mlterm\\")))
#endif
        ) {
      char new_path[strlen(dir) + 8 + 5 + DIGIT_STR_LEN(int) + 1];

      sprintf(new_path, "%sanim%d.gif", dir, hash);

      FILE *fp;
      if (stream && (fp = fopen(new_path, "wb"))) {
        BYTE buf[10240];
        ULONG rd_len;
        HRESULT res;

        do {
          res = stream->Read(buf, sizeof(buf), &rd_len);
          fwrite(buf, 1, rd_len, fp);
        } while (res == Gdiplus::Ok);

        fclose(fp);

        stream->Release();
        ctx->Release();
        moniker->Release();
        FreeLibrary(module);
        stream = NULL;

        path = new_path;
      }

      split_animation_gif(path, dir, hash);
      free(dir);

      /* Replace path by the split file. */
#if defined(__CYGWIN__) || defined(__MSYS__)
      if (bl_conv_to_win32_path(new_path, winpath, sizeof(winpath)) == 0) {
        path = winpath;
      } else
#endif
      {
        path = new_path;
      }

      if (!stream) {
        MultiByteToWideChar(CP_UTF8, 0, path, strlen(path) + 1, wpath, MAX_PATH);
      }
    } else {
      if (!stream) {
        MultiByteToWideChar(CP_UTF8, 0, path, strlen(path) + 1, wpath, MAX_PATH);
      }
    }

    cardinal = NULL;

    if (width == 0 && height == 0) {
      if (stream ? !(bitmap = Gdiplus::Bitmap::FromStream(stream))
          : !(bitmap = Gdiplus::Bitmap::FromFile(wpath))) {
        goto end2;
      }
    } else {
      Image *image;

      if ((stream ? !(image = Image::FromStream(stream)) : !(image = Image::FromFile(wpath))) ||
          image->GetLastStatus() != Gdiplus::Ok) {
        goto end2;
      }

      u_int img_width = image->GetWidth();
      u_int img_height = image->GetHeight();

      if (width == 0) {
        width = img_width;;
      } else if (height == 0) {
        height = img_height;
      }

      if (keep_aspect) {
        u_int w = height * img_width / img_height;

        if (w < width) {
          width = w;
        } else {
          u_int h = width * img_height / img_width;

          if (h < height) {
            height = h;
          }
        }
      }

      if (!(bitmap = new Bitmap(width, height, PixelFormat32bppARGB))) {
        delete image;

        goto end2;
      }

      Graphics *graphics;
      if (!(graphics = Graphics::FromImage(bitmap))) {
        delete image;

        goto end3;
      }

      Gdiplus::Rect rect(0, 0, width, height);

      graphics->DrawImage(image, rect, 0, 0, img_width, img_height, UnitPixel);

      delete image;
      delete graphics;
    }
  }

  if (bitmap->GetLastStatus() != Gdiplus::Ok) {
    goto end3;
  }

  width = bitmap->GetWidth();
  height = bitmap->GetHeight();

  u_int32_t *p;
  if (width > ((SSIZE_MAX / sizeof(*cardinal)) - 2) / height || /* integer overflow */
      !(p = cardinal = (u_int32_t*)malloc((width * height + 2) * sizeof(*cardinal)))) {
    goto end3;
  }

  *(p++) = width;
  *(p++) = height;

  for (int y = 0; y < height; y++) {
    for (int x = 0; x < width; x++) {
      Gdiplus::Color pixel;

      bitmap->GetPixel(x, y, &pixel);

      *(p++) = (pixel.GetA() << 24) | (pixel.GetR() << 16) | (pixel.GetG() << 8) | pixel.GetB();
    }
  }

end3:
  delete bitmap;

end2:
  if (stream) {
    stream->Release();
    ctx->Release();
    moniker->Release();
    FreeLibrary(module);
  }

end1:
  Gdiplus::GdiplusShutdown(token);

  return cardinal;
}

/* --- global functions --- */

int PASCAL WinMain(HINSTANCE hinst, HINSTANCE hprev, char *cmdline, int cmdshow) {
  WCHAR **w_argv;
  int argc;

#if 0
  bl_set_msg_log_file_name("mlterm/msg.log");
#endif

  w_argv = CommandLineToArgvW(GetCommandLineW(), &argc);
  if (argc == 0) {
    GlobalFree(w_argv);

    return -1;
  }

  char *argv[argc];

  for (int count = 0; count < argc; count++) {
    int len = WideCharToMultiByte(CP_UTF8, 0, w_argv[count], wcslen(w_argv[count]) + 1,
                                  NULL, 0, NULL, NULL);
    if ((argv[count] = (char*)malloc(len))) {
      WideCharToMultiByte(CP_UTF8, 0, w_argv[count], wcslen(w_argv[count]) + 1, argv[count], len,
                          NULL, NULL);
    } else {
      argc = count;
      break;
    }
  }

  GlobalFree(w_argv);

  if ((argc != 6 && argc != 7) || strcmp(argv[5], "stdout") != 0) {
    help();

    return -1;
  }

  char new_path[strlen(argv[4]) + 1];

  if (strstr(argv[4], ".rgs")) {
    strcpy(new_path, argv[4]);
    if (convert_regis_to_bmp(new_path)) {
      argv[4] = new_path;
    }
  }

  u_int width = atoi(argv[2]);
  u_int height = atoi(argv[3]);

  /*
   * attr.width / attr.height aren't trustworthy because this program can be
   * called before window is actually resized.
   */

  u_char *cardinal;
  ssize_t size; /* should declare before 'goto' */
  if (!(cardinal = (u_char*)create_cardinals_from_file(argv[4], width, height,
                                                       (argc == 7 &&
                                                        strcmp(argv[6], "-a") == 0)))) {
    goto error;
  }

  width = ((u_int32_t*)cardinal)[0];
  height = ((u_int32_t*)cardinal)[1];
  size = sizeof(u_int32_t) * (width * height + 2);

#ifdef USE_WIN32API
  setmode(STDOUT_FILENO, O_BINARY);
#endif

  while (size > 0) {
    ssize_t n_wr;

    if ((n_wr = write(STDOUT_FILENO, cardinal, size)) < 0) {
      goto error;
    }

    cardinal += n_wr;
    size -= n_wr;
  }

#ifdef __DEBUG
  bl_debug_printf(BL_DEBUG_TAG " Exit image loader\n");
#endif

  /* XXX should free(argv[n]) */

  return 0;

error:
  /* XXX should free(argv[n]) */
  bl_error_printf("Couldn't load %s\n", argv[4]);

  return -1;
}