datacache.c 67.9 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

47
#include <stdarg.h>
48
#include <string.h>
49

50
#define COBJMACROS
51
#define NONAMELESSUNION
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
enum stream_type
{
    no_stream,
    pres_stream,
95
    contents_stream
96 97
};

98 99 100 101 102
typedef struct DataCacheEntry
{
  struct list entry;
  /* format of this entry */
  FORMATETC fmtetc;
103 104
  /* the clipboard format of the data */
  CLIPFORMAT data_cf;
105 106
  /* cached data */
  STGMEDIUM stgmedium;
107
  /*
108
   * This stream pointer is set through a call to
109 110 111
   * IPersistStorage_Load. This is where the visual
   * representation of the object is stored.
   */
112
  IStream *stream;
113
  enum stream_type stream_type;
114
  /* connection ID */
115
  DWORD id;
116 117
  /* dirty flag */
  BOOL dirty;
118 119
  /* stream number (-1 if not set ) */
  unsigned short stream_number;
120 121 122 123
  /* sink id set when object is running */
  DWORD sink_id;
  /* Advise sink flags */
  DWORD advise_flags;
124 125
} DataCacheEntry;

126 127 128 129 130 131
/****************************************************************************
 * DataCache
 */
struct DataCache
{
  /*
132
   * List all interface here
133
   */
134
  IUnknown          IUnknown_inner;
135 136 137 138 139
  IDataObject       IDataObject_iface;
  IPersistStorage   IPersistStorage_iface;
  IViewObject2      IViewObject2_iface;
  IOleCache2        IOleCache2_iface;
  IOleCacheControl  IOleCacheControl_iface;
140

141 142
  /* The sink that is connected to a remote object.
     The other interfaces are not available by QI'ing the sink and vice-versa */
143
  IAdviseSink       IAdviseSink_iface;
144

145 146 147
  /*
   * Reference count of this object
   */
148
  LONG ref;
149 150 151 152

  /*
   * IUnknown implementation of the outer object.
   */
153
  IUnknown *outer_unk;
154

155 156 157 158 159 160 161 162
  /*
   * 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;
163
  IStorage *presentationStorage;
164

165
  /* list of cache entries */
166
  struct list cache_list;
167
  /* last id assigned to an entry */
168
  DWORD last_cache_id;
169 170
  /* dirty flag */
  BOOL dirty;
171 172
  /* running object set by OnRun */
  IDataObject *running_object;
173 174 175 176 177
};

typedef struct DataCache DataCache;

/*
178
 * Here, I define utility macros to help with the casting of the
179
 * "this" parameter.
180
 * There is a version to accommodate all of the VTables implemented
181 182
 * by this object.
 */
183 184 185

static inline DataCache *impl_from_IDataObject( IDataObject *iface )
{
186
    return CONTAINING_RECORD(iface, DataCache, IDataObject_iface);
187 188
}

189
static inline DataCache *impl_from_IUnknown( IUnknown *iface )
190
{
191
    return CONTAINING_RECORD(iface, DataCache, IUnknown_inner);
192 193 194 195
}

static inline DataCache *impl_from_IPersistStorage( IPersistStorage *iface )
{
196
    return CONTAINING_RECORD(iface, DataCache, IPersistStorage_iface);
197 198 199 200
}

static inline DataCache *impl_from_IViewObject2( IViewObject2 *iface )
{
201
    return CONTAINING_RECORD(iface, DataCache, IViewObject2_iface);
202 203 204 205
}

static inline DataCache *impl_from_IOleCache2( IOleCache2 *iface )
{
206
    return CONTAINING_RECORD(iface, DataCache, IOleCache2_iface);
207 208 209 210
}

static inline DataCache *impl_from_IOleCacheControl( IOleCacheControl *iface )
{
211
    return CONTAINING_RECORD(iface, DataCache, IOleCacheControl_iface);
212 213
}

214 215
static inline DataCache *impl_from_IAdviseSink( IAdviseSink *iface )
{
216
    return CONTAINING_RECORD(iface, DataCache, IAdviseSink_iface);
217 218
}

219
const char *debugstr_formatetc(const FORMATETC *formatetc)
220
{
221 222 223
    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);
224
}
225

226
static void DataCacheEntry_Destroy(DataCache *cache, DataCacheEntry *cache_entry)
227
{
228
    list_remove(&cache_entry->entry);
229 230
    if (cache_entry->stream)
        IStream_Release(cache_entry->stream);
231 232
    HeapFree(GetProcessHeap(), 0, cache_entry->fmtetc.ptd);
    ReleaseStgMedium(&cache_entry->stgmedium);
233 234 235
    if(cache_entry->sink_id)
        IDataObject_DUnadvise(cache->running_object, cache_entry->sink_id);

236
    HeapFree(GetProcessHeap(), 0, cache_entry);
237 238
}

239 240 241
static void DataCache_Destroy(
  DataCache* ptrToDestroy)
{
242 243
  DataCacheEntry *cache_entry, *next_cache_entry;

244
  TRACE("()\n");
245 246 247 248 249 250 251

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

252
  LIST_FOR_EACH_ENTRY_SAFE(cache_entry, next_cache_entry, &ptrToDestroy->cache_list, DataCacheEntry, entry)
253
    DataCacheEntry_Destroy(ptrToDestroy, cache_entry);
254

255 256 257 258 259 260
  if (ptrToDestroy->presentationStorage != NULL)
  {
    IStorage_Release(ptrToDestroy->presentationStorage);
    ptrToDestroy->presentationStorage = NULL;
  }

261 262 263 264 265 266
  /*
   * Free the datacache pointer.
   */
  HeapFree(GetProcessHeap(), 0, ptrToDestroy);
}

267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
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;
}

282 283 284
/* 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 */
285
static HRESULT check_valid_clipformat_and_tymed(CLIPFORMAT cfFormat, DWORD tymed, BOOL load)
286 287
{
    if (!cfFormat || !tymed ||
288
        (cfFormat == CF_METAFILEPICT && (tymed == TYMED_MFPICT || load)) ||
289 290 291 292 293 294 295 296 297 298 299 300 301
        (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;
    }
}

302
static HRESULT DataCache_CreateEntry(DataCache *This, const FORMATETC *formatetc, DataCacheEntry **cache_entry, BOOL load)
303
{
304 305
    HRESULT hr;

306
    hr = check_valid_clipformat_and_tymed(formatetc->cfFormat, formatetc->tymed, load);
307 308 309 310 311
    if (FAILED(hr))
        return hr;
    if (hr == CACHE_S_FORMATETC_NOTSUPPORTED)
        TRACE("creating unsupported format %d\n", formatetc->cfFormat);

312
    *cache_entry = HeapAlloc(GetProcessHeap(), 0, sizeof(**cache_entry));
313 314 315
    if (!*cache_entry)
        return E_OUTOFMEMORY;

316 317 318 319 320 321
    (*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);
    }
322
    (*cache_entry)->data_cf = 0;
323 324
    (*cache_entry)->stgmedium.tymed = TYMED_NULL;
    (*cache_entry)->stgmedium.pUnkForRelease = NULL;
325
    (*cache_entry)->stream = NULL;
326
    (*cache_entry)->stream_type = no_stream;
327
    (*cache_entry)->id = This->last_cache_id++;
328
    (*cache_entry)->dirty = TRUE;
329
    (*cache_entry)->stream_number = -1;
330 331
    (*cache_entry)->sink_id = 0;
    (*cache_entry)->advise_flags = 0;
332
    list_add_tail(&This->cache_list, &(*cache_entry)->entry);
333
    return hr;
334 335
}

336 337 338 339 340 341 342 343 344 345 346 347 348
/************************************************************************
 * 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)
{
349
  TRACE("(%p, %x, %d)\n", this, aspect, lindex);
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379

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

380
/* Helper for DataCacheEntry_OpenPresStream */
381 382 383 384 385 386 387 388 389
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)
390 391
	&& (strlenW(name) == 11)
	&& (strncmpW(name, OlePres, 8) == 0)
392 393 394
	&& (name[8] >= '0') && (name[8] <= '9')
	&& (name[9] >= '0') && (name[9] <= '9')
	&& (name[10] >= '0') && (name[10] <= '9');
395 396
}

397 398 399 400 401 402 403 404 405 406 407 408 409 410
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;
411
        hr = IStream_Read(stream, &cf, sizeof(cf), &read);
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461
        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;
}

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

492
    if (cache_entry->stream)
493
    {
494 495
        /* Rewind the stream before returning it. */
        offset.QuadPart = 0;
496

497 498 499 500 501 502
        hr = IStream_Seek( cache_entry->stream, offset, STREAM_SEEK_SET, NULL );
        if (SUCCEEDED( hr ))
        {
            *ppStm = cache_entry->stream;
            IStream_AddRef( cache_entry->stream );
        }
503
    }
504 505
    else
        hr = OLE_E_BLANK;
506

507
    return hr;
508 509
}

510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583

static HRESULT load_mf_pict( DataCacheEntry *cache_entry, IStream *stm )
{
    HRESULT hr;
    STATSTG stat;
    ULARGE_INTEGER current_pos;
    void *bits;
    METAFILEPICT *mfpict;
    HGLOBAL hmfpict;
    PresentationDataHeader header;
    CLIPFORMAT clipformat;
    static const LARGE_INTEGER offset_zero;
    ULONG read;

    if (cache_entry->stream_type != pres_stream)
    {
        FIXME( "Unimplemented for stream type %d\n", cache_entry->stream_type );
        return E_FAIL;
    }

    hr = IStream_Stat( stm, &stat, STATFLAG_NONAME );
    if (FAILED( hr )) return hr;

    hr = read_clipformat( stm, &clipformat );
    if (FAILED( hr )) return hr;

    hr = IStream_Read( stm, &header, sizeof(header), &read );
    if (hr != S_OK || read != sizeof(header)) return E_FAIL;

    hr = IStream_Seek( stm, offset_zero, STREAM_SEEK_CUR, &current_pos );
    if (FAILED( hr )) return hr;

    stat.cbSize.QuadPart -= current_pos.QuadPart;

    hmfpict = GlobalAlloc( GMEM_MOVEABLE, sizeof(METAFILEPICT) );
    if (!hmfpict) return E_OUTOFMEMORY;
    mfpict = GlobalLock( hmfpict );

    bits = HeapAlloc( GetProcessHeap(), 0, stat.cbSize.u.LowPart);
    if (!bits)
    {
        GlobalFree( hmfpict );
        return E_OUTOFMEMORY;
    }

    hr = IStream_Read( stm, bits, stat.cbSize.u.LowPart, &read );
    if (hr != S_OK || read != stat.cbSize.u.LowPart) hr = E_FAIL;

    if (SUCCEEDED( hr ))
    {
        /* FIXME: get this from the stream */
        mfpict->mm = MM_ANISOTROPIC;
        mfpict->xExt = header.dwObjectExtentX;
        mfpict->yExt = header.dwObjectExtentY;
        mfpict->hMF = SetMetaFileBitsEx( stat.cbSize.u.LowPart, bits );
        if (!mfpict->hMF)
            hr = E_FAIL;
    }

    GlobalUnlock( hmfpict );
    if (SUCCEEDED( hr ))
    {
        cache_entry->data_cf = cache_entry->fmtetc.cfFormat;
        cache_entry->stgmedium.tymed = TYMED_MFPICT;
        cache_entry->stgmedium.u.hMetaFilePict = hmfpict;
    }
    else
        GlobalFree( hmfpict );

    HeapFree( GetProcessHeap(), 0, bits );

    return hr;
}

584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620
static HRESULT load_dib( DataCacheEntry *cache_entry, IStream *stm )
{
    HRESULT hr;
    STATSTG stat;
    void *dib;
    HGLOBAL hglobal;
    ULONG read;

    if (cache_entry->stream_type != contents_stream)
    {
        FIXME( "Unimplemented for stream type %d\n", cache_entry->stream_type );
        return E_FAIL;
    }

    hr = IStream_Stat( stm, &stat, STATFLAG_NONAME );
    if (FAILED( hr )) return hr;

    hglobal = GlobalAlloc( GMEM_MOVEABLE, stat.cbSize.u.LowPart );
    if (!hglobal) return E_OUTOFMEMORY;
    dib = GlobalLock( hglobal );

    hr = IStream_Read( stm, dib, stat.cbSize.u.LowPart, &read );
    GlobalUnlock( hglobal );

    if (hr != S_OK || read != stat.cbSize.u.LowPart)
    {
        GlobalFree( hglobal );
        return E_FAIL;
    }

    cache_entry->data_cf = cache_entry->fmtetc.cfFormat;
    cache_entry->stgmedium.tymed = TYMED_HGLOBAL;
    cache_entry->stgmedium.u.hGlobal = hglobal;

    return S_OK;
}

621
/************************************************************************
622
 * DataCacheEntry_LoadData
623
 *
624
 * This method will read information for the requested presentation
625 626 627
 * into the given structure.
 *
 * Param:
628
 *   This - The entry to load the data from.
629 630 631 632 633
 *
 * Returns:
 *   This method returns a metafile handle if it is successful.
 *   it will return 0 if not.
 */
634
static HRESULT DataCacheEntry_LoadData(DataCacheEntry *cache_entry)
635
{
636 637
    HRESULT hr;
    IStream *stm;
638

639 640
    hr = DataCacheEntry_OpenPresStream( cache_entry, &stm );
    if (FAILED(hr)) return hr;
641

642 643 644 645 646
    switch (cache_entry->fmtetc.cfFormat)
    {
    case CF_METAFILEPICT:
        hr = load_mf_pict( cache_entry, stm );
        break;
647

648 649 650 651
    case CF_DIB:
        hr = load_dib( cache_entry, stm );
        break;

652 653 654 655
    default:
        FIXME( "Unimplemented clip format %x\n", cache_entry->fmtetc.cfFormat );
        hr = E_NOTIMPL;
    }
656

657 658
    IStream_Release( stm );
    return hr;
659 660
}

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

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

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

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

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

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

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

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

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

    IStream_Release(pres_stream);
    return hr;
}

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

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

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

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

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

855
static inline void DataCacheEntry_HandsOffStorage(DataCacheEntry *cache_entry)
856
{
857
    if (cache_entry->stream)
858
    {
859 860
        IStream_Release(cache_entry->stream);
        cache_entry->stream = NULL;
861 862 863
    }
}

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

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

882
  if ( ppvObject==0 )
883
    return E_INVALIDARG;
884

885 886
  *ppvObject = 0;

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

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

921 922
  IUnknown_AddRef((IUnknown*)*ppvObject);

923
  return S_OK;
924 925 926 927 928
}

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

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

951
  ref = InterlockedDecrement(&this->ref);
952

953
  if (ref == 0) DataCache_Destroy(this);
954

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

/*********************************************************
 * 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)
{
971
  DataCache *this = impl_from_IDataObject(iface);
972

973
  return IUnknown_QueryInterface(this->outer_unk, riid, ppvObject);
974 975 976 977 978
}

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

984
  return IUnknown_AddRef(this->outer_unk);
985 986 987 988 989
}

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

995
  return IUnknown_Release(this->outer_unk);
996 997
}

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

1011
    memset(pmedium, 0, sizeof(*pmedium));
1012

1013 1014 1015
    cache_entry = DataCache_GetEntryForFormatEtc(This, pformatetcIn);
    if (!cache_entry)
        return OLE_E_BLANK;
1016

1017
    return DataCacheEntry_GetData(cache_entry, pmedium);
1018 1019 1020
}

static HRESULT WINAPI DataCache_GetDataHere(
1021
	    IDataObject*     iface,
1022 1023 1024
	    LPFORMATETC      pformatetc,
	    STGMEDIUM*       pmedium)
{
1025
  FIXME("stub\n");
1026 1027 1028
  return E_NOTIMPL;
}

1029
static HRESULT WINAPI DataCache_QueryGetData( IDataObject *iface, FORMATETC *fmt )
1030
{
1031 1032 1033 1034 1035 1036 1037
    DataCache *This = impl_from_IDataObject( iface );
    DataCacheEntry *cache_entry;

    TRACE( "(%p)->(%s)\n", iface, debugstr_formatetc( fmt ) );
    cache_entry = DataCache_GetEntryForFormatEtc( This, fmt );

    return cache_entry ? S_OK : S_FALSE;
1038 1039 1040 1041 1042 1043 1044 1045
}

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

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

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

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

  if (FAILED(hres))
    return E_UNEXPECTED;

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

  IOleCache2_Release(oleCache);

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

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

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

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

/************************************************************************
 * DataCache_EnumDAdvise (IDataObject)
 *
 * The data cache doesn't support connections.
 */
static HRESULT WINAPI DataCache_EnumDAdvise(
	    IDataObject*     iface,
	    IEnumSTATDATA**  ppenumAdvise)
{
1134
  TRACE("()\n");
1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150
  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)
{
1151
  DataCache *this = impl_from_IPersistStorage(iface);
1152

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

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

1164
  return IUnknown_AddRef(this->outer_unk);
1165 1166 1167 1168 1169
}

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

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

/************************************************************************
 * DataCache_GetClassID (IPersistStorage)
 *
 */
1182
static HRESULT WINAPI DataCache_GetClassID(IPersistStorage *iface, CLSID *clsid)
1183
{
1184 1185 1186
    DataCache *This = impl_from_IPersistStorage( iface );
    HRESULT hr;
    STATSTG statstg;
1187

1188
    TRACE( "(%p, %p)\n", iface, clsid );
1189

1190
    if (This->presentationStorage)
1191
    {
1192 1193 1194 1195 1196 1197
        hr = IStorage_Stat( This->presentationStorage, &statstg, STATFLAG_NONAME );
        if (SUCCEEDED(hr))
        {
            *clsid = statstg.clsid;
            return S_OK;
        }
1198
    }
1199

1200
    *clsid = CLSID_NULL;
1201

1202
    return S_OK;
1203 1204
}

1205 1206 1207
/************************************************************************
 * DataCache_IsDirty (IPersistStorage)
 */
1208
static HRESULT WINAPI DataCache_IsDirty(
1209 1210
            IPersistStorage* iface)
{
1211 1212 1213 1214
    DataCache *This = impl_from_IPersistStorage(iface);
    DataCacheEntry *cache_entry;

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

1216 1217 1218 1219 1220 1221 1222 1223
    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;
1224 1225 1226 1227 1228 1229 1230 1231
}

/************************************************************************
 * DataCache_InitNew (IPersistStorage)
 *
 * The data cache implementation of IPersistStorage_InitNew simply stores
 * the storage pointer.
 */
1232 1233
static HRESULT WINAPI DataCache_InitNew(
            IPersistStorage* iface,
1234 1235
	    IStorage*        pStg)
{
1236 1237 1238 1239 1240 1241 1242 1243
    DataCache *This = impl_from_IPersistStorage(iface);

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

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

    This->presentationStorage = pStg;
1244

1245 1246 1247 1248
    IStorage_AddRef(This->presentationStorage);
    This->dirty = TRUE;

    return S_OK;
1249 1250
}

1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261

static HRESULT add_cache_entry( DataCache *This, const FORMATETC *fmt, IStream *stm,
                                enum stream_type type )
{
    DataCacheEntry *cache_entry;
    HRESULT hr = S_OK;

    TRACE( "loading entry with formatetc: %s\n", debugstr_formatetc( fmt ) );

    cache_entry = DataCache_GetEntryForFormatEtc( This, fmt );
    if (!cache_entry)
1262
        hr = DataCache_CreateEntry( This, fmt, &cache_entry, TRUE );
1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321
    if (SUCCEEDED( hr ))
    {
        DataCacheEntry_DiscardData( cache_entry );
        if (cache_entry->stream) IStream_Release( cache_entry->stream );
        cache_entry->stream = stm;
        IStream_AddRef( stm );
        cache_entry->stream_type = type;
        cache_entry->dirty = FALSE;
    }
    return hr;
}

static HRESULT parse_pres_streams( DataCache *This, IStorage *stg )
{
    HRESULT hr;
    IEnumSTATSTG *stat_enum;
    STATSTG stat;
    IStream *stm;
    PresentationDataHeader header;
    ULONG actual_read;
    CLIPFORMAT clipformat;
    FORMATETC fmtetc;

    hr = IStorage_EnumElements( stg, 0, NULL, 0, &stat_enum );
    if (FAILED( hr )) return hr;

    while ((hr = IEnumSTATSTG_Next( stat_enum, 1, &stat, NULL )) == S_OK)
    {
        if (DataCache_IsPresentationStream( &stat ))
        {
            hr = IStorage_OpenStream( stg, stat.pwcsName, NULL, STGM_READ | STGM_SHARE_EXCLUSIVE,
                                      0, &stm );
            if (SUCCEEDED( hr ))
            {
                hr = read_clipformat( stm, &clipformat );

                if (hr == S_OK)
                    hr = IStream_Read( stm, &header, sizeof(header), &actual_read );

                if (hr == S_OK && actual_read == sizeof(header))
                {
                    fmtetc.cfFormat = clipformat;
                    fmtetc.ptd = NULL; /* FIXME */
                    fmtetc.dwAspect = header.dvAspect;
                    fmtetc.lindex = header.lindex;
                    fmtetc.tymed = header.tymed;

                    add_cache_entry( This, &fmtetc, stm, pres_stream );
                }
                IStream_Release( stm );
            }
        }
        CoTaskMemFree( stat.pwcsName );
    }
    IEnumSTATSTG_Release( stat_enum );

    return S_OK;
}

1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335
static const FORMATETC static_dib_fmt = { CF_DIB, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };

static HRESULT parse_contents_stream( DataCache *This, IStorage *stg, IStream *stm )
{
    HRESULT hr;
    STATSTG stat;
    const FORMATETC *fmt;

    hr = IStorage_Stat( stg, &stat, STATFLAG_NONAME );
    if (FAILED( hr )) return hr;

    if (IsEqualCLSID( &stat.clsid, &CLSID_Picture_Dib ))
        fmt = &static_dib_fmt;
    else
1336 1337
    {
        FIXME("unsupported format %s\n", debugstr_guid( &stat.clsid ));
1338
        return E_FAIL;
1339
    }
1340 1341 1342 1343 1344

    return add_cache_entry( This, fmt, stm, contents_stream );
}

static const WCHAR CONTENTS[] = {'C','O','N','T','E','N','T','S',0};
1345

1346 1347 1348
/************************************************************************
 * DataCache_Load (IPersistStorage)
 *
1349
 * The data cache implementation of IPersistStorage_Load doesn't
1350
 * actually load anything. Instead, it holds on to the storage pointer
1351
 * and it will load the presentation information when the
1352 1353
 * IDataObject_GetData or IViewObject2_Draw methods are called.
 */
1354
static HRESULT WINAPI DataCache_Load( IPersistStorage *iface, IStorage *pStg )
1355
{
1356 1357
    DataCache *This = impl_from_IPersistStorage(iface);
    HRESULT hr;
1358
    IStream *stm;
1359

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

1362
    IPersistStorage_HandsOffStorage( iface );
1363

1364 1365 1366 1367 1368 1369 1370
    hr = IStorage_OpenStream( pStg, CONTENTS, NULL, STGM_READ | STGM_SHARE_EXCLUSIVE,
                              0, &stm );
    if (SUCCEEDED( hr ))
    {
        hr = parse_contents_stream( This, pStg, stm );
        IStream_Release( stm );
    }
1371 1372

    if (FAILED(hr))
1373
        hr = parse_pres_streams( This, pStg );
1374

1375
    if (SUCCEEDED( hr ))
1376
    {
1377 1378 1379
        This->dirty = FALSE;
        This->presentationStorage = pStg;
        IStorage_AddRef( This->presentationStorage );
1380 1381
    }

1382
    return hr;
1383 1384
}

1385 1386 1387
/************************************************************************
 * DataCache_Save (IPersistStorage)
 *
1388
 * Until we actually connect to a running object and retrieve new
1389
 * information to it, we never have to save anything. However, it is
1390
 * our responsibility to copy the information when saving to a new
1391 1392
 * storage.
 */
1393
static HRESULT WINAPI DataCache_Save(
1394
            IPersistStorage* iface,
1395
	    IStorage*        pStg,
1396 1397
	    BOOL             fSameAsLoad)
{
1398 1399 1400
    DataCache *This = impl_from_IPersistStorage(iface);
    DataCacheEntry *cache_entry;
    BOOL dirty = FALSE;
1401 1402
    HRESULT hr = S_OK;
    unsigned short stream_number = 0;
1403

1404
    TRACE("(%p, %p, %d)\n", iface, pStg, fSameAsLoad);
1405

1406 1407 1408 1409 1410 1411 1412 1413 1414 1415
    dirty = This->dirty;
    if (!dirty)
    {
        LIST_FOR_EACH_ENTRY(cache_entry, &This->cache_list, DataCacheEntry, entry)
        {
            dirty = cache_entry->dirty;
            if (dirty)
                break;
        }
    }
1416

1417 1418 1419 1420 1421 1422
    /* this is a shortcut if nothing changed */
    if (!dirty && !fSameAsLoad && This->presentationStorage)
    {
        return IStorage_CopyTo(This->presentationStorage, 0, NULL, NULL, pStg);
    }

1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434
    /* 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 */
1435 1436
    LIST_FOR_EACH_ENTRY(cache_entry, &This->cache_list, DataCacheEntry, entry)
    {
1437 1438 1439 1440 1441 1442 1443 1444
        if (!fSameAsLoad || cache_entry->dirty)
        {
            hr = DataCacheEntry_Save(cache_entry, pStg, fSameAsLoad);
            if (FAILED(hr))
                break;

            cache_entry->dirty = FALSE;
        }
1445 1446 1447
    }

    This->dirty = FALSE;
1448
    return hr;
1449 1450 1451 1452 1453 1454
}

/************************************************************************
 * DataCache_SaveCompleted (IPersistStorage)
 *
 * This method is called to tell the cache to release the storage
1455
 * pointer it's currently holding.
1456
 */
1457 1458
static HRESULT WINAPI DataCache_SaveCompleted(
            IPersistStorage* iface,
1459 1460
	    IStorage*        pStgNew)
{
1461
  TRACE("(%p, %p)\n", iface, pStgNew);
1462

1463 1464
  if (pStgNew)
  {
1465
    IPersistStorage_HandsOffStorage(iface);
1466

1467
    DataCache_Load(iface, pStgNew);
1468
  }
1469 1470 1471 1472 1473 1474 1475 1476

  return S_OK;
}

/************************************************************************
 * DataCache_HandsOffStorage (IPersistStorage)
 *
 * This method is called to tell the cache to release the storage
1477
 * pointer it's currently holding.
1478 1479 1480 1481
 */
static HRESULT WINAPI DataCache_HandsOffStorage(
            IPersistStorage* iface)
{
1482
  DataCache *this = impl_from_IPersistStorage(iface);
1483
  DataCacheEntry *cache_entry;
1484

1485
  TRACE("(%p)\n", iface);
1486 1487 1488 1489 1490 1491 1492

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

1493 1494 1495
  LIST_FOR_EACH_ENTRY(cache_entry, &this->cache_list, DataCacheEntry, entry)
    DataCacheEntry_HandsOffStorage(cache_entry);

1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511
  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)
{
1512
  DataCache *this = impl_from_IViewObject2(iface);
1513

1514
  return IUnknown_QueryInterface(this->outer_unk, riid, ppvObject);
1515 1516 1517 1518 1519
}

/************************************************************************
 * DataCache_IViewObject2_AddRef (IUnknown)
 */
1520
static ULONG WINAPI DataCache_IViewObject2_AddRef(
1521 1522
            IViewObject2* iface)
{
1523
  DataCache *this = impl_from_IViewObject2(iface);
1524

1525
  return IUnknown_AddRef(this->outer_unk);
1526 1527 1528 1529 1530
}

/************************************************************************
 * DataCache_IViewObject2_Release (IUnknown)
 */
1531
static ULONG WINAPI DataCache_IViewObject2_Release(
1532 1533
            IViewObject2* iface)
{
1534
  DataCache *this = impl_from_IViewObject2(iface);
1535

1536
  return IUnknown_Release(this->outer_unk);
1537 1538
}

1539 1540 1541 1542 1543 1544
/************************************************************************
 * DataCache_Draw (IViewObject2)
 *
 * This method will draw the cached representation of the object
 * to the given device context.
 */
1545 1546 1547 1548 1549
static HRESULT WINAPI DataCache_Draw(
            IViewObject2*    iface,
	    DWORD            dwDrawAspect,
	    LONG             lindex,
	    void*            pvAspect,
1550 1551
	    DVTARGETDEVICE*  ptd,
	    HDC              hdcTargetDev,
1552 1553 1554
	    HDC              hdcDraw,
	    LPCRECTL         lprcBounds,
	    LPCRECTL         lprcWBounds,
1555
	    BOOL  (CALLBACK *pfnContinue)(ULONG_PTR dwContinue),
1556
	    ULONG_PTR        dwContinue)
1557
{
1558
  DataCache *This = impl_from_IViewObject2(iface);
1559
  HRESULT                hres;
1560
  DataCacheEntry        *cache_entry;
1561

1562
  TRACE("(%p, %x, %d, %p, %p, %p, %p, %p, %p, %lx)\n",
1563 1564 1565 1566
	iface,
	dwDrawAspect,
	lindex,
	pvAspect,
1567
	hdcTargetDev,
1568 1569 1570 1571 1572 1573 1574 1575 1576
	hdcDraw,
	lprcBounds,
	lprcWBounds,
	pfnContinue,
	dwContinue);

  if (lprcBounds==NULL)
    return E_INVALIDARG;

1577 1578 1579 1580 1581 1582 1583
  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;

1584
    /* if the data hasn't been loaded yet, do it now */
1585
    if ((cache_entry->stgmedium.tymed == TYMED_NULL) && cache_entry->stream)
1586
    {
1587 1588 1589 1590 1591 1592 1593 1594 1595
      hres = DataCacheEntry_LoadData(cache_entry);
      if (FAILED(hres))
        continue;
    }

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

1596 1597
    if (pfnContinue && !pfnContinue(dwContinue)) return E_ABORT;

1598
    switch (cache_entry->data_cf)
1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655
    {
      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;
      }
1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675
      case CF_DIB:
      {
          BITMAPFILEHEADER *file_head;
          BITMAPINFO *info;
          BYTE *bits;

          if ((cache_entry->stgmedium.tymed != TYMED_HGLOBAL) ||
              !((file_head = GlobalLock( cache_entry->stgmedium.u.hGlobal ))))
              continue;

          info = (BITMAPINFO *)(file_head + 1);
          bits = (BYTE *) file_head + file_head->bfOffBits;
          StretchDIBits( hdcDraw, lprcBounds->left, lprcBounds->top,
                         lprcBounds->right - lprcBounds->left, lprcBounds->bottom - lprcBounds->top,
                         0, 0, info->bmiHeader.biWidth, info->bmiHeader.biHeight,
                         bits, info, DIB_RGB_COLORS, SRCCOPY );

          GlobalUnlock( cache_entry->stgmedium.u.hGlobal );
          return S_OK;
      }
1676
    }
1677 1678
  }

1679 1680
  WARN("no data could be found to be drawn\n");

1681
  return OLE_E_BLANK;
1682 1683 1684
}

static HRESULT WINAPI DataCache_GetColorSet(
1685 1686 1687 1688 1689 1690
            IViewObject2*   iface,
	    DWORD           dwDrawAspect,
	    LONG            lindex,
	    void*           pvAspect,
	    DVTARGETDEVICE* ptd,
	    HDC             hicTargetDevice,
1691 1692
	    LOGPALETTE**    ppColorSet)
{
1693
  FIXME("stub\n");
1694 1695 1696 1697 1698 1699 1700
  return E_NOTIMPL;
}

static HRESULT WINAPI DataCache_Freeze(
            IViewObject2*   iface,
	    DWORD           dwDrawAspect,
	    LONG            lindex,
1701
	    void*           pvAspect,
1702 1703
	    DWORD*          pdwFreeze)
{
1704
  FIXME("stub\n");
1705 1706 1707 1708 1709 1710 1711
  return E_NOTIMPL;
}

static HRESULT WINAPI DataCache_Unfreeze(
            IViewObject2*   iface,
	    DWORD           dwFreeze)
{
1712
  FIXME("stub\n");
1713 1714 1715
  return E_NOTIMPL;
}

1716 1717 1718 1719 1720 1721
/************************************************************************
 * DataCache_SetAdvise (IViewObject2)
 *
 * This sets-up an advisory sink with the data cache. When the object's
 * view changes, this sink is called.
 */
1722 1723
static HRESULT WINAPI DataCache_SetAdvise(
            IViewObject2*   iface,
1724 1725
	    DWORD           aspects,
	    DWORD           advf,
1726 1727
	    IAdviseSink*    pAdvSink)
{
1728
  DataCache *this = impl_from_IViewObject2(iface);
1729

1730
  TRACE("(%p, %x, %x, %p)\n", iface, aspects, advf, pAdvSink);
1731 1732 1733 1734 1735 1736 1737 1738

  /*
   * A call to this function removes the previous sink
   */
  if (this->sinkInterface != NULL)
  {
    IAdviseSink_Release(this->sinkInterface);
    this->sinkInterface  = NULL;
1739
    this->sinkAspects    = 0;
1740 1741 1742 1743 1744 1745 1746 1747 1748
    this->sinkAdviseFlag = 0;
  }

  /*
   * Now, setup the new one.
   */
  if (pAdvSink!=NULL)
  {
    this->sinkInterface  = pAdvSink;
1749 1750
    this->sinkAspects    = aspects;
    this->sinkAdviseFlag = advf;
1751 1752 1753 1754 1755 1756 1757 1758 1759 1760

    IAdviseSink_AddRef(this->sinkInterface);
  }

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

1764 1765 1766
  return S_OK;
}

1767 1768 1769
/************************************************************************
 * DataCache_GetAdvise (IViewObject2)
 *
1770
 * This method queries the current state of the advise sink
1771 1772
 * installed on the data cache.
 */
1773
static HRESULT WINAPI DataCache_GetAdvise(
1774 1775 1776
            IViewObject2*   iface,
	    DWORD*          pAspects,
	    DWORD*          pAdvf,
1777 1778
	    IAdviseSink**   ppAdvSink)
{
1779
  DataCache *this = impl_from_IViewObject2(iface);
1780

1781
  TRACE("(%p, %p, %p, %p)\n", iface, pAspects, pAdvf, ppAdvSink);
1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793

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

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

  if (ppAdvSink!=NULL)
  {
1794 1795
    if (this->sinkInterface != NULL)
        IAdviseSink_QueryInterface(this->sinkInterface,
1796
			       &IID_IAdviseSink,
1797
			       (void**)ppAdvSink);
1798
    else *ppAdvSink = NULL;
1799 1800 1801
  }

  return S_OK;
1802 1803
}

1804 1805 1806 1807 1808
/************************************************************************
 * DataCache_GetExtent (IViewObject2)
 *
 * This method retrieves the "natural" size of this cached object.
 */
1809
static HRESULT WINAPI DataCache_GetExtent(
1810 1811 1812 1813
            IViewObject2*   iface,
	    DWORD           dwDrawAspect,
	    LONG            lindex,
	    DVTARGETDEVICE* ptd,
1814 1815
	    LPSIZEL         lpsizel)
{
1816
  DataCache *This = impl_from_IViewObject2(iface);
1817
  HRESULT                hres = E_FAIL;
1818
  DataCacheEntry        *cache_entry;
1819

1820
  TRACE("(%p, %x, %d, %p, %p)\n",
1821 1822 1823 1824 1825 1826 1827 1828 1829
	iface, dwDrawAspect, lindex, ptd, lpsizel);

  if (lpsizel==NULL)
    return E_POINTER;

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

  if (lindex!=-1)
1830
    FIXME("Unimplemented flag lindex = %d\n", lindex);
1831 1832

  /*
1833
   * Right now, we support only the callback from
1834 1835 1836
   * the default handler.
   */
  if (ptd!=NULL)
1837
    FIXME("Unimplemented ptd = %p\n", ptd);
1838

1839 1840 1841 1842 1843 1844 1845
  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;

1846
    /* if the data hasn't been loaded yet, do it now */
1847
    if ((cache_entry->stgmedium.tymed == TYMED_NULL) && cache_entry->stream)
1848 1849 1850 1851 1852
    {
      hres = DataCacheEntry_LoadData(cache_entry);
      if (FAILED(hres))
        continue;
    }
1853

1854 1855 1856 1857 1858
    /* no data */
    if (cache_entry->stgmedium.tymed == TYMED_NULL)
      continue;


1859
    switch (cache_entry->data_cf)
1860
    {
1861 1862 1863 1864 1865 1866 1867
      case CF_METAFILEPICT:
      {
          METAFILEPICT *mfpict;

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

1869 1870 1871 1872 1873 1874 1875
        lpsizel->cx = mfpict->xExt;
        lpsizel->cy = mfpict->yExt;

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

        return S_OK;
      }
1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910
      case CF_DIB:
      {
          BITMAPFILEHEADER *file_head;
          BITMAPINFOHEADER *info;
          LONG x_pels_m, y_pels_m;


          if ((cache_entry->stgmedium.tymed != TYMED_HGLOBAL) ||
              !((file_head = GlobalLock( cache_entry->stgmedium.u.hGlobal ))))
              continue;

          info = (BITMAPINFOHEADER *)(file_head + 1);

          x_pels_m = info->biXPelsPerMeter;
          y_pels_m = info->biYPelsPerMeter;

          /* Size in units of 0.01mm (ie. MM_HIMETRIC) */
          if (x_pels_m != 0 && y_pels_m != 0)
          {
              lpsizel->cx = info->biWidth  * 100000 / x_pels_m;
              lpsizel->cy = info->biHeight * 100000 / y_pels_m;
          }
          else
          {
              HDC hdc = GetDC( 0 );
              lpsizel->cx = info->biWidth  * 2540 / GetDeviceCaps( hdc, LOGPIXELSX );
              lpsizel->cy = info->biHeight * 2540 / GetDeviceCaps( hdc, LOGPIXELSY );

              ReleaseDC( 0, hdc );
          }

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

          return S_OK;
      }
1911
    }
1912 1913
  }

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

1916 1917 1918
  /*
   * This method returns OLE_E_BLANK when it fails.
   */
1919
  return OLE_E_BLANK;
1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935
}


/*********************************************************
 * 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)
{
1936
  DataCache *this = impl_from_IOleCache2(iface);
1937

1938
  return IUnknown_QueryInterface(this->outer_unk, riid, ppvObject);
1939 1940 1941 1942 1943
}

/************************************************************************
 * DataCache_IOleCache2_AddRef (IUnknown)
 */
1944
static ULONG WINAPI DataCache_IOleCache2_AddRef(
1945 1946
            IOleCache2*     iface)
{
1947
  DataCache *this = impl_from_IOleCache2(iface);
1948

1949
  return IUnknown_AddRef(this->outer_unk);
1950 1951 1952 1953 1954
}

/************************************************************************
 * DataCache_IOleCache2_Release (IUnknown)
 */
1955
static ULONG WINAPI DataCache_IOleCache2_Release(
1956 1957
            IOleCache2*     iface)
{
1958
  DataCache *this = impl_from_IOleCache2(iface);
1959

1960
  return IUnknown_Release(this->outer_unk);
1961 1962
}

1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978
/*****************************************************************************
 * 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,
1979
                                     &This->IAdviseSink_iface, &cache_entry->sink_id);
1980 1981 1982
    return hr;
}

1983 1984 1985 1986 1987 1988
static HRESULT WINAPI DataCache_Cache(
            IOleCache2*     iface,
	    FORMATETC*      pformatetc,
	    DWORD           advf,
	    DWORD*          pdwConnection)
{
1989 1990 1991 1992 1993
    DataCache *This = impl_from_IOleCache2(iface);
    DataCacheEntry *cache_entry;
    HRESULT hr;

    TRACE("(%p, 0x%x, %p)\n", pformatetc, advf, pdwConnection);
1994 1995 1996 1997

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

1998
    TRACE("pformatetc = %s\n", debugstr_formatetc(pformatetc));
1999 2000 2001 2002 2003 2004

    *pdwConnection = 0;

    cache_entry = DataCache_GetEntryForFormatEtc(This, pformatetc);
    if (cache_entry)
    {
2005
        TRACE("found an existing cache entry\n");
2006 2007 2008 2009
        *pdwConnection = cache_entry->id;
        return CACHE_S_SAMECACHE;
    }

2010
    hr = DataCache_CreateEntry(This, pformatetc, &cache_entry, FALSE);
2011 2012

    if (SUCCEEDED(hr))
2013
    {
2014
        *pdwConnection = cache_entry->id;
2015 2016 2017
        cache_entry->advise_flags = advf;
        setup_sink(This, cache_entry);
    }
2018 2019

    return hr;
2020 2021 2022 2023 2024 2025
}

static HRESULT WINAPI DataCache_Uncache(
	    IOleCache2*     iface,
	    DWORD           dwConnection)
{
2026 2027 2028 2029 2030 2031 2032 2033
    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)
        {
2034
            DataCacheEntry_Destroy(This, cache_entry);
2035 2036 2037
            return S_OK;
        }

2038 2039
    WARN("no connection found for %d\n", dwConnection);

2040
    return OLE_E_NOCONNECTION;
2041 2042 2043 2044 2045 2046
}

static HRESULT WINAPI DataCache_EnumCache(
            IOleCache2*     iface,
	    IEnumSTATDATA** ppenumSTATDATA)
{
2047
  FIXME("stub\n");
2048 2049 2050 2051 2052 2053 2054
  return E_NOTIMPL;
}

static HRESULT WINAPI DataCache_InitCache(
	    IOleCache2*     iface,
	    IDataObject*    pDataObject)
{
2055
  FIXME("stub\n");
2056 2057 2058 2059 2060 2061 2062 2063 2064
  return E_NOTIMPL;
}

static HRESULT WINAPI DataCache_IOleCache2_SetData(
            IOleCache2*     iface,
	    FORMATETC*      pformatetc,
	    STGMEDIUM*      pmedium,
	    BOOL            fRelease)
{
2065 2066 2067 2068 2069
    DataCache *This = impl_from_IOleCache2(iface);
    DataCacheEntry *cache_entry;
    HRESULT hr;

    TRACE("(%p, %p, %s)\n", pformatetc, pmedium, fRelease ? "TRUE" : "FALSE");
2070
    TRACE("formatetc = %s\n", debugstr_formatetc(pformatetc));
2071 2072 2073 2074

    cache_entry = DataCache_GetEntryForFormatEtc(This, pformatetc);
    if (cache_entry)
    {
2075
        hr = DataCacheEntry_SetData(cache_entry, pformatetc, pmedium, fRelease);
2076 2077 2078 2079 2080 2081 2082

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

        return hr;
    }
2083
    WARN("cache entry not found\n");
2084 2085

    return OLE_E_BLANK;
2086 2087 2088 2089
}

static HRESULT WINAPI DataCache_UpdateCache(
            IOleCache2*     iface,
2090
	    LPDATAOBJECT    pDataObject,
2091 2092 2093
	    DWORD           grfUpdf,
	    LPVOID          pReserved)
{
2094
  FIXME("(%p, 0x%x, %p): stub\n", pDataObject, grfUpdf, pReserved);
2095 2096 2097 2098 2099 2100 2101
  return E_NOTIMPL;
}

static HRESULT WINAPI DataCache_DiscardCache(
            IOleCache2*     iface,
	    DWORD           dwDiscardOptions)
{
2102 2103 2104 2105 2106 2107 2108
    DataCache *This = impl_from_IOleCache2(iface);
    DataCacheEntry *cache_entry;
    HRESULT hr = S_OK;

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

    if (dwDiscardOptions == DISCARDCACHE_SAVEIFDIRTY)
2109
        hr = DataCache_Save(&This->IPersistStorage_iface, This->presentationStorage, TRUE);
2110 2111 2112 2113 2114 2115 2116 2117 2118

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

    return hr;
2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134
}


/*********************************************************
 * 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)
{
2135
  DataCache *this = impl_from_IOleCacheControl(iface);
2136

2137
  return IUnknown_QueryInterface(this->outer_unk, riid, ppvObject);
2138 2139 2140 2141 2142
}

/************************************************************************
 * DataCache_IOleCacheControl_AddRef (IUnknown)
 */
2143
static ULONG WINAPI DataCache_IOleCacheControl_AddRef(
2144 2145
            IOleCacheControl* iface)
{
2146
  DataCache *this = impl_from_IOleCacheControl(iface);
2147

2148
  return IUnknown_AddRef(this->outer_unk);
2149 2150 2151 2152 2153
}

/************************************************************************
 * DataCache_IOleCacheControl_Release (IUnknown)
 */
2154
static ULONG WINAPI DataCache_IOleCacheControl_Release(
2155 2156
            IOleCacheControl* iface)
{
2157
  DataCache *this = impl_from_IOleCacheControl(iface);
2158

2159
  return IUnknown_Release(this->outer_unk);
2160 2161
}

2162 2163 2164 2165
/************************************************************************
 * DataCache_OnRun (IOleCacheControl)
 */
static HRESULT WINAPI DataCache_OnRun(IOleCacheControl* iface, IDataObject *data_obj)
2166
{
2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182
    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;
2183 2184
}

2185 2186 2187 2188
/************************************************************************
 * DataCache_OnStop (IOleCacheControl)
 */
static HRESULT WINAPI DataCache_OnStop(IOleCacheControl* iface)
2189
{
2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208
    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;
2209
}
2210

2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245
/************************************************************************
 *              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)
{
2246 2247
    DataCache *This = impl_from_IAdviseSink(iface);
    TRACE("(%p)->(%s, %p)\n", This, debugstr_formatetc(fmt), med);
2248
    IOleCache2_SetData(&This->IOleCache2_iface, fmt, med, FALSE);
2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270
}

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");
}

2271 2272 2273
/*
 * Virtual function tables for the DataCache class.
 */
2274
static const IUnknownVtbl DataCache_NDIUnknown_VTable =
2275 2276 2277 2278 2279 2280
{
  DataCache_NDIUnknown_QueryInterface,
  DataCache_NDIUnknown_AddRef,
  DataCache_NDIUnknown_Release
};

2281
static const IDataObjectVtbl DataCache_IDataObject_VTable =
2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296
{
  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
};

2297
static const IPersistStorageVtbl DataCache_IPersistStorage_VTable =
2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310
{
  DataCache_IPersistStorage_QueryInterface,
  DataCache_IPersistStorage_AddRef,
  DataCache_IPersistStorage_Release,
  DataCache_GetClassID,
  DataCache_IsDirty,
  DataCache_InitNew,
  DataCache_Load,
  DataCache_Save,
  DataCache_SaveCompleted,
  DataCache_HandsOffStorage
};

2311
static const IViewObject2Vtbl DataCache_IViewObject2_VTable =
2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324
{
  DataCache_IViewObject2_QueryInterface,
  DataCache_IViewObject2_AddRef,
  DataCache_IViewObject2_Release,
  DataCache_Draw,
  DataCache_GetColorSet,
  DataCache_Freeze,
  DataCache_Unfreeze,
  DataCache_SetAdvise,
  DataCache_GetAdvise,
  DataCache_GetExtent
};

2325
static const IOleCache2Vtbl DataCache_IOleCache2_VTable =
2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338
{
  DataCache_IOleCache2_QueryInterface,
  DataCache_IOleCache2_AddRef,
  DataCache_IOleCache2_Release,
  DataCache_Cache,
  DataCache_Uncache,
  DataCache_EnumCache,
  DataCache_InitCache,
  DataCache_IOleCache2_SetData,
  DataCache_UpdateCache,
  DataCache_DiscardCache
};

2339
static const IOleCacheControlVtbl DataCache_IOleCacheControl_VTable =
2340 2341 2342 2343 2344 2345 2346 2347
{
  DataCache_IOleCacheControl_QueryInterface,
  DataCache_IOleCacheControl_AddRef,
  DataCache_IOleCacheControl_Release,
  DataCache_OnRun,
  DataCache_OnStop
};

2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359
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
};

2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379
/*********************************************************
 * 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.
   */
2380
  newObject->IDataObject_iface.lpVtbl = &DataCache_IDataObject_VTable;
2381
  newObject->IUnknown_inner.lpVtbl = &DataCache_NDIUnknown_VTable;
2382 2383 2384 2385 2386
  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;
2387
  newObject->outer_unk = pUnkOuter ? pUnkOuter : &newObject->IUnknown_inner;
2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399
  newObject->ref = 1;

  /*
   * 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;
2400
  newObject->running_object = NULL;
2401 2402 2403

  return newObject;
}
2404

2405 2406
/******************************************************************************
 *              CreateDataCache        [OLE32.@]
2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422
 *
 * 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
2423
 *  IOleCache, IOleCache2, IOleCacheControl, IPersistStorage, IDataObject,
2424
 *  IViewObject and IViewObject2.
2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450
 */
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.
   */
2451
  if ( pUnkOuter && !IsEqualIID(&IID_IUnknown, riid) )
2452
    return E_INVALIDARG;
2453 2454 2455 2456 2457 2458 2459 2460 2461 2462

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

  if (newCache == 0)
    return E_OUTOFMEMORY;

2463 2464
  hr = IUnknown_QueryInterface(&newCache->IUnknown_inner, riid, ppvObj);
  IUnknown_Release(&newCache->IUnknown_inner);
2465 2466 2467

  return hr;
}