riched20: Make richedit control IME aware.
[wine] / dlls / ole32 / hglobalstream.c
1 /*
2  * HGLOBAL Stream implementation
3  *
4  * This file contains the implementation of the stream interface
5  * for streams contained supported by an HGLOBAL pointer.
6  *
7  * Copyright 1999 Francis Beaudet
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with this library; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22  */
23
24 #include "config.h"
25
26 #include <assert.h>
27 #include <stdlib.h>
28 #include <stdarg.h>
29 #include <stdio.h>
30 #include <string.h>
31
32 #define COBJMACROS
33 #define NONAMELESSUNION
34 #define NONAMELESSSTRUCT
35
36 #include "windef.h"
37 #include "winbase.h"
38 #include "winuser.h"
39 #include "objbase.h"
40 #include "ole2.h"
41 #include "winerror.h"
42 #include "winternl.h"
43
44 #include "wine/debug.h"
45
46 WINE_DEFAULT_DEBUG_CHANNEL(storage);
47
48 /****************************************************************************
49  * HGLOBALStreamImpl definition.
50  *
51  * This class implements the IStream interface and represents a stream
52  * supported by an HGLOBAL pointer.
53  */
54 struct HGLOBALStreamImpl
55 {
56   const IStreamVtbl *lpVtbl;   /* Needs to be the first item in the struct
57                           * since we want to cast this in an IStream pointer */
58
59   /*
60    * Reference count
61    */
62   LONG               ref;
63
64   /*
65    * Support for the stream
66    */
67   HGLOBAL supportHandle;
68
69   /*
70    * This flag is TRUE if the HGLOBAL is destroyed when the stream
71    * is finally released.
72    */
73   BOOL    deleteOnRelease;
74
75   /*
76    * Helper variable that contains the size of the stream
77    */
78   ULARGE_INTEGER     streamSize;
79
80   /*
81    * This is the current position of the cursor in the stream
82    */
83   ULARGE_INTEGER     currentPosition;
84 };
85
86 typedef struct HGLOBALStreamImpl HGLOBALStreamImpl;
87
88 /***
89  * This is the destructor of the HGLOBALStreamImpl class.
90  *
91  * This method will clean-up all the resources used-up by the given HGLOBALStreamImpl
92  * class. The pointer passed-in to this function will be freed and will not
93  * be valid anymore.
94  */
95 static void HGLOBALStreamImpl_Destroy(HGLOBALStreamImpl* This)
96 {
97   TRACE("(%p)\n", This);
98
99   /*
100    * Release the HGlobal if the constructor asked for that.
101    */
102   if (This->deleteOnRelease)
103   {
104     GlobalFree(This->supportHandle);
105     This->supportHandle=0;
106   }
107
108   /*
109    * Finally, free the memory used-up by the class.
110    */
111   HeapFree(GetProcessHeap(), 0, This);
112 }
113
114 /***
115  * This implements the IUnknown method AddRef for this
116  * class
117  */
118 static ULONG WINAPI HGLOBALStreamImpl_AddRef(
119                 IStream* iface)
120 {
121   HGLOBALStreamImpl* const This=(HGLOBALStreamImpl*)iface;
122   return InterlockedIncrement(&This->ref);
123 }
124
125 /***
126  * This implements the IUnknown method QueryInterface for this
127  * class
128  */
129 static HRESULT WINAPI HGLOBALStreamImpl_QueryInterface(
130                   IStream*     iface,
131                   REFIID         riid,        /* [in] */
132                   void**         ppvObject)   /* [iid_is][out] */
133 {
134   HGLOBALStreamImpl* const This=(HGLOBALStreamImpl*)iface;
135
136   /*
137    * Perform a sanity check on the parameters.
138    */
139   if (ppvObject==0)
140     return E_INVALIDARG;
141
142   /*
143    * Initialize the return parameter.
144    */
145   *ppvObject = 0;
146
147   /*
148    * Compare the riid with the interface IDs implemented by this object.
149    */
150   if (IsEqualIID(&IID_IUnknown, riid) ||
151       IsEqualIID(&IID_ISequentialStream, riid) ||
152       IsEqualIID(&IID_IStream, riid))
153   {
154     *ppvObject = (IStream*)This;
155   }
156
157   /*
158    * Check that we obtained an interface.
159    */
160   if ((*ppvObject)==0)
161     return E_NOINTERFACE;
162
163   /*
164    * Query Interface always increases the reference count by one when it is
165    * successful
166    */
167   HGLOBALStreamImpl_AddRef(iface);
168
169   return S_OK;
170 }
171
172 /***
173  * This implements the IUnknown method Release for this
174  * class
175  */
176 static ULONG WINAPI HGLOBALStreamImpl_Release(
177                 IStream* iface)
178 {
179   HGLOBALStreamImpl* const This=(HGLOBALStreamImpl*)iface;
180   ULONG newRef;
181
182   newRef = InterlockedDecrement(&This->ref);
183
184   /*
185    * If the reference count goes down to 0, perform suicide.
186    */
187   if (newRef==0)
188   {
189     HGLOBALStreamImpl_Destroy(This);
190   }
191
192   return newRef;
193 }
194
195 /***
196  * This method is part of the ISequentialStream interface.
197  *
198  * If reads a block of information from the stream at the current
199  * position. It then moves the current position at the end of the
200  * read block
201  *
202  * See the documentation of ISequentialStream for more info.
203  */
204 static HRESULT WINAPI HGLOBALStreamImpl_Read(
205                   IStream*     iface,
206                   void*          pv,        /* [length_is][size_is][out] */
207                   ULONG          cb,        /* [in] */
208                   ULONG*         pcbRead)   /* [out] */
209 {
210   HGLOBALStreamImpl* const This=(HGLOBALStreamImpl*)iface;
211
212   void* supportBuffer;
213   ULONG bytesReadBuffer;
214   ULONG bytesToReadFromBuffer;
215
216   TRACE("(%p, %p, %d, %p)\n", iface,
217         pv, cb, pcbRead);
218
219   /*
220    * If the caller is not interested in the nubmer of bytes read,
221    * we use another buffer to avoid "if" statements in the code.
222    */
223   if (pcbRead==0)
224     pcbRead = &bytesReadBuffer;
225
226   /*
227    * Using the known size of the stream, calculate the number of bytes
228    * to read from the block chain
229    */
230   bytesToReadFromBuffer = min( This->streamSize.u.LowPart - This->currentPosition.u.LowPart, cb);
231
232   /*
233    * Lock the buffer in position and copy the data.
234    */
235   supportBuffer = GlobalLock(This->supportHandle);
236   if (!supportBuffer)
237   {
238       WARN("read from invalid hglobal %p\n", This->supportHandle);
239       *pcbRead = 0;
240       return S_OK;
241   }
242
243   memcpy(pv, (char *) supportBuffer+This->currentPosition.u.LowPart, bytesToReadFromBuffer);
244
245   /*
246    * Move the current position to the new position
247    */
248   This->currentPosition.u.LowPart+=bytesToReadFromBuffer;
249
250   /*
251    * Return the number of bytes read.
252    */
253   *pcbRead = bytesToReadFromBuffer;
254
255   /*
256    * Cleanup
257    */
258   GlobalUnlock(This->supportHandle);
259
260   /*
261    * Always returns S_OK even if the end of the stream is reached before the
262    * buffer is filled
263    */
264
265   return S_OK;
266 }
267
268 /***
269  * This method is part of the ISequentialStream interface.
270  *
271  * It writes a block of information to the stream at the current
272  * position. It then moves the current position at the end of the
273  * written block. If the stream is too small to fit the block,
274  * the stream is grown to fit.
275  *
276  * See the documentation of ISequentialStream for more info.
277  */
278 static HRESULT WINAPI HGLOBALStreamImpl_Write(
279                   IStream*     iface,
280                   const void*    pv,          /* [size_is][in] */
281                   ULONG          cb,          /* [in] */
282                   ULONG*         pcbWritten)  /* [out] */
283 {
284   HGLOBALStreamImpl* const This=(HGLOBALStreamImpl*)iface;
285
286   void*          supportBuffer;
287   ULARGE_INTEGER newSize;
288   ULONG          bytesWritten = 0;
289
290   TRACE("(%p, %p, %d, %p)\n", iface, pv, cb, pcbWritten);
291
292   /*
293    * If the caller is not interested in the number of bytes written,
294    * we use another buffer to avoid "if" statements in the code.
295    */
296   if (pcbWritten == 0)
297     pcbWritten = &bytesWritten;
298
299   if (cb == 0)
300     goto out;
301
302   *pcbWritten = 0;
303
304   newSize.u.HighPart = 0;
305   newSize.u.LowPart = This->currentPosition.u.LowPart + cb;
306
307   /*
308    * Verify if we need to grow the stream
309    */
310   if (newSize.u.LowPart > This->streamSize.u.LowPart)
311   {
312     /* grow stream */
313     HRESULT hr = IStream_SetSize(iface, newSize);
314     if (FAILED(hr))
315     {
316       ERR("IStream_SetSize failed with error 0x%08x\n", hr);
317       return hr;
318     }
319   }
320
321   /*
322    * Lock the buffer in position and copy the data.
323    */
324   supportBuffer = GlobalLock(This->supportHandle);
325   if (!supportBuffer)
326   {
327       WARN("write to invalid hglobal %p\n", This->supportHandle);
328       return S_OK;
329   }
330
331   memcpy((char *) supportBuffer+This->currentPosition.u.LowPart, pv, cb);
332
333   /*
334    * Move the current position to the new position
335    */
336   This->currentPosition.u.LowPart+=cb;
337
338   /*
339    * Cleanup
340    */
341   GlobalUnlock(This->supportHandle);
342
343 out:
344   /*
345    * Return the number of bytes read.
346    */
347   *pcbWritten = cb;
348
349   return S_OK;
350 }
351
352 /***
353  * This method is part of the IStream interface.
354  *
355  * It will move the current stream pointer according to the parameters
356  * given.
357  *
358  * See the documentation of IStream for more info.
359  */
360 static HRESULT WINAPI HGLOBALStreamImpl_Seek(
361                   IStream*      iface,
362                   LARGE_INTEGER   dlibMove,         /* [in] */
363                   DWORD           dwOrigin,         /* [in] */
364                   ULARGE_INTEGER* plibNewPosition) /* [out] */
365 {
366   HGLOBALStreamImpl* const This=(HGLOBALStreamImpl*)iface;
367
368   ULARGE_INTEGER newPosition;
369
370   TRACE("(%p, %x%08x, %d, %p)\n", iface, dlibMove.u.HighPart,
371         dlibMove.u.LowPart, dwOrigin, plibNewPosition);
372
373   /*
374    * The file pointer is moved depending on the given "function"
375    * parameter.
376    */
377   switch (dwOrigin)
378   {
379     case STREAM_SEEK_SET:
380       newPosition.u.HighPart = 0;
381       newPosition.u.LowPart = 0;
382       break;
383     case STREAM_SEEK_CUR:
384       newPosition = This->currentPosition;
385       break;
386     case STREAM_SEEK_END:
387       newPosition = This->streamSize;
388       break;
389     default:
390       return STG_E_INVALIDFUNCTION;
391   }
392
393   /*
394    * Move the actual file pointer
395    * If the file pointer ends-up after the end of the stream, the next Write operation will
396    * make the file larger. This is how it is documented.
397    */
398   if (dlibMove.QuadPart < 0 && newPosition.QuadPart < -dlibMove.QuadPart) return STG_E_INVALIDFUNCTION;
399
400   newPosition.QuadPart = RtlLargeIntegerAdd(newPosition.QuadPart, dlibMove.QuadPart);
401
402   if (plibNewPosition) *plibNewPosition = newPosition;
403   This->currentPosition = newPosition;
404
405   return S_OK;
406 }
407
408 /***
409  * This method is part of the IStream interface.
410  *
411  * It will change the size of a stream.
412  *
413  * TODO: Switch from small blocks to big blocks and vice versa.
414  *
415  * See the documentation of IStream for more info.
416  */
417 static HRESULT WINAPI HGLOBALStreamImpl_SetSize(
418                                      IStream*      iface,
419                                      ULARGE_INTEGER  libNewSize)   /* [in] */
420 {
421   HGLOBALStreamImpl* const This=(HGLOBALStreamImpl*)iface;
422   HGLOBAL supportHandle;
423
424   TRACE("(%p, %d)\n", iface, libNewSize.u.LowPart);
425
426   /*
427    * HighPart is ignored as shown in tests
428    */
429
430   if (This->streamSize.u.LowPart == libNewSize.u.LowPart)
431     return S_OK;
432
433   /*
434    * Re allocate the HGlobal to fit the new size of the stream.
435    */
436   supportHandle = GlobalReAlloc(This->supportHandle, libNewSize.u.LowPart, 0);
437
438   if (supportHandle == 0)
439     return E_OUTOFMEMORY;
440
441   This->supportHandle = supportHandle;
442   This->streamSize.u.LowPart = libNewSize.u.LowPart;
443
444   return S_OK;
445 }
446
447 /***
448  * This method is part of the IStream interface.
449  *
450  * It will copy the 'cb' Bytes to 'pstm' IStream.
451  *
452  * See the documentation of IStream for more info.
453  */
454 static HRESULT WINAPI HGLOBALStreamImpl_CopyTo(
455                                     IStream*      iface,
456                                     IStream*      pstm,         /* [unique][in] */
457                                     ULARGE_INTEGER  cb,           /* [in] */
458                                     ULARGE_INTEGER* pcbRead,      /* [out] */
459                                     ULARGE_INTEGER* pcbWritten)   /* [out] */
460 {
461   HRESULT        hr = S_OK;
462   BYTE           tmpBuffer[128];
463   ULONG          bytesRead, bytesWritten, copySize;
464   ULARGE_INTEGER totalBytesRead;
465   ULARGE_INTEGER totalBytesWritten;
466
467   TRACE("(%p, %p, %d, %p, %p)\n", iface, pstm,
468         cb.u.LowPart, pcbRead, pcbWritten);
469
470   /*
471    * Sanity check
472    */
473   if ( pstm == 0 )
474     return STG_E_INVALIDPOINTER;
475
476   totalBytesRead.u.LowPart = totalBytesRead.u.HighPart = 0;
477   totalBytesWritten.u.LowPart = totalBytesWritten.u.HighPart = 0;
478
479   /*
480    * use stack to store data temporarly
481    * there is surely more performant way of doing it, for now this basic
482    * implementation will do the job
483    */
484   while ( cb.u.LowPart > 0 )
485   {
486     if ( cb.u.LowPart >= 128 )
487       copySize = 128;
488     else
489       copySize = cb.u.LowPart;
490
491     hr = IStream_Read(iface, tmpBuffer, copySize, &bytesRead);
492     if (FAILED(hr))
493         break;
494
495     totalBytesRead.u.LowPart += bytesRead;
496
497     if (bytesRead)
498     {
499         hr = IStream_Write(pstm, tmpBuffer, bytesRead, &bytesWritten);
500         if (FAILED(hr))
501             break;
502
503         totalBytesWritten.u.LowPart += bytesWritten;
504     }
505
506     if (bytesRead!=copySize)
507       cb.u.LowPart = 0;
508     else
509       cb.u.LowPart -= bytesRead;
510   }
511
512   /*
513    * Update number of bytes read and written
514    */
515   if (pcbRead)
516   {
517     pcbRead->u.LowPart = totalBytesRead.u.LowPart;
518     pcbRead->u.HighPart = totalBytesRead.u.HighPart;
519   }
520
521   if (pcbWritten)
522   {
523     pcbWritten->u.LowPart = totalBytesWritten.u.LowPart;
524     pcbWritten->u.HighPart = totalBytesWritten.u.HighPart;
525   }
526   return hr;
527 }
528
529 /***
530  * This method is part of the IStream interface.
531  *
532  * For streams supported by HGLOBALS, this function does nothing.
533  * This is what the documentation tells us.
534  *
535  * See the documentation of IStream for more info.
536  */
537 static HRESULT WINAPI HGLOBALStreamImpl_Commit(
538                   IStream*      iface,
539                   DWORD         grfCommitFlags)  /* [in] */
540 {
541   return S_OK;
542 }
543
544 /***
545  * This method is part of the IStream interface.
546  *
547  * For streams supported by HGLOBALS, this function does nothing.
548  * This is what the documentation tells us.
549  *
550  * See the documentation of IStream for more info.
551  */
552 static HRESULT WINAPI HGLOBALStreamImpl_Revert(
553                   IStream* iface)
554 {
555   return S_OK;
556 }
557
558 /***
559  * This method is part of the IStream interface.
560  *
561  * For streams supported by HGLOBALS, this function does nothing.
562  * This is what the documentation tells us.
563  *
564  * See the documentation of IStream for more info.
565  */
566 static HRESULT WINAPI HGLOBALStreamImpl_LockRegion(
567                   IStream*       iface,
568                   ULARGE_INTEGER libOffset,   /* [in] */
569                   ULARGE_INTEGER cb,          /* [in] */
570                   DWORD          dwLockType)  /* [in] */
571 {
572   return STG_E_INVALIDFUNCTION;
573 }
574
575 /*
576  * This method is part of the IStream interface.
577  *
578  * For streams supported by HGLOBALS, this function does nothing.
579  * This is what the documentation tells us.
580  *
581  * See the documentation of IStream for more info.
582  */
583 static HRESULT WINAPI HGLOBALStreamImpl_UnlockRegion(
584                   IStream*       iface,
585                   ULARGE_INTEGER libOffset,   /* [in] */
586                   ULARGE_INTEGER cb,          /* [in] */
587                   DWORD          dwLockType)  /* [in] */
588 {
589   return S_OK;
590 }
591
592 /***
593  * This method is part of the IStream interface.
594  *
595  * This method returns information about the current
596  * stream.
597  *
598  * See the documentation of IStream for more info.
599  */
600 static HRESULT WINAPI HGLOBALStreamImpl_Stat(
601                   IStream*     iface,
602                   STATSTG*     pstatstg,     /* [out] */
603                   DWORD        grfStatFlag)  /* [in] */
604 {
605   HGLOBALStreamImpl* const This=(HGLOBALStreamImpl*)iface;
606
607   memset(pstatstg, 0, sizeof(STATSTG));
608
609   pstatstg->pwcsName = NULL;
610   pstatstg->type     = STGTY_STREAM;
611   pstatstg->cbSize   = This->streamSize;
612
613   return S_OK;
614 }
615
616 static HRESULT WINAPI HGLOBALStreamImpl_Clone(
617                   IStream*     iface,
618                   IStream**    ppstm) /* [out] */
619 {
620   ULARGE_INTEGER dummy;
621   LARGE_INTEGER offset;
622   HRESULT hr;
623   HGLOBALStreamImpl* const This=(HGLOBALStreamImpl*)iface;
624   TRACE(" Cloning %p (deleteOnRelease=%d seek position=%ld)\n",iface,This->deleteOnRelease,(long)This->currentPosition.QuadPart);
625   hr=CreateStreamOnHGlobal(This->supportHandle, FALSE, ppstm);
626   if(FAILED(hr))
627     return hr;
628   offset.QuadPart=(LONGLONG)This->currentPosition.QuadPart;
629   HGLOBALStreamImpl_Seek(*ppstm,offset,STREAM_SEEK_SET,&dummy);
630   return S_OK;
631 }
632
633 /*
634  * Virtual function table for the HGLOBALStreamImpl class.
635  */
636 static const IStreamVtbl HGLOBALStreamImpl_Vtbl =
637 {
638     HGLOBALStreamImpl_QueryInterface,
639     HGLOBALStreamImpl_AddRef,
640     HGLOBALStreamImpl_Release,
641     HGLOBALStreamImpl_Read,
642     HGLOBALStreamImpl_Write,
643     HGLOBALStreamImpl_Seek,
644     HGLOBALStreamImpl_SetSize,
645     HGLOBALStreamImpl_CopyTo,
646     HGLOBALStreamImpl_Commit,
647     HGLOBALStreamImpl_Revert,
648     HGLOBALStreamImpl_LockRegion,
649     HGLOBALStreamImpl_UnlockRegion,
650     HGLOBALStreamImpl_Stat,
651     HGLOBALStreamImpl_Clone
652 };
653
654 /******************************************************************************
655 ** HGLOBALStreamImpl implementation
656 */
657
658 /***
659  * This is the constructor for the HGLOBALStreamImpl class.
660  *
661  * Params:
662  *    hGlobal          - Handle that will support the stream. can be NULL.
663  *    fDeleteOnRelease - Flag set to TRUE if the HGLOBAL will be released
664  *                       when the IStream object is destroyed.
665  */
666 static HGLOBALStreamImpl* HGLOBALStreamImpl_Construct(
667                 HGLOBAL  hGlobal,
668                 BOOL     fDeleteOnRelease)
669 {
670   HGLOBALStreamImpl* newStream;
671
672   newStream = HeapAlloc(GetProcessHeap(), 0, sizeof(HGLOBALStreamImpl));
673
674   if (newStream!=0)
675   {
676     /*
677      * Set-up the virtual function table and reference count.
678      */
679     newStream->lpVtbl = &HGLOBALStreamImpl_Vtbl;
680     newStream->ref    = 0;
681
682     /*
683      * Initialize the support.
684      */
685     newStream->supportHandle = hGlobal;
686     newStream->deleteOnRelease = fDeleteOnRelease;
687
688     /*
689      * This method will allocate a handle if one is not supplied.
690      */
691     if (!newStream->supportHandle)
692     {
693       newStream->supportHandle = GlobalAlloc(GMEM_MOVEABLE | GMEM_NODISCARD |
694                                              GMEM_SHARE, 0);
695     }
696
697     /*
698      * Start the stream at the beginning.
699      */
700     newStream->currentPosition.u.HighPart = 0;
701     newStream->currentPosition.u.LowPart = 0;
702
703     /*
704      * Initialize the size of the stream to the size of the handle.
705      */
706     newStream->streamSize.u.HighPart = 0;
707     newStream->streamSize.u.LowPart  = GlobalSize(newStream->supportHandle);
708   }
709
710   return newStream;
711 }
712
713
714 /***********************************************************************
715  *           CreateStreamOnHGlobal     [OLE32.@]
716  */
717 HRESULT WINAPI CreateStreamOnHGlobal(
718                 HGLOBAL   hGlobal,
719                 BOOL      fDeleteOnRelease,
720                 LPSTREAM* ppstm)
721 {
722   HGLOBALStreamImpl* newStream;
723
724   newStream = HGLOBALStreamImpl_Construct(hGlobal,
725                                           fDeleteOnRelease);
726
727   if (newStream!=NULL)
728   {
729     return IUnknown_QueryInterface((IUnknown*)newStream,
730                                    &IID_IStream,
731                                    (void**)ppstm);
732   }
733
734   return E_OUTOFMEMORY;
735 }
736
737 /***********************************************************************
738  *           GetHGlobalFromStream     [OLE32.@]
739  */
740 HRESULT WINAPI GetHGlobalFromStream(IStream* pstm, HGLOBAL* phglobal)
741 {
742   HGLOBALStreamImpl* pStream;
743
744   if (pstm == NULL)
745     return E_INVALIDARG;
746
747   pStream = (HGLOBALStreamImpl*) pstm;
748
749   /*
750    * Verify that the stream object was created with CreateStreamOnHGlobal.
751    */
752   if (pStream->lpVtbl == &HGLOBALStreamImpl_Vtbl)
753     *phglobal = pStream->supportHandle;
754   else
755   {
756     *phglobal = 0;
757     return E_INVALIDARG;
758   }
759
760   return S_OK;
761 }