DWinProgramming /Samples/Chap18/EmfView/EmfView.d

Language D Lines 504
MD5 Hash e801266c243dfd76f32ca0190f0ba31d
Repository git://github.com/AndrejMitrovic/DWinProgramming.git View Raw File View Project SPDX
  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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
/+
 + Copyright (c) Charles Petzold, 1998.
 + Ported to the D Programming Language by Andrej Mitrovic, 2011.
 +/

module EmfView;

import core.memory;
import core.runtime;
import core.thread;
import std.conv;
import std.math;
import std.range;
import std.string;
import std.utf;

auto toUTF16z(S)(S s)
{
    return toUTFz!(const(wchar)*)(s);
}

pragma(lib, "gdi32.lib");
pragma(lib, "comdlg32.lib");
import win32.windef;
import win32.winuser;
import win32.wingdi;
import win32.winbase;
import win32.commdlg;

import resource;

string appName     = "EmfView";
string description = "Enhanced Metafile Viewer";
HINSTANCE hinst;

extern (Windows)
int WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int iCmdShow)
{
    int result;
    void exceptionHandler(Throwable e) { throw e; }

    try
    {
        Runtime.initialize(&exceptionHandler);
        result = myWinMain(hInstance, hPrevInstance, lpCmdLine, iCmdShow);
        Runtime.terminate(&exceptionHandler);
    }
    catch (Throwable o)
    {
        MessageBox(null, o.toString().toUTF16z, "Error", MB_OK | MB_ICONEXCLAMATION);
        result = 0;
    }

    return result;
}

int myWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int iCmdShow)
{
    hinst = hInstance;
    HACCEL hAccel;
    HWND hwnd;
    MSG  msg;
    WNDCLASS wndclass;

    wndclass.style         = CS_HREDRAW | CS_VREDRAW;
    wndclass.lpfnWndProc   = &WndProc;
    wndclass.cbClsExtra    = 0;
    wndclass.cbWndExtra    = 0;
    wndclass.hInstance     = hInstance;
    wndclass.hIcon         = LoadIcon(NULL, IDI_APPLICATION);
    wndclass.hCursor       = LoadCursor(NULL, IDC_ARROW);
    wndclass.hbrBackground = cast(HBRUSH) GetStockObject(WHITE_BRUSH);
    wndclass.lpszMenuName  = appName.toUTF16z;
    wndclass.lpszClassName = appName.toUTF16z;

    if (!RegisterClass(&wndclass))
    {
        MessageBox(NULL, "This program requires Windows NT!", appName.toUTF16z, MB_ICONERROR);
        return 0;
    }

    hwnd = CreateWindow(appName.toUTF16z,              // window class name
                        description.toUTF16z,          // window caption
                        WS_OVERLAPPEDWINDOW,           // window style
                        CW_USEDEFAULT,                 // initial x position
                        CW_USEDEFAULT,                 // initial y position
                        CW_USEDEFAULT,                 // initial x size
                        CW_USEDEFAULT,                 // initial y size
                        NULL,                          // parent window handle
                        NULL,                          // window menu handle
                        hInstance,                     // program instance handle
                        NULL);                         // creation parameters

    ShowWindow(hwnd, iCmdShow);
    UpdateWindow(hwnd);

    hAccel = LoadAccelerators(hInstance, appName.toUTF16z);

    while (GetMessage(&msg, NULL, 0, 0))
    {
        if (!TranslateAccelerator(hwnd, hAccel, &msg))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
    }

    return msg.wParam;
}

HPALETTE CreatePaletteFromMetaFile(HENHMETAFILE hemf)
{
    HPALETTE hPalette;
    int iNum;
    LOGPALETTE* plp;

    if (!hemf)
        return NULL;

    if (0 == (iNum = GetEnhMetaFilePaletteEntries(hemf, 0, NULL)))
        return NULL;

    plp = cast(typeof(plp))GC.malloc(LOGPALETTE.sizeof + (iNum - 1) * PALETTEENTRY.sizeof);

    plp.palVersion    = 0x0300;
    plp.palNumEntries = cast(ushort)iNum;  // hmm

    GetEnhMetaFilePaletteEntries(hemf, iNum, plp.palPalEntry.ptr);

    hPalette = CreatePalette(plp);

    GC.free(plp);

    return hPalette;
}

__gshared wchar[MAX_PATH] szFileName  = 0;
__gshared wchar[MAX_PATH] szTitleName = 0;

extern (Windows)
LRESULT WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    static DOCINFO di = DOCINFO(DOCINFO.sizeof, "EmfView: Printing");
    static HENHMETAFILE hemf;
    static OPENFILENAME ofn;
    static PRINTDLG printdlg = PRINTDLG(PRINTDLG.sizeof);
    static string szFilter = "Enhanced Metafiles (*.EMF)\0*.emf\0All Files (*.*)\0*.*\0\0";
    BOOL bSuccess;
    ENHMETAHEADER header;
    HDC hdc, hdcPrn;
    HENHMETAFILE hemfCopy;
    HMENU hMenu;
    HPALETTE hPalette;
    int i, iLength, iEnable;
    PAINTSTRUCT ps;
    RECT  rect;
    PTSTR pBuffer;

    switch (message)
    {
        case WM_CREATE:

            // Initialize OPENFILENAME structure
            ofn.hwndOwner         = hwnd;
            ofn.hInstance         = NULL;
            ofn.lpstrFilter       = szFilter.toUTF16z;
            ofn.lpstrCustomFilter = NULL;
            ofn.nMaxCustFilter    = 0;
            ofn.nFilterIndex      = 0;
            ofn.lpstrFile         = szFileName.ptr;
            ofn.nMaxFile          = MAX_PATH;
            ofn.lpstrFileTitle    = szTitleName.ptr;
            ofn.nMaxFileTitle     = MAX_PATH;
            ofn.lpstrInitialDir   = NULL;
            ofn.lpstrTitle        = NULL;
            ofn.Flags             = 0;
            ofn.nFileOffset       = 0;
            ofn.nFileExtension    = 0;
            ofn.lpstrDefExt       = "emf";
            ofn.lCustData         = 0;
            ofn.lpfnHook          = NULL;
            ofn.lpTemplateName    = NULL;
            return 0;

        case WM_INITMENUPOPUP:
            hMenu = GetMenu(hwnd);

            iEnable = hemf ? MF_ENABLED : MF_GRAYED;

            EnableMenuItem(hMenu, IDM_FILE_SAVE_AS,    iEnable);
            EnableMenuItem(hMenu, IDM_FILE_PRINT,      iEnable);
            EnableMenuItem(hMenu, IDM_FILE_PROPERTIES, iEnable);
            EnableMenuItem(hMenu, IDM_EDIT_CUT,        iEnable);
            EnableMenuItem(hMenu, IDM_EDIT_COPY,       iEnable);
            EnableMenuItem(hMenu, IDM_EDIT_DELETE,     iEnable);

            EnableMenuItem(hMenu, IDM_EDIT_PASTE,
                           IsClipboardFormatAvailable(CF_ENHMETAFILE) ?
                           MF_ENABLED : MF_GRAYED);
            return 0;

        case WM_COMMAND:

            switch (LOWORD(wParam))
            {
                case IDM_FILE_OPEN:

                    // Show the File Open dialog box

                    ofn.Flags = 0;

                    if (!GetOpenFileName(&ofn))
                        return 0;

                    // If there's an existing EMF, get rid of it.

                    if (hemf)
                    {
                        DeleteEnhMetaFile(hemf);
                        hemf = NULL;
                    }

                    // Load the EMF into memory

                    SetCursor(LoadCursor(NULL, IDC_WAIT));
                    ShowCursor(TRUE);

                    hemf = GetEnhMetaFile(szFileName.ptr);

                    ShowCursor(FALSE);
                    SetCursor(LoadCursor(NULL, IDC_ARROW));

                    // Invalidate the client area for later update

                    InvalidateRect(hwnd, NULL, TRUE);

                    if (hemf == NULL)
                    {
                        MessageBox(hwnd, "Cannot load metafile",
                                   appName.toUTF16z, MB_ICONEXCLAMATION | MB_OK);
                    }

                    return 0;

                case IDM_FILE_SAVE_AS:

                    if (!hemf)
                        return 0;

                    // Show the File Save dialog box

                    ofn.Flags = OFN_OVERWRITEPROMPT;

                    if (!GetSaveFileName(&ofn))
                        return 0;

                    // Save the EMF to disk file

                    SetCursor(LoadCursor(NULL, IDC_WAIT));
                    ShowCursor(TRUE);

                    hemfCopy = CopyEnhMetaFile(hemf, szFileName.ptr);

                    ShowCursor(FALSE);
                    SetCursor(LoadCursor(NULL, IDC_ARROW));

                    if (hemfCopy)
                    {
                        DeleteEnhMetaFile(hemf);
                        hemf = hemfCopy;
                    }
                    else
                        MessageBox(hwnd, "Cannot save metafile",
                                   appName.toUTF16z, MB_ICONEXCLAMATION | MB_OK);

                    return 0;

                case IDM_FILE_PRINT:

                    // Show the Print dialog box and get printer DC

                    printdlg.Flags = PD_RETURNDC | PD_NOPAGENUMS | PD_NOSELECTION;

                    if (!PrintDlg(&printdlg))
                        return 0;

                    if (NULL == (hdcPrn = printdlg.hDC))
                    {
                        MessageBox(hwnd, "Cannot obtain printer DC",
                                   appName.toUTF16z, MB_ICONEXCLAMATION | MB_OK);
                        return 0;
                    }

                    // Get size of printable area of page

                    rect.left   = 0;
                    rect.right  = GetDeviceCaps(hdcPrn, HORZRES);
                    rect.top    = 0;
                    rect.bottom = GetDeviceCaps(hdcPrn, VERTRES);

                    bSuccess = FALSE;

                    // Play the EMF to the printer

                    SetCursor(LoadCursor(NULL, IDC_WAIT));
                    ShowCursor(TRUE);

                    if ((StartDoc(hdcPrn, &di) > 0) && (StartPage(hdcPrn) > 0))
                    {
                        PlayEnhMetaFile(hdcPrn, hemf, &rect);

                        if (EndPage(hdcPrn) > 0)
                        {
                            bSuccess = TRUE;
                            EndDoc(hdcPrn);
                        }
                    }

                    ShowCursor(FALSE);
                    SetCursor(LoadCursor(NULL, IDC_ARROW));

                    DeleteDC(hdcPrn);

                    if (!bSuccess)
                        MessageBox(hwnd, "Could not print metafile",
                                   appName.toUTF16z, MB_ICONEXCLAMATION | MB_OK);

                    return 0;

                case IDM_FILE_PROPERTIES:

                    if (!hemf)
                        return 0;

                    iLength = GetEnhMetaFileDescription(hemf, 0, NULL);
                    pBuffer = cast(typeof(pBuffer))GC.malloc((iLength + 256) * TCHAR.sizeof);

                    GetEnhMetaFileHeader(hemf, ENHMETAHEADER.sizeof, &header);

                    // Format header file information
                    i = wsprintf(pBuffer,
                                 "Bounds = (%i, %i) to (%i, %i) pixels\n",
                                 header.rclBounds.left, header.rclBounds.top,
                                 header.rclBounds.right, header.rclBounds.bottom);

                    i += wsprintf(pBuffer + i,
                                  "Frame = (%i, %i) to (%i, %i) mms\n",
                                  header.rclFrame.left, header.rclFrame.top,
                                  header.rclFrame.right, header.rclFrame.bottom);

                    i += wsprintf(pBuffer + i,
                                  "Resolution = (%i, %i) pixels = (%i, %i) mms\n",
                                  header.szlDevice.cx, header.szlDevice.cy,
                                  header.szlMillimeters.cx,
                                  header.szlMillimeters.cy);

                    i += wsprintf(pBuffer + i,
                                  "Size = %i, Records = %i, Handles = %i, Palette entries = %i\n",
                                  header.nBytes, header.nRecords,
                                  header.nHandles, header.nPalEntries);

                    // Include the metafile description, if present

                    if (iLength)
                    {
                        i += wsprintf(pBuffer + i, "Description = ");
                        GetEnhMetaFileDescription(hemf, iLength, pBuffer + i);
                        pBuffer [lstrlen(pBuffer)] = '\t';
                    }

                    MessageBox(hwnd, pBuffer, "Metafile Properties", MB_OK);
                    GC.free(pBuffer);
                    return 0;

                case IDM_EDIT_COPY:
                case IDM_EDIT_CUT:

                    if (!hemf)
                        return 0;

                    // Transfer metafile copy to the clipboard

                    hemfCopy = CopyEnhMetaFile(hemf, NULL);

                    OpenClipboard(hwnd);
                    EmptyClipboard();
                    SetClipboardData(CF_ENHMETAFILE, hemfCopy);
                    CloseClipboard();

                    if (LOWORD(wParam) == IDM_EDIT_COPY)
                        return 0;
                    
                    goto case;

                // fall through if IDM_EDIT_CUT
                case IDM_EDIT_DELETE:

                    if (hemf)
                    {
                        DeleteEnhMetaFile(hemf);
                        hemf = NULL;
                        InvalidateRect(hwnd, NULL, TRUE);
                    }

                    return 0;

                case IDM_EDIT_PASTE:
                    OpenClipboard(hwnd);
                    hemfCopy = GetClipboardData(CF_ENHMETAFILE);
                    CloseClipboard();

                    if (hemfCopy && hemf)
                    {
                        DeleteEnhMetaFile(hemf);
                        hemf = NULL;
                    }

                    hemf = CopyEnhMetaFile(hemfCopy, NULL);
                    InvalidateRect(hwnd, NULL, TRUE);
                    return 0;

                case IDM_APP_ABOUT:
                    MessageBox(hwnd, "Enhanced Metafile Viewer\n(c) Charles Petzold, 1998",
                               appName.toUTF16z, MB_OK);
                    return 0;

                case IDM_APP_EXIT:
                    SendMessage(hwnd, WM_CLOSE, 0, 0L);
                    return 0;
                
                default:
            }

            break;

        case WM_PAINT:
            hdc = BeginPaint(hwnd, &ps);

            if (hemf)
            {
                hPalette = CreatePaletteFromMetaFile(hemf);
                if (hPalette !is null)
                {
                    SelectPalette(hdc, hPalette, FALSE);
                    RealizePalette(hdc);
                }

                GetClientRect(hwnd, &rect);
                PlayEnhMetaFile(hdc, hemf, &rect);

                if (hPalette)
                    DeleteObject(hPalette);
            }

            EndPaint(hwnd, &ps);
            return 0;

        case WM_QUERYNEWPALETTE:

            hPalette = CreatePaletteFromMetaFile(hemf);
            if (!hemf || hPalette is null)
                return FALSE;

            hdc = GetDC(hwnd);
            SelectPalette(hdc, hPalette, FALSE);
            RealizePalette(hdc);
            InvalidateRect(hwnd, NULL, FALSE);

            DeleteObject(hPalette);
            ReleaseDC(hwnd, hdc);
            return TRUE;

        case WM_PALETTECHANGED:

            if (cast(HWND)wParam == hwnd)
                break;

            hPalette = CreatePaletteFromMetaFile(hemf);
            if (!hemf || hPalette is null)
                break;

            hdc = GetDC(hwnd);
            SelectPalette(hdc, hPalette, FALSE);
            RealizePalette(hdc);
            UpdateColors(hdc);

            DeleteObject(hPalette);
            ReleaseDC(hwnd, hdc);
            break;

        case WM_DESTROY:

            if (hemf)
                DeleteEnhMetaFile(hemf);

            PostQuitMessage(0);
            return 0;
            
        default:
    }

    return DefWindowProc(hwnd, message, wParam, lParam);
}
Back to Top