datacache.c 65.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
 * PresentationDataHeader
 *
 * This structure represents the header of the \002OlePresXXX stream in
Austin English's avatar
Austin English committed
69
 * the OLE object storage.
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 114 115
  /* sink id set when object is running */
  DWORD sink_id;
  /* Advise sink flags */
  DWORD advise_flags;
116 117
} DataCacheEntry;

118 119 120 121 122 123
/****************************************************************************
 * DataCache
 */
struct DataCache
{
  /*
124
   * List all interface here
125
   */
126 127 128 129 130 131
  IDataObject       IDataObject_iface;
  IUnknown          IUnknown_iface;
  IPersistStorage   IPersistStorage_iface;
  IViewObject2      IViewObject2_iface;
  IOleCache2        IOleCache2_iface;
  IOleCacheControl  IOleCacheControl_iface;
132

133 134
  /* The sink that is connected to a remote object.
     The other interfaces are not available by QI'ing the sink and vice-versa */
135
  IAdviseSink       IAdviseSink_iface;
136

137 138 139
  /*
   * Reference count of this object
   */
140
  LONG ref;
141 142 143 144 145 146

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

147 148 149 150 151 152 153 154
  /*
   * 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;
155
  IStorage *presentationStorage;
156

157
  /* list of cache entries */
158
  struct list cache_list;
159
  /* last id assigned to an entry */
160
  DWORD last_cache_id;
161 162
  /* dirty flag */
  BOOL dirty;
163 164
  /* running object set by OnRun */
  IDataObject *running_object;
165 166 167 168 169
};

typedef struct DataCache DataCache;

/*
170
 * Here, I define utility macros to help with the casting of the
171
 * "this" parameter.
172
 * There is a version to accommodate all of the VTables implemented
173 174
 * by this object.
 */
175 176 177

static inline DataCache *impl_from_IDataObject( IDataObject *iface )
{
178
    return CONTAINING_RECORD(iface, DataCache, IDataObject_iface);
179 180
}

181
static inline DataCache *impl_from_IUnknown( IUnknown *iface )
182
{
183
    return CONTAINING_RECORD(iface, DataCache, IUnknown_iface);
184 185 186 187
}

static inline DataCache *impl_from_IPersistStorage( IPersistStorage *iface )
{
188
    return CONTAINING_RECORD(iface, DataCache, IPersistStorage_iface);
189 190 191 192
}

static inline DataCache *impl_from_IViewObject2( IViewObject2 *iface )
{
193
    return CONTAINING_RECORD(iface, DataCache, IViewObject2_iface);
194 195 196 197
}

static inline DataCache *impl_from_IOleCache2( IOleCache2 *iface )
{
198
    return CONTAINING_RECORD(iface, DataCache, IOleCache2_iface);
199 200 201 202
}

static inline DataCache *impl_from_IOleCacheControl( IOleCacheControl *iface )
{
203
    return CONTAINING_RECORD(iface, DataCache, IOleCacheControl_iface);
204 205
}

206 207
static inline DataCache *impl_from_IAdviseSink( IAdviseSink *iface )
{
208
    return CONTAINING_RECORD(iface, DataCache, IAdviseSink_iface);
209 210
}

211
static const char * debugstr_formatetc(const FORMATETC *formatetc)
212
{
213 214 215
    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);
216
}
217

218
static void DataCacheEntry_Destroy(DataCache *cache, DataCacheEntry *cache_entry)
219
{
220 221 222 223 224
    list_remove(&cache_entry->entry);
    if (cache_entry->storage)
        IStorage_Release(cache_entry->storage);
    HeapFree(GetProcessHeap(), 0, cache_entry->fmtetc.ptd);
    ReleaseStgMedium(&cache_entry->stgmedium);
225 226 227
    if(cache_entry->sink_id)
        IDataObject_DUnadvise(cache->running_object, cache_entry->sink_id);

228
    HeapFree(GetProcessHeap(), 0, cache_entry);
229 230
}

231 232 233
static void DataCache_Destroy(
  DataCache* ptrToDestroy)
{
234 235
  DataCacheEntry *cache_entry, *next_cache_entry;

236
  TRACE("()\n");
237 238 239 240 241 242 243

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

244
  LIST_FOR_EACH_ENTRY_SAFE(cache_entry, next_cache_entry, &ptrToDestroy->cache_list, DataCacheEntry, entry)
245
    DataCacheEntry_Destroy(ptrToDestroy, cache_entry);
246

247 248 249 250 251 252
  if (ptrToDestroy->presentationStorage != NULL)
  {
    IStorage_Release(ptrToDestroy->presentationStorage);
    ptrToDestroy->presentationStorage = NULL;
  }

253 254 255 256 257 258
  /*
   * Free the datacache pointer.
   */
  HeapFree(GetProcessHeap(), 0, ptrToDestroy);
}

259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
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;
}

274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
/* 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;
    }
}

294 295
static HRESULT DataCache_CreateEntry(DataCache *This, const FORMATETC *formatetc, DataCacheEntry **cache_entry)
{
296 297 298 299 300 301 302 303
    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);

304
    *cache_entry = HeapAlloc(GetProcessHeap(), 0, sizeof(**cache_entry));
305 306 307
    if (!*cache_entry)
        return E_OUTOFMEMORY;

308 309 310 311 312 313
    (*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);
    }
314
    (*cache_entry)->data_cf = 0;
315 316
    (*cache_entry)->stgmedium.tymed = TYMED_NULL;
    (*cache_entry)->stgmedium.pUnkForRelease = NULL;
317
    (*cache_entry)->storage = NULL;
318
    (*cache_entry)->id = This->last_cache_id++;
319
    (*cache_entry)->dirty = TRUE;
320
    (*cache_entry)->stream_number = -1;
321 322
    (*cache_entry)->sink_id = 0;
    (*cache_entry)->advise_flags = 0;
323
    list_add_tail(&This->cache_list, &(*cache_entry)->entry);
324
    return hr;
325 326
}

327 328 329 330 331 332 333 334 335 336 337 338 339
/************************************************************************
 * 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)
{
340
  TRACE("(%p, %x, %d)\n", this, aspect, lindex);
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370

  /*
   * 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;
      }
    }
  }
}

371
/* Helper for DataCacheEntry_OpenPresStream */
372 373 374 375 376 377 378 379 380
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)
381 382
	&& (strlenW(name) == 11)
	&& (strncmpW(name, OlePres, 8) == 0)
383 384 385
	&& (name[8] >= '0') && (name[8] <= '9')
	&& (name[9] >= '0') && (name[9] <= '9')
	&& (name[10] >= '0') && (name[10] <= '9');
386 387
}

388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
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;
}

453
/************************************************************************
454
 * DataCacheEntry_OpenPresStream
455
 *
456 457
 * This method will find the stream for the given presentation. It makes
 * no attempt at fallback.
458 459 460 461
 *
 * Param:
 *   this       - Pointer to the DataCache object
 *   drawAspect - The aspect of the object that we wish to draw.
462 463 464 465 466 467 468
 *   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.
469
 *
470 471 472
 * Notes:
 *   Algorithm:	Scan the elements of the presentation storage, looking
 *		for presentation streams. For each presentation stream,
473
 *		load the header and check to see if the aspect matches.
474 475 476
 *
 *   If a fallback is desired, just opening the first presentation stream
 *   is a possibility.
477
 */
478
static HRESULT DataCacheEntry_OpenPresStream(DataCacheEntry *cache_entry, IStream **ppStm)
479
{
480 481 482
    STATSTG elem;
    IEnumSTATSTG *pEnum;
    HRESULT hr;
483

484
    if (!ppStm) return E_POINTER;
485

486
    hr = IStorage_EnumElements(cache_entry->storage, 0, NULL, 0, &pEnum);
487
    if (FAILED(hr)) return hr;
488

489 490 491 492 493 494
    while ((hr = IEnumSTATSTG_Next(pEnum, 1, &elem, NULL)) == S_OK)
    {
	if (DataCache_IsPresentationStream(&elem))
	{
	    IStream *pStm;

495
	    hr = IStorage_OpenStream(cache_entry->storage, elem.pwcsName,
496 497 498 499 500 501
				     NULL, STGM_READ | STGM_SHARE_EXCLUSIVE, 0,
				     &pStm);
	    if (SUCCEEDED(hr))
	    {
		PresentationDataHeader header;
		ULONG actual_read;
502 503 504
                CLIPFORMAT clipformat;

                hr = read_clipformat(pStm, &clipformat);
505

506 507
                if (hr == S_OK)
                    hr = IStream_Read(pStm, &header, sizeof(header), &actual_read);
508 509 510

		/* can't use SUCCEEDED(hr): S_FALSE counts as an error */
		if (hr == S_OK && actual_read == sizeof(header)
511
		    && header.dvAspect == cache_entry->fmtetc.dwAspect)
512 513 514
		{
		    /* Rewind the stream before returning it. */
		    LARGE_INTEGER offset;
515 516
		    offset.u.LowPart = 0;
		    offset.u.HighPart = 0;
517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536
		    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);
537 538 539
}

/************************************************************************
540
 * DataCacheEntry_LoadData
541
 *
542
 * This method will read information for the requested presentation
543 544 545
 * into the given structure.
 *
 * Param:
546
 *   This - The entry to load the data from.
547 548 549 550 551
 *
 * Returns:
 *   This method returns a metafile handle if it is successful.
 *   it will return 0 if not.
 */
552
static HRESULT DataCacheEntry_LoadData(DataCacheEntry *cache_entry)
553 554 555
{
  IStream*      presStream = NULL;
  HRESULT       hres;
556
  ULARGE_INTEGER current_pos;
557
  STATSTG       streamInfo;
558 559 560 561
  void*         metafileBits;
  METAFILEPICT *mfpict;
  HGLOBAL       hmfpict;
  PresentationDataHeader header;
562 563
  CLIPFORMAT    clipformat;
  static const LARGE_INTEGER offset_zero;
564 565

  /*
566
   * Open the presentation stream.
567
   */
568
  hres = DataCacheEntry_OpenPresStream(cache_entry, &presStream);
569 570

  if (FAILED(hres))
571
    return hres;
572 573 574 575 576 577 578 579 580

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

  /*
581
   * Read the header.
582 583
   */

584 585 586 587 588 589 590
  hres = read_clipformat(presStream, &clipformat);
  if (FAILED(hres))
  {
      IStream_Release(presStream);
      return hres;
  }

591 592 593 594 595
  hres = IStream_Read(
                      presStream,
                      &header,
                      sizeof(PresentationDataHeader),
                      NULL);
596 597 598 599 600 601 602
  if (hres != S_OK)
  {
      IStream_Release(presStream);
      return E_FAIL;
  }

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

604
  streamInfo.cbSize.QuadPart -= current_pos.QuadPart;
605 606 607 608 609 610 611 612

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

614 615 616
  /*
   * Allocate a buffer for the metafile bits.
   */
617 618
  metafileBits = HeapAlloc(GetProcessHeap(),
			   0,
619
			   streamInfo.cbSize.u.LowPart);
620 621 622 623 624 625 626

  /*
   * Read the metafile bits.
   */
  hres = IStream_Read(
	   presStream,
	   metafileBits,
627
	   streamInfo.cbSize.u.LowPart,
628 629 630 631 632 633 634
	   NULL);

  /*
   * Create a metafile with those bits.
   */
  if (SUCCEEDED(hres))
  {
635 636 637 638 639 640 641 642 643 644 645 646
    /* 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))
  {
647 648 649
    cache_entry->data_cf = cache_entry->fmtetc.cfFormat;
    cache_entry->stgmedium.tymed = TYMED_MFPICT;
    cache_entry->stgmedium.u.hMetaFilePict = hmfpict;
650
  }
651 652
  else
    GlobalFree(hmfpict);
653 654 655 656 657 658 659

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

660
  return hres;
661 662
}

663
static HRESULT DataCacheEntry_CreateStream(DataCacheEntry *cache_entry,
664 665 666
                                           IStorage *storage, IStream **stream)
{
    WCHAR wszName[] = {2,'O','l','e','P','r','e','s',
667 668 669
        '0' + (cache_entry->stream_number / 100) % 10,
        '0' + (cache_entry->stream_number / 10) % 10,
        '0' + cache_entry->stream_number % 10, 0};
670 671

    /* FIXME: cache the created stream in This? */
672 673 674
    return IStorage_CreateStream(storage, wszName,
                                 STGM_READWRITE | STGM_SHARE_EXCLUSIVE | STGM_CREATE,
                                 0, 0, stream);
675 676
}

677
static HRESULT DataCacheEntry_Save(DataCacheEntry *cache_entry, IStorage *storage,
678 679 680 681 682 683 684
                                   BOOL same_as_load)
{
    PresentationDataHeader header;
    HRESULT hr;
    IStream *pres_stream;
    void *data = NULL;

685
    TRACE("stream_number = %d, fmtetc = %s\n", cache_entry->stream_number, debugstr_formatetc(&cache_entry->fmtetc));
686

687
    hr = DataCacheEntry_CreateStream(cache_entry, storage, &pres_stream);
688 689 690
    if (FAILED(hr))
        return hr;

691
    hr = write_clipformat(pres_stream, cache_entry->data_cf);
692 693 694
    if (FAILED(hr))
        return hr;

695
    if (cache_entry->fmtetc.ptd)
696 697
        FIXME("ptd not serialized\n");
    header.unknown3 = 4;
698 699 700
    header.dvAspect = cache_entry->fmtetc.dwAspect;
    header.lindex = cache_entry->fmtetc.lindex;
    header.tymed = cache_entry->stgmedium.tymed;
701 702 703 704 705 706
    header.unknown7 = 0;
    header.dwObjectExtentX = 0;
    header.dwObjectExtentY = 0;
    header.dwSize = 0;

    /* size the data */
707
    switch (cache_entry->data_cf)
708 709 710
    {
        case CF_METAFILEPICT:
        {
711
            if (cache_entry->stgmedium.tymed != TYMED_NULL)
712
            {
713
                const METAFILEPICT *mfpict = GlobalLock(cache_entry->stgmedium.u.hMetaFilePict);
714 715 716 717 718 719 720 721
                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);
722
                GlobalUnlock(cache_entry->stgmedium.u.hMetaFilePict);
723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741
            }
            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 */
742
    switch (cache_entry->data_cf)
743 744 745
    {
        case CF_METAFILEPICT:
        {
746
            if (cache_entry->stgmedium.tymed != TYMED_NULL)
747
            {
748
                const METAFILEPICT *mfpict = GlobalLock(cache_entry->stgmedium.u.hMetaFilePict);
749 750 751 752 753 754 755
                if (!mfpict)
                {
                    IStream_Release(pres_stream);
                    return DV_E_STGMEDIUM;
                }
                data = HeapAlloc(GetProcessHeap(), 0, header.dwSize);
                GetMetaFileBitsEx(mfpict->hMF, header.dwSize, data);
756
                GlobalUnlock(cache_entry->stgmedium.u.hMetaFilePict);
757 758 759 760 761 762 763 764 765
            }
            break;
        }
        default:
            break;
    }

    if (data)
        hr = IStream_Write(pres_stream, data, header.dwSize, NULL);
766
    HeapFree(GetProcessHeap(), 0, data);
767 768 769 770 771

    IStream_Release(pres_stream);
    return hr;
}

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 798 799 800 801 802 803 804 805 806 807 808 809 810
/* 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;
}

811
static HRESULT DataCacheEntry_SetData(DataCacheEntry *cache_entry,
812 813 814
                                      const FORMATETC *formatetc,
                                      const STGMEDIUM *stgmedium,
                                      BOOL fRelease)
815
{
816 817
    if ((!cache_entry->fmtetc.cfFormat && !formatetc->cfFormat) ||
        (cache_entry->fmtetc.tymed == TYMED_NULL && formatetc->tymed == TYMED_NULL) ||
818 819 820 821 822 823
        stgmedium->tymed == TYMED_NULL)
    {
        WARN("invalid formatetc\n");
        return DV_E_FORMATETC;
    }

824 825 826
    cache_entry->dirty = TRUE;
    ReleaseStgMedium(&cache_entry->stgmedium);
    cache_entry->data_cf = cache_entry->fmtetc.cfFormat ? cache_entry->fmtetc.cfFormat : formatetc->cfFormat;
827 828
    if (fRelease)
    {
829
        cache_entry->stgmedium = *stgmedium;
830 831 832
        return S_OK;
    }
    else
833 834
        return copy_stg_medium(cache_entry->data_cf,
                               &cache_entry->stgmedium, stgmedium);
835 836
}

837
static HRESULT DataCacheEntry_GetData(DataCacheEntry *cache_entry, STGMEDIUM *stgmedium)
838
{
839
    if (stgmedium->tymed == TYMED_NULL && cache_entry->storage)
840
    {
841
        HRESULT hr = DataCacheEntry_LoadData(cache_entry);
842 843 844
        if (FAILED(hr))
            return hr;
    }
845
    if (cache_entry->stgmedium.tymed == TYMED_NULL)
846
        return OLE_E_BLANK;
847
    return copy_stg_medium(cache_entry->data_cf, stgmedium, &cache_entry->stgmedium);
848 849
}

850
static inline HRESULT DataCacheEntry_DiscardData(DataCacheEntry *cache_entry)
851
{
852 853
    ReleaseStgMedium(&cache_entry->stgmedium);
    cache_entry->data_cf = cache_entry->fmtetc.cfFormat;
854 855 856
    return S_OK;
}

857
static inline void DataCacheEntry_HandsOffStorage(DataCacheEntry *cache_entry)
858
{
859
    if (cache_entry->storage)
860
    {
861 862
        IStorage_Release(cache_entry->storage);
        cache_entry->storage = NULL;
863 864 865
    }
}

866 867 868 869 870 871
/*********************************************************
 * Method implementation for the  non delegating IUnknown
 * part of the DataCache class.
 */

/************************************************************************
872
 * DataCache_NDIUnknown_QueryInterface (IUnknown)
873
 *
874
 * This version of QueryInterface will not delegate its implementation
875 876 877 878 879 880 881
 * to the outer unknown.
 */
static HRESULT WINAPI DataCache_NDIUnknown_QueryInterface(
            IUnknown*      iface,
            REFIID         riid,
            void**         ppvObject)
{
882
  DataCache *this = impl_from_IUnknown(iface);
883

884
  if ( ppvObject==0 )
885
    return E_INVALIDARG;
886

887 888
  *ppvObject = 0;

889
  if (IsEqualIID(&IID_IUnknown, riid))
890 891 892
  {
    *ppvObject = iface;
  }
893
  else if (IsEqualIID(&IID_IDataObject, riid))
894
  {
895
    *ppvObject = &this->IDataObject_iface;
896
  }
897 898
  else if ( IsEqualIID(&IID_IPersistStorage, riid)  ||
            IsEqualIID(&IID_IPersist, riid) )
899
  {
900
    *ppvObject = &this->IPersistStorage_iface;
901
  }
902 903
  else if ( IsEqualIID(&IID_IViewObject, riid) ||
            IsEqualIID(&IID_IViewObject2, riid) )
904
  {
905
    *ppvObject = &this->IViewObject2_iface;
906
  }
907 908
  else if ( IsEqualIID(&IID_IOleCache, riid) ||
            IsEqualIID(&IID_IOleCache2, riid) )
909
  {
910
    *ppvObject = &this->IOleCache2_iface;
911
  }
912
  else if ( IsEqualIID(&IID_IOleCacheControl, riid) )
913
  {
914
    *ppvObject = &this->IOleCacheControl_iface;
915 916 917 918
  }

  if ((*ppvObject)==0)
  {
Andreas Mohr's avatar
Andreas Mohr committed
919
    WARN( "() : asking for unsupported interface %s\n", debugstr_guid(riid));
920 921
    return E_NOINTERFACE;
  }
922

923 924
  IUnknown_AddRef((IUnknown*)*ppvObject);

925
  return S_OK;
926 927 928 929 930
}

/************************************************************************
 * DataCache_NDIUnknown_AddRef (IUnknown)
 *
931
 * This version of QueryInterface will not delegate its implementation
932 933
 * to the outer unknown.
 */
934
static ULONG WINAPI DataCache_NDIUnknown_AddRef(
935 936
            IUnknown*      iface)
{
937
  DataCache *this = impl_from_IUnknown(iface);
938
  return InterlockedIncrement(&this->ref);
939 940 941 942 943
}

/************************************************************************
 * DataCache_NDIUnknown_Release (IUnknown)
 *
944
 * This version of QueryInterface will not delegate its implementation
945 946
 * to the outer unknown.
 */
947
static ULONG WINAPI DataCache_NDIUnknown_Release(
948 949
            IUnknown*      iface)
{
950
  DataCache *this = impl_from_IUnknown(iface);
951
  ULONG ref;
952

953
  ref = InterlockedDecrement(&this->ref);
954

955
  if (ref == 0) DataCache_Destroy(this);
956

957
  return ref;
958 959 960 961 962 963 964 965 966 967 968 969 970 971 972
}

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

/************************************************************************
 * DataCache_IDataObject_QueryInterface (IUnknown)
 */
static HRESULT WINAPI DataCache_IDataObject_QueryInterface(
            IDataObject*     iface,
            REFIID           riid,
            void**           ppvObject)
{
973
  DataCache *this = impl_from_IDataObject(iface);
974

975
  return IUnknown_QueryInterface(this->outerUnknown, riid, ppvObject);
976 977 978 979 980
}

/************************************************************************
 * DataCache_IDataObject_AddRef (IUnknown)
 */
981
static ULONG WINAPI DataCache_IDataObject_AddRef(
982 983
            IDataObject*     iface)
{
984
  DataCache *this = impl_from_IDataObject(iface);
985

986
  return IUnknown_AddRef(this->outerUnknown);
987 988 989 990 991
}

/************************************************************************
 * DataCache_IDataObject_Release (IUnknown)
 */
992
static ULONG WINAPI DataCache_IDataObject_Release(
993 994
            IDataObject*     iface)
{
995
  DataCache *this = impl_from_IDataObject(iface);
996

997
  return IUnknown_Release(this->outerUnknown);
998 999
}

1000 1001 1002 1003 1004
/************************************************************************
 * DataCache_GetData
 *
 * Get Data from a source dataobject using format pformatetcIn->cfFormat
 */
1005 1006
static HRESULT WINAPI DataCache_GetData(
	    IDataObject*     iface,
1007
	    LPFORMATETC      pformatetcIn,
1008 1009
	    STGMEDIUM*       pmedium)
{
1010 1011
    DataCache *This = impl_from_IDataObject(iface);
    DataCacheEntry *cache_entry;
1012

1013
    memset(pmedium, 0, sizeof(*pmedium));
1014

1015 1016 1017
    cache_entry = DataCache_GetEntryForFormatEtc(This, pformatetcIn);
    if (!cache_entry)
        return OLE_E_BLANK;
1018

1019
    return DataCacheEntry_GetData(cache_entry, pmedium);
1020 1021 1022
}

static HRESULT WINAPI DataCache_GetDataHere(
1023
	    IDataObject*     iface,
1024 1025 1026
	    LPFORMATETC      pformatetc,
	    STGMEDIUM*       pmedium)
{
1027
  FIXME("stub\n");
1028 1029 1030 1031 1032 1033 1034
  return E_NOTIMPL;
}

static HRESULT WINAPI DataCache_QueryGetData(
	    IDataObject*     iface,
	    LPFORMATETC      pformatetc)
{
1035
  FIXME("stub\n");
1036 1037 1038 1039 1040 1041 1042 1043 1044
  return E_NOTIMPL;
}

/************************************************************************
 * DataCache_EnumFormatEtc (IDataObject)
 *
 * The data cache doesn't implement this method.
 */
static HRESULT WINAPI DataCache_GetCanonicalFormatEtc(
1045 1046
	    IDataObject*     iface,
	    LPFORMATETC      pformatectIn,
1047 1048
	    LPFORMATETC      pformatetcOut)
{
1049
  TRACE("()\n");
1050 1051 1052 1053 1054 1055 1056 1057 1058 1059
  return E_NOTIMPL;
}

/************************************************************************
 * DataCache_IDataObject_SetData (IDataObject)
 *
 * This method is delegated to the IOleCache2 implementation.
 */
static HRESULT WINAPI DataCache_IDataObject_SetData(
	    IDataObject*     iface,
1060 1061
	    LPFORMATETC      pformatetc,
	    STGMEDIUM*       pmedium,
1062 1063 1064 1065 1066
	    BOOL             fRelease)
{
  IOleCache2* oleCache = NULL;
  HRESULT     hres;

1067
  TRACE("(%p, %p, %p, %d)\n", iface, pformatetc, pmedium, fRelease);
1068

1069
  hres = IDataObject_QueryInterface(iface, &IID_IOleCache2, (void**)&oleCache);
1070 1071 1072 1073 1074 1075 1076 1077

  if (FAILED(hres))
    return E_UNEXPECTED;

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

  IOleCache2_Release(oleCache);

1078
  return hres;
1079 1080 1081 1082 1083 1084 1085 1086
}

/************************************************************************
 * DataCache_EnumFormatEtc (IDataObject)
 *
 * The data cache doesn't implement this method.
 */
static HRESULT WINAPI DataCache_EnumFormatEtc(
1087
	    IDataObject*     iface,
1088 1089 1090
	    DWORD            dwDirection,
	    IEnumFORMATETC** ppenumFormatEtc)
{
1091
  TRACE("()\n");
1092 1093 1094 1095 1096 1097 1098 1099 1100
  return E_NOTIMPL;
}

/************************************************************************
 * DataCache_DAdvise (IDataObject)
 *
 * The data cache doesn't support connections.
 */
static HRESULT WINAPI DataCache_DAdvise(
1101 1102 1103 1104
	    IDataObject*     iface,
	    FORMATETC*       pformatetc,
	    DWORD            advf,
	    IAdviseSink*     pAdvSink,
1105 1106
	    DWORD*           pdwConnection)
{
1107
  TRACE("()\n");
1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119
  return OLE_E_ADVISENOTSUPPORTED;
}

/************************************************************************
 * DataCache_DUnadvise (IDataObject)
 *
 * The data cache doesn't support connections.
 */
static HRESULT WINAPI DataCache_DUnadvise(
	    IDataObject*     iface,
	    DWORD            dwConnection)
{
1120
  TRACE("()\n");
1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132
  return OLE_E_NOCONNECTION;
}

/************************************************************************
 * DataCache_EnumDAdvise (IDataObject)
 *
 * The data cache doesn't support connections.
 */
static HRESULT WINAPI DataCache_EnumDAdvise(
	    IDataObject*     iface,
	    IEnumSTATDATA**  ppenumAdvise)
{
1133
  TRACE("()\n");
1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149
  return OLE_E_ADVISENOTSUPPORTED;
}

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

/************************************************************************
 * DataCache_IPersistStorage_QueryInterface (IUnknown)
 */
static HRESULT WINAPI DataCache_IPersistStorage_QueryInterface(
            IPersistStorage* iface,
            REFIID           riid,
            void**           ppvObject)
{
1150
  DataCache *this = impl_from_IPersistStorage(iface);
1151

1152
  return IUnknown_QueryInterface(this->outerUnknown, riid, ppvObject);
1153 1154 1155 1156 1157
}

/************************************************************************
 * DataCache_IPersistStorage_AddRef (IUnknown)
 */
1158
static ULONG WINAPI DataCache_IPersistStorage_AddRef(
1159 1160
            IPersistStorage* iface)
{
1161
  DataCache *this = impl_from_IPersistStorage(iface);
1162

1163
  return IUnknown_AddRef(this->outerUnknown);
1164 1165 1166 1167 1168
}

/************************************************************************
 * DataCache_IPersistStorage_Release (IUnknown)
 */
1169
static ULONG WINAPI DataCache_IPersistStorage_Release(
1170 1171
            IPersistStorage* iface)
{
1172
  DataCache *this = impl_from_IPersistStorage(iface);
1173

1174
  return IUnknown_Release(this->outerUnknown);
1175 1176 1177 1178 1179 1180 1181
}

/************************************************************************
 * DataCache_GetClassID (IPersistStorage)
 *
 * The data cache doesn't implement this method.
 */
1182
static HRESULT WINAPI DataCache_GetClassID(
Patrik Stridvall's avatar
Patrik Stridvall committed
1183
            IPersistStorage* iface,
1184 1185
	    CLSID*           pClassID)
{
1186
  DataCache *This = impl_from_IPersistStorage(iface);
1187
  DataCacheEntry *cache_entry;
1188

1189
  TRACE("(%p, %p)\n", iface, pClassID);
1190

1191
  LIST_FOR_EACH_ENTRY(cache_entry, &This->cache_list, DataCacheEntry, entry)
1192
  {
1193 1194 1195 1196 1197 1198
    if (cache_entry->storage != NULL)
    {
      STATSTG statstg;
      HRESULT hr = IStorage_Stat(cache_entry->storage, &statstg, STATFLAG_NONAME);
      if (SUCCEEDED(hr))
      {
1199
        *pClassID = statstg.clsid;
1200 1201 1202
        return S_OK;
      }
    }
1203 1204
  }

1205
  *pClassID = CLSID_NULL;
1206 1207

  return S_OK;
1208 1209
}

1210 1211 1212
/************************************************************************
 * DataCache_IsDirty (IPersistStorage)
 */
1213
static HRESULT WINAPI DataCache_IsDirty(
1214 1215
            IPersistStorage* iface)
{
1216 1217 1218 1219
    DataCache *This = impl_from_IPersistStorage(iface);
    DataCacheEntry *cache_entry;

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

1221 1222 1223 1224 1225 1226 1227 1228
    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;
1229 1230 1231 1232 1233 1234 1235 1236
}

/************************************************************************
 * DataCache_InitNew (IPersistStorage)
 *
 * The data cache implementation of IPersistStorage_InitNew simply stores
 * the storage pointer.
 */
1237 1238
static HRESULT WINAPI DataCache_InitNew(
            IPersistStorage* iface,
1239 1240
	    IStorage*        pStg)
{
1241 1242 1243 1244 1245 1246 1247 1248
    DataCache *This = impl_from_IPersistStorage(iface);

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

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

    This->presentationStorage = pStg;
1249

1250 1251 1252 1253
    IStorage_AddRef(This->presentationStorage);
    This->dirty = TRUE;

    return S_OK;
1254 1255 1256 1257 1258
}

/************************************************************************
 * DataCache_Load (IPersistStorage)
 *
1259
 * The data cache implementation of IPersistStorage_Load doesn't
1260
 * actually load anything. Instead, it holds on to the storage pointer
1261
 * and it will load the presentation information when the
1262 1263
 * IDataObject_GetData or IViewObject2_Draw methods are called.
 */
1264
static HRESULT WINAPI DataCache_Load(
1265 1266 1267
            IPersistStorage* iface,
	    IStorage*        pStg)
{
1268 1269 1270 1271
    DataCache *This = impl_from_IPersistStorage(iface);
    STATSTG elem;
    IEnumSTATSTG *pEnum;
    HRESULT hr;
1272

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

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

1278
    This->presentationStorage = pStg;
1279

1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293
    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))
	    {
1294 1295 1296 1297 1298
                PresentationDataHeader header;
                ULONG actual_read;
                CLIPFORMAT clipformat;

                hr = read_clipformat(pStm, &clipformat);
1299

1300 1301 1302
                if (hr == S_OK)
                    hr = IStream_Read(pStm, &header, sizeof(header),
                                      &actual_read);
1303 1304 1305 1306 1307 1308 1309

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

1310
		    fmtetc.cfFormat = clipformat;
1311 1312
		    fmtetc.ptd = NULL; /* FIXME */
		    fmtetc.dwAspect = header.dvAspect;
1313 1314 1315
		    fmtetc.lindex = header.lindex;
		    fmtetc.tymed = header.tymed;

1316
                    TRACE("loading entry with formatetc: %s\n", debugstr_formatetc(&fmtetc));
1317 1318 1319 1320 1321 1322

                    cache_entry = DataCache_GetEntryForFormatEtc(This, &fmtetc);
                    if (!cache_entry)
                        hr = DataCache_CreateEntry(This, &fmtetc, &cache_entry);
                    if (SUCCEEDED(hr))
                    {
1323
                        DataCacheEntry_DiscardData(cache_entry);
1324 1325 1326
                        if (cache_entry->storage) IStorage_Release(cache_entry->storage);
                        cache_entry->storage = pStg;
                        IStorage_AddRef(pStg);
1327
                        cache_entry->dirty = FALSE;
1328 1329 1330 1331 1332 1333 1334 1335 1336 1337
                    }
		}

		IStream_Release(pStm);
	    }
	}

	CoTaskMemFree(elem.pwcsName);
    }

1338 1339
    This->dirty = FALSE;

1340 1341 1342 1343
    IEnumSTATSTG_Release(pEnum);

    IStorage_AddRef(This->presentationStorage);
    return S_OK;
1344 1345
}

1346 1347 1348
/************************************************************************
 * DataCache_Save (IPersistStorage)
 *
1349
 * Until we actually connect to a running object and retrieve new
1350
 * information to it, we never have to save anything. However, it is
1351
 * our responsibility to copy the information when saving to a new
1352 1353
 * storage.
 */
1354
static HRESULT WINAPI DataCache_Save(
1355
            IPersistStorage* iface,
1356
	    IStorage*        pStg,
1357 1358
	    BOOL             fSameAsLoad)
{
1359 1360 1361
    DataCache *This = impl_from_IPersistStorage(iface);
    DataCacheEntry *cache_entry;
    BOOL dirty = FALSE;
1362 1363
    HRESULT hr = S_OK;
    unsigned short stream_number = 0;
1364

1365
    TRACE("(%p, %p, %d)\n", iface, pStg, fSameAsLoad);
1366

1367 1368 1369 1370 1371 1372 1373 1374 1375 1376
    dirty = This->dirty;
    if (!dirty)
    {
        LIST_FOR_EACH_ENTRY(cache_entry, &This->cache_list, DataCacheEntry, entry)
        {
            dirty = cache_entry->dirty;
            if (dirty)
                break;
        }
    }
1377

1378 1379 1380 1381 1382 1383
    /* this is a shortcut if nothing changed */
    if (!dirty && !fSameAsLoad && This->presentationStorage)
    {
        return IStorage_CopyTo(This->presentationStorage, 0, NULL, NULL, pStg);
    }

1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395
    /* 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 */
1396 1397
    LIST_FOR_EACH_ENTRY(cache_entry, &This->cache_list, DataCacheEntry, entry)
    {
1398 1399 1400 1401 1402 1403 1404 1405
        if (!fSameAsLoad || cache_entry->dirty)
        {
            hr = DataCacheEntry_Save(cache_entry, pStg, fSameAsLoad);
            if (FAILED(hr))
                break;

            cache_entry->dirty = FALSE;
        }
1406 1407 1408
    }

    This->dirty = FALSE;
1409
    return hr;
1410 1411 1412 1413 1414 1415
}

/************************************************************************
 * DataCache_SaveCompleted (IPersistStorage)
 *
 * This method is called to tell the cache to release the storage
1416
 * pointer it's currently holding.
1417
 */
1418 1419
static HRESULT WINAPI DataCache_SaveCompleted(
            IPersistStorage* iface,
1420 1421
	    IStorage*        pStgNew)
{
1422
  TRACE("(%p, %p)\n", iface, pStgNew);
1423

1424 1425
  if (pStgNew)
  {
1426
    IPersistStorage_HandsOffStorage(iface);
1427

1428
    DataCache_Load(iface, pStgNew);
1429
  }
1430 1431 1432 1433 1434 1435 1436 1437

  return S_OK;
}

/************************************************************************
 * DataCache_HandsOffStorage (IPersistStorage)
 *
 * This method is called to tell the cache to release the storage
1438
 * pointer it's currently holding.
1439 1440 1441 1442
 */
static HRESULT WINAPI DataCache_HandsOffStorage(
            IPersistStorage* iface)
{
1443
  DataCache *this = impl_from_IPersistStorage(iface);
1444
  DataCacheEntry *cache_entry;
1445

1446
  TRACE("(%p)\n", iface);
1447 1448 1449 1450 1451 1452 1453

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

1454 1455 1456
  LIST_FOR_EACH_ENTRY(cache_entry, &this->cache_list, DataCacheEntry, entry)
    DataCacheEntry_HandsOffStorage(cache_entry);

1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472
  return S_OK;
}

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

/************************************************************************
 * DataCache_IViewObject2_QueryInterface (IUnknown)
 */
static HRESULT WINAPI DataCache_IViewObject2_QueryInterface(
            IViewObject2* iface,
            REFIID           riid,
            void**           ppvObject)
{
1473
  DataCache *this = impl_from_IViewObject2(iface);
1474

1475
  return IUnknown_QueryInterface(this->outerUnknown, riid, ppvObject);
1476 1477 1478 1479 1480
}

/************************************************************************
 * DataCache_IViewObject2_AddRef (IUnknown)
 */
1481
static ULONG WINAPI DataCache_IViewObject2_AddRef(
1482 1483
            IViewObject2* iface)
{
1484
  DataCache *this = impl_from_IViewObject2(iface);
1485

1486
  return IUnknown_AddRef(this->outerUnknown);
1487 1488 1489 1490 1491
}

/************************************************************************
 * DataCache_IViewObject2_Release (IUnknown)
 */
1492
static ULONG WINAPI DataCache_IViewObject2_Release(
1493 1494
            IViewObject2* iface)
{
1495
  DataCache *this = impl_from_IViewObject2(iface);
1496

1497
  return IUnknown_Release(this->outerUnknown);
1498 1499
}

1500 1501 1502 1503 1504 1505
/************************************************************************
 * DataCache_Draw (IViewObject2)
 *
 * This method will draw the cached representation of the object
 * to the given device context.
 */
1506 1507 1508 1509 1510
static HRESULT WINAPI DataCache_Draw(
            IViewObject2*    iface,
	    DWORD            dwDrawAspect,
	    LONG             lindex,
	    void*            pvAspect,
1511 1512
	    DVTARGETDEVICE*  ptd,
	    HDC              hdcTargetDev,
1513 1514 1515
	    HDC              hdcDraw,
	    LPCRECTL         lprcBounds,
	    LPCRECTL         lprcWBounds,
1516
	    BOOL  (CALLBACK *pfnContinue)(ULONG_PTR dwContinue),
1517
	    ULONG_PTR        dwContinue)
1518
{
1519
  DataCache *This = impl_from_IViewObject2(iface);
1520
  HRESULT                hres;
1521
  DataCacheEntry        *cache_entry;
1522

1523
  TRACE("(%p, %x, %d, %p, %p, %p, %p, %p, %p, %lx)\n",
1524 1525 1526 1527
	iface,
	dwDrawAspect,
	lindex,
	pvAspect,
1528
	hdcTargetDev,
1529 1530 1531 1532 1533 1534 1535 1536 1537
	hdcDraw,
	lprcBounds,
	lprcWBounds,
	pfnContinue,
	dwContinue);

  if (lprcBounds==NULL)
    return E_INVALIDARG;

1538 1539 1540 1541 1542 1543 1544
  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;

1545 1546
    /* if the data hasn't been loaded yet, do it now */
    if ((cache_entry->stgmedium.tymed == TYMED_NULL) && cache_entry->storage)
1547
    {
1548 1549 1550 1551 1552 1553 1554 1555 1556
      hres = DataCacheEntry_LoadData(cache_entry);
      if (FAILED(hres))
        continue;
    }

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

1557 1558
    if (pfnContinue && !pfnContinue(dwContinue)) return E_ABORT;

1559
    switch (cache_entry->data_cf)
1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616
    {
      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;
      }
1617
    }
1618 1619
  }

1620 1621
  WARN("no data could be found to be drawn\n");

1622
  return OLE_E_BLANK;
1623 1624 1625
}

static HRESULT WINAPI DataCache_GetColorSet(
1626 1627 1628 1629 1630 1631
            IViewObject2*   iface,
	    DWORD           dwDrawAspect,
	    LONG            lindex,
	    void*           pvAspect,
	    DVTARGETDEVICE* ptd,
	    HDC             hicTargetDevice,
1632 1633
	    LOGPALETTE**    ppColorSet)
{
1634
  FIXME("stub\n");
1635 1636 1637 1638 1639 1640 1641
  return E_NOTIMPL;
}

static HRESULT WINAPI DataCache_Freeze(
            IViewObject2*   iface,
	    DWORD           dwDrawAspect,
	    LONG            lindex,
1642
	    void*           pvAspect,
1643 1644
	    DWORD*          pdwFreeze)
{
1645
  FIXME("stub\n");
1646 1647 1648 1649 1650 1651 1652
  return E_NOTIMPL;
}

static HRESULT WINAPI DataCache_Unfreeze(
            IViewObject2*   iface,
	    DWORD           dwFreeze)
{
1653
  FIXME("stub\n");
1654 1655 1656
  return E_NOTIMPL;
}

1657 1658 1659 1660 1661 1662
/************************************************************************
 * DataCache_SetAdvise (IViewObject2)
 *
 * This sets-up an advisory sink with the data cache. When the object's
 * view changes, this sink is called.
 */
1663 1664
static HRESULT WINAPI DataCache_SetAdvise(
            IViewObject2*   iface,
1665 1666
	    DWORD           aspects,
	    DWORD           advf,
1667 1668
	    IAdviseSink*    pAdvSink)
{
1669
  DataCache *this = impl_from_IViewObject2(iface);
1670

1671
  TRACE("(%p, %x, %x, %p)\n", iface, aspects, advf, pAdvSink);
1672 1673 1674 1675 1676 1677 1678 1679

  /*
   * A call to this function removes the previous sink
   */
  if (this->sinkInterface != NULL)
  {
    IAdviseSink_Release(this->sinkInterface);
    this->sinkInterface  = NULL;
1680
    this->sinkAspects    = 0;
1681 1682 1683 1684 1685 1686 1687 1688 1689
    this->sinkAdviseFlag = 0;
  }

  /*
   * Now, setup the new one.
   */
  if (pAdvSink!=NULL)
  {
    this->sinkInterface  = pAdvSink;
1690 1691
    this->sinkAspects    = aspects;
    this->sinkAdviseFlag = advf;
1692 1693 1694 1695 1696 1697 1698 1699 1700 1701

    IAdviseSink_AddRef(this->sinkInterface);
  }

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

1705 1706 1707
  return S_OK;
}

1708 1709 1710
/************************************************************************
 * DataCache_GetAdvise (IViewObject2)
 *
1711
 * This method queries the current state of the advise sink
1712 1713
 * installed on the data cache.
 */
1714
static HRESULT WINAPI DataCache_GetAdvise(
1715 1716 1717
            IViewObject2*   iface,
	    DWORD*          pAspects,
	    DWORD*          pAdvf,
1718 1719
	    IAdviseSink**   ppAdvSink)
{
1720
  DataCache *this = impl_from_IViewObject2(iface);
1721

1722
  TRACE("(%p, %p, %p, %p)\n", iface, pAspects, pAdvf, ppAdvSink);
1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734

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

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

  if (ppAdvSink!=NULL)
  {
1735 1736
    if (this->sinkInterface != NULL)
        IAdviseSink_QueryInterface(this->sinkInterface,
1737
			       &IID_IAdviseSink,
1738
			       (void**)ppAdvSink);
1739
    else *ppAdvSink = NULL;
1740 1741 1742
  }

  return S_OK;
1743 1744
}

1745 1746 1747 1748 1749
/************************************************************************
 * DataCache_GetExtent (IViewObject2)
 *
 * This method retrieves the "natural" size of this cached object.
 */
1750
static HRESULT WINAPI DataCache_GetExtent(
1751 1752 1753 1754
            IViewObject2*   iface,
	    DWORD           dwDrawAspect,
	    LONG            lindex,
	    DVTARGETDEVICE* ptd,
1755 1756
	    LPSIZEL         lpsizel)
{
1757
  DataCache *This = impl_from_IViewObject2(iface);
1758
  HRESULT                hres = E_FAIL;
1759
  DataCacheEntry        *cache_entry;
1760

1761
  TRACE("(%p, %x, %d, %p, %p)\n",
1762 1763 1764 1765 1766 1767 1768 1769 1770
	iface, dwDrawAspect, lindex, ptd, lpsizel);

  if (lpsizel==NULL)
    return E_POINTER;

  lpsizel->cx = 0;
  lpsizel->cy = 0;

  if (lindex!=-1)
1771
    FIXME("Unimplemented flag lindex = %d\n", lindex);
1772 1773

  /*
1774
   * Right now, we support only the callback from
1775 1776 1777
   * the default handler.
   */
  if (ptd!=NULL)
1778
    FIXME("Unimplemented ptd = %p\n", ptd);
1779

1780 1781 1782 1783 1784 1785 1786
  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;

1787 1788 1789 1790 1791 1792 1793
    /* 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;
    }
1794

1795 1796 1797 1798 1799
    /* no data */
    if (cache_entry->stgmedium.tymed == TYMED_NULL)
      continue;


1800
    switch (cache_entry->data_cf)
1801
    {
1802 1803 1804 1805 1806 1807 1808
      case CF_METAFILEPICT:
      {
          METAFILEPICT *mfpict;

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

1810 1811 1812 1813 1814 1815 1816
        lpsizel->cx = mfpict->xExt;
        lpsizel->cy = mfpict->yExt;

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

        return S_OK;
      }
1817
    }
1818 1819
  }

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

1822 1823 1824
  /*
   * This method returns OLE_E_BLANK when it fails.
   */
1825
  return OLE_E_BLANK;
1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841
}


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

/************************************************************************
 * DataCache_IOleCache2_QueryInterface (IUnknown)
 */
static HRESULT WINAPI DataCache_IOleCache2_QueryInterface(
            IOleCache2*     iface,
            REFIID          riid,
            void**          ppvObject)
{
1842
  DataCache *this = impl_from_IOleCache2(iface);
1843

1844
  return IUnknown_QueryInterface(this->outerUnknown, riid, ppvObject);
1845 1846 1847 1848 1849
}

/************************************************************************
 * DataCache_IOleCache2_AddRef (IUnknown)
 */
1850
static ULONG WINAPI DataCache_IOleCache2_AddRef(
1851 1852
            IOleCache2*     iface)
{
1853
  DataCache *this = impl_from_IOleCache2(iface);
1854

1855
  return IUnknown_AddRef(this->outerUnknown);
1856 1857 1858 1859 1860
}

/************************************************************************
 * DataCache_IOleCache2_Release (IUnknown)
 */
1861
static ULONG WINAPI DataCache_IOleCache2_Release(
1862 1863
            IOleCache2*     iface)
{
1864
  DataCache *this = impl_from_IOleCache2(iface);
1865

1866
  return IUnknown_Release(this->outerUnknown);
1867 1868
}

1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884
/*****************************************************************************
 * setup_sink
 *
 * Set up the sink connection to the running object.
 */
static HRESULT setup_sink(DataCache *This, DataCacheEntry *cache_entry)
{
    HRESULT hr = S_FALSE;
    DWORD flags;

    /* Clear the ADVFCACHE_* bits.  Native also sets the two highest bits for some reason. */
    flags = cache_entry->advise_flags & ~(ADVFCACHE_NOHANDLER | ADVFCACHE_FORCEBUILTIN | ADVFCACHE_ONSAVE);

    if(This->running_object)
        if(!(flags & ADVF_NODATA))
            hr = IDataObject_DAdvise(This->running_object, &cache_entry->fmtetc, flags,
1885
                                     &This->IAdviseSink_iface, &cache_entry->sink_id);
1886 1887 1888
    return hr;
}

1889 1890 1891 1892 1893 1894
static HRESULT WINAPI DataCache_Cache(
            IOleCache2*     iface,
	    FORMATETC*      pformatetc,
	    DWORD           advf,
	    DWORD*          pdwConnection)
{
1895 1896 1897 1898 1899
    DataCache *This = impl_from_IOleCache2(iface);
    DataCacheEntry *cache_entry;
    HRESULT hr;

    TRACE("(%p, 0x%x, %p)\n", pformatetc, advf, pdwConnection);
1900 1901 1902 1903

    if (!pformatetc || !pdwConnection)
        return E_INVALIDARG;

1904
    TRACE("pformatetc = %s\n", debugstr_formatetc(pformatetc));
1905 1906 1907 1908 1909 1910

    *pdwConnection = 0;

    cache_entry = DataCache_GetEntryForFormatEtc(This, pformatetc);
    if (cache_entry)
    {
1911
        TRACE("found an existing cache entry\n");
1912 1913 1914 1915 1916 1917 1918
        *pdwConnection = cache_entry->id;
        return CACHE_S_SAMECACHE;
    }

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

    if (SUCCEEDED(hr))
1919
    {
1920
        *pdwConnection = cache_entry->id;
1921 1922 1923
        cache_entry->advise_flags = advf;
        setup_sink(This, cache_entry);
    }
1924 1925

    return hr;
1926 1927 1928 1929 1930 1931
}

static HRESULT WINAPI DataCache_Uncache(
	    IOleCache2*     iface,
	    DWORD           dwConnection)
{
1932 1933 1934 1935 1936 1937 1938 1939
    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)
        {
1940
            DataCacheEntry_Destroy(This, cache_entry);
1941 1942 1943
            return S_OK;
        }

1944 1945
    WARN("no connection found for %d\n", dwConnection);

1946
    return OLE_E_NOCONNECTION;
1947 1948 1949 1950 1951 1952
}

static HRESULT WINAPI DataCache_EnumCache(
            IOleCache2*     iface,
	    IEnumSTATDATA** ppenumSTATDATA)
{
1953
  FIXME("stub\n");
1954 1955 1956 1957 1958 1959 1960
  return E_NOTIMPL;
}

static HRESULT WINAPI DataCache_InitCache(
	    IOleCache2*     iface,
	    IDataObject*    pDataObject)
{
1961
  FIXME("stub\n");
1962 1963 1964 1965 1966 1967 1968 1969 1970
  return E_NOTIMPL;
}

static HRESULT WINAPI DataCache_IOleCache2_SetData(
            IOleCache2*     iface,
	    FORMATETC*      pformatetc,
	    STGMEDIUM*      pmedium,
	    BOOL            fRelease)
{
1971 1972 1973 1974 1975
    DataCache *This = impl_from_IOleCache2(iface);
    DataCacheEntry *cache_entry;
    HRESULT hr;

    TRACE("(%p, %p, %s)\n", pformatetc, pmedium, fRelease ? "TRUE" : "FALSE");
1976
    TRACE("formatetc = %s\n", debugstr_formatetc(pformatetc));
1977 1978 1979 1980

    cache_entry = DataCache_GetEntryForFormatEtc(This, pformatetc);
    if (cache_entry)
    {
1981
        hr = DataCacheEntry_SetData(cache_entry, pformatetc, pmedium, fRelease);
1982 1983 1984 1985 1986 1987 1988

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

        return hr;
    }
1989
    WARN("cache entry not found\n");
1990 1991

    return OLE_E_BLANK;
1992 1993 1994 1995
}

static HRESULT WINAPI DataCache_UpdateCache(
            IOleCache2*     iface,
1996
	    LPDATAOBJECT    pDataObject,
1997 1998 1999
	    DWORD           grfUpdf,
	    LPVOID          pReserved)
{
2000
  FIXME("(%p, 0x%x, %p): stub\n", pDataObject, grfUpdf, pReserved);
2001 2002 2003 2004 2005 2006 2007
  return E_NOTIMPL;
}

static HRESULT WINAPI DataCache_DiscardCache(
            IOleCache2*     iface,
	    DWORD           dwDiscardOptions)
{
2008 2009 2010 2011 2012 2013 2014
    DataCache *This = impl_from_IOleCache2(iface);
    DataCacheEntry *cache_entry;
    HRESULT hr = S_OK;

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

    if (dwDiscardOptions == DISCARDCACHE_SAVEIFDIRTY)
2015
        hr = DataCache_Save(&This->IPersistStorage_iface, This->presentationStorage, TRUE);
2016 2017 2018 2019 2020 2021 2022 2023 2024

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

    return hr;
2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040
}


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

/************************************************************************
 * DataCache_IOleCacheControl_QueryInterface (IUnknown)
 */
static HRESULT WINAPI DataCache_IOleCacheControl_QueryInterface(
            IOleCacheControl* iface,
            REFIID            riid,
            void**            ppvObject)
{
2041
  DataCache *this = impl_from_IOleCacheControl(iface);
2042

2043
  return IUnknown_QueryInterface(this->outerUnknown, riid, ppvObject);
2044 2045 2046 2047 2048
}

/************************************************************************
 * DataCache_IOleCacheControl_AddRef (IUnknown)
 */
2049
static ULONG WINAPI DataCache_IOleCacheControl_AddRef(
2050 2051
            IOleCacheControl* iface)
{
2052
  DataCache *this = impl_from_IOleCacheControl(iface);
2053

2054
  return IUnknown_AddRef(this->outerUnknown);
2055 2056 2057 2058 2059
}

/************************************************************************
 * DataCache_IOleCacheControl_Release (IUnknown)
 */
2060
static ULONG WINAPI DataCache_IOleCacheControl_Release(
2061 2062
            IOleCacheControl* iface)
{
2063
  DataCache *this = impl_from_IOleCacheControl(iface);
2064

2065
  return IUnknown_Release(this->outerUnknown);
2066 2067
}

2068 2069 2070 2071
/************************************************************************
 * DataCache_OnRun (IOleCacheControl)
 */
static HRESULT WINAPI DataCache_OnRun(IOleCacheControl* iface, IDataObject *data_obj)
2072
{
2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088
    DataCache *This = impl_from_IOleCacheControl(iface);
    DataCacheEntry *cache_entry;

    TRACE("(%p)->(%p)\n", iface, data_obj);

    if(This->running_object) return S_OK;

    /* No reference is taken on the data object */
    This->running_object = data_obj;

    LIST_FOR_EACH_ENTRY(cache_entry, &This->cache_list, DataCacheEntry, entry)
    {
        setup_sink(This, cache_entry);
    }

    return S_OK;
2089 2090
}

2091 2092 2093 2094
/************************************************************************
 * DataCache_OnStop (IOleCacheControl)
 */
static HRESULT WINAPI DataCache_OnStop(IOleCacheControl* iface)
2095
{
2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114
    DataCache *This = impl_from_IOleCacheControl(iface);
    DataCacheEntry *cache_entry;

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

    if(!This->running_object) return S_OK;

    LIST_FOR_EACH_ENTRY(cache_entry, &This->cache_list, DataCacheEntry, entry)
    {
        if(cache_entry->sink_id)
        {
            IDataObject_DUnadvise(This->running_object, cache_entry->sink_id);
            cache_entry->sink_id = 0;
        }
    }

    /* No ref taken in OnRun, so no Release call here */
    This->running_object = NULL;
    return S_OK;
2115
}
2116

2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151
/************************************************************************
 *              IAdviseSink methods.
 * This behaves as an internal object to the data cache.  QI'ing its ptr doesn't
 * give access to the cache's other interfaces.  We don't maintain a ref count,
 * the object exists as long as the cache is around.
 */
static HRESULT WINAPI DataCache_IAdviseSink_QueryInterface(IAdviseSink *iface, REFIID iid, void **obj)
{
    *obj = NULL;
    if (IsEqualIID(&IID_IUnknown, iid) ||
        IsEqualIID(&IID_IAdviseSink, iid))
    {
        *obj = iface;
    }

    if(*obj)
    {
        IAdviseSink_AddRef(iface);
        return S_OK;
    }
    return E_NOINTERFACE;
}

static ULONG WINAPI DataCache_IAdviseSink_AddRef(IAdviseSink *iface)
{
    return 2;
}

static ULONG WINAPI DataCache_IAdviseSink_Release(IAdviseSink *iface)
{
    return 1;
}

static void WINAPI DataCache_OnDataChange(IAdviseSink *iface, FORMATETC *fmt, STGMEDIUM *med)
{
2152 2153
    DataCache *This = impl_from_IAdviseSink(iface);
    TRACE("(%p)->(%s, %p)\n", This, debugstr_formatetc(fmt), med);
2154
    IOleCache2_SetData(&This->IOleCache2_iface, fmt, med, FALSE);
2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176
}

static void WINAPI DataCache_OnViewChange(IAdviseSink *iface, DWORD aspect, LONG index)
{
    FIXME("stub\n");
}

static void WINAPI DataCache_OnRename(IAdviseSink *iface, IMoniker *mk)
{
    FIXME("stub\n");
}

static void WINAPI DataCache_OnSave(IAdviseSink *iface)
{
    FIXME("stub\n");
}

static void WINAPI DataCache_OnClose(IAdviseSink *iface)
{
    FIXME("stub\n");
}

2177 2178 2179
/*
 * Virtual function tables for the DataCache class.
 */
2180
static const IUnknownVtbl DataCache_NDIUnknown_VTable =
2181 2182 2183 2184 2185 2186
{
  DataCache_NDIUnknown_QueryInterface,
  DataCache_NDIUnknown_AddRef,
  DataCache_NDIUnknown_Release
};

2187
static const IDataObjectVtbl DataCache_IDataObject_VTable =
2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202
{
  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
};

2203
static const IPersistStorageVtbl DataCache_IPersistStorage_VTable =
2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216
{
  DataCache_IPersistStorage_QueryInterface,
  DataCache_IPersistStorage_AddRef,
  DataCache_IPersistStorage_Release,
  DataCache_GetClassID,
  DataCache_IsDirty,
  DataCache_InitNew,
  DataCache_Load,
  DataCache_Save,
  DataCache_SaveCompleted,
  DataCache_HandsOffStorage
};

2217
static const IViewObject2Vtbl DataCache_IViewObject2_VTable =
2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230
{
  DataCache_IViewObject2_QueryInterface,
  DataCache_IViewObject2_AddRef,
  DataCache_IViewObject2_Release,
  DataCache_Draw,
  DataCache_GetColorSet,
  DataCache_Freeze,
  DataCache_Unfreeze,
  DataCache_SetAdvise,
  DataCache_GetAdvise,
  DataCache_GetExtent
};

2231
static const IOleCache2Vtbl DataCache_IOleCache2_VTable =
2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244
{
  DataCache_IOleCache2_QueryInterface,
  DataCache_IOleCache2_AddRef,
  DataCache_IOleCache2_Release,
  DataCache_Cache,
  DataCache_Uncache,
  DataCache_EnumCache,
  DataCache_InitCache,
  DataCache_IOleCache2_SetData,
  DataCache_UpdateCache,
  DataCache_DiscardCache
};

2245
static const IOleCacheControlVtbl DataCache_IOleCacheControl_VTable =
2246 2247 2248 2249 2250 2251 2252 2253
{
  DataCache_IOleCacheControl_QueryInterface,
  DataCache_IOleCacheControl_AddRef,
  DataCache_IOleCacheControl_Release,
  DataCache_OnRun,
  DataCache_OnStop
};

2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265
static const IAdviseSinkVtbl DataCache_IAdviseSink_VTable =
{
    DataCache_IAdviseSink_QueryInterface,
    DataCache_IAdviseSink_AddRef,
    DataCache_IAdviseSink_Release,
    DataCache_OnDataChange,
    DataCache_OnViewChange,
    DataCache_OnRename,
    DataCache_OnSave,
    DataCache_OnClose
};

2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285
/*********************************************************
 * 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.
   */
2286 2287 2288 2289 2290 2291 2292
  newObject->IDataObject_iface.lpVtbl = &DataCache_IDataObject_VTable;
  newObject->IUnknown_iface.lpVtbl = &DataCache_NDIUnknown_VTable;
  newObject->IPersistStorage_iface.lpVtbl = &DataCache_IPersistStorage_VTable;
  newObject->IViewObject2_iface.lpVtbl = &DataCache_IViewObject2_VTable;
  newObject->IOleCache2_iface.lpVtbl = &DataCache_IOleCache2_VTable;
  newObject->IOleCacheControl_iface.lpVtbl = &DataCache_IOleCacheControl_VTable;
  newObject->IAdviseSink_iface.lpVtbl = &DataCache_IAdviseSink_VTable;
2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306

  /*
   * 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
   * aggregation works, our lifetime is at least as large as its
   * lifetime.
   */
  if (pUnkOuter==NULL)
2307
    pUnkOuter = &newObject->IUnknown_iface;
2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320

  newObject->outerUnknown = pUnkOuter;

  /*
   * Initialize the other members of the structure.
   */
  newObject->sinkAspects = 0;
  newObject->sinkAdviseFlag = 0;
  newObject->sinkInterface = 0;
  newObject->presentationStorage = NULL;
  list_init(&newObject->cache_list);
  newObject->last_cache_id = 1;
  newObject->dirty = FALSE;
2321
  newObject->running_object = NULL;
2322 2323 2324

  return newObject;
}
2325

2326 2327
/******************************************************************************
 *              CreateDataCache        [OLE32.@]
2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343
 *
 * 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:
Austin English's avatar
Austin English committed
2344
 *  IOleCache, IOleCache2, IOleCacheControl, IPersistStorage, IDataObject,
2345
 *  IViewObject and IViewObject2.
2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371
 */
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.
   */
2372
  if ( pUnkOuter && !IsEqualIID(&IID_IUnknown, riid) )
2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386
    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.
   */
2387
  hr = IUnknown_QueryInterface(&newCache->IUnknown_iface, riid, ppvObj);
2388 2389 2390 2391 2392

  /*
   * Release the reference obtained in the constructor. If
   * the QueryInterface was unsuccessful, it will free the class.
   */
2393
  IUnknown_Release(&newCache->IUnknown_iface);
2394 2395 2396

  return hr;
}