windowscodecs: Create Image Descriptor metadata block for a GIF frame.
[wine] / dlls / ddraw / main.c
1 /*        DirectDraw Base Functions
2  *
3  * Copyright 1997-1999 Marcus Meissner
4  * Copyright 1998 Lionel Ulmer
5  * Copyright 2000-2001 TransGaming Technologies Inc.
6  * Copyright 2006 Stefan Dösinger
7  * Copyright 2008 Denver Gingerich
8  *
9  * This file contains the (internal) driver registration functions,
10  * driver enumeration APIs and DirectDraw creation functions.
11  *
12  * This library is free software; you can redistribute it and/or
13  * modify it under the terms of the GNU Lesser General Public
14  * License as published by the Free Software Foundation; either
15  * version 2.1 of the License, or (at your option) any later version.
16  *
17  * This library is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20  * Lesser General Public License for more details.
21  *
22  * You should have received a copy of the GNU Lesser General Public
23  * License along with this library; if not, write to the Free Software
24  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
25  */
26
27 #include "config.h"
28 #include "wine/port.h"
29
30 #define DDRAW_INIT_GUID
31 #include "ddraw_private.h"
32 #include "rpcproxy.h"
33
34 #include "wine/exception.h"
35 #include "winreg.h"
36
37 WINE_DEFAULT_DEBUG_CHANNEL(ddraw);
38
39 /* The configured default surface */
40 enum wined3d_surface_type DefaultSurfaceType = WINED3D_SURFACE_TYPE_OPENGL;
41
42 static struct list global_ddraw_list = LIST_INIT(global_ddraw_list);
43
44 static HINSTANCE instance;
45
46 /* value of ForceRefreshRate */
47 DWORD force_refresh_rate = 0;
48
49 /* Handle table functions */
50 BOOL ddraw_handle_table_init(struct ddraw_handle_table *t, UINT initial_size)
51 {
52     t->entries = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, initial_size * sizeof(*t->entries));
53     if (!t->entries)
54     {
55         ERR("Failed to allocate handle table memory.\n");
56         return FALSE;
57     }
58     t->free_entries = NULL;
59     t->table_size = initial_size;
60     t->entry_count = 0;
61
62     return TRUE;
63 }
64
65 void ddraw_handle_table_destroy(struct ddraw_handle_table *t)
66 {
67     HeapFree(GetProcessHeap(), 0, t->entries);
68     memset(t, 0, sizeof(*t));
69 }
70
71 DWORD ddraw_allocate_handle(struct ddraw_handle_table *t, void *object, enum ddraw_handle_type type)
72 {
73     struct ddraw_handle_entry *entry;
74
75     if (t->free_entries)
76     {
77         DWORD idx = t->free_entries - t->entries;
78         /* Use a free handle */
79         entry = t->free_entries;
80         if (entry->type != DDRAW_HANDLE_FREE)
81         {
82             ERR("Handle %#x (%p) is in the free list, but has type %#x.\n", idx, entry->object, entry->type);
83             return DDRAW_INVALID_HANDLE;
84         }
85         t->free_entries = entry->object;
86         entry->object = object;
87         entry->type = type;
88
89         return idx;
90     }
91
92     if (!(t->entry_count < t->table_size))
93     {
94         /* Grow the table */
95         UINT new_size = t->table_size + (t->table_size >> 1);
96         struct ddraw_handle_entry *new_entries = HeapReAlloc(GetProcessHeap(),
97                 0, t->entries, new_size * sizeof(*t->entries));
98         if (!new_entries)
99         {
100             ERR("Failed to grow the handle table.\n");
101             return DDRAW_INVALID_HANDLE;
102         }
103         t->entries = new_entries;
104         t->table_size = new_size;
105     }
106
107     entry = &t->entries[t->entry_count];
108     entry->object = object;
109     entry->type = type;
110
111     return t->entry_count++;
112 }
113
114 void *ddraw_free_handle(struct ddraw_handle_table *t, DWORD handle, enum ddraw_handle_type type)
115 {
116     struct ddraw_handle_entry *entry;
117     void *object;
118
119     if (handle == DDRAW_INVALID_HANDLE || handle >= t->entry_count)
120     {
121         WARN("Invalid handle %#x passed.\n", handle);
122         return NULL;
123     }
124
125     entry = &t->entries[handle];
126     if (entry->type != type)
127     {
128         WARN("Handle %#x (%p) is not of type %#x.\n", handle, entry->object, type);
129         return NULL;
130     }
131
132     object = entry->object;
133     entry->object = t->free_entries;
134     entry->type = DDRAW_HANDLE_FREE;
135     t->free_entries = entry;
136
137     return object;
138 }
139
140 void *ddraw_get_object(struct ddraw_handle_table *t, DWORD handle, enum ddraw_handle_type type)
141 {
142     struct ddraw_handle_entry *entry;
143
144     if (handle == DDRAW_INVALID_HANDLE || handle >= t->entry_count)
145     {
146         WARN("Invalid handle %#x passed.\n", handle);
147         return NULL;
148     }
149
150     entry = &t->entries[handle];
151     if (entry->type != type)
152     {
153         WARN("Handle %#x (%p) is not of type %#x.\n", handle, entry->object, type);
154         return NULL;
155     }
156
157     return entry->object;
158 }
159
160 /***********************************************************************
161  *
162  * Helper function for DirectDrawCreate and friends
163  * Creates a new DDraw interface with the given REFIID
164  *
165  * Interfaces that can be created:
166  *  IDirectDraw, IDirectDraw2, IDirectDraw4, IDirectDraw7
167  *  IDirect3D, IDirect3D2, IDirect3D3, IDirect3D7. (Does Windows return
168  *  IDirect3D interfaces?)
169  *
170  * Arguments:
171  *  guid: ID of the requested driver, NULL for the default driver.
172  *        The GUID can be queried with DirectDrawEnumerate(Ex)A/W
173  *  DD: Used to return the pointer to the created object
174  *  UnkOuter: For aggregation, which is unsupported. Must be NULL
175  *  iid: requested version ID.
176  *
177  * Returns:
178  *  DD_OK if the Interface was created successfully
179  *  CLASS_E_NOAGGREGATION if UnkOuter is not NULL
180  *  E_OUTOFMEMORY if some allocation failed
181  *
182  ***********************************************************************/
183 static HRESULT
184 DDRAW_Create(const GUID *guid,
185              void **DD,
186              IUnknown *UnkOuter,
187              REFIID iid)
188 {
189     enum wined3d_device_type device_type;
190     struct ddraw *ddraw;
191     HRESULT hr;
192
193     TRACE("driver_guid %s, ddraw %p, outer_unknown %p, interface_iid %s.\n",
194             debugstr_guid(guid), DD, UnkOuter, debugstr_guid(iid));
195
196     *DD = NULL;
197
198     /* We don't care about this guids. Well, there's no special guid anyway
199      * OK, we could
200      */
201     if (guid == (GUID *) DDCREATE_EMULATIONONLY)
202     {
203         /* Use the reference device id. This doesn't actually change anything,
204          * WineD3D always uses OpenGL for D3D rendering. One could make it request
205          * indirect rendering
206          */
207         device_type = WINED3D_DEVICE_TYPE_REF;
208     }
209     else if(guid == (GUID *) DDCREATE_HARDWAREONLY)
210     {
211         device_type = WINED3D_DEVICE_TYPE_HAL;
212     }
213     else
214     {
215         device_type = 0;
216     }
217
218     /* DDraw doesn't support aggregation, according to msdn */
219     if (UnkOuter != NULL)
220         return CLASS_E_NOAGGREGATION;
221
222     /* DirectDraw creation comes here */
223     ddraw = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ddraw));
224     if (!ddraw)
225     {
226         ERR("Out of memory when creating DirectDraw\n");
227         return E_OUTOFMEMORY;
228     }
229
230     hr = ddraw_init(ddraw, device_type);
231     if (FAILED(hr))
232     {
233         WARN("Failed to initialize ddraw object, hr %#x.\n", hr);
234         HeapFree(GetProcessHeap(), 0, ddraw);
235         return hr;
236     }
237
238     hr = IDirectDraw7_QueryInterface(&ddraw->IDirectDraw7_iface, iid, DD);
239     IDirectDraw7_Release(&ddraw->IDirectDraw7_iface);
240     if (SUCCEEDED(hr))
241         list_add_head(&global_ddraw_list, &ddraw->ddraw_list_entry);
242     else
243         WARN("Failed to query interface %s from ddraw object %p.\n", debugstr_guid(iid), ddraw);
244
245     return hr;
246 }
247
248 /***********************************************************************
249  * DirectDrawCreate (DDRAW.@)
250  *
251  * Creates legacy DirectDraw Interfaces. Can't create IDirectDraw7
252  * interfaces in theory
253  *
254  * Arguments, return values: See DDRAW_Create
255  *
256  ***********************************************************************/
257 HRESULT WINAPI DECLSPEC_HOTPATCH
258 DirectDrawCreate(GUID *GUID,
259                  LPDIRECTDRAW *DD,
260                  IUnknown *UnkOuter)
261 {
262     HRESULT hr;
263
264     TRACE("driver_guid %s, ddraw %p, outer_unknown %p.\n",
265             debugstr_guid(GUID), DD, UnkOuter);
266
267     wined3d_mutex_lock();
268     hr = DDRAW_Create(GUID, (void **) DD, UnkOuter, &IID_IDirectDraw);
269     wined3d_mutex_unlock();
270
271     if (SUCCEEDED(hr))
272     {
273         hr = IDirectDraw_Initialize(*DD, GUID);
274         if (FAILED(hr))
275             IDirectDraw_Release(*DD);
276     }
277
278     return hr;
279 }
280
281 /***********************************************************************
282  * DirectDrawCreateEx (DDRAW.@)
283  *
284  * Only creates new IDirectDraw7 interfaces, supposed to fail if legacy
285  * interfaces are requested.
286  *
287  * Arguments, return values: See DDRAW_Create
288  *
289  ***********************************************************************/
290 HRESULT WINAPI DECLSPEC_HOTPATCH
291 DirectDrawCreateEx(GUID *guid,
292                    LPVOID *dd,
293                    REFIID iid,
294                    IUnknown *UnkOuter)
295 {
296     HRESULT hr;
297
298     TRACE("driver_guid %s, ddraw %p, interface_iid %s, outer_unknown %p.\n",
299             debugstr_guid(guid), dd, debugstr_guid(iid), UnkOuter);
300
301     if (!IsEqualGUID(iid, &IID_IDirectDraw7))
302         return DDERR_INVALIDPARAMS;
303
304     wined3d_mutex_lock();
305     hr = DDRAW_Create(guid, dd, UnkOuter, iid);
306     wined3d_mutex_unlock();
307
308     if (SUCCEEDED(hr))
309     {
310         IDirectDraw7 *ddraw7 = *(IDirectDraw7 **)dd;
311         hr = IDirectDraw7_Initialize(ddraw7, guid);
312         if (FAILED(hr))
313             IDirectDraw7_Release(ddraw7);
314     }
315
316     return hr;
317 }
318
319 /***********************************************************************
320  * DirectDrawEnumerateA (DDRAW.@)
321  *
322  * Enumerates legacy ddraw drivers, ascii version. We only have one
323  * driver, which relays to WineD3D. If we were sufficiently cool,
324  * we could offer various interfaces, which use a different default surface
325  * implementation, but I think it's better to offer this choice in
326  * winecfg, because some apps use the default driver, so we would need
327  * a winecfg option anyway, and there shouldn't be 2 ways to set one setting
328  *
329  * Arguments:
330  *  Callback: Callback function from the app
331  *  Context: Argument to the call back.
332  *
333  * Returns:
334  *  DD_OK on success
335  *  E_INVALIDARG if the Callback caused a page fault
336  *
337  *
338  ***********************************************************************/
339 HRESULT WINAPI DirectDrawEnumerateA(LPDDENUMCALLBACKA Callback, void *Context)
340 {
341     TRACE("callback %p, context %p.\n", Callback, Context);
342
343     TRACE(" Enumerating default DirectDraw HAL interface\n");
344     /* We only have one driver */
345     __TRY
346     {
347         static CHAR driver_desc[] = "DirectDraw HAL",
348         driver_name[] = "display";
349
350         Callback(NULL, driver_desc, driver_name, Context);
351     }
352     __EXCEPT_PAGE_FAULT
353     {
354         return DDERR_INVALIDPARAMS;
355     }
356     __ENDTRY
357
358     TRACE(" End of enumeration\n");
359     return DD_OK;
360 }
361
362 /***********************************************************************
363  * DirectDrawEnumerateExA (DDRAW.@)
364  *
365  * Enumerates DirectDraw7 drivers, ascii version. See
366  * the comments above DirectDrawEnumerateA for more details.
367  *
368  * The Flag member is not supported right now.
369  *
370  ***********************************************************************/
371 HRESULT WINAPI DirectDrawEnumerateExA(LPDDENUMCALLBACKEXA Callback, void *Context, DWORD Flags)
372 {
373     TRACE("callback %p, context %p, flags %#x.\n", Callback, Context, Flags);
374
375     if (Flags & ~(DDENUM_ATTACHEDSECONDARYDEVICES |
376                   DDENUM_DETACHEDSECONDARYDEVICES |
377                   DDENUM_NONDISPLAYDEVICES))
378         return DDERR_INVALIDPARAMS;
379
380     if (Flags)
381         FIXME("flags 0x%08x not handled\n", Flags);
382
383     TRACE("Enumerating default DirectDraw HAL interface\n");
384
385     /* We only have one driver by now */
386     __TRY
387     {
388         static CHAR driver_desc[] = "DirectDraw HAL",
389         driver_name[] = "display";
390
391         /* QuickTime expects the description "DirectDraw HAL" */
392         Callback(NULL, driver_desc, driver_name, Context, 0);
393     }
394     __EXCEPT_PAGE_FAULT
395     {
396         return DDERR_INVALIDPARAMS;
397     }
398     __ENDTRY;
399
400     TRACE("End of enumeration\n");
401     return DD_OK;
402 }
403
404 /***********************************************************************
405  * DirectDrawEnumerateW (DDRAW.@)
406  *
407  * Enumerates legacy drivers, unicode version.
408  * This function is not implemented on Windows.
409  *
410  ***********************************************************************/
411 HRESULT WINAPI DirectDrawEnumerateW(LPDDENUMCALLBACKW callback, void *context)
412 {
413     TRACE("callback %p, context %p.\n", callback, context);
414
415     if (!callback)
416         return DDERR_INVALIDPARAMS;
417     else
418         return DDERR_UNSUPPORTED;
419 }
420
421 /***********************************************************************
422  * DirectDrawEnumerateExW (DDRAW.@)
423  *
424  * Enumerates DirectDraw7 drivers, unicode version.
425  * This function is not implemented on Windows.
426  *
427  ***********************************************************************/
428 HRESULT WINAPI DirectDrawEnumerateExW(LPDDENUMCALLBACKEXW callback, void *context, DWORD flags)
429 {
430     TRACE("callback %p, context %p, flags %#x.\n", callback, context, flags);
431
432     return DDERR_UNSUPPORTED;
433 }
434
435 /***********************************************************************
436  * Classfactory implementation.
437  ***********************************************************************/
438
439 /***********************************************************************
440  * CF_CreateDirectDraw
441  *
442  * DDraw creation function for the class factory
443  *
444  * Params:
445  *  UnkOuter: Set to NULL
446  *  iid: ID of the wanted interface
447  *  obj: Address to pass the interface pointer back
448  *
449  * Returns
450  *  DD_OK / DDERR*, see DDRAW_Create
451  *
452  ***********************************************************************/
453 static HRESULT
454 CF_CreateDirectDraw(IUnknown* UnkOuter, REFIID iid,
455                     void **obj)
456 {
457     HRESULT hr;
458
459     TRACE("outer_unknown %p, riid %s, object %p.\n", UnkOuter, debugstr_guid(iid), obj);
460
461     wined3d_mutex_lock();
462     hr = DDRAW_Create(NULL, obj, UnkOuter, iid);
463     wined3d_mutex_unlock();
464
465     return hr;
466 }
467
468 /***********************************************************************
469  * CF_CreateDirectDraw
470  *
471  * Clipper creation function for the class factory
472  *
473  * Params:
474  *  UnkOuter: Set to NULL
475  *  iid: ID of the wanted interface
476  *  obj: Address to pass the interface pointer back
477  *
478  * Returns
479  *  DD_OK / DDERR*, see DDRAW_Create
480  *
481  ***********************************************************************/
482 static HRESULT
483 CF_CreateDirectDrawClipper(IUnknown* UnkOuter, REFIID riid,
484                               void **obj)
485 {
486     HRESULT hr;
487     IDirectDrawClipper *Clip;
488
489     TRACE("outer_unknown %p, riid %s, object %p.\n", UnkOuter, debugstr_guid(riid), obj);
490
491     wined3d_mutex_lock();
492     hr = DirectDrawCreateClipper(0, &Clip, UnkOuter);
493     if (hr != DD_OK)
494     {
495         wined3d_mutex_unlock();
496         return hr;
497     }
498
499     hr = IDirectDrawClipper_QueryInterface(Clip, riid, obj);
500     IDirectDrawClipper_Release(Clip);
501
502     wined3d_mutex_unlock();
503
504     return hr;
505 }
506
507 static const struct object_creation_info object_creation[] =
508 {
509     { &CLSID_DirectDraw,        CF_CreateDirectDraw },
510     { &CLSID_DirectDraw7,       CF_CreateDirectDraw },
511     { &CLSID_DirectDrawClipper, CF_CreateDirectDrawClipper }
512 };
513
514 struct ddraw_class_factory
515 {
516     IClassFactory IClassFactory_iface;
517
518     LONG ref;
519     HRESULT (*pfnCreateInstance)(IUnknown *pUnkOuter, REFIID iid, LPVOID *ppObj);
520 };
521
522 static inline struct ddraw_class_factory *impl_from_IClassFactory(IClassFactory *iface)
523 {
524     return CONTAINING_RECORD(iface, struct ddraw_class_factory, IClassFactory_iface);
525 }
526
527 /*******************************************************************************
528  * IDirectDrawClassFactory::QueryInterface
529  *
530  * QueryInterface for the class factory
531  *
532  * PARAMS
533  *    riid   Reference to identifier of queried interface
534  *    ppv    Address to return the interface pointer at
535  *
536  * RETURNS
537  *    Success: S_OK
538  *    Failure: E_NOINTERFACE
539  *
540  *******************************************************************************/
541 static HRESULT WINAPI ddraw_class_factory_QueryInterface(IClassFactory *iface, REFIID riid, void **out)
542 {
543     TRACE("iface %p, riid %s, out %p.\n", iface, debugstr_guid(riid), out);
544
545     if (IsEqualGUID(riid, &IID_IUnknown)
546         || IsEqualGUID(riid, &IID_IClassFactory))
547     {
548         IClassFactory_AddRef(iface);
549         *out = iface;
550         return S_OK;
551     }
552
553     WARN("%s not implemented, returning E_NOINTERFACE.\n", debugstr_guid(riid));
554
555     return E_NOINTERFACE;
556 }
557
558 /*******************************************************************************
559  * IDirectDrawClassFactory::AddRef
560  *
561  * AddRef for the class factory
562  *
563  * RETURNS
564  *  The new refcount
565  *
566  *******************************************************************************/
567 static ULONG WINAPI ddraw_class_factory_AddRef(IClassFactory *iface)
568 {
569     struct ddraw_class_factory *factory = impl_from_IClassFactory(iface);
570     ULONG ref = InterlockedIncrement(&factory->ref);
571
572     TRACE("%p increasing refcount to %u.\n", factory, ref);
573
574     return ref;
575 }
576
577 /*******************************************************************************
578  * IDirectDrawClassFactory::Release
579  *
580  * Release for the class factory. If the refcount falls to 0, the object
581  * is destroyed
582  *
583  * RETURNS
584  *  The new refcount
585  *
586  *******************************************************************************/
587 static ULONG WINAPI ddraw_class_factory_Release(IClassFactory *iface)
588 {
589     struct ddraw_class_factory *factory = impl_from_IClassFactory(iface);
590     ULONG ref = InterlockedDecrement(&factory->ref);
591
592     TRACE("%p decreasing refcount to %u.\n", factory, ref);
593
594     if (!ref)
595         HeapFree(GetProcessHeap(), 0, factory);
596
597     return ref;
598 }
599
600
601 /*******************************************************************************
602  * IDirectDrawClassFactory::CreateInstance
603  *
604  * What is this? Seems to create DirectDraw objects...
605  *
606  * Params
607  *  The usual things???
608  *
609  * RETURNS
610  *  ???
611  *
612  *******************************************************************************/
613 static HRESULT WINAPI ddraw_class_factory_CreateInstance(IClassFactory *iface,
614         IUnknown *outer_unknown, REFIID riid, void **out)
615 {
616     struct ddraw_class_factory *factory = impl_from_IClassFactory(iface);
617
618     TRACE("iface %p, outer_unknown %p, riid %s, out %p.\n",
619             iface, outer_unknown, debugstr_guid(riid), out);
620
621     return factory->pfnCreateInstance(outer_unknown, riid, out);
622 }
623
624 /*******************************************************************************
625  * IDirectDrawClassFactory::LockServer
626  *
627  * What is this?
628  *
629  * Params
630  *  ???
631  *
632  * RETURNS
633  *  S_OK, because it's a stub
634  *
635  *******************************************************************************/
636 static HRESULT WINAPI ddraw_class_factory_LockServer(IClassFactory *iface, BOOL dolock)
637 {
638     FIXME("iface %p, dolock %#x stub!\n", iface, dolock);
639
640     return S_OK;
641 }
642
643 /*******************************************************************************
644  * The class factory VTable
645  *******************************************************************************/
646 static const IClassFactoryVtbl IClassFactory_Vtbl =
647 {
648     ddraw_class_factory_QueryInterface,
649     ddraw_class_factory_AddRef,
650     ddraw_class_factory_Release,
651     ddraw_class_factory_CreateInstance,
652     ddraw_class_factory_LockServer
653 };
654
655 /*******************************************************************************
656  * DllGetClassObject [DDRAW.@]
657  * Retrieves class object from a DLL object
658  *
659  * NOTES
660  *    Docs say returns STDAPI
661  *
662  * PARAMS
663  *    rclsid [I] CLSID for the class object
664  *    riid   [I] Reference to identifier of interface for class object
665  *    ppv    [O] Address of variable to receive interface pointer for riid
666  *
667  * RETURNS
668  *    Success: S_OK
669  *    Failure: CLASS_E_CLASSNOTAVAILABLE, E_OUTOFMEMORY, E_INVALIDARG,
670  *             E_UNEXPECTED
671  */
672 HRESULT WINAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID *ppv)
673 {
674     struct ddraw_class_factory *factory;
675     unsigned int i;
676
677     TRACE("rclsid %s, riid %s, object %p.\n",
678             debugstr_guid(rclsid), debugstr_guid(riid), ppv);
679
680     if (!IsEqualGUID(&IID_IClassFactory, riid)
681             && !IsEqualGUID(&IID_IUnknown, riid))
682         return E_NOINTERFACE;
683
684     for (i=0; i < sizeof(object_creation)/sizeof(object_creation[0]); i++)
685     {
686         if (IsEqualGUID(object_creation[i].clsid, rclsid))
687             break;
688     }
689
690     if (i == sizeof(object_creation)/sizeof(object_creation[0]))
691     {
692         FIXME("%s: no class found.\n", debugstr_guid(rclsid));
693         return CLASS_E_CLASSNOTAVAILABLE;
694     }
695
696     factory = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*factory));
697     if (factory == NULL) return E_OUTOFMEMORY;
698
699     factory->IClassFactory_iface.lpVtbl = &IClassFactory_Vtbl;
700     factory->ref = 1;
701
702     factory->pfnCreateInstance = object_creation[i].pfnCreateInstance;
703
704     *ppv = factory;
705     return S_OK;
706 }
707
708
709 /*******************************************************************************
710  * DllCanUnloadNow [DDRAW.@]  Determines whether the DLL is in use.
711  *
712  * RETURNS
713  *    Success: S_OK
714  *    Failure: S_FALSE
715  */
716 HRESULT WINAPI DllCanUnloadNow(void)
717 {
718     TRACE("\n");
719
720     return S_FALSE;
721 }
722
723
724 /***********************************************************************
725  *              DllRegisterServer (DDRAW.@)
726  */
727 HRESULT WINAPI DllRegisterServer(void)
728 {
729     return __wine_register_resources( instance );
730 }
731
732 /***********************************************************************
733  *              DllUnregisterServer (DDRAW.@)
734  */
735 HRESULT WINAPI DllUnregisterServer(void)
736 {
737     return __wine_unregister_resources( instance );
738 }
739
740 /*******************************************************************************
741  * DestroyCallback
742  *
743  * Callback function for the EnumSurfaces call in DllMain.
744  * Dumps some surface info and releases the surface
745  *
746  * Params:
747  *  surf: The enumerated surface
748  *  desc: it's description
749  *  context: Pointer to the ddraw impl
750  *
751  * Returns:
752  *  DDENUMRET_OK;
753  *******************************************************************************/
754 static HRESULT WINAPI
755 DestroyCallback(IDirectDrawSurface7 *surf,
756                 DDSURFACEDESC2 *desc,
757                 void *context)
758 {
759     struct ddraw_surface *Impl = impl_from_IDirectDrawSurface7(surf);
760     ULONG ref7, ref4, ref3, ref2, ref1, gamma_count, iface_count;
761
762     ref7 = IDirectDrawSurface7_Release(surf);  /* For the EnumSurfaces */
763     ref4 = Impl->ref4;
764     ref3 = Impl->ref3;
765     ref2 = Impl->ref2;
766     ref1 = Impl->ref1;
767     gamma_count = Impl->gamma_count;
768
769     WARN("Surface %p has an reference counts of 7: %u 4: %u 3: %u 2: %u 1: %u gamma: %u\n",
770             Impl, ref7, ref4, ref3, ref2, ref1, gamma_count);
771
772     /* Skip surfaces which are attached somewhere or which are
773      * part of a complex compound. They will get released when destroying
774      * the root
775      */
776     if( (!Impl->is_complex_root) || (Impl->first_attached != Impl) )
777         return DDENUMRET_OK;
778
779     /* Destroy the surface */
780     iface_count = ddraw_surface_release_iface(Impl);
781     while (iface_count) iface_count = ddraw_surface_release_iface(Impl);
782
783     return DDENUMRET_OK;
784 }
785
786 /***********************************************************************
787  * get_config_key
788  *
789  * Reads a config key from the registry. Taken from WineD3D
790  *
791  ***********************************************************************/
792 static inline DWORD get_config_key(HKEY defkey, HKEY appkey, const char* name, char* buffer, DWORD size)
793 {
794     if (0 != appkey && !RegQueryValueExA( appkey, name, 0, NULL, (LPBYTE) buffer, &size )) return 0;
795     if (0 != defkey && !RegQueryValueExA( defkey, name, 0, NULL, (LPBYTE) buffer, &size )) return 0;
796     return ERROR_FILE_NOT_FOUND;
797 }
798
799 /***********************************************************************
800  * DllMain (DDRAW.0)
801  *
802  * Could be used to register DirectDraw drivers, if we have more than
803  * one. Also used to destroy any objects left at unload if the
804  * app didn't release them properly(Gothic 2, Diablo 2, Moto racer, ...)
805  *
806  ***********************************************************************/
807 BOOL WINAPI
808 DllMain(HINSTANCE hInstDLL,
809         DWORD Reason,
810         LPVOID lpv)
811 {
812     TRACE("(%p,%x,%p)\n", hInstDLL, Reason, lpv);
813     if (Reason == DLL_PROCESS_ATTACH)
814     {
815         static HMODULE ddraw_self;
816         char buffer[MAX_PATH+10];
817         DWORD size = sizeof(buffer);
818         HKEY hkey = 0;
819         HKEY appkey = 0;
820         WNDCLASSA wc;
821         DWORD len;
822
823         /* Register the window class. This is used to create a hidden window
824          * for D3D rendering, if the application didn't pass one. It can also
825          * be used for creating a device window from SetCooperativeLevel(). */
826         wc.style = CS_HREDRAW | CS_VREDRAW;
827         wc.lpfnWndProc = DefWindowProcA;
828         wc.cbClsExtra = 0;
829         wc.cbWndExtra = 0;
830         wc.hInstance = hInstDLL;
831         wc.hIcon = 0;
832         wc.hCursor = 0;
833         wc.hbrBackground = GetStockObject(BLACK_BRUSH);
834         wc.lpszMenuName = NULL;
835         wc.lpszClassName = DDRAW_WINDOW_CLASS_NAME;
836         if (!RegisterClassA(&wc))
837         {
838             ERR("Failed to register ddraw window class, last error %#x.\n", GetLastError());
839             return FALSE;
840         }
841
842        /* @@ Wine registry key: HKCU\Software\Wine\Direct3D */
843        if ( RegOpenKeyA( HKEY_CURRENT_USER, "Software\\Wine\\Direct3D", &hkey ) ) hkey = 0;
844
845        len = GetModuleFileNameA( 0, buffer, MAX_PATH );
846        if (len && len < MAX_PATH)
847        {
848             HKEY tmpkey;
849             /* @@ Wine registry key: HKCU\Software\Wine\AppDefaults\app.exe\Direct3D */
850             if (!RegOpenKeyA( HKEY_CURRENT_USER, "Software\\Wine\\AppDefaults", &tmpkey ))
851             {
852                 char *p, *appname = buffer;
853                 if ((p = strrchr( appname, '/' ))) appname = p + 1;
854                 if ((p = strrchr( appname, '\\' ))) appname = p + 1;
855                 strcat( appname, "\\Direct3D" );
856                 TRACE("appname = [%s]\n", appname);
857                 if (RegOpenKeyA( tmpkey, appname, &appkey )) appkey = 0;
858                 RegCloseKey( tmpkey );
859             }
860        }
861
862        if ( 0 != hkey || 0 != appkey )
863        {
864             if ( !get_config_key( hkey, appkey, "DirectDrawRenderer", buffer, size) )
865             {
866                 if (!strcmp(buffer,"gdi"))
867                 {
868                     TRACE("Defaulting to GDI surfaces\n");
869                     DefaultSurfaceType = WINED3D_SURFACE_TYPE_GDI;
870                 }
871                 else if (!strcmp(buffer,"opengl"))
872                 {
873                     TRACE("Defaulting to opengl surfaces\n");
874                     DefaultSurfaceType = WINED3D_SURFACE_TYPE_OPENGL;
875                 }
876                 else
877                 {
878                     ERR("Unknown default surface type. Supported are:\n gdi, opengl\n");
879                 }
880             }
881         }
882
883         /* On Windows one can force the refresh rate that DirectDraw uses by
884          * setting an override value in dxdiag.  This is documented in KB315614
885          * (main article), KB230002, and KB217348.  By comparing registry dumps
886          * before and after setting the override, we see that the override value
887          * is stored in HKLM\Software\Microsoft\DirectDraw\ForceRefreshRate as a
888          * DWORD that represents the refresh rate to force.  We use this
889          * registry entry to modify the behavior of SetDisplayMode so that Wine
890          * users can override the refresh rate in a Windows-compatible way.
891          *
892          * dxdiag will not accept a refresh rate lower than 40 or higher than
893          * 120 so this value should be within that range.  It is, of course,
894          * possible for a user to set the registry entry value directly so that
895          * assumption might not hold.
896          *
897          * There is no current mechanism for setting this value through the Wine
898          * GUI.  It would be most appropriate to set this value through a dxdiag
899          * clone, but it may be sufficient to use winecfg.
900          *
901          * TODO: Create a mechanism for setting this value through the Wine GUI.
902          */
903         if ( !RegOpenKeyA( HKEY_LOCAL_MACHINE, "Software\\Microsoft\\DirectDraw", &hkey ) )
904         {
905             DWORD type, data;
906             size = sizeof(data);
907             if (!RegQueryValueExA( hkey, "ForceRefreshRate", NULL, &type, (LPBYTE)&data, &size ) && type == REG_DWORD)
908             {
909                 TRACE("ForceRefreshRate set; overriding refresh rate to %d Hz\n", data);
910                 force_refresh_rate = data;
911             }
912             RegCloseKey( hkey );
913         }
914
915         /* Prevent the ddraw module from being unloaded. When switching to
916          * exclusive mode, we replace the window proc of the ddraw window. If
917          * an application would unload ddraw from the WM_DESTROY handler for
918          * that window, it would return to unmapped memory and die. Apparently
919          * this is supposed to work on Windows. We should probably use
920          * GET_MODULE_HANDLE_EX_FLAG_PIN for this, but that's not currently
921          * implemented. */
922         if (!GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (const WCHAR *)&ddraw_self, &ddraw_self))
923             ERR("Failed to get own module handle.\n");
924
925         instance = hInstDLL;
926         DisableThreadLibraryCalls(hInstDLL);
927     }
928     else if (Reason == DLL_PROCESS_DETACH)
929     {
930         if(!list_empty(&global_ddraw_list))
931         {
932             struct list *entry, *entry2;
933             WARN("There are still existing DirectDraw interfaces. Wine bug or buggy application?\n");
934
935             /* We remove elements from this loop */
936             LIST_FOR_EACH_SAFE(entry, entry2, &global_ddraw_list)
937             {
938                 struct ddraw *ddraw = LIST_ENTRY(entry, struct ddraw, ddraw_list_entry);
939                 HRESULT hr;
940                 DDSURFACEDESC2 desc;
941                 int i;
942
943                 WARN("DDraw %p has a refcount of %d\n", ddraw, ddraw->ref7 + ddraw->ref4 + ddraw->ref3 + ddraw->ref2 + ddraw->ref1);
944
945                 /* Add references to each interface to avoid freeing them unexpectedly */
946                 IDirectDraw_AddRef(&ddraw->IDirectDraw_iface);
947                 IDirectDraw2_AddRef(&ddraw->IDirectDraw2_iface);
948                 IDirectDraw4_AddRef(&ddraw->IDirectDraw4_iface);
949                 IDirectDraw7_AddRef(&ddraw->IDirectDraw7_iface);
950
951                 /* Does a D3D device exist? Destroy it
952                     * TODO: Destroy all Vertex buffers, Lights, Materials
953                     * and execute buffers too
954                     */
955                 if(ddraw->d3ddevice)
956                 {
957                     WARN("DDraw %p has d3ddevice %p attached\n", ddraw, ddraw->d3ddevice);
958                     while(IDirect3DDevice7_Release(&ddraw->d3ddevice->IDirect3DDevice7_iface));
959                 }
960
961                 /* Destroy the swapchain after any 3D device. The 3D device
962                  * cleanup code needs a swapchain. Specifically, it tries to
963                  * set the current render target to the front buffer. */
964                 if (ddraw->wined3d_swapchain)
965                     ddraw_destroy_swapchain(ddraw);
966
967                 /* Try to release the objects
968                     * Do an EnumSurfaces to find any hanging surfaces
969                     */
970                 memset(&desc, 0, sizeof(desc));
971                 desc.dwSize = sizeof(desc);
972                 for(i = 0; i <= 1; i++)
973                 {
974                     hr = IDirectDraw7_EnumSurfaces(&ddraw->IDirectDraw7_iface, DDENUMSURFACES_ALL,
975                             &desc, ddraw, DestroyCallback);
976                     if(hr != D3D_OK)
977                         ERR("(%p) EnumSurfaces failed, prepare for trouble\n", ddraw);
978                 }
979
980                 if (!list_empty(&ddraw->surface_list))
981                     ERR("DDraw %p still has surfaces attached.\n", ddraw);
982
983                 /* Release all hanging references to destroy the objects. This
984                     * restores the screen mode too
985                     */
986                 while(IDirectDraw_Release(&ddraw->IDirectDraw_iface));
987                 while(IDirectDraw2_Release(&ddraw->IDirectDraw2_iface));
988                 while(IDirectDraw4_Release(&ddraw->IDirectDraw4_iface));
989                 while(IDirectDraw7_Release(&ddraw->IDirectDraw7_iface));
990             }
991         }
992
993         /* Unregister the window class. */
994         UnregisterClassA(DDRAW_WINDOW_CLASS_NAME, hInstDLL);
995     }
996
997     return TRUE;
998 }