olepicture.c 74 KB
Newer Older
1 2 3 4 5 6
/*
 * OLE Picture object
 *
 * Implementation of OLE IPicture and related interfaces
 *
 * Copyright 2000 Huw D M Davies for CodeWeavers.
7
 * Copyright 2001 Marcus Meissner
8
 * Copyright 2008 Kirill K. Smirnov
9
 *
10 11 12 13 14 15 16 17 18 19 20 21
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
22
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
23 24 25
 *
 * BUGS
 *
26
 * Support PICTYPE_BITMAP and PICTYPE_ICON, although only bitmaps very well..
27
 * Lots of methods are just stubs.
28 29 30 31 32 33 34 35 36 37 38
 *
 *
 * NOTES (or things that msdn doesn't tell you)
 *
 * The width and height properties are returned in HIMETRIC units (0.01mm)
 * IPicture::Render also uses these to select a region of the src picture.
 * A bitmap's size is converted into these units by using the screen resolution
 * thus an 8x8 bitmap on a 96dpi screen has a size of 212x212 (8/96 * 2540).
 *
 */

39
#include "config.h"
40
#include "wine/port.h"
41

42 43 44
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
45
#include <stdarg.h>
46
#include <stdio.h>
47
#include <string.h>
48

49
#define COBJMACROS
50
#define NONAMELESSUNION
51

52
#include "winerror.h"
53
#include "windef.h"
54 55 56 57
#include "winbase.h"
#include "wingdi.h"
#include "winuser.h"
#include "ole2.h"
58
#include "olectl.h"
59 60
#include "oleauto.h"
#include "connpt.h"
61
#include "urlmon.h"
62
#include "initguid.h"
63
#include "wincodec.h"
64
#include "wine/debug.h"
65
#include "wine/unicode.h"
66
#include "wine/library.h"
67

68
WINE_DEFAULT_DEBUG_CHANNEL(olepicture);
69

70 71 72 73 74 75
#define BITMAP_FORMAT_BMP   0x4d42 /* "BM" */
#define BITMAP_FORMAT_JPEG  0xd8ff
#define BITMAP_FORMAT_GIF   0x4947
#define BITMAP_FORMAT_PNG   0x5089
#define BITMAP_FORMAT_APM   0xcdd7

76 77
#include "pshpack1.h"

78 79 80 81 82 83 84 85 86 87 88 89 90 91
/* Header for Aldus Placable Metafiles - a standard metafile follows */
typedef struct _APM_HEADER
{
    DWORD key;
    WORD handle;
    SHORT left;
    SHORT top;
    SHORT right;
    SHORT bottom;
    WORD inch;
    DWORD reserved;
    WORD checksum;
} APM_HEADER;

92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
typedef struct {
    BYTE bWidth;
    BYTE bHeight;
    BYTE bColorCount;
    BYTE bReserved;
    WORD xHotspot;
    WORD yHotspot;
    DWORD dwDIBSize;
    DWORD dwDIBOffset;
} CURSORICONFILEDIRENTRY;

typedef struct
{
    WORD                idReserved;
    WORD                idType;
    WORD                idCount;
    CURSORICONFILEDIRENTRY  idEntries[1];
} CURSORICONFILEDIR;

#include "poppack.h"

113 114 115 116 117 118 119 120 121 122
/*************************************************************************
 *  Declaration of implementation class
 */

typedef struct OLEPictureImpl {

  /*
   * IPicture handles IUnknown
   */

123 124 125 126
    IPicture                  IPicture_iface;
    IDispatch                 IDispatch_iface;
    IPersistStream            IPersistStream_iface;
    IConnectionPointContainer IConnectionPointContainer_iface;
127

128
  /* Object reference count */
129
    LONG ref;
130 131 132

  /* We own the object and must destroy it ourselves */
    BOOL fOwn;
133

134 135 136 137 138 139 140 141 142 143 144
  /* Picture description */
    PICTDESC desc;

  /* These are the pixel size of a bitmap */
    DWORD origWidth;
    DWORD origHeight;

  /* And these are the size of the picture converted into HIMETRIC units */
    OLE_XSIZE_HIMETRIC himetricWidth;
    OLE_YSIZE_HIMETRIC himetricHeight;

145 146 147 148
    IConnectionPoint *pCP;

    BOOL keepOrigFormat;
    HDC	hDCCur;
149
    HBITMAP stock_bitmap;
150

151 152
  /* Bitmap transparency mask */
    HBITMAP hbmMask;
153
    HBITMAP hbmXor;
154 155
    COLORREF rgbTrans;

156 157 158
  /* data */
    void* data;
    int datalen;
159 160 161
    BOOL bIsDirty;                  /* Set to TRUE if picture has changed */
    unsigned int loadtime_magic;    /* If a length header was found, saves value */
    unsigned int loadtime_format;   /* for PICTYPE_BITMAP only, keeps track of image format (GIF/BMP/JPEG) */
162 163
} OLEPictureImpl;

164 165 166 167
static inline OLEPictureImpl *impl_from_IPicture(IPicture *iface)
{
    return CONTAINING_RECORD(iface, OLEPictureImpl, IPicture_iface);
}
168 169 170

static inline OLEPictureImpl *impl_from_IDispatch( IDispatch *iface )
{
171
    return CONTAINING_RECORD(iface, OLEPictureImpl, IDispatch_iface);
172 173 174 175
}

static inline OLEPictureImpl *impl_from_IPersistStream( IPersistStream *iface )
{
176
    return CONTAINING_RECORD(iface, OLEPictureImpl, IPersistStream_iface);
177 178 179 180
}

static inline OLEPictureImpl *impl_from_IConnectionPointContainer( IConnectionPointContainer *iface )
{
181
    return CONTAINING_RECORD(iface, OLEPictureImpl, IConnectionPointContainer_iface);
182
}
183 184 185 186

/*
 * Predeclare VTables.  They get initialized at the end.
 */
187 188 189 190
static const IPictureVtbl OLEPictureImpl_VTable;
static const IDispatchVtbl OLEPictureImpl_IDispatch_VTable;
static const IPersistStreamVtbl OLEPictureImpl_IPersistStream_VTable;
static const IConnectionPointContainerVtbl OLEPictureImpl_IConnectionPointContainer_VTable;
191

192 193 194 195 196 197 198 199 200 201 202
/* pixels to HIMETRIC units conversion */
static inline OLE_XSIZE_HIMETRIC xpixels_to_himetric(INT pixels, HDC hdc)
{
    return MulDiv(pixels, 2540, GetDeviceCaps(hdc, LOGPIXELSX));
}

static inline OLE_YSIZE_HIMETRIC ypixels_to_himetric(INT pixels, HDC hdc)
{
    return MulDiv(pixels, 2540, GetDeviceCaps(hdc, LOGPIXELSY));
}

203 204 205 206
/***********************************************************************
 * Implementation of the OLEPictureImpl class.
 */

207 208
static void OLEPictureImpl_SetBitmap(OLEPictureImpl *This)
{
209 210 211
  BITMAP bm;
  HDC hdcRef;

212
  TRACE("bitmap handle %p\n", This->desc.u.bmp.hbitmap);
213
  if(GetObjectW(This->desc.u.bmp.hbitmap, sizeof(bm), &bm) != sizeof(bm)) {
214 215 216 217 218
    ERR("GetObject fails\n");
    return;
  }
  This->origWidth = bm.bmWidth;
  This->origHeight = bm.bmHeight;
219

220 221
  TRACE("width %d, height %d, bpp %d\n", bm.bmWidth, bm.bmHeight, bm.bmBitsPixel);

222 223 224 225 226
  /* The width and height are stored in HIMETRIC units (0.01 mm),
     so we take our pixel width divide by pixels per inch and
     multiply by 25.4 * 100 */
  /* Should we use GetBitmapDimension if available? */
  hdcRef = CreateCompatibleDC(0);
227

228 229
  This->himetricWidth  = xpixels_to_himetric(bm.bmWidth, hdcRef);
  This->himetricHeight = ypixels_to_himetric(bm.bmHeight, hdcRef);
230
  This->stock_bitmap = GetCurrentObject( hdcRef, OBJ_BITMAP );
231

232 233
  This->loadtime_format = BITMAP_FORMAT_BMP;

234 235 236
  DeleteDC(hdcRef);
}

237 238 239 240 241 242 243 244 245 246
static void OLEPictureImpl_SetIcon(OLEPictureImpl * This)
{
    ICONINFO infoIcon;

    TRACE("icon handle %p\n", This->desc.u.icon.hicon);
    if (GetIconInfo(This->desc.u.icon.hicon, &infoIcon)) {
        HDC hdcRef;
        BITMAP bm;

        TRACE("bitmap handle for icon is %p\n", infoIcon.hbmColor);
247
        if(GetObjectW(infoIcon.hbmColor ? infoIcon.hbmColor : infoIcon.hbmMask, sizeof(bm), &bm) != sizeof(bm)) {
248 249 250 251 252 253 254 255
            ERR("GetObject fails on icon bitmap\n");
            return;
        }

        This->origWidth = bm.bmWidth;
        This->origHeight = infoIcon.hbmColor ? bm.bmHeight : bm.bmHeight / 2;
        /* see comment on HIMETRIC on OLEPictureImpl_SetBitmap() */
        hdcRef = GetDC(0);
256 257 258 259

        This->himetricWidth  = xpixels_to_himetric(This->origWidth, hdcRef);
        This->himetricHeight = ypixels_to_himetric(This->origHeight, hdcRef);

260 261 262 263 264 265 266 267 268
        ReleaseDC(0, hdcRef);

        DeleteObject(infoIcon.hbmMask);
        if (infoIcon.hbmColor) DeleteObject(infoIcon.hbmColor);
    } else {
        ERR("GetIconInfo() fails on icon %p\n", This->desc.u.icon.hicon);
    }
}

269 270 271 272 273 274 275 276 277 278 279 280
/************************************************************************
 * OLEPictureImpl_Construct
 *
 * This method will construct a new instance of the OLEPictureImpl
 * class.
 *
 * The caller of this method must release the object when it's
 * done with it.
 */
static OLEPictureImpl* OLEPictureImpl_Construct(LPPICTDESC pictDesc, BOOL fOwn)
{
  OLEPictureImpl* newObject = 0;
281 282 283

  if (pictDesc)
      TRACE("(%p) type = %d\n", pictDesc, pictDesc->picType);
284 285 286 287

  /*
   * Allocate space for the object.
   */
288
  newObject = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(OLEPictureImpl));
289 290 291

  if (newObject==0)
    return newObject;
292

293 294 295
  /*
   * Initialize the virtual function table.
   */
296 297 298 299
  newObject->IPicture_iface.lpVtbl = &OLEPictureImpl_VTable;
  newObject->IDispatch_iface.lpVtbl = &OLEPictureImpl_IDispatch_VTable;
  newObject->IPersistStream_iface.lpVtbl = &OLEPictureImpl_IPersistStream_VTable;
  newObject->IConnectionPointContainer_iface.lpVtbl = &OLEPictureImpl_IConnectionPointContainer_VTable;
300

301
  newObject->pCP = NULL;
302
  CreateConnectionPoint((IUnknown*)newObject,&IID_IPropertyNotifySink,&newObject->pCP);
303 304 305 306 307
  if (!newObject->pCP)
  {
    HeapFree(GetProcessHeap(), 0, newObject);
    return NULL;
  }
308

309
  /*
310
   * Start with one reference count. The caller of this function
311 312
   * must release the interface pointer when it is done.
   */
313 314
  newObject->ref	= 1;
  newObject->hDCCur	= 0;
315

316
  newObject->fOwn	= fOwn;
317

318 319
  /* dunno about original value */
  newObject->keepOrigFormat = TRUE;
320

321
  newObject->hbmMask = NULL;
322
  newObject->hbmXor = NULL;
323 324 325
  newObject->loadtime_magic = 0xdeadbeef;
  newObject->loadtime_format = 0;
  newObject->bIsDirty = FALSE;
326

327
  if (pictDesc) {
328
      newObject->desc = *pictDesc;
329

330 331 332 333
      switch(pictDesc->picType) {
      case PICTYPE_BITMAP:
	OLEPictureImpl_SetBitmap(newObject);
	break;
334

335
      case PICTYPE_METAFILE:
336
	TRACE("metafile handle %p\n", pictDesc->u.wmf.hmeta);
337 338 339
	newObject->himetricWidth = pictDesc->u.wmf.xExt;
	newObject->himetricHeight = pictDesc->u.wmf.yExt;
	break;
340

341 342 343 344 345
      case PICTYPE_NONE:
	/* not sure what to do here */
	newObject->himetricWidth = newObject->himetricHeight = 0;
	break;

346
      case PICTYPE_ICON:
347 348
        OLEPictureImpl_SetIcon(newObject);
        break;
349 350 351 352 353 354 355 356
      case PICTYPE_ENHMETAFILE:
      default:
	FIXME("Unsupported type %d\n", pictDesc->picType);
	newObject->himetricWidth = newObject->himetricHeight = 0;
	break;
      }
  } else {
      newObject->desc.picType = PICTYPE_UNINITIALIZED;
357
  }
358

359 360 361 362 363 364 365 366
  TRACE("returning %p\n", newObject);
  return newObject;
}

/************************************************************************
 * OLEPictureImpl_Destroy
 *
 * This method is called by the Release method when the reference
Andreas Mohr's avatar
Andreas Mohr committed
367
 * count goes down to 0. It will free all resources used by
368 369
 * this object.  */
static void OLEPictureImpl_Destroy(OLEPictureImpl* Obj)
370
{
371 372
  TRACE("(%p)\n", Obj);

373 374 375
  if (Obj->pCP)
    IConnectionPoint_Release(Obj->pCP);

376 377 378 379
  if(Obj->fOwn) { /* We need to destroy the picture */
    switch(Obj->desc.picType) {
    case PICTYPE_BITMAP:
      DeleteObject(Obj->desc.u.bmp.hbitmap);
380 381
      if (Obj->hbmMask != NULL) DeleteObject(Obj->hbmMask);
      if (Obj->hbmXor != NULL) DeleteObject(Obj->hbmXor);
382 383 384 385 386 387 388 389 390 391
      break;
    case PICTYPE_METAFILE:
      DeleteMetaFile(Obj->desc.u.wmf.hmeta);
      break;
    case PICTYPE_ICON:
      DestroyIcon(Obj->desc.u.icon.hicon);
      break;
    case PICTYPE_ENHMETAFILE:
      DeleteEnhMetaFile(Obj->desc.u.emf.hemf);
      break;
392
    case PICTYPE_NONE:
393
    case PICTYPE_UNINITIALIZED:
394 395
      /* Nothing to do */
      break;
396 397 398 399 400
    default:
      FIXME("Unsupported type %d - unable to delete\n", Obj->desc.picType);
      break;
    }
  }
401
  HeapFree(GetProcessHeap(), 0, Obj->data);
402 403 404
  HeapFree(GetProcessHeap(), 0, Obj);
}

405 406 407 408 409 410 411 412 413

/************************************************************************
 * OLEPictureImpl_AddRef (IUnknown)
 *
 * See Windows documentation for more details on IUnknown methods.
 */
static ULONG WINAPI OLEPictureImpl_AddRef(
  IPicture* iface)
{
414
  OLEPictureImpl *This = impl_from_IPicture(iface);
415 416
  ULONG refCount = InterlockedIncrement(&This->ref);

417
  TRACE("(%p)->(ref before=%d)\n", This, refCount - 1);
418 419 420 421 422 423 424 425 426 427 428 429

  return refCount;
}

/************************************************************************
 * OLEPictureImpl_Release (IUnknown)
 *
 * See Windows documentation for more details on IUnknown methods.
 */
static ULONG WINAPI OLEPictureImpl_Release(
      IPicture* iface)
{
430
  OLEPictureImpl *This = impl_from_IPicture(iface);
431 432
  ULONG refCount = InterlockedDecrement(&This->ref);

433
  TRACE("(%p)->(ref before=%d)\n", This, refCount + 1);
434 435 436 437 438 439 440 441

  /*
   * If the reference count goes down to 0, perform suicide.
   */
  if (!refCount) OLEPictureImpl_Destroy(This);

  return refCount;
}
442 443 444 445 446 447 448 449 450 451 452

/************************************************************************
 * OLEPictureImpl_QueryInterface (IUnknown)
 *
 * See Windows documentation for more details on IUnknown methods.
 */
static HRESULT WINAPI OLEPictureImpl_QueryInterface(
  IPicture*  iface,
  REFIID  riid,
  void**  ppvObject)
{
453
  OLEPictureImpl *This = impl_from_IPicture(iface);
454

455 456
  TRACE("(%p)->(%s, %p)\n", This, debugstr_guid(riid), ppvObject);

457
  if (!ppvObject)
458
    return E_INVALIDARG;
459

460
  *ppvObject = 0;
461

462
  if (IsEqualIID(&IID_IUnknown, riid) || IsEqualIID(&IID_IPicture, riid))
463
    *ppvObject = This;
464
  else if (IsEqualIID(&IID_IDispatch, riid))
465
    *ppvObject = &This->IDispatch_iface;
466
  else if (IsEqualIID(&IID_IPictureDisp, riid))
467
    *ppvObject = &This->IDispatch_iface;
468
  else if (IsEqualIID(&IID_IPersist, riid) || IsEqualIID(&IID_IPersistStream, riid))
469
    *ppvObject = &This->IPersistStream_iface;
470
  else if (IsEqualIID(&IID_IConnectionPointContainer, riid))
471
    *ppvObject = &This->IConnectionPointContainer_iface;
472

473
  if (!*ppvObject)
474 475 476 477
  {
    FIXME("() : asking for un supported interface %s\n",debugstr_guid(riid));
    return E_NOINTERFACE;
  }
478

479
  IPicture_AddRef(iface);
480

481
  return S_OK;
482
}
483

484 485 486 487 488 489 490 491 492 493 494
/***********************************************************************
 *    OLEPicture_SendNotify (internal)
 *
 * Sends notification messages of changed properties to any interested
 * connections.
 */
static void OLEPicture_SendNotify(OLEPictureImpl* this, DISPID dispID)
{
  IEnumConnections *pEnum;
  CONNECTDATA CD;

495
  if (IConnectionPoint_EnumConnections(this->pCP, &pEnum) != S_OK)
496 497 498 499 500 501 502 503 504 505 506 507
      return;
  while(IEnumConnections_Next(pEnum, 1, &CD, NULL) == S_OK) {
    IPropertyNotifySink *sink;

    IUnknown_QueryInterface(CD.pUnk, &IID_IPropertyNotifySink, (LPVOID)&sink);
    IPropertyNotifySink_OnChanged(sink, dispID);
    IPropertyNotifySink_Release(sink);
    IUnknown_Release(CD.pUnk);
  }
  IEnumConnections_Release(pEnum);
}

508 509
/************************************************************************
 * OLEPictureImpl_get_Handle
510
 */
511 512 513
static HRESULT WINAPI OLEPictureImpl_get_Handle(IPicture *iface,
						OLE_HANDLE *phandle)
{
514
  OLEPictureImpl *This = impl_from_IPicture(iface);
515
  TRACE("(%p)->(%p)\n", This, phandle);
516 517 518 519

  if(!phandle)
    return E_POINTER;

520
  switch(This->desc.picType) {
521
  case PICTYPE_NONE:
522
  case PICTYPE_UNINITIALIZED:
523 524
    *phandle = 0;
    break;
525
  case PICTYPE_BITMAP:
526
    *phandle = HandleToUlong(This->desc.u.bmp.hbitmap);
527 528
    break;
  case PICTYPE_METAFILE:
529
    *phandle = HandleToUlong(This->desc.u.wmf.hmeta);
530 531
    break;
  case PICTYPE_ICON:
532
    *phandle = HandleToUlong(This->desc.u.icon.hicon);
533 534
    break;
  case PICTYPE_ENHMETAFILE:
535
    *phandle = HandleToUlong(This->desc.u.emf.hemf);
536 537 538 539 540 541 542 543 544 545 546
    break;
  default:
    FIXME("Unimplemented type %d\n", This->desc.picType);
    return E_NOTIMPL;
  }
  TRACE("returning handle %08x\n", *phandle);
  return S_OK;
}

/************************************************************************
 * OLEPictureImpl_get_hPal
547
 */
548 549 550
static HRESULT WINAPI OLEPictureImpl_get_hPal(IPicture *iface,
					      OLE_HANDLE *phandle)
{
551
  OLEPictureImpl *This = impl_from_IPicture(iface);
552 553
  HRESULT hres;
  TRACE("(%p)->(%p)\n", This, phandle);
554

555 556 557 558
  if (!phandle)
    return E_POINTER;

  switch (This->desc.picType) {
559
    case (UINT)PICTYPE_UNINITIALIZED:
560 561 562 563 564
    case PICTYPE_NONE:
      *phandle = 0;
      hres = S_FALSE;
      break;
    case PICTYPE_BITMAP:
565
      *phandle = HandleToUlong(This->desc.u.bmp.hpal);
566 567 568
      hres = S_OK;
      break;
    case PICTYPE_METAFILE:
569 570 571
      hres = E_FAIL;
      break;
    case PICTYPE_ICON:
572 573 574 575 576 577 578 579
    case PICTYPE_ENHMETAFILE:
    default:
      FIXME("unimplemented for type %d. Returning 0 palette.\n",
           This->desc.picType);
      *phandle = 0;
      hres = S_OK;
  }

580
  TRACE("returning 0x%08x, palette handle %08x\n", hres, *phandle);
581
  return hres;
582 583 584 585
}

/************************************************************************
 * OLEPictureImpl_get_Type
586
 */
587 588 589
static HRESULT WINAPI OLEPictureImpl_get_Type(IPicture *iface,
					      short *ptype)
{
590
  OLEPictureImpl *This = impl_from_IPicture(iface);
591
  TRACE("(%p)->(%p): type is %d\n", This, ptype, This->desc.picType);
592 593 594 595

  if(!ptype)
    return E_POINTER;

596 597 598 599 600 601
  *ptype = This->desc.picType;
  return S_OK;
}

/************************************************************************
 * OLEPictureImpl_get_Width
602
 */
603 604 605
static HRESULT WINAPI OLEPictureImpl_get_Width(IPicture *iface,
					       OLE_XSIZE_HIMETRIC *pwidth)
{
606
  OLEPictureImpl *This = impl_from_IPicture(iface);
607
  TRACE("(%p)->(%p): width is %d\n", This, pwidth, This->himetricWidth);
608 609 610 611 612 613
  *pwidth = This->himetricWidth;
  return S_OK;
}

/************************************************************************
 * OLEPictureImpl_get_Height
614
 */
615 616 617
static HRESULT WINAPI OLEPictureImpl_get_Height(IPicture *iface,
						OLE_YSIZE_HIMETRIC *pheight)
{
618
  OLEPictureImpl *This = impl_from_IPicture(iface);
619
  TRACE("(%p)->(%p): height is %d\n", This, pheight, This->himetricHeight);
620 621 622 623 624 625
  *pheight = This->himetricHeight;
  return S_OK;
}

/************************************************************************
 * OLEPictureImpl_Render
626
 */
627
static HRESULT WINAPI OLEPictureImpl_Render(IPicture *iface, HDC hdc,
628
					    LONG x, LONG y, LONG cx, LONG cy,
629 630 631 632 633 634
					    OLE_XPOS_HIMETRIC xSrc,
					    OLE_YPOS_HIMETRIC ySrc,
					    OLE_XSIZE_HIMETRIC cxSrc,
					    OLE_YSIZE_HIMETRIC cySrc,
					    LPCRECT prcWBounds)
{
635
  OLEPictureImpl *This = impl_from_IPicture(iface);
636
  TRACE("(%p)->(%p, (%d,%d), (%d,%d) <- (%d,%d), (%d,%d), %p)\n",
637 638
	This, hdc, x, y, cx, cy, xSrc, ySrc, cxSrc, cySrc, prcWBounds);
  if(prcWBounds)
639
    TRACE("prcWBounds (%d,%d) - (%d,%d)\n", prcWBounds->left, prcWBounds->top,
640 641
	  prcWBounds->right, prcWBounds->bottom);

642 643 644 645
  if(cx == 0 || cy == 0 || cxSrc == 0 || cySrc == 0){
    return CTL_E_INVALIDPROPERTYVALUE;
  }

646 647 648 649 650 651
  /*
   * While the documentation suggests this to be here (or after rendering?)
   * it does cause an endless recursion in my sample app. -MM 20010804
  OLEPicture_SendNotify(This,DISPID_PICT_RENDER);
   */

652
  switch(This->desc.picType) {
653 654 655 656
  case PICTYPE_UNINITIALIZED:
  case PICTYPE_NONE:
    /* nothing to do */
    return S_OK;
657 658 659 660 661 662 663 664 665 666 667 668 669 670 671
  case PICTYPE_BITMAP:
    {
      HBITMAP hbmpOld;
      HDC hdcBmp;

      /* Set a mapping mode that maps bitmap pixels into HIMETRIC units.
         NB y-axis gets flipped */

      hdcBmp = CreateCompatibleDC(0);
      SetMapMode(hdcBmp, MM_ANISOTROPIC);
      SetWindowOrgEx(hdcBmp, 0, 0, NULL);
      SetWindowExtEx(hdcBmp, This->himetricWidth, This->himetricHeight, NULL);
      SetViewportOrgEx(hdcBmp, 0, This->origHeight, NULL);
      SetViewportExtEx(hdcBmp, This->origWidth, -This->origHeight, NULL);

672 673 674 675
      if (This->hbmMask) {
	  HDC hdcMask = CreateCompatibleDC(0);
	  HBITMAP hOldbm = SelectObject(hdcMask, This->hbmMask);

676 677
          hbmpOld = SelectObject(hdcBmp, This->hbmXor);

678 679 680 681 682 683 684 685 686 687 688 689 690
	  SetMapMode(hdcMask, MM_ANISOTROPIC);
	  SetWindowOrgEx(hdcMask, 0, 0, NULL);
	  SetWindowExtEx(hdcMask, This->himetricWidth, This->himetricHeight, NULL);
	  SetViewportOrgEx(hdcMask, 0, This->origHeight, NULL);
	  SetViewportExtEx(hdcMask, This->origWidth, -This->origHeight, NULL);
	  
	  SetBkColor(hdc, RGB(255, 255, 255));    
	  SetTextColor(hdc, RGB(0, 0, 0));        
	  StretchBlt(hdc, x, y, cx, cy, hdcMask, xSrc, ySrc, cxSrc, cySrc, SRCAND); 
	  StretchBlt(hdc, x, y, cx, cy, hdcBmp, xSrc, ySrc, cxSrc, cySrc, SRCPAINT);

	  SelectObject(hdcMask, hOldbm);
	  DeleteDC(hdcMask);
691 692
      } else {
          hbmpOld = SelectObject(hdcBmp, This->desc.u.bmp.hbitmap);
693
	  StretchBlt(hdc, x, y, cx, cy, hdcBmp, xSrc, ySrc, cxSrc, cySrc, SRCCOPY);
694
      }
695 696 697 698 699

      SelectObject(hdcBmp, hbmpOld);
      DeleteDC(hdcBmp);
    }
    break;
700 701
  case PICTYPE_ICON:
    FIXME("Not quite correct implementation of rendering icons...\n");
702
    DrawIconEx(hdc, x, y, This->desc.u.icon.hicon, cx, cy, 0, NULL, DI_NORMAL);
703
    break;
704 705

  case PICTYPE_METAFILE:
706
  {
707 708
    POINT prevOrg, prevWndOrg;
    SIZE prevExt, prevWndExt;
709 710
    int oldmode;

711 712
    /* Render the WMF to the appropriate location by setting the
       appropriate ratio between "device units" and "logical units" */
713
    oldmode = SetMapMode(hdc, MM_ANISOTROPIC);
714 715 716 717
    /* For the "source rectangle" the y-axis must be inverted */
    SetWindowOrgEx(hdc, xSrc, This->himetricHeight-ySrc, &prevWndOrg);
    SetWindowExtEx(hdc, cxSrc, -cySrc, &prevWndExt);
    /* For the "destination rectangle" no inversion is necessary */
718 719 720 721 722 723
    SetViewportOrgEx(hdc, x, y, &prevOrg);
    SetViewportExtEx(hdc, cx, cy, &prevExt);

    if (!PlayMetaFile(hdc, This->desc.u.wmf.hmeta))
        ERR("PlayMetaFile failed!\n");

724 725 726 727
    /* We're done, restore the DC to the previous settings for converting
       logical units to device units */
    SetWindowExtEx(hdc, prevWndExt.cx, prevWndExt.cy, NULL);
    SetWindowOrgEx(hdc, prevWndOrg.x, prevWndOrg.y, NULL);
728 729 730
    SetViewportExtEx(hdc, prevExt.cx, prevExt.cy, NULL);
    SetViewportOrgEx(hdc, prevOrg.x, prevOrg.y, NULL);
    SetMapMode(hdc, oldmode);
731
    break;
732
  }
733

734
  case PICTYPE_ENHMETAFILE:
735
  {
736
    RECT rc = { x, y, x + cx, y + cy };
737 738 739 740
    PlayEnhMetaFile(hdc, This->desc.u.emf.hemf, &rc);
    break;
  }

741 742 743 744 745 746 747 748 749
  default:
    FIXME("type %d not implemented\n", This->desc.picType);
    return E_NOTIMPL;
  }
  return S_OK;
}

/************************************************************************
 * OLEPictureImpl_set_hPal
750
 */
751 752 753
static HRESULT WINAPI OLEPictureImpl_set_hPal(IPicture *iface,
					      OLE_HANDLE hpal)
{
754
  OLEPictureImpl *This = impl_from_IPicture(iface);
755
  FIXME("(%p)->(%08x): stub\n", This, hpal);
756
  OLEPicture_SendNotify(This,DISPID_PICT_HPAL);
757 758 759 760 761
  return E_NOTIMPL;
}

/************************************************************************
 * OLEPictureImpl_get_CurDC
762
 */
763 764 765
static HRESULT WINAPI OLEPictureImpl_get_CurDC(IPicture *iface,
					       HDC *phdc)
{
766
  OLEPictureImpl *This = impl_from_IPicture(iface);
767
  TRACE("(%p), returning %p\n", This, This->hDCCur);
768 769
  if (phdc) *phdc = This->hDCCur;
  return S_OK;
770 771 772 773
}

/************************************************************************
 * OLEPictureImpl_SelectPicture
774
 */
775 776 777 778 779
static HRESULT WINAPI OLEPictureImpl_SelectPicture(IPicture *iface,
						   HDC hdcIn,
						   HDC *phdcOut,
						   OLE_HANDLE *phbmpOut)
{
780
  OLEPictureImpl *This = impl_from_IPicture(iface);
781
  TRACE("(%p)->(%p, %p, %p)\n", This, hdcIn, phdcOut, phbmpOut);
782 783 784
  if (This->desc.picType == PICTYPE_BITMAP) {
      if (phdcOut)
	  *phdcOut = This->hDCCur;
785 786
      if (This->hDCCur) SelectObject(This->hDCCur,This->stock_bitmap);
      if (hdcIn) SelectObject(hdcIn,This->desc.u.bmp.hbitmap);
787 788
      This->hDCCur = hdcIn;
      if (phbmpOut)
789
	  *phbmpOut = HandleToUlong(This->desc.u.bmp.hbitmap);
790 791 792 793 794
      return S_OK;
  } else {
      FIXME("Don't know how to select picture type %d\n",This->desc.picType);
      return E_FAIL;
  }
795 796 797 798
}

/************************************************************************
 * OLEPictureImpl_get_KeepOriginalFormat
799
 */
800 801 802
static HRESULT WINAPI OLEPictureImpl_get_KeepOriginalFormat(IPicture *iface,
							    BOOL *pfKeep)
{
803
  OLEPictureImpl *This = impl_from_IPicture(iface);
804 805 806 807 808
  TRACE("(%p)->(%p)\n", This, pfKeep);
  if (!pfKeep)
      return E_POINTER;
  *pfKeep = This->keepOrigFormat;
  return S_OK;
809 810 811 812
}

/************************************************************************
 * OLEPictureImpl_put_KeepOriginalFormat
813
 */
814 815 816
static HRESULT WINAPI OLEPictureImpl_put_KeepOriginalFormat(IPicture *iface,
							    BOOL keep)
{
817
  OLEPictureImpl *This = impl_from_IPicture(iface);
818 819 820 821
  TRACE("(%p)->(%d)\n", This, keep);
  This->keepOrigFormat = keep;
  /* FIXME: what DISPID notification here? */
  return S_OK;
822 823 824 825
}

/************************************************************************
 * OLEPictureImpl_PictureChanged
826
 */
827 828
static HRESULT WINAPI OLEPictureImpl_PictureChanged(IPicture *iface)
{
829
  OLEPictureImpl *This = impl_from_IPicture(iface);
830 831
  TRACE("(%p)->()\n", This);
  OLEPicture_SendNotify(This,DISPID_PICT_HANDLE);
832
  This->bIsDirty = TRUE;
833
  return S_OK;
834 835 836 837
}

/************************************************************************
 * OLEPictureImpl_SaveAsFile
838
 */
839 840 841 842 843
static HRESULT WINAPI OLEPictureImpl_SaveAsFile(IPicture *iface,
						IStream *pstream,
						BOOL SaveMemCopy,
						LONG *pcbSize)
{
844
  OLEPictureImpl *This = impl_from_IPicture(iface);
845 846
  FIXME("(%p)->(%p, %d, %p), hacked stub.\n", This, pstream, SaveMemCopy, pcbSize);
  return IStream_Write(pstream,This->data,This->datalen,(ULONG*)pcbSize);
847 848 849 850
}

/************************************************************************
 * OLEPictureImpl_get_Attributes
851
 */
852 853 854
static HRESULT WINAPI OLEPictureImpl_get_Attributes(IPicture *iface,
						    DWORD *pdwAttr)
{
855
  OLEPictureImpl *This = impl_from_IPicture(iface);
856
  TRACE("(%p)->(%p).\n", This, pdwAttr);
857 858 859 860

  if(!pdwAttr)
    return E_POINTER;

861 862
  *pdwAttr = 0;
  switch (This->desc.picType) {
863 864
  case PICTYPE_UNINITIALIZED:
  case PICTYPE_NONE: break;
865
  case PICTYPE_BITMAP: 	if (This->hbmMask) *pdwAttr = PICTURE_TRANSPARENT; break;	/* not 'truly' scalable, see MSDN. */
866
  case PICTYPE_ICON: *pdwAttr     = PICTURE_TRANSPARENT;break;
867
  case PICTYPE_ENHMETAFILE: /* fall through */
868 869 870 871 872 873 874 875 876 877 878 879 880
  case PICTYPE_METAFILE: *pdwAttr = PICTURE_TRANSPARENT|PICTURE_SCALABLE;break;
  default:FIXME("Unknown pictype %d\n",This->desc.picType);break;
  }
  return S_OK;
}


/************************************************************************
 *    IConnectionPointContainer
 */
static HRESULT WINAPI OLEPictureImpl_IConnectionPointContainer_QueryInterface(
  IConnectionPointContainer* iface,
  REFIID riid,
881 882 883
  VOID** ppvoid)
{
  OLEPictureImpl *This = impl_from_IConnectionPointContainer(iface);
884

885
  return IPicture_QueryInterface(&This->IPicture_iface,riid,ppvoid);
886 887 888 889 890
}

static ULONG WINAPI OLEPictureImpl_IConnectionPointContainer_AddRef(
  IConnectionPointContainer* iface)
{
891
  OLEPictureImpl *This = impl_from_IConnectionPointContainer(iface);
892

893
  return IPicture_AddRef(&This->IPicture_iface);
894 895 896 897 898
}

static ULONG WINAPI OLEPictureImpl_IConnectionPointContainer_Release(
  IConnectionPointContainer* iface)
{
899
  OLEPictureImpl *This = impl_from_IConnectionPointContainer(iface);
900

901
  return IPicture_Release(&This->IPicture_iface);
902 903 904 905
}

static HRESULT WINAPI OLEPictureImpl_EnumConnectionPoints(
  IConnectionPointContainer* iface,
906 907 908
  IEnumConnectionPoints** ppEnum)
{
  OLEPictureImpl *This = impl_from_IConnectionPointContainer(iface);
909 910 911 912 913 914 915 916

  FIXME("(%p,%p), stub!\n",This,ppEnum);
  return E_NOTIMPL;
}

static HRESULT WINAPI OLEPictureImpl_FindConnectionPoint(
  IConnectionPointContainer* iface,
  REFIID riid,
917 918 919
  IConnectionPoint **ppCP)
{
  OLEPictureImpl *This = impl_from_IConnectionPointContainer(iface);
920
  TRACE("(%p,%s,%p)\n",This,debugstr_guid(riid),ppCP);
921
  if (!ppCP)
922 923 924
      return E_POINTER;
  *ppCP = NULL;
  if (IsEqualGUID(riid,&IID_IPropertyNotifySink))
925
      return IConnectionPoint_QueryInterface(This->pCP, &IID_IConnectionPoint, (void**)ppCP);
926 927
  FIXME("no connection point for %s\n",debugstr_guid(riid));
  return CONNECT_E_NOCONNECTION;
928
}
929 930


931 932 933
/************************************************************************
 *    IPersistStream
 */
934

935 936 937 938 939 940 941 942 943 944
/************************************************************************
 * OLEPictureImpl_IPersistStream_QueryInterface (IUnknown)
 *
 * See Windows documentation for more details on IUnknown methods.
 */
static HRESULT WINAPI OLEPictureImpl_IPersistStream_QueryInterface(
  IPersistStream* iface,
  REFIID     riid,
  VOID**     ppvoid)
{
945
  OLEPictureImpl *This = impl_from_IPersistStream(iface);
946

947
  return IPicture_QueryInterface(&This->IPicture_iface, riid, ppvoid);
948 949 950 951 952 953 954 955 956 957
}

/************************************************************************
 * OLEPictureImpl_IPersistStream_AddRef (IUnknown)
 *
 * See Windows documentation for more details on IUnknown methods.
 */
static ULONG WINAPI OLEPictureImpl_IPersistStream_AddRef(
  IPersistStream* iface)
{
958
  OLEPictureImpl *This = impl_from_IPersistStream(iface);
959

960
  return IPicture_AddRef(&This->IPicture_iface);
961 962 963 964 965 966 967 968 969 970
}

/************************************************************************
 * OLEPictureImpl_IPersistStream_Release (IUnknown)
 *
 * See Windows documentation for more details on IUnknown methods.
 */
static ULONG WINAPI OLEPictureImpl_IPersistStream_Release(
  IPersistStream* iface)
{
971
  OLEPictureImpl *This = impl_from_IPersistStream(iface);
972

973
  return IPicture_Release(&This->IPicture_iface);
974 975 976 977 978 979 980 981
}

/************************************************************************
 * OLEPictureImpl_IPersistStream_GetClassID
 */
static HRESULT WINAPI OLEPictureImpl_GetClassID(
  IPersistStream* iface,CLSID* pClassID)
{
982
  TRACE("(%p)\n", pClassID);
983
  *pClassID = CLSID_StdPicture;
984
  return S_OK;
985 986
}

987 988 989 990 991 992
/************************************************************************
 * OLEPictureImpl_IPersistStream_IsDirty
 */
static HRESULT WINAPI OLEPictureImpl_IsDirty(
  IPersistStream* iface)
{
993
  OLEPictureImpl *This = impl_from_IPersistStream(iface);
994 995 996
  FIXME("(%p),stub!\n",This);
  return E_NOTIMPL;
}
997

998 999
static HRESULT OLEPictureImpl_LoadDIB(OLEPictureImpl *This, BYTE *xbuf, ULONG xread)
{
1000 1001 1002 1003 1004 1005 1006
    BITMAPFILEHEADER	*bfh = (BITMAPFILEHEADER*)xbuf;
    BITMAPINFO		*bi = (BITMAPINFO*)(bfh+1);
    HDC			hdcref;

    /* Does not matter whether this is a coreheader or not, we only use
     * components which are in both
     */
1007
    hdcref = GetDC(0);
1008 1009 1010 1011 1012 1013
    This->desc.u.bmp.hbitmap = CreateDIBitmap(
	hdcref,
	&(bi->bmiHeader),
	CBM_INIT,
	xbuf+bfh->bfOffBits,
	bi,
1014
       DIB_RGB_COLORS
1015
    );
1016
    ReleaseDC(0, hdcref);
1017 1018
    if (This->desc.u.bmp.hbitmap == 0)
        return E_FAIL;
1019 1020
    This->desc.picType = PICTYPE_BITMAP;
    OLEPictureImpl_SetBitmap(This);
1021 1022 1023
    return S_OK;
}

1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153
static HRESULT OLEPictureImpl_LoadWICSource(OLEPictureImpl *This, IWICBitmapSource *src)
{
    HRESULT hr;
    BITMAPINFOHEADER bih;
    HDC hdcref;
    UINT width, height;
    UINT stride, buffersize;
    LPBYTE bits=NULL;
    WICRect rc;
    IWICBitmapSource *real_source;
    UINT x, y;
    COLORREF white = RGB(255, 255, 255), black = RGB(0, 0, 0);
    BOOL has_alpha=FALSE;

    hr = WICConvertBitmapSource(&GUID_WICPixelFormat32bppBGRA, src, &real_source);
    if (FAILED(hr)) return hr;

    hr = IWICBitmapSource_GetSize(real_source, &width, &height);
    if (FAILED(hr)) goto end;

    bih.biSize = sizeof(bih);
    bih.biWidth = width;
    bih.biHeight = -height;
    bih.biPlanes = 1;
    bih.biBitCount = 32;
    bih.biCompression = BI_RGB;
    bih.biSizeImage = 0;
    bih.biXPelsPerMeter = 4085; /* olepicture ignores the stored resolution */
    bih.biYPelsPerMeter = 4085;
    bih.biClrUsed = 0;
    bih.biClrImportant = 0;

    stride = 4 * width;
    buffersize = stride * height;

    bits = HeapAlloc(GetProcessHeap(), 0, buffersize);
    if (!bits)
    {
        hr = E_OUTOFMEMORY;
        goto end;
    }

    rc.X = 0;
    rc.Y = 0;
    rc.Width = width;
    rc.Height = height;
    hr = IWICBitmapSource_CopyPixels(real_source, &rc, stride, buffersize, bits);
    if (FAILED(hr))
        goto end;

    hdcref = GetDC(0);
    This->desc.u.bmp.hbitmap = CreateDIBitmap(
        hdcref,
        &bih,
        CBM_INIT,
        bits,
        (BITMAPINFO*)&bih,
        DIB_RGB_COLORS);

    if (This->desc.u.bmp.hbitmap == 0)
    {
        hr = E_FAIL;
        ReleaseDC(0, hdcref);
        goto end;
    }

    This->desc.picType = PICTYPE_BITMAP;
    OLEPictureImpl_SetBitmap(This);

    /* set transparent pixels to black, all others to white */
    for(y = 0; y < height; y++){
        for(x = 0; x < width; x++){
            DWORD *pixel = (DWORD*)(bits + stride*y + 4*x);
            if((*pixel & 0x80000000) == 0)
            {
                has_alpha = TRUE;
                *pixel = black;
            }
            else
                *pixel = white;
        }
    }

    if (has_alpha)
    {
        HDC hdcBmp, hdcXor, hdcMask;
        HBITMAP hbmoldBmp, hbmoldXor, hbmoldMask;

        This->hbmXor = CreateDIBitmap(
            hdcref,
            &bih,
            CBM_INIT,
            bits,
            (BITMAPINFO*)&bih,
            DIB_RGB_COLORS
        );

        This->hbmMask = CreateBitmap(width,-height,1,1,NULL);
        hdcBmp = CreateCompatibleDC(NULL);
        hdcXor = CreateCompatibleDC(NULL);
        hdcMask = CreateCompatibleDC(NULL);

        hbmoldBmp = SelectObject(hdcBmp,This->desc.u.bmp.hbitmap);
        hbmoldXor = SelectObject(hdcXor,This->hbmXor);
        hbmoldMask = SelectObject(hdcMask,This->hbmMask);

        SetBkColor(hdcXor,black);
        BitBlt(hdcMask,0,0,width,height,hdcXor,0,0,SRCCOPY);
        BitBlt(hdcXor,0,0,width,height,hdcBmp,0,0,SRCAND);

        SelectObject(hdcBmp,hbmoldBmp);
        SelectObject(hdcXor,hbmoldXor);
        SelectObject(hdcMask,hbmoldMask);

        DeleteDC(hdcBmp);
        DeleteDC(hdcXor);
        DeleteDC(hdcMask);
    }

    ReleaseDC(0, hdcref);

end:
    HeapFree(GetProcessHeap(), 0, bits);
    IWICBitmapSource_Release(real_source);
    return hr;
}

static HRESULT OLEPictureImpl_LoadWICDecoder(OLEPictureImpl *This, REFCLSID decoder_clsid, BYTE *xbuf, ULONG xread)
{
    HRESULT hr;
1154
    IWICImagingFactory *factory;
1155 1156 1157
    IWICBitmapDecoder *decoder;
    IWICBitmapFrameDecode *framedecode;
    HRESULT initresult;
1158
    IWICStream *stream;
1159

1160
    initresult = CoInitialize(NULL);
1161

1162 1163 1164
    hr = CoCreateInstance(&CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER,
        &IID_IWICImagingFactory, (void**)&factory);
    if (SUCCEEDED(hr)) /* created factory */
1165
    {
1166 1167
        hr = IWICImagingFactory_CreateStream(factory, &stream);
        IWICImagingFactory_Release(factory);
1168 1169
    }

1170
    if (SUCCEEDED(hr)) /* created stream */
1171
    {
1172 1173 1174
        hr = IWICStream_InitializeFromMemory(stream, xbuf, xread);

        if (SUCCEEDED(hr)) /* initialized stream */
1175
        {
1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186
            hr = CoCreateInstance(decoder_clsid, NULL, CLSCTX_INPROC_SERVER,
                &IID_IWICBitmapDecoder, (void**)&decoder);
            if (SUCCEEDED(hr)) /* created decoder */
            {
                hr = IWICBitmapDecoder_Initialize(decoder, (IStream*)stream, WICDecodeMetadataCacheOnLoad);

                if (SUCCEEDED(hr)) /* initialized decoder */
                    hr = IWICBitmapDecoder_GetFrame(decoder, 0, &framedecode);

                IWICBitmapDecoder_Release(decoder);
            }
1187
        }
1188 1189

        IWICStream_Release(stream);
1190 1191
    }

1192 1193 1194 1195 1196
    if (SUCCEEDED(hr)) /* got framedecode */
    {
        hr = OLEPictureImpl_LoadWICSource(This, (IWICBitmapSource*)framedecode);
        IWICBitmapFrameDecode_Release(framedecode);
    }
1197 1198 1199 1200 1201

    if (SUCCEEDED(initresult)) CoUninitialize();
    return hr;
}

1202 1203 1204 1205
/*****************************************************
*   start of Icon-specific code
*/

1206 1207
static HRESULT OLEPictureImpl_LoadIcon(OLEPictureImpl *This, BYTE *xbuf, ULONG xread)
{
1208 1209
    HICON hicon;
    CURSORICONFILEDIR	*cifd = (CURSORICONFILEDIR*)xbuf;
1210
    HDC hdcRef;
1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239
    int	i;

    /*
    FIXME("icon.idReserved=%d\n",cifd->idReserved);
    FIXME("icon.idType=%d\n",cifd->idType);
    FIXME("icon.idCount=%d\n",cifd->idCount);

    for (i=0;i<cifd->idCount;i++) {
	FIXME("[%d] width %d\n",i,cifd->idEntries[i].bWidth);
	FIXME("[%d] height %d\n",i,cifd->idEntries[i].bHeight);
	FIXME("[%d] bColorCount %d\n",i,cifd->idEntries[i].bColorCount);
	FIXME("[%d] bReserved %d\n",i,cifd->idEntries[i].bReserved);
	FIXME("[%d] xHotspot %d\n",i,cifd->idEntries[i].xHotspot);
	FIXME("[%d] yHotspot %d\n",i,cifd->idEntries[i].yHotspot);
	FIXME("[%d] dwDIBSize %d\n",i,cifd->idEntries[i].dwDIBSize);
	FIXME("[%d] dwDIBOffset %d\n",i,cifd->idEntries[i].dwDIBOffset);
    }
    */
    i=0;
    /* If we have more than one icon, try to find the best.
     * this currently means '32 pixel wide'.
     */
    if (cifd->idCount!=1) {
	for (i=0;i<cifd->idCount;i++) {
	    if (cifd->idEntries[i].bWidth == 32)
		break;
	}
	if (i==cifd->idCount) i=0;
    }
1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267
    if (cifd->idType == 2)
    {
        LPBYTE buf = HeapAlloc(GetProcessHeap(), 0, cifd->idEntries[i].dwDIBSize + 4);
        memcpy(buf, &cifd->idEntries[i].xHotspot, 4);
        memcpy(buf + 4, xbuf+cifd->idEntries[i].dwDIBOffset, cifd->idEntries[i].dwDIBSize);
        hicon = CreateIconFromResourceEx(
		    buf,
		    cifd->idEntries[i].dwDIBSize + 4,
		    FALSE, /* is cursor */
		    0x00030000,
		    cifd->idEntries[i].bWidth,
		    cifd->idEntries[i].bHeight,
		    0
	);
	HeapFree(GetProcessHeap(), 0, buf);
    }
    else
    {
        hicon = CreateIconFromResourceEx(
		    xbuf+cifd->idEntries[i].dwDIBOffset,
		    cifd->idEntries[i].dwDIBSize,
		    TRUE, /* is icon */
		    0x00030000,
		    cifd->idEntries[i].bWidth,
		    cifd->idEntries[i].bHeight,
		    0
	);
    }
1268
    if (!hicon) {
1269
	ERR("CreateIcon failed.\n");
1270
	return E_FAIL;
1271 1272 1273
    } else {
	This->desc.picType = PICTYPE_ICON;
	This->desc.u.icon.hicon = hicon;
1274 1275 1276
	This->origWidth = cifd->idEntries[i].bWidth;
	This->origHeight = cifd->idEntries[i].bHeight;
	hdcRef = CreateCompatibleDC(0);
1277 1278
	This->himetricWidth = xpixels_to_himetric(cifd->idEntries[i].bWidth, hdcRef);
	This->himetricHeight= ypixels_to_himetric(cifd->idEntries[i].bHeight, hdcRef);
1279
	DeleteDC(hdcRef);
1280
	return S_OK;
1281
    }
1282 1283
}

1284 1285
static HRESULT OLEPictureImpl_LoadEnhMetafile(OLEPictureImpl *This,
                                              const BYTE *data, ULONG size)
1286 1287
{
    HENHMETAFILE hemf;
1288
    ENHMETAHEADER hdr;
1289 1290 1291 1292

    hemf = SetEnhMetaFileBits(size, data);
    if (!hemf) return E_FAIL;

1293 1294
    GetEnhMetaFileHeader(hemf, sizeof(hdr), &hdr);

1295 1296 1297 1298 1299
    This->desc.picType = PICTYPE_ENHMETAFILE;
    This->desc.u.emf.hemf = hemf;

    This->origWidth = 0;
    This->origHeight = 0;
1300 1301
    This->himetricWidth = hdr.rclFrame.right - hdr.rclFrame.left;
    This->himetricHeight = hdr.rclFrame.bottom - hdr.rclFrame.top;
1302 1303 1304 1305

    return S_OK;
}

1306 1307 1308
static HRESULT OLEPictureImpl_LoadAPM(OLEPictureImpl *This,
                                      const BYTE *data, ULONG size)
{
1309
    const APM_HEADER *header = (const APM_HEADER *)data;
1310
    HMETAFILE hmf;
1311 1312 1313 1314 1315 1316

    if (size < sizeof(APM_HEADER))
        return E_FAIL;
    if (header->key != 0x9ac6cdd7)
        return E_FAIL;

1317 1318 1319
    /* SetMetaFileBitsEx performs data check on its own */
    hmf = SetMetaFileBitsEx(size - sizeof(*header), data + sizeof(*header));
    if (!hmf) return E_FAIL;
1320

1321 1322 1323 1324 1325 1326 1327
    This->desc.picType = PICTYPE_METAFILE;
    This->desc.u.wmf.hmeta = hmf;
    This->desc.u.wmf.xExt = 0;
    This->desc.u.wmf.yExt = 0;

    This->origWidth = 0;
    This->origHeight = 0;
1328 1329 1330 1331 1332
    This->himetricWidth = MulDiv((INT)header->right - header->left, 2540, header->inch);
    This->himetricHeight = MulDiv((INT)header->bottom - header->top, 2540, header->inch);
    return S_OK;
}

1333 1334 1335 1336 1337 1338 1339 1340
/************************************************************************
 * OLEPictureImpl_IPersistStream_Load (IUnknown)
 *
 * Loads the binary data from the IStream. Starts at current position.
 * There appears to be an 2 DWORD header:
 * 	DWORD magic;
 * 	DWORD len;
 *
1341
 * Currently implemented: BITMAP, ICON, CURSOR, JPEG, GIF, WMF, EMF
1342
 */
1343
static HRESULT WINAPI OLEPictureImpl_Load(IPersistStream* iface, IStream *pStm) {
1344
  HRESULT	hr;
1345
  BOOL		headerisdata;
1346 1347
  BOOL		statfailed = FALSE;
  ULONG		xread, toread;
1348
  ULONG 	headerread;
1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372
  BYTE 		*xbuf;
  DWORD		header[2];
  WORD		magic;
  STATSTG       statstg;
  OLEPictureImpl *This = impl_from_IPersistStream(iface);
  
  TRACE("(%p,%p)\n",This,pStm);

  /****************************************************************************************
   * Part 1: Load the data
   */
  /* Sometimes we have a header, sometimes we don't. Apply some guesses to find
   * out whether we do.
   *
   * UPDATE: the IStream can be mapped to a plain file instead of a stream in a
   * compound file. This may explain most, if not all, of the cases of "no
   * header", and the header validation should take this into account.
   * At least in Visual Basic 6, resource streams, valid headers are
   *    header[0] == "lt\0\0",
   *    header[1] == length_of_stream.
   *
   * Also handle streams where we do not have a working "Stat" method by
   * reading all data until the end of the stream.
   */
1373 1374
  hr = IStream_Stat(pStm,&statstg,STATFLAG_NONAME);
  if (hr != S_OK) {
1375
      TRACE("stat failed with hres %x, proceeding to read all data.\n",hr);
1376 1377 1378 1379 1380
      statfailed = TRUE;
      /* we will read at least 8 byte ... just right below */
      statstg.cbSize.QuadPart = 8;
  }

1381 1382
  toread = 0;
  headerread = 0;
1383
  headerisdata = FALSE;
1384
  do {
1385 1386
      hr = IStream_Read(pStm, header, 8, &xread);
      if (hr != S_OK || xread!=8) {
1387
          ERR("Failure while reading picture header (hr is %x, nread is %d).\n",hr,xread);
1388
          return (hr?hr:E_FAIL);
1389 1390 1391
      }
      headerread += xread;
      xread = 0;
1392

1393 1394 1395 1396
      if (!memcmp(&(header[0]),"lt\0\0", 4) && (statfailed || (header[1] + headerread <= statstg.cbSize.QuadPart))) {
          if (toread != 0 && toread != header[1]) 
              FIXME("varying lengths of image data (prev=%u curr=%u), only last one will be used\n",
                  toread, header[1]);
1397
          toread = header[1];
1398 1399 1400 1401 1402
          if (statfailed)
          {
              statstg.cbSize.QuadPart = header[1] + 8;
              statfailed = FALSE;
          }
1403 1404 1405 1406 1407
          if (toread == 0) break;
      } else {
          if (!memcmp(&(header[0]), "GIF8",     4) ||   /* GIF header */
              !memcmp(&(header[0]), "BM",       2) ||   /* BMP header */
              !memcmp(&(header[0]), "\xff\xd8", 2) ||   /* JPEG header */
1408
              (header[0] == EMR_HEADER)            ||   /* EMF header */
1409 1410
              (header[0] == 0x10000)               ||   /* icon: idReserved 0, idType 1 */
              (header[0] == 0x20000)               ||   /* cursor: idReserved 0, idType 2 */
1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422
              (header[1] > statstg.cbSize.QuadPart)||   /* invalid size */
              (header[1]==0)
          ) {/* Found start of bitmap data */
              headerisdata = TRUE;
              if (toread == 0) 
              	  toread = statstg.cbSize.QuadPart-8;
              else toread -= 8;
              xread = 8;
          } else {
              FIXME("Unknown stream header magic: %08x\n", header[0]);
              toread = header[1];
          }
1423
      }
1424
  } while (!headerisdata);
1425 1426

  if (statfailed) { /* we don't know the size ... read all we get */
1427 1428
      unsigned int sizeinc = 4096;
      unsigned int origsize = sizeinc;
1429 1430 1431 1432 1433
      ULONG nread = 42;

      TRACE("Reading all data from stream.\n");
      xbuf = HeapAlloc (GetProcessHeap(), HEAP_ZERO_MEMORY, origsize);
      if (headerisdata)
1434
          memcpy (xbuf, header, 8);
1435 1436 1437
      while (1) {
          while (xread < origsize) {
              hr = IStream_Read(pStm,xbuf+xread,origsize-xread,&nread);
1438 1439
              xread += nread;
              if (hr != S_OK || !nread)
1440 1441
                  break;
          }
1442
          if (!nread || hr != S_OK) /* done, or error */
1443 1444 1445 1446 1447 1448 1449
              break;
          if (xread == origsize) {
              origsize += sizeinc;
              sizeinc = 2*sizeinc; /* exponential increase */
              xbuf = HeapReAlloc (GetProcessHeap(), HEAP_ZERO_MEMORY, xbuf, origsize);
          }
      }
1450
      if (hr != S_OK)
1451 1452
          TRACE("hr in no-stat loader case is %08x\n", hr);
      TRACE("loaded %d bytes.\n", xread);
1453 1454 1455 1456 1457
      This->datalen = xread;
      This->data    = xbuf;
  } else {
      This->datalen = toread+(headerisdata?8:0);
      xbuf = This->data = HeapAlloc (GetProcessHeap(), HEAP_ZERO_MEMORY, This->datalen);
1458 1459
      if (!xbuf)
          return E_OUTOFMEMORY;
1460 1461

      if (headerisdata)
1462
          memcpy (xbuf, header, 8);
1463 1464 1465 1466

      while (xread < This->datalen) {
          ULONG nread;
          hr = IStream_Read(pStm,xbuf+xread,This->datalen-xread,&nread);
1467 1468
          xread += nread;
          if (hr != S_OK || !nread)
1469 1470 1471
              break;
      }
      if (xread != This->datalen)
1472
          ERR("Could only read %d of %d bytes out of stream?\n",xread,This->datalen);
1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484
  }
  if (This->datalen == 0) { /* Marks the "NONE" picture */
      This->desc.picType = PICTYPE_NONE;
      return S_OK;
  }


  /****************************************************************************************
   * Part 2: Process the loaded data
   */

  magic = xbuf[0] + (xbuf[1]<<8);
1485 1486
  This->loadtime_format = magic;

1487
  switch (magic) {
1488
  case BITMAP_FORMAT_GIF: /* GIF */
1489
    hr = OLEPictureImpl_LoadWICDecoder(This, &CLSID_WICGifDecoder, xbuf, xread);
1490
    break;
1491
  case BITMAP_FORMAT_JPEG: /* JPEG */
1492
    hr = OLEPictureImpl_LoadWICDecoder(This, &CLSID_WICJpegDecoder, xbuf, xread);
1493
    break;
1494
  case BITMAP_FORMAT_BMP: /* Bitmap */
1495 1496
    hr = OLEPictureImpl_LoadDIB(This, xbuf, xread);
    break;
1497
  case BITMAP_FORMAT_PNG: /* PNG */
1498
    hr = OLEPictureImpl_LoadWICDecoder(This, &CLSID_WICPngDecoder, xbuf, xread);
1499
    break;
1500
  case BITMAP_FORMAT_APM: /* APM */
1501 1502
    hr = OLEPictureImpl_LoadAPM(This, xbuf, xread);
    break;
1503
  case 0x0000: { /* ICON or CURSOR, first word is dwReserved */
1504
    hr = OLEPictureImpl_LoadIcon(This, xbuf, xread);
1505 1506 1507
    break;
  }
  default:
1508
  {
1509
    unsigned int i;
1510

1511 1512
    /* let's see if it's a EMF */
    hr = OLEPictureImpl_LoadEnhMetafile(This, xbuf, xread);
1513 1514
    if (hr == S_OK) break;

1515
    FIXME("Unknown magic %04x, %d read bytes:\n",magic,xread);
1516
    hr=E_FAIL;
1517
    for (i=0;i<xread+8;i++) {
1518
	if (i<8) MESSAGE("%02x ",((unsigned char*)header)[i]);
1519 1520 1521 1522
	else MESSAGE("%02x ",xbuf[i-8]);
        if (i % 10 == 9) MESSAGE("\n");
    }
    MESSAGE("\n");
1523 1524
    break;
  }
1525
  }
1526
  This->bIsDirty = FALSE;
1527 1528 1529 1530 1531 1532 1533

  /* FIXME: this notify is not really documented */
  if (hr==S_OK)
      OLEPicture_SendNotify(This,DISPID_PICT_TYPE);
  return hr;
}

1534
static BOOL serializeBMP(HBITMAP hBitmap, void ** ppBuffer, unsigned int * pLength)
1535
{
1536
    BOOL success = FALSE;
1537 1538 1539 1540 1541 1542 1543
    HDC hDC;
    BITMAPINFO * pInfoBitmap;
    int iNumPaletteEntries;
    unsigned char * pPixelData;
    BITMAPFILEHEADER * pFileHeader;
    BITMAPINFO * pInfoHeader;

1544
    pInfoBitmap = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1545 1546 1547 1548 1549 1550 1551 1552 1553
        sizeof(BITMAPINFOHEADER) + 256 * sizeof(RGBQUAD));

    /* Find out bitmap size and padded length */
    hDC = GetDC(0);
    pInfoBitmap->bmiHeader.biSize = sizeof(pInfoBitmap->bmiHeader);
    GetDIBits(hDC, hBitmap, 0, 0, NULL, pInfoBitmap, DIB_RGB_COLORS);

    /* Fetch bitmap palette & pixel data */

1554
    pPixelData = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, pInfoBitmap->bmiHeader.biSizeImage);
1555 1556 1557
    GetDIBits(hDC, hBitmap, 0, pInfoBitmap->bmiHeader.biHeight, pPixelData, pInfoBitmap, DIB_RGB_COLORS);

    /* Calculate the total length required for the BMP data */
1558 1559 1560 1561 1562 1563 1564 1565 1566
    if (pInfoBitmap->bmiHeader.biClrUsed != 0) {
	iNumPaletteEntries = pInfoBitmap->bmiHeader.biClrUsed;
	if (iNumPaletteEntries > 256) iNumPaletteEntries = 256;
    } else {
	if (pInfoBitmap->bmiHeader.biBitCount <= 8)
	    iNumPaletteEntries = 1 << pInfoBitmap->bmiHeader.biBitCount;
	else
    	    iNumPaletteEntries = 0;
    }
1567 1568 1569 1570 1571
    *pLength =
        sizeof(BITMAPFILEHEADER) +
        sizeof(BITMAPINFOHEADER) +
        iNumPaletteEntries * sizeof(RGBQUAD) +
        pInfoBitmap->bmiHeader.biSizeImage;
1572
    *ppBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, *pLength);
1573 1574

    /* Fill the BITMAPFILEHEADER */
1575
    pFileHeader = *ppBuffer;
1576
    pFileHeader->bfType = BITMAP_FORMAT_BMP;
1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591
    pFileHeader->bfSize = *pLength;
    pFileHeader->bfOffBits =
        sizeof(BITMAPFILEHEADER) +
        sizeof(BITMAPINFOHEADER) +
        iNumPaletteEntries * sizeof(RGBQUAD);

    /* Fill the BITMAPINFOHEADER and the palette data */
    pInfoHeader = (BITMAPINFO *)((unsigned char *)(*ppBuffer) + sizeof(BITMAPFILEHEADER));
    memcpy(pInfoHeader, pInfoBitmap, sizeof(BITMAPINFOHEADER) + iNumPaletteEntries * sizeof(RGBQUAD));
    memcpy(
        (unsigned char *)(*ppBuffer) +
            sizeof(BITMAPFILEHEADER) +
            sizeof(BITMAPINFOHEADER) +
            iNumPaletteEntries * sizeof(RGBQUAD),
        pPixelData, pInfoBitmap->bmiHeader.biSizeImage);
1592
    success = TRUE;
1593 1594 1595

    HeapFree(GetProcessHeap(), 0, pPixelData);
    HeapFree(GetProcessHeap(), 0, pInfoBitmap);
1596
    return success;
1597 1598
}

1599
static BOOL serializeIcon(HICON hIcon, void ** ppBuffer, unsigned int * pLength)
1600 1601
{
	ICONINFO infoIcon;
1602
        BOOL success = FALSE;
1603 1604 1605 1606 1607 1608 1609 1610

	*ppBuffer = NULL; *pLength = 0;
	if (GetIconInfo(hIcon, &infoIcon)) {
		HDC hDC;
		BITMAPINFO * pInfoBitmap;
		unsigned char * pIconData = NULL;
		unsigned int iDataSize = 0;

1611
        pInfoBitmap = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(BITMAPINFOHEADER) + 256 * sizeof(RGBQUAD));
1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637

		/* Find out icon size */
		hDC = GetDC(0);
		pInfoBitmap->bmiHeader.biSize = sizeof(pInfoBitmap->bmiHeader);
		GetDIBits(hDC, infoIcon.hbmColor, 0, 0, NULL, pInfoBitmap, DIB_RGB_COLORS);
		if (1) {
			/* Auxiliary pointers */
			CURSORICONFILEDIR * pIconDir;
			CURSORICONFILEDIRENTRY * pIconEntry;
			BITMAPINFOHEADER * pIconBitmapHeader;
			unsigned int iOffsetPalette;
			unsigned int iOffsetColorData;
			unsigned int iOffsetMaskData;

			unsigned int iLengthScanLineMask;
			unsigned int iNumEntriesPalette;

			iLengthScanLineMask = ((pInfoBitmap->bmiHeader.biWidth + 31) >> 5) << 2;
/*
			FIXME("DEBUG: bitmap size is %d x %d\n",
				pInfoBitmap->bmiHeader.biWidth,
				pInfoBitmap->bmiHeader.biHeight);
			FIXME("DEBUG: bitmap bpp is %d\n",
				pInfoBitmap->bmiHeader.biBitCount);
			FIXME("DEBUG: bitmap nplanes is %d\n",
				pInfoBitmap->bmiHeader.biPlanes);
1638
			FIXME("DEBUG: bitmap biSizeImage is %u\n",
1639 1640 1641 1642
				pInfoBitmap->bmiHeader.biSizeImage);
*/
			/* Let's start with one CURSORICONFILEDIR and one CURSORICONFILEDIRENTRY */
			iDataSize += 3 * sizeof(WORD) + sizeof(CURSORICONFILEDIRENTRY) + sizeof(BITMAPINFOHEADER);
1643
			pIconData = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, iDataSize);
1644 1645 1646 1647 1648

			/* Fill out the CURSORICONFILEDIR */
			pIconDir = (CURSORICONFILEDIR *)pIconData;
			pIconDir->idType = 1;
			pIconDir->idCount = 1;
1649
			pIconDir->idReserved = 0;
1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665

			/* Fill out the CURSORICONFILEDIRENTRY */
			pIconEntry = (CURSORICONFILEDIRENTRY *)(pIconData + 3 * sizeof(WORD));
			pIconEntry->bWidth = (unsigned char)pInfoBitmap->bmiHeader.biWidth;
			pIconEntry->bHeight = (unsigned char)pInfoBitmap->bmiHeader.biHeight;
			pIconEntry->bColorCount =
				(pInfoBitmap->bmiHeader.biBitCount < 8)
				? 1 << pInfoBitmap->bmiHeader.biBitCount
				: 0;
			pIconEntry->xHotspot = pInfoBitmap->bmiHeader.biPlanes;
			pIconEntry->yHotspot = pInfoBitmap->bmiHeader.biBitCount;
			pIconEntry->dwDIBSize = 0;
			pIconEntry->dwDIBOffset = 3 * sizeof(WORD) + sizeof(CURSORICONFILEDIRENTRY);

			/* Fill out the BITMAPINFOHEADER */
			pIconBitmapHeader = (BITMAPINFOHEADER *)(pIconData + 3 * sizeof(WORD) + sizeof(CURSORICONFILEDIRENTRY));
1666
			*pIconBitmapHeader = pInfoBitmap->bmiHeader;
1667 1668 1669 1670 1671 1672

			/*	Find out whether a palette exists for the bitmap */
			if (	(pInfoBitmap->bmiHeader.biBitCount == 16 && pInfoBitmap->bmiHeader.biCompression == BI_RGB)
				||	(pInfoBitmap->bmiHeader.biBitCount == 24)
				||	(pInfoBitmap->bmiHeader.biBitCount == 32 && pInfoBitmap->bmiHeader.biCompression == BI_RGB)) {
				iNumEntriesPalette = pInfoBitmap->bmiHeader.biClrUsed;
1673
				if (iNumEntriesPalette > 256) iNumEntriesPalette = 256; 
1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691
			} else if ((pInfoBitmap->bmiHeader.biBitCount == 16 || pInfoBitmap->bmiHeader.biBitCount == 32)
				&& pInfoBitmap->bmiHeader.biCompression == BI_BITFIELDS) {
				iNumEntriesPalette = 3;
			} else if (pInfoBitmap->bmiHeader.biBitCount <= 8) {
				iNumEntriesPalette = 1 << pInfoBitmap->bmiHeader.biBitCount;
			} else {
				iNumEntriesPalette = 0;
			}

			/*  Add bitmap size and header size to icon data size. */
			iOffsetPalette = iDataSize;
			iDataSize += iNumEntriesPalette * sizeof(DWORD);
			iOffsetColorData = iDataSize;
			iDataSize += pIconBitmapHeader->biSizeImage;
			iOffsetMaskData = iDataSize;
			iDataSize += pIconBitmapHeader->biHeight * iLengthScanLineMask;
			pIconBitmapHeader->biSizeImage += pIconBitmapHeader->biHeight * iLengthScanLineMask;
			pIconBitmapHeader->biHeight *= 2;
1692
			pIconData = HeapReAlloc(GetProcessHeap(), 0, pIconData, iDataSize);
1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713
			pIconEntry = (CURSORICONFILEDIRENTRY *)(pIconData + 3 * sizeof(WORD));
			pIconBitmapHeader = (BITMAPINFOHEADER *)(pIconData + 3 * sizeof(WORD) + sizeof(CURSORICONFILEDIRENTRY));
			pIconEntry->dwDIBSize = iDataSize - (3 * sizeof(WORD) + sizeof(CURSORICONFILEDIRENTRY));

			/* Get the actual bitmap data from the icon bitmap */
			GetDIBits(hDC, infoIcon.hbmColor, 0, pInfoBitmap->bmiHeader.biHeight,
				pIconData + iOffsetColorData, pInfoBitmap, DIB_RGB_COLORS);
			if (iNumEntriesPalette > 0) {
				memcpy(pIconData + iOffsetPalette, pInfoBitmap->bmiColors,
					iNumEntriesPalette * sizeof(RGBQUAD));
			}

			/* Reset all values so that GetDIBits call succeeds */
			memset(pIconData + iOffsetMaskData, 0, iDataSize - iOffsetMaskData);
			memset(pInfoBitmap, 0, sizeof(BITMAPINFOHEADER) + 256 * sizeof(RGBQUAD));
			pInfoBitmap->bmiHeader.biSize = sizeof(pInfoBitmap->bmiHeader);
/*
            if (!(GetDIBits(hDC, infoIcon.hbmMask, 0, 0, NULL, pInfoBitmap, DIB_RGB_COLORS)
				&& GetDIBits(hDC, infoIcon.hbmMask, 0, pIconEntry->bHeight,
					pIconData + iOffsetMaskData, pInfoBitmap, DIB_RGB_COLORS))) {

1714
                printf("ERROR: unable to get bitmap mask (error %u)\n",
1715 1716 1717 1718 1719 1720 1721 1722 1723
					GetLastError());

			}
*/
            GetDIBits(hDC, infoIcon.hbmMask, 0, 0, NULL, pInfoBitmap, DIB_RGB_COLORS);
            GetDIBits(hDC, infoIcon.hbmMask, 0, pIconEntry->bHeight, pIconData + iOffsetMaskData, pInfoBitmap, DIB_RGB_COLORS);

			/* Write out everything produced so far to the stream */
			*ppBuffer = pIconData; *pLength = iDataSize;
1724
                        success = TRUE;
1725 1726
		} else {
/*
1727
			printf("ERROR: unable to get bitmap information via GetDIBits() (error %u)\n",
1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743
				GetLastError());
*/
		}
		/*
			Remarks (from MSDN entry on GetIconInfo):

			GetIconInfo creates bitmaps for the hbmMask and hbmColor
			members of ICONINFO. The calling application must manage
			these bitmaps and delete them when they are no longer
			necessary.
		 */
		if (hDC) ReleaseDC(0, hDC);
		DeleteObject(infoIcon.hbmMask);
		if (infoIcon.hbmColor) DeleteObject(infoIcon.hbmColor);
		HeapFree(GetProcessHeap(), 0, pInfoBitmap);
	} else {
1744
		printf("ERROR: Unable to get icon information (error %u)\n",
1745 1746
			GetLastError());
	}
1747
        return success;
1748 1749
}

1750 1751 1752 1753 1754 1755
static HRESULT WINAPI OLEPictureImpl_Save(
  IPersistStream* iface,IStream*pStm,BOOL fClearDirty)
{
    HRESULT hResult = E_NOTIMPL;
    void * pIconData;
    unsigned int iDataSize;
1756
    DWORD header[2];
1757
    ULONG dummy;
1758
    BOOL serializeResult = FALSE;
1759
    OLEPictureImpl *This = impl_from_IPersistStream(iface);
1760

1761
    TRACE("%p %p %d\n", This, pStm, fClearDirty);
1762 1763

    switch (This->desc.picType) {
1764 1765 1766 1767 1768 1769
    case PICTYPE_NONE:
        header[0] = 0x0000746c;
        header[1] = 0;
        hResult = IStream_Write(pStm, header, 2 * sizeof(DWORD), &dummy);
        break;

1770
    case PICTYPE_ICON:
1771 1772 1773
        if (This->bIsDirty || !This->data) {
            if (!serializeIcon(This->desc.u.icon.hicon, &pIconData, &iDataSize)) {
                ERR("(%p,%p,%d), serializeIcon() failed\n", This, pStm, fClearDirty);
1774
                hResult = E_FAIL;
1775
                break;
1776
            }
1777
            HeapFree(GetProcessHeap(), 0, This->data);
1778 1779 1780
            This->data = pIconData;
            This->datalen = iDataSize;
        }
1781

1782 1783 1784
        header[0] = (This->loadtime_magic != 0xdeadbeef) ? This->loadtime_magic : 0x0000746c;
        header[1] = This->datalen;
        IStream_Write(pStm, header, 2 * sizeof(DWORD), &dummy);
1785 1786
        IStream_Write(pStm, This->data, This->datalen, &dummy);
        hResult = S_OK;
1787 1788
        break;
    case PICTYPE_BITMAP:
1789
        if (This->bIsDirty || !This->data) {
1790 1791
            switch (This->keepOrigFormat ? This->loadtime_format : BITMAP_FORMAT_BMP) {
            case BITMAP_FORMAT_BMP:
1792
                serializeResult = serializeBMP(This->desc.u.bmp.hbitmap, &pIconData, &iDataSize);
1793
                break;
1794
            case BITMAP_FORMAT_JPEG:
1795 1796
                FIXME("(%p,%p,%d), PICTYPE_BITMAP (format JPEG) not implemented!\n",This,pStm,fClearDirty);
                break;
1797
            case BITMAP_FORMAT_GIF:
1798 1799
                FIXME("(%p,%p,%d), PICTYPE_BITMAP (format GIF) not implemented!\n",This,pStm,fClearDirty);
                break;
1800
            case BITMAP_FORMAT_PNG:
1801 1802
                FIXME("(%p,%p,%d), PICTYPE_BITMAP (format PNG) not implemented!\n",This,pStm,fClearDirty);
                break;
1803 1804 1805 1806
            default:
                FIXME("(%p,%p,%d), PICTYPE_BITMAP (format UNKNOWN, using BMP?) not implemented!\n",This,pStm,fClearDirty);
                break;
            }
1807

1808
            if (!serializeResult)
1809 1810 1811
            {
                hResult = E_FAIL;
                break;
1812
            }
1813 1814 1815 1816

            HeapFree(GetProcessHeap(), 0, This->data);
            This->data = pIconData;
            This->datalen = iDataSize;
1817
        }
1818 1819 1820 1821 1822 1823

        header[0] = (This->loadtime_magic != 0xdeadbeef) ? This->loadtime_magic : 0x0000746c;
        header[1] = This->datalen;
        IStream_Write(pStm, header, 2 * sizeof(DWORD), &dummy);
        IStream_Write(pStm, This->data, This->datalen, &dummy);
        hResult = S_OK;
1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838
        break;
    case PICTYPE_METAFILE:
        FIXME("(%p,%p,%d), PICTYPE_METAFILE not implemented!\n",This,pStm,fClearDirty);
        break;
    case PICTYPE_ENHMETAFILE:
        FIXME("(%p,%p,%d),PICTYPE_ENHMETAFILE not implemented!\n",This,pStm,fClearDirty);
        break;
    default:
        FIXME("(%p,%p,%d), [unknown type] not implemented!\n",This,pStm,fClearDirty);
        break;
    }
    if (hResult == S_OK && fClearDirty) This->bIsDirty = FALSE;
    return hResult;
}

1839 1840 1841
static HRESULT WINAPI OLEPictureImpl_GetSizeMax(
  IPersistStream* iface,ULARGE_INTEGER*pcbSize)
{
1842
  OLEPictureImpl *This = impl_from_IPersistStream(iface);
1843 1844 1845
  FIXME("(%p,%p),stub!\n",This,pcbSize);
  return E_NOTIMPL;
}
1846

1847

1848 1849 1850
/************************************************************************
 *    IDispatch
 */
1851

1852 1853 1854 1855 1856 1857 1858 1859 1860 1861
/************************************************************************
 * OLEPictureImpl_IDispatch_QueryInterface (IUnknown)
 *
 * See Windows documentation for more details on IUnknown methods.
 */
static HRESULT WINAPI OLEPictureImpl_IDispatch_QueryInterface(
  IDispatch* iface,
  REFIID     riid,
  VOID**     ppvoid)
{
1862
  OLEPictureImpl *This = impl_from_IDispatch(iface);
1863

1864
  return IPicture_QueryInterface(&This->IPicture_iface, riid, ppvoid);
1865 1866 1867 1868 1869 1870 1871 1872 1873 1874
}

/************************************************************************
 * OLEPictureImpl_IDispatch_AddRef (IUnknown)
 *
 * See Windows documentation for more details on IUnknown methods.
 */
static ULONG WINAPI OLEPictureImpl_IDispatch_AddRef(
  IDispatch* iface)
{
1875
  OLEPictureImpl *This = impl_from_IDispatch(iface);
1876

1877
  return IPicture_AddRef(&This->IPicture_iface);
1878 1879 1880 1881 1882 1883 1884 1885 1886 1887
}

/************************************************************************
 * OLEPictureImpl_IDispatch_Release (IUnknown)
 *
 * See Windows documentation for more details on IUnknown methods.
 */
static ULONG WINAPI OLEPictureImpl_IDispatch_Release(
  IDispatch* iface)
{
1888
  OLEPictureImpl *This = impl_from_IDispatch(iface);
1889

1890
  return IPicture_Release(&This->IPicture_iface);
1891 1892 1893 1894 1895 1896 1897 1898
}

/************************************************************************
 * OLEPictureImpl_GetTypeInfoCount (IDispatch)
 *
 * See Windows documentation for more details on IDispatch methods.
 */
static HRESULT WINAPI OLEPictureImpl_GetTypeInfoCount(
1899
  IDispatch*    iface,
1900 1901
  unsigned int* pctinfo)
{
1902
  TRACE("(%p)\n", pctinfo);
1903

1904 1905 1906
  *pctinfo = 1;

  return S_OK;
1907 1908 1909 1910 1911 1912 1913 1914
}

/************************************************************************
 * OLEPictureImpl_GetTypeInfo (IDispatch)
 *
 * See Windows documentation for more details on IDispatch methods.
 */
static HRESULT WINAPI OLEPictureImpl_GetTypeInfo(
1915
  IDispatch*  iface,
1916
  UINT      iTInfo,
1917
  LCID        lcid,
1918 1919
  ITypeInfo** ppTInfo)
{
1920 1921 1922
  static const WCHAR stdole2tlb[] = {'s','t','d','o','l','e','2','.','t','l','b',0};
  ITypeLib *tl;
  HRESULT hres;
1923

1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937
  TRACE("(iTInfo=%d, lcid=%04x, %p)\n", iTInfo, (int)lcid, ppTInfo);

  if (iTInfo != 0)
    return E_FAIL;

  hres = LoadTypeLib(stdole2tlb, &tl);
  if (FAILED(hres))
  {
    ERR("Could not load stdole2.tlb\n");
    return hres;
  }

  hres = ITypeLib_GetTypeInfoOfGuid(tl, &IID_IPictureDisp, ppTInfo);
  if (FAILED(hres))
1938
    ERR("Did not get IPictureDisp typeinfo from typelib, hres %x\n", hres);
1939 1940

  return hres;
1941 1942 1943 1944 1945 1946 1947 1948 1949
}

/************************************************************************
 * OLEPictureImpl_GetIDsOfNames (IDispatch)
 *
 * See Windows documentation for more details on IDispatch methods.
 */
static HRESULT WINAPI OLEPictureImpl_GetIDsOfNames(
  IDispatch*  iface,
1950 1951 1952
  REFIID      riid,
  LPOLESTR* rgszNames,
  UINT      cNames,
1953 1954 1955
  LCID        lcid,
  DISPID*     rgDispId)
{
1956 1957
  ITypeInfo * pTInfo;
  HRESULT hres;
1958

1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982
  TRACE("(%p,%s,%p,cNames=%d,lcid=%04x,%p)\n", iface, debugstr_guid(riid),
        rgszNames, cNames, (int)lcid, rgDispId);

  if (cNames == 0)
  {
    return E_INVALIDARG;
  }
  else
  {
    /* retrieve type information */
    hres = OLEPictureImpl_GetTypeInfo(iface, 0, lcid, &pTInfo);

    if (FAILED(hres))
    {
      ERR("GetTypeInfo failed.\n");
      return hres;
    }

    /* convert names to DISPIDs */
    hres = DispGetIDsOfNames (pTInfo, rgszNames, cNames, rgDispId);
    ITypeInfo_Release(pTInfo);

    return hres;
  }
1983 1984 1985 1986 1987 1988 1989 1990 1991
}

/************************************************************************
 * OLEPictureImpl_Invoke (IDispatch)
 *
 * See Windows documentation for more details on IDispatch methods.
 */
static HRESULT WINAPI OLEPictureImpl_Invoke(
  IDispatch*  iface,
1992 1993 1994
  DISPID      dispIdMember,
  REFIID      riid,
  LCID        lcid,
1995 1996
  WORD        wFlags,
  DISPPARAMS* pDispParams,
1997
  VARIANT*    pVarResult,
1998 1999 2000
  EXCEPINFO*  pExepInfo,
  UINT*     puArgErr)
{
2001
  OLEPictureImpl *This = impl_from_IDispatch(iface);
2002
  HRESULT hr;
2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019

  /* validate parameters */

  if (!IsEqualIID(riid, &IID_NULL))
  {
    ERR("riid was %s instead of IID_NULL\n", debugstr_guid(riid));
    return DISP_E_UNKNOWNNAME;
  }

  if (!pDispParams)
  {
    ERR("null pDispParams not allowed\n");
    return DISP_E_PARAMNOTOPTIONAL;
  }

  if (wFlags & DISPATCH_PROPERTYGET)
  {
2020 2021 2022 2023 2024
    if (pDispParams->cArgs != 0)
    {
      ERR("param count for DISPATCH_PROPERTYGET was %d instead of 0\n", pDispParams->cArgs);
      return DISP_E_BADPARAMCOUNT;
    }
2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039
    if (!pVarResult)
    {
      ERR("null pVarResult not allowed when DISPATCH_PROPERTYGET specified\n");
      return DISP_E_PARAMNOTOPTIONAL;
    }
  }
  else if (wFlags & DISPATCH_PROPERTYPUT)
  {
    if (pDispParams->cArgs != 1)
    {
      ERR("param count for DISPATCH_PROPERTYPUT was %d instead of 1\n", pDispParams->cArgs);
      return DISP_E_BADPARAMCOUNT;
    }
  }

2040
  switch (dispIdMember)
2041
  {
2042 2043
  case DISPID_PICT_HANDLE:
    if (wFlags & DISPATCH_PROPERTYGET)
2044
    {
2045 2046
      TRACE("DISPID_PICT_HANDLE\n");
      V_VT(pVarResult) = VT_I4;
2047
      return IPicture_get_Handle(&This->IPicture_iface, &V_UINT(pVarResult));
2048
    }
2049 2050 2051 2052 2053 2054
    break;
  case DISPID_PICT_HPAL:
    if (wFlags & DISPATCH_PROPERTYGET)
    {
      TRACE("DISPID_PICT_HPAL\n");
      V_VT(pVarResult) = VT_I4;
2055
      return IPicture_get_hPal(&This->IPicture_iface, &V_UINT(pVarResult));
2056
    }
2057 2058 2059
    else if (wFlags & DISPATCH_PROPERTYPUT)
    {
      VARIANTARG vararg;
2060

2061 2062 2063 2064 2065 2066 2067
      TRACE("DISPID_PICT_HPAL\n");

      VariantInit(&vararg);
      hr = VariantChangeTypeEx(&vararg, &pDispParams->rgvarg[0], lcid, 0, VT_I4);
      if (FAILED(hr))
        return hr;

2068
      hr = IPicture_set_hPal(&This->IPicture_iface, V_I4(&vararg));
2069 2070 2071 2072

      VariantClear(&vararg);
      return hr;
    }
2073 2074 2075 2076 2077 2078
    break;
  case DISPID_PICT_TYPE:
    if (wFlags & DISPATCH_PROPERTYGET)
    {
      TRACE("DISPID_PICT_TYPE\n");
      V_VT(pVarResult) = VT_I2;
2079
      return OLEPictureImpl_get_Type(&This->IPicture_iface, &V_I2(pVarResult));
2080 2081 2082 2083 2084 2085 2086
    }
    break;
  case DISPID_PICT_WIDTH:
    if (wFlags & DISPATCH_PROPERTYGET)
    {
      TRACE("DISPID_PICT_WIDTH\n");
      V_VT(pVarResult) = VT_I4;
2087
      return IPicture_get_Width(&This->IPicture_iface, &V_I4(pVarResult));
2088 2089 2090 2091 2092 2093 2094
    }
    break;
  case DISPID_PICT_HEIGHT:
    if (wFlags & DISPATCH_PROPERTYGET)
    {
      TRACE("DISPID_PICT_HEIGHT\n");
      V_VT(pVarResult) = VT_I4;
2095
      return IPicture_get_Height(&This->IPicture_iface, &V_I4(pVarResult));
2096 2097
    }
    break;
2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131
  case DISPID_PICT_RENDER:
    if (wFlags & DISPATCH_METHOD)
    {
      VARIANTARG *args = pDispParams->rgvarg;
      int i;

      TRACE("DISPID_PICT_RENDER\n");

      if (pDispParams->cArgs != 10)
        return DISP_E_BADPARAMCOUNT;

      /* All parameters are supposed to be VT_I4 (on 64 bits too). */
      for (i = 0; i < pDispParams->cArgs; i++)
        if (V_VT(&args[i]) != VT_I4)
        {
          ERR("DISPID_PICT_RENDER: wrong argument type %d:%d\n", i, V_VT(&args[i]));
          return DISP_E_TYPEMISMATCH;
        }

      /* FIXME: rectangle pointer argument handling seems broken on 64 bits,
                currently Render() doesn't use it at all so for now NULL is passed. */
      return IPicture_Render(&This->IPicture_iface,
                LongToHandle(V_I4(&args[9])),
                             V_I4(&args[8]),
                             V_I4(&args[7]),
                             V_I4(&args[6]),
                             V_I4(&args[5]),
                             V_I4(&args[4]),
                             V_I4(&args[3]),
                             V_I4(&args[2]),
                             V_I4(&args[1]),
                                      NULL);
    }
    break;
2132
  }
2133

2134
  ERR("invalid dispid 0x%x or wFlags 0x%x\n", dispIdMember, wFlags);
2135
  return DISP_E_MEMBERNOTFOUND;
2136 2137 2138
}


2139
static const IPictureVtbl OLEPictureImpl_VTable =
2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159
{
  OLEPictureImpl_QueryInterface,
  OLEPictureImpl_AddRef,
  OLEPictureImpl_Release,
  OLEPictureImpl_get_Handle,
  OLEPictureImpl_get_hPal,
  OLEPictureImpl_get_Type,
  OLEPictureImpl_get_Width,
  OLEPictureImpl_get_Height,
  OLEPictureImpl_Render,
  OLEPictureImpl_set_hPal,
  OLEPictureImpl_get_CurDC,
  OLEPictureImpl_SelectPicture,
  OLEPictureImpl_get_KeepOriginalFormat,
  OLEPictureImpl_put_KeepOriginalFormat,
  OLEPictureImpl_PictureChanged,
  OLEPictureImpl_SaveAsFile,
  OLEPictureImpl_get_Attributes
};

2160
static const IDispatchVtbl OLEPictureImpl_IDispatch_VTable =
2161 2162 2163 2164 2165 2166 2167 2168 2169 2170
{
  OLEPictureImpl_IDispatch_QueryInterface,
  OLEPictureImpl_IDispatch_AddRef,
  OLEPictureImpl_IDispatch_Release,
  OLEPictureImpl_GetTypeInfoCount,
  OLEPictureImpl_GetTypeInfo,
  OLEPictureImpl_GetIDsOfNames,
  OLEPictureImpl_Invoke
};

2171
static const IPersistStreamVtbl OLEPictureImpl_IPersistStream_VTable =
2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182
{
  OLEPictureImpl_IPersistStream_QueryInterface,
  OLEPictureImpl_IPersistStream_AddRef,
  OLEPictureImpl_IPersistStream_Release,
  OLEPictureImpl_GetClassID,
  OLEPictureImpl_IsDirty,
  OLEPictureImpl_Load,
  OLEPictureImpl_Save,
  OLEPictureImpl_GetSizeMax
};

2183
static const IConnectionPointContainerVtbl OLEPictureImpl_IConnectionPointContainer_VTable =
2184 2185 2186 2187 2188 2189 2190 2191
{
  OLEPictureImpl_IConnectionPointContainer_QueryInterface,
  OLEPictureImpl_IConnectionPointContainer_AddRef,
  OLEPictureImpl_IConnectionPointContainer_Release,
  OLEPictureImpl_EnumConnectionPoints,
  OLEPictureImpl_FindConnectionPoint
};

2192
/***********************************************************************
2193
 * OleCreatePictureIndirect (OLEAUT32.419)
2194 2195
 */
HRESULT WINAPI OleCreatePictureIndirect(LPPICTDESC lpPictDesc, REFIID riid,
2196
		            BOOL Own, void **ppvObj )
2197
{
2198 2199
  OLEPictureImpl* newPict;
  HRESULT hr;
2200

2201
  TRACE("(%p,%s,%d,%p)\n", lpPictDesc, debugstr_guid(riid), Own, ppvObj);
2202 2203 2204

  *ppvObj = NULL;

2205
  newPict = OLEPictureImpl_Construct(lpPictDesc, Own);
2206 2207 2208 2209 2210 2211 2212

  if (newPict == NULL)
    return E_OUTOFMEMORY;

  /*
   * Make sure it supports the interface required by the caller.
   */
2213
  hr = IPicture_QueryInterface(&newPict->IPicture_iface, riid, ppvObj);
2214 2215 2216 2217 2218

  /*
   * Release the reference obtained in the constructor. If
   * the QueryInterface was unsuccessful, it will free the class.
   */
2219
  IPicture_Release(&newPict->IPicture_iface);
2220 2221 2222 2223 2224 2225

  return hr;
}


/***********************************************************************
2226
 * OleLoadPicture (OLEAUT32.418)
2227 2228
 */
HRESULT WINAPI OleLoadPicture( LPSTREAM lpstream, LONG lSize, BOOL fRunmode,
2229
		            REFIID riid, LPVOID *ppvObj )
2230
{
2231 2232 2233 2234
  LPPERSISTSTREAM ps;
  IPicture	*newpic;
  HRESULT hr;

2235
  TRACE("(%p,%d,%d,%s,%p), partially implemented.\n",
2236 2237 2238
	lpstream, lSize, fRunmode, debugstr_guid(riid), ppvObj);

  hr = OleCreatePictureIndirect(NULL,riid,!fRunmode,(LPVOID*)&newpic);
2239
  if (hr != S_OK)
2240 2241
    return hr;
  hr = IPicture_QueryInterface(newpic,&IID_IPersistStream, (LPVOID*)&ps);
2242
  if (hr != S_OK) {
2243
      ERR("Could not get IPersistStream iface from Ole Picture?\n");
2244 2245 2246 2247
      IPicture_Release(newpic);
      *ppvObj = NULL;
      return hr;
  }
2248
  hr = IPersistStream_Load(ps,lpstream);
2249
  IPersistStream_Release(ps);
2250 2251 2252 2253 2254 2255 2256
  if (FAILED(hr))
  {
      ERR("IPersistStream_Load failed\n");
      IPicture_Release(newpic);
      *ppvObj = NULL;
      return hr;
  }
2257
  hr = IPicture_QueryInterface(newpic,riid,ppvObj);
2258
  if (hr != S_OK)
2259
      ERR("Failed to get interface %s from IPicture.\n",debugstr_guid(riid));
2260 2261
  IPicture_Release(newpic);
  return hr;
2262
}
2263 2264

/***********************************************************************
2265
 * OleLoadPictureEx (OLEAUT32.401)
2266 2267
 */
HRESULT WINAPI OleLoadPictureEx( LPSTREAM lpstream, LONG lSize, BOOL fRunmode,
2268
		            REFIID riid, DWORD xsiz, DWORD ysiz, DWORD flags, LPVOID *ppvObj )
2269
{
2270 2271 2272 2273
  LPPERSISTSTREAM ps;
  IPicture	*newpic;
  HRESULT hr;

2274
  FIXME("(%p,%d,%d,%s,x=%d,y=%d,f=%x,%p), partially implemented.\n",
2275 2276 2277
	lpstream, lSize, fRunmode, debugstr_guid(riid), xsiz, ysiz, flags, ppvObj);

  hr = OleCreatePictureIndirect(NULL,riid,!fRunmode,(LPVOID*)&newpic);
2278
  if (hr != S_OK)
2279 2280
    return hr;
  hr = IPicture_QueryInterface(newpic,&IID_IPersistStream, (LPVOID*)&ps);
2281
  if (hr != S_OK) {
2282
      ERR("Could not get IPersistStream iface from Ole Picture?\n");
2283 2284 2285 2286
      IPicture_Release(newpic);
      *ppvObj = NULL;
      return hr;
  }
2287
  hr = IPersistStream_Load(ps,lpstream);
2288
  IPersistStream_Release(ps);
2289 2290 2291 2292 2293 2294 2295
  if (FAILED(hr))
  {
      ERR("IPersistStream_Load failed\n");
      IPicture_Release(newpic);
      *ppvObj = NULL;
      return hr;
  }
2296
  hr = IPicture_QueryInterface(newpic,riid,ppvObj);
2297
  if (hr != S_OK)
2298
      ERR("Failed to get interface %s from IPicture.\n",debugstr_guid(riid));
2299 2300
  IPicture_Release(newpic);
  return hr;
2301
}
2302

2303 2304 2305 2306 2307 2308 2309 2310 2311
/***********************************************************************
 * OleSavePictureFile (OLEAUT32.423)
 */
HRESULT WINAPI OleSavePictureFile(IDispatch *picture, BSTR filename)
{
  FIXME("(%p %s): stub\n", picture, debugstr_w(filename));
  return CTL_E_FILENOTFOUND;
}

2312 2313 2314 2315 2316 2317 2318
/***********************************************************************
 * OleLoadPicturePath (OLEAUT32.424)
 */
HRESULT WINAPI OleLoadPicturePath( LPOLESTR szURLorPath, LPUNKNOWN punkCaller,
		DWORD dwReserved, OLE_COLOR clrReserved, REFIID riid,
		LPVOID *ppvRet )
{
2319
  static const WCHAR file[] = { 'f','i','l','e',':',0 };
2320 2321 2322 2323
  IPicture *ipicture;
  HANDLE hFile;
  DWORD dwFileSize;
  HGLOBAL hGlobal = NULL;
2324
  DWORD dwBytesRead;
2325 2326 2327 2328
  IStream *stream;
  BOOL bRead;
  IPersistStream *pStream;
  HRESULT hRes;
2329
  HRESULT init_res;
2330 2331
  WCHAR *file_candidate;
  WCHAR path_buf[MAX_PATH];
2332

2333
  TRACE("(%s,%p,%d,%08x,%s,%p): stub\n",
2334 2335 2336
        debugstr_w(szURLorPath), punkCaller, dwReserved, clrReserved,
        debugstr_guid(riid), ppvRet);

2337 2338 2339 2340
  if (!szURLorPath || !ppvRet)
      return E_INVALIDARG;

  *ppvRet = NULL;
2341

2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358
  /* Convert file URLs to DOS paths. */
  if (strncmpW(szURLorPath, file, 5) == 0) {
      DWORD size;
      hRes = CoInternetParseUrl(szURLorPath, PARSE_PATH_FROM_URL, 0, path_buf,
                                sizeof(path_buf)/sizeof(WCHAR), &size, 0);
      if (FAILED(hRes))
          return hRes;

      file_candidate = path_buf;
  }
  else
      file_candidate = szURLorPath;

  /* Handle candidate DOS paths separately. */
  if (file_candidate[1] == ':') {
      hFile = CreateFileW(file_candidate, GENERIC_READ, 0, NULL, OPEN_EXISTING,
                          0, NULL);
2359
      if (hFile == INVALID_HANDLE_VALUE)
2360
          return INET_E_RESOURCE_NOT_FOUND;
2361 2362 2363 2364 2365 2366 2367

      dwFileSize = GetFileSize(hFile, NULL);
      if (dwFileSize != INVALID_FILE_SIZE )
      {
	  hGlobal = GlobalAlloc(GMEM_FIXED,dwFileSize);
	  if ( hGlobal)
	  {
2368
	      bRead = ReadFile(hFile, hGlobal, dwFileSize, &dwBytesRead, NULL) && dwBytesRead == dwFileSize;
2369 2370 2371 2372 2373 2374 2375 2376 2377 2378
	      if (!bRead)
	      {
		  GlobalFree(hGlobal);
		  hGlobal = 0;
	      }
	  }
      }
      CloseHandle(hFile);
      
      if (!hGlobal)
2379
	  return INET_E_RESOURCE_NOT_FOUND;
2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405

      hRes = CreateStreamOnHGlobal(hGlobal, TRUE, &stream);
      if (FAILED(hRes)) 
      {
	  GlobalFree(hGlobal);
	  return hRes;
      }
  } else {
      IMoniker *pmnk;
      IBindCtx *pbc;

      hRes = CreateBindCtx(0, &pbc);
      if (SUCCEEDED(hRes)) 
      {
	  hRes = CreateURLMoniker(NULL, szURLorPath, &pmnk);
	  if (SUCCEEDED(hRes))
	  {	         
	      hRes = IMoniker_BindToStorage(pmnk, pbc, NULL, &IID_IStream, (LPVOID*)&stream);
	      IMoniker_Release(pmnk);
	  }
	  IBindCtx_Release(pbc);
      }
      if (FAILED(hRes))
	  return hRes;
  }

2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423
  init_res = CoInitialize(NULL);

  hRes = CoCreateInstance(&CLSID_StdPicture, punkCaller, CLSCTX_INPROC_SERVER,
                          &IID_IPicture, (LPVOID*)&ipicture);
  if (SUCCEEDED(hRes)) {
      hRes = IPicture_QueryInterface(ipicture, &IID_IPersistStream, (LPVOID*)&pStream);

      if (SUCCEEDED(hRes)) {
          hRes = IPersistStream_Load(pStream, stream);

          if (SUCCEEDED(hRes)) {
              hRes = IPicture_QueryInterface(ipicture, riid, ppvRet);

              if (FAILED(hRes))
                  ERR("Failed to get interface %s from IPicture.\n", debugstr_guid(riid));
          }
          IPersistStream_Release(pStream);
      }
2424 2425 2426 2427 2428
      IPicture_Release(ipicture);
  }

  IStream_Release(stream);

2429 2430
  if (SUCCEEDED(init_res))
      CoUninitialize();
2431 2432

  return hRes;
2433 2434
}

2435 2436 2437 2438 2439 2440
/*******************************************************************************
 * StdPic ClassFactory
 */
typedef struct
{
    /* IUnknown fields */
2441 2442
    IClassFactory IClassFactory_iface;
    LONG          ref;
2443 2444
} IClassFactoryImpl;

2445 2446 2447 2448 2449
static inline IClassFactoryImpl *impl_from_IClassFactory(IClassFactory *iface)
{
       return CONTAINING_RECORD(iface, IClassFactoryImpl, IClassFactory_iface);
}

2450 2451
static HRESULT WINAPI
SPCF_QueryInterface(LPCLASSFACTORY iface,REFIID riid,LPVOID *ppobj) {
2452
	IClassFactoryImpl *This = impl_from_IClassFactory(iface);
2453 2454 2455 2456 2457 2458 2459

	FIXME("(%p)->(%s,%p),stub!\n",This,debugstr_guid(riid),ppobj);
	return E_NOINTERFACE;
}

static ULONG WINAPI
SPCF_AddRef(LPCLASSFACTORY iface) {
2460
	IClassFactoryImpl *This = impl_from_IClassFactory(iface);
2461
	return InterlockedIncrement(&This->ref);
2462 2463 2464
}

static ULONG WINAPI SPCF_Release(LPCLASSFACTORY iface) {
2465
	IClassFactoryImpl *This = impl_from_IClassFactory(iface);
2466
	/* static class, won't be  freed */
2467
	return InterlockedDecrement(&This->ref);
2468 2469 2470 2471 2472
}

static HRESULT WINAPI SPCF_CreateInstance(
	LPCLASSFACTORY iface,LPUNKNOWN pOuter,REFIID riid,LPVOID *ppobj
) {
2473 2474
    /* Creates an uninitialized picture */
    return OleCreatePictureIndirect(NULL,riid,TRUE,ppobj);
2475 2476 2477 2478

}

static HRESULT WINAPI SPCF_LockServer(LPCLASSFACTORY iface,BOOL dolock) {
2479
	IClassFactoryImpl *This = impl_from_IClassFactory(iface);
2480 2481 2482 2483
	FIXME("(%p)->(%d),stub!\n",This,dolock);
	return S_OK;
}

2484
static const IClassFactoryVtbl SPCF_Vtbl = {
2485 2486 2487 2488 2489 2490
	SPCF_QueryInterface,
	SPCF_AddRef,
	SPCF_Release,
	SPCF_CreateInstance,
	SPCF_LockServer
};
2491
static IClassFactoryImpl STDPIC_CF = {{&SPCF_Vtbl}, 1 };
2492

2493
void _get_STDPIC_CF(LPVOID *ppv) { *ppv = &STDPIC_CF; }