kernel32: GetModuleHandleEx already clears the module handle on failure.
[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
515 /******************************************************************************
516  * DirectDraw ClassFactory implementation
517  ******************************************************************************/
518 typedef struct
519 {
520     IClassFactory IClassFactory_iface;
521
522     LONG ref;
523     HRESULT (*pfnCreateInstance)(IUnknown *pUnkOuter, REFIID iid, LPVOID *ppObj);
524 } IClassFactoryImpl;
525
526 static inline IClassFactoryImpl *impl_from_IClassFactory(IClassFactory *iface)
527 {
528     return CONTAINING_RECORD(iface, IClassFactoryImpl, IClassFactory_iface);
529 }
530
531 /*******************************************************************************
532  * IDirectDrawClassFactory::QueryInterface
533  *
534  * QueryInterface for the class factory
535  *
536  * PARAMS
537  *    riid   Reference to identifier of queried interface
538  *    ppv    Address to return the interface pointer at
539  *
540  * RETURNS
541  *    Success: S_OK
542  *    Failure: E_NOINTERFACE
543  *
544  *******************************************************************************/
545 static HRESULT WINAPI IDirectDrawClassFactoryImpl_QueryInterface(IClassFactory *iface, REFIID riid,
546         void **obj)
547 {
548     TRACE("iface %p, riid %s, object %p.\n", iface, debugstr_guid(riid), obj);
549
550     if (IsEqualGUID(riid, &IID_IUnknown)
551         || IsEqualGUID(riid, &IID_IClassFactory))
552     {
553         IClassFactory_AddRef(iface);
554         *obj = iface;
555         return S_OK;
556     }
557
558     WARN("%s not implemented, returning E_NOINTERFACE.\n", debugstr_guid(riid));
559
560     return E_NOINTERFACE;
561 }
562
563 /*******************************************************************************
564  * IDirectDrawClassFactory::AddRef
565  *
566  * AddRef for the class factory
567  *
568  * RETURNS
569  *  The new refcount
570  *
571  *******************************************************************************/
572 static ULONG WINAPI IDirectDrawClassFactoryImpl_AddRef(IClassFactory *iface)
573 {
574     IClassFactoryImpl *This = impl_from_IClassFactory(iface);
575     ULONG ref = InterlockedIncrement(&This->ref);
576
577     TRACE("%p increasing refcount to %u.\n", This, ref);
578
579     return ref;
580 }
581
582 /*******************************************************************************
583  * IDirectDrawClassFactory::Release
584  *
585  * Release for the class factory. If the refcount falls to 0, the object
586  * is destroyed
587  *
588  * RETURNS
589  *  The new refcount
590  *
591  *******************************************************************************/
592 static ULONG WINAPI IDirectDrawClassFactoryImpl_Release(IClassFactory *iface)
593 {
594     IClassFactoryImpl *This = impl_from_IClassFactory(iface);
595     ULONG ref = InterlockedDecrement(&This->ref);
596
597     TRACE("%p decreasing refcount to %u.\n", This, ref);
598
599     if (ref == 0)
600         HeapFree(GetProcessHeap(), 0, This);
601
602     return ref;
603 }
604
605
606 /*******************************************************************************
607  * IDirectDrawClassFactory::CreateInstance
608  *
609  * What is this? Seems to create DirectDraw objects...
610  *
611  * Params
612  *  The usual things???
613  *
614  * RETURNS
615  *  ???
616  *
617  *******************************************************************************/
618 static HRESULT WINAPI IDirectDrawClassFactoryImpl_CreateInstance(IClassFactory *iface,
619         IUnknown *UnkOuter, REFIID riid, void **obj)
620 {
621     IClassFactoryImpl *This = impl_from_IClassFactory(iface);
622
623     TRACE("iface %p, outer_unknown %p, riid %s, object %p.\n",
624             iface, UnkOuter, debugstr_guid(riid), obj);
625
626     return This->pfnCreateInstance(UnkOuter, riid, obj);
627 }
628
629 /*******************************************************************************
630  * IDirectDrawClassFactory::LockServer
631  *
632  * What is this?
633  *
634  * Params
635  *  ???
636  *
637  * RETURNS
638  *  S_OK, because it's a stub
639  *
640  *******************************************************************************/
641 static HRESULT WINAPI IDirectDrawClassFactoryImpl_LockServer(IClassFactory *iface, BOOL dolock)
642 {
643     FIXME("iface %p, dolock %#x stub!\n", iface, dolock);
644
645     return S_OK;
646 }
647
648 /*******************************************************************************
649  * The class factory VTable
650  *******************************************************************************/
651 static const IClassFactoryVtbl IClassFactory_Vtbl =
652 {
653     IDirectDrawClassFactoryImpl_QueryInterface,
654     IDirectDrawClassFactoryImpl_AddRef,
655     IDirectDrawClassFactoryImpl_Release,
656     IDirectDrawClassFactoryImpl_CreateInstance,
657     IDirectDrawClassFactoryImpl_LockServer
658 };
659
660 /*******************************************************************************
661  * DllGetClassObject [DDRAW.@]
662  * Retrieves class object from a DLL object
663  *
664  * NOTES
665  *    Docs say returns STDAPI
666  *
667  * PARAMS
668  *    rclsid [I] CLSID for the class object
669  *    riid   [I] Reference to identifier of interface for class object
670  *    ppv    [O] Address of variable to receive interface pointer for riid
671  *
672  * RETURNS
673  *    Success: S_OK
674  *    Failure: CLASS_E_CLASSNOTAVAILABLE, E_OUTOFMEMORY, E_INVALIDARG,
675  *             E_UNEXPECTED
676  */
677 HRESULT WINAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID *ppv)
678 {
679     unsigned int i;
680     IClassFactoryImpl *factory;
681
682     TRACE("rclsid %s, riid %s, object %p.\n",
683             debugstr_guid(rclsid), debugstr_guid(riid), ppv);
684
685     if (!IsEqualGUID(&IID_IClassFactory, riid)
686             && !IsEqualGUID(&IID_IUnknown, riid))
687         return E_NOINTERFACE;
688
689     for (i=0; i < sizeof(object_creation)/sizeof(object_creation[0]); i++)
690     {
691         if (IsEqualGUID(object_creation[i].clsid, rclsid))
692             break;
693     }
694
695     if (i == sizeof(object_creation)/sizeof(object_creation[0]))
696     {
697         FIXME("%s: no class found.\n", debugstr_guid(rclsid));
698         return CLASS_E_CLASSNOTAVAILABLE;
699     }
700
701     factory = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*factory));
702     if (factory == NULL) return E_OUTOFMEMORY;
703
704     factory->IClassFactory_iface.lpVtbl = &IClassFactory_Vtbl;
705     factory->ref = 1;
706
707     factory->pfnCreateInstance = object_creation[i].pfnCreateInstance;
708
709     *ppv = factory;
710     return S_OK;
711 }
712
713
714 /*******************************************************************************
715  * DllCanUnloadNow [DDRAW.@]  Determines whether the DLL is in use.
716  *
717  * RETURNS
718  *    Success: S_OK
719  *    Failure: S_FALSE
720  */
721 HRESULT WINAPI DllCanUnloadNow(void)
722 {
723     TRACE("\n");
724
725     return S_FALSE;
726 }
727
728
729 /***********************************************************************
730  *              DllRegisterServer (DDRAW.@)
731  */
732 HRESULT WINAPI DllRegisterServer(void)
733 {
734     return __wine_register_resources( instance );
735 }
736
737 /***********************************************************************
738  *              DllUnregisterServer (DDRAW.@)
739  */
740 HRESULT WINAPI DllUnregisterServer(void)
741 {
742     return __wine_unregister_resources( instance );
743 }
744
745 /*******************************************************************************
746  * DestroyCallback
747  *
748  * Callback function for the EnumSurfaces call in DllMain.
749  * Dumps some surface info and releases the surface
750  *
751  * Params:
752  *  surf: The enumerated surface
753  *  desc: it's description
754  *  context: Pointer to the ddraw impl
755  *
756  * Returns:
757  *  DDENUMRET_OK;
758  *******************************************************************************/
759 static HRESULT WINAPI
760 DestroyCallback(IDirectDrawSurface7 *surf,
761                 DDSURFACEDESC2 *desc,
762                 void *context)
763 {
764     struct ddraw_surface *Impl = impl_from_IDirectDrawSurface7(surf);
765     ULONG ref7, ref4, ref3, ref2, ref1, gamma_count, iface_count;
766
767     ref7 = IDirectDrawSurface7_Release(surf);  /* For the EnumSurfaces */
768     ref4 = Impl->ref4;
769     ref3 = Impl->ref3;
770     ref2 = Impl->ref2;
771     ref1 = Impl->ref1;
772     gamma_count = Impl->gamma_count;
773
774     WARN("Surface %p has an reference counts of 7: %u 4: %u 3: %u 2: %u 1: %u gamma: %u\n",
775             Impl, ref7, ref4, ref3, ref2, ref1, gamma_count);
776
777     /* Skip surfaces which are attached somewhere or which are
778      * part of a complex compound. They will get released when destroying
779      * the root
780      */
781     if( (!Impl->is_complex_root) || (Impl->first_attached != Impl) )
782         return DDENUMRET_OK;
783
784     /* Destroy the surface */
785     iface_count = ddraw_surface_release_iface(Impl);
786     while (iface_count) iface_count = ddraw_surface_release_iface(Impl);
787
788     return DDENUMRET_OK;
789 }
790
791 /***********************************************************************
792  * get_config_key
793  *
794  * Reads a config key from the registry. Taken from WineD3D
795  *
796  ***********************************************************************/
797 static inline DWORD get_config_key(HKEY defkey, HKEY appkey, const char* name, char* buffer, DWORD size)
798 {
799     if (0 != appkey && !RegQueryValueExA( appkey, name, 0, NULL, (LPBYTE) buffer, &size )) return 0;
800     if (0 != defkey && !RegQueryValueExA( defkey, name, 0, NULL, (LPBYTE) buffer, &size )) return 0;
801     return ERROR_FILE_NOT_FOUND;
802 }
803
804 /***********************************************************************
805  * DllMain (DDRAW.0)
806  *
807  * Could be used to register DirectDraw drivers, if we have more than
808  * one. Also used to destroy any objects left at unload if the
809  * app didn't release them properly(Gothic 2, Diablo 2, Moto racer, ...)
810  *
811  ***********************************************************************/
812 BOOL WINAPI
813 DllMain(HINSTANCE hInstDLL,
814         DWORD Reason,
815         LPVOID lpv)
816 {
817     TRACE("(%p,%x,%p)\n", hInstDLL, Reason, lpv);
818     if (Reason == DLL_PROCESS_ATTACH)
819     {
820         char buffer[MAX_PATH+10];
821         DWORD size = sizeof(buffer);
822         HKEY hkey = 0;
823         HKEY appkey = 0;
824         WNDCLASSA wc;
825         DWORD len;
826
827         /* Register the window class. This is used to create a hidden window
828          * for D3D rendering, if the application didn't pass one. It can also
829          * be used for creating a device window from SetCooperativeLevel(). */
830         wc.style = CS_HREDRAW | CS_VREDRAW;
831         wc.lpfnWndProc = DefWindowProcA;
832         wc.cbClsExtra = 0;
833         wc.cbWndExtra = 0;
834         wc.hInstance = hInstDLL;
835         wc.hIcon = 0;
836         wc.hCursor = 0;
837         wc.hbrBackground = GetStockObject(BLACK_BRUSH);
838         wc.lpszMenuName = NULL;
839         wc.lpszClassName = DDRAW_WINDOW_CLASS_NAME;
840         if (!RegisterClassA(&wc))
841         {
842             ERR("Failed to register ddraw window class, last error %#x.\n", GetLastError());
843             return FALSE;
844         }
845
846        /* @@ Wine registry key: HKCU\Software\Wine\Direct3D */
847        if ( RegOpenKeyA( HKEY_CURRENT_USER, "Software\\Wine\\Direct3D", &hkey ) ) hkey = 0;
848
849        len = GetModuleFileNameA( 0, buffer, MAX_PATH );
850        if (len && len < MAX_PATH)
851        {
852             HKEY tmpkey;
853             /* @@ Wine registry key: HKCU\Software\Wine\AppDefaults\app.exe\Direct3D */
854             if (!RegOpenKeyA( HKEY_CURRENT_USER, "Software\\Wine\\AppDefaults", &tmpkey ))
855             {
856                 char *p, *appname = buffer;
857                 if ((p = strrchr( appname, '/' ))) appname = p + 1;
858                 if ((p = strrchr( appname, '\\' ))) appname = p + 1;
859                 strcat( appname, "\\Direct3D" );
860                 TRACE("appname = [%s]\n", appname);
861                 if (RegOpenKeyA( tmpkey, appname, &appkey )) appkey = 0;
862                 RegCloseKey( tmpkey );
863             }
864        }
865
866        if ( 0 != hkey || 0 != appkey )
867        {
868             if ( !get_config_key( hkey, appkey, "DirectDrawRenderer", buffer, size) )
869             {
870                 if (!strcmp(buffer,"gdi"))
871                 {
872                     TRACE("Defaulting to GDI surfaces\n");
873                     DefaultSurfaceType = WINED3D_SURFACE_TYPE_GDI;
874                 }
875                 else if (!strcmp(buffer,"opengl"))
876                 {
877                     TRACE("Defaulting to opengl surfaces\n");
878                     DefaultSurfaceType = WINED3D_SURFACE_TYPE_OPENGL;
879                 }
880                 else
881                 {
882                     ERR("Unknown default surface type. Supported are:\n gdi, opengl\n");
883                 }
884             }
885         }
886
887         /* On Windows one can force the refresh rate that DirectDraw uses by
888          * setting an override value in dxdiag.  This is documented in KB315614
889          * (main article), KB230002, and KB217348.  By comparing registry dumps
890          * before and after setting the override, we see that the override value
891          * is stored in HKLM\Software\Microsoft\DirectDraw\ForceRefreshRate as a
892          * DWORD that represents the refresh rate to force.  We use this
893          * registry entry to modify the behavior of SetDisplayMode so that Wine
894          * users can override the refresh rate in a Windows-compatible way.
895          *
896          * dxdiag will not accept a refresh rate lower than 40 or higher than
897          * 120 so this value should be within that range.  It is, of course,
898          * possible for a user to set the registry entry value directly so that
899          * assumption might not hold.
900          *
901          * There is no current mechanism for setting this value through the Wine
902          * GUI.  It would be most appropriate to set this value through a dxdiag
903          * clone, but it may be sufficient to use winecfg.
904          *
905          * TODO: Create a mechanism for setting this value through the Wine GUI.
906          */
907         if ( !RegOpenKeyA( HKEY_LOCAL_MACHINE, "Software\\Microsoft\\DirectDraw", &hkey ) )
908         {
909             DWORD type, data;
910             size = sizeof(data);
911             if (!RegQueryValueExA( hkey, "ForceRefreshRate", NULL, &type, (LPBYTE)&data, &size ) && type == REG_DWORD)
912             {
913                 TRACE("ForceRefreshRate set; overriding refresh rate to %d Hz\n", data);
914                 force_refresh_rate = data;
915             }
916             RegCloseKey( hkey );
917         }
918
919         instance = hInstDLL;
920         DisableThreadLibraryCalls(hInstDLL);
921     }
922     else if (Reason == DLL_PROCESS_DETACH)
923     {
924         if(!list_empty(&global_ddraw_list))
925         {
926             struct list *entry, *entry2;
927             WARN("There are still existing DirectDraw interfaces. Wine bug or buggy application?\n");
928
929             /* We remove elements from this loop */
930             LIST_FOR_EACH_SAFE(entry, entry2, &global_ddraw_list)
931             {
932                 struct ddraw *ddraw = LIST_ENTRY(entry, struct ddraw, ddraw_list_entry);
933                 HRESULT hr;
934                 DDSURFACEDESC2 desc;
935                 int i;
936
937                 WARN("DDraw %p has a refcount of %d\n", ddraw, ddraw->ref7 + ddraw->ref4 + ddraw->ref3 + ddraw->ref2 + ddraw->ref1);
938
939                 /* Add references to each interface to avoid freeing them unexpectedly */
940                 IDirectDraw_AddRef(&ddraw->IDirectDraw_iface);
941                 IDirectDraw2_AddRef(&ddraw->IDirectDraw2_iface);
942                 IDirectDraw4_AddRef(&ddraw->IDirectDraw4_iface);
943                 IDirectDraw7_AddRef(&ddraw->IDirectDraw7_iface);
944
945                 /* Does a D3D device exist? Destroy it
946                     * TODO: Destroy all Vertex buffers, Lights, Materials
947                     * and execute buffers too
948                     */
949                 if(ddraw->d3ddevice)
950                 {
951                     WARN("DDraw %p has d3ddevice %p attached\n", ddraw, ddraw->d3ddevice);
952                     while(IDirect3DDevice7_Release(&ddraw->d3ddevice->IDirect3DDevice7_iface));
953                 }
954
955                 /* Destroy the swapchain after any 3D device. The 3D device
956                  * cleanup code needs a swapchain. Specifically, it tries to
957                  * set the current render target to the front buffer. */
958                 if (ddraw->wined3d_swapchain)
959                     ddraw_destroy_swapchain(ddraw);
960
961                 /* Try to release the objects
962                     * Do an EnumSurfaces to find any hanging surfaces
963                     */
964                 memset(&desc, 0, sizeof(desc));
965                 desc.dwSize = sizeof(desc);
966                 for(i = 0; i <= 1; i++)
967                 {
968                     hr = IDirectDraw7_EnumSurfaces(&ddraw->IDirectDraw7_iface, DDENUMSURFACES_ALL,
969                             &desc, ddraw, DestroyCallback);
970                     if(hr != D3D_OK)
971                         ERR("(%p) EnumSurfaces failed, prepare for trouble\n", ddraw);
972                 }
973
974                 if (!list_empty(&ddraw->surface_list))
975                     ERR("DDraw %p still has surfaces attached.\n", ddraw);
976
977                 /* Release all hanging references to destroy the objects. This
978                     * restores the screen mode too
979                     */
980                 while(IDirectDraw_Release(&ddraw->IDirectDraw_iface));
981                 while(IDirectDraw2_Release(&ddraw->IDirectDraw2_iface));
982                 while(IDirectDraw4_Release(&ddraw->IDirectDraw4_iface));
983                 while(IDirectDraw7_Release(&ddraw->IDirectDraw7_iface));
984             }
985         }
986
987         /* Unregister the window class. */
988         UnregisterClassA(DDRAW_WINDOW_CLASS_NAME, hInstDLL);
989     }
990
991     return TRUE;
992 }