datacache.c 64.1 KB
Newer Older
1 2 3 4
/*
 *	OLE 2 Data cache
 *
 *      Copyright 1999  Francis Beaudet
5
 *      Copyright 2000  Abey George
6
 *
7 8 9 10 11 12 13 14 15 16 17 18
 * 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
19
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20
 *
21 22 23 24 25 26
 * NOTES:
 *    The OLE2 data cache supports a whole whack of
 *    interfaces including:
 *       IDataObject, IPersistStorage, IViewObject2,
 *       IOleCache2 and IOleCacheControl.
 *
27
 *    Most of the implementation details are taken from: Inside OLE
28 29
 *    second edition by Kraig Brockschmidt,
 *
30 31 32
 * NOTES
 *  -  This implementation of the datacache will let your application
 *     load documents that have embedded OLE objects in them and it will
33
 *     also retrieve the metafile representation of those objects.
34 35
 *  -  This implementation of the datacache will also allow your
 *     application to save new documents with OLE objects in them.
36
 *  -  The main thing that it doesn't do is allow you to activate
37 38 39 40
 *     or modify the OLE objects in any way.
 *  -  I haven't found any good documentation on the real usage of
 *     the streams created by the data cache. In particular, How to
 *     determine what the XXX stands for in the stream name
41
 *     "\002OlePresXXX". It appears to just be a counter.
42
 *  -  Also, I don't know the real content of the presentation stream
43
 *     header. I was able to figure-out where the extent of the object
44
 *     was stored and the aspect, but that's about it.
45
 */
46
#include <stdarg.h>
47
#include <string.h>
48

49
#define COBJMACROS
50 51
#define NONAMELESSUNION
#define NONAMELESSSTRUCT
52

53
#include "windef.h"
54
#include "winbase.h"
55
#include "wingdi.h"
56
#include "winuser.h"
57
#include "winerror.h"
58
#include "wine/unicode.h"
59
#include "ole2.h"
60
#include "wine/list.h"
61
#include "wine/debug.h"
62

63
WINE_DEFAULT_DEBUG_CHANNEL(ole);
64 65

/****************************************************************************
66 67 68 69
 * PresentationDataHeader
 *
 * This structure represents the header of the \002OlePresXXX stream in
 * the OLE object strorage.
70
 */
71
typedef struct PresentationDataHeader
72
{
73 74 75 76 77 78 79 80
  /* clipformat:
   *  - standard clipformat:
   *  DWORD length = 0xffffffff;
   *  DWORD cfFormat;
   *  - or custom clipformat:
   *  DWORD length;
   *  CHAR format_name[length]; (null-terminated)
   */
81 82
  DWORD unknown3;	/* 4, possibly TYMED_ISTREAM */
  DVASPECT dvAspect;
83 84
  DWORD lindex;
  DWORD tymed;
85
  DWORD unknown7;	/* 0 */
86 87 88
  DWORD dwObjectExtentX;
  DWORD dwObjectExtentY;
  DWORD dwSize;
89
} PresentationDataHeader;
90

91 92 93 94 95
typedef struct DataCacheEntry
{
  struct list entry;
  /* format of this entry */
  FORMATETC fmtetc;
96 97
  /* the clipboard format of the data */
  CLIPFORMAT data_cf;
98 99
  /* cached data */
  STGMEDIUM stgmedium;
100 101 102 103 104 105
  /*
   * This storage pointer is set through a call to
   * IPersistStorage_Load. This is where the visual
   * representation of the object is stored.
   */
  IStorage *storage;
106
  /* connection ID */
107
  DWORD id;
108 109
  /* dirty flag */
  BOOL dirty;
110 111
  /* stream number (-1 if not set ) */
  unsigned short stream_number;
112 113
} DataCacheEntry;

114 115 116 117 118 119 120 121
/****************************************************************************
 * DataCache
 */
struct DataCache
{
  /*
   * List all interface VTables here
   */
122 123 124 125 126 127
  const IDataObjectVtbl*      lpVtbl;
  const IUnknownVtbl*         lpvtblNDIUnknown;
  const IPersistStorageVtbl*  lpvtblIPersistStorage;
  const IViewObject2Vtbl*     lpvtblIViewObject;
  const IOleCache2Vtbl*       lpvtblIOleCache2;
  const IOleCacheControlVtbl* lpvtblIOleCacheControl;
128 129 130 131

  /*
   * Reference count of this object
   */
132
  LONG ref;
133 134 135 136 137 138

  /*
   * IUnknown implementation of the outer object.
   */
  IUnknown* outerUnknown;

139 140 141 142 143 144 145 146
  /*
   * The user of this object can setup ONE advise sink
   * connection with the object. These parameters describe
   * that connection.
   */
  DWORD        sinkAspects;
  DWORD        sinkAdviseFlag;
  IAdviseSink* sinkInterface;
147
  IStorage *presentationStorage;
148

149
  /* list of cache entries */
150
  struct list cache_list;
151
  /* last id assigned to an entry */
152
  DWORD last_cache_id;
153 154
  /* dirty flag */
  BOOL dirty;
155 156 157 158 159
};

typedef struct DataCache DataCache;

/*
160
 * Here, I define utility macros to help with the casting of the
161
 * "this" parameter.
162
 * There is a version to accommodate all of the VTables implemented
163 164
 * by this object.
 */
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

static inline DataCache *impl_from_IDataObject( IDataObject *iface )
{
    return (DataCache *)((char*)iface - FIELD_OFFSET(DataCache, lpVtbl));
}

static inline DataCache *impl_from_NDIUnknown( IUnknown *iface )
{
    return (DataCache *)((char*)iface - FIELD_OFFSET(DataCache, lpvtblNDIUnknown));
}

static inline DataCache *impl_from_IPersistStorage( IPersistStorage *iface )
{
    return (DataCache *)((char*)iface - FIELD_OFFSET(DataCache, lpvtblIPersistStorage));
}

static inline DataCache *impl_from_IViewObject2( IViewObject2 *iface )
{
    return (DataCache *)((char*)iface - FIELD_OFFSET(DataCache, lpvtblIViewObject));
}

static inline DataCache *impl_from_IOleCache2( IOleCache2 *iface )
{
    return (DataCache *)((char*)iface - FIELD_OFFSET(DataCache, lpvtblIOleCache2));
}

static inline DataCache *impl_from_IOleCacheControl( IOleCacheControl *iface )
{
    return (DataCache *)((char*)iface - FIELD_OFFSET(DataCache, lpvtblIOleCacheControl));
}

196
static const char * debugstr_formatetc(const FORMATETC *formatetc)
197
{
198 199 200
    return wine_dbg_sprintf("{ cfFormat = 0x%x, ptd = %p, dwAspect = %d, lindex = %d, tymed = %d }",
        formatetc->cfFormat, formatetc->ptd, formatetc->dwAspect,
        formatetc->lindex, formatetc->tymed);
201
}
202 203 204 205 206 207

/*
 * Prototypes for the methods of the DataCache class.
 */
static DataCache* DataCache_Construct(REFCLSID  clsid,
				      LPUNKNOWN pUnkOuter);
208
static HRESULT    DataCacheEntry_OpenPresStream(DataCacheEntry *This,
209
					   IStream  **pStm);
210

211 212 213 214 215 216
static void DataCacheEntry_Destroy(DataCacheEntry *This)
{
    list_remove(&This->entry);
    if (This->storage)
        IStorage_Release(This->storage);
    HeapFree(GetProcessHeap(), 0, This->fmtetc.ptd);
217
    ReleaseStgMedium(&This->stgmedium);
218 219 220
    HeapFree(GetProcessHeap(), 0, This);
}

221 222 223
static void DataCache_Destroy(
  DataCache* ptrToDestroy)
{
224 225
  DataCacheEntry *cache_entry, *next_cache_entry;

226
  TRACE("()\n");
227 228 229 230 231 232 233

  if (ptrToDestroy->sinkInterface != NULL)
  {
    IAdviseSink_Release(ptrToDestroy->sinkInterface);
    ptrToDestroy->sinkInterface = NULL;
  }

234
  LIST_FOR_EACH_ENTRY_SAFE(cache_entry, next_cache_entry, &ptrToDestroy->cache_list, DataCacheEntry, entry)
235
    DataCacheEntry_Destroy(cache_entry);
236 237 238 239 240 241 242

  /*
   * Free the datacache pointer.
   */
  HeapFree(GetProcessHeap(), 0, ptrToDestroy);
}

243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
static DataCacheEntry *DataCache_GetEntryForFormatEtc(DataCache *This, const FORMATETC *formatetc)
{
    DataCacheEntry *cache_entry;
    LIST_FOR_EACH_ENTRY(cache_entry, &This->cache_list, DataCacheEntry, entry)
    {
        /* FIXME: also compare DVTARGETDEVICEs */
        if ((!cache_entry->fmtetc.cfFormat || !formatetc->cfFormat || (formatetc->cfFormat == cache_entry->fmtetc.cfFormat)) &&
            (formatetc->dwAspect == cache_entry->fmtetc.dwAspect) &&
            (formatetc->lindex == cache_entry->fmtetc.lindex) &&
            (!cache_entry->fmtetc.tymed || !formatetc->tymed || (formatetc->tymed == cache_entry->fmtetc.tymed)))
            return cache_entry;
    }
    return NULL;
}

258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
/* checks that the clipformat and tymed are valid and returns an error if they
* aren't and CACHE_S_NOTSUPPORTED if they are valid, but can't be rendered by
* DataCache_Draw */
static HRESULT check_valid_clipformat_and_tymed(CLIPFORMAT cfFormat, DWORD tymed)
{
    if (!cfFormat || !tymed ||
        (cfFormat == CF_METAFILEPICT && tymed == TYMED_MFPICT) ||
        (cfFormat == CF_BITMAP && tymed == TYMED_GDI) ||
        (cfFormat == CF_DIB && tymed == TYMED_HGLOBAL) ||
        (cfFormat == CF_ENHMETAFILE && tymed == TYMED_ENHMF))
        return S_OK;
    else if (tymed == TYMED_HGLOBAL)
        return CACHE_S_FORMATETC_NOTSUPPORTED;
    else
    {
        WARN("invalid clipformat/tymed combination: %d/%d\n", cfFormat, tymed);
        return DV_E_TYMED;
    }
}

278 279
static HRESULT DataCache_CreateEntry(DataCache *This, const FORMATETC *formatetc, DataCacheEntry **cache_entry)
{
280 281 282 283 284 285 286 287
    HRESULT hr;

    hr = check_valid_clipformat_and_tymed(formatetc->cfFormat, formatetc->tymed);
    if (FAILED(hr))
        return hr;
    if (hr == CACHE_S_FORMATETC_NOTSUPPORTED)
        TRACE("creating unsupported format %d\n", formatetc->cfFormat);

288
    *cache_entry = HeapAlloc(GetProcessHeap(), 0, sizeof(**cache_entry));
289 290 291
    if (!*cache_entry)
        return E_OUTOFMEMORY;

292 293 294 295 296 297
    (*cache_entry)->fmtetc = *formatetc;
    if (formatetc->ptd)
    {
        (*cache_entry)->fmtetc.ptd = HeapAlloc(GetProcessHeap(), 0, formatetc->ptd->tdSize);
        memcpy((*cache_entry)->fmtetc.ptd, formatetc->ptd, formatetc->ptd->tdSize);
    }
298 299
    (*cache_entry)->stgmedium.tymed = TYMED_NULL;
    (*cache_entry)->stgmedium.pUnkForRelease = NULL;
300
    (*cache_entry)->storage = NULL;
301
    (*cache_entry)->id = This->last_cache_id++;
302
    (*cache_entry)->dirty = TRUE;
303
    (*cache_entry)->stream_number = -1;
304
    list_add_tail(&This->cache_list, &(*cache_entry)->entry);
305
    return hr;
306 307
}

308 309 310 311 312 313 314 315 316 317 318 319 320
/************************************************************************
 * DataCache_FireOnViewChange
 *
 * This method will fire an OnViewChange notification to the advise
 * sink registered with the datacache.
 *
 * See IAdviseSink::OnViewChange for more details.
 */
static void DataCache_FireOnViewChange(
  DataCache* this,
  DWORD      aspect,
  LONG       lindex)
{
321
  TRACE("(%p, %x, %d)\n", this, aspect, lindex);
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

  /*
   * The sink supplies a filter when it registers
   * we make sure we only send the notifications when that
   * filter matches.
   */
  if ((this->sinkAspects & aspect) != 0)
  {
    if (this->sinkInterface != NULL)
    {
      IAdviseSink_OnViewChange(this->sinkInterface,
			       aspect,
			       lindex);

      /*
       * Some sinks want to be unregistered automatically when
       * the first notification goes out.
       */
      if ( (this->sinkAdviseFlag & ADVF_ONLYONCE) != 0)
      {
	IAdviseSink_Release(this->sinkInterface);

	this->sinkInterface  = NULL;
	this->sinkAspects    = 0;
	this->sinkAdviseFlag = 0;
      }
    }
  }
}

352
/* Helper for DataCacheEntry_OpenPresStream */
353 354 355 356 357 358 359 360 361
static BOOL DataCache_IsPresentationStream(const STATSTG *elem)
{
    /* The presentation streams have names of the form "\002OlePresXXX",
     * where XXX goes from 000 to 999. */
    static const WCHAR OlePres[] = { 2,'O','l','e','P','r','e','s' };

    LPCWSTR name = elem->pwcsName;

    return (elem->type == STGTY_STREAM)
362 363
	&& (strlenW(name) == 11)
	&& (strncmpW(name, OlePres, 8) == 0)
364 365 366
	&& (name[8] >= '0') && (name[8] <= '9')
	&& (name[9] >= '0') && (name[9] <= '9')
	&& (name[10] >= '0') && (name[10] <= '9');
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
static HRESULT read_clipformat(IStream *stream, CLIPFORMAT *clipformat)
{
    DWORD length;
    HRESULT hr;
    ULONG read;

    *clipformat = 0;

    hr = IStream_Read(stream, &length, sizeof(length), &read);
    if (hr != S_OK || read != sizeof(length))
        return DV_E_CLIPFORMAT;
    if (length == -1)
    {
        DWORD cf;
        hr = IStream_Read(stream, &cf, sizeof(cf), 0);
        if (hr != S_OK || read != sizeof(cf))
            return DV_E_CLIPFORMAT;
        *clipformat = cf;
    }
    else
    {
        char *format_name = HeapAlloc(GetProcessHeap(), 0, length);
        if (!format_name)
            return E_OUTOFMEMORY;
        hr = IStream_Read(stream, format_name, length, &read);
        if (hr != S_OK || read != length || format_name[length - 1] != '\0')
        {
            HeapFree(GetProcessHeap(), 0, format_name);
            return DV_E_CLIPFORMAT;
        }
        *clipformat = RegisterClipboardFormatA(format_name);
        HeapFree(GetProcessHeap(), 0, format_name);
    }
    return S_OK;
}

static HRESULT write_clipformat(IStream *stream, CLIPFORMAT clipformat)
{
    DWORD length;
    HRESULT hr;

    if (clipformat < 0xc000)
        length = -1;
    else
        length = GetClipboardFormatNameA(clipformat, NULL, 0);
    hr = IStream_Write(stream, &length, sizeof(length), NULL);
    if (FAILED(hr))
        return hr;
    if (clipformat < 0xc000)
    {
        DWORD cf = clipformat;
        hr = IStream_Write(stream, &cf, sizeof(cf), NULL);
    }
    else
    {
        char *format_name = HeapAlloc(GetProcessHeap(), 0, length);
        if (!format_name)
            return E_OUTOFMEMORY;
        GetClipboardFormatNameA(clipformat, format_name, length);
        hr = IStream_Write(stream, format_name, length, NULL);
        HeapFree(GetProcessHeap(), 0, format_name);
    }
    return hr;
}

434
/************************************************************************
435
 * DataCacheEntry_OpenPresStream
436
 *
437 438
 * This method will find the stream for the given presentation. It makes
 * no attempt at fallback.
439 440 441 442
 *
 * Param:
 *   this       - Pointer to the DataCache object
 *   drawAspect - The aspect of the object that we wish to draw.
443 444 445 446 447 448 449
 *   pStm       - A returned stream. It points to the beginning of the
 *              - presentation data, including the header.
 *
 * Errors:
 *   S_OK		The requested stream has been opened.
 *   OLE_E_BLANK	The requested stream could not be found.
 *   Quite a few others I'm too lazy to map correctly.
450
 *
451 452 453
 * Notes:
 *   Algorithm:	Scan the elements of the presentation storage, looking
 *		for presentation streams. For each presentation stream,
454
 *		load the header and check to see if the aspect matches.
455 456 457
 *
 *   If a fallback is desired, just opening the first presentation stream
 *   is a possibility.
458
 */
459 460
static HRESULT DataCacheEntry_OpenPresStream(
  DataCacheEntry *This,
461
  IStream  **ppStm)
462
{
463 464 465
    STATSTG elem;
    IEnumSTATSTG *pEnum;
    HRESULT hr;
466

467
    if (!ppStm) return E_POINTER;
468

469
    hr = IStorage_EnumElements(This->storage, 0, NULL, 0, &pEnum);
470
    if (FAILED(hr)) return hr;
471

472 473 474 475 476 477
    while ((hr = IEnumSTATSTG_Next(pEnum, 1, &elem, NULL)) == S_OK)
    {
	if (DataCache_IsPresentationStream(&elem))
	{
	    IStream *pStm;

478
	    hr = IStorage_OpenStream(This->storage, elem.pwcsName,
479 480 481 482 483 484
				     NULL, STGM_READ | STGM_SHARE_EXCLUSIVE, 0,
				     &pStm);
	    if (SUCCEEDED(hr))
	    {
		PresentationDataHeader header;
		ULONG actual_read;
485 486 487
                CLIPFORMAT clipformat;

                hr = read_clipformat(pStm, &clipformat);
488

489 490
                if (hr == S_OK)
                    hr = IStream_Read(pStm, &header, sizeof(header), &actual_read);
491 492 493

		/* can't use SUCCEEDED(hr): S_FALSE counts as an error */
		if (hr == S_OK && actual_read == sizeof(header)
494
		    && header.dvAspect == This->fmtetc.dwAspect)
495 496 497
		{
		    /* Rewind the stream before returning it. */
		    LARGE_INTEGER offset;
498 499
		    offset.u.LowPart = 0;
		    offset.u.HighPart = 0;
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519
		    IStream_Seek(pStm, offset, STREAM_SEEK_SET, NULL);

		    *ppStm = pStm;

		    CoTaskMemFree(elem.pwcsName);
		    IEnumSTATSTG_Release(pEnum);

		    return S_OK;
		}

		IStream_Release(pStm);
	    }
	}

	CoTaskMemFree(elem.pwcsName);
    }

    IEnumSTATSTG_Release(pEnum);

    return (hr == S_FALSE ? OLE_E_BLANK : hr);
520 521 522
}

/************************************************************************
523
 * DataCacheEntry_LoadData
524
 *
525
 * This method will read information for the requested presentation
526 527 528
 * into the given structure.
 *
 * Param:
529
 *   This - The entry to load the data from.
530 531 532 533 534
 *
 * Returns:
 *   This method returns a metafile handle if it is successful.
 *   it will return 0 if not.
 */
535
static HRESULT DataCacheEntry_LoadData(DataCacheEntry *This)
536 537 538
{
  IStream*      presStream = NULL;
  HRESULT       hres;
539
  ULARGE_INTEGER current_pos;
540
  STATSTG       streamInfo;
541 542 543 544
  void*         metafileBits;
  METAFILEPICT *mfpict;
  HGLOBAL       hmfpict;
  PresentationDataHeader header;
545 546
  CLIPFORMAT    clipformat;
  static const LARGE_INTEGER offset_zero;
547 548

  /*
549
   * Open the presentation stream.
550
   */
551
  hres = DataCacheEntry_OpenPresStream(
552
           This,
553 554 555
	   &presStream);

  if (FAILED(hres))
556
    return hres;
557 558 559 560 561 562 563 564 565

  /*
   * Get the size of the stream.
   */
  hres = IStream_Stat(presStream,
		      &streamInfo,
		      STATFLAG_NONAME);

  /*
566
   * Read the header.
567 568
   */

569 570 571 572 573 574 575
  hres = read_clipformat(presStream, &clipformat);
  if (FAILED(hres))
  {
      IStream_Release(presStream);
      return hres;
  }

576 577 578 579 580
  hres = IStream_Read(
                      presStream,
                      &header,
                      sizeof(PresentationDataHeader),
                      NULL);
581 582 583 584 585 586 587
  if (hres != S_OK)
  {
      IStream_Release(presStream);
      return E_FAIL;
  }

  hres = IStream_Seek(presStream, offset_zero, STREAM_SEEK_CUR, &current_pos);
588

589
  streamInfo.cbSize.QuadPart -= current_pos.QuadPart;
590 591 592 593 594 595 596 597

  hmfpict = GlobalAlloc(GMEM_MOVEABLE, sizeof(METAFILEPICT));
  if (!hmfpict)
  {
      IStream_Release(presStream);
      return E_OUTOFMEMORY;
  }
  mfpict = GlobalLock(hmfpict);
598

599 600 601
  /*
   * Allocate a buffer for the metafile bits.
   */
602 603
  metafileBits = HeapAlloc(GetProcessHeap(),
			   0,
604
			   streamInfo.cbSize.u.LowPart);
605 606 607 608 609 610 611

  /*
   * Read the metafile bits.
   */
  hres = IStream_Read(
	   presStream,
	   metafileBits,
612
	   streamInfo.cbSize.u.LowPart,
613 614 615 616 617 618 619
	   NULL);

  /*
   * Create a metafile with those bits.
   */
  if (SUCCEEDED(hres))
  {
620 621 622 623 624 625 626 627 628 629 630 631
    /* FIXME: get this from the stream */
    mfpict->mm = MM_ANISOTROPIC;
    mfpict->xExt = header.dwObjectExtentX;
    mfpict->yExt = header.dwObjectExtentY;
    mfpict->hMF = SetMetaFileBitsEx(streamInfo.cbSize.u.LowPart, metafileBits);
    if (!mfpict->hMF)
      hres = E_FAIL;
  }

  GlobalUnlock(hmfpict);
  if (SUCCEEDED(hres))
  {
632
    This->data_cf = This->fmtetc.cfFormat;
633 634
    This->stgmedium.tymed = TYMED_MFPICT;
    This->stgmedium.u.hMetaFilePict = hmfpict;
635
  }
636 637
  else
    GlobalFree(hmfpict);
638 639 640 641 642 643 644

  /*
   * Cleanup.
   */
  HeapFree(GetProcessHeap(), 0, metafileBits);
  IStream_Release(presStream);

645
  return hres;
646 647
}

648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671
static HRESULT DataCacheEntry_CreateStream(DataCacheEntry *This,
                                           IStorage *storage, IStream **stream)
{
    HRESULT hr;
    WCHAR wszName[] = {2,'O','l','e','P','r','e','s',
        '0' + (This->stream_number / 100) % 10,
        '0' + (This->stream_number / 10) % 10,
        '0' + This->stream_number % 10, 0};

    /* FIXME: cache the created stream in This? */
    hr = IStorage_CreateStream(storage, wszName,
                               STGM_READWRITE | STGM_SHARE_EXCLUSIVE | STGM_CREATE,
                               0, 0, stream);
    return hr;
}

static HRESULT DataCacheEntry_Save(DataCacheEntry *This, IStorage *storage,
                                   BOOL same_as_load)
{
    PresentationDataHeader header;
    HRESULT hr;
    IStream *pres_stream;
    void *data = NULL;

672
    TRACE("stream_number = %d, fmtetc = %s\n", This->stream_number, debugstr_formatetc(&This->fmtetc));
673 674 675 676 677

    hr = DataCacheEntry_CreateStream(This, storage, &pres_stream);
    if (FAILED(hr))
        return hr;

678 679 680 681
    hr = write_clipformat(pres_stream, This->data_cf);
    if (FAILED(hr))
        return hr;

682 683 684 685 686
    if (This->fmtetc.ptd)
        FIXME("ptd not serialized\n");
    header.unknown3 = 4;
    header.dvAspect = This->fmtetc.dwAspect;
    header.lindex = This->fmtetc.lindex;
687
    header.tymed = This->stgmedium.tymed;
688 689 690 691 692 693
    header.unknown7 = 0;
    header.dwObjectExtentX = 0;
    header.dwObjectExtentY = 0;
    header.dwSize = 0;

    /* size the data */
694
    switch (This->data_cf)
695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728
    {
        case CF_METAFILEPICT:
        {
            if (This->stgmedium.tymed != TYMED_NULL)
            {
                const METAFILEPICT *mfpict = GlobalLock(This->stgmedium.u.hMetaFilePict);
                if (!mfpict)
                {
                    IStream_Release(pres_stream);
                    return DV_E_STGMEDIUM;
                }
                header.dwObjectExtentX = mfpict->xExt;
                header.dwObjectExtentY = mfpict->yExt;
                header.dwSize = GetMetaFileBitsEx(mfpict->hMF, 0, NULL);
                GlobalUnlock(This->stgmedium.u.hMetaFilePict);
            }
            break;
        }
        default:
            break;
    }

    /*
     * Write the header.
     */
    hr = IStream_Write(pres_stream, &header, sizeof(PresentationDataHeader),
                       NULL);
    if (FAILED(hr))
    {
        IStream_Release(pres_stream);
        return hr;
    }

    /* get the data */
729
    switch (This->data_cf)
730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757
    {
        case CF_METAFILEPICT:
        {
            if (This->stgmedium.tymed != TYMED_NULL)
            {
                const METAFILEPICT *mfpict = GlobalLock(This->stgmedium.u.hMetaFilePict);
                if (!mfpict)
                {
                    IStream_Release(pres_stream);
                    return DV_E_STGMEDIUM;
                }
                data = HeapAlloc(GetProcessHeap(), 0, header.dwSize);
                GetMetaFileBitsEx(mfpict->hMF, header.dwSize, data);
                GlobalUnlock(This->stgmedium.u.hMetaFilePict);
            }
            break;
        }
        default:
            break;
    }

    if (data)
        hr = IStream_Write(pres_stream, data, header.dwSize, NULL);

    IStream_Release(pres_stream);
    return hr;
}

758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797
/* helper for copying STGMEDIUM of type bitmap, MF, EMF or HGLOBAL.
* does no checking of whether src_stgm has a supported tymed, so this should be
* done in the caller */
static HRESULT copy_stg_medium(CLIPFORMAT cf, STGMEDIUM *dest_stgm,
                               const STGMEDIUM *src_stgm)
{
    if (src_stgm->tymed == TYMED_MFPICT)
    {
        const METAFILEPICT *src_mfpict = GlobalLock(src_stgm->u.hMetaFilePict);
        METAFILEPICT *dest_mfpict;

        if (!src_mfpict)
            return DV_E_STGMEDIUM;
        dest_stgm->u.hMetaFilePict = GlobalAlloc(GMEM_MOVEABLE, sizeof(METAFILEPICT));
        dest_mfpict = GlobalLock(dest_stgm->u.hMetaFilePict);
        if (!dest_mfpict)
        {
            GlobalUnlock(src_stgm->u.hMetaFilePict);
            return E_OUTOFMEMORY;
        }
        *dest_mfpict = *src_mfpict;
        dest_mfpict->hMF = CopyMetaFileW(src_mfpict->hMF, NULL);
        GlobalUnlock(src_stgm->u.hMetaFilePict);
        GlobalUnlock(dest_stgm->u.hMetaFilePict);
    }
    else if (src_stgm->tymed != TYMED_NULL)
    {
        dest_stgm->u.hGlobal = OleDuplicateData(src_stgm->u.hGlobal, cf,
                                                GMEM_MOVEABLE);
        if (!dest_stgm->u.hGlobal)
            return E_OUTOFMEMORY;
    }
    dest_stgm->tymed = src_stgm->tymed;
    dest_stgm->pUnkForRelease = src_stgm->pUnkForRelease;
    if (dest_stgm->pUnkForRelease)
        IUnknown_AddRef(dest_stgm->pUnkForRelease);
    return S_OK;
}

static HRESULT DataCacheEntry_SetData(DataCacheEntry *This,
798 799 800
                                      const FORMATETC *formatetc,
                                      const STGMEDIUM *stgmedium,
                                      BOOL fRelease)
801
{
802 803 804 805 806 807 808 809
    if ((!This->fmtetc.cfFormat && !formatetc->cfFormat) ||
        (This->fmtetc.tymed == TYMED_NULL && formatetc->tymed == TYMED_NULL) ||
        stgmedium->tymed == TYMED_NULL)
    {
        WARN("invalid formatetc\n");
        return DV_E_FORMATETC;
    }

810
    This->dirty = TRUE;
811
    ReleaseStgMedium(&This->stgmedium);
812
    This->data_cf = This->fmtetc.cfFormat ? This->fmtetc.cfFormat : formatetc->cfFormat;
813 814 815 816 817 818
    if (fRelease)
    {
        This->stgmedium = *stgmedium;
        return S_OK;
    }
    else
819
        return copy_stg_medium(This->data_cf,
820 821 822
                               &This->stgmedium, stgmedium);
}

823 824 825 826 827 828 829 830 831 832 833 834 835 836
static HRESULT DataCacheEntry_GetData(DataCacheEntry *This,
                                      STGMEDIUM *stgmedium)
{
    if (stgmedium->tymed == TYMED_NULL && This->storage)
    {
        HRESULT hr = DataCacheEntry_LoadData(This);
        if (FAILED(hr))
            return hr;
    }
    if (stgmedium->tymed == TYMED_NULL)
        return OLE_E_BLANK;
    return copy_stg_medium(This->data_cf, stgmedium, &This->stgmedium);
}

837 838 839 840 841 842 843
static inline HRESULT DataCacheEntry_DiscardData(DataCacheEntry *This)
{
    ReleaseStgMedium(&This->stgmedium);
    This->data_cf = This->fmtetc.cfFormat;
    return S_OK;
}

844 845 846 847 848 849 850 851 852
static inline void DataCacheEntry_HandsOffStorage(DataCacheEntry *This)
{
    if (This->storage)
    {
        IStorage_Release(This->storage);
        This->storage = NULL;
    }
}

853 854 855 856 857 858
/*********************************************************
 * Method implementation for the  non delegating IUnknown
 * part of the DataCache class.
 */

/************************************************************************
859
 * DataCache_NDIUnknown_QueryInterface (IUnknown)
860 861 862 863 864 865 866 867 868 869 870
 *
 * See Windows documentation for more details on IUnknown methods.
 *
 * This version of QueryInterface will not delegate it's implementation
 * to the outer unknown.
 */
static HRESULT WINAPI DataCache_NDIUnknown_QueryInterface(
            IUnknown*      iface,
            REFIID         riid,
            void**         ppvObject)
{
871
  DataCache *this = impl_from_NDIUnknown(iface);
872 873 874 875 876 877

  /*
   * Perform a sanity check on the parameters.
   */
  if ( (this==0) || (ppvObject==0) )
    return E_INVALIDARG;
878

879 880 881 882 883 884 885 886
  /*
   * Initialize the return parameter.
   */
  *ppvObject = 0;

  /*
   * Compare the riid with the interface IDs implemented by this object.
   */
887
  if (memcmp(&IID_IUnknown, riid, sizeof(IID_IUnknown)) == 0)
888 889 890
  {
    *ppvObject = iface;
  }
891
  else if (memcmp(&IID_IDataObject, riid, sizeof(IID_IDataObject)) == 0)
892
  {
893
    *ppvObject = (IDataObject*)&(this->lpVtbl);
894 895 896 897
  }
  else if ( (memcmp(&IID_IPersistStorage, riid, sizeof(IID_IPersistStorage)) == 0)  ||
	    (memcmp(&IID_IPersist, riid, sizeof(IID_IPersist)) == 0) )
  {
898
    *ppvObject = (IPersistStorage*)&(this->lpvtblIPersistStorage);
899 900 901 902
  }
  else if ( (memcmp(&IID_IViewObject, riid, sizeof(IID_IViewObject)) == 0) ||
	    (memcmp(&IID_IViewObject2, riid, sizeof(IID_IViewObject2)) == 0) )
  {
903
    *ppvObject = (IViewObject2*)&(this->lpvtblIViewObject);
904 905 906 907
  }
  else if ( (memcmp(&IID_IOleCache, riid, sizeof(IID_IOleCache)) == 0) ||
	    (memcmp(&IID_IOleCache2, riid, sizeof(IID_IOleCache2)) == 0) )
  {
908
    *ppvObject = (IOleCache2*)&(this->lpvtblIOleCache2);
909
  }
910
  else if (memcmp(&IID_IOleCacheControl, riid, sizeof(IID_IOleCacheControl)) == 0)
911
  {
912
    *ppvObject = (IOleCacheControl*)&(this->lpvtblIOleCacheControl);
913 914 915 916 917 918 919
  }

  /*
   * Check that we obtained an interface.
   */
  if ((*ppvObject)==0)
  {
Andreas Mohr's avatar
Andreas Mohr committed
920
    WARN( "() : asking for unsupported interface %s\n", debugstr_guid(riid));
921 922
    return E_NOINTERFACE;
  }
923

924 925
  /*
   * Query Interface always increases the reference count by one when it is
926
   * successful.
927 928 929
   */
  IUnknown_AddRef((IUnknown*)*ppvObject);

930
  return S_OK;
931 932 933 934 935 936 937 938 939 940
}

/************************************************************************
 * DataCache_NDIUnknown_AddRef (IUnknown)
 *
 * See Windows documentation for more details on IUnknown methods.
 *
 * This version of QueryInterface will not delegate it's implementation
 * to the outer unknown.
 */
941
static ULONG WINAPI DataCache_NDIUnknown_AddRef(
942 943
            IUnknown*      iface)
{
944
  DataCache *this = impl_from_NDIUnknown(iface);
945
  return InterlockedIncrement(&this->ref);
946 947 948 949 950 951 952 953 954 955
}

/************************************************************************
 * DataCache_NDIUnknown_Release (IUnknown)
 *
 * See Windows documentation for more details on IUnknown methods.
 *
 * This version of QueryInterface will not delegate it's implementation
 * to the outer unknown.
 */
956
static ULONG WINAPI DataCache_NDIUnknown_Release(
957 958
            IUnknown*      iface)
{
959
  DataCache *this = impl_from_NDIUnknown(iface);
960
  ULONG ref;
961 962 963 964

  /*
   * Decrease the reference count on this object.
   */
965
  ref = InterlockedDecrement(&this->ref);
966 967 968 969

  /*
   * If the reference count goes down to 0, perform suicide.
   */
970
  if (ref == 0) DataCache_Destroy(this);
971

972
  return ref;
973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989
}

/*********************************************************
 * Method implementation for the IDataObject
 * part of the DataCache class.
 */

/************************************************************************
 * DataCache_IDataObject_QueryInterface (IUnknown)
 *
 * See Windows documentation for more details on IUnknown methods.
 */
static HRESULT WINAPI DataCache_IDataObject_QueryInterface(
            IDataObject*     iface,
            REFIID           riid,
            void**           ppvObject)
{
990
  DataCache *this = impl_from_IDataObject(iface);
991

992
  return IUnknown_QueryInterface(this->outerUnknown, riid, ppvObject);
993 994 995 996 997 998 999
}

/************************************************************************
 * DataCache_IDataObject_AddRef (IUnknown)
 *
 * See Windows documentation for more details on IUnknown methods.
 */
1000
static ULONG WINAPI DataCache_IDataObject_AddRef(
1001 1002
            IDataObject*     iface)
{
1003
  DataCache *this = impl_from_IDataObject(iface);
1004

1005
  return IUnknown_AddRef(this->outerUnknown);
1006 1007 1008 1009 1010 1011 1012
}

/************************************************************************
 * DataCache_IDataObject_Release (IUnknown)
 *
 * See Windows documentation for more details on IUnknown methods.
 */
1013
static ULONG WINAPI DataCache_IDataObject_Release(
1014 1015
            IDataObject*     iface)
{
1016
  DataCache *this = impl_from_IDataObject(iface);
1017

1018
  return IUnknown_Release(this->outerUnknown);
1019 1020
}

1021 1022 1023 1024 1025 1026
/************************************************************************
 * DataCache_GetData
 *
 * Get Data from a source dataobject using format pformatetcIn->cfFormat
 * See Windows documentation for more details on GetData.
 */
1027 1028
static HRESULT WINAPI DataCache_GetData(
	    IDataObject*     iface,
1029
	    LPFORMATETC      pformatetcIn,
1030 1031
	    STGMEDIUM*       pmedium)
{
1032 1033
    DataCache *This = impl_from_IDataObject(iface);
    DataCacheEntry *cache_entry;
1034

1035
    memset(pmedium, 0, sizeof(*pmedium));
1036

1037 1038 1039
    cache_entry = DataCache_GetEntryForFormatEtc(This, pformatetcIn);
    if (!cache_entry)
        return OLE_E_BLANK;
1040

1041
    return DataCacheEntry_GetData(cache_entry, pmedium);
1042 1043 1044
}

static HRESULT WINAPI DataCache_GetDataHere(
1045
	    IDataObject*     iface,
1046 1047 1048
	    LPFORMATETC      pformatetc,
	    STGMEDIUM*       pmedium)
{
1049
  FIXME("stub\n");
1050 1051 1052 1053 1054 1055 1056
  return E_NOTIMPL;
}

static HRESULT WINAPI DataCache_QueryGetData(
	    IDataObject*     iface,
	    LPFORMATETC      pformatetc)
{
1057
  FIXME("stub\n");
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068
  return E_NOTIMPL;
}

/************************************************************************
 * DataCache_EnumFormatEtc (IDataObject)
 *
 * The data cache doesn't implement this method.
 *
 * See Windows documentation for more details on IDataObject methods.
 */
static HRESULT WINAPI DataCache_GetCanonicalFormatEtc(
1069 1070
	    IDataObject*     iface,
	    LPFORMATETC      pformatectIn,
1071 1072
	    LPFORMATETC      pformatetcOut)
{
1073
  TRACE("()\n");
1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085
  return E_NOTIMPL;
}

/************************************************************************
 * DataCache_IDataObject_SetData (IDataObject)
 *
 * This method is delegated to the IOleCache2 implementation.
 *
 * See Windows documentation for more details on IDataObject methods.
 */
static HRESULT WINAPI DataCache_IDataObject_SetData(
	    IDataObject*     iface,
1086 1087
	    LPFORMATETC      pformatetc,
	    STGMEDIUM*       pmedium,
1088 1089 1090 1091 1092
	    BOOL             fRelease)
{
  IOleCache2* oleCache = NULL;
  HRESULT     hres;

1093
  TRACE("(%p, %p, %p, %d)\n", iface, pformatetc, pmedium, fRelease);
1094

1095
  hres = IDataObject_QueryInterface(iface, &IID_IOleCache2, (void**)&oleCache);
1096 1097 1098 1099 1100 1101 1102 1103

  if (FAILED(hres))
    return E_UNEXPECTED;

  hres = IOleCache2_SetData(oleCache, pformatetc, pmedium, fRelease);

  IOleCache2_Release(oleCache);

1104
  return hres;
1105 1106 1107 1108 1109 1110 1111 1112 1113 1114
}

/************************************************************************
 * DataCache_EnumFormatEtc (IDataObject)
 *
 * The data cache doesn't implement this method.
 *
 * See Windows documentation for more details on IDataObject methods.
 */
static HRESULT WINAPI DataCache_EnumFormatEtc(
1115
	    IDataObject*     iface,
1116 1117 1118
	    DWORD            dwDirection,
	    IEnumFORMATETC** ppenumFormatEtc)
{
1119
  TRACE("()\n");
1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130
  return E_NOTIMPL;
}

/************************************************************************
 * DataCache_DAdvise (IDataObject)
 *
 * The data cache doesn't support connections.
 *
 * See Windows documentation for more details on IDataObject methods.
 */
static HRESULT WINAPI DataCache_DAdvise(
1131 1132 1133 1134
	    IDataObject*     iface,
	    FORMATETC*       pformatetc,
	    DWORD            advf,
	    IAdviseSink*     pAdvSink,
1135 1136
	    DWORD*           pdwConnection)
{
1137
  TRACE("()\n");
1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151
  return OLE_E_ADVISENOTSUPPORTED;
}

/************************************************************************
 * DataCache_DUnadvise (IDataObject)
 *
 * The data cache doesn't support connections.
 *
 * See Windows documentation for more details on IDataObject methods.
 */
static HRESULT WINAPI DataCache_DUnadvise(
	    IDataObject*     iface,
	    DWORD            dwConnection)
{
1152
  TRACE("()\n");
1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166
  return OLE_E_NOCONNECTION;
}

/************************************************************************
 * DataCache_EnumDAdvise (IDataObject)
 *
 * The data cache doesn't support connections.
 *
 * See Windows documentation for more details on IDataObject methods.
 */
static HRESULT WINAPI DataCache_EnumDAdvise(
	    IDataObject*     iface,
	    IEnumSTATDATA**  ppenumAdvise)
{
1167
  TRACE("()\n");
1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185
  return OLE_E_ADVISENOTSUPPORTED;
}

/*********************************************************
 * Method implementation for the IDataObject
 * part of the DataCache class.
 */

/************************************************************************
 * DataCache_IPersistStorage_QueryInterface (IUnknown)
 *
 * See Windows documentation for more details on IUnknown methods.
 */
static HRESULT WINAPI DataCache_IPersistStorage_QueryInterface(
            IPersistStorage* iface,
            REFIID           riid,
            void**           ppvObject)
{
1186
  DataCache *this = impl_from_IPersistStorage(iface);
1187

1188
  return IUnknown_QueryInterface(this->outerUnknown, riid, ppvObject);
1189 1190 1191 1192 1193 1194 1195
}

/************************************************************************
 * DataCache_IPersistStorage_AddRef (IUnknown)
 *
 * See Windows documentation for more details on IUnknown methods.
 */
1196
static ULONG WINAPI DataCache_IPersistStorage_AddRef(
1197 1198
            IPersistStorage* iface)
{
1199
  DataCache *this = impl_from_IPersistStorage(iface);
1200

1201
  return IUnknown_AddRef(this->outerUnknown);
1202 1203 1204 1205 1206 1207 1208
}

/************************************************************************
 * DataCache_IPersistStorage_Release (IUnknown)
 *
 * See Windows documentation for more details on IUnknown methods.
 */
1209
static ULONG WINAPI DataCache_IPersistStorage_Release(
1210 1211
            IPersistStorage* iface)
{
1212
  DataCache *this = impl_from_IPersistStorage(iface);
1213

1214
  return IUnknown_Release(this->outerUnknown);
1215 1216 1217 1218 1219 1220 1221 1222 1223
}

/************************************************************************
 * DataCache_GetClassID (IPersistStorage)
 *
 * The data cache doesn't implement this method.
 *
 * See Windows documentation for more details on IPersistStorage methods.
 */
1224
static HRESULT WINAPI DataCache_GetClassID(
Patrik Stridvall's avatar
Patrik Stridvall committed
1225
            IPersistStorage* iface,
1226 1227
	    CLSID*           pClassID)
{
1228
  DataCache *This = impl_from_IPersistStorage(iface);
1229
  DataCacheEntry *cache_entry;
1230

1231
  TRACE("(%p, %p)\n", iface, pClassID);
1232

1233
  LIST_FOR_EACH_ENTRY(cache_entry, &This->cache_list, DataCacheEntry, entry)
1234
  {
1235 1236 1237 1238 1239 1240 1241 1242 1243 1244
    if (cache_entry->storage != NULL)
    {
      STATSTG statstg;
      HRESULT hr = IStorage_Stat(cache_entry->storage, &statstg, STATFLAG_NONAME);
      if (SUCCEEDED(hr))
      {
        memcpy(pClassID, &statstg.clsid, sizeof(*pClassID));
        return S_OK;
      }
    }
1245 1246
  }

1247 1248 1249
  memcpy(pClassID, &CLSID_NULL, sizeof(*pClassID));

  return S_OK;
1250 1251
}

1252 1253 1254 1255 1256
/************************************************************************
 * DataCache_IsDirty (IPersistStorage)
 *
 * See Windows documentation for more details on IPersistStorage methods.
 */
1257
static HRESULT WINAPI DataCache_IsDirty(
1258 1259
            IPersistStorage* iface)
{
1260 1261 1262 1263
    DataCache *This = impl_from_IPersistStorage(iface);
    DataCacheEntry *cache_entry;

    TRACE("(%p)\n", iface);
1264

1265 1266 1267 1268 1269 1270 1271 1272
    if (This->dirty)
        return S_OK;

    LIST_FOR_EACH_ENTRY(cache_entry, &This->cache_list, DataCacheEntry, entry)
        if (cache_entry->dirty)
            return S_OK;

    return S_FALSE;
1273 1274 1275 1276 1277 1278 1279 1280 1281 1282
}

/************************************************************************
 * DataCache_InitNew (IPersistStorage)
 *
 * The data cache implementation of IPersistStorage_InitNew simply stores
 * the storage pointer.
 *
 * See Windows documentation for more details on IPersistStorage methods.
 */
1283 1284
static HRESULT WINAPI DataCache_InitNew(
            IPersistStorage* iface,
1285 1286
	    IStorage*        pStg)
{
1287 1288 1289 1290 1291 1292 1293 1294
    DataCache *This = impl_from_IPersistStorage(iface);

    TRACE("(%p, %p)\n", iface, pStg);

    if (This->presentationStorage != NULL)
        IStorage_Release(This->presentationStorage);

    This->presentationStorage = pStg;
1295

1296 1297 1298 1299
    IStorage_AddRef(This->presentationStorage);
    This->dirty = TRUE;

    return S_OK;
1300 1301 1302 1303 1304
}

/************************************************************************
 * DataCache_Load (IPersistStorage)
 *
1305
 * The data cache implementation of IPersistStorage_Load doesn't
1306
 * actually load anything. Instead, it holds on to the storage pointer
1307
 * and it will load the presentation information when the
1308 1309 1310 1311
 * IDataObject_GetData or IViewObject2_Draw methods are called.
 *
 * See Windows documentation for more details on IPersistStorage methods.
 */
1312
static HRESULT WINAPI DataCache_Load(
1313 1314 1315
            IPersistStorage* iface,
	    IStorage*        pStg)
{
1316 1317 1318 1319
    DataCache *This = impl_from_IPersistStorage(iface);
    STATSTG elem;
    IEnumSTATSTG *pEnum;
    HRESULT hr;
1320

1321
    TRACE("(%p, %p)\n", iface, pStg);
1322

1323 1324
    if (This->presentationStorage != NULL)
      IStorage_Release(This->presentationStorage);
1325

1326
    This->presentationStorage = pStg;
1327

1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341
    hr = IStorage_EnumElements(pStg, 0, NULL, 0, &pEnum);
    if (FAILED(hr)) return hr;

    while ((hr = IEnumSTATSTG_Next(pEnum, 1, &elem, NULL)) == S_OK)
    {
	if (DataCache_IsPresentationStream(&elem))
	{
	    IStream *pStm;

	    hr = IStorage_OpenStream(This->presentationStorage, elem.pwcsName,
				     NULL, STGM_READ | STGM_SHARE_EXCLUSIVE, 0,
				     &pStm);
	    if (SUCCEEDED(hr))
	    {
1342 1343 1344 1345 1346
                PresentationDataHeader header;
                ULONG actual_read;
                CLIPFORMAT clipformat;

                hr = read_clipformat(pStm, &clipformat);
1347

1348 1349 1350
                if (hr == S_OK)
                    hr = IStream_Read(pStm, &header, sizeof(header),
                                      &actual_read);
1351 1352 1353 1354 1355 1356 1357

		/* can't use SUCCEEDED(hr): S_FALSE counts as an error */
		if (hr == S_OK && actual_read == sizeof(header))
		{
		    DataCacheEntry *cache_entry;
		    FORMATETC fmtetc;

1358
		    fmtetc.cfFormat = clipformat;
1359 1360
		    fmtetc.ptd = NULL; /* FIXME */
		    fmtetc.dwAspect = header.dvAspect;
1361 1362 1363
		    fmtetc.lindex = header.lindex;
		    fmtetc.tymed = header.tymed;

1364
                    TRACE("loading entry with formatetc: %s\n", debugstr_formatetc(&fmtetc));
1365 1366 1367 1368 1369 1370

                    cache_entry = DataCache_GetEntryForFormatEtc(This, &fmtetc);
                    if (!cache_entry)
                        hr = DataCache_CreateEntry(This, &fmtetc, &cache_entry);
                    if (SUCCEEDED(hr))
                    {
1371
                        DataCacheEntry_DiscardData(cache_entry);
1372 1373 1374
                        if (cache_entry->storage) IStorage_Release(cache_entry->storage);
                        cache_entry->storage = pStg;
                        IStorage_AddRef(pStg);
1375
                        cache_entry->dirty = FALSE;
1376 1377 1378 1379 1380 1381 1382 1383 1384 1385
                    }
		}

		IStream_Release(pStm);
	    }
	}

	CoTaskMemFree(elem.pwcsName);
    }

1386 1387
    This->dirty = FALSE;

1388 1389 1390 1391
    IEnumSTATSTG_Release(pEnum);

    IStorage_AddRef(This->presentationStorage);
    return S_OK;
1392 1393
}

1394 1395 1396
/************************************************************************
 * DataCache_Save (IPersistStorage)
 *
1397
 * Until we actually connect to a running object and retrieve new
1398
 * information to it, we never have to save anything. However, it is
1399
 * our responsibility to copy the information when saving to a new
1400 1401 1402 1403
 * storage.
 *
 * See Windows documentation for more details on IPersistStorage methods.
 */
1404
static HRESULT WINAPI DataCache_Save(
1405
            IPersistStorage* iface,
1406
	    IStorage*        pStg,
1407 1408
	    BOOL             fSameAsLoad)
{
1409 1410 1411
    DataCache *This = impl_from_IPersistStorage(iface);
    DataCacheEntry *cache_entry;
    BOOL dirty = FALSE;
1412 1413
    HRESULT hr = S_OK;
    unsigned short stream_number = 0;
1414

1415
    TRACE("(%p, %p, %d)\n", iface, pStg, fSameAsLoad);
1416

1417 1418 1419 1420 1421 1422 1423 1424 1425 1426
    dirty = This->dirty;
    if (!dirty)
    {
        LIST_FOR_EACH_ENTRY(cache_entry, &This->cache_list, DataCacheEntry, entry)
        {
            dirty = cache_entry->dirty;
            if (dirty)
                break;
        }
    }
1427

1428 1429 1430 1431 1432 1433
    /* this is a shortcut if nothing changed */
    if (!dirty && !fSameAsLoad && This->presentationStorage)
    {
        return IStorage_CopyTo(This->presentationStorage, 0, NULL, NULL, pStg);
    }

1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445
    /* assign stream numbers to the cache entries */
    LIST_FOR_EACH_ENTRY(cache_entry, &This->cache_list, DataCacheEntry, entry)
    {
        if (cache_entry->stream_number != stream_number)
        {
            cache_entry->dirty = TRUE; /* needs to be written out again */
            cache_entry->stream_number = stream_number;
        }
        stream_number++;
    }

    /* write out the cache entries */
1446 1447
    LIST_FOR_EACH_ENTRY(cache_entry, &This->cache_list, DataCacheEntry, entry)
    {
1448 1449 1450 1451 1452 1453 1454 1455
        if (!fSameAsLoad || cache_entry->dirty)
        {
            hr = DataCacheEntry_Save(cache_entry, pStg, fSameAsLoad);
            if (FAILED(hr))
                break;

            cache_entry->dirty = FALSE;
        }
1456 1457 1458
    }

    This->dirty = FALSE;
1459
    return hr;
1460 1461 1462 1463 1464 1465
}

/************************************************************************
 * DataCache_SaveCompleted (IPersistStorage)
 *
 * This method is called to tell the cache to release the storage
1466
 * pointer it's currently holding.
1467 1468 1469
 *
 * See Windows documentation for more details on IPersistStorage methods.
 */
1470 1471
static HRESULT WINAPI DataCache_SaveCompleted(
            IPersistStorage* iface,
1472 1473
	    IStorage*        pStgNew)
{
1474
  TRACE("(%p, %p)\n", iface, pStgNew);
1475

1476 1477
  if (pStgNew)
  {
1478 1479 1480
  /*
   * First, make sure we get our hands off any storage we have.
   */
1481

1482
  IPersistStorage_HandsOffStorage(iface);
1483 1484 1485 1486

  /*
   * Then, attach to the new storage.
   */
1487

1488
  DataCache_Load(iface, pStgNew);
1489
  }
1490 1491 1492 1493 1494 1495 1496 1497

  return S_OK;
}

/************************************************************************
 * DataCache_HandsOffStorage (IPersistStorage)
 *
 * This method is called to tell the cache to release the storage
1498
 * pointer it's currently holding.
1499 1500 1501 1502 1503 1504
 *
 * See Windows documentation for more details on IPersistStorage methods.
 */
static HRESULT WINAPI DataCache_HandsOffStorage(
            IPersistStorage* iface)
{
1505
  DataCache *this = impl_from_IPersistStorage(iface);
1506
  DataCacheEntry *cache_entry;
1507

1508
  TRACE("(%p)\n", iface);
1509 1510 1511 1512 1513 1514 1515

  if (this->presentationStorage != NULL)
  {
    IStorage_Release(this->presentationStorage);
    this->presentationStorage = NULL;
  }

1516 1517 1518
  LIST_FOR_EACH_ENTRY(cache_entry, &this->cache_list, DataCacheEntry, entry)
    DataCacheEntry_HandsOffStorage(cache_entry);

1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536
  return S_OK;
}

/*********************************************************
 * Method implementation for the IViewObject2
 * part of the DataCache class.
 */

/************************************************************************
 * DataCache_IViewObject2_QueryInterface (IUnknown)
 *
 * See Windows documentation for more details on IUnknown methods.
 */
static HRESULT WINAPI DataCache_IViewObject2_QueryInterface(
            IViewObject2* iface,
            REFIID           riid,
            void**           ppvObject)
{
1537
  DataCache *this = impl_from_IViewObject2(iface);
1538

1539
  return IUnknown_QueryInterface(this->outerUnknown, riid, ppvObject);
1540 1541 1542 1543 1544 1545 1546
}

/************************************************************************
 * DataCache_IViewObject2_AddRef (IUnknown)
 *
 * See Windows documentation for more details on IUnknown methods.
 */
1547
static ULONG WINAPI DataCache_IViewObject2_AddRef(
1548 1549
            IViewObject2* iface)
{
1550
  DataCache *this = impl_from_IViewObject2(iface);
1551

1552
  return IUnknown_AddRef(this->outerUnknown);
1553 1554 1555 1556 1557 1558 1559
}

/************************************************************************
 * DataCache_IViewObject2_Release (IUnknown)
 *
 * See Windows documentation for more details on IUnknown methods.
 */
1560
static ULONG WINAPI DataCache_IViewObject2_Release(
1561 1562
            IViewObject2* iface)
{
1563
  DataCache *this = impl_from_IViewObject2(iface);
1564

1565
  return IUnknown_Release(this->outerUnknown);
1566 1567
}

1568 1569 1570 1571 1572 1573 1574 1575
/************************************************************************
 * DataCache_Draw (IViewObject2)
 *
 * This method will draw the cached representation of the object
 * to the given device context.
 *
 * See Windows documentation for more details on IViewObject2 methods.
 */
1576 1577 1578 1579 1580
static HRESULT WINAPI DataCache_Draw(
            IViewObject2*    iface,
	    DWORD            dwDrawAspect,
	    LONG             lindex,
	    void*            pvAspect,
1581 1582
	    DVTARGETDEVICE*  ptd,
	    HDC              hdcTargetDev,
1583 1584 1585
	    HDC              hdcDraw,
	    LPCRECTL         lprcBounds,
	    LPCRECTL         lprcWBounds,
1586
	    BOOL  (CALLBACK *pfnContinue)(ULONG_PTR dwContinue),
1587
	    ULONG_PTR        dwContinue)
1588
{
1589
  DataCache *This = impl_from_IViewObject2(iface);
1590
  HRESULT                hres;
1591
  DataCacheEntry        *cache_entry;
1592

1593
  TRACE("(%p, %x, %d, %p, %p, %p, %p, %p, %p, %lx)\n",
1594 1595 1596 1597
	iface,
	dwDrawAspect,
	lindex,
	pvAspect,
1598
	hdcTargetDev,
1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610
	hdcDraw,
	lprcBounds,
	lprcWBounds,
	pfnContinue,
	dwContinue);

  /*
   * Sanity check
   */
  if (lprcBounds==NULL)
    return E_INVALIDARG;

1611 1612 1613 1614 1615 1616 1617
  LIST_FOR_EACH_ENTRY(cache_entry, &This->cache_list, DataCacheEntry, entry)
  {
    /* FIXME: compare ptd too */
    if ((cache_entry->fmtetc.dwAspect != dwDrawAspect) ||
        (cache_entry->fmtetc.lindex != lindex))
      continue;

1618 1619
    /* if the data hasn't been loaded yet, do it now */
    if ((cache_entry->stgmedium.tymed == TYMED_NULL) && cache_entry->storage)
1620
    {
1621 1622 1623 1624 1625 1626 1627 1628 1629
      hres = DataCacheEntry_LoadData(cache_entry);
      if (FAILED(hres))
        continue;
    }

    /* no data */
    if (cache_entry->stgmedium.tymed == TYMED_NULL)
      continue;

1630
    switch (cache_entry->data_cf)
1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687
    {
      case CF_METAFILEPICT:
      {
        /*
         * We have to be careful not to modify the state of the
         * DC.
         */
        INT   prevMapMode;
        SIZE  oldWindowExt;
        SIZE  oldViewportExt;
        POINT oldViewportOrg;
        METAFILEPICT *mfpict;

        if ((cache_entry->stgmedium.tymed != TYMED_MFPICT) ||
            !((mfpict = GlobalLock(cache_entry->stgmedium.u.hMetaFilePict))))
          continue;

        prevMapMode = SetMapMode(hdcDraw, mfpict->mm);

        SetWindowExtEx(hdcDraw,
		       mfpict->xExt,
		       mfpict->yExt,
		       &oldWindowExt);

        SetViewportExtEx(hdcDraw,
		         lprcBounds->right - lprcBounds->left,
		         lprcBounds->bottom - lprcBounds->top,
		         &oldViewportExt);

        SetViewportOrgEx(hdcDraw,
		         lprcBounds->left,
		         lprcBounds->top,
		         &oldViewportOrg);

        PlayMetaFile(hdcDraw, mfpict->hMF);

        SetWindowExtEx(hdcDraw,
		       oldWindowExt.cx,
		       oldWindowExt.cy,
		       NULL);

        SetViewportExtEx(hdcDraw,
		         oldViewportExt.cx,
		         oldViewportExt.cy,
		         NULL);

        SetViewportOrgEx(hdcDraw,
		         oldViewportOrg.x,
		         oldViewportOrg.y,
		         NULL);

        SetMapMode(hdcDraw, prevMapMode);

        GlobalUnlock(cache_entry->stgmedium.u.hMetaFilePict);

        return S_OK;
      }
1688
    }
1689 1690
  }

1691 1692
  WARN("no data could be found to be drawn\n");

1693
  return OLE_E_BLANK;
1694 1695 1696
}

static HRESULT WINAPI DataCache_GetColorSet(
1697 1698 1699 1700 1701 1702
            IViewObject2*   iface,
	    DWORD           dwDrawAspect,
	    LONG            lindex,
	    void*           pvAspect,
	    DVTARGETDEVICE* ptd,
	    HDC             hicTargetDevice,
1703 1704
	    LOGPALETTE**    ppColorSet)
{
1705
  FIXME("stub\n");
1706 1707 1708 1709 1710 1711 1712
  return E_NOTIMPL;
}

static HRESULT WINAPI DataCache_Freeze(
            IViewObject2*   iface,
	    DWORD           dwDrawAspect,
	    LONG            lindex,
1713
	    void*           pvAspect,
1714 1715
	    DWORD*          pdwFreeze)
{
1716
  FIXME("stub\n");
1717 1718 1719 1720 1721 1722 1723
  return E_NOTIMPL;
}

static HRESULT WINAPI DataCache_Unfreeze(
            IViewObject2*   iface,
	    DWORD           dwFreeze)
{
1724
  FIXME("stub\n");
1725 1726 1727
  return E_NOTIMPL;
}

1728 1729 1730 1731 1732 1733 1734 1735
/************************************************************************
 * DataCache_SetAdvise (IViewObject2)
 *
 * This sets-up an advisory sink with the data cache. When the object's
 * view changes, this sink is called.
 *
 * See Windows documentation for more details on IViewObject2 methods.
 */
1736 1737
static HRESULT WINAPI DataCache_SetAdvise(
            IViewObject2*   iface,
1738 1739
	    DWORD           aspects,
	    DWORD           advf,
1740 1741
	    IAdviseSink*    pAdvSink)
{
1742
  DataCache *this = impl_from_IViewObject2(iface);
1743

1744
  TRACE("(%p, %x, %x, %p)\n", iface, aspects, advf, pAdvSink);
1745 1746 1747 1748 1749 1750 1751 1752

  /*
   * A call to this function removes the previous sink
   */
  if (this->sinkInterface != NULL)
  {
    IAdviseSink_Release(this->sinkInterface);
    this->sinkInterface  = NULL;
1753
    this->sinkAspects    = 0;
1754 1755 1756 1757 1758 1759 1760 1761 1762
    this->sinkAdviseFlag = 0;
  }

  /*
   * Now, setup the new one.
   */
  if (pAdvSink!=NULL)
  {
    this->sinkInterface  = pAdvSink;
1763 1764
    this->sinkAspects    = aspects;
    this->sinkAdviseFlag = advf;
1765 1766 1767 1768 1769 1770 1771 1772 1773 1774

    IAdviseSink_AddRef(this->sinkInterface);
  }

  /*
   * When the ADVF_PRIMEFIRST flag is set, we have to advise the
   * sink immediately.
   */
  if (advf & ADVF_PRIMEFIRST)
  {
1775
    DataCache_FireOnViewChange(this, aspects, -1);
1776 1777
  }

1778 1779 1780
  return S_OK;
}

1781 1782 1783
/************************************************************************
 * DataCache_GetAdvise (IViewObject2)
 *
1784
 * This method queries the current state of the advise sink
1785 1786 1787 1788
 * installed on the data cache.
 *
 * See Windows documentation for more details on IViewObject2 methods.
 */
1789
static HRESULT WINAPI DataCache_GetAdvise(
1790 1791 1792
            IViewObject2*   iface,
	    DWORD*          pAspects,
	    DWORD*          pAdvf,
1793 1794
	    IAdviseSink**   ppAdvSink)
{
1795
  DataCache *this = impl_from_IViewObject2(iface);
1796

1797
  TRACE("(%p, %p, %p, %p)\n", iface, pAspects, pAdvf, ppAdvSink);
1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809

  /*
   * Just copy all the requested values.
   */
  if (pAspects!=NULL)
    *pAspects = this->sinkAspects;

  if (pAdvf!=NULL)
    *pAdvf = this->sinkAdviseFlag;

  if (ppAdvSink!=NULL)
  {
1810 1811
    if (this->sinkInterface != NULL)
        IAdviseSink_QueryInterface(this->sinkInterface,
1812
			       &IID_IAdviseSink,
1813
			       (void**)ppAdvSink);
1814
    else *ppAdvSink = NULL;
1815 1816 1817
  }

  return S_OK;
1818 1819
}

1820 1821 1822 1823 1824 1825 1826
/************************************************************************
 * DataCache_GetExtent (IViewObject2)
 *
 * This method retrieves the "natural" size of this cached object.
 *
 * See Windows documentation for more details on IViewObject2 methods.
 */
1827
static HRESULT WINAPI DataCache_GetExtent(
1828 1829 1830 1831
            IViewObject2*   iface,
	    DWORD           dwDrawAspect,
	    LONG            lindex,
	    DVTARGETDEVICE* ptd,
1832 1833
	    LPSIZEL         lpsizel)
{
1834
  DataCache *This = impl_from_IViewObject2(iface);
1835
  HRESULT                hres = E_FAIL;
1836
  DataCacheEntry        *cache_entry;
1837

1838
  TRACE("(%p, %x, %d, %p, %p)\n",
1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856
	iface, dwDrawAspect, lindex, ptd, lpsizel);

  /*
   * Sanity check
   */
  if (lpsizel==NULL)
    return E_POINTER;

  /*
   * Initialize the out parameter.
   */
  lpsizel->cx = 0;
  lpsizel->cy = 0;

  /*
   * This flag should be set to -1.
   */
  if (lindex!=-1)
1857
    FIXME("Unimplemented flag lindex = %d\n", lindex);
1858 1859

  /*
1860
   * Right now, we support only the callback from
1861 1862 1863
   * the default handler.
   */
  if (ptd!=NULL)
1864
    FIXME("Unimplemented ptd = %p\n", ptd);
1865

1866 1867 1868 1869 1870 1871 1872
  LIST_FOR_EACH_ENTRY(cache_entry, &This->cache_list, DataCacheEntry, entry)
  {
    /* FIXME: compare ptd too */
    if ((cache_entry->fmtetc.dwAspect != dwDrawAspect) ||
        (cache_entry->fmtetc.lindex != lindex))
      continue;

1873 1874 1875 1876 1877 1878 1879
    /* if the data hasn't been loaded yet, do it now */
    if ((cache_entry->stgmedium.tymed == TYMED_NULL) && cache_entry->storage)
    {
      hres = DataCacheEntry_LoadData(cache_entry);
      if (FAILED(hres))
        continue;
    }
1880

1881 1882 1883 1884 1885
    /* no data */
    if (cache_entry->stgmedium.tymed == TYMED_NULL)
      continue;


1886
    switch (cache_entry->data_cf)
1887
    {
1888 1889 1890 1891 1892 1893 1894
      case CF_METAFILEPICT:
      {
          METAFILEPICT *mfpict;

          if ((cache_entry->stgmedium.tymed != TYMED_MFPICT) ||
              !((mfpict = GlobalLock(cache_entry->stgmedium.u.hMetaFilePict))))
            continue;
1895

1896 1897 1898 1899 1900 1901 1902
        lpsizel->cx = mfpict->xExt;
        lpsizel->cy = mfpict->yExt;

        GlobalUnlock(cache_entry->stgmedium.u.hMetaFilePict);

        return S_OK;
      }
1903
    }
1904 1905
  }

1906 1907
  WARN("no data could be found to get the extents from\n");

1908 1909 1910
  /*
   * This method returns OLE_E_BLANK when it fails.
   */
1911
  return OLE_E_BLANK;
1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929
}


/*********************************************************
 * Method implementation for the IOleCache2
 * part of the DataCache class.
 */

/************************************************************************
 * DataCache_IOleCache2_QueryInterface (IUnknown)
 *
 * See Windows documentation for more details on IUnknown methods.
 */
static HRESULT WINAPI DataCache_IOleCache2_QueryInterface(
            IOleCache2*     iface,
            REFIID          riid,
            void**          ppvObject)
{
1930
  DataCache *this = impl_from_IOleCache2(iface);
1931

1932
  return IUnknown_QueryInterface(this->outerUnknown, riid, ppvObject);
1933 1934 1935 1936 1937 1938 1939
}

/************************************************************************
 * DataCache_IOleCache2_AddRef (IUnknown)
 *
 * See Windows documentation for more details on IUnknown methods.
 */
1940
static ULONG WINAPI DataCache_IOleCache2_AddRef(
1941 1942
            IOleCache2*     iface)
{
1943
  DataCache *this = impl_from_IOleCache2(iface);
1944

1945
  return IUnknown_AddRef(this->outerUnknown);
1946 1947 1948 1949 1950 1951 1952
}

/************************************************************************
 * DataCache_IOleCache2_Release (IUnknown)
 *
 * See Windows documentation for more details on IUnknown methods.
 */
1953
static ULONG WINAPI DataCache_IOleCache2_Release(
1954 1955
            IOleCache2*     iface)
{
1956
  DataCache *this = impl_from_IOleCache2(iface);
1957

1958
  return IUnknown_Release(this->outerUnknown);
1959 1960 1961 1962 1963 1964 1965 1966
}

static HRESULT WINAPI DataCache_Cache(
            IOleCache2*     iface,
	    FORMATETC*      pformatetc,
	    DWORD           advf,
	    DWORD*          pdwConnection)
{
1967 1968 1969 1970 1971
    DataCache *This = impl_from_IOleCache2(iface);
    DataCacheEntry *cache_entry;
    HRESULT hr;

    TRACE("(%p, 0x%x, %p)\n", pformatetc, advf, pdwConnection);
1972
    TRACE("pformatetc = %s\n", debugstr_formatetc(pformatetc));
1973 1974 1975 1976 1977 1978

    *pdwConnection = 0;

    cache_entry = DataCache_GetEntryForFormatEtc(This, pformatetc);
    if (cache_entry)
    {
1979
        TRACE("found an existing cache entry\n");
1980 1981 1982 1983 1984 1985 1986 1987 1988 1989
        *pdwConnection = cache_entry->id;
        return CACHE_S_SAMECACHE;
    }

    hr = DataCache_CreateEntry(This, pformatetc, &cache_entry);

    if (SUCCEEDED(hr))
        *pdwConnection = cache_entry->id;

    return hr;
1990 1991 1992 1993 1994 1995
}

static HRESULT WINAPI DataCache_Uncache(
	    IOleCache2*     iface,
	    DWORD           dwConnection)
{
1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007
    DataCache *This = impl_from_IOleCache2(iface);
    DataCacheEntry *cache_entry;

    TRACE("(%d)\n", dwConnection);

    LIST_FOR_EACH_ENTRY(cache_entry, &This->cache_list, DataCacheEntry, entry)
        if (cache_entry->id == dwConnection)
        {
            DataCacheEntry_Destroy(cache_entry);
            return S_OK;
        }

2008 2009
    WARN("no connection found for %d\n", dwConnection);

2010
    return OLE_E_NOCONNECTION;
2011 2012 2013 2014 2015 2016
}

static HRESULT WINAPI DataCache_EnumCache(
            IOleCache2*     iface,
	    IEnumSTATDATA** ppenumSTATDATA)
{
2017
  FIXME("stub\n");
2018 2019 2020 2021 2022 2023 2024
  return E_NOTIMPL;
}

static HRESULT WINAPI DataCache_InitCache(
	    IOleCache2*     iface,
	    IDataObject*    pDataObject)
{
2025
  FIXME("stub\n");
2026 2027 2028 2029 2030 2031 2032 2033 2034
  return E_NOTIMPL;
}

static HRESULT WINAPI DataCache_IOleCache2_SetData(
            IOleCache2*     iface,
	    FORMATETC*      pformatetc,
	    STGMEDIUM*      pmedium,
	    BOOL            fRelease)
{
2035 2036 2037 2038 2039
    DataCache *This = impl_from_IOleCache2(iface);
    DataCacheEntry *cache_entry;
    HRESULT hr;

    TRACE("(%p, %p, %s)\n", pformatetc, pmedium, fRelease ? "TRUE" : "FALSE");
2040
    TRACE("formatetc = %s\n", debugstr_formatetc(pformatetc));
2041 2042 2043 2044

    cache_entry = DataCache_GetEntryForFormatEtc(This, pformatetc);
    if (cache_entry)
    {
2045
        hr = DataCacheEntry_SetData(cache_entry, pformatetc, pmedium, fRelease);
2046 2047 2048 2049 2050 2051 2052

        if (SUCCEEDED(hr))
            DataCache_FireOnViewChange(This, cache_entry->fmtetc.dwAspect,
                                       cache_entry->fmtetc.lindex);

        return hr;
    }
2053
    WARN("cache entry not found\n");
2054 2055

    return OLE_E_BLANK;
2056 2057 2058 2059
}

static HRESULT WINAPI DataCache_UpdateCache(
            IOleCache2*     iface,
2060
	    LPDATAOBJECT    pDataObject,
2061 2062 2063
	    DWORD           grfUpdf,
	    LPVOID          pReserved)
{
2064
  FIXME("(%p, 0x%x, %p): stub\n", pDataObject, grfUpdf, pReserved);
2065 2066 2067 2068 2069 2070 2071
  return E_NOTIMPL;
}

static HRESULT WINAPI DataCache_DiscardCache(
            IOleCache2*     iface,
	    DWORD           dwDiscardOptions)
{
2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089
    DataCache *This = impl_from_IOleCache2(iface);
    DataCacheEntry *cache_entry;
    HRESULT hr = S_OK;

    TRACE("(%d)\n", dwDiscardOptions);

    if (dwDiscardOptions == DISCARDCACHE_SAVEIFDIRTY)
        hr = DataCache_Save((IPersistStorage *)&This->lpvtblIPersistStorage,
                            This->presentationStorage, TRUE);

    LIST_FOR_EACH_ENTRY(cache_entry, &This->cache_list, DataCacheEntry, entry)
    {
        hr = DataCacheEntry_DiscardData(cache_entry);
        if (FAILED(hr))
            break;
    }

    return hr;
2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107
}


/*********************************************************
 * Method implementation for the IOleCacheControl
 * part of the DataCache class.
 */

/************************************************************************
 * DataCache_IOleCacheControl_QueryInterface (IUnknown)
 *
 * See Windows documentation for more details on IUnknown methods.
 */
static HRESULT WINAPI DataCache_IOleCacheControl_QueryInterface(
            IOleCacheControl* iface,
            REFIID            riid,
            void**            ppvObject)
{
2108
  DataCache *this = impl_from_IOleCacheControl(iface);
2109

2110
  return IUnknown_QueryInterface(this->outerUnknown, riid, ppvObject);
2111 2112 2113 2114 2115 2116 2117
}

/************************************************************************
 * DataCache_IOleCacheControl_AddRef (IUnknown)
 *
 * See Windows documentation for more details on IUnknown methods.
 */
2118
static ULONG WINAPI DataCache_IOleCacheControl_AddRef(
2119 2120
            IOleCacheControl* iface)
{
2121
  DataCache *this = impl_from_IOleCacheControl(iface);
2122

2123
  return IUnknown_AddRef(this->outerUnknown);
2124 2125 2126 2127 2128 2129 2130
}

/************************************************************************
 * DataCache_IOleCacheControl_Release (IUnknown)
 *
 * See Windows documentation for more details on IUnknown methods.
 */
2131
static ULONG WINAPI DataCache_IOleCacheControl_Release(
2132 2133
            IOleCacheControl* iface)
{
2134
  DataCache *this = impl_from_IOleCacheControl(iface);
2135

2136
  return IUnknown_Release(this->outerUnknown);
2137 2138 2139 2140 2141 2142
}

static HRESULT WINAPI DataCache_OnRun(
	    IOleCacheControl* iface,
	    LPDATAOBJECT      pDataObject)
{
2143
  FIXME("stub\n");
2144 2145 2146 2147 2148 2149
  return E_NOTIMPL;
}

static HRESULT WINAPI DataCache_OnStop(
	    IOleCacheControl* iface)
{
2150
  FIXME("stub\n");
2151 2152
  return E_NOTIMPL;
}
2153 2154 2155 2156

/*
 * Virtual function tables for the DataCache class.
 */
2157
static const IUnknownVtbl DataCache_NDIUnknown_VTable =
2158 2159 2160 2161 2162 2163
{
  DataCache_NDIUnknown_QueryInterface,
  DataCache_NDIUnknown_AddRef,
  DataCache_NDIUnknown_Release
};

2164
static const IDataObjectVtbl DataCache_IDataObject_VTable =
2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179
{
  DataCache_IDataObject_QueryInterface,
  DataCache_IDataObject_AddRef,
  DataCache_IDataObject_Release,
  DataCache_GetData,
  DataCache_GetDataHere,
  DataCache_QueryGetData,
  DataCache_GetCanonicalFormatEtc,
  DataCache_IDataObject_SetData,
  DataCache_EnumFormatEtc,
  DataCache_DAdvise,
  DataCache_DUnadvise,
  DataCache_EnumDAdvise
};

2180
static const IPersistStorageVtbl DataCache_IPersistStorage_VTable =
2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193
{
  DataCache_IPersistStorage_QueryInterface,
  DataCache_IPersistStorage_AddRef,
  DataCache_IPersistStorage_Release,
  DataCache_GetClassID,
  DataCache_IsDirty,
  DataCache_InitNew,
  DataCache_Load,
  DataCache_Save,
  DataCache_SaveCompleted,
  DataCache_HandsOffStorage
};

2194
static const IViewObject2Vtbl DataCache_IViewObject2_VTable =
2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207
{
  DataCache_IViewObject2_QueryInterface,
  DataCache_IViewObject2_AddRef,
  DataCache_IViewObject2_Release,
  DataCache_Draw,
  DataCache_GetColorSet,
  DataCache_Freeze,
  DataCache_Unfreeze,
  DataCache_SetAdvise,
  DataCache_GetAdvise,
  DataCache_GetExtent
};

2208
static const IOleCache2Vtbl DataCache_IOleCache2_VTable =
2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221
{
  DataCache_IOleCache2_QueryInterface,
  DataCache_IOleCache2_AddRef,
  DataCache_IOleCache2_Release,
  DataCache_Cache,
  DataCache_Uncache,
  DataCache_EnumCache,
  DataCache_InitCache,
  DataCache_IOleCache2_SetData,
  DataCache_UpdateCache,
  DataCache_DiscardCache
};

2222
static const IOleCacheControlVtbl DataCache_IOleCacheControl_VTable =
2223 2224 2225 2226 2227 2228 2229 2230 2231 2232
{
  DataCache_IOleCacheControl_QueryInterface,
  DataCache_IOleCacheControl_AddRef,
  DataCache_IOleCacheControl_Release,
  DataCache_OnRun,
  DataCache_OnStop
};

/******************************************************************************
 *              CreateDataCache        [OLE32.@]
2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250
 *
 * Creates a data cache to allow an object to render one or more of its views,
 * whether running or not.
 *
 * PARAMS
 *  pUnkOuter [I] Outer unknown for the object.
 *  rclsid    [I]
 *  riid      [I] IID of interface to return.
 *  ppvObj    [O] Address where the data cache object will be stored on return.
 *
 * RETURNS
 *  Success: S_OK.
 *  Failure: HRESULT code.
 *
 * NOTES
 *  The following interfaces are supported by the returned data cache object:
 *  IOleCache, IOleCache2, IOleCacheControl, IPersistStorae, IDataObject,
 *  IViewObject and IViewObject2.
2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292
 */
HRESULT WINAPI CreateDataCache(
  LPUNKNOWN pUnkOuter,
  REFCLSID  rclsid,
  REFIID    riid,
  LPVOID*   ppvObj)
{
  DataCache* newCache = NULL;
  HRESULT    hr       = S_OK;

  TRACE("(%s, %p, %s, %p)\n", debugstr_guid(rclsid), pUnkOuter, debugstr_guid(riid), ppvObj);

  /*
   * Sanity check
   */
  if (ppvObj==0)
    return E_POINTER;

  *ppvObj = 0;

  /*
   * If this cache is constructed for aggregation, make sure
   * the caller is requesting the IUnknown interface.
   * This is necessary because it's the only time the non-delegating
   * IUnknown pointer can be returned to the outside.
   */
  if ( (pUnkOuter!=NULL) &&
       (memcmp(&IID_IUnknown, riid, sizeof(IID_IUnknown)) != 0) )
    return CLASS_E_NOAGGREGATION;

  /*
   * Try to construct a new instance of the class.
   */
  newCache = DataCache_Construct(rclsid,
				 pUnkOuter);

  if (newCache == 0)
    return E_OUTOFMEMORY;

  /*
   * Make sure it supports the interface required by the caller.
   */
2293
  hr = IUnknown_QueryInterface((IUnknown*)&(newCache->lpvtblNDIUnknown), riid, ppvObj);
2294 2295 2296 2297 2298

  /*
   * Release the reference obtained in the constructor. If
   * the QueryInterface was unsuccessful, it will free the class.
   */
2299
  IUnknown_Release((IUnknown*)&(newCache->lpvtblNDIUnknown));
2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323

  return hr;
}

/*********************************************************
 * Method implementation for DataCache class.
 */
static DataCache* DataCache_Construct(
  REFCLSID  clsid,
  LPUNKNOWN pUnkOuter)
{
  DataCache* newObject = 0;

  /*
   * Allocate space for the object.
   */
  newObject = HeapAlloc(GetProcessHeap(), 0, sizeof(DataCache));

  if (newObject==0)
    return newObject;

  /*
   * Initialize the virtual function table.
   */
2324 2325 2326 2327 2328 2329
  newObject->lpVtbl = &DataCache_IDataObject_VTable;
  newObject->lpvtblNDIUnknown = &DataCache_NDIUnknown_VTable;
  newObject->lpvtblIPersistStorage = &DataCache_IPersistStorage_VTable;
  newObject->lpvtblIViewObject = &DataCache_IViewObject2_VTable;
  newObject->lpvtblIOleCache2 = &DataCache_IOleCache2_VTable;
  newObject->lpvtblIOleCacheControl = &DataCache_IOleCacheControl_VTable;
2330 2331 2332 2333 2334 2335 2336 2337 2338 2339

  /*
   * Start with one reference count. The caller of this function
   * must release the interface pointer when it is done.
   */
  newObject->ref = 1;

  /*
   * Initialize the outer unknown
   * We don't keep a reference on the outer unknown since, the way
2340
   * aggregation works, our lifetime is at least as large as its
2341 2342 2343
   * lifetime.
   */
  if (pUnkOuter==NULL)
2344
    pUnkOuter = (IUnknown*)&(newObject->lpvtblNDIUnknown);
2345 2346 2347 2348 2349 2350 2351 2352 2353

  newObject->outerUnknown = pUnkOuter;

  /*
   * Initialize the other members of the structure.
   */
  newObject->sinkAspects = 0;
  newObject->sinkAdviseFlag = 0;
  newObject->sinkInterface = 0;
2354 2355
  newObject->presentationStorage = NULL;
  list_init(&newObject->cache_list);
2356 2357
  newObject->last_cache_id = 1;
  newObject->dirty = FALSE;
2358 2359 2360

  return newObject;
}