ddraw: Destroy the swapchain in the DllMain() cleanup handler.
[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 WINED3DSURFTYPE DefaultSurfaceType = SURFACE_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     WINED3DDEVTYPE devicetype;
190     IDirectDrawImpl *This;
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         devicetype = WINED3DDEVTYPE_REF;
208     }
209     else if(guid == (GUID *) DDCREATE_HARDWAREONLY)
210     {
211         devicetype = WINED3DDEVTYPE_HAL;
212     }
213     else
214     {
215         devicetype = 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     This = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(IDirectDrawImpl));
224     if(!This)
225     {
226         ERR("Out of memory when creating DirectDraw\n");
227         return E_OUTOFMEMORY;
228     }
229
230     hr = ddraw_init(This, devicetype);
231     if (FAILED(hr))
232     {
233         WARN("Failed to initialize ddraw object, hr %#x.\n", hr);
234         HeapFree(GetProcessHeap(), 0, This);
235         return hr;
236     }
237
238     hr = IDirectDraw7_QueryInterface(&This->IDirectDraw7_iface, iid, DD);
239     IDirectDraw7_Release(&This->IDirectDraw7_iface);
240     if (SUCCEEDED(hr)) list_add_head(&global_ddraw_list, &This->ddraw_list_entry);
241     else WARN("Failed to query interface %s from ddraw object %p.\n", debugstr_guid(iid), This);
242
243     return hr;
244 }
245
246 /***********************************************************************
247  * DirectDrawCreate (DDRAW.@)
248  *
249  * Creates legacy DirectDraw Interfaces. Can't create IDirectDraw7
250  * interfaces in theory
251  *
252  * Arguments, return values: See DDRAW_Create
253  *
254  ***********************************************************************/
255 HRESULT WINAPI DECLSPEC_HOTPATCH
256 DirectDrawCreate(GUID *GUID,
257                  LPDIRECTDRAW *DD,
258                  IUnknown *UnkOuter)
259 {
260     HRESULT hr;
261
262     TRACE("driver_guid %s, ddraw %p, outer_unknown %p.\n",
263             debugstr_guid(GUID), DD, UnkOuter);
264
265     wined3d_mutex_lock();
266     hr = DDRAW_Create(GUID, (void **) DD, UnkOuter, &IID_IDirectDraw);
267     wined3d_mutex_unlock();
268
269     if (SUCCEEDED(hr))
270     {
271         hr = IDirectDraw_Initialize(*DD, GUID);
272         if (FAILED(hr))
273             IDirectDraw_Release(*DD);
274     }
275
276     return hr;
277 }
278
279 /***********************************************************************
280  * DirectDrawCreateEx (DDRAW.@)
281  *
282  * Only creates new IDirectDraw7 interfaces, supposed to fail if legacy
283  * interfaces are requested.
284  *
285  * Arguments, return values: See DDRAW_Create
286  *
287  ***********************************************************************/
288 HRESULT WINAPI DECLSPEC_HOTPATCH
289 DirectDrawCreateEx(GUID *guid,
290                    LPVOID *dd,
291                    REFIID iid,
292                    IUnknown *UnkOuter)
293 {
294     HRESULT hr;
295
296     TRACE("driver_guid %s, ddraw %p, interface_iid %s, outer_unknown %p.\n",
297             debugstr_guid(guid), dd, debugstr_guid(iid), UnkOuter);
298
299     if (!IsEqualGUID(iid, &IID_IDirectDraw7))
300         return DDERR_INVALIDPARAMS;
301
302     wined3d_mutex_lock();
303     hr = DDRAW_Create(guid, dd, UnkOuter, iid);
304     wined3d_mutex_unlock();
305
306     if (SUCCEEDED(hr))
307     {
308         IDirectDraw7 *ddraw7 = *(IDirectDraw7 **)dd;
309         hr = IDirectDraw7_Initialize(ddraw7, guid);
310         if (FAILED(hr))
311             IDirectDraw7_Release(ddraw7);
312     }
313
314     return hr;
315 }
316
317 /***********************************************************************
318  * DirectDrawEnumerateA (DDRAW.@)
319  *
320  * Enumerates legacy ddraw drivers, ascii version. We only have one
321  * driver, which relays to WineD3D. If we were sufficiently cool,
322  * we could offer various interfaces, which use a different default surface
323  * implementation, but I think it's better to offer this choice in
324  * winecfg, because some apps use the default driver, so we would need
325  * a winecfg option anyway, and there shouldn't be 2 ways to set one setting
326  *
327  * Arguments:
328  *  Callback: Callback function from the app
329  *  Context: Argument to the call back.
330  *
331  * Returns:
332  *  DD_OK on success
333  *  E_INVALIDARG if the Callback caused a page fault
334  *
335  *
336  ***********************************************************************/
337 HRESULT WINAPI DirectDrawEnumerateA(LPDDENUMCALLBACKA Callback, void *Context)
338 {
339     TRACE("callback %p, context %p.\n", Callback, Context);
340
341     TRACE(" Enumerating default DirectDraw HAL interface\n");
342     /* We only have one driver */
343     __TRY
344     {
345         static CHAR driver_desc[] = "DirectDraw HAL",
346         driver_name[] = "display";
347
348         Callback(NULL, driver_desc, driver_name, Context);
349     }
350     __EXCEPT_PAGE_FAULT
351     {
352         return DDERR_INVALIDPARAMS;
353     }
354     __ENDTRY
355
356     TRACE(" End of enumeration\n");
357     return DD_OK;
358 }
359
360 /***********************************************************************
361  * DirectDrawEnumerateExA (DDRAW.@)
362  *
363  * Enumerates DirectDraw7 drivers, ascii version. See
364  * the comments above DirectDrawEnumerateA for more details.
365  *
366  * The Flag member is not supported right now.
367  *
368  ***********************************************************************/
369 HRESULT WINAPI DirectDrawEnumerateExA(LPDDENUMCALLBACKEXA Callback, void *Context, DWORD Flags)
370 {
371     TRACE("callback %p, context %p, flags %#x.\n", Callback, Context, Flags);
372
373     if (Flags & ~(DDENUM_ATTACHEDSECONDARYDEVICES |
374                   DDENUM_DETACHEDSECONDARYDEVICES |
375                   DDENUM_NONDISPLAYDEVICES))
376         return DDERR_INVALIDPARAMS;
377
378     if (Flags)
379         FIXME("flags 0x%08x not handled\n", Flags);
380
381     TRACE("Enumerating default DirectDraw HAL interface\n");
382
383     /* We only have one driver by now */
384     __TRY
385     {
386         static CHAR driver_desc[] = "DirectDraw HAL",
387         driver_name[] = "display";
388
389         /* QuickTime expects the description "DirectDraw HAL" */
390         Callback(NULL, driver_desc, driver_name, Context, 0);
391     }
392     __EXCEPT_PAGE_FAULT
393     {
394         return DDERR_INVALIDPARAMS;
395     }
396     __ENDTRY;
397
398     TRACE("End of enumeration\n");
399     return DD_OK;
400 }
401
402 /***********************************************************************
403  * DirectDrawEnumerateW (DDRAW.@)
404  *
405  * Enumerates legacy drivers, unicode version.
406  * This function is not implemented on Windows.
407  *
408  ***********************************************************************/
409 HRESULT WINAPI DirectDrawEnumerateW(LPDDENUMCALLBACKW callback, void *context)
410 {
411     TRACE("callback %p, context %p.\n", callback, context);
412
413     if (!callback)
414         return DDERR_INVALIDPARAMS;
415     else
416         return DDERR_UNSUPPORTED;
417 }
418
419 /***********************************************************************
420  * DirectDrawEnumerateExW (DDRAW.@)
421  *
422  * Enumerates DirectDraw7 drivers, unicode version.
423  * This function is not implemented on Windows.
424  *
425  ***********************************************************************/
426 HRESULT WINAPI DirectDrawEnumerateExW(LPDDENUMCALLBACKEXW callback, void *context, DWORD flags)
427 {
428     TRACE("callback %p, context %p, flags %#x.\n", callback, context, flags);
429
430     return DDERR_UNSUPPORTED;
431 }
432
433 /***********************************************************************
434  * Classfactory implementation.
435  ***********************************************************************/
436
437 /***********************************************************************
438  * CF_CreateDirectDraw
439  *
440  * DDraw creation function for the class factory
441  *
442  * Params:
443  *  UnkOuter: Set to NULL
444  *  iid: ID of the wanted interface
445  *  obj: Address to pass the interface pointer back
446  *
447  * Returns
448  *  DD_OK / DDERR*, see DDRAW_Create
449  *
450  ***********************************************************************/
451 static HRESULT
452 CF_CreateDirectDraw(IUnknown* UnkOuter, REFIID iid,
453                     void **obj)
454 {
455     HRESULT hr;
456
457     TRACE("outer_unknown %p, riid %s, object %p.\n", UnkOuter, debugstr_guid(iid), obj);
458
459     wined3d_mutex_lock();
460     hr = DDRAW_Create(NULL, obj, UnkOuter, iid);
461     wined3d_mutex_unlock();
462
463     return hr;
464 }
465
466 /***********************************************************************
467  * CF_CreateDirectDraw
468  *
469  * Clipper creation function for the class factory
470  *
471  * Params:
472  *  UnkOuter: Set to NULL
473  *  iid: ID of the wanted interface
474  *  obj: Address to pass the interface pointer back
475  *
476  * Returns
477  *  DD_OK / DDERR*, see DDRAW_Create
478  *
479  ***********************************************************************/
480 static HRESULT
481 CF_CreateDirectDrawClipper(IUnknown* UnkOuter, REFIID riid,
482                               void **obj)
483 {
484     HRESULT hr;
485     IDirectDrawClipper *Clip;
486
487     TRACE("outer_unknown %p, riid %s, object %p.\n", UnkOuter, debugstr_guid(riid), obj);
488
489     wined3d_mutex_lock();
490     hr = DirectDrawCreateClipper(0, &Clip, UnkOuter);
491     if (hr != DD_OK)
492     {
493         wined3d_mutex_unlock();
494         return hr;
495     }
496
497     hr = IDirectDrawClipper_QueryInterface(Clip, riid, obj);
498     IDirectDrawClipper_Release(Clip);
499
500     wined3d_mutex_unlock();
501
502     return hr;
503 }
504
505 static const struct object_creation_info object_creation[] =
506 {
507     { &CLSID_DirectDraw,        CF_CreateDirectDraw },
508     { &CLSID_DirectDraw7,       CF_CreateDirectDraw },
509     { &CLSID_DirectDrawClipper, CF_CreateDirectDrawClipper }
510 };
511
512
513 /******************************************************************************
514  * DirectDraw ClassFactory implementation
515  ******************************************************************************/
516 typedef struct
517 {
518     IClassFactory IClassFactory_iface;
519
520     LONG ref;
521     HRESULT (*pfnCreateInstance)(IUnknown *pUnkOuter, REFIID iid, LPVOID *ppObj);
522 } IClassFactoryImpl;
523
524 static inline IClassFactoryImpl *impl_from_IClassFactory(IClassFactory *iface)
525 {
526     return CONTAINING_RECORD(iface, IClassFactoryImpl, IClassFactory_iface);
527 }
528
529 /*******************************************************************************
530  * IDirectDrawClassFactory::QueryInterface
531  *
532  * QueryInterface for the class factory
533  *
534  * PARAMS
535  *    riid   Reference to identifier of queried interface
536  *    ppv    Address to return the interface pointer at
537  *
538  * RETURNS
539  *    Success: S_OK
540  *    Failure: E_NOINTERFACE
541  *
542  *******************************************************************************/
543 static HRESULT WINAPI IDirectDrawClassFactoryImpl_QueryInterface(IClassFactory *iface, REFIID riid,
544         void **obj)
545 {
546     IClassFactoryImpl *This = impl_from_IClassFactory(iface);
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 = This;
555         return S_OK;
556     }
557
558     WARN("(%p)->(%s,%p),not found\n",This,debugstr_guid(riid),obj);
559     return E_NOINTERFACE;
560 }
561
562 /*******************************************************************************
563  * IDirectDrawClassFactory::AddRef
564  *
565  * AddRef for the class factory
566  *
567  * RETURNS
568  *  The new refcount
569  *
570  *******************************************************************************/
571 static ULONG WINAPI IDirectDrawClassFactoryImpl_AddRef(IClassFactory *iface)
572 {
573     IClassFactoryImpl *This = impl_from_IClassFactory(iface);
574     ULONG ref = InterlockedIncrement(&This->ref);
575
576     TRACE("%p increasing refcount to %u.\n", This, ref);
577
578     return ref;
579 }
580
581 /*******************************************************************************
582  * IDirectDrawClassFactory::Release
583  *
584  * Release for the class factory. If the refcount falls to 0, the object
585  * is destroyed
586  *
587  * RETURNS
588  *  The new refcount
589  *
590  *******************************************************************************/
591 static ULONG WINAPI IDirectDrawClassFactoryImpl_Release(IClassFactory *iface)
592 {
593     IClassFactoryImpl *This = impl_from_IClassFactory(iface);
594     ULONG ref = InterlockedDecrement(&This->ref);
595
596     TRACE("%p decreasing refcount to %u.\n", This, ref);
597
598     if (ref == 0)
599         HeapFree(GetProcessHeap(), 0, This);
600
601     return ref;
602 }
603
604
605 /*******************************************************************************
606  * IDirectDrawClassFactory::CreateInstance
607  *
608  * What is this? Seems to create DirectDraw objects...
609  *
610  * Params
611  *  The usual things???
612  *
613  * RETURNS
614  *  ???
615  *
616  *******************************************************************************/
617 static HRESULT WINAPI IDirectDrawClassFactoryImpl_CreateInstance(IClassFactory *iface,
618         IUnknown *UnkOuter, REFIID riid, void **obj)
619 {
620     IClassFactoryImpl *This = impl_from_IClassFactory(iface);
621
622     TRACE("iface %p, outer_unknown %p, riid %s, object %p.\n",
623             iface, UnkOuter, debugstr_guid(riid), obj);
624
625     return This->pfnCreateInstance(UnkOuter, riid, obj);
626 }
627
628 /*******************************************************************************
629  * IDirectDrawClassFactory::LockServer
630  *
631  * What is this?
632  *
633  * Params
634  *  ???
635  *
636  * RETURNS
637  *  S_OK, because it's a stub
638  *
639  *******************************************************************************/
640 static HRESULT WINAPI IDirectDrawClassFactoryImpl_LockServer(IClassFactory *iface, BOOL dolock)
641 {
642     FIXME("iface %p, dolock %#x stub!\n", iface, dolock);
643
644     return S_OK;
645 }
646
647 /*******************************************************************************
648  * The class factory VTable
649  *******************************************************************************/
650 static const IClassFactoryVtbl IClassFactory_Vtbl =
651 {
652     IDirectDrawClassFactoryImpl_QueryInterface,
653     IDirectDrawClassFactoryImpl_AddRef,
654     IDirectDrawClassFactoryImpl_Release,
655     IDirectDrawClassFactoryImpl_CreateInstance,
656     IDirectDrawClassFactoryImpl_LockServer
657 };
658
659 /*******************************************************************************
660  * DllGetClassObject [DDRAW.@]
661  * Retrieves class object from a DLL object
662  *
663  * NOTES
664  *    Docs say returns STDAPI
665  *
666  * PARAMS
667  *    rclsid [I] CLSID for the class object
668  *    riid   [I] Reference to identifier of interface for class object
669  *    ppv    [O] Address of variable to receive interface pointer for riid
670  *
671  * RETURNS
672  *    Success: S_OK
673  *    Failure: CLASS_E_CLASSNOTAVAILABLE, E_OUTOFMEMORY, E_INVALIDARG,
674  *             E_UNEXPECTED
675  */
676 HRESULT WINAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID *ppv)
677 {
678     unsigned int i;
679     IClassFactoryImpl *factory;
680
681     TRACE("rclsid %s, riid %s, object %p.\n",
682             debugstr_guid(rclsid), debugstr_guid(riid), ppv);
683
684     if (!IsEqualGUID(&IID_IClassFactory, riid)
685             && !IsEqualGUID(&IID_IUnknown, riid))
686         return E_NOINTERFACE;
687
688     for (i=0; i < sizeof(object_creation)/sizeof(object_creation[0]); i++)
689     {
690         if (IsEqualGUID(object_creation[i].clsid, rclsid))
691             break;
692     }
693
694     if (i == sizeof(object_creation)/sizeof(object_creation[0]))
695     {
696         FIXME("%s: no class found.\n", debugstr_guid(rclsid));
697         return CLASS_E_CLASSNOTAVAILABLE;
698     }
699
700     factory = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*factory));
701     if (factory == NULL) return E_OUTOFMEMORY;
702
703     factory->IClassFactory_iface.lpVtbl = &IClassFactory_Vtbl;
704     factory->ref = 1;
705
706     factory->pfnCreateInstance = object_creation[i].pfnCreateInstance;
707
708     *ppv = factory;
709     return S_OK;
710 }
711
712
713 /*******************************************************************************
714  * DllCanUnloadNow [DDRAW.@]  Determines whether the DLL is in use.
715  *
716  * RETURNS
717  *    Success: S_OK
718  *    Failure: S_FALSE
719  */
720 HRESULT WINAPI DllCanUnloadNow(void)
721 {
722     TRACE("\n");
723
724     return S_FALSE;
725 }
726
727
728 /***********************************************************************
729  *              DllRegisterServer (DDRAW.@)
730  */
731 HRESULT WINAPI DllRegisterServer(void)
732 {
733     return __wine_register_resources( instance );
734 }
735
736 /***********************************************************************
737  *              DllUnregisterServer (DDRAW.@)
738  */
739 HRESULT WINAPI DllUnregisterServer(void)
740 {
741     return __wine_unregister_resources( instance );
742 }
743
744 /*******************************************************************************
745  * DestroyCallback
746  *
747  * Callback function for the EnumSurfaces call in DllMain.
748  * Dumps some surface info and releases the surface
749  *
750  * Params:
751  *  surf: The enumerated surface
752  *  desc: it's description
753  *  context: Pointer to the ddraw impl
754  *
755  * Returns:
756  *  DDENUMRET_OK;
757  *******************************************************************************/
758 static HRESULT WINAPI
759 DestroyCallback(IDirectDrawSurface7 *surf,
760                 DDSURFACEDESC2 *desc,
761                 void *context)
762 {
763     IDirectDrawSurfaceImpl *Impl = impl_from_IDirectDrawSurface7(surf);
764     ULONG ref7, ref4, ref3, ref2, ref1, gamma_count, iface_count;
765
766     ref7 = IDirectDrawSurface7_Release(surf);  /* For the EnumSurfaces */
767     IDirectDrawSurface4_AddRef(&Impl->IDirectDrawSurface4_iface);
768     ref4 = IDirectDrawSurface4_Release(&Impl->IDirectDrawSurface4_iface);
769     IDirectDrawSurface3_AddRef(&Impl->IDirectDrawSurface3_iface);
770     ref3 = IDirectDrawSurface3_Release(&Impl->IDirectDrawSurface3_iface);
771     IDirectDrawSurface2_AddRef(&Impl->IDirectDrawSurface2_iface);
772     ref2 = IDirectDrawSurface2_Release(&Impl->IDirectDrawSurface2_iface);
773     IDirectDrawSurface_AddRef(&Impl->IDirectDrawSurface_iface);
774     ref1 = IDirectDrawSurface_Release(&Impl->IDirectDrawSurface_iface);
775     IDirectDrawGammaControl_AddRef(&Impl->IDirectDrawGammaControl_iface);
776     gamma_count = IDirectDrawGammaControl_Release(&Impl->IDirectDrawGammaControl_iface);
777     WARN("Surface %p has an reference counts of 7: %u 4: %u 3: %u 2: %u 1: %u gamma: %u\n",
778             Impl, ref7, ref4, ref3, ref2, ref1, gamma_count);
779
780     /* Skip surfaces which are attached somewhere or which are
781      * part of a complex compound. They will get released when destroying
782      * the root
783      */
784     if( (!Impl->is_complex_root) || (Impl->first_attached != Impl) )
785         return DDENUMRET_OK;
786
787     /* Destroy the surface */
788     iface_count = ddraw_surface_release_iface(Impl);
789     while (iface_count) iface_count = ddraw_surface_release_iface(Impl);
790
791     return DDENUMRET_OK;
792 }
793
794 /***********************************************************************
795  * get_config_key
796  *
797  * Reads a config key from the registry. Taken from WineD3D
798  *
799  ***********************************************************************/
800 static inline DWORD get_config_key(HKEY defkey, HKEY appkey, const char* name, char* buffer, DWORD size)
801 {
802     if (0 != appkey && !RegQueryValueExA( appkey, name, 0, NULL, (LPBYTE) buffer, &size )) return 0;
803     if (0 != defkey && !RegQueryValueExA( defkey, name, 0, NULL, (LPBYTE) buffer, &size )) return 0;
804     return ERROR_FILE_NOT_FOUND;
805 }
806
807 /***********************************************************************
808  * DllMain (DDRAW.0)
809  *
810  * Could be used to register DirectDraw drivers, if we have more than
811  * one. Also used to destroy any objects left at unload if the
812  * app didn't release them properly(Gothic 2, Diablo 2, Moto racer, ...)
813  *
814  ***********************************************************************/
815 BOOL WINAPI
816 DllMain(HINSTANCE hInstDLL,
817         DWORD Reason,
818         LPVOID lpv)
819 {
820     TRACE("(%p,%x,%p)\n", hInstDLL, Reason, lpv);
821     if (Reason == DLL_PROCESS_ATTACH)
822     {
823         char buffer[MAX_PATH+10];
824         DWORD size = sizeof(buffer);
825         HKEY hkey = 0;
826         HKEY appkey = 0;
827         WNDCLASSA wc;
828         DWORD len;
829
830         /* Register the window class. This is used to create a hidden window
831          * for D3D rendering, if the application didn't pass one. It can also
832          * be used for creating a device window from SetCooperativeLevel(). */
833         wc.style = CS_HREDRAW | CS_VREDRAW;
834         wc.lpfnWndProc = DefWindowProcA;
835         wc.cbClsExtra = 0;
836         wc.cbWndExtra = 0;
837         wc.hInstance = hInstDLL;
838         wc.hIcon = 0;
839         wc.hCursor = 0;
840         wc.hbrBackground = GetStockObject(BLACK_BRUSH);
841         wc.lpszMenuName = NULL;
842         wc.lpszClassName = DDRAW_WINDOW_CLASS_NAME;
843         if (!RegisterClassA(&wc))
844         {
845             ERR("Failed to register ddraw window class, last error %#x.\n", GetLastError());
846             return FALSE;
847         }
848
849        /* @@ Wine registry key: HKCU\Software\Wine\Direct3D */
850        if ( RegOpenKeyA( HKEY_CURRENT_USER, "Software\\Wine\\Direct3D", &hkey ) ) hkey = 0;
851
852        len = GetModuleFileNameA( 0, buffer, MAX_PATH );
853        if (len && len < MAX_PATH)
854        {
855             HKEY tmpkey;
856             /* @@ Wine registry key: HKCU\Software\Wine\AppDefaults\app.exe\Direct3D */
857             if (!RegOpenKeyA( HKEY_CURRENT_USER, "Software\\Wine\\AppDefaults", &tmpkey ))
858             {
859                 char *p, *appname = buffer;
860                 if ((p = strrchr( appname, '/' ))) appname = p + 1;
861                 if ((p = strrchr( appname, '\\' ))) appname = p + 1;
862                 strcat( appname, "\\Direct3D" );
863                 TRACE("appname = [%s]\n", appname);
864                 if (RegOpenKeyA( tmpkey, appname, &appkey )) appkey = 0;
865                 RegCloseKey( tmpkey );
866             }
867        }
868
869        if ( 0 != hkey || 0 != appkey )
870        {
871             if ( !get_config_key( hkey, appkey, "DirectDrawRenderer", buffer, size) )
872             {
873                 if (!strcmp(buffer,"gdi"))
874                 {
875                     TRACE("Defaulting to GDI surfaces\n");
876                     DefaultSurfaceType = SURFACE_GDI;
877                 }
878                 else if (!strcmp(buffer,"opengl"))
879                 {
880                     TRACE("Defaulting to opengl surfaces\n");
881                     DefaultSurfaceType = SURFACE_OPENGL;
882                 }
883                 else
884                 {
885                     ERR("Unknown default surface type. Supported are:\n gdi, opengl\n");
886                 }
887             }
888         }
889
890         /* On Windows one can force the refresh rate that DirectDraw uses by
891          * setting an override value in dxdiag.  This is documented in KB315614
892          * (main article), KB230002, and KB217348.  By comparing registry dumps
893          * before and after setting the override, we see that the override value
894          * is stored in HKLM\Software\Microsoft\DirectDraw\ForceRefreshRate as a
895          * DWORD that represents the refresh rate to force.  We use this
896          * registry entry to modify the behavior of SetDisplayMode so that Wine
897          * users can override the refresh rate in a Windows-compatible way.
898          *
899          * dxdiag will not accept a refresh rate lower than 40 or higher than
900          * 120 so this value should be within that range.  It is, of course,
901          * possible for a user to set the registry entry value directly so that
902          * assumption might not hold.
903          *
904          * There is no current mechanism for setting this value through the Wine
905          * GUI.  It would be most appropriate to set this value through a dxdiag
906          * clone, but it may be sufficient to use winecfg.
907          *
908          * TODO: Create a mechanism for setting this value through the Wine GUI.
909          */
910         if ( !RegOpenKeyA( HKEY_LOCAL_MACHINE, "Software\\Microsoft\\DirectDraw", &hkey ) )
911         {
912             DWORD type, data;
913             size = sizeof(data);
914             if (!RegQueryValueExA( hkey, "ForceRefreshRate", NULL, &type, (LPBYTE)&data, &size ) && type == REG_DWORD)
915             {
916                 TRACE("ForceRefreshRate set; overriding refresh rate to %d Hz\n", data);
917                 force_refresh_rate = data;
918             }
919             RegCloseKey( hkey );
920         }
921
922         instance = hInstDLL;
923         DisableThreadLibraryCalls(hInstDLL);
924     }
925     else if (Reason == DLL_PROCESS_DETACH)
926     {
927         if(!list_empty(&global_ddraw_list))
928         {
929             struct list *entry, *entry2;
930             WARN("There are still existing DirectDraw interfaces. Wine bug or buggy application?\n");
931
932             /* We remove elements from this loop */
933             LIST_FOR_EACH_SAFE(entry, entry2, &global_ddraw_list)
934             {
935                 HRESULT hr;
936                 DDSURFACEDESC2 desc;
937                 int i;
938                 IDirectDrawImpl *ddraw = LIST_ENTRY(entry, IDirectDrawImpl, ddraw_list_entry);
939
940                 WARN("DDraw %p has a refcount of %d\n", ddraw, ddraw->ref7 + ddraw->ref4 + ddraw->ref3 + ddraw->ref2 + ddraw->ref1);
941
942                 /* Add references to each interface to avoid freeing them unexpectedly */
943                 IDirectDraw_AddRef(&ddraw->IDirectDraw_iface);
944                 IDirectDraw2_AddRef(&ddraw->IDirectDraw2_iface);
945                 IDirectDraw4_AddRef(&ddraw->IDirectDraw4_iface);
946                 IDirectDraw7_AddRef(&ddraw->IDirectDraw7_iface);
947
948                 if (ddraw->wined3d_swapchain)
949                     ddraw_destroy_swapchain(ddraw);
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                 /* 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 }