Previous 15994 Revisions Next

r996 Tuesday 18th September, 2007 at 12:33:45 UTC by Nathan Woods
[Windows GUI] Sync with MAME32
[ROOT]makefile.mes
[src/mess/osd/windows]mess.rc
[src/mess/osd/windows/ui]cfgfile.c devview.c devview.h guimain.c layoutms.c mess32.rc mess32ui.c mess32ui.h ms32util.c ms32util.h optionsms.c optionsms.h propertiesms.c propertiesms.h res resourcems.h softwarepicker.c softwarepicker.h
[src/mess/osd/winui]cfgfile.c* devview.c* devview.h* guimain.c* layoutms.c* mess32.rc* mess32ui.c* mess32ui.h* ms32util.c* ms32util.h* optionsms.c* optionsms.h* propertiesms.c* propertiesms.h* res* resourcems.h* softwarepicker.c* softwarepicker.h*
[src/osd/windows/ui]audit32.c audit32.h bitmask.c bitmask.h columnedit.c columnedit.h datafile.c datafile.h datamap.c datamap.h dialogs.c dialogs.h dijoystick.c dijoystick.h directdraw.c directdraw.h directinput.c directinput.h directories.c directories.h dirwatch.c dirwatch.h dxdecode.c dxdecode.h file.h help.c help.h history.c history.h layout.c m32main.c m32opts.c m32opts.h m32util.c m32util.h mame32.h mame32.rc picker.c picker.h properties.c properties.h res resource.h resource.hm screenshot.c screenshot.h splitters.c splitters.h tabview.c tabview.h treeview.c treeview.h ui.mak verinfo.c win32ui.c win32ui.h
[src/osd/winui]audit32.c* audit32.h* bitmask.c* bitmask.h* columnedit.c* columnedit.h* datafile.c* datafile.h* datamap.c* datamap.h* dialogs.c* dialogs.h* dijoystick.c* dijoystick.h* directdraw.c* directdraw.h* directinput.c* directinput.h* directories.c* directories.h* dirwatch.c* dirwatch.h* dxdecode.c* dxdecode.h* file.h* help.c* help.h* history.c* history.h* layout.c* m32main.c* m32opts.c* m32opts.h* m32util.c* m32util.h* mame32.h* mame32.rc* mkhelp.c* picker.c* picker.h* properties.c* properties.h* resource.h* resource.hm* screenshot.c* screenshot.h* splitters.c* splitters.h* tabview.c* tabview.h* treeview.c* treeview.h* ui.mak* verinfo.c* win32ui.c* win32ui.h* winui.mak*
[src/osd/winui/res]horz.ico* vert.ico*

makefile.mes
r995r996
575575   $(LD) -shared $(LDFLAGS) $(LDFLAGSEMULATOR) $^ $(LIBS) -o $@
576576
577577# gui target
578$(EMULATORGUI):   $(EMULATORDLL) $(OBJ)/mess/osd/windows/ui/guimain.o $(GUIRESFILE)
578$(EMULATORGUI):   $(EMULATORDLL) $(OBJ)/mess/osd/winui/guimain.o $(GUIRESFILE)
579579   @echo Linking $@...
580   $(LD) $(LDFLAGS) $(LDFLAGSEMULATOR) -mwindows $(FULLNAME)lib.$(DLLLINK) $(OBJ)/mess/osd/windows/ui/guimain.o $(GUIRESFILE) $(LIBS) -o $@
580   $(LD) $(LDFLAGS) $(LDFLAGSEMULATOR) -mwindows $(FULLNAME)lib.$(DLLLINK) $(OBJ)/mess/osd/winui/guimain.o $(GUIRESFILE) $(LIBS) -o $@
581581
582582# cli target
583583$(EMULATORCLI):   $(EMULATORDLL) $(OBJ)/mess/osd/windows/climain.o
src/osd/windows/ui/m32util.c
r995r996
1/***************************************************************************
2
3  M.A.M.E.32   -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11 ***************************************************************************/
12
13/***************************************************************************
14
15  M32Util.c
16
17 ***************************************************************************/
18
19#define WIN32_LEAN_AND_MEAN
20#include <windows.h>
21#include <shellapi.h>
22#include <shlwapi.h>
23#include <assert.h>
24#include <stdio.h>
25#include <tchar.h>
26
27#include "unzip.h"
28#include "bitmask.h"
29#include "screenshot.h"
30#include "sound/samples.h"
31#include "MAME32.h"
32#include "M32Util.h"
33#include "winutf8.h"
34#include "strconv.h"
35
36
37/***************************************************************************
38   function prototypes
39 ***************************************************************************/
40
41/***************************************************************************
42   External variables
43 ***************************************************************************/
44
45/***************************************************************************
46   Internal structures
47 ***************************************************************************/
48static struct DriversInfo
49{
50   BOOL isClone;
51   BOOL isBroken;
52   BOOL isHarddisk;
53   BOOL hasOptionalBIOS;
54   BOOL isStereo;
55   BOOL isMultiMon;
56   BOOL isVector;
57   BOOL usesRoms;
58   BOOL usesSamples;
59   BOOL usesTrackball;
60   BOOL usesLightGun;
61   BOOL supportsSaveState;
62} *drivers_info = NULL;
63
64
65/***************************************************************************
66   External functions
67 ***************************************************************************/
68
69/*
70   ErrorMsg
71*/
72void __cdecl ErrorMsg(const char* fmt, ...)
73{
74   static FILE*   pFile = NULL;
75   DWORD         dwWritten;
76   char         buf[5000];
77   char         buf2[5000];
78   va_list       va;
79
80   va_start(va, fmt);
81
82   vsprintf(buf, fmt, va);
83
84   win_message_box_utf8(GetActiveWindow(), buf, MAME32NAME, MB_OK | MB_ICONERROR);
85
86   strcpy(buf2, MAME32NAME ": ");
87   strcat(buf2,buf);
88   strcat(buf2, "\n");
89
90   WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), buf2, strlen(buf2), &dwWritten, NULL);
91
92   if (pFile == NULL)
93      pFile = fopen("debug.txt", "wt");
94
95   if (pFile != NULL)
96   {
97      fprintf(pFile, "%s", buf2);
98      fflush(pFile);
99   }
100
101   va_end(va);
102}
103
104void __cdecl dprintf(const char* fmt, ...)
105{
106   char    buf[5000];
107   va_list va;
108
109   va_start(va, fmt);
110
111   _vsnprintf(buf,sizeof(buf),fmt,va);
112
113   win_output_debug_string_utf8(buf);
114
115   va_end(va);
116}
117
118UINT GetDepth(HWND hWnd)
119{
120   UINT   nBPP;
121   HDC    hDC;
122
123   hDC = GetDC(hWnd);
124   
125   nBPP = GetDeviceCaps(hDC, BITSPIXEL) * GetDeviceCaps(hDC, PLANES);
126
127   ReleaseDC(hWnd, hDC);
128
129   return nBPP;
130}
131
132/*
133 * Return TRUE if comctl32.dll is version 4.71 or greater
134 * otherwise return FALSE.
135 */
136LONG GetCommonControlVersion()
137{
138   HMODULE hModule = GetModuleHandle(TEXT("comctl32"));
139
140   if (hModule)
141   {
142      FARPROC lpfnICCE = GetProcAddress(hModule, "InitCommonControlsEx");
143
144      if (NULL != lpfnICCE)
145      {
146         FARPROC lpfnDLLI = GetProcAddress(hModule, "DllInstall");
147
148         if (NULL != lpfnDLLI)
149         {
150            /* comctl 4.71 or greater */
151
152            // see if we can find out exactly
153           
154            DLLGETVERSIONPROC pDllGetVersion;
155            pDllGetVersion = (DLLGETVERSIONPROC)GetProcAddress(hModule, "DllGetVersion");
156
157            /* Because some DLLs might not implement this function, you
158               must test for it explicitly. Depending on the particular
159               DLL, the lack of a DllGetVersion function can be a useful
160               indicator of the version. */
161
162            if(pDllGetVersion)
163            {
164               DLLVERSIONINFO dvi;
165               HRESULT hr;
166
167               ZeroMemory(&dvi, sizeof(dvi));
168               dvi.cbSize = sizeof(dvi);
169
170               hr = (*pDllGetVersion)(&dvi);
171
172               if (SUCCEEDED(hr))
173               {
174                  return PACKVERSION(dvi.dwMajorVersion, dvi.dwMinorVersion);
175               }
176            }
177            return PACKVERSION(4,71);
178         }
179         return PACKVERSION(4,7);
180      }
181      return PACKVERSION(4,0);
182   }
183   /* DLL not found */
184   return PACKVERSION(0,0);
185}
186
187void DisplayTextFile(HWND hWnd, const char *cName)
188{
189   HINSTANCE hErr;
190   LPCTSTR     msg = 0;
191   LPTSTR    tName;
192   
193   tName = tstring_from_utf8(cName);
194   if( !tName )
195      return;
196
197   hErr = ShellExecute(hWnd, NULL, tName, NULL, NULL, SW_SHOWNORMAL);
198   if ((FPTR)hErr > 32)
199   {
200      free(tName);
201      return;
202   }
203
204   switch((FPTR)hErr)
205   {
206   case 0:
207      msg = TEXT("The operating system is out of memory or resources.");
208      break;
209
210   case ERROR_FILE_NOT_FOUND:
211      msg = TEXT("The specified file was not found.");
212      break;
213
214   case SE_ERR_NOASSOC :
215      msg = TEXT("There is no application associated with the given filename extension.");
216      break;
217
218   case SE_ERR_OOM :
219      msg = TEXT("There was not enough memory to complete the operation.");
220      break;
221
222   case SE_ERR_PNF :
223      msg = TEXT("The specified path was not found.");
224      break;
225
226   case SE_ERR_SHARE :
227      msg = TEXT("A sharing violation occurred.");
228      break;
229
230   default:
231      msg = TEXT("Unknown error.");
232   }
233 
234   MessageBox(NULL, msg, tName, MB_OK);
235   
236   free(tName);
237}
238
239char* MyStrStrI(const char* pFirst, const char* pSrch)
240{
241   char* cp = (char*)pFirst;
242   char* s1;
243   char* s2;
244   
245   while (*cp)
246   {
247      s1 = cp;
248      s2 = (char*)pSrch;
249     
250      while (*s1 && *s2 && !mame_strnicmp(s1, s2, 1))
251         s1++, s2++;
252     
253      if (!*s2)
254         return cp;
255     
256      cp++;
257   }
258   return NULL;
259}
260
261char * ConvertToWindowsNewlines(const char *source)
262{
263   static char buf[40000];
264   char *dest;
265
266   dest = buf;
267   while (*source != 0)
268   {
269      if (*source == '\n')
270      {
271         *dest++ = '\r';
272         *dest++ = '\n';
273      }
274      else
275         *dest++ = *source;
276      source++;
277   }
278   *dest = 0;
279   return buf;
280}
281
282/* Lop off path and extention from a source file name
283 * This assumes their is a pathname passed to the function
284 * like src\drivers\blah.c
285 */
286const char * GetDriverFilename(int nIndex)
287{
288   static char tmp[40];
289   char *ptmp;
290
291   const char *s = drivers[nIndex]->source_file;
292
293   tmp[0] = '\0';
294
295   ptmp = strrchr(s, '\\');
296   if (ptmp == NULL)
297      ptmp = strrchr(s, '/');
298   if (ptmp == NULL)
299      return s;
300
301   ptmp++;
302   strcpy(tmp,ptmp);
303   return tmp;
304}
305
306static struct DriversInfo* GetDriversInfo(int driver_index)
307{
308   if (drivers_info == NULL)
309   {
310      int ndriver, i;
311      drivers_info = malloc(sizeof(struct DriversInfo) * driver_list_get_count(drivers));
312      for (ndriver = 0; ndriver < driver_list_get_count(drivers); ndriver++)
313      {
314         const game_driver *gamedrv = drivers[ndriver];
315         struct DriversInfo *gameinfo = &drivers_info[ndriver];
316         const rom_entry *region, *rom;
317         machine_config drv;
318         const input_port_entry *input_ports;
319         int speakernum, num_speakers;
320         gameinfo->isClone = (GetParentRomSetIndex(gamedrv) != -1);
321         gameinfo->isBroken = ((gamedrv->flags & GAME_NOT_WORKING) != 0);
322         gameinfo->supportsSaveState = ((gamedrv->flags & GAME_SUPPORTS_SAVE) != 0);
323         gameinfo->isHarddisk = FALSE;
324         for (region = rom_first_region(gamedrv); region; region = rom_next_region(region))
325         {
326            if (ROMREGION_ISDISKDATA(region))
327               gameinfo->isHarddisk = TRUE;
328         }
329         gameinfo->hasOptionalBIOS = FALSE;
330         if (gamedrv->rom != NULL)
331         {
332            for (rom = gamedrv->rom; !ROMENTRY_ISEND(rom); rom++)
333            {
334               if (ROMENTRY_ISSYSTEM_BIOS(rom))
335               {
336                  gameinfo->hasOptionalBIOS = TRUE;
337                  break;
338               }
339            }
340         }
341         expand_machine_driver(gamedrv->drv, &drv);
342
343         num_speakers = 0;
344         for (speakernum = 0; speakernum < MAX_SPEAKER; speakernum++)
345            if (drv.speaker[speakernum].tag != NULL)
346               num_speakers++;
347
348         gameinfo->isStereo = (num_speakers > 1);
349         //gameinfo->isMultiMon = ((drv.video_attributes & VIDEO_DUAL_MONITOR) != 0);
350         // Was removed from Core
351         gameinfo->isMultiMon = 0;
352         gameinfo->isVector = ((drv.video_attributes & VIDEO_TYPE_VECTOR) != 0);
353         gameinfo->usesRoms = FALSE;
354         for (region = rom_first_region(gamedrv); region; region = rom_next_region(region))
355            for (rom = rom_first_file(region); rom; rom = rom_next_file(rom))
356            {
357               gameinfo->usesRoms = TRUE;
358               break;
359            }
360         gameinfo->usesSamples = FALSE;
361         
362         if (HAS_SAMPLES || HAS_VLM5030)
363         {
364            for (i = 0; drv.sound[i].sound_type && i < MAX_SOUND; i++)
365            {
366               const char **samplenames = NULL;
367               
368#if (HAS_SAMPLES || HAS_VLM5030)
369               for( i = 0; drv.sound[i].sound_type && i < MAX_SOUND; i++ )
370               {
371#if (HAS_SAMPLES)
372                  if( drv.sound[i].sound_type == SOUND_SAMPLES )
373                     samplenames = ((struct Samplesinterface *)drv.sound[i].config)->samplenames;
374#endif
375               }
376#endif
377               if (samplenames != 0 && samplenames[0] != 0)
378               {
379                  gameinfo->usesSamples = TRUE;
380                  break;
381               }
382            }
383         }
384
385         gameinfo->usesTrackball = FALSE;
386         gameinfo->usesLightGun = FALSE;
387         if (gamedrv->ipt != NULL)
388         {
389            begin_resource_tracking();
390            input_ports = input_port_allocate(gamedrv->ipt, NULL);
391            while (1)
392            {
393               UINT32 type;
394               type = input_ports->type;
395               if (type == IPT_END)
396                  break;
397               if (type == IPT_DIAL || type == IPT_PADDLE ||
398                  type == IPT_TRACKBALL_X || type == IPT_TRACKBALL_Y ||
399                  type == IPT_AD_STICK_X || type == IPT_AD_STICK_Y)
400                  gameinfo->usesTrackball = TRUE;
401               if (type == IPT_LIGHTGUN_X || type == IPT_LIGHTGUN_Y)
402                  gameinfo->usesLightGun = TRUE;
403               input_ports++;
404            }
405            end_resource_tracking();
406         }
407      }
408   }
409   return &drivers_info[driver_index];
410}
411
412BOOL DriverIsClone(int driver_index)
413{
414    return GetDriversInfo(driver_index)->isClone;
415}
416
417BOOL DriverIsBroken(int driver_index)
418{
419   return GetDriversInfo(driver_index)->isBroken;
420}
421
422BOOL DriverIsHarddisk(int driver_index)
423{
424   return GetDriversInfo(driver_index)->isHarddisk;
425}
426
427BOOL DriverIsBios(int driver_index)
428{
429   BOOL bBios = FALSE;
430   if( !( (drivers[driver_index]->flags & GAME_IS_BIOS_ROOT ) == 0)   )
431      bBios = TRUE;
432   return bBios;
433}
434
435
436BOOL DriverHasOptionalBIOS(int driver_index)
437{
438   return GetDriversInfo(driver_index)->hasOptionalBIOS;
439}
440
441BOOL DriverIsStereo(int driver_index)
442{
443   return GetDriversInfo(driver_index)->isStereo;
444}
445BOOL DriverIsMultiMon(int driver_index)
446{
447   return GetDriversInfo(driver_index)->isMultiMon;
448}
449
450BOOL DriverIsVector(int driver_index)
451{
452   return GetDriversInfo(driver_index)->isVector;
453}
454
455BOOL DriverUsesRoms(int driver_index)
456{
457   return GetDriversInfo(driver_index)->usesRoms;
458}
459
460BOOL DriverUsesSamples(int driver_index)
461{
462   return GetDriversInfo(driver_index)->usesSamples;
463}
464
465BOOL DriverUsesTrackball(int driver_index)
466{
467   return GetDriversInfo(driver_index)->usesTrackball;
468}
469
470BOOL DriverUsesLightGun(int driver_index)
471{
472   return GetDriversInfo(driver_index)->usesLightGun;
473}
474
475BOOL DriverSupportsSaveState(int driver_index)
476{
477   return GetDriversInfo(driver_index)->supportsSaveState;
478}
479
480
481void FlushFileCaches(void)
482{
483   zip_file_cache_clear();
484}
485
486void FreeIfAllocated(char **s)
487{
488   if (*s)
489      free(*s);
490   *s = NULL;
491}
492
493BOOL StringIsSuffixedBy(const char *s, const char *suffix)
494{
495   return (strlen(s) > strlen(suffix)) && (strcmp(s + strlen(s) - strlen(suffix), suffix) == 0);
496}
497
498/***************************************************************************
499   Win32 wrappers
500 ***************************************************************************/
501
502BOOL SafeIsAppThemed(void)
503{
504   BOOL bResult = FALSE;
505   HMODULE hThemes;
506   BOOL (WINAPI *pfnIsAppThemed)(void);
507   
508   hThemes = LoadLibrary(TEXT("uxtheme.dll"));
509   if (hThemes != NULL)
510   {
511      pfnIsAppThemed = (BOOL (WINAPI *)(void)) GetProcAddress(hThemes, "IsAppThemed");
512      if (pfnIsAppThemed != NULL)
513         bResult = pfnIsAppThemed();
514      FreeLibrary(hThemes);
515   }
516   return bResult;
517
518}
519
520
521
522//============================================================
523//  win_extract_icon_utf8
524//============================================================
525
526HICON win_extract_icon_utf8(HINSTANCE inst, const char* exefilename, UINT iconindex)
527{
528   HICON icon = 0;
529   TCHAR* t_exefilename = tstring_from_utf8(exefilename);
530   if( !t_exefilename )
531      return icon;
532   
533   icon = ExtractIcon(inst, t_exefilename, iconindex);
534   
535   free(t_exefilename);
536   
537   return icon;
538}
539
540
541
542//============================================================
543//  win_tstring_strdup
544//============================================================
545
546TCHAR* win_tstring_strdup(LPCTSTR str)
547{
548   TCHAR *cpy = NULL;
549   if (str != NULL)
550   {
551      cpy = malloc((_tcslen(str) + 1) * sizeof(TCHAR));
552      if (cpy != NULL)
553         _tcscpy(cpy, str);
554   }
555   return cpy;
556}
557
558//============================================================
559//  win_create_file_utf8
560//============================================================
561
562HANDLE win_create_file_utf8(const char* filename, DWORD desiredmode, DWORD sharemode,
563                        LPSECURITY_ATTRIBUTES securityattributes, DWORD creationdisposition,
564                        DWORD flagsandattributes, HANDLE templatehandle)
565{
566   HANDLE result = 0;
567   TCHAR* t_filename = tstring_from_utf8(filename);
568   if( !t_filename )
569      return result;
570   
571   result = CreateFile(t_filename, desiredmode, sharemode, securityattributes, creationdisposition,
572                  flagsandattributes, templatehandle);
573
574   free(t_filename);
575                 
576   return result;
577}
578
579//============================================================
580//  win_get_current_directory_utf8
581//============================================================
582
583DWORD win_get_current_directory_utf8(DWORD bufferlength, char* buffer)
584{
585   DWORD result = 0;
586   TCHAR* t_buffer = NULL;
587   char* utf8_buffer = NULL;
588   
589   if( bufferlength > 0 ) {
590      t_buffer = malloc((bufferlength * sizeof(TCHAR)) + 1);
591      if( !t_buffer )
592         return result;
593   }
594   
595   result = GetCurrentDirectory(bufferlength, t_buffer);
596   
597   if( bufferlength > 0 ) {
598      utf8_buffer = utf8_from_tstring(t_buffer);
599      if( !utf8_buffer ) {
600         free(t_buffer);
601         return result;
602      }
603   }
604     
605   strncpy(buffer, utf8_buffer, bufferlength);
606   
607   if( utf8_buffer )
608      free(utf8_buffer);
609   
610   if( t_buffer )
611      free(t_buffer);
612   
613   return result;
614}
615
616//============================================================
617//  win_find_first_file_utf8
618//============================================================
619
620HANDLE win_find_first_file_utf8(const char* filename, LPWIN32_FIND_DATA findfiledata)
621{
622   HANDLE result = 0;
623   TCHAR* t_filename = tstring_from_utf8(filename);
624   if( !t_filename )
625      return result;
626   
627   result = FindFirstFile(t_filename, findfiledata);
628   
629   free(t_filename);
630   
631   return result;
632}
src/osd/windows/ui/treeview.h
r995r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11 ***************************************************************************/
12
13#ifndef TREEVIEW_H
14#define TREEVIEW_H
15
16/* corrections for commctrl.h */
17
18#if defined(__GNUC__)
19/* fix warning: cast does not match function type */
20#undef  TreeView_InsertItem
21#define TreeView_InsertItem(w,i) (HTREEITEM)(LRESULT)(int)SendMessage((w),TVM_INSERTITEM,0,(LPARAM)(LPTV_INSERTSTRUCT)(i))
22
23#undef  TreeView_SetImageList
24#define TreeView_SetImageList(w,h,i) (HIMAGELIST)(LRESULT)(int)SendMessage((w),TVM_SETIMAGELIST,i,(LPARAM)(HIMAGELIST)(h))
25
26#undef  TreeView_GetNextItem
27#define TreeView_GetNextItem(w,i,c) (HTREEITEM)(LRESULT)(int)SendMessage((w),TVM_GETNEXTITEM,c,(LPARAM)(HTREEITEM)(i))
28
29#undef TreeView_HitTest
30#define TreeView_HitTest(hwnd, lpht) \
31    (HTREEITEM)(LRESULT)(int)SNDMSG((hwnd), TVM_HITTEST, 0, (LPARAM)(LPTV_HITTESTINFO)(lpht))
32
33/* fix wrong return type */
34#undef  TreeView_Select
35#define TreeView_Select(w,i,c) (BOOL)(int)SendMessage((w),TVM_SELECTITEM,c,(LPARAM)(HTREEITEM)(i))
36
37#undef TreeView_EditLabel
38#define TreeView_EditLabel(w, i) \
39    SNDMSG(w,TVM_EDITLABEL,0,(LPARAM)(i))
40
41#endif /* defined(__GNUC__) */
42
43/***************************************************************************
44    Folder And Filter Definitions
45 ***************************************************************************/
46
47typedef struct
48{
49   const char *m_lpTitle; // Folder Title
50   const char *short_name;  // for saving in the .ini
51   UINT        m_nFolderId; // ID
52   UINT        m_nIconId; // if >= 0, resource id of icon (IDI_xxx), otherwise index in image list
53   DWORD       m_dwUnset; // Excluded filters
54   DWORD       m_dwSet;   // Implied filters
55   void        (*m_pfnCreateFolders)(int parent_index); // Constructor for special folders
56   BOOL        (*m_pfnQuery)(int nDriver);              // Query function
57   BOOL        m_bExpectedResult;                       // Expected query result
58} FOLDERDATA, *LPFOLDERDATA;
59
60typedef struct
61{
62   DWORD m_dwFilterType;            /* Filter value */
63   DWORD m_dwCtrlID;               /* Control ID that represents it */
64   BOOL (*m_pfnQuery)(int nDriver);   /* Query function */
65   BOOL m_bExpectedResult;            /* Expected query result */
66} FILTER_ITEM, *LPFILTER_ITEM;
67
68/***************************************************************************
69    Functions to build builtin folder lists
70 ***************************************************************************/
71
72void CreateManufacturerFolders(int parent_index);
73void CreateYearFolders(int parent_index);
74void CreateSourceFolders(int parent_index);
75void CreateCPUFolders(int parent_index);
76void CreateSoundFolders(int parent_index);
77void CreateOrientationFolders(int parent_index);
78void CreateDeficiencyFolders(int parent_index);
79void CreateDumpingFolders(int parent_index);
80
81/***************************************************************************/
82
83#define MAX_EXTRA_FOLDERS 256
84#define MAX_EXTRA_SUBFOLDERS 256
85
86/* TreeView structures */
87enum
88{
89   FOLDER_NONE = 0,
90   FOLDER_ALLGAMES,
91   FOLDER_AVAILABLE,
92#ifdef SHOW_UNAVAILABLE_FOLDER
93   FOLDER_UNAVAILABLE,
94#endif
95   FOLDER_MANUFACTURER,
96   FOLDER_YEAR,
97   FOLDER_SOURCE,
98   FOLDER_CPU,
99   FOLDER_SND,
100   FOLDER_ORIENTATION,
101   FOLDER_DEFICIENCY,
102   FOLDER_WORKING,
103   FOLDER_NONWORKING,
104   FOLDER_ORIGINAL,
105   FOLDER_CLONES,
106   FOLDER_RASTER,
107   FOLDER_VECTOR,
108   FOLDER_TRACKBALL,
109   FOLDER_LIGHTGUN,
110   FOLDER_STEREO,
111    //FOLDER_MULTIMON,
112   FOLDER_HARDDISK,
113   FOLDER_SAMPLES,
114   FOLDER_DUMPING,
115   FOLDER_SAVESTATE,
116   FOLDER_BIOS,
117#ifdef MESS
118   FOLDER_CONSOLE,
119   FOLDER_COMPUTER,
120   FOLDER_MODIFIED,
121   FOLDER_MOUSE,
122#endif
123   MAX_FOLDERS,
124};
125
126typedef enum
127{
128   F_CLONES        = 0x00000001,
129   F_NONWORKING    = 0x00000002,
130   F_UNAVAILABLE   = 0x00000004,
131   F_VECTOR        = 0x00000008,
132   F_RASTER        = 0x00000010,
133   F_ORIGINALS     = 0x00000020,
134   F_WORKING       = 0x00000040,
135   F_AVAILABLE     = 0x00000080,
136#ifdef MESS
137   F_COMPUTER      = 0x00000200,
138   F_CONSOLE       = 0x00000400,
139   F_MODIFIED      = 0x00000800,
140#endif
141   F_MASK          = 0x00000FFF,
142   F_CUSTOM        = 0x01000000  // for current .ini custom folders
143} FOLDERFLAG;
144
145typedef struct
146{
147    LPSTR m_lpTitle;              // String contains the folder name
148    LPTSTR m_lptTitle;            // String contains the folder name as TCHAR*
149    UINT        m_nFolderId;      // Index / Folder ID number
150    int         m_nParent;        // Parent folder index in treeFolders[]
151    int         m_nIconId;        // negative icon index into the ImageList, or IDI_xxx resource id
152    DWORD       m_dwFlags;        // Misc flags
153    LPBITS      m_lpGameBits;     // Game bits, represent game indices
154} TREEFOLDER, *LPTREEFOLDER;
155
156typedef struct
157{
158    char        m_szTitle[64];  // Folder Title
159    UINT        m_nFolderId;    // ID
160    int         m_nParent;      // Parent Folder index in treeFolders[]
161    DWORD       m_dwFlags;      // Flags - Customizable and Filters
162    int         m_nIconId;      // negative icon index into the ImageList, or IDI_xxx resource id
163    int         m_nSubIconId;   // negative icon index into the ImageList, or IDI_xxx resource id
164} EXFOLDERDATA, *LPEXFOLDERDATA;
165
166void FreeFolders(void);
167void ResetFilters(void);
168void InitTree(LPFOLDERDATA lpFolderData, LPFILTER_ITEM lpFilterList);
169void SetCurrentFolder(LPTREEFOLDER lpFolder);
170UINT GetCurrentFolderID(void);
171
172LPTREEFOLDER GetCurrentFolder(void);
173int GetNumFolders(void);
174LPTREEFOLDER GetFolder(UINT nFolder);
175LPTREEFOLDER GetFolderByID(UINT nID);
176LPTREEFOLDER GetFolderByName(int nParentId, const char *pszFolderName);
177
178void AddGame(LPTREEFOLDER lpFolder, UINT nGame);
179void RemoveGame(LPTREEFOLDER lpFolder, UINT nGame);
180int  FindGame(LPTREEFOLDER lpFolder, int nGame);
181
182void ResetWhichGamesInFolders(void);
183
184LPFOLDERDATA FindFilter(DWORD folderID);
185
186BOOL GameFiltered(int nGame, DWORD dwFlags);
187BOOL GetParentFound(int nGame);
188
189LPFILTER_ITEM GetFilterList(void);
190
191void SetTreeIconSize(HWND hWnd, BOOL bLarge);
192BOOL GetTreeIconSize(void);
193
194void GetFolders(TREEFOLDER ***folders,int *num_folders);
195BOOL TryRenameCustomFolder(LPTREEFOLDER lpFolder,const char *new_name);
196void AddToCustomFolder(LPTREEFOLDER lpFolder,int driver_index);
197void RemoveFromCustomFolder(LPTREEFOLDER lpFolder,int driver_index);
198
199HIMAGELIST GetTreeViewIconList(void);
200int GetTreeViewIconIndex(int icon_id);
201
202void ResetTreeViewFolders(void);
203void SelectTreeViewFolder(int folder_id);
204
205#endif /* TREEVIEW_H */
src/osd/windows/ui/win32ui.c
r995r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11 ***************************************************************************/
12
13 /***************************************************************************
14
15  win32ui.c
16
17  Win32 GUI code.
18
19  Created 8/12/97 by Christopher Kirmse (ckirmse@ricochet.net)
20  Additional code November 1997 by Jeff Miller (miller@aa.net)
21  More July 1998 by Mike Haaland (mhaaland@hypertech.com)
22  Added Spitters/Property Sheets/Removed Tabs/Added Tree Control in
23  Nov/Dec 1998 - Mike Haaland
24
25***************************************************************************/
26
27#ifdef _MSC_VER
28#ifndef NONAMELESSUNION
29#define NONAMELESSUNION
30#endif
31#endif
32
33#define WIN32_LEAN_AND_MEAN
34#include <windows.h>
35#include <windowsx.h>
36#include <shellapi.h>
37#include <stdio.h>
38#include <ctype.h>
39#include <io.h>
40#include <fcntl.h>
41#include <commctrl.h>
42#include <dlgs.h>
43#include <string.h>
44#include <sys/stat.h>
45#include <wingdi.h>
46#include <time.h>
47#include <tchar.h>
48
49#include <driver.h>
50#include <osdepend.h>
51#include <unzip.h>
52
53#include "resource.h"
54#include "resource.hm"
55
56#include "screenshot.h"
57#include "mame32.h"
58#include "M32Util.h"
59#include "file.h"
60#include "audit32.h"
61#include "Directories.h"
62#include "Properties.h"
63#include "ColumnEdit.h"
64#include "picker.h"
65#include "tabview.h"
66#include "bitmask.h"
67#include "TreeView.h"
68#include "Splitters.h"
69#include "DirWatch.h"
70#include "help.h"
71#include "history.h"
72#include "m32opts.h"
73#include "dialogs.h"
74#include "state.h"
75#include "winmain.h"
76#include "winutf8.h"
77#include "strconv.h"
78#include "input.h"
79#include "windows/window.h"
80
81#include "DirectDraw.h"
82#include "DirectInput.h"
83#include "DIJoystick.h"     /* For DIJoystick avalibility. */
84
85#ifdef MESS
86#include "ui/mess32ui.h"
87#include "messopts.h"
88#endif // MESS
89
90#ifdef _MSC_VER
91#define snprintf _snprintf
92#endif
93
94#ifndef LVS_EX_LABELTIP
95#define LVS_EX_LABELTIP         0x00004000 // listview unfolds partly hidden labels if it does not have infotip text
96#endif // LVS_EX_LABELTIP
97
98// fix warning: cast does not match function type
99#if defined(__GNUC__) && defined(ListView_CreateDragImage)
100#undef ListView_CreateDragImage
101#endif
102
103#ifndef ListView_CreateDragImage
104#define ListView_CreateDragImage(hwnd, i, lpptUpLeft) \
105    (HIMAGELIST)(LRESULT)(int)SendMessage((hwnd), LVM_CREATEDRAGIMAGE, (WPARAM)(int)(i), (LPARAM)(LPPOINT)(lpptUpLeft))
106#endif // ListView_CreateDragImage
107
108#ifndef TreeView_EditLabel
109#define TreeView_EditLabel(w, i) \
110    SNDMSG(w,TVM_EDITLABEL,0,(LPARAM)(i))
111#endif // TreeView_EditLabel
112
113#ifndef HDF_SORTUP
114#define HDF_SORTUP 0x400
115#endif // HDF_SORTUP
116
117#ifndef HDF_SORTDOWN
118#define HDF_SORTDOWN 0x200
119#endif // HDF_SORTDOWN
120
121#ifndef LVM_SETBKIMAGEA
122#define LVM_SETBKIMAGEA         (LVM_FIRST + 68)
123#endif // LVM_SETBKIMAGEA
124
125#ifndef LVM_SETBKIMAGEW
126#define LVM_SETBKIMAGEW         (LVM_FIRST + 138)
127#endif // LVM_SETBKIMAGEW
128
129#ifndef LVM_GETBKIMAGEA
130#define LVM_GETBKIMAGEA         (LVM_FIRST + 69)
131#endif // LVM_GETBKIMAGEA
132
133#ifndef LVM_GETBKIMAGEW
134#define LVM_GETBKIMAGEW         (LVM_FIRST + 139)
135#endif // LVM_GETBKIMAGEW
136
137#ifndef LVBKIMAGE
138
139typedef struct tagLVBKIMAGEA
140{
141   ULONG ulFlags;
142   HBITMAP hbm;
143   LPSTR pszImage;
144   UINT cchImageMax;
145   int xOffsetPercent;
146   int yOffsetPercent;
147} LVBKIMAGEA, *LPLVBKIMAGEA;
148
149typedef struct tagLVBKIMAGEW
150{
151   ULONG ulFlags;
152   HBITMAP hbm;
153   LPWSTR pszImage;
154   UINT cchImageMax;
155   int xOffsetPercent;
156   int yOffsetPercent;
157} LVBKIMAGEW, *LPLVBKIMAGEW;
158
159#ifdef UNICODE
160#define LVBKIMAGE               LVBKIMAGEW
161#define LPLVBKIMAGE             LPLVBKIMAGEW
162#define LVM_SETBKIMAGE          LVM_SETBKIMAGEW
163#define LVM_GETBKIMAGE          LVM_GETBKIMAGEW
164#else
165#define LVBKIMAGE               LVBKIMAGEA
166#define LPLVBKIMAGE             LPLVBKIMAGEA
167#define LVM_SETBKIMAGE          LVM_SETBKIMAGEA
168#define LVM_GETBKIMAGE          LVM_GETBKIMAGEA
169#endif
170#endif
171
172#ifndef LVBKIF_SOURCE_NONE
173#define LVBKIF_SOURCE_NONE      0x00000000
174#endif // LVBKIF_SOURCE_NONE
175
176#ifndef LVBKIF_SOURCE_HBITMAP
177#define LVBKIF_SOURCE_HBITMAP   0x00000001
178#endif
179
180#ifndef LVBKIF_SOURCE_URL
181#define LVBKIF_SOURCE_URL       0x00000002
182#endif // LVBKIF_SOURCE_URL
183
184#ifndef LVBKIF_SOURCE_MASK
185#define LVBKIF_SOURCE_MASK      0x00000003
186#endif // LVBKIF_SOURCE_MASK
187
188#ifndef LVBKIF_STYLE_NORMAL
189#define LVBKIF_STYLE_NORMAL     0x00000000
190#endif // LVBKIF_STYLE_NORMAL
191
192#ifndef LVBKIF_STYLE_TILE
193#define LVBKIF_STYLE_TILE       0x00000010
194#endif // LVBKIF_STYLE_TILE
195
196#ifndef LVBKIF_STYLE_MASK
197#define LVBKIF_STYLE_MASK       0x00000010
198#endif // LVBKIF_STYLE_MASK
199
200#ifndef ListView_SetBkImage
201#define ListView_SetBkImage(hwnd, plvbki) \
202    (BOOL)SNDMSG((hwnd), LVM_SETBKIMAGE, 0, (LPARAM)(plvbki))
203#endif // ListView_SetBkImage
204
205#ifndef ListView_GetBkImage
206#define ListView_GetBkImage(hwnd, plvbki) \
207    (BOOL)SNDMSG((hwnd), LVM_GETBKIMAGE, 0, (LPARAM)(plvbki))
208#endif // ListView_GetBkImage
209
210#define MM_PLAY_GAME (WM_APP + 15000)
211
212#define JOYGUI_MS 100
213
214#define JOYGUI_TIMER 1
215#define SCREENSHOT_TIMER 2
216#define GAMEWND_TIMER 3
217
218/* Max size of a sub-menu */
219#define DBU_MIN_WIDTH  292
220#define DBU_MIN_HEIGHT 190
221
222int MIN_WIDTH  = DBU_MIN_WIDTH;
223int MIN_HEIGHT = DBU_MIN_HEIGHT;
224
225/* Max number of bkground picture files */
226#define MAX_BGFILES 100
227
228#ifndef LVS_EX_LABELTIP
229#define LVS_EX_LABELTIP         0x00004000 // listview unfolds partly hidden labels if it does not have infotip text
230#endif
231
232#define NO_FOLDER -1
233#define STATESAVE_VERSION 1
234
235/***************************************************************************
236 externally defined global variables
237 ***************************************************************************/
238extern const ICONDATA g_iconData[];
239extern const TCHAR g_szPlayGameString[];
240extern const char g_szGameCountString[];
241
242typedef struct _play_options play_options;
243struct _play_options
244{
245   const char *record;         // OPTION_RECORD
246   const char *playback;      // OPTION_PLAYBACK
247   const char *state;         // OPTION_STATE
248   const char *wavwrite;      // OPTION_WAVWRITE
249   const char *mngwrite;      // OPTION_MNGWRITE
250};
251
252/***************************************************************************
253    function prototypes
254 ***************************************************************************/
255
256static BOOL             Win32UI_init(HINSTANCE hInstance, LPSTR lpCmdLine, int nCmdShow);
257static void             Win32UI_exit(void);
258
259static BOOL             PumpMessage(void);
260static BOOL             OnIdle(HWND hWnd);
261static void             OnSize(HWND hwnd, UINT state, int width, int height);
262static long WINAPI      MameWindowProc(HWND hwnd,UINT message,UINT wParam,LONG lParam);
263
264static void             SetView(int menu_id);
265static void             ResetListView(void);
266static void             UpdateGameList(BOOL bUpdateRomAudit, BOOL bUpdateSampleAudit);
267static void             DestroyIcons(void);
268static void             ReloadIcons(void);
269static void             PollGUIJoystick(void);
270static void             PressKey(HWND hwnd,UINT vk);
271static BOOL             MameCommand(HWND hwnd,int id, HWND hwndCtl, UINT codeNotify);
272static void             KeyboardKeyDown(int syskey, int vk_code, int special);
273static void             KeyboardKeyUp(int syskey, int vk_code, int special);
274static void             KeyboardStateClear(void);
275
276static void             UpdateStatusBar(void);
277static BOOL             PickerHitTest(HWND hWnd);
278static BOOL             TreeViewNotify(NMHDR *nm);
279
280static void             ResetBackground(char *szFile);
281static void            RandomSelectBackground(void);
282static void             LoadBackgroundBitmap(void);
283static void             PaintBackgroundImage(HWND hWnd, HRGN hRgn, int x, int y);
284
285static int CLIB_DECL    DriverDataCompareFunc(const void *arg1,const void *arg2);
286static int              GamePicker_Compare(HWND hwndPicker, int index1, int index2, int sort_subitem);
287
288static void             DisableSelection(void);
289static void             EnableSelection(int nGame);
290
291static HICON         GetSelectedPickItemIcon(void);
292static void             SetRandomPickItem(void);
293static void            PickColor(COLORREF *cDefault);
294
295static LPTREEFOLDER     GetSelectedFolder(void);
296static HICON         GetSelectedFolderIcon(void);
297
298static LRESULT CALLBACK HistoryWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
299static LRESULT CALLBACK PictureFrameWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
300static LRESULT CALLBACK PictureWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
301static INT_PTR CALLBACK LanguageDialogProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam);
302
303static BOOL             SelectLanguageFile(HWND hWnd, TCHAR* filename);
304static void             MamePlayRecordGame(void);
305static void             MamePlayBackGame(void);
306static void             MamePlayRecordWave(void);
307static void             MamePlayRecordMNG(void);
308static void            MameLoadState(void);
309static void             MamePlayGameWithOptions(int nGame, const play_options *playopts);
310static BOOL             GameCheck(void);
311static BOOL             FolderCheck(void);
312
313static void             ToggleScreenShot(void);
314static void             AdjustMetrics(void);
315static void             EnablePlayOptions(int nIndex, core_options *o);
316
317/* Icon routines */
318static DWORD            GetShellLargeIconSize(void);
319static DWORD            GetShellSmallIconSize(void);
320static void             CreateIcons(void);
321static int              GetIconForDriver(int nItem);
322static void             AddDriverIcon(int nItem,int default_icon_index);
323
324// Context Menu handlers
325static void             UpdateMenu(HMENU hMenu);
326static void             InitTreeContextMenu(HMENU hTreeMenu);
327static void             InitBodyContextMenu(HMENU hBodyContextMenu);
328static void             ToggleShowFolder(int folder);
329static BOOL             HandleTreeContextMenu( HWND hWnd, WPARAM wParam, LPARAM lParam);
330static BOOL             HandleScreenShotContextMenu( HWND hWnd, WPARAM wParam, LPARAM lParam);
331static void            GamePicker_OnHeaderContextMenu(POINT pt, int nColumn);
332static void            GamePicker_OnBodyContextMenu(POINT pt);
333
334static void             InitListView(void);
335/* Re/initialize the ListView header columns */
336static void             ResetColumnDisplay(BOOL first_time);
337
338static void             CopyToolTipText (LPTOOLTIPTEXT lpttt);
339
340static void             ProgressBarShow(void);
341static void             ProgressBarHide(void);
342static void             ResizeProgressBar(void);
343static void             ProgressBarStep(void);
344static void             ProgressBarStepParam(int iGameIndex, int nGameCount);
345
346static HWND             InitProgressBar(HWND hParent);
347static HWND             InitToolbar(HWND hParent);
348static HWND             InitStatusBar(HWND hParent);
349
350static LRESULT          Statusbar_MenuSelect (HWND hwnd, WPARAM wParam, LPARAM lParam);
351
352static void             UpdateHistory(void);
353
354
355void RemoveCurrentGameCustomFolder(void);
356void RemoveGameCustomFolder(int driver_index);
357
358void BeginListViewDrag(NM_LISTVIEW *pnmv);
359void MouseMoveListViewDrag(POINTS pt);
360void ButtonUpListViewDrag(POINTS p);
361
362void CalculateBestScreenShotRect(HWND hWnd, RECT *pRect, BOOL restrict_height);
363
364BOOL MouseHasBeenMoved(void);
365void SwitchFullScreenMode(void);
366
367/***************************************************************************
368    External variables
369 ***************************************************************************/
370
371/***************************************************************************
372    Internal structures
373 ***************************************************************************/
374
375/*
376 * These next two structs represent how the icon information
377 * is stored in an ICO file.
378 */
379typedef struct
380{
381   BYTE    bWidth;               /* Width of the image */
382   BYTE    bHeight;              /* Height of the image (times 2) */
383   BYTE    bColorCount;          /* Number of colors in image (0 if >=8bpp) */
384   BYTE    bReserved;            /* Reserved */
385   WORD    wPlanes;              /* Color Planes */
386   WORD    wBitCount;            /* Bits per pixel */
387   DWORD   dwBytesInRes;         /* how many bytes in this resource? */
388   DWORD   dwImageOffset;        /* where in the file is this image */
389} ICONDIRENTRY, *LPICONDIRENTRY;
390
391typedef struct
392{
393   UINT            Width, Height, Colors; /* Width, Height and bpp */
394   LPBYTE          lpBits;                /* ptr to DIB bits */
395   DWORD           dwNumBytes;            /* how many bytes? */
396   LPBITMAPINFO    lpbi;                  /* ptr to header */
397   LPBYTE          lpXOR;                 /* ptr to XOR image bits */
398   LPBYTE          lpAND;                 /* ptr to AND image bits */
399} ICONIMAGE, *LPICONIMAGE;
400
401/* Which edges of a control are anchored to the corresponding side of the parent window */
402#define RA_LEFT     0x01
403#define RA_RIGHT    0x02
404#define RA_TOP      0x04
405#define RA_BOTTOM   0x08
406#define RA_ALL      0x0F
407
408#define RA_END  0
409#define RA_ID   1
410#define RA_HWND 2
411
412typedef struct
413{
414   int         type;       /* Either RA_ID or RA_HWND, to indicate which member of u is used; or RA_END
415                        to signify last entry */
416   union                   /* Can identify a child window by control id or by handle */
417   {
418      int     id;         /* Window control id */
419      HWND    hwnd;       /* Window handle */
420   } u;
421   BOOL      setfont;   /* Do we set this item's font? */
422   int         action;     /* What to do when control is resized */
423   void        *subwindow; /* Points to a Resize structure for this subwindow; NULL if none */
424} ResizeItem;
425
426typedef struct
427{
428   RECT        rect;       /* Client rect of window; must be initialized before first resize */
429   ResizeItem* items;      /* Array of subitems to be resized */
430} Resize;
431
432static void ResizeWindow(HWND hParent, Resize *r);
433static void SetAllWindowsFont(HWND hParent, const Resize *r, HFONT hFont, BOOL bRedraw);
434
435/* List view Icon defines */
436#define LG_ICONMAP_WIDTH    GetSystemMetrics(SM_CXICON)
437#define LG_ICONMAP_HEIGHT   GetSystemMetrics(SM_CYICON)
438#define ICONMAP_WIDTH       GetSystemMetrics(SM_CXSMICON)
439#define ICONMAP_HEIGHT      GetSystemMetrics(SM_CYSMICON)
440
441typedef struct tagPOPUPSTRING
442{
443   HMENU hMenu;
444   UINT uiString;
445} POPUPSTRING;
446
447#define MAX_MENUS 3
448
449#define SPLITTER_WIDTH   4
450#define MIN_VIEW_WIDTH   10
451
452// Struct needed for Game Window Communication
453
454typedef struct
455{
456   LPPROCESS_INFORMATION ProcessInfo;
457   HWND hwndFound;
458} FINDWINDOWHANDLE;
459
460/***************************************************************************
461    Internal variables
462 ***************************************************************************/
463
464static HWND   hMain  = NULL;
465static HACCEL hAccel = NULL;
466
467static HWND hwndList  = NULL;
468static HWND hTreeView = NULL;
469static HWND hProgWnd  = NULL;
470static HWND hTabCtrl  = NULL;
471
472static HINSTANCE hInst = NULL;
473
474static HFONT hFont = NULL;     /* Font for list view */
475
476static int optionfolder_count = 0;
477
478/* global data--know where to send messages */
479static BOOL in_emulation;
480
481/* idle work at startup */
482static BOOL idle_work;
483
484/* object pool in use */
485static object_pool *mame32_pool;
486
487static int  game_index;
488static int  progBarStep;
489
490static BOOL bDoGameCheck = FALSE;
491
492/* Tree control variables */
493static BOOL bShowTree      = 1;
494static BOOL bShowToolBar   = 1;
495static BOOL bShowStatusBar = 1;
496static BOOL bShowTabCtrl   = 1;
497static BOOL bProgressShown = FALSE;
498static BOOL bListReady     = FALSE;
499
500#define   WM_MAME32_FILECHANGED   (WM_USER + 0)
501#define   WM_MAME32_AUDITGAME      (WM_USER + 1)
502
503static PDIRWATCHER s_pWatcher;
504
505/* use a joystick subsystem in the gui? */
506static struct OSDJoystick* g_pJoyGUI = NULL;
507
508/* store current keyboard state (in internal codes) here */
509static input_code keyboard_state[ 2048 ]; /* __code_max #defines the number of internal key_codes */
510
511/* table copied from windows/inputs.c */
512// table entry indices
513#define MAME_KEY      0
514#define DI_KEY         1
515#define VIRTUAL_KEY      2
516#define ASCII_KEY      3
517
518// master keyboard translation table
519static const int win_key_trans_table[][4] =
520{
521   // MAME key             dinput key          virtual key     ascii
522   { ITEM_ID_ESC,          DIK_ESCAPE,         VK_ESCAPE,       27 },
523   { ITEM_ID_1,          DIK_1,            '1',         '1' },
524   { ITEM_ID_2,          DIK_2,            '2',         '2' },
525   { ITEM_ID_3,          DIK_3,            '3',         '3' },
526   { ITEM_ID_4,          DIK_4,            '4',         '4' },
527   { ITEM_ID_5,          DIK_5,            '5',         '5' },
528   { ITEM_ID_6,          DIK_6,            '6',         '6' },
529   { ITEM_ID_7,          DIK_7,            '7',         '7' },
530   { ITEM_ID_8,          DIK_8,            '8',         '8' },
531   { ITEM_ID_9,          DIK_9,            '9',         '9' },
532   { ITEM_ID_0,          DIK_0,            '0',         '0' },
533   { ITEM_ID_BACKSPACE,   DIK_BACK,          VK_BACK,       8 },
534   { ITEM_ID_TAB,          DIK_TAB,          VK_TAB,       9 },
535   { ITEM_ID_Q,          DIK_Q,            'Q',         'Q' },
536   { ITEM_ID_W,          DIK_W,            'W',         'W' },
537   { ITEM_ID_E,          DIK_E,            'E',         'E' },
538   { ITEM_ID_R,          DIK_R,            'R',         'R' },
539   { ITEM_ID_T,          DIK_T,            'T',         'T' },
540   { ITEM_ID_Y,          DIK_Y,            'Y',         'Y' },
541   { ITEM_ID_U,          DIK_U,            'U',         'U' },
542   { ITEM_ID_I,          DIK_I,            'I',         'I' },
543   { ITEM_ID_O,          DIK_O,            'O',         'O' },
544   { ITEM_ID_P,          DIK_P,            'P',         'P' },
545   { ITEM_ID_OPENBRACE,   DIK_LBRACKET,       VK_OEM_4,      '[' },
546   { ITEM_ID_CLOSEBRACE,   DIK_RBRACKET,       VK_OEM_6,      ']' },
547   { ITEM_ID_ENTER,       DIK_RETURN,       VK_RETURN,       13 },
548   { ITEM_ID_LCONTROL,    DIK_LCONTROL,       VK_LCONTROL,    0 },
549   { ITEM_ID_A,          DIK_A,            'A',         'A' },
550   { ITEM_ID_S,          DIK_S,            'S',         'S' },
551   { ITEM_ID_D,          DIK_D,            'D',         'D' },
552   { ITEM_ID_F,          DIK_F,            'F',         'F' },
553   { ITEM_ID_G,          DIK_G,            'G',         'G' },
554   { ITEM_ID_H,          DIK_H,            'H',         'H' },
555   { ITEM_ID_J,          DIK_J,            'J',         'J' },
556   { ITEM_ID_K,          DIK_K,            'K',         'K' },
557   { ITEM_ID_L,          DIK_L,            'L',         'L' },
558   { ITEM_ID_COLON,       DIK_SEMICOLON,      VK_OEM_1,      ';' },
559   { ITEM_ID_QUOTE,       DIK_APOSTROPHE,      VK_OEM_7,      '\'' },
560   { ITEM_ID_TILDE,       DIK_GRAVE,          VK_OEM_3,      '`' },
561   { ITEM_ID_LSHIFT,       DIK_LSHIFT,       VK_LSHIFT,       0 },
562   { ITEM_ID_BACKSLASH,   DIK_BACKSLASH,       VK_OEM_5,      '\\' },
563   { ITEM_ID_Z,          DIK_Z,            'Z',         'Z' },
564   { ITEM_ID_X,          DIK_X,            'X',         'X' },
565   { ITEM_ID_C,          DIK_C,            'C',         'C' },
566   { ITEM_ID_V,          DIK_V,            'V',         'V' },
567   { ITEM_ID_B,          DIK_B,            'B',         'B' },
568   { ITEM_ID_N,          DIK_N,            'N',         'N' },
569   { ITEM_ID_M,          DIK_M,            'M',         'M' },
570   { ITEM_ID_SLASH,       DIK_SLASH,          VK_OEM_2,      '/' },
571   { ITEM_ID_RSHIFT,       DIK_RSHIFT,       VK_RSHIFT,       0 },
572   { ITEM_ID_ASTERISK,    DIK_MULTIPLY,       VK_MULTIPLY,   '*' },
573   { ITEM_ID_LALT,       DIK_LMENU,          VK_LMENU,       0 },
574   { ITEM_ID_SPACE,       DIK_SPACE,          VK_SPACE,      ' ' },
575   { ITEM_ID_CAPSLOCK,    DIK_CAPITAL,       VK_CAPITAL,    0 },
576   { ITEM_ID_F1,          DIK_F1,            VK_F1,          0 },
577   { ITEM_ID_F2,          DIK_F2,            VK_F2,          0 },
578   { ITEM_ID_F3,          DIK_F3,            VK_F3,          0 },
579   { ITEM_ID_F4,          DIK_F4,            VK_F4,          0 },
580   { ITEM_ID_F5,          DIK_F5,            VK_F5,          0 },
581   { ITEM_ID_F6,          DIK_F6,            VK_F6,          0 },
582   { ITEM_ID_F7,          DIK_F7,            VK_F7,          0 },
583   { ITEM_ID_F8,          DIK_F8,            VK_F8,          0 },
584   { ITEM_ID_F9,          DIK_F9,            VK_F9,          0 },
585   { ITEM_ID_F10,          DIK_F10,         VK_F10,       0 },
586   { ITEM_ID_NUMLOCK,       DIK_NUMLOCK,      VK_NUMLOCK,    0 },
587   { ITEM_ID_SCRLOCK,       DIK_SCROLL,         VK_SCROLL,       0 },
588   { ITEM_ID_7_PAD,       DIK_NUMPAD7,      VK_NUMPAD7,    0 },
589   { ITEM_ID_8_PAD,       DIK_NUMPAD8,      VK_NUMPAD8,    0 },
590   { ITEM_ID_9_PAD,       DIK_NUMPAD9,      VK_NUMPAD9,    0 },
591   { ITEM_ID_MINUS_PAD,   DIK_SUBTRACT,      VK_SUBTRACT,    0 },
592   { ITEM_ID_4_PAD,       DIK_NUMPAD4,      VK_NUMPAD4,    0 },
593   { ITEM_ID_5_PAD,       DIK_NUMPAD5,      VK_NUMPAD5,    0 },
594   { ITEM_ID_6_PAD,       DIK_NUMPAD6,      VK_NUMPAD6,    0 },
595   { ITEM_ID_PLUS_PAD,    DIK_ADD,         VK_ADD,       0 },
596   { ITEM_ID_1_PAD,       DIK_NUMPAD1,      VK_NUMPAD1,    0 },
597   { ITEM_ID_2_PAD,       DIK_NUMPAD2,      VK_NUMPAD2,    0 },
598   { ITEM_ID_3_PAD,       DIK_NUMPAD3,      VK_NUMPAD3,    0 },
599   { ITEM_ID_0_PAD,       DIK_NUMPAD0,      VK_NUMPAD0,    0 },
600   { ITEM_ID_DEL_PAD,       DIK_DECIMAL,      VK_DECIMAL,    0 },
601   { ITEM_ID_F11,          DIK_F11,         VK_F11,       0 },
602   { ITEM_ID_F12,          DIK_F12,         VK_F12,       0 },
603   { ITEM_ID_F13,          DIK_F13,         VK_F13,       0 },
604   { ITEM_ID_F14,          DIK_F14,         VK_F14,       0 },
605   { ITEM_ID_F15,          DIK_F15,         VK_F15,       0 },
606   { ITEM_ID_ENTER_PAD,   DIK_NUMPADENTER,   VK_RETURN,       0 },
607   { ITEM_ID_RCONTROL,    DIK_RCONTROL,      VK_RCONTROL,    0 },
608   { ITEM_ID_SLASH_PAD,   DIK_DIVIDE,         VK_DIVIDE,       0 },
609   { ITEM_ID_PRTSCR,       DIK_SYSRQ,          0,             0 },
610   { ITEM_ID_RALT,       DIK_RMENU,         VK_RMENU,       0 },
611   { ITEM_ID_HOME,       DIK_HOME,         VK_HOME,       0 },
612   { ITEM_ID_UP,          DIK_UP,            VK_UP,          0 },
613   { ITEM_ID_PGUP,       DIK_PRIOR,         VK_PRIOR,       0 },
614   { ITEM_ID_LEFT,       DIK_LEFT,         VK_LEFT,       0 },
615   { ITEM_ID_RIGHT,       DIK_RIGHT,         VK_RIGHT,       0 },
616   { ITEM_ID_END,          DIK_END,         VK_END,       0 },
617   { ITEM_ID_DOWN,       DIK_DOWN,         VK_DOWN,       0 },
618   { ITEM_ID_PGDN,       DIK_NEXT,         VK_NEXT,       0 },
619   { ITEM_ID_INSERT,       DIK_INSERT,         VK_INSERT,       0 },
620   { ITEM_ID_DEL,          DIK_DELETE,         VK_DELETE,       0 },
621   { ITEM_ID_LWIN,       DIK_LWIN,         VK_LWIN,       0 },
622   { ITEM_ID_RWIN,       DIK_RWIN,         VK_RWIN,       0 },
623   { ITEM_ID_MENU,       DIK_APPS,         VK_APPS,       0 },
624   { ITEM_ID_PAUSE,       DIK_PAUSE,         VK_PAUSE,      0 },
625   { ITEM_ID_CANCEL,      0,               VK_CANCEL,      0 },
626};
627
628
629
630typedef struct
631{
632   char      name[40];       // functionality name (optional)
633   input_seq   is;            // the input sequence (the keys pressed)
634   UINT      func_id;        // the identifier
635   input_seq* (*getiniptr)(void);// pointer to function to get the value from .ini file
636} GUISequence;
637
638static GUISequence GUISequenceControl[]=
639{
640   {"gui_key_up",                SEQ_DEF_0,    ID_UI_UP,           Get_ui_key_up },
641   {"gui_key_down",              SEQ_DEF_0,    ID_UI_DOWN,         Get_ui_key_down },
642   {"gui_key_left",              SEQ_DEF_0,    ID_UI_LEFT,         Get_ui_key_left },
643   {"gui_key_right",             SEQ_DEF_0,    ID_UI_RIGHT,        Get_ui_key_right },
644   {"gui_key_start",             SEQ_DEF_0,    ID_UI_START,        Get_ui_key_start },
645   {"gui_key_pgup",              SEQ_DEF_0,    ID_UI_PGUP,         Get_ui_key_pgup },
646   {"gui_key_pgdwn",             SEQ_DEF_0,    ID_UI_PGDOWN,       Get_ui_key_pgdwn },
647   {"gui_key_home",              SEQ_DEF_0,    ID_UI_HOME,         Get_ui_key_home },
648   {"gui_key_end",               SEQ_DEF_0,    ID_UI_END,          Get_ui_key_end },
649   {"gui_key_ss_change",         SEQ_DEF_0,    IDC_SSFRAME,        Get_ui_key_ss_change },
650   {"gui_key_history_up",        SEQ_DEF_0,    ID_UI_HISTORY_UP,   Get_ui_key_history_up },
651   {"gui_key_history_down",      SEQ_DEF_0,    ID_UI_HISTORY_DOWN, Get_ui_key_history_down },
652   
653   {"gui_key_context_filters",    SEQ_DEF_0,    ID_CONTEXT_FILTERS,       Get_ui_key_context_filters },
654   {"gui_key_select_random",      SEQ_DEF_0,    ID_CONTEXT_SELECT_RANDOM, Get_ui_key_select_random },
655   {"gui_key_game_audit",         SEQ_DEF_0,    ID_GAME_AUDIT,            Get_ui_key_game_audit },
656   {"gui_key_game_properties",    SEQ_DEF_0,    ID_GAME_PROPERTIES,       Get_ui_key_game_properties },
657   {"gui_key_help_contents",      SEQ_DEF_0,    ID_HELP_CONTENTS,         Get_ui_key_help_contents },
658   {"gui_key_update_gamelist",    SEQ_DEF_0,    ID_UPDATE_GAMELIST,       Get_ui_key_update_gamelist },
659   {"gui_key_view_folders",       SEQ_DEF_0,    ID_VIEW_FOLDERS,          Get_ui_key_view_folders },
660   {"gui_key_view_fullscreen",    SEQ_DEF_0,    ID_VIEW_FULLSCREEN,       Get_ui_key_view_fullscreen },
661   {"gui_key_view_pagetab",       SEQ_DEF_0,    ID_VIEW_PAGETAB,          Get_ui_key_view_pagetab },
662   {"gui_key_view_picture_area",  SEQ_DEF_0,    ID_VIEW_PICTURE_AREA,     Get_ui_key_view_picture_area },
663   {"gui_key_view_status",        SEQ_DEF_0,    ID_VIEW_STATUS,           Get_ui_key_view_status },
664   {"gui_key_view_toolbars",      SEQ_DEF_0,    ID_VIEW_TOOLBARS,         Get_ui_key_view_toolbars },
665
666   {"gui_key_view_tab_cabinet",     SEQ_DEF_0,  ID_VIEW_TAB_CABINET,       Get_ui_key_view_tab_cabinet },
667   {"gui_key_view_tab_cpanel",      SEQ_DEF_0,  ID_VIEW_TAB_CONTROL_PANEL, Get_ui_key_view_tab_cpanel },
668   {"gui_key_view_tab_flyer",       SEQ_DEF_0,  ID_VIEW_TAB_FLYER,         Get_ui_key_view_tab_flyer },
669   {"gui_key_view_tab_history",     SEQ_DEF_0,  ID_VIEW_TAB_HISTORY,       Get_ui_key_view_tab_history },
670   {"gui_key_view_tab_marquee",     SEQ_DEF_0,  ID_VIEW_TAB_MARQUEE,       Get_ui_key_view_tab_marquee },
671   {"gui_key_view_tab_screenshot",  SEQ_DEF_0,  ID_VIEW_TAB_SCREENSHOT,    Get_ui_key_view_tab_screenshot },
672   {"gui_key_view_tab_title",       SEQ_DEF_0,  ID_VIEW_TAB_TITLE,         Get_ui_key_view_tab_title },
673   {"gui_key_quit",                 SEQ_DEF_0,  ID_FILE_EXIT,              Get_ui_key_quit },
674};
675
676
677#define NUM_GUI_SEQUENCES (sizeof(GUISequenceControl) / sizeof(GUISequenceControl[0]))
678
679
680static UINT    lastColumnClick   = 0;
681static WNDPROC g_lpHistoryWndProc = NULL;
682static WNDPROC g_lpPictureFrameWndProc = NULL;
683static WNDPROC g_lpPictureWndProc = NULL;
684
685static POPUPSTRING popstr[MAX_MENUS + 1];
686
687/* Tool and Status bar variables */
688static HWND hStatusBar = 0;
689static HWND hToolBar   = 0;
690
691/* Column Order as Displayed */
692static BOOL oldControl = FALSE;
693static BOOL xpControl = FALSE;
694
695/* Used to recalculate the main window layout */
696static int  bottomMargin;
697static int  topMargin;
698static int  have_history = FALSE;
699
700static BOOL have_selection = FALSE;
701
702static HBITMAP hMissing_bitmap;
703
704/* Icon variables */
705static HIMAGELIST   hLarge = NULL;
706static HIMAGELIST   hSmall = NULL;
707static HIMAGELIST   hHeaderImages = NULL;
708static int          *icon_index = NULL; /* for custom per-game icons */
709
710static TBBUTTON tbb[] =
711{
712   {0, ID_VIEW_FOLDERS,    TBSTATE_ENABLED, TBSTYLE_CHECK,      {0, 0}, 0, 0},
713   {1, ID_VIEW_PICTURE_AREA,TBSTATE_ENABLED, TBSTYLE_CHECK,      {0, 0}, 0, 1},
714   {0, 0,                  TBSTATE_ENABLED, TBSTYLE_SEP,        {0, 0}, 0, 0},
715   {2, ID_VIEW_LARGE_ICON, TBSTATE_ENABLED, TBSTYLE_CHECKGROUP, {0, 0}, 0, 2},
716   {3, ID_VIEW_SMALL_ICON, TBSTATE_ENABLED, TBSTYLE_CHECKGROUP, {0, 0}, 0, 3},
717   {4, ID_VIEW_LIST_MENU,  TBSTATE_ENABLED, TBSTYLE_CHECKGROUP, {0, 0}, 0, 4},
718   {5, ID_VIEW_DETAIL,     TBSTATE_ENABLED, TBSTYLE_CHECKGROUP, {0, 0}, 0, 5},
719   {6, ID_VIEW_GROUPED, TBSTATE_ENABLED, TBSTYLE_CHECKGROUP, {0, 0}, 0, 6},
720   {0, 0,                  TBSTATE_ENABLED, TBSTYLE_SEP,        {0, 0}, 0, 0},
721   {7, ID_HELP_ABOUT,      TBSTATE_ENABLED, TBSTYLE_BUTTON,     {0, 0}, 0, 7},
722   {8, ID_HELP_CONTENTS,   TBSTATE_ENABLED, TBSTYLE_BUTTON,     {0, 0}, 0, 8}
723};
724
725#define NUM_TOOLBUTTONS (sizeof(tbb) / sizeof(tbb[0]))
726
727#define NUM_TOOLTIPS 8
728
729static const TCHAR szTbStrings[NUM_TOOLTIPS + 1][30] =
730{
731   TEXT("Toggle Folder List"),
732   TEXT("Toggle Screen Shot"),
733   TEXT("Large Icons"),
734   TEXT("Small Icons"),
735   TEXT("List"),
736   TEXT("Details"),
737   TEXT("Grouped"),
738   TEXT("About"),
739   TEXT("Help")
740};
741
742static int CommandToString[] =
743{
744   ID_VIEW_FOLDERS,
745   ID_VIEW_PICTURE_AREA,
746   ID_VIEW_LARGE_ICON,
747   ID_VIEW_SMALL_ICON,
748   ID_VIEW_LIST_MENU,
749   ID_VIEW_DETAIL,
750   ID_VIEW_GROUPED,
751   ID_HELP_ABOUT,
752   ID_HELP_CONTENTS,
753   -1
754};
755
756static const int s_nPickers[] =
757{
758   IDC_LIST
759#ifdef MESS
760   ,IDC_SWLIST
761#endif
762};
763
764/* How to resize main window */
765static ResizeItem main_resize_items[] =
766{
767   { RA_HWND, { 0 },            FALSE, RA_LEFT  | RA_RIGHT  | RA_TOP,     NULL },
768   { RA_HWND, { 0 },            FALSE, RA_LEFT  | RA_RIGHT  | RA_BOTTOM,  NULL },
769   { RA_ID,   { IDC_DIVIDER },  FALSE, RA_LEFT  | RA_RIGHT  | RA_TOP,     NULL },
770   { RA_ID,   { IDC_TREE },     TRUE,   RA_LEFT  | RA_BOTTOM | RA_TOP,     NULL },
771   { RA_ID,   { IDC_LIST },     TRUE,   RA_ALL,                            NULL },
772   { RA_ID,   { IDC_SPLITTER }, FALSE,   RA_LEFT  | RA_BOTTOM | RA_TOP,     NULL },
773   { RA_ID,   { IDC_SPLITTER2 },FALSE,   RA_RIGHT | RA_BOTTOM | RA_TOP,     NULL },
774   { RA_ID,   { IDC_SSFRAME },  FALSE,   RA_RIGHT | RA_BOTTOM | RA_TOP,     NULL },
775   { RA_ID,   { IDC_SSPICTURE },FALSE,   RA_RIGHT | RA_BOTTOM | RA_TOP,     NULL },
776   { RA_ID,   { IDC_HISTORY },  TRUE,   RA_RIGHT | RA_BOTTOM | RA_TOP,     NULL },
777   { RA_ID,   { IDC_SSTAB },    FALSE,   RA_RIGHT | RA_TOP,                 NULL },
778#ifdef MESS
779   { RA_ID,   { IDC_SWLIST },    TRUE,   RA_RIGHT | RA_BOTTOM | RA_TOP,     NULL },
780   { RA_ID,   { IDC_SPLITTER3 },FALSE,   RA_RIGHT | RA_BOTTOM | RA_TOP,     NULL },
781#endif /* MESS */
782   { RA_END,  { 0 },            FALSE, 0,                                 NULL }
783};
784
785static Resize main_resize = { {0, 0, 0, 0}, main_resize_items };
786
787/* last directory for common file dialogs */
788TCHAR last_directory[MAX_PATH];
789
790/* system-wide window message sent out with an ATOM of the current game name
791   each time it changes */
792static UINT g_mame32_message = 0;
793static BOOL g_bDoBroadcast   = FALSE;
794
795static BOOL use_gui_romloading = FALSE;
796
797static BOOL g_listview_dragging = FALSE;
798HIMAGELIST himl_drag;
799int game_dragged; /* which game started the drag */
800HTREEITEM prev_drag_drop_target; /* which tree view item we're currently highlighting */
801
802static BOOL g_in_treeview_edit = FALSE;
803
804typedef struct
805{
806    const char *name;
807    int index;
808} driver_data_type;
809static driver_data_type *sorted_drivers;
810
811/***************************************************************************
812    Global variables
813 ***************************************************************************/
814
815/* Background Image handles also accessed from TreeView.c */
816static HPALETTE         hPALbg   = 0;
817static HBITMAP          hBackground  = 0;
818static MYBITMAPINFO     bmDesc;
819
820/* List view Column text */
821LPCTSTR column_names[COLUMN_MAX] =
822{
823#ifdef MESS
824   TEXT("System"),
825   TEXT("Bios"),
826#else
827   TEXT("Game"),
828   TEXT("ROMs"),
829#endif
830   TEXT("Samples"),
831   TEXT("Directory"),
832   TEXT("Type"),
833   TEXT("Trackball"),
834   TEXT("Played"),
835   TEXT("Manufacturer"),
836   TEXT("Year"),
837   TEXT("Clone Of"),
838   TEXT("Source"),
839   TEXT("Play Time")
840};
841
842/***************************************************************************
843    Message Macros
844 ***************************************************************************/
845
846#ifndef StatusBar_GetItemRect
847#define StatusBar_GetItemRect(hWnd, iPart, lpRect) \
848    SendMessage(hWnd, SB_GETRECT, (WPARAM) iPart, (LPARAM) (LPRECT) lpRect)
849#endif
850
851#ifndef ToolBar_CheckButton
852#define ToolBar_CheckButton(hWnd, idButton, fCheck) \
853    SendMessage(hWnd, TB_CHECKBUTTON, (WPARAM)idButton, (LPARAM)MAKELONG(fCheck, 0))
854#endif
855
856/***************************************************************************
857    External functions
858 ***************************************************************************/
859
860static void CopyOptions(core_options *pDestOpts, core_options *pSourceOpts)
861{
862   options_enumerator *enumerator;
863   const char *option_name;
864   const char *option_value;
865
866   enumerator = options_enumerator_begin(pSourceOpts);
867   if (enumerator != NULL)
868   {
869      while((option_name = options_enumerator_next(enumerator)) != NULL)
870      {
871         option_value = options_get_string(pSourceOpts, option_name);
872         if (option_value != NULL)
873         {
874            dprintf("CopyOptions(): Copying %s = \"%s\"\n", option_name, option_value);
875            options_set_string(pDestOpts, option_name, option_value, OPTION_PRIORITY_CMDLINE);
876         }
877      }
878      options_enumerator_free(enumerator);
879   }
880}
881
882
883
884static BOOL WaitWithMessageLoop(HANDLE hEvent)
885{
886   DWORD dwRet;
887   MSG   msg;
888
889   while (1)
890   {
891      dwRet = MsgWaitForMultipleObjects(1, &hEvent, FALSE, INFINITE, QS_ALLINPUT);
892
893      if (dwRet == WAIT_OBJECT_0)
894         return TRUE;
895
896      if (dwRet != WAIT_OBJECT_0 + 1)
897         break;
898
899      while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
900      {
901         TranslateMessage(&msg);
902         DispatchMessage(&msg);
903         if (WaitForSingleObject(hEvent, 0) == WAIT_OBJECT_0)
904            return TRUE;
905      }
906   }
907   return FALSE;
908}
909
910static DWORD RunMAME(int nGameIndex, const play_options *playopts)
911{
912   DWORD dwExitCode = 0;
913   core_options *pOpts;
914   core_options *opts;
915   LPTREEFOLDER folder;
916   int i;
917
918   // set up MAME options
919   opts = mame_options_init(mame_win_options);
920
921   // retrieve the options we're going to pass
922   folder = GetFolderByName(FOLDER_SOURCE, GetDriverFilename(nGameIndex));
923   if (folder)
924      pOpts = GetGameOptions(nGameIndex, folder->m_nFolderId);
925   else
926      pOpts = GetGameOptions(nGameIndex, NO_FOLDER);
927
928#ifdef MESS
929   // add MESS specific device options
930   mess_add_device_options(opts, drivers[nGameIndex]);
931#endif // MESS
932
933   // load MAME options
934   CopyOptions(opts, Mame32Global());
935   CopyOptions(opts, pOpts);
936
937   // load specified play options
938   if (playopts != NULL)
939   {
940      if (playopts->record != NULL)
941         options_set_string(opts, OPTION_RECORD, playopts->record, OPTION_PRIORITY_CMDLINE);
942      if (playopts->playback != NULL)
943         options_set_string(opts, OPTION_PLAYBACK, playopts->playback, OPTION_PRIORITY_CMDLINE);
944      if (playopts->state != NULL)
945         options_set_string(opts, OPTION_STATE, playopts->state, OPTION_PRIORITY_CMDLINE);
946      if (playopts->wavwrite != NULL)
947         options_set_string(opts, OPTION_WAVWRITE, playopts->wavwrite, OPTION_PRIORITY_CMDLINE);
948      if (playopts->mngwrite != NULL)
949         options_set_string(opts, OPTION_MNGWRITE, playopts->mngwrite, OPTION_PRIORITY_CMDLINE);
950   }
951
952   // prepare MAME32 to run the game
953   ShowWindow(hMain, SW_HIDE);
954   for (i = 0; i < ARRAY_LENGTH(s_nPickers); i++)
955      Picker_ClearIdle(GetDlgItem(hMain, s_nPickers[i]));
956
957   // run the emulation
958   options_set_string(opts, OPTION_GAMENAME, drivers[nGameIndex]->name, OPTION_PRIORITY_CMDLINE);
959   mame_execute(opts);
960
961   // the emulation is complete; continue
962   for (i = 0; i < ARRAY_LENGTH(s_nPickers); i++)
963      Picker_ResetIdle(GetDlgItem(hMain, s_nPickers[i]));
964   ShowWindow(hMain, SW_SHOW);
965   SetForegroundWindow(hMain);
966
967   // close out MAME options
968   options_free(opts);
969
970   // NPW 16-Apr-2007 - God I hate this hack
971   if (GetGameUsesDefaults(nGameIndex))
972      ResetGameOptions(nGameIndex);
973
974   return dwExitCode;
975}
976
977int Mame32Main(HINSTANCE    hInstance,
978                   LPSTR        lpCmdLine,
979                   int          nCmdShow)
980{
981   dprintf("MAME32 starting\n");
982
983   use_gui_romloading = TRUE;
984
985   if (__argc != 1)
986   {
987      /* Rename main because gcc will use it instead of WinMain even with -mwindows */
988      extern int DECL_SPEC mame_main(int, char**);
989      exit(mame_main(__argc, __argv));
990   }
991   if (!Win32UI_init(hInstance, lpCmdLine, nCmdShow))
992      return 1;
993
994   // pump message, but quit on WM_QUIT
995   while(PumpMessage())
996      ;
997
998   Win32UI_exit();
999   return 0;
1000}
1001
1002
1003HWND GetMainWindow(void)
1004{
1005   return hMain;
1006}
1007
1008HWND GetTreeView(void)
1009{
1010   return hTreeView;
1011}
1012
1013HIMAGELIST GetLargeImageList(void)
1014{
1015   return hLarge;
1016}
1017
1018HIMAGELIST GetSmallImageList(void)
1019{
1020   return hSmall;
1021}
1022
1023object_pool *GetMame32MemoryPool(void)
1024{
1025   return mame32_pool;
1026}
1027
1028void GetRealColumnOrder(int order[])
1029{
1030   int tmpOrder[COLUMN_MAX];
1031   int nColumnMax;
1032   int i;
1033
1034   nColumnMax = Picker_GetNumColumns(hwndList);
1035
1036   /* Get the Column Order and save it */
1037   if (!oldControl)
1038   {
1039      ListView_GetColumnOrderArray(hwndList, nColumnMax, tmpOrder);
1040
1041      for (i = 0; i < nColumnMax; i++)
1042      {
1043         order[i] = Picker_GetRealColumnFromViewColumn(hwndList, tmpOrder[i]);
1044      }
1045   }
1046}
1047
1048/*
1049 * PURPOSE: Format raw data read from an ICO file to an HICON
1050 * PARAMS:  PBYTE ptrBuffer  - Raw data from an ICO file
1051 *          UINT nBufferSize - Size of buffer ptrBuffer
1052 * RETURNS: HICON - handle to the icon, NULL for failure
1053 * History: July '95 - Created
1054 *          March '00- Seriously butchered from MSDN for mine own
1055 *          purposes, sayeth H0ek.
1056 */
1057HICON FormatICOInMemoryToHICON(PBYTE ptrBuffer, UINT nBufferSize)
1058{
1059   ICONIMAGE           IconImage;
1060   LPICONDIRENTRY      lpIDE = NULL;
1061   UINT                nNumImages;
1062   UINT                nBufferIndex = 0;
1063   HICON               hIcon = NULL;
1064
1065   /* Is there a WORD? */
1066   if (nBufferSize < sizeof(WORD))
1067   {
1068      return NULL;
1069   }
1070
1071   /* Was it 'reserved' ?    (ie 0) */
1072   if ((WORD)(ptrBuffer[nBufferIndex]) != 0)
1073   {
1074      return NULL;
1075   }
1076
1077   nBufferIndex += sizeof(WORD);
1078
1079   /* Is there a WORD? */
1080   if (nBufferSize - nBufferIndex < sizeof(WORD))
1081   {
1082      return NULL;
1083   }
1084
1085   /* Was it type 1? */
1086   if ((WORD)(ptrBuffer[nBufferIndex]) != 1)
1087   {
1088      return NULL;
1089   }
1090
1091   nBufferIndex += sizeof(WORD);
1092
1093   /* Is there a WORD? */
1094   if (nBufferSize - nBufferIndex < sizeof(WORD))
1095   {
1096      return NULL;
1097   }
1098
1099   /* Then that's the number of images in the ICO file */
1100   nNumImages = (WORD)(ptrBuffer[nBufferIndex]);
1101
1102   /* Is there at least one icon in the file? */
1103   if ( nNumImages < 1 )
1104   {
1105      return NULL;
1106   }
1107
1108   nBufferIndex += sizeof(WORD);
1109
1110   /* Is there enough space for the icon directory entries? */
1111   if ((nBufferIndex + nNumImages * sizeof(ICONDIRENTRY)) > nBufferSize)
1112   {
1113      return NULL;
1114   }
1115
1116   /* Assign icon directory entries from buffer */
1117   lpIDE = (LPICONDIRENTRY)(&ptrBuffer[nBufferIndex]);
1118   nBufferIndex += nNumImages * sizeof (ICONDIRENTRY);
1119
1120   IconImage.dwNumBytes = lpIDE->dwBytesInRes;
1121
1122   /* Seek to beginning of this image */
1123   if ( lpIDE->dwImageOffset > nBufferSize )
1124   {
1125      return NULL;
1126   }
1127
1128   nBufferIndex = lpIDE->dwImageOffset;
1129
1130   /* Read it in */
1131   if ((nBufferIndex + lpIDE->dwBytesInRes) > nBufferSize)
1132   {
1133      return NULL;
1134   }
1135
1136   IconImage.lpBits = &ptrBuffer[nBufferIndex];
1137   nBufferIndex += lpIDE->dwBytesInRes;
1138
1139   hIcon = CreateIconFromResourceEx(IconImage.lpBits, IconImage.dwNumBytes, TRUE, 0x00030000,
1140         (*(LPBITMAPINFOHEADER)(IconImage.lpBits)).biWidth, (*(LPBITMAPINFOHEADER)(IconImage.lpBits)).biHeight/2, 0 );
1141
1142   /* It failed, odds are good we're on NT so try the non-Ex way */
1143   if (hIcon == NULL)
1144   {
1145      /* We would break on NT if we try with a 16bpp image */
1146      if (((LPBITMAPINFO)IconImage.lpBits)->bmiHeader.biBitCount != 16)
1147      {
1148         hIcon = CreateIconFromResource(IconImage.lpBits, IconImage.dwNumBytes, TRUE, 0x00030000);
1149      }
1150   }
1151   return hIcon;
1152}
1153
1154HICON LoadIconFromFile(const char *iconname)
1155{
1156   HICON hIcon = 0;
1157   struct stat file_stat;
1158   char tmpStr[MAX_PATH];
1159   char tmpIcoName[MAX_PATH];
1160   const char* sDirName = GetImgDir();
1161   PBYTE bufferPtr;
1162   zip_error ziperr;
1163   zip_file *zip;
1164   const zip_file_header *entry;
1165
1166   sprintf(tmpStr, "%s/%s.ico", GetIconsDir(), iconname);
1167   if (stat(tmpStr, &file_stat) != 0
1168   || (hIcon = win_extract_icon_utf8(hInst, tmpStr, 0)) == 0)
1169   {
1170      sprintf(tmpStr, "%s/%s.ico", sDirName, iconname);
1171      if (stat(tmpStr, &file_stat) != 0
1172      || (hIcon = win_extract_icon_utf8(hInst, tmpStr, 0)) == 0)
1173      {
1174         sprintf(tmpStr, "%s/icons.zip", GetIconsDir());
1175         sprintf(tmpIcoName, "%s.ico", iconname);
1176
1177         ziperr = zip_file_open(tmpStr, &zip);
1178         if (ziperr == ZIPERR_NONE)
1179         {
1180            entry = zip_file_first_file(zip);
1181            while(!hIcon && entry)
1182            {
1183               if (!mame_stricmp(entry->filename, tmpIcoName))
1184               {
1185                  bufferPtr = malloc(entry->uncompressed_length);
1186                  if (bufferPtr)
1187                  {
1188                     ziperr = zip_file_decompress(zip, bufferPtr, entry->uncompressed_length);
1189                     if (ziperr == ZIPERR_NONE)
1190                     {
1191                        hIcon = FormatICOInMemoryToHICON(bufferPtr, entry->uncompressed_length);
1192                     }
1193                     free(bufferPtr);
1194                  }
1195               }
1196               entry = zip_file_next_file(zip);
1197            }
1198            zip_file_close(zip);
1199         }
1200      }
1201   }
1202   return hIcon;
1203}
1204
1205/* Return the number of folders with options */
1206int GetNumOptionFolders()
1207{
1208   return optionfolder_count;
1209}
1210
1211/* Return the number of folders with options */
1212void SetNumOptionFolders(int count)
1213{
1214   optionfolder_count = count;
1215}
1216
1217
1218/* Sets the treeview and listviews sizes in accordance with their visibility and the splitters */
1219static void ResizeTreeAndListViews(BOOL bResizeHidden)
1220{
1221   int i;
1222   int nLastWidth = 0;
1223   int nLastWidth2 = 0;
1224   int nLeftWindowWidth = 0;
1225   RECT rect;
1226   BOOL bVisible;
1227
1228   /* Size the List Control in the Picker */
1229   GetClientRect(hMain, &rect);
1230
1231   if (bShowStatusBar)
1232      rect.bottom -= bottomMargin;
1233   if (bShowToolBar)
1234      rect.top += topMargin;
1235
1236   /* Tree control */
1237   ShowWindow(GetDlgItem(hMain, IDC_TREE), bShowTree ? SW_SHOW : SW_HIDE);
1238
1239   for (i = 0; g_splitterInfo[i].nSplitterWindow; i++)
1240   {
1241      bVisible = GetWindowLong(GetDlgItem(hMain, g_splitterInfo[i].nLeftWindow), GWL_STYLE) & WS_VISIBLE ? TRUE : FALSE;
1242      if (bResizeHidden || bVisible)
1243      {
1244         nLeftWindowWidth = nSplitterOffset[i] - SPLITTER_WIDTH/2 - nLastWidth;
1245
1246         /* special case for the rightmost pane when the screenshot is gone */
1247         if (!GetShowScreenShot() && !g_splitterInfo[i+1].nSplitterWindow)
1248            nLeftWindowWidth = rect.right - nLastWidth;
1249
1250         /* woah?  are we overlapping ourselves? */
1251         if (nLeftWindowWidth < MIN_VIEW_WIDTH)
1252         {
1253            nLastWidth = nLastWidth2;
1254            nLeftWindowWidth = nSplitterOffset[i] - MIN_VIEW_WIDTH - (SPLITTER_WIDTH*3/2) - nLastWidth;
1255            i--;
1256         }
1257
1258         MoveWindow(GetDlgItem(hMain, g_splitterInfo[i].nLeftWindow), nLastWidth, rect.top + 2,
1259            nLeftWindowWidth, (rect.bottom - rect.top) - 4 , TRUE);
1260
1261         MoveWindow(GetDlgItem(hMain, g_splitterInfo[i].nSplitterWindow), nSplitterOffset[i], rect.top + 2,
1262            SPLITTER_WIDTH, (rect.bottom - rect.top) - 4, TRUE);
1263      }
1264
1265      if (bVisible)
1266      {
1267         nLastWidth2 = nLastWidth;
1268         nLastWidth += nLeftWindowWidth + SPLITTER_WIDTH;
1269      }
1270   }
1271}
1272
1273/* Adjust the list view and screenshot button based on GetShowScreenShot() */
1274void UpdateScreenShot(void)
1275{
1276   RECT rect;
1277   int  nWidth;
1278   RECT fRect;
1279   POINT p = {0, 0};
1280
1281   /* first time through can't do this stuff */
1282   if (hwndList == NULL)
1283      return;
1284
1285   /* Size the List Control in the Picker */
1286   GetClientRect(hMain, &rect);
1287
1288   if (bShowStatusBar)
1289      rect.bottom -= bottomMargin;
1290   if (bShowToolBar)
1291      rect.top += topMargin;
1292
1293   if (GetShowScreenShot())
1294   {
1295      nWidth = nSplitterOffset[GetSplitterCount() - 1];
1296      CheckMenuItem(GetMenu(hMain),ID_VIEW_PICTURE_AREA, MF_CHECKED);
1297      ToolBar_CheckButton(hToolBar, ID_VIEW_PICTURE_AREA, MF_CHECKED);
1298   }
1299   else
1300   {
1301      nWidth = rect.right;
1302      CheckMenuItem(GetMenu(hMain),ID_VIEW_PICTURE_AREA, MF_UNCHECKED);
1303      ToolBar_CheckButton(hToolBar, ID_VIEW_PICTURE_AREA, MF_UNCHECKED);
1304   }
1305
1306   ResizeTreeAndListViews(FALSE);
1307
1308   FreeScreenShot();
1309
1310   if (have_selection)
1311   {
1312#ifdef MESS
1313      if (!g_szSelectedItem[0] || !LoadScreenShotEx(Picker_GetSelectedItem(hwndList), g_szSelectedItem,
1314         TabView_GetCurrentTab(hTabCtrl)))
1315#endif
1316      {
1317         // load and set image, or empty it if we don't have one
1318         LoadScreenShot(Picker_GetSelectedItem(hwndList), TabView_GetCurrentTab(hTabCtrl));
1319      }
1320   }
1321
1322   // figure out if we have a history or not, to place our other windows properly
1323   UpdateHistory();
1324
1325   // setup the picture area
1326
1327   if (GetShowScreenShot())
1328   {
1329      DWORD dwStyle;
1330      DWORD dwStyleEx;
1331      BOOL showing_history;
1332
1333      ClientToScreen(hMain, &p);
1334      GetWindowRect(GetDlgItem(hMain, IDC_SSFRAME), &fRect);
1335      OffsetRect(&fRect, -p.x, -p.y);
1336
1337      // show history on this tab IFF
1338      // - we have history for the game
1339      // - we're on the first tab
1340      // - we DON'T have a separate history tab
1341      showing_history = (have_history && (TabView_GetCurrentTab(hTabCtrl) == GetHistoryTab() || GetHistoryTab() == TAB_ALL ) &&
1342                     GetShowTab(TAB_HISTORY) == FALSE);
1343      CalculateBestScreenShotRect(GetDlgItem(hMain, IDC_SSFRAME), &rect,showing_history);
1344         
1345      dwStyle   = GetWindowLong(GetDlgItem(hMain, IDC_SSPICTURE), GWL_STYLE);
1346      dwStyleEx = GetWindowLong(GetDlgItem(hMain, IDC_SSPICTURE), GWL_EXSTYLE);
1347         
1348      AdjustWindowRectEx(&rect, dwStyle, FALSE, dwStyleEx);
1349      MoveWindow(GetDlgItem(hMain, IDC_SSPICTURE),
1350               fRect.left  + rect.left,
1351               fRect.top   + rect.top,
1352               rect.right  - rect.left,
1353               rect.bottom - rect.top,
1354               TRUE);
1355     
1356      ShowWindow(GetDlgItem(hMain,IDC_SSPICTURE),
1357               (TabView_GetCurrentTab(hTabCtrl) != TAB_HISTORY) ? SW_SHOW : SW_HIDE);
1358      ShowWindow(GetDlgItem(hMain,IDC_SSFRAME),SW_SHOW);
1359      ShowWindow(GetDlgItem(hMain,IDC_SSTAB),bShowTabCtrl ? SW_SHOW : SW_HIDE);
1360
1361      InvalidateRect(GetDlgItem(hMain,IDC_SSPICTURE),NULL,FALSE);
1362   }
1363   else
1364   {
1365      ShowWindow(GetDlgItem(hMain,IDC_SSPICTURE),SW_HIDE);
1366      ShowWindow(GetDlgItem(hMain,IDC_SSFRAME),SW_HIDE);
1367      ShowWindow(GetDlgItem(hMain,IDC_SSTAB),SW_HIDE);
1368   }
1369
1370}
1371
1372void ResizePickerControls(HWND hWnd)
1373{
1374   RECT frameRect;
1375   RECT rect, sRect;
1376   int  nListWidth, nScreenShotWidth;
1377   static BOOL firstTime = TRUE;
1378   int  doSSControls = TRUE;
1379   int i, nSplitterCount;
1380
1381   nSplitterCount = GetSplitterCount();
1382
1383   /* Size the List Control in the Picker */
1384   GetClientRect(hWnd, &rect);
1385
1386   /* Calc the display sizes based on g_splitterInfo */
1387   if (firstTime)
1388   {
1389      RECT rWindow;
1390
1391      for (i = 0; i < nSplitterCount; i++)
1392         nSplitterOffset[i] = rect.right * g_splitterInfo[i].dPosition;
1393
1394      GetWindowRect(hStatusBar, &rWindow);
1395      bottomMargin = rWindow.bottom - rWindow.top;
1396      GetWindowRect(hToolBar, &rWindow);
1397      topMargin = rWindow.bottom - rWindow.top;
1398      /*buttonMargin = (sRect.bottom + 4); */
1399
1400      firstTime = FALSE;
1401   }
1402   else
1403   {
1404      doSSControls = GetShowScreenShot();
1405   }
1406
1407   if (bShowStatusBar)
1408      rect.bottom -= bottomMargin;
1409
1410   if (bShowToolBar)
1411      rect.top += topMargin;
1412
1413   MoveWindow(GetDlgItem(hWnd, IDC_DIVIDER), rect.left, rect.top - 4, rect.right, 2, TRUE);
1414
1415   ResizeTreeAndListViews(TRUE);
1416
1417   nListWidth = nSplitterOffset[nSplitterCount-1];
1418   nScreenShotWidth = (rect.right - nListWidth) - 4;
1419
1420   /* Screen shot Page tab control */
1421   if (bShowTabCtrl)
1422   {
1423      MoveWindow(GetDlgItem(hWnd, IDC_SSTAB), nListWidth + 4, rect.top + 2,
1424         nScreenShotWidth - 2, rect.top + 20, doSSControls);
1425      rect.top += 20;
1426   }
1427
1428   /* resize the Screen shot frame */
1429   MoveWindow(GetDlgItem(hWnd, IDC_SSFRAME), nListWidth + 4, rect.top + 2,
1430      nScreenShotWidth - 2, (rect.bottom - rect.top) - 4, doSSControls);
1431
1432   /* The screen shot controls */
1433   GetClientRect(GetDlgItem(hWnd, IDC_SSFRAME), &frameRect);
1434
1435   /* Text control - game history */
1436   sRect.left = nListWidth + 14;
1437   sRect.right = sRect.left + (nScreenShotWidth - 22);
1438
1439   
1440   if (GetShowTab(TAB_HISTORY))
1441   {
1442      // We're using the new mode, with the history filling the entire tab (almost)
1443      sRect.top = rect.top + 14;
1444      sRect.bottom = (rect.bottom - rect.top) - 30;   
1445   }
1446   else
1447   {
1448      // We're using the original mode, with the history beneath the SS picture
1449      sRect.top = rect.top + 264;
1450      sRect.bottom = (rect.bottom - rect.top) - 278;
1451   }
1452
1453   MoveWindow(GetDlgItem(hWnd, IDC_HISTORY),
1454      sRect.left, sRect.top,
1455      sRect.right - sRect.left, sRect.bottom, doSSControls);
1456
1457   /* the other screen shot controls will be properly placed in UpdateScreenshot() */
1458
1459}
1460
1461char *ModifyThe(const char *str)
1462{
1463   static int  bufno = 0;
1464   static char buffer[4][255];
1465
1466   if (strncmp(str, "The ", 4) == 0)
1467   {
1468      char *s, *p;
1469      char temp[255];
1470
1471      strcpy(temp, &str[4]);
1472
1473      bufno = (bufno + 1) % 4;
1474
1475      s = buffer[bufno];
1476
1477      /* Check for version notes in parens */
1478      p = strchr(temp, '(');
1479      if (p)
1480      {
1481         p[-1] = '\0';
1482      }
1483
1484      strcpy(s, temp);
1485      strcat(s, ", The");
1486
1487      if (p)
1488      {
1489         strcat(s, " ");
1490         strcat(s, p);
1491      }
1492
1493      return s;
1494   }
1495   return (char *)str;
1496}
1497
1498HBITMAP GetBackgroundBitmap(void)
1499{
1500   return hBackground;
1501}
1502
1503HPALETTE GetBackgroundPalette(void)
1504{
1505   return hPALbg;
1506}
1507
1508MYBITMAPINFO * GetBackgroundInfo(void)
1509{
1510   return &bmDesc;
1511}
1512
1513BOOL GetUseOldControl(void)
1514{
1515   return oldControl;
1516}
1517
1518BOOL GetUseXPControl(void)
1519{
1520   return xpControl;
1521}
1522
1523int GetMinimumScreenShotWindowWidth(void)
1524{
1525   BITMAP bmp;
1526   GetObject(hMissing_bitmap,sizeof(BITMAP),&bmp);
1527
1528   return bmp.bmWidth + 6; // 6 is for a little breathing room
1529}
1530
1531
1532int GetDriverIndex(const game_driver *driver)
1533{
1534   return GetGameNameIndex(driver->name);
1535}
1536
1537int GetParentIndex(const game_driver *driver)
1538{
1539   return GetGameNameIndex(driver->parent);
1540}
1541
1542int GetParentRomSetIndex(const game_driver *driver)
1543{
1544   int nParentIndex = GetGameNameIndex(driver->parent);
1545
1546   if( nParentIndex >= 0)
1547   {
1548      if ((drivers[nParentIndex]->flags & GAME_IS_BIOS_ROOT) == 0)
1549         return nParentIndex;
1550   }
1551
1552   return -1;
1553}
1554
1555int GetGameNameIndex(const char *name)
1556{
1557   driver_data_type *driver_index_info;
1558   driver_data_type key;
1559   key.name = name;
1560
1561   // uses our sorted array of driver names to get the index in log time
1562   driver_index_info = bsearch(&key,sorted_drivers,driver_list_get_count(drivers),sizeof(driver_data_type),
1563                        DriverDataCompareFunc);
1564
1565   if (driver_index_info == NULL)
1566      return -1;
1567
1568   return driver_index_info->index;
1569
1570}
1571
1572int GetIndexFromSortedIndex(int sorted_index)
1573{
1574   return sorted_drivers[sorted_index].index;
1575}
1576
1577/***************************************************************************
1578    Internal functions
1579 ***************************************************************************/
1580
1581// used for our sorted array of game names
1582int CLIB_DECL DriverDataCompareFunc(const void *arg1,const void *arg2)
1583{
1584    return strcmp( ((driver_data_type *)arg1)->name, ((driver_data_type *)arg2)->name );
1585}
1586
1587static void ResetBackground(char *szFile)
1588{
1589   char szDestFile[MAX_PATH];
1590
1591   /* The MAME core load the .png file first, so we only need replace this file */
1592   sprintf(szDestFile, "%s\\bkground.png", GetBgDir());
1593   win_set_file_attributes_utf8(szDestFile, FILE_ATTRIBUTE_NORMAL);
1594   win_copy_file_utf8(szFile, szDestFile, FALSE);
1595}
1596
1597static void RandomSelectBackground(void)
1598{
1599   struct _finddata_t c_file;
1600   long hFile;
1601   char szFile[MAX_PATH];
1602   int count=0;
1603   const char *szDir=GetBgDir();
1604   char *buf=malloc(_MAX_FNAME * MAX_BGFILES);
1605
1606   if (buf == NULL)
1607      return;
1608
1609   sprintf(szFile, "%s\\*.bmp", szDir);
1610   hFile = _findfirst(szFile, &c_file);
1611   if (hFile != -1L)
1612   {
1613      int Done = 0;
1614      while (!Done && count < MAX_BGFILES)
1615      {
1616         memcpy(buf + count * _MAX_FNAME, c_file.name, _MAX_FNAME);
1617         count++;
1618         Done = _findnext(hFile, &c_file);
1619      }
1620      _findclose(hFile);
1621   }
1622   sprintf(szFile, "%s\\*.png", szDir);
1623   hFile = _findfirst(szFile, &c_file);
1624   if (hFile != -1L)
1625   {
1626      int Done = 0;
1627      while (!Done && count < MAX_BGFILES)
1628      {
1629         memcpy(buf + count * _MAX_FNAME, c_file.name, _MAX_FNAME);
1630         count++;
1631         Done = _findnext(hFile, &c_file);
1632      }
1633      _findclose(hFile);
1634   }
1635
1636   if (count)
1637   {
1638#ifdef rand
1639#undef rand
1640#endif
1641
1642      srand( (unsigned)time( NULL ) );
1643      sprintf(szFile, "%s\\%s", szDir, buf + (rand() % count) * _MAX_FNAME);
1644      ResetBackground(szFile);
1645   }
1646
1647   free(buf);
1648}
1649
1650void SetMainTitle(void)
1651{
1652   char version[50];
1653   char buffer[100];
1654
1655   sscanf(build_version,"%s",version);
1656   snprintf(buffer, ARRAY_LENGTH(buffer), "%s %s", MAME32NAME, version);
1657   win_set_window_text_utf8(hMain,buffer);
1658}
1659
1660static void winui_output_error(void *param, const char *format, va_list argptr)
1661{
1662   char buffer[1024];
1663
1664   // if we are in fullscreen mode, go to windowed mode
1665   if ((video_config.windowed == 0) && (win_window_list != NULL))
1666      winwindow_toggle_full_screen();
1667
1668   vsnprintf(buffer, ARRAY_LENGTH(buffer), format, argptr);
1669   win_message_box_utf8(win_window_list ? win_window_list->hwnd : NULL, buffer, APPNAME, MB_OK);
1670}
1671
1672static void memory_error(const char *message)
1673{
1674   win_message_box_utf8(hMain, message, APPNAME, MB_OK);
1675   exit(-1);
1676}
1677
1678static BOOL Win32UI_init(HINSTANCE hInstance, LPSTR lpCmdLine, int nCmdShow)
1679{
1680   extern int mame_validitychecks(int game);
1681   WNDCLASS   wndclass;
1682   RECT      rect;
1683   int i, nSplitterCount;
1684   extern FOLDERDATA g_folderData[];
1685   extern FILTER_ITEM g_filterList[];
1686   extern const char *history_filename;
1687   extern const char *mameinfo_filename;
1688   LONG common_control_version = GetCommonControlVersion();
1689   int validity_failed = 0;
1690   TCHAR* t_inpdir;
1691
1692   dprintf("about to init options\n");
1693   if (!OptionsInit())
1694      return FALSE;
1695   dprintf("options loaded\n");
1696
1697   srand((unsigned)time(NULL));
1698
1699   // output errors to message boxes
1700   mame_set_output_channel(OUTPUT_CHANNEL_ERROR, winui_output_error, NULL, NULL, NULL);
1701
1702   // create the memory pool
1703   mame32_pool = pool_alloc(memory_error);
1704
1705   // custom per-game icons
1706   icon_index = pool_malloc(mame32_pool, sizeof(int) * driver_list_get_count(drivers));
1707   memset(icon_index, '\0', sizeof(int) * driver_list_get_count(drivers));
1708
1709   // sorted list of drivers by name
1710   sorted_drivers = (driver_data_type *) pool_malloc(mame32_pool, sizeof(driver_data_type) * driver_list_get_count(drivers));
1711   memset(sorted_drivers, '\0', sizeof(driver_data_type) * driver_list_get_count(drivers));
1712   for (i = 0; i < driver_list_get_count(drivers); i++)
1713   {
1714      sorted_drivers[i].name = drivers[i]->name;
1715      sorted_drivers[i].index = i;
1716   }
1717   qsort(sorted_drivers, driver_list_get_count(drivers), sizeof(driver_data_type), DriverDataCompareFunc);
1718
1719   // set up window class
1720   wndclass.style         = CS_HREDRAW | CS_VREDRAW;
1721   wndclass.lpfnWndProc   = MameWindowProc;
1722   wndclass.cbClsExtra    = 0;
1723   wndclass.cbWndExtra    = DLGWINDOWEXTRA;
1724   wndclass.hInstance      = hInstance;
1725   wndclass.hIcon         = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_MAME32_ICON));
1726   wndclass.hCursor      = NULL;
1727   wndclass.hbrBackground = (HBRUSH)(COLOR_3DFACE + 1);
1728   wndclass.lpszMenuName  = MAKEINTRESOURCE(IDR_UI_MENU);
1729   wndclass.lpszClassName = TEXT("MainClass");
1730
1731   RegisterClass(&wndclass);
1732
1733#ifdef MESS
1734   DevView_RegisterClass();
1735#endif //MESS
1736
1737   InitCommonControls();
1738
1739   // Are we using an Old comctl32.dll?
1740   dprintf("common controlversion %i %i",common_control_version >> 16,
1741         common_control_version & 0xffff);
1742         
1743   oldControl = (common_control_version < PACKVERSION(4,71));
1744   xpControl = (common_control_version >= PACKVERSION(6,0));
1745   if (oldControl)
1746   {
1747      char buf[] = MAME32NAME " has detected an old version of comctl32.dll\n\n"
1748                "Game Properties, many configuration options and\n"
1749                "features are not available without an updated DLL\n\n"
1750                "Please install the common control update found at:\n\n"
1751                "http://www.microsoft.com/msdownload/ieplatform/ie/comctrlx86.asp\n\n"
1752                "Would you like to continue without using the new features?\n";
1753
1754      if (IDNO == win_message_box_utf8(0, buf, MAME32NAME " Outdated comctl32.dll Warning", MB_YESNO | MB_ICONWARNING))
1755         return FALSE;
1756    }
1757
1758   g_mame32_message = RegisterWindowMessage(TEXT("MAME32"));
1759   g_bDoBroadcast = GetBroadcast();
1760
1761   HelpInit();
1762   
1763   t_inpdir = tstring_from_utf8(GetInpDir());
1764   if( ! t_inpdir )
1765      return FALSE;
1766
1767   _tcscpy(last_directory,t_inpdir);
1768   free(t_inpdir);
1769   hMain = CreateDialog(hInstance, MAKEINTRESOURCE(IDD_MAIN), 0, NULL);
1770   if (hMain == NULL)
1771   {
1772      dprintf("error creating main dialog, aborting");
1773      return FALSE;
1774   }
1775
1776   s_pWatcher = DirWatcher_Init(hMain, WM_MAME32_FILECHANGED);
1777   if (s_pWatcher)
1778   {
1779      DirWatcher_Watch(s_pWatcher, 0, GetRomDirs(), TRUE);
1780      DirWatcher_Watch(s_pWatcher, 1, GetSampleDirs(), TRUE);
1781   }
1782
1783   SetMainTitle();
1784   hTabCtrl = GetDlgItem(hMain, IDC_SSTAB);
1785   
1786   {
1787      struct TabViewOptions opts;
1788
1789      static struct TabViewCallbacks s_tabviewCallbacks =
1790      {
1791         GetShowTabCtrl,         // pfnGetShowTabCtrl
1792         SetCurrentTab,         // pfnSetCurrentTab
1793         GetCurrentTab,         // pfnGetCurrentTab
1794         SetShowTab,            // pfnSetShowTab
1795         GetShowTab,            // pfnGetShowTab
1796
1797         GetImageTabShortName,   // pfnGetTabShortName
1798         GetImageTabLongName,   // pfnGetTabLongName
1799         UpdateScreenShot      // pfnOnSelectionChanged
1800      };
1801
1802      memset(&opts, 0, sizeof(opts));
1803      opts.pCallbacks = &s_tabviewCallbacks;
1804      opts.nTabCount = MAX_TAB_TYPES;
1805
1806      if (!SetupTabView(hTabCtrl, &opts))
1807         return FALSE;
1808   }
1809
1810   /* subclass history window */
1811   g_lpHistoryWndProc = (WNDPROC)(LONG)(int)GetWindowLong(GetDlgItem(hMain, IDC_HISTORY), GWL_WNDPROC);
1812   SetWindowLong(GetDlgItem(hMain, IDC_HISTORY), GWL_WNDPROC, (LONG)HistoryWndProc);
1813
1814   /* subclass picture frame area */
1815   g_lpPictureFrameWndProc = (WNDPROC)(LONG)(int)GetWindowLong(GetDlgItem(hMain, IDC_SSFRAME), GWL_WNDPROC);
1816   SetWindowLong(GetDlgItem(hMain, IDC_SSFRAME), GWL_WNDPROC, (LONG)PictureFrameWndProc);
1817
1818   /* subclass picture area */
1819   g_lpPictureWndProc = (WNDPROC)(LONG)(int)GetWindowLong(GetDlgItem(hMain, IDC_SSPICTURE), GWL_WNDPROC);
1820   SetWindowLong(GetDlgItem(hMain, IDC_SSPICTURE), GWL_WNDPROC, (LONG)PictureWndProc);
1821
1822   /* Load the pic for the default screenshot. */
1823   hMissing_bitmap = LoadBitmap(GetModuleHandle(NULL),MAKEINTRESOURCE(IDB_ABOUT));
1824
1825   /* Stash hInstance for later use */
1826   hInst = hInstance;
1827
1828   hToolBar   = InitToolbar(hMain);
1829   hStatusBar = InitStatusBar(hMain);
1830   hProgWnd   = InitProgressBar(hStatusBar);
1831
1832   main_resize_items[0].u.hwnd = hToolBar;
1833   main_resize_items[1].u.hwnd = hStatusBar;
1834
1835   /* In order to handle 'Large Fonts' as the Windows
1836    * default setting, we need to make the dialogs small
1837    * enough to fit in our smallest window size with
1838    * large fonts, then resize the picker, tab and button
1839    * controls to fill the window, no matter which font
1840    * is currently set.  This will still look like bad
1841    * if the user uses a bigger default font than 125%
1842    * (Large Fonts) on the Windows display setting tab.
1843    *
1844    * NOTE: This has to do with Windows default font size
1845    * settings, NOT our picker font size.
1846    */
1847
1848   GetClientRect(hMain, &rect);
1849
1850   hTreeView = GetDlgItem(hMain, IDC_TREE);
1851   hwndList  = GetDlgItem(hMain, IDC_LIST);
1852
1853   history_filename = mame_strdup(GetHistoryFileName());
1854   mameinfo_filename = mame_strdup(GetMAMEInfoFileName());
1855
1856   if (!InitSplitters())
1857      return FALSE;
1858
1859   nSplitterCount = GetSplitterCount();
1860   for (i = 0; i < nSplitterCount; i++)
1861   {
1862      HWND hWnd;
1863      HWND hWndLeft;
1864      HWND hWndRight;
1865
1866      hWnd = GetDlgItem(hMain, g_splitterInfo[i].nSplitterWindow);
1867      hWndLeft = GetDlgItem(hMain, g_splitterInfo[i].nLeftWindow);
1868      hWndRight = GetDlgItem(hMain, g_splitterInfo[i].nRightWindow);
1869
1870      AddSplitter(hWnd, hWndLeft, hWndRight, g_splitterInfo[i].pfnAdjust);
1871   }
1872
1873   /* Initial adjustment of controls on the Picker window */
1874   ResizePickerControls(hMain);
1875
1876   TabView_UpdateSelection(hTabCtrl);
1877
1878   bDoGameCheck = GetGameCheck();
1879   idle_work    = TRUE;
1880   game_index   = 0;
1881
1882   bShowTree      = GetShowFolderList();
1883   bShowToolBar   = GetShowToolBar();
1884   bShowStatusBar = GetShowStatusBar();
1885   bShowTabCtrl   = GetShowTabCtrl();
1886
1887   CheckMenuItem(GetMenu(hMain), ID_VIEW_FOLDERS, (bShowTree) ? MF_CHECKED : MF_UNCHECKED);
1888   ToolBar_CheckButton(hToolBar, ID_VIEW_FOLDERS, (bShowTree) ? MF_CHECKED : MF_UNCHECKED);
1889   CheckMenuItem(GetMenu(hMain), ID_VIEW_TOOLBARS, (bShowToolBar) ? MF_CHECKED : MF_UNCHECKED);
1890   ShowWindow(hToolBar, (bShowToolBar) ? SW_SHOW : SW_HIDE);
1891   CheckMenuItem(GetMenu(hMain), ID_VIEW_STATUS, (bShowStatusBar) ? MF_CHECKED : MF_UNCHECKED);
1892   ShowWindow(hStatusBar, (bShowStatusBar) ? SW_SHOW : SW_HIDE);
1893   CheckMenuItem(GetMenu(hMain), ID_VIEW_PAGETAB, (bShowTabCtrl) ? MF_CHECKED : MF_UNCHECKED);
1894
1895   if (oldControl)
1896   {
1897      EnableMenuItem(GetMenu(hMain), ID_CUSTOMIZE_FIELDS, MF_GRAYED);
1898      EnableMenuItem(GetMenu(hMain), ID_GAME_PROPERTIES,   MF_GRAYED);
1899      EnableMenuItem(GetMenu(hMain), ID_OPTIONS_DEFAULTS, MF_GRAYED);
1900   }
1901
1902   /* Init DirectDraw */
1903   if (!DirectDraw_Initialize())
1904   {
1905      DialogBox(GetModuleHandle(NULL),MAKEINTRESOURCE(IDD_DIRECTX), NULL, DirectXDialogProc);
1906      return FALSE;
1907   }
1908
1909   if (GetRandomBackground())
1910      RandomSelectBackground();
1911
1912   LoadBackgroundBitmap();
1913
1914   dprintf("about to init tree");
1915   InitTree(g_folderData, g_filterList);
1916   dprintf("did init tree");
1917   FolderOptionsInit();
1918   PropertiesInit();
1919
1920   /* Initialize listview columns */
1921#ifdef MESS
1922   InitMessPicker();
1923#endif
1924   InitListView();
1925   SetFocus(hwndList);
1926
1927   /* Reset the font */
1928   {
1929      LOGFONT logfont;
1930
1931      GetListFont(&logfont);
1932      hFont = CreateFontIndirect(&logfont);
1933      if (hFont != NULL)
1934         SetAllWindowsFont(hMain, &main_resize, hFont, FALSE);
1935   }
1936
1937   /* Init DirectInput */
1938   if (!DirectInputInitialize())
1939   {
1940      DialogBox(GetModuleHandle(NULL),MAKEINTRESOURCE(IDD_DIRECTX), NULL, DirectXDialogProc);
1941      return FALSE;
1942   }
1943
1944   AdjustMetrics();
1945   UpdateScreenShot();
1946
1947   hAccel = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDA_TAB_KEYS));
1948
1949   /* clear keyboard state */
1950   KeyboardStateClear();
1951
1952   for (i = 0; i < NUM_GUI_SEQUENCES; i++)
1953   {
1954      input_seq *is1;
1955      input_seq *is2;
1956      is1 = &(GUISequenceControl[i].is);
1957      is2 = GUISequenceControl[i].getiniptr();
1958      // FIXME
1959      //input_seq_copy(is1, is2);
1960      //dprintf("seq =%s is: %4i %4i %4i %4i\n",GUISequenceControl[i].name, (*is1)[0], (*is1)[1], (*is1)[2], (*is1)[3]);
1961   }
1962
1963   if (GetJoyGUI() == TRUE)
1964   {
1965      g_pJoyGUI = &DIJoystick;
1966      if (g_pJoyGUI->init() != 0)
1967         g_pJoyGUI = NULL;
1968      else
1969         SetTimer(hMain, JOYGUI_TIMER, JOYGUI_MS, NULL);
1970   }
1971   else
1972      g_pJoyGUI = NULL;
1973
1974   if (GetHideMouseOnStartup())
1975   {   
1976      /*  For some reason the mouse is centered when a game is exited, which of
1977         course causes a WM_MOUSEMOVE event that shows the mouse. So we center
1978         it now, before the startup coords are initilized, and that way the mouse
1979         will still be hidden when exiting from a game (i hope) :)
1980      */     
1981      SetCursorPos(GetSystemMetrics(SM_CXSCREEN)/2,GetSystemMetrics(SM_CYSCREEN)/2);
1982     
1983      // Then hide it
1984      ShowCursor(FALSE);
1985   }
1986
1987   dprintf("about to show window\n");
1988
1989   nCmdShow = GetWindowState();
1990   if (nCmdShow == SW_HIDE || nCmdShow == SW_MINIMIZE || nCmdShow == SW_SHOWMINIMIZED)
1991   {
1992      nCmdShow = SW_RESTORE;
1993   }
1994
1995   if (GetRunFullScreen())
1996   {
1997      LONG lMainStyle;
1998
1999      // Remove menu
2000      SetMenu(hMain,NULL);
2001
2002      // Frameless dialog (fake fullscreen)
2003      lMainStyle = GetWindowLong(hMain, GWL_STYLE);
2004      lMainStyle = lMainStyle & (WS_BORDER ^ 0xffffffff);
2005      SetWindowLong(hMain, GWL_STYLE, lMainStyle);
2006
2007      nCmdShow = SW_MAXIMIZE;
2008   }
2009
2010   ShowWindow(hMain, nCmdShow);
2011
2012   
2013   switch (GetViewMode())
2014   {
2015   case VIEW_LARGE_ICONS :
2016      SetView(ID_VIEW_LARGE_ICON);
2017      break;
2018   case VIEW_SMALL_ICONS :
2019      SetView(ID_VIEW_SMALL_ICON);
2020      break;
2021   case VIEW_INLIST :
2022      SetView(ID_VIEW_LIST_MENU);
2023      break;
2024   case VIEW_REPORT :
2025      SetView(ID_VIEW_DETAIL);
2026      break;
2027   case VIEW_GROUPED :
2028   default :
2029      SetView(ID_VIEW_GROUPED);
2030      break;
2031   }
2032
2033   if (GetCycleScreenshot() > 0)
2034   {
2035      SetTimer(hMain, SCREENSHOT_TIMER, GetCycleScreenshot()*1000, NULL); //scale to Seconds
2036   }
2037
2038   if (validity_failed)
2039   {
2040      win_message_box_utf8(hMain, MAMENAME " has failed its validity checks.  The GUI will "
2041         "still work, but emulations will fail to execute", MAMENAME, MB_OK);
2042   }
2043
2044   return TRUE;
2045}
2046
2047
2048static void Win32UI_exit()
2049{
2050    if (g_bDoBroadcast == TRUE)
2051    {
2052        ATOM a = GlobalAddAtom(TEXT(""));
2053        SendMessage(HWND_BROADCAST, g_mame32_message, a, a);
2054        GlobalDeleteAtom(a);
2055    }
2056
2057   if (g_pJoyGUI != NULL)
2058      g_pJoyGUI->exit();
2059
2060   /* Free GDI resources */
2061
2062   if (hMissing_bitmap)
2063   {
2064      DeleteObject(hMissing_bitmap);
2065      hMissing_bitmap = NULL;
2066   }
2067
2068   if (hBackground)
2069   {
2070      DeleteObject(hBackground);
2071      hBackground = NULL;
2072   }
2073   
2074   if (hPALbg)
2075   {
2076      DeleteObject(hPALbg);
2077      hPALbg = NULL;
2078   }
2079   
2080   if (hFont)
2081   {
2082      DeleteObject(hFont);
2083      hFont = NULL;
2084   }
2085   
2086   DestroyIcons();
2087
2088   DestroyAcceleratorTable(hAccel);
2089
2090   DirectInputClose();
2091   DirectDraw_Close();
2092
2093   SetSavedFolderID(GetCurrentFolderID());
2094
2095   SaveOptions();
2096
2097   FreeFolders();
2098
2099    /* DestroyTree(hTreeView); */
2100
2101   FreeScreenShot();
2102
2103   OptionsExit();
2104
2105   HelpExit();
2106
2107   pool_free(mame32_pool);
2108   mame32_pool = NULL;
2109}
2110
2111static long WINAPI MameWindowProc(HWND hWnd, UINT message, UINT wParam, LONG lParam)
2112{
2113   MINMAXINFO   *mminfo;
2114   int       i;
2115   TCHAR szClass[128];
2116
2117   switch (message)
2118   {
2119   case WM_CTLCOLORSTATIC:
2120      if (hBackground && (HWND)lParam == GetDlgItem(hMain, IDC_HISTORY))
2121      {
2122         static HBRUSH hBrush=0;
2123         HDC hDC=(HDC)wParam;
2124         LOGBRUSH lb;
2125
2126         if (hBrush)
2127            DeleteObject(hBrush);
2128         lb.lbStyle  = BS_HOLLOW;
2129         hBrush = CreateBrushIndirect(&lb);
2130         SetBkMode(hDC, TRANSPARENT);
2131         SetTextColor(hDC, GetListFontColor());
2132         return (LRESULT) hBrush;
2133      }
2134      break;
2135
2136   case WM_INITDIALOG:
2137      /* Initialize info for resizing subitems */
2138      GetClientRect(hWnd, &main_resize.rect);
2139      return TRUE;
2140
2141   case WM_SETFOCUS:
2142      SetFocus(hwndList);
2143      break;
2144
2145   case WM_SETTINGCHANGE:
2146      AdjustMetrics();
2147      return 0;
2148
2149   case WM_SIZE:
2150      OnSize(hWnd, wParam, LOWORD(lParam), HIWORD(wParam));
2151      return TRUE;
2152
2153   case WM_MENUSELECT:
2154      return Statusbar_MenuSelect(hWnd, wParam, lParam);
2155
2156   case MM_PLAY_GAME:
2157      MamePlayGame();
2158      return TRUE;
2159
2160   case WM_INITMENUPOPUP:
2161      UpdateMenu(GetMenu(hWnd));
2162      break;
2163
2164   case WM_CONTEXTMENU:
2165      if (HandleTreeContextMenu(hWnd, wParam, lParam)
2166      ||   HandleScreenShotContextMenu(hWnd, wParam, lParam))
2167         return FALSE;
2168      break;
2169
2170   case WM_COMMAND:
2171      return MameCommand(hWnd,(int)(LOWORD(wParam)),(HWND)(lParam),(UINT)HIWORD(wParam));
2172
2173   case WM_GETMINMAXINFO:
2174      /* Don't let the window get too small; it can break resizing */
2175      mminfo = (MINMAXINFO *) lParam;
2176      mminfo->ptMinTrackSize.x = MIN_WIDTH;
2177      mminfo->ptMinTrackSize.y = MIN_HEIGHT;
2178      return 0;
2179
2180   case WM_TIMER:
2181      switch (wParam)
2182      {
2183      case JOYGUI_TIMER:
2184         PollGUIJoystick();
2185         break;
2186      case SCREENSHOT_TIMER:
2187         TabView_CalculateNextTab(hTabCtrl);
2188         UpdateScreenShot();
2189         TabView_UpdateSelection(hTabCtrl);
2190         break;
2191      default:
2192         break;
2193      }
2194      return TRUE;
2195
2196   case WM_CLOSE:
2197      {
2198         /* save current item */
2199         RECT rect;
2200         AREA area;
2201         int nItem;
2202         WINDOWPLACEMENT wndpl;
2203         UINT state;
2204
2205         wndpl.length = sizeof(WINDOWPLACEMENT);
2206         GetWindowPlacement(hMain, &wndpl);
2207         state = wndpl.showCmd;
2208
2209         /* Restore the window before we attempt to save parameters,
2210          * This fixed the lost window on startup problem, among other problems
2211          */
2212         if (state == SW_MINIMIZE || state == SW_SHOWMINIMIZED || state == SW_MAXIMIZE)
2213         {
2214            if( wndpl.flags & WPF_RESTORETOMAXIMIZED || state == SW_MAXIMIZE)
2215               state = SW_MAXIMIZE;
2216            else
2217            {
2218               state = SW_RESTORE;
2219               ShowWindow(hWnd, SW_RESTORE);
2220            }
2221         }
2222         for (i = 0; i < GetSplitterCount(); i++)
2223            SetSplitterPos(i, nSplitterOffset[i]);
2224         SetWindowState(state);
2225
2226         for (i = 0; i < sizeof(s_nPickers) / sizeof(s_nPickers[0]); i++)
2227            Picker_SaveColumnWidths(GetDlgItem(hMain, s_nPickers[i]));
2228
2229         GetWindowRect(hWnd, &rect);
2230         area.x      = rect.left;
2231         area.y      = rect.top;
2232         area.width   = rect.right  - rect.left;
2233         area.height = rect.bottom - rect.top;
2234         SetWindowArea(&area);
2235
2236         /* Save the users current game options and default game */
2237         nItem = Picker_GetSelectedItem(hwndList);
2238         SetDefaultGame(ModifyThe(drivers[nItem]->name));
2239
2240         /* hide window to prevent orphan empty rectangles on the taskbar */
2241         /* ShowWindow(hWnd,SW_HIDE); */
2242            DestroyWindow( hWnd );
2243
2244         /* PostQuitMessage(0); */
2245         break;
2246      }
2247
2248   case WM_DESTROY:
2249        PostQuitMessage(0);
2250      return 0;
2251
2252   case WM_LBUTTONDOWN:
2253      OnLButtonDown(hWnd, (UINT)wParam, MAKEPOINTS(lParam));
2254      break;
2255
2256      /*
2257        Check to see if the mouse has been moved by the user since
2258        startup. I'd like this checking to be done only in the
2259        main WinProc (here), but somehow the WM_MOUSEDOWN messages
2260        are eaten up before they reach MameWindowProc. That's why
2261        there is one check for each of the subclassed windows too.
2262   
2263        POSSIBLE BUGS:
2264        I've included this check in the subclassed windows, but a
2265        mose move in either the title bar, the menu, or the
2266        toolbar will not generate a WM_MOUSEOVER message. At least
2267        not one that I know how to pick up. A solution could maybe
2268        be to subclass those too, but that's too much work :)
2269      */
2270     
2271   case WM_MOUSEMOVE:
2272   {
2273      if (MouseHasBeenMoved())
2274         ShowCursor(TRUE);
2275     
2276      if (g_listview_dragging)
2277         MouseMoveListViewDrag(MAKEPOINTS(lParam));
2278      else
2279         /* for splitters */
2280         OnMouseMove(hWnd, (UINT)wParam, MAKEPOINTS(lParam));
2281      break;
2282   }
2283
2284   case WM_LBUTTONUP:
2285       if (g_listview_dragging)
2286          ButtonUpListViewDrag(MAKEPOINTS(lParam));
2287      else
2288         /* for splitters */
2289         OnLButtonUp(hWnd, (UINT)wParam, MAKEPOINTS(lParam));
2290      break;
2291
2292   case WM_NOTIFY:
2293      /* Where is this message intended to go */
2294      {
2295         LPNMHDR lpNmHdr = (LPNMHDR)lParam;
2296
2297         /* Fetch tooltip text */
2298         if (lpNmHdr->code == TTN_NEEDTEXT)
2299         {
2300            LPTOOLTIPTEXT lpttt = (LPTOOLTIPTEXT)lParam;
2301            CopyToolTipText(lpttt);
2302         }
2303
2304         if (lpNmHdr->hwndFrom == hTreeView)
2305            return TreeViewNotify(lpNmHdr);
2306
2307         GetClassName(lpNmHdr->hwndFrom, szClass, sizeof(szClass) / sizeof(szClass[0]));
2308         if (!_tcscmp(szClass, TEXT("SysListView32")))
2309            return Picker_HandleNotify(lpNmHdr);   
2310         if (!_tcscmp(szClass, TEXT("SysTabControl32")))
2311            return TabView_HandleNotify(lpNmHdr);
2312      }
2313      break;
2314
2315   case WM_DRAWITEM:
2316      {
2317         LPDRAWITEMSTRUCT lpDis = (LPDRAWITEMSTRUCT)lParam;
2318
2319         GetClassName(lpDis->hwndItem, szClass, sizeof(szClass) / sizeof(szClass[0]));
2320         if (!_tcscmp(szClass, TEXT("SysListView32")))
2321            Picker_HandleDrawItem(GetDlgItem(hMain, lpDis->CtlID), lpDis);
2322      }
2323      break;
2324
2325   case WM_MEASUREITEM :
2326   {
2327      LPMEASUREITEMSTRUCT lpmis = (LPMEASUREITEMSTRUCT) lParam;
2328
2329      // tell the list view that each row (item) should be just taller than our font
2330
2331      //DefWindowProc(hWnd, message, wParam, lParam);
2332      //dprintf("default row height calculation gives %u\n",lpmis->itemHeight);
2333
2334      TEXTMETRIC tm;
2335      HDC hDC = GetDC(NULL);
2336      HFONT hFontOld = (HFONT)SelectObject(hDC,hFont);
2337
2338      GetTextMetrics(hDC,&tm);
2339     
2340      lpmis->itemHeight = tm.tmHeight + tm.tmExternalLeading + 1;
2341      if (lpmis->itemHeight < 17)
2342         lpmis->itemHeight = 17;
2343      //dprintf("we would do %u\n",tm.tmHeight + tm.tmExternalLeading + 1);
2344      SelectObject(hDC,hFontOld);
2345      ReleaseDC(NULL,hDC);
2346
2347      return TRUE;
2348   }
2349
2350   case WM_MAME32_FILECHANGED:
2351      {
2352         char szFileName[32];
2353         char *s;
2354         int nGameIndex;
2355         int (*pfnGetAuditResults)(int driver_index) = NULL;
2356         void (*pfnSetAuditResults)(int driver_index, int audit_results) = NULL;
2357
2358         switch(HIWORD(wParam))
2359         {
2360            case 0:
2361               pfnGetAuditResults = GetRomAuditResults;
2362               pfnSetAuditResults = SetRomAuditResults;
2363               break;
2364
2365            case 1:
2366               pfnGetAuditResults = GetSampleAuditResults;
2367               pfnSetAuditResults = SetSampleAuditResults;
2368               break;
2369         }
2370
2371         if (pfnGetAuditResults && pfnSetAuditResults)
2372         {
2373            int nParentIndex = -1;
2374
2375            snprintf(szFileName, sizeof(szFileName), "%s", (LPCSTR) lParam);
2376            s = strchr(szFileName, '.');
2377            if (s)
2378               *s = '\0';
2379            s = strchr(szFileName, '\\');
2380            if (s)
2381               *s = '\0';
2382
2383            for (nGameIndex = 0; drivers[nGameIndex]; nGameIndex++)
2384            {
2385               for (nParentIndex = nGameIndex; nGameIndex == -1; nParentIndex = GetParentIndex(drivers[nParentIndex]))
2386               {
2387                  if (!mame_stricmp(drivers[nParentIndex]->name, szFileName))
2388                  {
2389                     if (pfnGetAuditResults(nGameIndex) != UNKNOWN)
2390                     {
2391                        pfnSetAuditResults(nGameIndex, UNKNOWN);
2392                        PostMessage(hMain, WM_MAME32_AUDITGAME, wParam, nGameIndex);
2393                     }
2394                     break;
2395                  }
2396               }
2397            }
2398         }
2399      }
2400      break;
2401
2402   case WM_MAME32_AUDITGAME:
2403      {
2404         LV_FINDINFO lvfi;
2405         int nGameIndex;
2406
2407         nGameIndex = lParam;
2408
2409         switch(HIWORD(wParam))
2410         {
2411            case 0:
2412               Mame32VerifyRomSet(nGameIndex);
2413               break;
2414            case 1:
2415               Mame32VerifySampleSet(nGameIndex);
2416               break;
2417         }
2418
2419         memset(&lvfi, 0, sizeof(lvfi));
2420         lvfi.flags   = LVFI_PARAM;
2421         lvfi.lParam = nGameIndex;
2422
2423         i = ListView_FindItem(hwndList, -1, &lvfi);
2424         if (i != -1)
2425         {
2426            ListView_RedrawItems(hwndList, i, i);
2427         }
2428      }
2429      break;
2430
2431   default:
2432
2433      break;
2434   }
2435
2436   return DefWindowProc(hWnd, message, wParam, lParam);
2437}
2438
2439static int HandleKeyboardGUIMessage(HWND hWnd, UINT message, UINT wParam, LONG lParam)
2440{
2441   switch (message)
2442   {
2443      case WM_CHAR: /* List-View controls use this message for searching the items "as user types" */
2444         //MessageBox(NULL,"wm_char message arrived","TitleBox",MB_OK);
2445         return TRUE;
2446
2447      case WM_KEYDOWN:
2448         KeyboardKeyDown(0, wParam, lParam);
2449         return TRUE;
2450
2451      case WM_KEYUP:
2452         KeyboardKeyUp(0, wParam, lParam);
2453         return TRUE;
2454
2455      case WM_SYSKEYDOWN:
2456         KeyboardKeyDown(1, wParam, lParam);
2457         return TRUE;
2458
2459      case WM_SYSKEYUP:
2460         KeyboardKeyUp(1, wParam, lParam);
2461         return TRUE;
2462   }
2463
2464   return FALSE;   /* message not processed */
2465}
2466
2467static BOOL PumpMessage()
2468{
2469   MSG msg;
2470
2471   if (!GetMessage(&msg, NULL, 0, 0))
2472    {
2473      return FALSE;
2474    }
2475
2476   if (IsWindow(hMain))
2477   {
2478      BOOL absorbed_key = FALSE;
2479      if (GetKeyGUI())
2480         absorbed_key = HandleKeyboardGUIMessage(msg.hwnd, msg.message,
2481                                       msg.wParam, msg.lParam);
2482      else
2483         absorbed_key = TranslateAccelerator(hMain, hAccel, &msg);
2484
2485      if (!absorbed_key)
2486      {
2487         if (!IsDialogMessage(hMain, &msg))
2488         {
2489            TranslateMessage(&msg);
2490            DispatchMessage(&msg);
2491         }
2492      }
2493   }
2494
2495   return TRUE;
2496}
2497
2498static BOOL FolderCheck(void)
2499{
2500   
2501   char *pDescription = NULL;
2502   int nGameIndex = 0;
2503   int i=0;
2504   int iStep = 0;
2505   LV_FINDINFO lvfi;
2506   int nCount = ListView_GetItemCount(hwndList);
2507   BOOL changed = FALSE;
2508
2509   MSG msg;
2510   for(i=0; i<nCount;i++)
2511   {
2512      LV_ITEM lvi;
2513
2514      lvi.iItem = i;
2515      lvi.iSubItem = 0;
2516      lvi.mask    = LVIF_PARAM;
2517      ListView_GetItem(hwndList, &lvi);
2518      nGameIndex  = lvi.lParam;
2519      SetRomAuditResults(nGameIndex, UNKNOWN);
2520      SetSampleAuditResults(nGameIndex, UNKNOWN);
2521   }
2522   if( nCount > 0)
2523      ProgressBarShow();
2524   else
2525      return FALSE;
2526   if( nCount < 100 )
2527      iStep = 100 / nCount;
2528   else
2529      iStep = nCount/100;
2530   UpdateListView();
2531   UpdateWindow(hMain);
2532   for(i=0; i<nCount;i++)
2533   {
2534      LV_ITEM lvi;
2535
2536      lvi.iItem = i;
2537      lvi.iSubItem = 0;
2538      lvi.mask    = LVIF_PARAM;
2539      ListView_GetItem(hwndList, &lvi);
2540      nGameIndex  = lvi.lParam;
2541      if (GetRomAuditResults(nGameIndex) == UNKNOWN)
2542      {
2543         Mame32VerifyRomSet(nGameIndex);
2544         changed = TRUE;
2545      }
2546
2547      if (GetSampleAuditResults(nGameIndex) == UNKNOWN)
2548      {
2549         Mame32VerifySampleSet(nGameIndex);
2550         changed = TRUE;
2551      }
2552
2553      lvfi.flags   = LVFI_PARAM;
2554      lvfi.lParam = nGameIndex;
2555
2556      i = ListView_FindItem(hwndList, -1, &lvfi);
2557      if (changed && i != -1);
2558      {
2559         ListView_RedrawItems(hwndList, i, i);
2560         while( PeekMessage( &msg, hwndList, 0, 0, PM_REMOVE ) != 0)
2561         {
2562            TranslateMessage(&msg);
2563            DispatchMessage(&msg);
2564         }
2565      }
2566      changed = FALSE;
2567      if ((i % iStep) == 0)
2568         ProgressBarStepParam(i, nCount);
2569   }
2570   ProgressBarHide();
2571   pDescription = ModifyThe(drivers[Picker_GetSelectedItem(hwndList)]->description);
2572   SetStatusBarText(0, pDescription);
2573   UpdateStatusBar();
2574   return TRUE;
2575}
2576
2577static BOOL GameCheck(void)
2578{
2579   LV_FINDINFO lvfi;
2580   int i;
2581   BOOL changed = FALSE;
2582
2583   if (game_index == 0)
2584      ProgressBarShow();
2585
2586   if (game_index >= driver_list_get_count(drivers))
2587   {
2588      bDoGameCheck = FALSE;
2589      ProgressBarHide();
2590      ResetWhichGamesInFolders();
2591      return FALSE;
2592   }
2593
2594   if (GetRomAuditResults(game_index) == UNKNOWN)
2595   {
2596      Mame32VerifyRomSet(game_index);
2597      changed = TRUE;
2598   }
2599
2600   if (GetSampleAuditResults(game_index) == UNKNOWN)
2601   {
2602      Mame32VerifySampleSet(game_index);
2603      changed = TRUE;
2604   }
2605
2606   lvfi.flags   = LVFI_PARAM;
2607   lvfi.lParam = game_index;
2608
2609   i = ListView_FindItem(hwndList, -1, &lvfi);
2610   if (changed && i != -1);
2611      ListView_RedrawItems(hwndList, i, i);
2612   if ((game_index % progBarStep) == 0)
2613      ProgressBarStep();
2614   game_index++;
2615
2616   return changed;
2617}
2618
2619static BOOL OnIdle(HWND hWnd)
2620{
2621   static int bFirstTime = TRUE;
2622   static int bResetList = TRUE;
2623
2624   char *pDescription;
2625   int driver_index;
2626
2627   if (bFirstTime)
2628   {
2629      bResetList = FALSE;
2630      bFirstTime = FALSE;
2631   }
2632   if (bDoGameCheck)
2633   {
2634      bResetList |= GameCheck();
2635      return idle_work;
2636   }
2637   // NPW 17-Jun-2003 - Commenting this out because it is redundant
2638   // and it causes the game to reset back to the original game after an F5
2639   // refresh
2640   //driver_index = GetGameNameIndex(GetDefaultGame());
2641   //SetSelectedPickItem(driver_index);
2642
2643   // in case it's not found, get it back
2644   driver_index = Picker_GetSelectedItem(hwndList);
2645
2646   pDescription = ModifyThe(drivers[driver_index]->description);
2647   SetStatusBarText(0, pDescription);
2648   idle_work = FALSE;
2649   UpdateStatusBar();
2650   bFirstTime = TRUE;
2651
2652   if (!idle_work)
2653      PostMessage(GetMainWindow(),WM_COMMAND, MAKEWPARAM(ID_VIEW_LINEUPICONS, TRUE),(LPARAM)NULL);
2654   return idle_work;
2655}
2656
2657static void OnSize(HWND hWnd, UINT nState, int nWidth, int nHeight)
2658{
2659   static BOOL firstTime = TRUE;
2660
2661   if (nState != SIZE_MAXIMIZED && nState != SIZE_RESTORED)
2662      return;
2663
2664   ResizeWindow(hWnd, &main_resize);
2665   ResizeProgressBar();
2666   if (firstTime == FALSE)
2667      OnSizeSplitter(hMain);
2668   //firstTime = FALSE;
2669   /* Update the splitters structures as appropriate */
2670   RecalcSplitters();
2671   if (firstTime == FALSE)
2672      ResizePickerControls(hMain);
2673   firstTime = FALSE;
2674   UpdateScreenShot();
2675}
2676
2677
2678
2679static HWND GetResizeItemWindow(HWND hParent, const ResizeItem *ri)
2680{
2681   HWND hControl;
2682   if (ri->type == RA_ID)
2683      hControl = GetDlgItem(hParent, ri->u.id);
2684   else
2685      hControl = ri->u.hwnd;
2686   return hControl;
2687}
2688
2689
2690
2691static void SetAllWindowsFont(HWND hParent, const Resize *r, HFONT hTheFont, BOOL bRedraw)
2692{
2693   int i;
2694   HWND hControl;
2695
2696   for (i = 0; r->items[i].type != RA_END; i++)
2697   {
2698      if (r->items[i].setfont)
2699      {
2700         hControl = GetResizeItemWindow(hParent, &r->items[i]);
2701         SetWindowFont(hControl, hTheFont, bRedraw);
2702      }
2703   }
2704}
2705
2706
2707
2708static void ResizeWindow(HWND hParent, Resize *r)
2709{
2710   int cmkindex = 0, dx, dy, dx1, dtempx;
2711   HWND hControl;
2712   RECT parent_rect, rect;
2713   ResizeItem *ri;
2714   POINT p = {0, 0};
2715
2716   if (hParent == NULL)
2717      return;
2718
2719   /* Calculate change in width and height of parent window */
2720   GetClientRect(hParent, &parent_rect);
2721   //dx = parent_rect.right - r->rect.right;
2722   dtempx = parent_rect.right - r->rect.right;
2723   dy = parent_rect.bottom - r->rect.bottom;
2724   dx = dtempx/2;
2725   dx1 = dtempx - dx;
2726   ClientToScreen(hParent, &p);
2727
2728   while (r->items[cmkindex].type != RA_END)
2729   {
2730      ri = &r->items[cmkindex];
2731      if (ri->type == RA_ID)
2732         hControl = GetDlgItem(hParent, ri->u.id);
2733      else
2734         hControl = ri->u.hwnd;
2735
2736      if (hControl == NULL)
2737      {
2738         cmkindex++;
2739         continue;
2740      }
2741
2742      /* Get control's rectangle relative to parent */
2743      GetWindowRect(hControl, &rect);
2744      OffsetRect(&rect, -p.x, -p.y);
2745
2746      if (!(ri->action & RA_LEFT))
2747         rect.left += dx;
2748
2749      if (!(ri->action & RA_TOP))
2750         rect.top += dy;
2751
2752      if (ri->action & RA_RIGHT)
2753         rect.right += dx;
2754
2755      if (ri->action & RA_BOTTOM)
2756         rect.bottom += dy;
2757
2758      MoveWindow(hControl, rect.left, rect.top,
2759               (rect.right - rect.left),
2760               (rect.bottom - rect.top), TRUE);
2761
2762      /* Take care of subcontrols, if appropriate */
2763      if (ri->subwindow != NULL)
2764         ResizeWindow(hControl, ri->subwindow);
2765
2766      cmkindex++;
2767   }
2768
2769   /* Record parent window's new location */
2770   memcpy(&r->rect, &parent_rect, sizeof(RECT));
2771}
2772
2773static void ProgressBarShow()
2774{
2775   RECT rect;
2776   int  widths[2] = {150, -1};
2777
2778   if (driver_list_get_count(drivers) < 100)
2779      progBarStep = 100 / driver_list_get_count(drivers);
2780   else
2781      progBarStep = (driver_list_get_count(drivers) / 100);
2782
2783   SendMessage(hStatusBar, SB_SETPARTS, (WPARAM)2, (LPARAM)(LPINT)widths);
2784   SendMessage(hProgWnd, PBM_SETRANGE, 0, (LPARAM)MAKELONG(0, driver_list_get_count(drivers)));
2785   SendMessage(hProgWnd, PBM_SETSTEP, (WPARAM)progBarStep, 0);
2786   SendMessage(hProgWnd, PBM_SETPOS, 0, 0);
2787
2788   StatusBar_GetItemRect(hStatusBar, 1, &rect);
2789
2790   MoveWindow(hProgWnd, rect.left, rect.top,
2791            rect.right - rect.left,
2792            rect.bottom - rect.top, TRUE);
2793
2794   bProgressShown = TRUE;
2795}
2796
2797static void ProgressBarHide()
2798{
2799   RECT rect;
2800   int  widths[4];
2801   HDC  hDC;
2802   SIZE size;
2803   int  numParts = 4;
2804
2805   if (hProgWnd == NULL)
2806   {
2807      return;
2808   }
2809
2810   hDC = GetDC(hProgWnd);
2811
2812   ShowWindow(hProgWnd, SW_HIDE);
2813
2814   GetTextExtentPoint32(hDC, TEXT("MMX"), 3, &size);
2815   widths[3] = size.cx;
2816   GetTextExtentPoint32(hDC, TEXT("MMMM games"), 10, &size);
2817   widths[2] = size.cx;
2818   //Just specify 24 instead of 30, gives us sufficient space to display the message, and saves some space
2819   GetTextExtentPoint32(hDC, TEXT("Screen flip support is missing"), 24, &size);
2820   widths[1] = size.cx;
2821
2822   ReleaseDC(hProgWnd, hDC);
2823
2824   widths[0] = -1;
2825   SendMessage(hStatusBar, SB_SETPARTS, (WPARAM)1, (LPARAM)(LPINT)widths);
2826   StatusBar_GetItemRect(hStatusBar, 0, &rect);
2827
2828   widths[0] = (rect.right - rect.left) - (widths[1] + widths[2] + widths[3]);
2829   widths[1] += widths[0];
2830   widths[2] += widths[1];
2831   widths[3] = -1;
2832
2833   SendMessage(hStatusBar, SB_SETPARTS, (WPARAM)numParts, (LPARAM)(LPINT)widths);
2834   UpdateStatusBar();
2835
2836   bProgressShown = FALSE;
2837}
2838
2839static void ResizeProgressBar()
2840{
2841   if (bProgressShown)
2842   {
2843      RECT rect;
2844      int  widths[2] = {150, -1};
2845
2846      SendMessage(hStatusBar, SB_SETPARTS, (WPARAM)2, (LPARAM)(LPINT)widths);
2847      StatusBar_GetItemRect(hStatusBar, 1, &rect);
2848      MoveWindow(hProgWnd, rect.left, rect.top,
2849               rect.right  - rect.left,
2850               rect.bottom - rect.top, TRUE);
2851   }
2852   else
2853   {
2854      ProgressBarHide();
2855   }
2856}
2857
2858static void ProgressBarStepParam(int iGameIndex, int nGameCount)
2859{
2860   SetStatusBarTextF(0, "Game search %d%% complete",
2861         ((iGameIndex + 1) * 100) / nGameCount);
2862   if (iGameIndex == 0)
2863      ShowWindow(hProgWnd, SW_SHOW);
2864   SendMessage(hProgWnd, PBM_STEPIT, 0, 0);
2865}
2866
2867static void ProgressBarStep()
2868{
2869   ProgressBarStepParam(game_index, driver_list_get_count(drivers));
2870}
2871
2872static HWND InitProgressBar(HWND hParent)
2873{
2874   RECT rect;
2875
2876   StatusBar_GetItemRect(hStatusBar, 0, &rect);
2877
2878   rect.left += 150;
2879
2880   return CreateWindowEx(WS_EX_STATICEDGE,
2881         PROGRESS_CLASS,
2882         TEXT("Progress Bar"),
2883         WS_CHILD | PBS_SMOOTH,
2884         rect.left,
2885         rect.top,
2886         rect.right   - rect.left,
2887         rect.bottom - rect.top,
2888         hParent,
2889         NULL,
2890         hInst,
2891         NULL);
2892}
2893
2894static void CopyToolTipText(LPTOOLTIPTEXT lpttt)
2895{
2896   int   i;
2897   int   iButton = lpttt->hdr.idFrom;
2898   static TCHAR String[1024];
2899   BOOL bConverted = FALSE;
2900   TCHAR* t_gameinfostatus;
2901
2902   /* Map command ID to string index */
2903   for (i = 0; CommandToString[i] != -1; i++)
2904   {
2905      if (CommandToString[i] == iButton)
2906      {
2907         iButton = i;
2908         bConverted = TRUE;
2909         break;
2910      }
2911   }
2912   if( bConverted )
2913   {
2914      /* Check for valid parameter */
2915      if(iButton > NUM_TOOLTIPS)
2916      {
2917         _tcscpy(String,TEXT("Invalid Button Index"));
2918      }
2919      else
2920      {
2921         _tcscpy(String,szTbStrings[iButton]);
2922      }
2923   }
2924   else if ( iButton <= 2 )
2925   {
2926      //Statusbar
2927      SendMessage(lpttt->hdr.hwndFrom, TTM_SETMAXTIPWIDTH, 0, 200);
2928      if( iButton != 1)
2929         SendMessage(hStatusBar, SB_GETTEXT, (WPARAM)iButton, (LPARAM)&String );
2930      else {
2931         //for first pane we get the Status directly, to get the line breaks
2932         t_gameinfostatus = tstring_from_utf8( GameInfoStatus(Picker_GetSelectedItem(hwndList), FALSE));
2933         if( !t_gameinfostatus )
2934            return;
2935         _tcscpy(String, t_gameinfostatus);
2936         free(t_gameinfostatus);
2937      }
2938   }
2939   else
2940      _tcscpy(String,TEXT("Invalid Button Index"));
2941
2942   lpttt->lpszText = String;
2943}
2944
2945static HWND InitToolbar(HWND hParent)
2946{
2947   return CreateToolbarEx(hParent,
2948                     WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS |
2949                     CCS_TOP | TBSTYLE_FLAT | TBSTYLE_TOOLTIPS,
2950                     1,
2951                     8,
2952                     hInst,
2953                     IDB_TOOLBAR,
2954                     tbb,
2955                     NUM_TOOLBUTTONS,
2956                     16,
2957                     16,
2958                     0,
2959                     0,
2960                     sizeof(TBBUTTON));
2961}
2962
2963static HWND InitStatusBar(HWND hParent)
2964{
2965   HMENU hMenu = GetMenu(hParent);
2966
2967   popstr[0].hMenu    = 0;
2968   popstr[0].uiString = 0;
2969   popstr[1].hMenu    = hMenu;
2970   popstr[1].uiString = IDS_UI_FILE;
2971   popstr[2].hMenu    = GetSubMenu(hMenu, 1);
2972   popstr[2].uiString = IDS_UI_TOOLBAR;
2973   popstr[3].hMenu    = 0;
2974   popstr[3].uiString = 0;
2975
2976   return CreateStatusWindow(WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS |
2977                       CCS_BOTTOM | SBARS_SIZEGRIP | SBT_TOOLTIPS,
2978                       TEXT("Ready"),
2979                       hParent,
2980                       2);
2981}
2982
2983
2984static LRESULT Statusbar_MenuSelect(HWND hwnd, WPARAM wParam, LPARAM lParam)
2985{
2986   UINT  fuFlags   = (UINT)HIWORD(wParam);
2987   HMENU hMainMenu = NULL;
2988   int   iMenu    = 0;
2989
2990   /* Handle non-system popup menu descriptions. */
2991   if (  (fuFlags & MF_POPUP)
2992   &&   (!(fuFlags & MF_SYSMENU)))
2993   {
2994      for (iMenu = 1; iMenu < MAX_MENUS; iMenu++)
2995      {
2996         if ((HMENU)lParam == popstr[iMenu].hMenu)
2997         {
2998            hMainMenu = (HMENU)lParam;
2999            break ;
3000         }
3001      }
3002   }
3003
3004   if (hMainMenu)
3005   {
3006      /* Display helpful text in status bar */
3007      MenuHelp(WM_MENUSELECT, wParam, lParam, hMainMenu, hInst,
3008             hStatusBar, (UINT *)&popstr[iMenu]);
3009   }
3010   else
3011   {
3012      UINT nZero = 0;
3013      MenuHelp(WM_MENUSELECT, wParam, lParam, NULL, hInst,
3014             hStatusBar, &nZero);
3015   }
3016
3017   return 0;
3018}
3019
3020static void UpdateStatusBar()
3021{
3022   LPTREEFOLDER lpFolder = GetCurrentFolder();
3023   int        games_shown = 0;
3024   int        i = -1;
3025
3026   if (!lpFolder)
3027      return;
3028
3029   while (1)
3030   {
3031      i = FindGame(lpFolder,i+1);
3032      if (i == -1)
3033         break;
3034
3035      if (!GameFiltered(i, lpFolder->m_dwFlags))
3036         games_shown++;
3037   }
3038
3039   /* Show number of games in the current 'View' in the status bar */
3040   SetStatusBarTextF(2, g_szGameCountString, games_shown);
3041
3042   i = Picker_GetSelectedItem(hwndList);
3043
3044   if (games_shown == 0)
3045      DisableSelection();
3046   else
3047   {
3048      const char* pStatus = GameInfoStatus(i, FALSE);
3049      SetStatusBarText(1, pStatus);
3050   }
3051}
3052
3053static void UpdateHistory(void)
3054{
3055   HDC hDC;
3056   RECT rect;
3057   TEXTMETRIC     tm ;
3058   int nLines, nLineHeight;
3059   //DWORD dwStyle = GetWindowLong(GetDlgItem(hMain, IDC_HISTORY), GWL_STYLE);
3060   have_history = FALSE;
3061
3062   if (GetSelectedPick() >= 0)
3063   {
3064      char *histText = GetGameHistory(Picker_GetSelectedItem(hwndList));
3065
3066      have_history = (histText && histText[0]) ? TRUE : FALSE;
3067      win_set_window_text_utf8(GetDlgItem(hMain, IDC_HISTORY), histText);
3068   }
3069
3070   if (have_history && GetShowScreenShot()
3071      && ((TabView_GetCurrentTab(hTabCtrl) == TAB_HISTORY) ||
3072         (TabView_GetCurrentTab(hTabCtrl) == GetHistoryTab() && GetShowTab(TAB_HISTORY) == FALSE) ||
3073         (TAB_ALL == GetHistoryTab() && GetShowTab(TAB_HISTORY) == FALSE) ))
3074   {
3075      Edit_GetRect(GetDlgItem(hMain, IDC_HISTORY),&rect);
3076      nLines = Edit_GetLineCount(GetDlgItem(hMain, IDC_HISTORY) );
3077      hDC = GetDC(GetDlgItem(hMain, IDC_HISTORY));
3078      GetTextMetrics (hDC, &tm);
3079      nLineHeight = tm.tmHeight - tm.tmInternalLeading;
3080      if( ( (rect.bottom - rect.top) / nLineHeight) < (nLines) )
3081      {
3082         //more than one Page, so show Scrollbar
3083         SetScrollRange(GetDlgItem(hMain, IDC_HISTORY), SB_VERT, 0, nLines, TRUE);
3084      }
3085      else
3086      {
3087         //hide Scrollbar
3088         SetScrollRange(GetDlgItem(hMain, IDC_HISTORY),SB_VERT, 0, 0, TRUE);
3089
3090      }
3091       ShowWindow(GetDlgItem(hMain, IDC_HISTORY), SW_SHOW);
3092   }
3093   else
3094      ShowWindow(GetDlgItem(hMain, IDC_HISTORY), SW_HIDE);
3095
3096}
3097
3098
3099static void DisableSelection()
3100{
3101   MENUITEMINFO   mmi;
3102   HMENU         hMenu = GetMenu(hMain);
3103   BOOL         prev_have_selection = have_selection;
3104
3105   mmi.cbSize      = sizeof(mmi);
3106   mmi.fMask      = MIIM_TYPE;
3107   mmi.fType      = MFT_STRING;
3108   mmi.dwTypeData = (TCHAR *) TEXT("&Play");
3109   mmi.cch       = _tcslen(mmi.dwTypeData);
3110   SetMenuItemInfo(hMenu, ID_FILE_PLAY, FALSE, &mmi);
3111
3112   EnableMenuItem(hMenu, ID_FILE_PLAY,          MF_GRAYED);
3113   EnableMenuItem(hMenu, ID_FILE_PLAY_RECORD,      MF_GRAYED);
3114   EnableMenuItem(hMenu, ID_GAME_PROPERTIES,      MF_GRAYED);
3115
3116   SetStatusBarText(0, "No Selection");
3117   SetStatusBarText(1, "");
3118   SetStatusBarText(3, "");
3119
3120   have_selection = FALSE;
3121
3122   if (prev_have_selection != have_selection)
3123      UpdateScreenShot();
3124}
3125
3126static void EnableSelection(int nGame)
3127{
3128   TCHAR         buf[200];
3129   const char *   pText;
3130   MENUITEMINFO   mmi;
3131   HMENU         hMenu = GetMenu(hMain);
3132   TCHAR*          t_description;
3133
3134#ifdef MESS
3135   MyFillSoftwareList(nGame, FALSE);
3136#endif
3137
3138   t_description = tstring_from_utf8(ConvertAmpersandString(ModifyThe(drivers[nGame]->description)));
3139   if( !t_description )
3140      return;
3141
3142   _sntprintf(buf, sizeof(buf) / sizeof(buf[0]), g_szPlayGameString, t_description);
3143   mmi.cbSize      = sizeof(mmi);
3144   mmi.fMask      = MIIM_TYPE;
3145   mmi.fType      = MFT_STRING;
3146   mmi.dwTypeData = buf;
3147   mmi.cch       = _tcslen(mmi.dwTypeData);
3148   SetMenuItemInfo(hMenu, ID_FILE_PLAY, FALSE, &mmi);
3149
3150   pText = ModifyThe(drivers[nGame]->description);
3151   SetStatusBarText(0, pText);
3152   /* Add this game's status to the status bar */
3153   pText = GameInfoStatus(nGame, FALSE);
3154   SetStatusBarText(1, pText);
3155   SetStatusBarText(3, "");
3156
3157   /* If doing updating game status and the game name is NOT pacman.... */
3158
3159   EnableMenuItem(hMenu, ID_FILE_PLAY,          MF_ENABLED);
3160   EnableMenuItem(hMenu, ID_FILE_PLAY_RECORD,      MF_ENABLED);
3161
3162   if (!oldControl)
3163      EnableMenuItem(hMenu, ID_GAME_PROPERTIES, MF_ENABLED);
3164
3165   if (bProgressShown && bListReady == TRUE)
3166   {
3167      SetDefaultGame(ModifyThe(drivers[nGame]->name));
3168   }
3169   have_selection = TRUE;
3170
3171   UpdateScreenShot();
3172
3173   free(t_description);
3174}
3175
3176static void PaintBackgroundImage(HWND hWnd, HRGN hRgn, int x, int y)
3177{
3178   RECT      rcClient;
3179   HRGN      rgnBitmap;
3180   HPALETTE   hPAL;
3181   HDC       hDC = GetDC(hWnd);
3182   int       i, j;
3183   HDC       htempDC;
3184   HBITMAP    oldBitmap;
3185
3186   /* x and y are offsets within the background image that should be at 0,0 in hWnd */
3187
3188   /* So we don't paint over the control's border */
3189   GetClientRect(hWnd, &rcClient);
3190
3191   htempDC = CreateCompatibleDC(hDC);
3192   oldBitmap = SelectObject(htempDC, hBackground);
3193
3194   if (hRgn == NULL)
3195   {
3196      /* create a region of our client area */
3197      rgnBitmap = CreateRectRgnIndirect(&rcClient);
3198      SelectClipRgn(hDC, rgnBitmap);
3199      DeleteObject(rgnBitmap);
3200   }
3201   else
3202   {
3203      /* use the passed in region */
3204      SelectClipRgn(hDC, hRgn);
3205   }
3206
3207   hPAL = GetBackgroundPalette();
3208   if (hPAL == NULL)
3209      hPAL = CreateHalftonePalette(hDC);
3210
3211   if (GetDeviceCaps(htempDC, RASTERCAPS) & RC_PALETTE && hPAL != NULL)
3212   {
3213      SelectPalette(htempDC, hPAL, FALSE);
3214      RealizePalette(htempDC);
3215   }
3216
3217   for (i = rcClient.left-x; i < rcClient.right; i += bmDesc.bmWidth)
3218      for (j = rcClient.top-y; j < rcClient.bottom; j += bmDesc.bmHeight)
3219         BitBlt(hDC, i, j, bmDesc.bmWidth, bmDesc.bmHeight, htempDC, 0, 0, SRCCOPY);
3220   
3221   SelectObject(htempDC, oldBitmap);
3222   DeleteDC(htempDC);
3223   
3224   if (GetBackgroundPalette() == NULL)
3225   {
3226      DeleteObject(hPAL);
3227      hPAL = NULL;
3228   }
3229
3230   ReleaseDC(hWnd, hDC);
3231}
3232
3233static LPCSTR GetCloneParentName(int nItem)
3234{
3235   int nParentIndex = -1;
3236
3237   if (DriverIsClone(nItem) == TRUE)
3238   {
3239      nParentIndex = GetParentIndex(drivers[nItem]);
3240      if( nParentIndex >= 0)
3241         return ModifyThe(drivers[nParentIndex]->description);
3242   }
3243   return "";
3244}
3245
3246static BOOL PickerHitTest(HWND hWnd)
3247{
3248   RECT         rect;
3249   POINTS         p;
3250   DWORD         res = GetMessagePos();
3251   LVHITTESTINFO   htInfo;
3252
3253    ZeroMemory(&htInfo,sizeof(LVHITTESTINFO));
3254   p = MAKEPOINTS(res);
3255   GetWindowRect(hWnd, &rect);
3256   htInfo.pt.x = p.x - rect.left;
3257   htInfo.pt.y = p.y - rect.top;
3258   ListView_HitTest(hWnd, &htInfo);
3259
3260   return (! (htInfo.flags & LVHT_NOWHERE));
3261}
3262
3263static BOOL TreeViewNotify(LPNMHDR nm)
3264{
3265   switch (nm->code)
3266   {
3267   case TVN_SELCHANGED :
3268   {
3269      HTREEITEM hti = TreeView_GetSelection(hTreeView);
3270      TVITEM     tvi;
3271
3272      tvi.mask  = TVIF_PARAM | TVIF_HANDLE;
3273      tvi.hItem = hti;
3274     
3275      if (TreeView_GetItem(hTreeView, &tvi))
3276      {
3277         SetCurrentFolder((LPTREEFOLDER)tvi.lParam);
3278         if (bListReady)
3279         {
3280            ResetListView();
3281            UpdateScreenShot();
3282         }
3283      }
3284      return TRUE;
3285   }
3286   case TVN_BEGINLABELEDIT :
3287   {
3288      TV_DISPINFO *ptvdi = (TV_DISPINFO *)nm;
3289      LPTREEFOLDER folder = (LPTREEFOLDER)ptvdi->item.lParam;
3290
3291      if (folder->m_dwFlags & F_CUSTOM)
3292      {
3293         // user can edit custom folder names
3294         g_in_treeview_edit = TRUE;
3295         return FALSE;
3296      }
3297      // user can't edit built in folder names
3298      return TRUE;
3299   }
3300   case TVN_ENDLABELEDIT :
3301   {
3302      TV_DISPINFO *ptvdi = (TV_DISPINFO *)nm;
3303      LPTREEFOLDER folder = (LPTREEFOLDER)ptvdi->item.lParam;
3304      char* szText;
3305      BOOL result;
3306
3307      g_in_treeview_edit = FALSE;
3308
3309      if (ptvdi->item.pszText == NULL || _tcslen(ptvdi->item.pszText) == 0)
3310         return FALSE;
3311         
3312      szText = utf8_from_tstring(ptvdi->item.pszText);
3313      if( !szText )
3314         return FALSE;
3315
3316      result = TryRenameCustomFolder(folder,szText);
3317     
3318      free(szText);
3319     
3320      return result;
3321   }
3322   }
3323   return FALSE;
3324}
3325
3326
3327
3328static void GamePicker_OnHeaderContextMenu(POINT pt, int nColumn)
3329{
3330   // Right button was clicked on header
3331   HMENU hMenuLoad;
3332   HMENU hMenu;
3333
3334   hMenuLoad = LoadMenu(hInst, MAKEINTRESOURCE(IDR_CONTEXT_HEADER));
3335   hMenu = GetSubMenu(hMenuLoad, 0);
3336   lastColumnClick = nColumn;
3337   TrackPopupMenu(hMenu,TPM_LEFTALIGN | TPM_RIGHTBUTTON,pt.x,pt.y,0,hMain,NULL);
3338
3339   DestroyMenu(hMenuLoad);
3340}
3341
3342
3343
3344char* ConvertAmpersandString(const char *s)
3345{
3346   /* takes a string and changes any ampersands to double ampersands,
3347      for setting text of window controls that don't allow us to disable
3348      the ampersand underlining.
3349    */
3350   /* returns a static buffer--use before calling again */
3351
3352   static char buf[200];
3353   char *ptr;
3354
3355   ptr = buf;
3356   while (*s)
3357   {
3358      if (*s == '&')
3359         *ptr++ = *s;
3360      *ptr++ = *s++;
3361   }
3362   *ptr = 0;
3363
3364   return buf;
3365}
3366
3367static int GUI_seq_pressed(const input_seq *seq)
3368{
3369   int codenum;
3370   int res = 1;
3371   int invert = 0;
3372   int count = 0;
3373
3374   for (codenum = 0; codenum < ARRAY_LENGTH(seq->code); codenum++)
3375   {
3376      input_code code = seq->code[codenum];
3377
3378      switch (code)
3379      {
3380         case SEQCODE_OR :
3381            if (res && count)
3382               return 1;
3383            res = 1;
3384            count = 0;
3385            break;
3386         case SEQCODE_NOT :
3387            invert = !invert;
3388            break;
3389         default:
3390            if (res)
3391            {
3392               int pressed = keyboard_state[code];
3393               if ((pressed != 0) == invert)
3394                  res = 0;
3395            }
3396            invert = 0;
3397            ++count;
3398      }
3399   }
3400   return res && count;
3401}
3402
3403static void check_for_GUI_action(void)
3404{
3405   int i;
3406
3407   for (i = 0; i < NUM_GUI_SEQUENCES; i++)
3408   {
3409      input_seq *is = &(GUISequenceControl[i].is);
3410
3411      if (GUI_seq_pressed(is))
3412      {
3413         dprintf("seq =%s pressed\n", GUISequenceControl[i].name);
3414         switch (GUISequenceControl[i].func_id)
3415         {
3416         case ID_GAME_AUDIT:
3417         case ID_GAME_PROPERTIES:
3418         case ID_CONTEXT_FILTERS:
3419         case ID_UI_START:
3420            KeyboardStateClear(); /* beacuse whe won't receive KeyUp mesage when we loose focus */
3421            break;
3422         default:
3423            break;
3424         }
3425         SendMessage(hMain, WM_COMMAND, GUISequenceControl[i].func_id, 0);
3426      }
3427   }
3428}
3429
3430static void KeyboardStateClear(void)
3431{
3432   memset(keyboard_state, 0, sizeof(keyboard_state));
3433   dprintf("keyboard gui state cleared.\n");
3434}
3435
3436
3437static void KeyboardKeyDown(int syskey, int vk_code, int special)
3438{
3439   int i, found = 0;
3440   input_code icode = 0;
3441   int special_code = (special >> 24) & 1;
3442   int scancode = (special>>16) & 0xff;
3443
3444   if ((vk_code==VK_MENU) || (vk_code==VK_CONTROL) || (vk_code==VK_SHIFT))
3445   {
3446      found = 1;
3447
3448      /* a hack for right shift - it's better to use Direct X for keyboard input it seems......*/
3449      if (vk_code==VK_SHIFT)
3450         if (scancode>0x30) /* on my keyboard left shift scancode is 0x2a, right shift is 0x36 */
3451            special_code = 1;
3452
3453      if (special_code) /* right hand keys */
3454      {
3455         switch(vk_code)
3456         {
3457         case VK_MENU:
3458            icode = KEYCODE_RALT;
3459            break;
3460         case VK_CONTROL:
3461            icode = KEYCODE_RCONTROL;
3462            break;
3463         case VK_SHIFT:
3464            icode = KEYCODE_RSHIFT;
3465            break;
3466         }
3467      }
3468      else /* left hand keys */
3469      {
3470         switch(vk_code)
3471         {
3472         case VK_MENU:
3473            icode = KEYCODE_LALT;
3474            break;
3475         case VK_CONTROL:
3476            icode = KEYCODE_LCONTROL;
3477            break;
3478         case VK_SHIFT:
3479            icode = KEYCODE_LSHIFT;
3480            break;
3481         }
3482      }
3483   }
3484   else
3485   {
3486      for (i = 0; i < ARRAY_LENGTH(win_key_trans_table); i++)
3487      {
3488         if ( vk_code == win_key_trans_table[i][VIRTUAL_KEY])
3489         {
3490            icode = win_key_trans_table[i][MAME_KEY];
3491            found = 1;
3492            break;
3493         }
3494      }
3495   }
3496   if (!found)
3497   {
3498      dprintf("VK_code pressed not found =  %i\n",vk_code);
3499      //MessageBox(NULL,"keydown message arrived not processed","TitleBox",MB_OK);
3500      return;
3501   }
3502   dprintf("VK_code pressed found =  %i, sys=%i, mame_keycode=%i special=%08x\n", vk_code, syskey, icode, special);
3503   keyboard_state[icode] = 1;
3504   check_for_GUI_action();
3505}
3506
3507static void KeyboardKeyUp(int syskey, int vk_code, int special)
3508{
3509   int i, found = 0;
3510   input_code icode = 0;
3511   int special_code = (special >> 24) & 1;
3512   int scancode = (special>>16) & 0xff;
3513
3514   if ((vk_code==VK_MENU) || (vk_code==VK_CONTROL) || (vk_code==VK_SHIFT))
3515   {
3516      found = 1;
3517
3518      /* a hack for right shift - it's better to use Direct X for keyboard input it seems......*/
3519      if (vk_code==VK_SHIFT)
3520         if (scancode>0x30) /* on my keyboard left shift scancode is 0x2a, right shift is 0x36 */
3521            special_code = 1;
3522
3523      if (special_code) /* right hand keys */
3524      {
3525         switch(vk_code)
3526         {
3527         case VK_MENU:
3528            icode = KEYCODE_RALT;
3529            break;
3530         case VK_CONTROL:
3531            icode = KEYCODE_RCONTROL;
3532            break;
3533         case VK_SHIFT:
3534            icode = KEYCODE_RSHIFT;
3535            break;
3536         }
3537      }
3538      else /* left hand keys */
3539      {
3540         switch(vk_code)
3541         {
3542         case VK_MENU:
3543            icode = KEYCODE_LALT;
3544            break;
3545         case VK_CONTROL:
3546            icode = KEYCODE_LCONTROL;
3547            break;
3548         case VK_SHIFT:
3549            icode = KEYCODE_LSHIFT;
3550            break;
3551         }
3552      }
3553   }
3554   else
3555   {
3556      for (i = 0; i < ARRAY_LENGTH(win_key_trans_table); i++)
3557      {
3558         if (vk_code == win_key_trans_table[i][VIRTUAL_KEY])
3559         {
3560            icode = win_key_trans_table[i][MAME_KEY];
3561            found = 1;
3562            break;
3563         }
3564      }
3565   }
3566   if (!found)
3567   {
3568      dprintf("VK_code released not found =  %i",vk_code);
3569      //MessageBox(NULL,"keyup message arrived not processed","TitleBox",MB_OK);
3570      return;
3571   }
3572   keyboard_state[icode] = 0;
3573   dprintf("VK_code released found=  %i, sys=%i, mame_keycode=%i special=%08x\n", vk_code, syskey, icode, special );
3574   check_for_GUI_action();
3575}
3576
3577static void PollGUIJoystick()
3578{
3579   // For the exec timer, will keep track of how long the button has been pressed 
3580   static int exec_counter = 0;
3581   const char* exec_command;
3582   TCHAR* t_exec_command;
3583 
3584   if (in_emulation)
3585      return;
3586
3587   if (g_pJoyGUI == NULL)
3588      return;
3589
3590   g_pJoyGUI->poll_joysticks();
3591
3592
3593   // User pressed UP
3594   if (g_pJoyGUI->is_joy_pressed(JOYCODE(GetUIJoyUp(0), GetUIJoyUp(1), GetUIJoyUp(2),GetUIJoyUp(3))))
3595   {
3596      SendMessage(hMain, WM_COMMAND, ID_UI_UP, 0);
3597   }
3598   
3599   // User pressed DOWN
3600   if (g_pJoyGUI->is_joy_pressed(JOYCODE(GetUIJoyDown(0), GetUIJoyDown(1), GetUIJoyDown(2),GetUIJoyDown(3))))
3601   {
3602      SendMessage(hMain, WM_COMMAND, ID_UI_DOWN, 0);
3603   }
3604   
3605   // User pressed LEFT
3606   if (g_pJoyGUI->is_joy_pressed(JOYCODE(GetUIJoyLeft(0), GetUIJoyLeft(1), GetUIJoyLeft(2),GetUIJoyLeft(3))))
3607   {
3608      SendMessage(hMain, WM_COMMAND, ID_UI_LEFT, 0);
3609   }
3610
3611   // User pressed RIGHT
3612   if (g_pJoyGUI->is_joy_pressed(JOYCODE(GetUIJoyRight(0), GetUIJoyRight(1), GetUIJoyRight(2),GetUIJoyRight(3))))
3613   {
3614      SendMessage(hMain, WM_COMMAND, ID_UI_RIGHT, 0);
3615   }
3616
3617   // User pressed START GAME
3618   if (g_pJoyGUI->is_joy_pressed(JOYCODE(GetUIJoyStart(0), GetUIJoyStart(1), GetUIJoyStart(2),GetUIJoyStart(3))))
3619   {
3620      SendMessage(hMain, WM_COMMAND, ID_UI_START, 0);
3621   }
3622
3623   // User pressed PAGE UP
3624   if (g_pJoyGUI->is_joy_pressed(JOYCODE(GetUIJoyPageUp(0), GetUIJoyPageUp(1), GetUIJoyPageUp(2),GetUIJoyPageUp(3))))
3625   {
3626      SendMessage(hMain, WM_COMMAND, ID_UI_PGUP, 0);
3627   }
3628
3629   // User pressed PAGE DOWN
3630   if (g_pJoyGUI->is_joy_pressed(JOYCODE(GetUIJoyPageDown(0), GetUIJoyPageDown(1), GetUIJoyPageDown(2),GetUIJoyPageDown(3))))
3631   {
3632      SendMessage(hMain, WM_COMMAND, ID_UI_PGDOWN, 0);
3633   }
3634
3635   // User pressed HOME
3636   if (g_pJoyGUI->is_joy_pressed(JOYCODE(GetUIJoyHome(0), GetUIJoyHome(1), GetUIJoyHome(2),GetUIJoyHome(3))))
3637   {
3638      SendMessage(hMain, WM_COMMAND, ID_UI_HOME, 0);
3639   }
3640
3641   // User pressed END
3642   if (g_pJoyGUI->is_joy_pressed(JOYCODE(GetUIJoyEnd(0), GetUIJoyEnd(1), GetUIJoyEnd(2),GetUIJoyEnd(3))))
3643   {
3644      SendMessage(hMain, WM_COMMAND, ID_UI_END, 0);
3645   }
3646
3647   // User pressed CHANGE SCREENSHOT
3648   if (g_pJoyGUI->is_joy_pressed(JOYCODE(GetUIJoySSChange(0), GetUIJoySSChange(1), GetUIJoySSChange(2),GetUIJoySSChange(3))))
3649   {
3650      SendMessage(hMain, WM_COMMAND, IDC_SSFRAME, 0);
3651   }
3652   
3653   // User pressed SCROLL HISTORY UP
3654   if (g_pJoyGUI->is_joy_pressed(JOYCODE(GetUIJoyHistoryUp(0), GetUIJoyHistoryUp(1), GetUIJoyHistoryUp(2),GetUIJoyHistoryUp(3))))
3655   {
3656      SendMessage(hMain, WM_COMMAND, ID_UI_HISTORY_UP, 0);
3657   }
3658   
3659   // User pressed SCROLL HISTORY DOWN
3660   if (g_pJoyGUI->is_joy_pressed(JOYCODE(GetUIJoyHistoryDown(0), GetUIJoyHistoryDown(1), GetUIJoyHistoryDown(2),GetUIJoyHistoryDown(3))))
3661   {
3662      SendMessage(hMain, WM_COMMAND, ID_UI_HISTORY_DOWN, 0);
3663   }
3664 
3665  // User pressed EXECUTE COMMANDLINE
3666   if (g_pJoyGUI->is_joy_pressed(JOYCODE(GetUIJoyExec(0), GetUIJoyExec(1), GetUIJoyExec(2),GetUIJoyExec(3))))
3667   {
3668      if (++exec_counter >= GetExecWait()) // Button has been pressed > exec timeout
3669      {
3670         PROCESS_INFORMATION pi;
3671         STARTUPINFO si;
3672         
3673         // Reset counter
3674         exec_counter = 0;
3675
3676         ZeroMemory( &si, sizeof(si) );
3677         ZeroMemory( &pi, sizeof(pi) );
3678         si.dwFlags = STARTF_FORCEONFEEDBACK;
3679         si.cb = sizeof(si);
3680         
3681         exec_command = GetExecCommand();
3682         t_exec_command = tstring_from_utf8(exec_command);
3683         if( !t_exec_command )
3684            return;
3685         CreateProcess(NULL, t_exec_command, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
3686         
3687         free(t_exec_command);
3688
3689         // We will not wait for the process to finish cause it might be a background task
3690         // The process won't get closed when MAME32 closes either.
3691
3692         // But close the handles cause we won't need them anymore. Will not close process.
3693         CloseHandle(pi.hProcess);
3694         CloseHandle(pi.hThread);
3695      }
3696   }
3697   else
3698   {
3699      // Button has been released within the timeout period, reset the counter
3700      exec_counter = 0;
3701   }
3702}
3703
3704static void PressKey(HWND hwnd, UINT vk)
3705{
3706   SendMessage(hwnd, WM_KEYDOWN, vk, 0);
3707   SendMessage(hwnd, WM_KEYUP,   vk, 0xc0000000);
3708}
3709
3710static void SetView(int menu_id)
3711{
3712   BOOL force_reset = FALSE;
3713   int i;
3714
3715   // first uncheck previous menu item, check new one
3716   CheckMenuRadioItem(GetMenu(hMain), ID_VIEW_LARGE_ICON, ID_VIEW_GROUPED, menu_id, MF_CHECKED);
3717   ToolBar_CheckButton(hToolBar, menu_id, MF_CHECKED);
3718
3719   if (Picker_GetViewID(hwndList) == VIEW_GROUPED || menu_id == ID_VIEW_GROUPED)
3720   {
3721      // this changes the sort order, so redo everything
3722      force_reset = TRUE;
3723   }
3724
3725   for (i = 0; i < sizeof(s_nPickers) / sizeof(s_nPickers[0]); i++)
3726      Picker_SetViewID(GetDlgItem(hMain, s_nPickers[i]), menu_id - ID_VIEW_LARGE_ICON);
3727
3728   if (force_reset)
3729   {
3730      for (i = 0; i < sizeof(s_nPickers) / sizeof(s_nPickers[0]); i++)
3731         Picker_Sort(GetDlgItem(hMain, s_nPickers[i]));
3732   }
3733}
3734
3735static void ResetListView()
3736{
3737   int    i;
3738   int    current_game;
3739   LV_ITEM lvi;
3740   BOOL   no_selection = FALSE;
3741   LPTREEFOLDER lpFolder = GetCurrentFolder();
3742
3743   if (!lpFolder)
3744    {
3745      return;
3746    }
3747
3748   /* If the last folder was empty, no_selection is TRUE */
3749   if (have_selection == FALSE)
3750    {
3751      no_selection = TRUE;
3752    }
3753
3754   current_game = Picker_GetSelectedItem(hwndList);
3755
3756   SetWindowRedraw(hwndList,FALSE);
3757
3758   ListView_DeleteAllItems(hwndList);
3759
3760   // hint to have it allocate it all at once
3761   ListView_SetItemCount(hwndList,driver_list_get_count(drivers));
3762
3763   lvi.mask = LVIF_TEXT | LVIF_IMAGE | LVIF_PARAM;
3764   lvi.stateMask = 0;
3765
3766   i = -1;
3767
3768   do
3769   {
3770      /* Add the games that are in this folder */
3771      if ((i = FindGame(lpFolder, i + 1)) != -1)
3772      {
3773         if (GameFiltered(i, lpFolder->m_dwFlags))
3774            continue;
3775
3776         lvi.iItem    = i;
3777         lvi.iSubItem = 0;
3778         lvi.lParam    = i;
3779         lvi.pszText  = LPSTR_TEXTCALLBACK;
3780         lvi.iImage    = I_IMAGECALLBACK;
3781         ListView_InsertItem(hwndList, &lvi);
3782      }
3783   } while (i != -1);
3784
3785   Picker_Sort(hwndList);
3786
3787   if (bListReady)
3788   {
3789       /* If last folder was empty, select the first item in this folder */
3790       if (no_selection)
3791          Picker_SetSelectedPick(hwndList, 0);
3792      else
3793          Picker_SetSelectedItem(hwndList, current_game);
3794   }
3795
3796   /*RS Instead of the Arrange Call that was here previously on all Views
3797       We now need to set the ViewMode for SmallIcon again,
3798       for an explanation why, see SetView*/
3799   if (GetViewMode() == VIEW_SMALL_ICONS)
3800      SetView(ID_VIEW_SMALL_ICON);
3801
3802   SetWindowRedraw(hwndList, TRUE);
3803
3804   UpdateStatusBar();
3805
3806}
3807
3808static void UpdateGameList(BOOL bUpdateRomAudit, BOOL bUpdateSampleAudit)
3809{
3810   int i;
3811
3812   for (i = 0; i < driver_list_get_count(drivers); i++)
3813   {
3814      if (bUpdateRomAudit && DriverUsesRoms(i))
3815         SetRomAuditResults(i, UNKNOWN);
3816      if (bUpdateSampleAudit && DriverUsesSamples(i))
3817         SetSampleAuditResults(i, UNKNOWN);
3818   }
3819
3820   idle_work    = TRUE;
3821   bDoGameCheck = TRUE;
3822   game_index    = 0;
3823
3824   ReloadIcons();
3825
3826   // Let REFRESH also load new background if found
3827   LoadBackgroundBitmap();
3828   InvalidateRect(hMain,NULL,TRUE);
3829   Picker_ResetIdle(hwndList);
3830}
3831
3832UINT_PTR CALLBACK CFHookProc(
3833  HWND hdlg,      // handle to dialog box
3834  UINT uiMsg,     // message identifier
3835  WPARAM wParam,  // message parameter
3836  LPARAM lParam   // message parameter
3837)
3838{
3839   int iIndex, i;
3840   COLORREF cCombo, cList;
3841   switch (uiMsg)
3842   {
3843      case WM_INITDIALOG:
3844         SendDlgItemMessage(hdlg, cmb4, CB_ADDSTRING, 0, (LPARAM)TEXT("Custom"));
3845         iIndex = SendDlgItemMessage(hdlg, cmb4, CB_GETCOUNT, 0, 0);
3846         cList = GetListFontColor();
3847         SendDlgItemMessage(hdlg, cmb4, CB_SETITEMDATA,(WPARAM)iIndex-1,(LPARAM)cList );
3848         for( i = 0; i< iIndex; i++)
3849         {
3850            cCombo = SendDlgItemMessage(hdlg, cmb4, CB_GETITEMDATA,(WPARAM)i,0 );
3851            if( cList == cCombo)
3852            {
3853               SendDlgItemMessage(hdlg, cmb4, CB_SETCURSEL,(WPARAM)i,0 );
3854               break;
3855            }
3856         }
3857         break;
3858      case WM_COMMAND:
3859         if( LOWORD(wParam) == cmb4)
3860         {
3861            switch (HIWORD(wParam))
3862            {
3863               case CBN_SELCHANGE:  // The color ComboBox changed selection
3864                  iIndex = (int)SendDlgItemMessage(hdlg, cmb4,
3865                                         CB_GETCURSEL, 0, 0L);
3866                  if( iIndex == SendDlgItemMessage(hdlg, cmb4, CB_GETCOUNT, 0, 0)-1)
3867                  {
3868                     //Custom color selected
3869                      cList = GetListFontColor();
3870                      PickColor(&cList);
3871                     SendDlgItemMessage(hdlg, cmb4, CB_DELETESTRING, iIndex, 0);
3872                     SendDlgItemMessage(hdlg, cmb4, CB_ADDSTRING, 0, (LPARAM)TEXT("Custom"));
3873                     SendDlgItemMessage(hdlg, cmb4, CB_SETITEMDATA,(WPARAM)iIndex,(LPARAM)cList);
3874                     SendDlgItemMessage(hdlg, cmb4, CB_SETCURSEL,(WPARAM)iIndex,0 );
3875                     return TRUE;
3876                  }
3877            }
3878         }
3879         break;
3880   }
3881   return FALSE;
3882}
3883
3884static void PickFont(void)
3885{
3886   LOGFONT font;
3887   CHOOSEFONT cf;
3888   TCHAR szClass[128];
3889   HWND hWnd;
3890
3891   GetListFont(&font);
3892   font.lfQuality = DEFAULT_QUALITY;
3893
3894   cf.lStructSize = sizeof(CHOOSEFONT);
3895   cf.hwndOwner   = hMain;
3896   cf.lpLogFont   = &font;
3897   cf.lpfnHook = &CFHookProc;
3898   cf.rgbColors   = GetListFontColor();
3899   cf.Flags      = CF_SCREENFONTS | CF_INITTOLOGFONTSTRUCT | CF_EFFECTS | CF_ENABLEHOOK;
3900   if (!ChooseFont(&cf))
3901      return;
3902
3903   SetListFont(&font);
3904   if (hFont != NULL)
3905      DeleteObject(hFont);
3906   hFont = CreateFontIndirect(&font);
3907   if (hFont != NULL)
3908   {
3909      COLORREF textColor = cf.rgbColors;
3910
3911      if (textColor == RGB(255,255,255))
3912      {
3913         textColor = RGB(240, 240, 240);
3914      }
3915
3916      SetAllWindowsFont(hMain, &main_resize, hFont, TRUE);
3917
3918      hWnd = GetWindow(hMain, GW_CHILD);
3919      while(hWnd)
3920      {
3921         if (GetClassName(hWnd, szClass, sizeof(szClass) / sizeof(szClass[0])))
3922         {
3923            if (!_tcscmp(szClass, TEXT("SysListView32")))
3924            {
3925               ListView_SetTextColor(hWnd, textColor);
3926            }
3927            else if (!_tcscmp(szClass, TEXT("SysTreeView32")))
3928            {
3929               TreeView_SetTextColor(hTreeView, textColor);
3930            }
3931         }
3932         hWnd = GetWindow(hWnd, GW_HWNDNEXT);
3933      }
3934      SetListFontColor(cf.rgbColors);
3935      ResetListView();
3936   }
3937}
3938
3939static void PickColor(COLORREF *cDefault)
3940{
3941    CHOOSECOLOR cc;
3942    COLORREF choice_colors[16];
3943    int i;
3944   
3945    for (i=0;i<16;i++)
3946       choice_colors[i] = GetCustomColor(i);
3947 
3948    cc.lStructSize = sizeof(CHOOSECOLOR);
3949    cc.hwndOwner   = hMain;
3950    cc.rgbResult   = *cDefault;
3951    cc.lpCustColors = choice_colors;
3952    cc.Flags       = CC_ANYCOLOR | CC_RGBINIT | CC_SOLIDCOLOR;
3953    if (!ChooseColor(&cc))
3954       return;
3955    for (i=0;i<16;i++)
3956       SetCustomColor(i,choice_colors[i]);
3957    *cDefault = cc.rgbResult;
3958}
3959 
3960static void PickCloneColor(void)
3961{
3962    COLORREF cClonecolor;
3963    cClonecolor = GetListCloneColor();
3964    PickColor( &cClonecolor);
3965    SetListCloneColor(cClonecolor);
3966    InvalidateRect(hwndList,NULL,FALSE);
3967}
3968 
3969static BOOL MameCommand(HWND hwnd,int id, HWND hwndCtl, UINT codeNotify)
3970{
3971   int i;
3972   LPTREEFOLDER folder;
3973   char* t_szFile;
3974   
3975   switch (id)
3976   {
3977   case ID_FILE_PLAY:
3978      MamePlayGame();
3979      return TRUE;
3980
3981   case ID_FILE_PLAY_RECORD:
3982      MamePlayRecordGame();
3983      return TRUE;
3984
3985   case ID_FILE_PLAY_BACK:
3986      MamePlayBackGame();
3987      return TRUE;
3988
3989   case ID_FILE_PLAY_RECORD_WAVE:
3990      MamePlayRecordWave();
3991      return TRUE;
3992
3993   case ID_FILE_PLAY_RECORD_MNG:
3994      MamePlayRecordMNG();
3995      return TRUE;
3996
3997   case ID_FILE_LOADSTATE :
3998      MameLoadState();
3999      return TRUE;
4000
4001   case ID_FILE_AUDIT:
4002      AuditDialog(hMain);
4003      ResetWhichGamesInFolders();
4004      ResetListView();
4005      SetFocus(hwndList);
4006      return TRUE;
4007
4008   case ID_FILE_EXIT:
4009      PostMessage(hMain, WM_CLOSE, 0, 0);
4010      return TRUE;
4011
4012   case ID_VIEW_LARGE_ICON:
4013      SetView(ID_VIEW_LARGE_ICON);
4014      return TRUE;
4015
4016   case ID_VIEW_SMALL_ICON:
4017      SetView(ID_VIEW_SMALL_ICON);
4018      ResetListView();
4019      return TRUE;
4020
4021   case ID_VIEW_LIST_MENU:
4022      SetView(ID_VIEW_LIST_MENU);
4023      return TRUE;
4024
4025   case ID_VIEW_DETAIL:
4026      SetView(ID_VIEW_DETAIL);
4027      return TRUE;
4028
4029   case ID_VIEW_GROUPED:
4030      SetView(ID_VIEW_GROUPED);
4031      return TRUE;
4032
4033   /* Arrange Icons submenu */
4034   case ID_VIEW_BYGAME:
4035      SetSortReverse(FALSE);
4036      SetSortColumn(COLUMN_GAMES);
4037      Picker_Sort(hwndList);
4038      break;
4039
4040   case ID_VIEW_BYDIRECTORY:
4041      SetSortReverse(FALSE);
4042      SetSortColumn(COLUMN_DIRECTORY);
4043      Picker_Sort(hwndList);
4044      break;
4045
4046   case ID_VIEW_BYMANUFACTURER:
4047      SetSortReverse(FALSE);
4048      SetSortColumn(COLUMN_MANUFACTURER);
4049      Picker_Sort(hwndList);
4050      break;
4051
4052   case ID_VIEW_BYTIMESPLAYED:
4053      SetSortReverse(FALSE);
4054      SetSortColumn(COLUMN_PLAYED);
4055      Picker_Sort(hwndList);
4056      break;
4057
4058   case ID_VIEW_BYTYPE:
4059      SetSortReverse(FALSE);
4060      SetSortColumn(COLUMN_TYPE);
4061      Picker_Sort(hwndList);
4062      break;
4063
4064   case ID_VIEW_BYYEAR:
4065      SetSortReverse(FALSE);
4066      SetSortColumn(COLUMN_YEAR);
4067      Picker_Sort(hwndList);
4068      break;
4069
4070   case ID_VIEW_FOLDERS:
4071      bShowTree = !bShowTree;
4072      SetShowFolderList(bShowTree);
4073      CheckMenuItem(GetMenu(hMain), ID_VIEW_FOLDERS, (bShowTree) ? MF_CHECKED : MF_UNCHECKED);
4074      ToolBar_CheckButton(hToolBar, ID_VIEW_FOLDERS, (bShowTree) ? MF_CHECKED : MF_UNCHECKED);
4075      UpdateScreenShot();
4076      break;
4077
4078   case ID_VIEW_TOOLBARS:
4079      bShowToolBar = !bShowToolBar;
4080      SetShowToolBar(bShowToolBar);
4081      CheckMenuItem(GetMenu(hMain), ID_VIEW_TOOLBARS, (bShowToolBar) ? MF_CHECKED : MF_UNCHECKED);
4082      ToolBar_CheckButton(hToolBar, ID_VIEW_TOOLBARS, (bShowToolBar) ? MF_CHECKED : MF_UNCHECKED);
4083      ShowWindow(hToolBar, (bShowToolBar) ? SW_SHOW : SW_HIDE);
4084      ResizePickerControls(hMain);
4085      UpdateScreenShot();
4086      break;
4087
4088   case ID_VIEW_STATUS:
4089      bShowStatusBar = !bShowStatusBar;
4090      SetShowStatusBar(bShowStatusBar);
4091      CheckMenuItem(GetMenu(hMain), ID_VIEW_STATUS, (bShowStatusBar) ? MF_CHECKED : MF_UNCHECKED);
4092      ToolBar_CheckButton(hToolBar, ID_VIEW_STATUS, (bShowStatusBar) ? MF_CHECKED : MF_UNCHECKED);
4093      ShowWindow(hStatusBar, (bShowStatusBar) ? SW_SHOW : SW_HIDE);
4094      ResizePickerControls(hMain);
4095      UpdateScreenShot();
4096      break;
4097
4098   case ID_VIEW_PAGETAB:
4099      bShowTabCtrl = !bShowTabCtrl;
4100      SetShowTabCtrl(bShowTabCtrl);
4101      ShowWindow(hTabCtrl, (bShowTabCtrl) ? SW_SHOW : SW_HIDE);
4102      ResizePickerControls(hMain);
4103      UpdateScreenShot();
4104      InvalidateRect(hMain,NULL,TRUE);
4105      break;
4106
4107      /*
4108        Switches to fullscreen mode. No check mark handeling
4109        for this item cause in fullscreen mode the menu won't
4110        be visible anyways.
4111      */   
4112   case ID_VIEW_FULLSCREEN:
4113      SwitchFullScreenMode();
4114      break;
4115
4116   case ID_GAME_AUDIT:
4117      InitGameAudit(0);
4118      if (!oldControl)
4119      {
4120         InitPropertyPageToPage(hInst, hwnd, Picker_GetSelectedItem(hwndList), GetSelectedPickItemIcon(), AUDIT_PAGE, -1, SRC_GAME);
4121         SaveGameOptions(Picker_GetSelectedItem(hwndList));
4122      }
4123      /* Just in case the toggle MMX on/off */
4124      UpdateStatusBar();
4125      break;
4126
4127   /* ListView Context Menu */
4128   case ID_CONTEXT_ADD_CUSTOM:
4129   {
4130       int  nResult;
4131
4132      nResult = DialogBoxParam(GetModuleHandle(NULL),MAKEINTRESOURCE(IDD_CUSTOM_FILE),
4133                         hMain,AddCustomFileDialogProc,Picker_GetSelectedItem(hwndList));
4134      SetFocus(hwndList);
4135      break;
4136   }
4137
4138   case ID_CONTEXT_REMOVE_CUSTOM:
4139   {
4140       RemoveCurrentGameCustomFolder();
4141      break;
4142   }
4143
4144   /* Tree Context Menu */
4145   case ID_CONTEXT_FILTERS:
4146      if (DialogBox(GetModuleHandle(NULL),
4147         MAKEINTRESOURCE(IDD_FILTERS), hMain, FilterDialogProc) == TRUE)
4148         ResetListView();
4149      SetFocus(hwndList);
4150      return TRUE;
4151
4152      // ScreenShot Context Menu
4153      // select current tab
4154   case ID_VIEW_TAB_SCREENSHOT :
4155   case ID_VIEW_TAB_FLYER :
4156   case ID_VIEW_TAB_CABINET :
4157   case ID_VIEW_TAB_MARQUEE :
4158   case ID_VIEW_TAB_TITLE :
4159   case ID_VIEW_TAB_CONTROL_PANEL :
4160   case ID_VIEW_TAB_HISTORY:
4161      if (id == ID_VIEW_TAB_HISTORY && GetShowTab(TAB_HISTORY) == FALSE)
4162         break;
4163
4164      TabView_SetCurrentTab(hTabCtrl, id - ID_VIEW_TAB_SCREENSHOT);
4165      UpdateScreenShot();
4166      TabView_UpdateSelection(hTabCtrl);
4167      break;
4168
4169      // toggle tab's existence
4170   case ID_TOGGLE_TAB_SCREENSHOT :
4171   case ID_TOGGLE_TAB_FLYER :
4172   case ID_TOGGLE_TAB_CABINET :
4173   case ID_TOGGLE_TAB_MARQUEE :
4174   case ID_TOGGLE_TAB_TITLE :
4175   case ID_TOGGLE_TAB_CONTROL_PANEL :
4176   case ID_TOGGLE_TAB_HISTORY :
4177   {
4178      int toggle_flag = id - ID_TOGGLE_TAB_SCREENSHOT;
4179
4180      if (AllowedToSetShowTab(toggle_flag,!GetShowTab(toggle_flag)) == FALSE)
4181      {
4182         // attempt to hide the last tab
4183         // should show error dialog? hide picture area? or ignore?
4184         break;
4185      }
4186
4187      SetShowTab(toggle_flag,!GetShowTab(toggle_flag));
4188
4189      TabView_Reset(hTabCtrl);
4190
4191      if (TabView_GetCurrentTab(hTabCtrl) == toggle_flag && GetShowTab(toggle_flag) == FALSE)
4192      {
4193         // we're deleting the tab we're on, so go to the next one
4194         TabView_CalculateNextTab(hTabCtrl);
4195      }
4196
4197
4198      // Resize the controls in case we toggled to another history
4199      // mode (and the history control needs resizing).
4200
4201      ResizePickerControls(hMain);
4202      UpdateScreenShot();
4203   
4204      TabView_UpdateSelection(hTabCtrl);
4205
4206      break;
4207   }
4208
4209   /* Header Context Menu */
4210   case ID_SORT_ASCENDING:
4211      SetSortReverse(FALSE);
4212      SetSortColumn(Picker_GetRealColumnFromViewColumn(hwndList, lastColumnClick));
4213      Picker_Sort(hwndList);
4214      break;
4215
4216   case ID_SORT_DESCENDING:
4217      SetSortReverse(TRUE);
4218      SetSortColumn(Picker_GetRealColumnFromViewColumn(hwndList, lastColumnClick));
4219      Picker_Sort(hwndList);
4220      break;
4221
4222   case ID_CUSTOMIZE_FIELDS:
4223      if (DialogBox(GetModuleHandle(NULL),
4224         MAKEINTRESOURCE(IDD_COLUMNS), hMain, ColumnDialogProc) == TRUE)
4225         ResetColumnDisplay(FALSE);
4226      SetFocus(hwndList);
4227      return TRUE;
4228
4229   /* View Menu */
4230   case ID_VIEW_LINEUPICONS:
4231      if( codeNotify == FALSE)
4232         ResetListView();
4233      else
4234      {
4235         /*it was sent after a refresh (F5) was done, we only reset the View if "available" is the selected folder
4236           as it doesn't affect the others*/
4237         folder = GetSelectedFolder();
4238         if( folder )
4239         {
4240            if (folder->m_nFolderId == FOLDER_AVAILABLE )
4241               ResetListView();
4242
4243         }
4244      }
4245      break;
4246
4247   case ID_GAME_PROPERTIES:
4248      if (!oldControl)
4249      {
4250         //folder = GetSelectedFolder();
4251         folder = GetFolderByName(FOLDER_SOURCE, GetDriverFilename(Picker_GetSelectedItem(hwndList)) );
4252         InitPropertyPage(hInst, hwnd, Picker_GetSelectedItem(hwndList), GetSelectedPickItemIcon(), folder->m_nFolderId, SRC_GAME);
4253         SaveGameOptions(Picker_GetSelectedItem(hwndList));
4254#ifdef MESS
4255         {
4256            extern BOOL g_bModifiedSoftwarePaths;
4257            if (g_bModifiedSoftwarePaths) {
4258               g_bModifiedSoftwarePaths = FALSE;
4259               MessUpdateSoftwareList();
4260            }
4261         }
4262#endif
4263      }
4264      /* Just in case the toggle MMX on/off */
4265      UpdateStatusBar();
4266      break;
4267
4268   case ID_FOLDER_PROPERTIES:
4269      if (!oldControl)
4270      {
4271         folder = GetSelectedFolder();
4272         InitPropertyPage(hInst, hwnd, folder->m_nFolderId, GetSelectedFolderIcon(), Picker_GetSelectedItem(hwndList), SRC_FOLDER);
4273         SaveFolderOptions(folder->m_nFolderId, Picker_GetSelectedItem(hwndList) );
4274      }
4275      /* Just in case the toggle MMX on/off */
4276      UpdateStatusBar();
4277      break;
4278     
4279   case ID_FOLDER_SOURCEPROPERTIES:
4280      if (!oldControl)
4281      {
4282         folder = GetFolderByName(FOLDER_SOURCE, GetDriverFilename(Picker_GetSelectedItem(hwndList)) );
4283         InitPropertyPage(hInst, hwnd, folder->m_nFolderId, GetSelectedFolderIcon(), Picker_GetSelectedItem(hwndList), SRC_FOLDER);
4284         SaveFolderOptions(folder->m_nFolderId, Picker_GetSelectedItem(hwndList) );
4285      }
4286      /* Just in case the toggle MMX on/off */
4287      UpdateStatusBar();
4288      break;
4289
4290   case ID_FOLDER_VECTORPROPERTIES:
4291      if (!oldControl)
4292      {
4293         folder = GetFolderByID( FOLDER_VECTOR );
4294         InitPropertyPage(hInst, hwnd, folder->m_nFolderId, GetSelectedFolderIcon(), Picker_GetSelectedItem(hwndList), SRC_FOLDER);
4295         SaveFolderOptions(folder->m_nFolderId, Picker_GetSelectedItem(hwndList) );
4296      }
4297      /* Just in case the toggle MMX on/off */
4298      UpdateStatusBar();
4299      break;
4300     
4301   case ID_FOLDER_AUDIT:
4302      FolderCheck();
4303      /* Just in case the toggle MMX on/off */
4304      UpdateStatusBar();
4305      break;
4306
4307   case ID_VIEW_PICTURE_AREA :
4308      ToggleScreenShot();
4309      break;
4310
4311   case ID_UPDATE_GAMELIST:
4312      UpdateGameList(TRUE, TRUE);
4313      break;
4314
4315   case ID_OPTIONS_FONT:
4316      PickFont();
4317      return TRUE;
4318
4319   case ID_OPTIONS_CLONE_COLOR:
4320      PickCloneColor();
4321      return TRUE;
4322
4323   case ID_OPTIONS_DEFAULTS:
4324      /* Check the return value to see if changes were applied */
4325      if (!oldControl)
4326      {
4327         InitDefaultPropertyPage(hInst, hwnd);
4328         SaveDefaultOptions();
4329      }
4330      SetFocus(hwndList);
4331      return TRUE;
4332
4333   case ID_OPTIONS_DIR:
4334      {
4335         int  nResult;
4336         BOOL bUpdateRoms;
4337         BOOL bUpdateSamples;
4338#ifdef MESS
4339         BOOL bUpdateSoftware;
4340#endif
4341
4342         nResult = DialogBox(GetModuleHandle(NULL),
4343                        MAKEINTRESOURCE(IDD_DIRECTORIES),
4344                        hMain,
4345                        DirectoriesDialogProc);
4346
4347         SaveDefaultOptions();
4348
4349         bUpdateRoms    = ((nResult & DIRDLG_ROMS)    == DIRDLG_ROMS)   ? TRUE : FALSE;
4350         bUpdateSamples = ((nResult & DIRDLG_SAMPLES) == DIRDLG_SAMPLES) ? TRUE : FALSE;
4351#ifdef MESS
4352         bUpdateSoftware = ((nResult & DIRDLG_SOFTWARE) == DIRDLG_SOFTWARE) ? TRUE : FALSE;
4353
4354         if (bUpdateSoftware)
4355            MessUpdateSoftwareList();
4356#endif /* MESS */
4357
4358         if (s_pWatcher)
4359         {
4360            if (bUpdateRoms)
4361               DirWatcher_Watch(s_pWatcher, 0, GetRomDirs(), TRUE);
4362            if (bUpdateSamples)
4363               DirWatcher_Watch(s_pWatcher, 1, GetSampleDirs(), TRUE);
4364         }
4365
4366         /* update game list */
4367         if (bUpdateRoms == TRUE || bUpdateSamples == TRUE)
4368            UpdateGameList(bUpdateRoms, bUpdateSamples);
4369
4370         SetFocus(hwndList);
4371      }
4372      return TRUE;
4373
4374   case ID_OPTIONS_RESET_DEFAULTS:
4375      if (DialogBox(GetModuleHandle(NULL),
4376                 MAKEINTRESOURCE(IDD_RESET), hMain, ResetDialogProc) == TRUE)
4377        {
4378         // these may have been changed
4379         SaveDefaultOptions();
4380         DestroyWindow(hwnd);
4381         PostQuitMessage(0);
4382        }
4383      return TRUE;
4384
4385   case ID_OPTIONS_INTERFACE:
4386      DialogBox(GetModuleHandle(NULL), MAKEINTRESOURCE(IDD_INTERFACE_OPTIONS),
4387              hMain, InterfaceDialogProc);
4388      SaveDefaultOptions();
4389
4390      KillTimer(hMain, SCREENSHOT_TIMER);
4391      if( GetCycleScreenshot() > 0)
4392      {
4393         SetTimer(hMain, SCREENSHOT_TIMER, GetCycleScreenshot()*1000, NULL ); // Scale to seconds
4394      }
4395
4396      return TRUE;
4397
4398   case ID_OPTIONS_BG:
4399      {
4400         OPENFILENAME OpenFileName;
4401         static TCHAR szFile[MAX_PATH] = TEXT("\0");
4402         TCHAR*       t_bgdir = tstring_from_utf8(GetBgDir());
4403         if( !t_bgdir )
4404            return FALSE;
4405
4406         OpenFileName.lStructSize       = sizeof(OPENFILENAME);
4407         OpenFileName.hwndOwner         = hMain;
4408         OpenFileName.hInstance         = 0;
4409         OpenFileName.lpstrFilter       = TEXT("Image Files (*.png, *.bmp)\0*.PNG;*.BMP\0");
4410         OpenFileName.lpstrCustomFilter = NULL;
4411         OpenFileName.nMaxCustFilter    = 0;
4412         OpenFileName.nFilterIndex      = 1;
4413         OpenFileName.lpstrFile         = szFile;
4414         OpenFileName.nMaxFile          = sizeof(szFile);
4415         OpenFileName.lpstrFileTitle    = NULL;
4416         OpenFileName.nMaxFileTitle     = 0;
4417         OpenFileName.lpstrInitialDir   = t_bgdir;
4418         OpenFileName.lpstrTitle        = TEXT("Select a Background Image");
4419         OpenFileName.nFileOffset       = 0;
4420         OpenFileName.nFileExtension    = 0;
4421         OpenFileName.lpstrDefExt       = NULL;
4422         OpenFileName.lCustData         = 0;                                                 
4423         OpenFileName.lpfnHook          = NULL;
4424         OpenFileName.lpTemplateName    = NULL;                                   
4425         OpenFileName.Flags             = OFN_NOCHANGEDIR | OFN_SHOWHELP | OFN_EXPLORER;
4426
4427         if (GetOpenFileName(&OpenFileName))
4428         {
4429            t_szFile = utf8_from_tstring(szFile);
4430            if( !t_szFile )
4431               return FALSE;
4432            ResetBackground(t_szFile);
4433            LoadBackgroundBitmap();
4434            InvalidateRect(hMain, NULL, TRUE);
4435            free(t_bgdir);
4436            free(t_szFile);
4437            return TRUE;
4438         }
4439         free(t_bgdir);
4440      }
4441      break;
4442
4443   case ID_OPTIONS_LANGUAGE:
4444      DialogBox(GetModuleHandle(NULL),
4445              MAKEINTRESOURCE(IDD_LANGUAGE),
4446              hMain,
4447              LanguageDialogProc);
4448      return TRUE;
4449
4450   case ID_HELP_ABOUT:
4451      DialogBox(GetModuleHandle(NULL), MAKEINTRESOURCE(IDD_ABOUT),
4452              hMain, AboutDialogProc);
4453      SetFocus(hwndList);
4454      return TRUE;
4455
4456   case IDOK :
4457      /* cmk -- might need to check more codes here, not sure */
4458      if (codeNotify != EN_CHANGE && codeNotify != EN_UPDATE)
4459      {
4460         /* enter key */
4461         if (g_in_treeview_edit)
4462         {
4463            TreeView_EndEditLabelNow(hTreeView, FALSE);
4464            return TRUE;
4465         }
4466         else
4467            if (have_selection)
4468               MamePlayGame();
4469      }
4470      break;
4471
4472   case IDCANCEL : /* esc key */
4473      if (g_in_treeview_edit)
4474         TreeView_EndEditLabelNow(hTreeView, TRUE);
4475      break;
4476
4477   case IDC_PLAY_GAME :
4478      if (have_selection)
4479         MamePlayGame();
4480      break;
4481
4482   case ID_UI_START:
4483      SetFocus(hwndList);
4484      MamePlayGame();
4485      break;
4486
4487   case ID_UI_UP:
4488      Picker_SetSelectedPick(hwndList, GetSelectedPick() - 1);
4489       break;
4490
4491   case ID_UI_DOWN:
4492      Picker_SetSelectedPick(hwndList, GetSelectedPick() + 1);
4493       break;
4494
4495   case ID_UI_PGUP:
4496      Picker_SetSelectedPick(hwndList, GetSelectedPick() - ListView_GetCountPerPage(hwndList));
4497       break;
4498
4499   case ID_UI_PGDOWN:
4500      if ( (GetSelectedPick() + ListView_GetCountPerPage(hwndList)) < ListView_GetItemCount(hwndList) )
4501         Picker_SetSelectedPick(hwndList,  GetSelectedPick() + ListView_GetCountPerPage(hwndList) );
4502      else
4503         Picker_SetSelectedPick(hwndList,  ListView_GetItemCount(hwndList)-1 );
4504       break;
4505
4506   case ID_UI_HOME:
4507      Picker_SetSelectedPick(hwndList, 0);
4508       break;
4509
4510   case ID_UI_END:
4511      Picker_SetSelectedPick(hwndList,  ListView_GetItemCount(hwndList)-1 );
4512      break;
4513   case ID_UI_LEFT:
4514      /* hmmmmm..... */
4515      SendMessage(hwndList,WM_HSCROLL, SB_LINELEFT, 0);
4516       break;
4517
4518   case ID_UI_RIGHT:
4519      /* hmmmmm..... */
4520      SendMessage(hwndList,WM_HSCROLL, SB_LINERIGHT, 0);
4521       break;
4522   case ID_UI_HISTORY_UP:
4523      /* hmmmmm..... */
4524      {
4525         HWND hHistory = GetDlgItem(hMain, IDC_HISTORY);
4526         SendMessage(hHistory, EM_SCROLL, SB_PAGEUP, 0);
4527      }
4528       break;
4529
4530   case ID_UI_HISTORY_DOWN:
4531      /* hmmmmm..... */
4532      {
4533         HWND hHistory = GetDlgItem(hMain, IDC_HISTORY);
4534         SendMessage(hHistory, EM_SCROLL, SB_PAGEDOWN, 0);
4535      }
4536       break;
4537
4538   case IDC_SSFRAME:
4539      TabView_CalculateNextTab(hTabCtrl);
4540      UpdateScreenShot();
4541      TabView_UpdateSelection(hTabCtrl);
4542      break;
4543
4544   case ID_CONTEXT_SELECT_RANDOM:
4545      SetRandomPickItem();
4546      break;
4547
4548   case ID_CONTEXT_RESET_PLAYTIME:
4549      ResetPlayTime( Picker_GetSelectedItem(hwndList) );
4550      ListView_RedrawItems(hwndList, GetSelectedPick(), GetSelectedPick());
4551      break;
4552
4553   case ID_CONTEXT_RESET_PLAYCOUNT:
4554      ResetPlayCount( Picker_GetSelectedItem(hwndList) );
4555      ListView_RedrawItems(hwndList, GetSelectedPick(), GetSelectedPick());
4556      break;
4557
4558   case ID_CONTEXT_RENAME_CUSTOM :
4559      TreeView_EditLabel(hTreeView,TreeView_GetSelection(hTreeView));
4560      break;
4561
4562   default:
4563      if (id >= ID_CONTEXT_SHOW_FOLDER_START && id < ID_CONTEXT_SHOW_FOLDER_END)
4564      {
4565         ToggleShowFolder(id - ID_CONTEXT_SHOW_FOLDER_START);
4566         break;
4567      }
4568      for (i = 0; g_helpInfo[i].nMenuItem > 0; i++)
4569      {
4570         if (g_helpInfo[i].nMenuItem == id)
4571         {
4572            if (g_helpInfo[i].bIsHtmlHelp)
4573               HelpFunction(hMain, g_helpInfo[i].lpFile, HH_DISPLAY_TOPIC, 0);
4574            else
4575               DisplayTextFile(hMain, g_helpInfo[i].lpFile);
4576            return FALSE;
4577         }
4578      }
4579#ifdef MESS
4580      return MessCommand(hwnd, id, hwndCtl, codeNotify);
4581#else
4582      break;
4583#endif
4584   }
4585
4586   return FALSE;
4587}
4588
4589static void LoadBackgroundBitmap()
4590{
4591   HGLOBAL hDIBbg;
4592   char*   pFileName = 0;
4593
4594   if (hBackground)
4595   {
4596      DeleteObject(hBackground);
4597      hBackground = 0;
4598   }
4599
4600   if (hPALbg)
4601   {
4602      DeleteObject(hPALbg);
4603      hPALbg = 0;
4604   }
4605
4606   /* Pick images based on number of colors avaliable. */
4607   if (GetDepth(hwndList) <= 8)
4608   {
4609      pFileName = (char *)"bkgnd16";
4610      /*nResource = IDB_BKGROUND16;*/
4611   }
4612   else
4613   {
4614      pFileName = (char *)"bkground";
4615      /*nResource = IDB_BKGROUND;*/
4616   }
4617
4618   if (LoadDIB(pFileName, &hDIBbg, &hPALbg, BACKGROUND))
4619   {
4620      HDC hDC = GetDC(hwndList);
4621      hBackground = DIBToDDB(hDC, hDIBbg, &bmDesc);
4622      GlobalFree(hDIBbg);
4623      ReleaseDC(hwndList, hDC);
4624   }
4625}
4626
4627static void ResetColumnDisplay(BOOL first_time)
4628{
4629   int driver_index;
4630
4631   if (!first_time)
4632      Picker_ResetColumnDisplay(hwndList);
4633
4634   ResetListView();
4635
4636   driver_index = GetGameNameIndex(GetDefaultGame());
4637   Picker_SetSelectedItem(hwndList, driver_index);
4638}
4639
4640int GamePicker_GetItemImage(HWND hwndPicker, int nItem)
4641{
4642   return GetIconForDriver(nItem);
4643}
4644
4645const TCHAR *GamePicker_GetItemString(HWND hwndPicker, int nItem, int nColumn,
4646   TCHAR *pszBuffer, UINT nBufferLength)
4647{
4648   const TCHAR *s = NULL;
4649   const char* utf8_s = NULL;
4650   char playtime_buf[256];
4651
4652   switch(nColumn)
4653   {
4654      case COLUMN_GAMES:
4655         /* Driver description */
4656         utf8_s = ModifyThe(drivers[nItem]->description);
4657         break;
4658
4659      case COLUMN_ROMS:
4660         /* Has Roms */
4661         utf8_s = GetAuditString(GetRomAuditResults(nItem));
4662         break;
4663
4664      case COLUMN_SAMPLES:
4665         /* Samples */
4666         if (DriverUsesSamples(nItem))
4667            utf8_s = GetAuditString(GetSampleAuditResults(nItem));
4668         break;
4669
4670      case COLUMN_DIRECTORY:
4671         /* Driver name (directory) */
4672         utf8_s = drivers[nItem]->name;
4673         break;
4674
4675      case COLUMN_SRCDRIVERS:
4676         /* Source drivers */
4677         utf8_s = GetDriverFilename(nItem);
4678         break;
4679
4680      case COLUMN_PLAYTIME:
4681         /* Source drivers */
4682         GetTextPlayTime(nItem, playtime_buf);
4683         utf8_s = playtime_buf;
4684         break;
4685
4686      case COLUMN_TYPE:
4687        {
4688            machine_config drv;
4689            expand_machine_driver(drivers[nItem]->drv,&drv);
4690
4691         /* Vector/Raster */
4692         if (drv.video_attributes & VIDEO_TYPE_VECTOR)
4693            s = TEXT("Vector");
4694         else
4695            s = TEXT("Raster");
4696         break;
4697        }
4698      case COLUMN_TRACKBALL:
4699         /* Trackball */
4700         if (DriverUsesTrackball(nItem))
4701            s = TEXT("Yes");
4702         else
4703            s = TEXT("No");
4704         break;
4705
4706      case COLUMN_PLAYED:
4707         /* times played */
4708         _sntprintf(pszBuffer, nBufferLength, TEXT("%i"), GetPlayCount(nItem));
4709         s = pszBuffer;
4710         break;
4711
4712      case COLUMN_MANUFACTURER:
4713         /* Manufacturer */
4714         utf8_s = drivers[nItem]->manufacturer;
4715         break;
4716
4717      case COLUMN_YEAR:
4718         /* Year */
4719         utf8_s = drivers[nItem]->year;
4720         break;
4721
4722      case COLUMN_CLONE:
4723         utf8_s = GetCloneParentName(nItem);
4724         break;
4725   }
4726   
4727   if( utf8_s )
4728   {
4729      TCHAR* t_s = tstring_from_utf8(utf8_s);
4730      if( !t_s )
4731         return s;
4732     
4733      _sntprintf(pszBuffer, nBufferLength, TEXT("%s"), t_s);     
4734      free(t_s);
4735     
4736      s = pszBuffer;
4737   }
4738   
4739   return s;
4740}
4741
4742static void GamePicker_LeavingItem(HWND hwndPicker, int nItem)
4743{
4744   // leaving item
4745   // printf("leaving %s\n",drivers[nItem]->name);
4746}
4747
4748static void GamePicker_EnteringItem(HWND hwndPicker, int nItem)
4749{
4750   TCHAR* t_description;
4751   ATOM a;
4752   // printf("entering %s\n",drivers[nItem]->name);
4753   if (g_bDoBroadcast == TRUE)
4754   {
4755      t_description = tstring_from_utf8(drivers[nItem]->description);
4756      if( !t_description )
4757         return;
4758      a = GlobalAddAtom(t_description);
4759      SendMessage(HWND_BROADCAST, g_mame32_message, a, a);
4760      GlobalDeleteAtom(a);
4761      free(t_description);
4762   }
4763
4764   EnableSelection(nItem);
4765#ifdef MESS
4766   MessReadMountedSoftware(nItem);
4767#endif
4768}
4769
4770static int GamePicker_FindItemParent(HWND hwndPicker, int nItem)
4771{
4772   return GetParentRomSetIndex(drivers[nItem]);
4773}
4774
4775/* Initialize the Picker and List controls */
4776static void InitListView()
4777{
4778   LVBKIMAGE bki;
4779   TCHAR path[MAX_PATH];
4780   TCHAR* t_bgdir;
4781
4782   static const struct PickerCallbacks s_gameListCallbacks =
4783   {
4784      SetSortColumn,            /* pfnSetSortColumn */
4785      GetSortColumn,            /* pfnGetSortColumn */
4786      SetSortReverse,            /* pfnSetSortReverse */
4787      GetSortReverse,            /* pfnGetSortReverse */
4788      SetViewMode,            /* pfnSetViewMode */
4789      GetViewMode,            /* pfnGetViewMode */
4790      SetColumnWidths,         /* pfnSetColumnWidths */
4791      GetColumnWidths,         /* pfnGetColumnWidths */
4792      SetColumnOrder,            /* pfnSetColumnOrder */
4793      GetColumnOrder,            /* pfnGetColumnOrder */
4794      SetColumnShown,            /* pfnSetColumnShown */
4795      GetColumnShown,            /* pfnGetColumnShown */
4796      GetOffsetClones,         /* pfnGetOffsetChildren */
4797
4798      GamePicker_Compare,         /* pfnCompare */
4799      MamePlayGame,            /* pfnDoubleClick */
4800      GamePicker_GetItemString,   /* pfnGetItemString */
4801      GamePicker_GetItemImage,   /* pfnGetItemImage */
4802      GamePicker_LeavingItem,      /* pfnLeavingItem */
4803      GamePicker_EnteringItem,   /* pfnEnteringItem */
4804      BeginListViewDrag,         /* pfnBeginListViewDrag */
4805      GamePicker_FindItemParent,   /* pfnFindItemParent */
4806      OnIdle,                     /* pfnIdle */
4807      GamePicker_OnHeaderContextMenu,   /* pfnOnHeaderContextMenu */
4808      GamePicker_OnBodyContextMenu   /* pfnOnBodyContextMenu */
4809   };
4810
4811   struct PickerOptions opts;
4812
4813   // subclass the list view
4814   memset(&opts, 0, sizeof(opts));
4815   opts.pCallbacks = &s_gameListCallbacks;
4816   opts.nColumnCount = COLUMN_MAX;
4817   opts.ppszColumnNames = column_names;
4818   SetupPicker(hwndList, &opts);
4819
4820   ListView_SetTextBkColor(hwndList, CLR_NONE);
4821   ListView_SetBkColor(hwndList, CLR_NONE);
4822   t_bgdir = tstring_from_utf8(GetBgDir());
4823   if( !t_bgdir )
4824      return;
4825   _stprintf(path, TEXT("%s\\bkground.png"), t_bgdir);
4826   bki.ulFlags = LVBKIF_SOURCE_URL | LVBKIF_STYLE_TILE;
4827   bki.pszImage = path;
4828   if( hBackground )   
4829      ListView_SetBkImage(hwndList, &bki);
4830
4831   CreateIcons();
4832
4833   ResetColumnDisplay(TRUE);
4834
4835   // Allow selection to change the default saved game
4836   bListReady = TRUE;
4837   free(t_bgdir);
4838}
4839
4840static void AddDriverIcon(int nItem,int default_icon_index)
4841{
4842   HICON hIcon = 0;
4843   int nParentIndex = -1;
4844
4845   /* if already set to rom or clone icon, we've been here before */
4846   if (icon_index[nItem] == 1 || icon_index[nItem] == 3)
4847      return;
4848
4849   hIcon = LoadIconFromFile((char *)drivers[nItem]->name);
4850   if (hIcon == NULL)
4851   {
4852      nParentIndex = GetParentIndex(drivers[nItem]);
4853      if( nParentIndex >= 0)
4854      {
4855         hIcon = LoadIconFromFile((char *)drivers[nParentIndex]->name);
4856         nParentIndex = GetParentIndex(drivers[nParentIndex]);
4857         if (hIcon == NULL && nParentIndex >= 0)
4858            hIcon = LoadIconFromFile((char *)drivers[nParentIndex]->name);
4859      }
4860   }
4861
4862   if (hIcon != NULL)
4863   {
4864      int nIconPos = ImageList_AddIcon(hSmall, hIcon);
4865      ImageList_AddIcon(hLarge, hIcon);
4866      if (nIconPos != -1)
4867         icon_index[nItem] = nIconPos;
4868   }
4869   if (icon_index[nItem] == 0)
4870      icon_index[nItem] = default_icon_index;
4871}
4872
4873static void DestroyIcons(void)
4874{
4875   if (hSmall != NULL)
4876   {
4877      ImageList_Destroy(hSmall);
4878      hSmall = NULL;
4879   }
4880
4881   if (icon_index != NULL)
4882   {
4883      int i;
4884      for (i=0;i<driver_list_get_count(drivers);i++)
4885         icon_index[i] = 0; // these are indices into hSmall
4886   }
4887
4888   if (hLarge != NULL)
4889   {
4890      ImageList_Destroy(hLarge);
4891      hLarge = NULL;
4892   }
4893
4894   if (hHeaderImages != NULL)
4895   {
4896      ImageList_Destroy(hHeaderImages);
4897      hHeaderImages = NULL;
4898   }
4899
4900}
4901
4902static void ReloadIcons(void)
4903{
4904   HICON hIcon;
4905   INT i;
4906
4907   // clear out all the images
4908   ImageList_Remove(hSmall,-1);
4909   ImageList_Remove(hLarge,-1);
4910
4911   if (icon_index != NULL)
4912   {
4913      for (i=0;i<driver_list_get_count(drivers);i++)
4914         icon_index[i] = 0; // these are indices into hSmall
4915   }
4916
4917   for (i = 0; g_iconData[i].icon_name; i++)
4918   {
4919      hIcon = LoadIconFromFile((char *) g_iconData[i].icon_name);
4920      if (hIcon == NULL)
4921         hIcon = LoadIcon(hInst, MAKEINTRESOURCE(g_iconData[i].resource));
4922
4923      ImageList_AddIcon(hSmall, hIcon);
4924      ImageList_AddIcon(hLarge, hIcon);
4925   }
4926}
4927
4928static DWORD GetShellLargeIconSize(void)
4929{
4930   DWORD  dwSize, dwLength = 512, dwType = REG_SZ;
4931   TCHAR  szBuffer[512];
4932   HKEY   hKey;
4933
4934   /* Get the Key */
4935   RegOpenKey(HKEY_CURRENT_USER, TEXT("Control Panel\\desktop\\WindowMetrics"), &hKey);
4936   /* Save the last size */
4937   RegQueryValueEx(hKey, TEXT("Shell Icon Size"), NULL, &dwType, (LPBYTE)szBuffer, &dwLength);
4938   dwSize = _ttol(szBuffer);
4939   if (dwSize < 32)
4940      dwSize = 32;
4941
4942   if (dwSize > 48)
4943      dwSize = 48;
4944
4945   /* Clean up */
4946   RegCloseKey(hKey);
4947   return dwSize;
4948}
4949
4950static DWORD GetShellSmallIconSize(void)
4951{
4952   DWORD dwSize = ICONMAP_WIDTH;
4953
4954   if (dwSize < 48)
4955   {
4956      if (dwSize < 32)
4957         dwSize = 16;
4958      else
4959         dwSize = 32;
4960   }
4961   else
4962   {
4963      dwSize = 48;
4964   }
4965   return dwSize;
4966}
4967
4968// create iconlist for Listview control
4969static void CreateIcons(void)
4970{
4971   DWORD dwLargeIconSize = GetShellLargeIconSize();
4972   HICON hIcon;
4973   int icon_count;
4974   DWORD dwStyle;
4975   int i;
4976
4977   icon_count = 0;
4978   while(g_iconData[icon_count].icon_name)
4979      icon_count++;
4980
4981   // the current window style affects the sizing of the rows when changing
4982   // between list views, so put it in small icon mode temporarily while we associate
4983   // our image list
4984   //
4985   // using large icon mode instead kills the horizontal scrollbar when doing
4986   // full refresh, which seems odd (it should recreate the scrollbar when
4987   // set back to report mode, for example, but it doesn't).
4988
4989   dwStyle = GetWindowLong(hwndList,GWL_STYLE);
4990   SetWindowLong(hwndList,GWL_STYLE,(dwStyle & ~LVS_TYPEMASK) | LVS_ICON);
4991
4992   hSmall = ImageList_Create(GetShellSmallIconSize(),GetShellSmallIconSize(),
4993                       ILC_COLORDDB | ILC_MASK, icon_count, 500);
4994   hLarge = ImageList_Create(dwLargeIconSize, dwLargeIconSize,
4995                       ILC_COLORDDB | ILC_MASK, icon_count, 500);
4996
4997   ReloadIcons();
4998
4999   // Associate the image lists with the list view control.
5000   (void)ListView_SetImageList(hwndList, hSmall, LVSIL_SMALL);
5001   (void)ListView_SetImageList(hwndList, hLarge, LVSIL_NORMAL);
5002
5003   // restore our view
5004   SetWindowLong(hwndList,GWL_STYLE,dwStyle);
5005
5006#ifdef MESS
5007   CreateMessIcons();
5008#endif
5009
5010   // Now set up header specific stuff
5011   hHeaderImages = ImageList_Create(8,8,ILC_COLORDDB | ILC_MASK,2,2);
5012   hIcon = LoadIcon(hInst,MAKEINTRESOURCE(IDI_HEADER_UP));
5013   ImageList_AddIcon(hHeaderImages,hIcon);
5014   hIcon = LoadIcon(hInst,MAKEINTRESOURCE(IDI_HEADER_DOWN));
5015   ImageList_AddIcon(hHeaderImages,hIcon);
5016
5017   for (i = 0; i < sizeof(s_nPickers) / sizeof(s_nPickers[0]); i++)
5018      Picker_SetHeaderImageList(GetDlgItem(hMain, s_nPickers[i]), hHeaderImages);
5019}
5020
5021
5022
5023static int GamePicker_Compare(HWND hwndPicker, int index1, int index2, int sort_subitem)
5024{
5025   int value;
5026   const char *name1 = NULL;
5027   const char *name2 = NULL;
5028   int nTemp1, nTemp2;
5029
5030#ifdef DEBUG
5031   if (strcmp(drivers[index1]->name,"1941") == 0 && strcmp(drivers[index2]->name,"1942") == 0)
5032   {
5033      dprintf("comparing 1941, 1942");
5034   }
5035
5036   if (strcmp(drivers[index1]->name,"1942") == 0 && strcmp(drivers[index2]->name,"1941") == 0)
5037   {
5038      dprintf("comparing 1942, 1941");
5039   }
5040#endif
5041
5042   switch (sort_subitem)
5043   {
5044   case COLUMN_GAMES:
5045      value = mame_stricmp(ModifyThe(drivers[index1]->description),
5046                  ModifyThe(drivers[index2]->description));
5047      break;
5048
5049   case COLUMN_ROMS:
5050      nTemp1 = GetRomAuditResults(index1);
5051      nTemp2 = GetRomAuditResults(index2);
5052
5053      if (IsAuditResultKnown(nTemp1) == FALSE && IsAuditResultKnown(nTemp2) == FALSE)
5054         return GamePicker_Compare(hwndPicker, index1, index2, COLUMN_GAMES);
5055
5056      if (IsAuditResultKnown(nTemp1) == FALSE)
5057      {
5058         value = 1;
5059         break;
5060      }
5061
5062      if (IsAuditResultKnown(nTemp2) == FALSE)
5063      {
5064         value = -1;
5065         break;
5066      }
5067
5068      // ok, both are known
5069
5070      if (IsAuditResultYes(nTemp1) && IsAuditResultYes(nTemp2))
5071         return GamePicker_Compare(hwndPicker, index1, index2, COLUMN_GAMES);
5072     
5073      if (IsAuditResultNo(nTemp1) && IsAuditResultNo(nTemp2))
5074         return GamePicker_Compare(hwndPicker, index1, index2, COLUMN_GAMES);
5075
5076      if (IsAuditResultYes(nTemp1) && IsAuditResultNo(nTemp2))
5077         value = -1;
5078      else
5079         value = 1;
5080      break;
5081
5082   case COLUMN_SAMPLES:
5083      nTemp1 = -1;
5084      if (DriverUsesSamples(index1))
5085      {
5086         int audit_result = GetSampleAuditResults(index1);
5087         if (IsAuditResultKnown(audit_result))
5088         {
5089            if (IsAuditResultYes(audit_result))
5090               nTemp1 = 1;
5091            else
5092               nTemp1 = 0;
5093         }
5094         else
5095            nTemp1 = 2;
5096      }
5097
5098      nTemp2 = -1;
5099      if (DriverUsesSamples(index2))
5100      {
5101         int audit_result = GetSampleAuditResults(index1);
5102         if (IsAuditResultKnown(audit_result))
5103         {
5104            if (IsAuditResultYes(audit_result))
5105               nTemp2 = 1;
5106            else
5107               nTemp2 = 0;
5108         }
5109         else
5110            nTemp2 = 2;
5111      }
5112
5113      if (nTemp1 == nTemp2)
5114         return GamePicker_Compare(hwndPicker, index1, index2, COLUMN_GAMES);
5115
5116      value = nTemp2 - nTemp1;
5117      break;
5118
5119   case COLUMN_DIRECTORY:
5120      value = mame_stricmp(drivers[index1]->name, drivers[index2]->name);
5121      break;
5122
5123      case COLUMN_SRCDRIVERS:
5124      if (mame_stricmp(drivers[index1]->source_file+12, drivers[index2]->source_file+12) == 0)
5125         return GamePicker_Compare(hwndPicker, index1, index2, COLUMN_GAMES);
5126
5127      value = mame_stricmp(drivers[index1]->source_file+12, drivers[index2]->source_file+12);
5128      break;
5129   case COLUMN_PLAYTIME:
5130      value = GetPlayTime(index1) - GetPlayTime(index2);
5131      if (value == 0)
5132        return GamePicker_Compare(hwndPicker, index1, index2, COLUMN_GAMES);
5133
5134      break;
5135
5136   case COLUMN_TYPE:
5137    {
5138        machine_config drv1,drv2;
5139        expand_machine_driver(drivers[index1]->drv,&drv1);
5140        expand_machine_driver(drivers[index2]->drv,&drv2);
5141
5142      if ((drv1.video_attributes & VIDEO_TYPE_VECTOR) ==
5143         (drv2.video_attributes & VIDEO_TYPE_VECTOR))
5144         return GamePicker_Compare(hwndPicker, index1, index2, COLUMN_GAMES);
5145
5146      value = (drv1.video_attributes & VIDEO_TYPE_VECTOR) -
5147            (drv2.video_attributes & VIDEO_TYPE_VECTOR);
5148      break;
5149    }
5150   case COLUMN_TRACKBALL:
5151      if (DriverUsesTrackball(index1) == DriverUsesTrackball(index2))
5152         return GamePicker_Compare(hwndPicker, index1, index2, COLUMN_GAMES);
5153
5154      value = DriverUsesTrackball(index1) - DriverUsesTrackball(index2);
5155      break;
5156
5157   case COLUMN_PLAYED:
5158      value = GetPlayCount(index1) - GetPlayCount(index2);
5159      if (value == 0)
5160        return GamePicker_Compare(hwndPicker, index1, index2, COLUMN_GAMES);
5161
5162      break;
5163
5164   case COLUMN_MANUFACTURER:
5165      if (mame_stricmp(drivers[index1]->manufacturer, drivers[index2]->manufacturer) == 0)
5166         return GamePicker_Compare(hwndPicker, index1, index2, COLUMN_GAMES);
5167
5168      value = mame_stricmp(drivers[index1]->manufacturer, drivers[index2]->manufacturer);
5169      break;
5170
5171   case COLUMN_YEAR:
5172      if (mame_stricmp(drivers[index1]->year, drivers[index2]->year) == 0)
5173         return GamePicker_Compare(hwndPicker, index1, index2, COLUMN_GAMES);
5174
5175      value = mame_stricmp(drivers[index1]->year, drivers[index2]->year);
5176      break;
5177
5178   case COLUMN_CLONE:
5179      name1 = GetCloneParentName(index1);
5180      name2 = GetCloneParentName(index2);
5181
5182      if (*name1 == '\0')
5183         name1 = NULL;
5184      if (*name2 == '\0')
5185         name2 = NULL;
5186
5187      if (name1 == name2)
5188         return GamePicker_Compare(hwndPicker, index1, index2, COLUMN_GAMES);
5189
5190      if (name2 == NULL)
5191         value = -1;
5192      else if (name1 == NULL)
5193         value = 1;
5194      else
5195         value = mame_stricmp(name1, name2);
5196      break;
5197
5198   default :
5199      return GamePicker_Compare(hwndPicker, index1, index2, COLUMN_GAMES);
5200   }
5201
5202#ifdef DEBUG
5203   if ((strcmp(drivers[index1]->name,"1941") == 0 && strcmp(drivers[index2]->name,"1942") == 0) ||
5204      (strcmp(drivers[index1]->name,"1942") == 0 && strcmp(drivers[index2]->name,"1941") == 0))
5205      dprintf("result: %i",value);
5206#endif
5207
5208   return value;
5209}
5210
5211int GetSelectedPick()
5212{
5213   /* returns index of listview selected item */
5214   /* This will return -1 if not found */
5215   return ListView_GetNextItem(hwndList, -1, LVIS_SELECTED | LVIS_FOCUSED);
5216}
5217
5218static HICON GetSelectedPickItemIcon()
5219{
5220   LV_ITEM lvi;
5221
5222   lvi.iItem = GetSelectedPick();
5223   lvi.iSubItem = 0;
5224   lvi.mask = LVIF_IMAGE;
5225   ListView_GetItem(hwndList, &lvi);
5226
5227   return ImageList_GetIcon(hLarge, lvi.iImage, ILD_TRANSPARENT);
5228}
5229
5230static void SetRandomPickItem()
5231{
5232   int nListCount;
5233
5234   nListCount = ListView_GetItemCount(hwndList);
5235
5236   if (nListCount > 0)
5237   {
5238      Picker_SetSelectedPick(hwndList, rand() % nListCount);
5239   }
5240}
5241
5242BOOL CommonFileDialog(common_file_dialog_proc cfd, char *filename, int filetype)
5243{
5244   BOOL success;
5245   OPENFILENAME of;
5246   TCHAR* t_filename;
5247   TCHAR* t_statedir = 0;
5248   TCHAR* t_artdir = 0;
5249   TCHAR t_filename_buffer[MAX_PATH]  = {0, };
5250   char *utf8_filename;
5251
5252   // convert the filename to UTF-8 and copy into buffer
5253   t_filename = tstring_from_utf8(filename);
5254   if (t_filename != NULL)
5255   {
5256      _sntprintf(t_filename_buffer, ARRAY_LENGTH(t_filename_buffer), TEXT("%s"), t_filename);
5257      free(t_filename);
5258   }
5259
5260   of.lStructSize       = sizeof(of);
5261   of.hwndOwner         = hMain;
5262   of.hInstance         = NULL;
5263   switch (filetype)
5264   {
5265   case FILETYPE_INPUT_FILES :
5266      of.lpstrFilter   = TEXT(MAMENAME " input files (*.inp,*.zip)\0*.inp;*.zip\0All files (*.*)\0*.*\0");
5267      break;
5268   case FILETYPE_SAVESTATE_FILES :
5269      of.lpstrFilter   = TEXT(MAMENAME " savestate files (*.sta)\0*.sta;\0All files (*.*)\0*.*\0");
5270      break;
5271   case FILETYPE_WAVE_FILES :
5272      of.lpstrFilter   = TEXT("sounds (*.wav)\0*.wav;\0All files (*.*)\0*.*\0");
5273      break;
5274   case FILETYPE_MNG_FILES :
5275      of.lpstrFilter   = TEXT("videos (*.mng)\0*.mng;\0All files (*.*)\0*.*\0");
5276      break;
5277   case FILETYPE_EFFECT_FILES :
5278      of.lpstrFilter   = TEXT("effects (*.png)\0*.png;\0All files (*.*)\0*.*\0");
5279      break;
5280   }
5281   of.lpstrCustomFilter = NULL;
5282   of.nMaxCustFilter    = 0;
5283   of.nFilterIndex      = 1;
5284   of.lpstrFile         = t_filename_buffer;
5285   of.nMaxFile          = ARRAY_LENGTH(t_filename_buffer);
5286   of.lpstrFileTitle    = NULL;
5287   of.nMaxFileTitle     = 0;
5288   if (filetype == FILETYPE_SAVESTATE_FILES)
5289   {
5290      t_statedir = tstring_from_utf8(GetStateDir());
5291      if( !t_statedir )
5292         return FALSE;
5293
5294      of.lpstrInitialDir = t_statedir;
5295   }
5296   else
5297   {
5298      if (filetype == FILETYPE_EFFECT_FILES)
5299      {
5300         t_artdir = tstring_from_utf8(GetArtDir());
5301         if( !t_artdir )
5302            return FALSE;
5303
5304         of.lpstrInitialDir = t_artdir;
5305      }
5306      else
5307         of.lpstrInitialDir = last_directory;
5308   }
5309   of.lpstrTitle        = NULL;
5310   of.Flags             = OFN_EXPLORER | OFN_NOCHANGEDIR | OFN_PATHMUSTEXIST | OFN_HIDEREADONLY;
5311   of.nFileOffset       = 0;
5312   of.nFileExtension    = 0;
5313   switch (filetype)
5314   {
5315   case FILETYPE_INPUT_FILES :
5316      of.lpstrDefExt       = TEXT("inp");
5317      break;
5318   case FILETYPE_SAVESTATE_FILES :
5319      of.lpstrDefExt       = TEXT("sta");
5320      break;
5321   case FILETYPE_WAVE_FILES :
5322      of.lpstrDefExt       = TEXT("wav");
5323      break;
5324   case FILETYPE_MNG_FILES :
5325      of.lpstrDefExt       = TEXT("mng");
5326      break;
5327   case FILETYPE_EFFECT_FILES :
5328      of.lpstrDefExt       = TEXT("png");
5329      break;
5330   }
5331   of.lCustData         = 0;
5332   of.lpfnHook          = NULL;
5333   of.lpTemplateName    = NULL;
5334
5335   success = cfd(&of);
5336   if (success)
5337   {
5338      //dprintf("got filename %s nFileExtension %u\n",filename,of.nFileExtension);
5339      /*GetDirectory(filename,last_directory,sizeof(last_directory));*/
5340   }
5341   
5342   if( t_artdir )
5343      free(t_artdir);
5344   if( t_statedir )
5345      free(t_statedir);
5346
5347   utf8_filename = utf8_from_tstring(t_filename_buffer);
5348   if (utf8_filename != NULL)
5349   {
5350      snprintf(filename, MAX_PATH, "%s", utf8_filename);
5351   }
5352
5353   return success;
5354}
5355
5356static BOOL SelectLanguageFile(HWND hWnd, TCHAR* filename)
5357{
5358   OPENFILENAME of;
5359
5360   of.lStructSize       = sizeof(of);
5361   of.hwndOwner         = hWnd;
5362   of.hInstance         = NULL;
5363   of.lpstrFilter       = TEXT(MAMENAME " Language files (*.lng)\0*.lng\0");
5364   of.lpstrCustomFilter = NULL;
5365   of.nMaxCustFilter    = 0;
5366   of.nFilterIndex      = 1;
5367   of.lpstrFile         = filename;
5368   of.nMaxFile          = MAX_PATH;
5369   of.lpstrFileTitle    = NULL;
5370   of.nMaxFileTitle     = 0;
5371   of.lpstrInitialDir   = NULL;
5372   of.lpstrTitle        = NULL;
5373   of.Flags             = OFN_EXPLORER | OFN_NOCHANGEDIR | OFN_PATHMUSTEXIST | OFN_HIDEREADONLY | OFN_FILEMUSTEXIST;
5374   of.nFileOffset       = 0;
5375   of.nFileExtension    = 0;
5376   of.lpstrDefExt       = TEXT("lng");
5377   of.lCustData         = 0;
5378   of.lpfnHook          = NULL;
5379   of.lpTemplateName    = NULL;
5380
5381   return GetOpenFileName(&of);
5382}
5383
5384static INT_PTR CALLBACK LanguageDialogProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam)
5385{
5386   TCHAR pLangFile[MAX_PATH];
5387   DWORD dwHelpIDs[] = { IDC_LANGUAGECHECK, HIDC_LANGUAGECHECK,
5388                    IDC_LANGUAGEEDIT,  HIDC_LANGUAGEEDIT,
5389                    0, 0};
5390   char* utf8_LangFile;
5391
5392   switch (Msg)
5393   {
5394   case WM_INITDIALOG:
5395      {
5396         const char* pLang = GetLanguage();
5397         if (pLang == NULL || *pLang == '\0')
5398         {
5399            win_set_window_text_utf8(GetDlgItem(hDlg, IDC_LANGUAGEEDIT), "");
5400            Button_SetCheck(GetDlgItem(hDlg, IDC_LANGUAGECHECK), FALSE);
5401            EnableWindow(GetDlgItem(hDlg, IDC_LANGUAGEEDIT),   FALSE);
5402            EnableWindow(GetDlgItem(hDlg, IDC_LANGUAGEBROWSE), FALSE);
5403         }
5404         else
5405         {
5406            win_set_window_text_utf8(GetDlgItem(hDlg, IDC_LANGUAGEEDIT), pLang);
5407            Button_SetCheck(GetDlgItem(hDlg, IDC_LANGUAGECHECK), TRUE);
5408            EnableWindow(GetDlgItem(hDlg, IDC_LANGUAGEEDIT),   TRUE);
5409            EnableWindow(GetDlgItem(hDlg, IDC_LANGUAGEBROWSE), TRUE);
5410         }
5411
5412         return TRUE;
5413      }
5414
5415   case WM_HELP:
5416      HelpFunction(((LPHELPINFO)lParam)->hItemHandle, MAME32CONTEXTHELP, HH_TP_HELP_WM_HELP, (DWORD)dwHelpIDs);
5417      break;
5418
5419   case WM_CONTEXTMENU:
5420      HelpFunction((HWND)wParam, MAME32CONTEXTHELP, HH_TP_HELP_CONTEXTMENU, (DWORD)dwHelpIDs);
5421      break;
5422
5423   case WM_COMMAND:
5424      switch (GET_WM_COMMAND_ID(wParam, lParam))
5425      {
5426      case IDOK:
5427         Edit_GetText(GetDlgItem(hDlg, IDC_LANGUAGEEDIT), pLangFile, MAX_PATH);
5428         utf8_LangFile = utf8_from_tstring(pLangFile);
5429         if( !utf8_LangFile )
5430            return FALSE;
5431         SetLanguage(utf8_LangFile);
5432         free(utf8_LangFile);
5433
5434      case IDCANCEL:
5435         EndDialog(hDlg, 0);
5436         return TRUE;
5437
5438      case IDC_LANGUAGECHECK:
5439      {
5440         BOOL bCheck = Button_GetCheck(GetDlgItem(hDlg, IDC_LANGUAGECHECK));
5441         EnableWindow(GetDlgItem(hDlg, IDC_LANGUAGEEDIT),   bCheck);
5442         EnableWindow(GetDlgItem(hDlg, IDC_LANGUAGEBROWSE), bCheck);
5443         if (bCheck == FALSE)
5444            Edit_SetText(GetDlgItem(hDlg, IDC_LANGUAGEEDIT), TEXT(""));
5445         return TRUE;
5446      }
5447
5448      case IDC_LANGUAGEBROWSE:
5449         Edit_GetText(GetDlgItem(hDlg, IDC_LANGUAGEEDIT), pLangFile, MAX_PATH);
5450         if (SelectLanguageFile(hDlg, pLangFile) == TRUE)
5451            Edit_SetText(GetDlgItem(hDlg, IDC_LANGUAGEEDIT), pLangFile);
5452         break;
5453      }
5454      break;
5455   }
5456   return 0;
5457}
5458
5459void SetStatusBarText(int part_index, const char *message)
5460{
5461   TCHAR* t_message = tstring_from_utf8(message);
5462   if( !t_message )
5463      return;
5464   SendMessage(hStatusBar, SB_SETTEXT, (WPARAM) part_index, (LPARAM)(LPCTSTR) win_tstring_strdup(t_message));
5465   free(t_message);
5466}
5467
5468void SetStatusBarTextF(int part_index, const char *fmt, ...)
5469{
5470   char buf[256];
5471   va_list va;
5472
5473   va_start(va, fmt);
5474   vsprintf(buf, fmt, va);
5475   va_end(va);
5476
5477   SetStatusBarText(part_index, buf);
5478}
5479
5480static void CLIB_DECL MameMessageBox(const char *fmt, ...)
5481{
5482   char buf[2048];
5483   va_list va;
5484
5485   va_start(va, fmt);
5486   vsprintf(buf, fmt, va);
5487   win_message_box_utf8(GetMainWindow(), buf, MAME32NAME, MB_OK | MB_ICONERROR);
5488   va_end(va);
5489}
5490
5491static void MamePlayBackGame()
5492{
5493   int nGame;
5494   char filename[MAX_PATH];
5495
5496   *filename = 0;
5497
5498   nGame = Picker_GetSelectedItem(hwndList);
5499   if (nGame != -1)
5500      strcpy(filename, drivers[nGame]->name);
5501
5502   if (CommonFileDialog(GetOpenFileName, filename, FILETYPE_INPUT_FILES))
5503   {
5504      file_error fileerr;
5505      mame_file* pPlayBack;
5506      char drive[_MAX_DRIVE];
5507      char dir[_MAX_DIR];
5508      char bare_fname[_MAX_FNAME];
5509      char ext[_MAX_EXT];
5510
5511      char path[MAX_PATH];
5512      char fname[MAX_PATH];
5513      play_options playopts;
5514
5515      _splitpath(filename, drive, dir, bare_fname, ext);
5516
5517      sprintf(path,"%s%s",drive,dir);
5518      sprintf(fname,"%s%s",bare_fname,ext);
5519      if (path[strlen(path)-1] == '\\')
5520         path[strlen(path)-1] = 0; // take off trailing back slash
5521
5522      fileerr = mame_fopen_options(Mame32Global(), SEARCHPATH_INPUTLOG, fname, OPEN_FLAG_READ, &pPlayBack);
5523      if (fileerr != FILERR_NONE)
5524      {
5525         MameMessageBox("Could not open '%s' as a valid input file.", filename);
5526         return;
5527      }
5528
5529      // check for game name embedded in .inp header
5530      if (pPlayBack)
5531      {
5532         inp_header input_header;
5533
5534         // read playback header
5535         mame_fread(pPlayBack, &input_header, sizeof(inp_header));
5536
5537         if (!isalnum(input_header.name[0])) // If first byte is not alpha-numeric
5538            mame_fseek(pPlayBack, 0, SEEK_SET); // old .inp file - no header
5539         else
5540         {
5541            int i;
5542            for (i = 0; drivers[i] != 0; i++) // find game and play it
5543            {
5544               if (strcmp(drivers[i]->name, input_header.name) == 0)
5545               {
5546                  nGame = i;
5547                  break;
5548               }
5549            }
5550         }
5551      }
5552      mame_fclose(pPlayBack);
5553
5554      memset(&playopts, 0, sizeof(playopts));
5555      playopts.playback = fname;
5556      MamePlayGameWithOptions(nGame, &playopts);
5557   }
5558}
5559
5560static void MameLoadState()
5561{
5562   int nGame;
5563   char filename[MAX_PATH];
5564   char selected_filename[MAX_PATH];
5565   play_options playopts;
5566
5567   *filename = 0;
5568
5569   nGame = Picker_GetSelectedItem(hwndList);
5570   if (nGame != -1)
5571   {
5572      strcpy(filename, drivers[nGame]->name);
5573      strcpy(selected_filename, drivers[nGame]->name);
5574   }
5575   if (CommonFileDialog(GetOpenFileName, filename, FILETYPE_SAVESTATE_FILES))
5576   {
5577      mame_file* pSaveState;
5578      char drive[_MAX_DRIVE];
5579      char dir[_MAX_DIR];
5580      char ext[_MAX_EXT];
5581
5582      char path[MAX_PATH];
5583      char fname[MAX_PATH];
5584      char bare_fname[_MAX_FNAME];
5585      char *state_fname;
5586      int rc;
5587
5588      _splitpath(filename, drive, dir, bare_fname, ext);
5589
5590      // parse path
5591      sprintf(path,"%s%s",drive,dir);
5592      sprintf(fname,"%s%s",bare_fname,ext);
5593      if (path[strlen(path)-1] == '\\')
5594         path[strlen(path)-1] = 0; // take off trailing back slash
5595
5596#ifdef MESS
5597      {
5598         state_fname = filename;
5599      }
5600#else // !MESS
5601      {
5602         char *cPos=0;
5603         int  iPos=0;
5604         char romname[MAX_PATH];
5605
5606         cPos = strchr(bare_fname, '-' );
5607         iPos = cPos ? cPos - bare_fname : strlen(bare_fname);
5608         strncpy(romname, bare_fname, iPos );
5609         romname[iPos] = '\0';
5610         if( strcmp(selected_filename,romname) != 0 )
5611         {
5612            MameMessageBox("'%s' is not a valid savestate file for game '%s'.", filename, selected_filename);
5613            return;
5614         }
5615         state_fname = fname;
5616      }
5617#endif // MESS
5618
5619      mame_fopen_options(Mame32Global(), SEARCHPATH_STATE, state_fname, OPEN_FLAG_READ, &pSaveState);
5620      if (pSaveState == NULL)
5621      {
5622         MameMessageBox("Could not open '%s' as a valid savestate file.", filename);
5623         return;
5624      }
5625
5626      // call the MAME core function to check the save state file
5627      rc = state_save_check_file(pSaveState, selected_filename, TRUE, MameMessageBox);
5628      mame_fclose(pSaveState);
5629      if (rc)
5630         return;
5631
5632      memset(&playopts, 0, sizeof(playopts));
5633#ifdef MESS
5634      playopts.state = state_fname;
5635#else
5636      {
5637         char *cPos;
5638         cPos = strrchr(bare_fname, '-' );
5639         cPos = cPos+1;
5640         if( strlen(cPos) >0)
5641         {
5642            playopts.state = cPos;
5643         }
5644      }
5645#endif
5646
5647      MamePlayGameWithOptions(nGame, &playopts);
5648   }
5649}
5650
5651static void MamePlayRecordGame()
5652{
5653   int  nGame;
5654   char filename[MAX_PATH];
5655   *filename = 0;
5656
5657   nGame = Picker_GetSelectedItem(hwndList);
5658   strcpy(filename, drivers[nGame]->name);
5659
5660   if (CommonFileDialog(GetSaveFileName, filename, FILETYPE_INPUT_FILES))
5661   {
5662      char drive[_MAX_DRIVE];
5663      char dir[_MAX_DIR];
5664      char fname[_MAX_FNAME];
5665      char ext[_MAX_EXT];
5666      char path[MAX_PATH];
5667      play_options playopts;
5668
5669      _splitpath(filename, drive, dir, fname, ext);
5670
5671      sprintf(path,"%s%s",drive,dir);
5672      if (path[strlen(path)-1] == '\\')
5673         path[strlen(path)-1] = 0; // take off trailing back slash
5674
5675      memset(&playopts, 0, sizeof(playopts));
5676      playopts.record = fname;
5677      MamePlayGameWithOptions(nGame, &playopts);
5678   }
5679}
5680
5681void MamePlayGame(void)
5682{
5683   int nGame;
5684   play_options playopts;
5685
5686   nGame = Picker_GetSelectedItem(hwndList);
5687
5688   memset(&playopts, 0, sizeof(playopts));
5689   MamePlayGameWithOptions(nGame, &playopts);
5690}
5691
5692static void MamePlayRecordWave()
5693{
5694   int  nGame;
5695   char filename[MAX_PATH];
5696   play_options playopts;
5697
5698   nGame = Picker_GetSelectedItem(hwndList);
5699   strcpy(filename, drivers[nGame]->name);
5700
5701   if (CommonFileDialog(GetSaveFileName, filename, FILETYPE_WAVE_FILES))
5702   {
5703      memset(&playopts, 0, sizeof(playopts));
5704      playopts.wavwrite = filename;
5705      MamePlayGameWithOptions(nGame, &playopts);
5706   }   
5707}
5708
5709static void MamePlayRecordMNG()
5710{
5711   int  nGame;
5712   char filename[MAX_PATH] = { 0, };
5713   play_options playopts;
5714
5715   nGame = Picker_GetSelectedItem(hwndList);
5716   strcpy(filename, drivers[nGame]->name);
5717
5718   if (CommonFileDialog(GetSaveFileName, filename, FILETYPE_MNG_FILES))
5719   {
5720      memset(&playopts, 0, sizeof(playopts));
5721      playopts.mngwrite = filename;
5722      MamePlayGameWithOptions(nGame, &playopts);
5723   }   
5724}
5725
5726static void MamePlayGameWithOptions(int nGame, const play_options *playopts)
5727{
5728   DWORD dwExitCode;
5729
5730#ifdef MESS
5731   if (!MessApproveImageList(hMain, nGame))
5732      return;
5733#endif
5734
5735   if (g_pJoyGUI != NULL)
5736      KillTimer(hMain, JOYGUI_TIMER);
5737   if (GetCycleScreenshot() > 0)
5738      KillTimer(hMain, SCREENSHOT_TIMER);
5739
5740   in_emulation = TRUE;
5741
5742   dwExitCode = RunMAME(nGame, playopts);
5743   if (dwExitCode == 0)
5744   {
5745      IncrementPlayCount(nGame);
5746      ListView_RedrawItems(hwndList, GetSelectedPick(), GetSelectedPick());
5747   }
5748   else
5749   {
5750      ShowWindow(hMain, SW_SHOW);
5751   }
5752
5753   in_emulation = FALSE;
5754
5755   // re-sort if sorting on # of times played
5756   if (GetSortColumn() == COLUMN_PLAYED)
5757      Picker_Sort(hwndList);
5758
5759   UpdateStatusBar();
5760
5761   ShowWindow(hMain, SW_SHOW);
5762   SetFocus(hwndList);
5763
5764   if (g_pJoyGUI != NULL)
5765      SetTimer(hMain, JOYGUI_TIMER, JOYGUI_MS, NULL);
5766   if (GetCycleScreenshot() > 0)
5767      SetTimer(hMain, SCREENSHOT_TIMER, GetCycleScreenshot()*1000, NULL); //scale to seconds
5768}
5769
5770/* Toggle ScreenShot ON/OFF */
5771static void ToggleScreenShot(void)
5772{
5773   BOOL showScreenShot = GetShowScreenShot();
5774
5775   SetShowScreenShot((showScreenShot) ? FALSE : TRUE);
5776   UpdateScreenShot();
5777
5778   /* Redraw list view */
5779   if (hBackground != NULL && showScreenShot)
5780      InvalidateRect(hwndList, NULL, FALSE);
5781}
5782
5783static void AdjustMetrics(void)
5784{
5785   HDC hDC;
5786   TEXTMETRIC tm;
5787   int xtraX, xtraY;
5788   AREA area;
5789   int  offX, offY;
5790   int  maxX, maxY;
5791   COLORREF textColor;
5792   TCHAR szClass[128];
5793   HWND hWnd;
5794
5795   /* WM_SETTINGCHANGE also */
5796   xtraX  = GetSystemMetrics(SM_CXFIXEDFRAME); /* Dialog frame width */
5797   xtraY  = GetSystemMetrics(SM_CYFIXEDFRAME); /* Dialog frame height */
5798   xtraY += GetSystemMetrics(SM_CYMENUSIZE);   /* Menu height */
5799   xtraY += GetSystemMetrics(SM_CYCAPTION);   /* Caption Height */
5800   maxX   = GetSystemMetrics(SM_CXSCREEN);    /* Screen Width */
5801   maxY   = GetSystemMetrics(SM_CYSCREEN);    /* Screen Height */
5802
5803   hDC = GetDC(hMain);
5804   GetTextMetrics (hDC, &tm);
5805
5806   /* Convert MIN Width/Height from Dialog Box Units to pixels. */
5807   MIN_WIDTH  = (int)((tm.tmAveCharWidth / 4.0) * DBU_MIN_WIDTH)  + xtraX;
5808   MIN_HEIGHT = (int)((tm.tmHeight      / 8.0) * DBU_MIN_HEIGHT) + xtraY;
5809   ReleaseDC(hMain, hDC);
5810
5811   if ((textColor = GetListFontColor()) == RGB(255, 255, 255))
5812      textColor = RGB(240, 240, 240);
5813
5814   hWnd = GetWindow(hMain, GW_CHILD);
5815   while(hWnd)
5816   {
5817      if (GetClassName(hWnd, szClass, sizeof(szClass) / sizeof(szClass[0])))
5818      {
5819         if (!_tcscmp(szClass, TEXT("SysListView32")))
5820         {
5821            ListView_SetBkColor(hWnd, GetSysColor(COLOR_WINDOW));
5822            ListView_SetTextColor(hWnd, textColor);
5823         }
5824         else if (!_tcscmp(szClass, TEXT("SysTreeView32")))
5825         {
5826            TreeView_SetBkColor(hTreeView, GetSysColor(COLOR_WINDOW));
5827            TreeView_SetTextColor(hTreeView, textColor);
5828         }
5829      }
5830      hWnd = GetWindow(hWnd, GW_HWNDNEXT);
5831   }
5832
5833   GetWindowArea(&area);
5834
5835   offX = area.x + area.width;
5836   offY = area.y + area.height;
5837
5838   if (offX > maxX)
5839   {
5840      offX = maxX;
5841      area.x = (offX - area.width > 0) ? (offX - area.width) : 0;
5842   }
5843   if (offY > maxY)
5844   {
5845      offY = maxY;
5846      area.y = (offY - area.height > 0) ? (offY - area.height) : 0;
5847   }
5848
5849   SetWindowArea(&area);
5850   SetWindowPos(hMain, 0, area.x, area.y, area.width, area.height, SWP_NOZORDER | SWP_SHOWWINDOW | SWP_NOACTIVATE);
5851}
5852
5853
5854/* Adjust options - tune them to the currently selected game */
5855static void EnablePlayOptions(int nIndex, core_options *o)
5856{
5857}
5858
5859int FindIconIndex(int nIconResource)
5860{
5861   int i;
5862   for(i = 0; g_iconData[i].icon_name; i++)
5863   {
5864      if (g_iconData[i].resource == nIconResource)
5865         return i;
5866   }
5867   return -1;
5868}
5869
5870int FindIconIndexByName(const char *icon_name)
5871{
5872   int i;
5873   for (i = 0; g_iconData[i].icon_name; i++)
5874   {
5875      if (!strcmp(g_iconData[i].icon_name, icon_name))
5876         return i;
5877   }
5878   return -1;
5879}
5880
5881static int GetIconForDriver(int nItem)
5882{
5883   int iconRoms;
5884
5885   if (DriverUsesRoms(nItem))
5886   {
5887      int audit_result = GetRomAuditResults(nItem);
5888      if (IsAuditResultKnown(audit_result) == FALSE)
5889         return 2;
5890
5891      if (IsAuditResultYes(audit_result))
5892         iconRoms = 1;
5893      else
5894         iconRoms = 0;
5895   }
5896   else
5897      iconRoms = 1;
5898
5899   // iconRoms is now either 0 (no roms), 1 (roms), or 2 (unknown)
5900
5901   /* these are indices into icon_names, which maps into our image list
5902    * also must match IDI_WIN_NOROMS + iconRoms
5903     */
5904
5905   // Show Red-X if the ROMs are present and flagged as NOT WORKING
5906   if (iconRoms == 1 && DriverIsBroken(nItem))
5907      iconRoms = FindIconIndex(IDI_WIN_REDX);
5908
5909   // show clone icon if we have roms and game is working
5910   if (iconRoms == 1 && DriverIsClone(nItem))
5911      iconRoms = FindIconIndex(IDI_WIN_CLONE);
5912
5913   // if we have the roms, then look for a custom per-game icon to override
5914   if (iconRoms == 1 || iconRoms == 3)
5915   {
5916      if (icon_index[nItem] == 0)
5917         AddDriverIcon(nItem,iconRoms);
5918      iconRoms = icon_index[nItem];
5919   }
5920
5921   return iconRoms;
5922}
5923
5924static BOOL HandleTreeContextMenu(HWND hWnd, WPARAM wParam, LPARAM lParam)
5925{
5926   HMENU hTreeMenu;
5927   HMENU hMenu;
5928   TVHITTESTINFO hti;
5929   POINT pt;
5930
5931   if ((HWND)wParam != GetDlgItem(hWnd, IDC_TREE))
5932      return FALSE;
5933
5934   pt.x = GET_X_LPARAM(lParam);
5935   pt.y = GET_Y_LPARAM(lParam);
5936   if (pt.x < 0 && pt.y < 0)
5937      GetCursorPos(&pt);
5938
5939   /* select the item that was right clicked or shift-F10'ed */
5940   hti.pt = pt;
5941   ScreenToClient(hTreeView,&hti.pt);
5942   (void)TreeView_HitTest(hTreeView,&hti);
5943   if ((hti.flags & TVHT_ONITEM) != 0)
5944      TreeView_SelectItem(hTreeView,hti.hItem);
5945
5946   hTreeMenu = LoadMenu(hInst,MAKEINTRESOURCE(IDR_CONTEXT_TREE));
5947
5948   InitTreeContextMenu(hTreeMenu);
5949
5950   hMenu = GetSubMenu(hTreeMenu, 0);
5951   
5952   UpdateMenu(hMenu);
5953
5954   TrackPopupMenu(hMenu,TPM_LEFTALIGN | TPM_RIGHTBUTTON,pt.x,pt.y,0,hWnd,NULL);
5955
5956   DestroyMenu(hTreeMenu);
5957
5958   return TRUE;
5959}
5960
5961
5962
5963static void GamePicker_OnBodyContextMenu(POINT pt)
5964{
5965   HMENU hMenuLoad;
5966   HMENU hMenu;
5967
5968   hMenuLoad = LoadMenu(hInst, MAKEINTRESOURCE(IDR_CONTEXT_MENU));
5969   hMenu = GetSubMenu(hMenuLoad, 0);
5970   InitBodyContextMenu(hMenu);
5971   
5972   UpdateMenu(hMenu);
5973
5974   TrackPopupMenu(hMenu,TPM_LEFTALIGN | TPM_RIGHTBUTTON,pt.x,pt.y,0,hMain,NULL);
5975
5976   DestroyMenu(hMenuLoad);
5977}
5978
5979
5980
5981static BOOL HandleScreenShotContextMenu(HWND hWnd, WPARAM wParam, LPARAM lParam)
5982{
5983   HMENU hMenuLoad;
5984   HMENU hMenu;
5985   POINT pt;
5986
5987   if ((HWND)wParam != GetDlgItem(hWnd, IDC_SSPICTURE) && (HWND)wParam != GetDlgItem(hWnd, IDC_SSFRAME))
5988      return FALSE;
5989
5990   pt.x = GET_X_LPARAM(lParam);
5991   pt.y = GET_Y_LPARAM(lParam);
5992   if (pt.x < 0 && pt.y < 0)
5993      GetCursorPos(&pt);
5994
5995   hMenuLoad = LoadMenu(hInst, MAKEINTRESOURCE(IDR_CONTEXT_SCREENSHOT));
5996   hMenu = GetSubMenu(hMenuLoad, 0);
5997
5998   UpdateMenu(hMenu);
5999
6000   TrackPopupMenu(hMenu,TPM_LEFTALIGN | TPM_RIGHTBUTTON,pt.x,pt.y,0,hWnd,NULL);
6001
6002   DestroyMenu(hMenuLoad);
6003
6004   return TRUE;
6005}
6006
6007static void UpdateMenu(HMENU hMenu)
6008{
6009   TCHAR         buf[200];
6010   MENUITEMINFO   mItem;
6011   int          nGame = Picker_GetSelectedItem(hwndList);
6012   LPTREEFOLDER lpFolder = GetCurrentFolder();
6013   int i;
6014   const char *pParent;
6015   TCHAR* t_description;
6016
6017   if (have_selection)
6018   {
6019      t_description = tstring_from_utf8(ConvertAmpersandString(ModifyThe(drivers[nGame]->description)));
6020      if( !t_description )
6021         return;
6022     
6023      _sntprintf(buf, ARRAY_LENGTH(buf), g_szPlayGameString, t_description);
6024
6025      mItem.cbSize    = sizeof(mItem);
6026      mItem.fMask     = MIIM_TYPE;
6027      mItem.fType     = MFT_STRING;
6028      mItem.dwTypeData = buf;
6029      mItem.cch       = _tcslen(mItem.dwTypeData);
6030
6031      SetMenuItemInfo(hMenu, ID_FILE_PLAY, FALSE, &mItem);
6032
6033      EnableMenuItem(hMenu, ID_CONTEXT_SELECT_RANDOM, MF_ENABLED);
6034     
6035      free(t_description);
6036   }
6037   else
6038   {
6039      EnableMenuItem(hMenu, ID_FILE_PLAY,          MF_GRAYED);
6040      EnableMenuItem(hMenu, ID_FILE_PLAY_RECORD,      MF_GRAYED);
6041      EnableMenuItem(hMenu, ID_GAME_PROPERTIES,      MF_GRAYED);
6042      EnableMenuItem(hMenu, ID_CONTEXT_SELECT_RANDOM, MF_GRAYED);
6043   }
6044
6045   if (oldControl)
6046   {
6047      EnableMenuItem(hMenu, ID_CUSTOMIZE_FIELDS, MF_GRAYED);
6048      EnableMenuItem(hMenu, ID_GAME_PROPERTIES,  MF_GRAYED);
6049      EnableMenuItem(hMenu, ID_OPTIONS_DEFAULTS, MF_GRAYED);
6050   }
6051
6052   if (lpFolder->m_dwFlags & F_CUSTOM)
6053   {
6054       EnableMenuItem(hMenu,ID_CONTEXT_REMOVE_CUSTOM,MF_ENABLED);
6055      EnableMenuItem(hMenu,ID_CONTEXT_RENAME_CUSTOM,MF_ENABLED);
6056   }
6057   else
6058   {
6059       EnableMenuItem(hMenu,ID_CONTEXT_REMOVE_CUSTOM,MF_GRAYED);
6060      EnableMenuItem(hMenu,ID_CONTEXT_RENAME_CUSTOM,MF_GRAYED);
6061   }
6062   pParent = GetFolderNameByID(lpFolder->m_nParent+1);
6063
6064   if( (strcmp(lpFolder->m_lpTitle, "Vector" ) == 0) ||
6065      (pParent && (strcmp(pParent, "Source" ) == 0) ) )
6066      EnableMenuItem(hMenu,ID_FOLDER_PROPERTIES,MF_ENABLED);
6067   else
6068      EnableMenuItem(hMenu,ID_FOLDER_PROPERTIES,MF_GRAYED);
6069
6070   CheckMenuRadioItem(hMenu, ID_VIEW_TAB_SCREENSHOT, ID_VIEW_TAB_HISTORY,
6071                  ID_VIEW_TAB_SCREENSHOT + TabView_GetCurrentTab(hTabCtrl), MF_BYCOMMAND);
6072
6073   // set whether we're showing the tab control or not
6074   if (bShowTabCtrl)
6075      CheckMenuItem(hMenu,ID_VIEW_PAGETAB,MF_BYCOMMAND | MF_CHECKED);
6076   else
6077      CheckMenuItem(hMenu,ID_VIEW_PAGETAB,MF_BYCOMMAND | MF_UNCHECKED);
6078
6079
6080   for (i=0;i<MAX_TAB_TYPES;i++)
6081   {
6082      // disable menu items for tabs we're not currently showing
6083      if (GetShowTab(i))
6084         EnableMenuItem(hMenu,ID_VIEW_TAB_SCREENSHOT + i,MF_BYCOMMAND | MF_ENABLED);
6085      else
6086         EnableMenuItem(hMenu,ID_VIEW_TAB_SCREENSHOT + i,MF_BYCOMMAND | MF_GRAYED);
6087
6088      // check toggle menu items
6089      if (GetShowTab(i))
6090         CheckMenuItem(hMenu, ID_TOGGLE_TAB_SCREENSHOT + i,MF_BYCOMMAND | MF_CHECKED);
6091      else
6092         CheckMenuItem(hMenu, ID_TOGGLE_TAB_SCREENSHOT + i,MF_BYCOMMAND | MF_UNCHECKED);
6093   }
6094
6095   for (i=0;i<MAX_FOLDERS;i++)
6096   {
6097      if (GetShowFolder(i))
6098         CheckMenuItem(hMenu,ID_CONTEXT_SHOW_FOLDER_START + i,MF_BYCOMMAND | MF_CHECKED);
6099      else
6100         CheckMenuItem(hMenu,ID_CONTEXT_SHOW_FOLDER_START + i,MF_BYCOMMAND | MF_UNCHECKED);
6101   }
6102
6103}
6104
6105void InitTreeContextMenu(HMENU hTreeMenu)
6106{
6107   MENUITEMINFO mii;
6108   HMENU hMenu;
6109   int i;
6110   extern FOLDERDATA g_folderData[];
6111
6112   ZeroMemory(&mii,sizeof(mii));
6113   mii.cbSize = sizeof(mii);
6114
6115   mii.wID = -1;
6116   mii.fMask = MIIM_SUBMENU | MIIM_ID;
6117
6118   hMenu = GetSubMenu(hTreeMenu, 0);
6119
6120   if (GetMenuItemInfo(hMenu,3,TRUE,&mii) == FALSE)
6121   {
6122      dprintf("can't find show folders context menu");
6123      return;
6124   }
6125
6126   if (mii.hSubMenu == NULL)
6127   {
6128      dprintf("can't find submenu for show folders context menu");
6129      return;
6130   }
6131
6132   hMenu = mii.hSubMenu;
6133   
6134   for (i=0;g_folderData[i].m_lpTitle != NULL;i++)
6135   {
6136      TCHAR* t_title = tstring_from_utf8(g_folderData[i].m_lpTitle);
6137      if( !t_title )
6138         return;
6139     
6140      mii.fMask = MIIM_TYPE | MIIM_ID;
6141      mii.fType = MFT_STRING;
6142      mii.dwTypeData = t_title;
6143      mii.cch = _tcslen(mii.dwTypeData);
6144      mii.wID = ID_CONTEXT_SHOW_FOLDER_START + g_folderData[i].m_nFolderId;
6145
6146
6147      // menu in resources has one empty item (needed for the submenu to setup properly)
6148      // so overwrite this one, append after
6149      if (i == 0)
6150         SetMenuItemInfo(hMenu,ID_CONTEXT_SHOW_FOLDER_START,FALSE,&mii);
6151      else
6152         InsertMenuItem(hMenu,i,FALSE,&mii);
6153         
6154      free(t_title);
6155   }
6156
6157}
6158
6159void InitBodyContextMenu(HMENU hBodyContextMenu)
6160{
6161   LPTREEFOLDER lpFolder;
6162   TCHAR tmp[30];
6163   MENUITEMINFO mii;
6164   ZeroMemory(&mii,sizeof(mii));
6165   mii.cbSize = sizeof(mii);
6166
6167   if (GetMenuItemInfo(hBodyContextMenu,ID_FOLDER_SOURCEPROPERTIES,FALSE,&mii) == FALSE)
6168   {
6169      dprintf("can't find show folders context menu");
6170      return;
6171   }
6172   lpFolder = GetFolderByName(FOLDER_SOURCE, GetDriverFilename(Picker_GetSelectedItem(hwndList)) );
6173   _sntprintf(tmp,ARRAY_LENGTH(tmp),TEXT("Properties for %s"),lpFolder->m_lptTitle );
6174   mii.fMask = MIIM_TYPE | MIIM_ID;
6175   mii.fType = MFT_STRING;
6176   mii.dwTypeData = tmp;
6177   mii.cch = _tcslen(mii.dwTypeData);
6178   mii.wID = ID_FOLDER_SOURCEPROPERTIES;
6179
6180
6181   // menu in resources has one default item
6182   // so overwrite this one
6183   SetMenuItemInfo(hBodyContextMenu,ID_FOLDER_SOURCEPROPERTIES,FALSE,&mii);
6184   if( ! DriverIsVector(Picker_GetSelectedItem(hwndList) ) )
6185      EnableMenuItem(hBodyContextMenu, ID_FOLDER_VECTORPROPERTIES, MF_GRAYED);
6186}
6187
6188
6189void ToggleShowFolder(int folder)
6190{
6191   int current_id = GetCurrentFolderID();
6192
6193   SetWindowRedraw(hwndList,FALSE);
6194
6195   SetShowFolder(folder,!GetShowFolder(folder));
6196
6197   ResetTreeViewFolders();
6198   SelectTreeViewFolder(current_id);
6199
6200   SetWindowRedraw(hwndList,TRUE);
6201}
6202
6203static LRESULT CALLBACK HistoryWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
6204{
6205   if (hBackground)
6206   {
6207      switch (uMsg)
6208      {
6209       case WM_MOUSEMOVE:
6210      {
6211         if (MouseHasBeenMoved())
6212            ShowCursor(TRUE);
6213         break;
6214      }
6215   
6216      case WM_ERASEBKGND:
6217         return TRUE;
6218      case WM_PAINT:
6219      {
6220         POINT p = { 0, 0 };
6221           
6222         /* get base point of background bitmap */
6223         MapWindowPoints(hWnd,hTreeView,&p,1);
6224         PaintBackgroundImage(hWnd, NULL, p.x, p.y);
6225         /* to ensure our parent procedure repaints the whole client area */
6226         InvalidateRect(hWnd, NULL, FALSE);
6227         break;
6228      }
6229      }
6230   }
6231   return CallWindowProc(g_lpHistoryWndProc, hWnd, uMsg, wParam, lParam);
6232}
6233
6234static LRESULT CALLBACK PictureFrameWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
6235{
6236   switch (uMsg)
6237   {
6238   case WM_MOUSEMOVE:
6239    {
6240      if (MouseHasBeenMoved())
6241         ShowCursor(TRUE);
6242      break;
6243    }
6244 
6245    case WM_NCHITTEST :
6246   {
6247      POINT pt;
6248      RECT  rect;
6249      HWND hHistory = GetDlgItem(hMain, IDC_HISTORY);
6250
6251      pt.x = LOWORD(lParam);
6252      pt.y = HIWORD(lParam);
6253      GetWindowRect(hHistory, &rect);
6254      // check if they clicked on the picture area (leave 6 pixel no man's land
6255      // by the history window to reduce mistaken clicks)
6256      // no more no man's land, the Cursor changes when Edit control is left, should be enough feedback
6257      if (have_history &&       
6258         ( ( (TabView_GetCurrentTab(hTabCtrl) == TAB_HISTORY) ||
6259          (TabView_GetCurrentTab(hTabCtrl) == GetHistoryTab() && GetShowTab(TAB_HISTORY) == FALSE) ||
6260         (TAB_ALL == GetHistoryTab() && GetShowTab(TAB_HISTORY) == FALSE) ) &&
6261//           (rect.top - 6) < pt.y && pt.y < (rect.bottom + 6) ) )
6262                 PtInRect( &rect, pt ) ) )
6263
6264      {
6265         return HTTRANSPARENT;
6266      }
6267      else
6268      {
6269         return HTCLIENT;
6270      }
6271   }
6272   break;
6273   case WM_CONTEXTMENU:
6274      if ( HandleScreenShotContextMenu(hWnd, wParam, lParam))
6275         return FALSE;
6276      break;
6277   }
6278
6279   if (hBackground)
6280   {
6281      switch (uMsg)
6282      {
6283      case WM_ERASEBKGND :
6284         return TRUE;
6285      case WM_PAINT :
6286      {
6287         RECT rect,nodraw_rect;
6288         HRGN region,nodraw_region;
6289         POINT p = { 0, 0 };
6290
6291         /* get base point of background bitmap */
6292         MapWindowPoints(hWnd,hTreeView,&p,1);
6293
6294         /* get big region */
6295         GetClientRect(hWnd,&rect);
6296         region = CreateRectRgnIndirect(&rect);
6297
6298         if (IsWindowVisible(GetDlgItem(hMain,IDC_HISTORY)))
6299         {
6300            /* don't draw over this window */
6301            GetWindowRect(GetDlgItem(hMain,IDC_HISTORY),&nodraw_rect);
6302            MapWindowPoints(HWND_DESKTOP,hWnd,(LPPOINT)&nodraw_rect,2);
6303            nodraw_region = CreateRectRgnIndirect(&nodraw_rect);
6304            CombineRgn(region,region,nodraw_region,RGN_DIFF);
6305            DeleteObject(nodraw_region);
6306         }
6307         if (IsWindowVisible(GetDlgItem(hMain,IDC_SSPICTURE)))
6308         {
6309            /* don't draw over this window */
6310            GetWindowRect(GetDlgItem(hMain,IDC_SSPICTURE),&nodraw_rect);
6311            MapWindowPoints(HWND_DESKTOP,hWnd,(LPPOINT)&nodraw_rect,2);
6312            nodraw_region = CreateRectRgnIndirect(&nodraw_rect);
6313            CombineRgn(region,region,nodraw_region,RGN_DIFF);
6314            DeleteObject(nodraw_region);
6315         }
6316
6317         PaintBackgroundImage(hWnd,region,p.x,p.y);
6318
6319         DeleteObject(region);
6320
6321         /* to ensure our parent procedure repaints the whole client area */
6322         InvalidateRect(hWnd, NULL, FALSE);
6323
6324         break;
6325      }
6326      }
6327   }
6328   return CallWindowProc(g_lpPictureFrameWndProc, hWnd, uMsg, wParam, lParam);
6329}
6330
6331static LRESULT CALLBACK PictureWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
6332{
6333   switch (uMsg)
6334   {
6335   case WM_ERASEBKGND :
6336      return TRUE;
6337   case WM_PAINT :
6338   {
6339      PAINTSTRUCT ps;
6340      HDC   hdc,hdc_temp;
6341      RECT rect;
6342      HBITMAP old_bitmap;
6343
6344      int width,height;
6345
6346      RECT rect2;
6347      HBRUSH hBrush;
6348      HBRUSH holdBrush;
6349      HRGN region1, region2;
6350      int nBordersize;
6351      nBordersize = GetScreenshotBorderSize();
6352      hBrush = CreateSolidBrush(GetScreenshotBorderColor());
6353
6354      hdc = BeginPaint(hWnd,&ps);
6355
6356      hdc_temp = CreateCompatibleDC(hdc);
6357      if (ScreenShotLoaded())
6358      {
6359         width = GetScreenShotWidth();
6360         height = GetScreenShotHeight();
6361
6362         old_bitmap = SelectObject(hdc_temp,GetScreenShotHandle());
6363      }
6364      else
6365      {
6366         BITMAP bmp;
6367
6368         GetObject(hMissing_bitmap,sizeof(BITMAP),&bmp);
6369         width = bmp.bmWidth;
6370         height = bmp.bmHeight;
6371
6372         old_bitmap = SelectObject(hdc_temp,hMissing_bitmap);
6373      }
6374
6375      GetClientRect(hWnd,&rect);
6376
6377      rect2 = rect;
6378      //Configurable Borders around images
6379      rect.bottom -= nBordersize;
6380      if( rect.bottom < 0)
6381         rect.bottom = rect2.bottom;
6382      rect.right -= nBordersize;
6383      if( rect.right < 0)
6384         rect.right = rect2.right;
6385      rect.top += nBordersize;
6386      if( rect.top > rect.bottom )
6387         rect.top = rect2.top;
6388      rect.left += nBordersize;
6389      if( rect.left > rect.right )
6390         rect.left = rect2.left;
6391      region1 = CreateRectRgnIndirect(&rect);
6392      region2 = CreateRectRgnIndirect(&rect2);
6393      CombineRgn(region2,region2,region1,RGN_DIFF);
6394      holdBrush = SelectObject(hdc, hBrush);
6395
6396      FillRgn(hdc,region2, hBrush );
6397      SelectObject(hdc, holdBrush);
6398      DeleteObject(hBrush);
6399
6400      SetStretchBltMode(hdc,STRETCH_HALFTONE);
6401      StretchBlt(hdc,nBordersize,nBordersize,rect.right-rect.left,rect.bottom-rect.top,
6402               hdc_temp,0,0,width,height,SRCCOPY);
6403      SelectObject(hdc_temp,old_bitmap);
6404      DeleteDC(hdc_temp);
6405
6406      EndPaint(hWnd,&ps);
6407
6408      return TRUE;
6409   }
6410   }
6411
6412   return CallWindowProc(g_lpPictureWndProc, hWnd, uMsg, wParam, lParam);
6413}
6414
6415void RemoveCurrentGameCustomFolder(void)
6416{
6417    RemoveGameCustomFolder(Picker_GetSelectedItem(hwndList));
6418}
6419
6420void RemoveGameCustomFolder(int driver_index)
6421{
6422    int i;
6423   TREEFOLDER **folders;
6424   int num_folders;
6425
6426   GetFolders(&folders,&num_folders);
6427   
6428   for (i=0;i<num_folders;i++)
6429   {
6430       if (folders[i]->m_dwFlags & F_CUSTOM && folders[i]->m_nFolderId == GetCurrentFolderID())
6431      {
6432          int current_pick_index;
6433
6434          RemoveFromCustomFolder(folders[i],driver_index);
6435
6436         if (driver_index == Picker_GetSelectedItem(hwndList))
6437         {
6438            /* if we just removed the current game,
6439              move the current selection so that when we rebuild the listview it
6440              leaves the cursor on next or previous one */
6441         
6442            current_pick_index = GetSelectedPick();
6443            Picker_SetSelectedPick(hwndList, GetSelectedPick() + 1);
6444            if (current_pick_index == GetSelectedPick()) /* we must have deleted the last item */
6445              Picker_SetSelectedPick(hwndList, GetSelectedPick() - 1);
6446         }
6447
6448         ResetListView();
6449         return;
6450      }
6451   }
6452   MessageBox(GetMainWindow(), TEXT("Error searching for custom folder"), TEXT(MAME32NAME), MB_OK | MB_ICONERROR);
6453
6454}
6455
6456
6457void BeginListViewDrag(NM_LISTVIEW *pnmv)
6458{
6459    LV_ITEM lvi;
6460   POINT pt;
6461
6462   lvi.iItem = pnmv->iItem;
6463   lvi.mask    = LVIF_PARAM;
6464   ListView_GetItem(hwndList, &lvi);
6465
6466   game_dragged = lvi.lParam;
6467
6468   pt.x = 0;
6469   pt.y = 0;
6470
6471   /* Tell the list view control to create an image to use
6472      for dragging. */
6473    himl_drag = ListView_CreateDragImage(hwndList,pnmv->iItem,&pt);
6474 
6475    /* Start the drag operation. */
6476    ImageList_BeginDrag(himl_drag, 0, 0, 0);
6477
6478   pt = pnmv->ptAction;
6479   ClientToScreen(hwndList,&pt);
6480   ImageList_DragEnter(GetDesktopWindow(),pt.x,pt.y);
6481
6482    /* Hide the mouse cursor, and direct mouse input to the
6483      parent window. */
6484    SetCapture(hMain);
6485
6486   prev_drag_drop_target = NULL;
6487
6488    g_listview_dragging = TRUE;
6489
6490}
6491
6492void MouseMoveListViewDrag(POINTS p)
6493{
6494   HTREEITEM htiTarget;
6495   TV_HITTESTINFO tvht;
6496
6497   POINT pt;
6498   pt.x = p.x;
6499   pt.y = p.y;
6500
6501   ClientToScreen(hMain,&pt);
6502
6503   ImageList_DragMove(pt.x,pt.y);
6504
6505   MapWindowPoints(GetDesktopWindow(),hTreeView,&pt,1);
6506
6507   tvht.pt = pt;
6508   htiTarget = TreeView_HitTest(hTreeView,&tvht);
6509
6510   if (htiTarget != prev_drag_drop_target)
6511   {
6512      ImageList_DragShowNolock(FALSE);
6513      if (htiTarget != NULL)
6514         TreeView_SelectDropTarget(hTreeView,htiTarget);
6515      else
6516         TreeView_SelectDropTarget(hTreeView,NULL);
6517      ImageList_DragShowNolock(TRUE);
6518     
6519      prev_drag_drop_target = htiTarget;
6520   }
6521}
6522
6523void ButtonUpListViewDrag(POINTS p)
6524{
6525    POINT pt;
6526    HTREEITEM htiTarget;
6527   TV_HITTESTINFO tvht;
6528   TVITEM tvi;
6529   
6530   ReleaseCapture();
6531
6532    ImageList_DragLeave(hwndList);
6533    ImageList_EndDrag();
6534   ImageList_Destroy(himl_drag);
6535
6536   TreeView_SelectDropTarget(hTreeView,NULL);
6537
6538   g_listview_dragging = FALSE;
6539
6540   /* see where the game was dragged */
6541
6542   pt.x = p.x;
6543   pt.y = p.y;
6544
6545   MapWindowPoints(hMain,hTreeView,&pt,1);
6546
6547   tvht.pt = pt;
6548   htiTarget = TreeView_HitTest(hTreeView,&tvht);
6549   if (htiTarget == NULL)
6550   {
6551      LVHITTESTINFO lvhtti;
6552      LPTREEFOLDER folder;
6553      RECT rcList;
6554
6555      /* the user dragged a game onto something other than the treeview */
6556      /* try to remove if we're in a custom folder */
6557
6558      /* see if it was dragged within the list view; if so, ignore */
6559
6560      MapWindowPoints(hTreeView,hwndList,&pt,1);
6561      lvhtti.pt = pt;
6562      GetWindowRect(hwndList, &rcList);
6563      ClientToScreen(hwndList, &pt);
6564      if( PtInRect(&rcList, pt) != 0 )
6565         return;
6566
6567      folder = GetCurrentFolder();
6568      if (folder->m_dwFlags & F_CUSTOM)
6569      {
6570         /* dragged out of a custom folder, so let's remove it */
6571         RemoveCurrentGameCustomFolder();
6572      }
6573      return;
6574   }
6575
6576
6577   tvi.lParam = 0;
6578   tvi.mask  = TVIF_PARAM | TVIF_HANDLE;
6579   tvi.hItem = htiTarget;
6580
6581   if (TreeView_GetItem(hTreeView, &tvi))
6582   {
6583      LPTREEFOLDER folder = (LPTREEFOLDER)tvi.lParam;
6584      AddToCustomFolder(folder,game_dragged);
6585   }
6586
6587}
6588
6589static LPTREEFOLDER GetSelectedFolder(void)
6590{
6591   HTREEITEM htree;
6592   TVITEM tvi;
6593   htree = TreeView_GetSelection(hTreeView);
6594   if(htree != NULL)
6595   {
6596      tvi.hItem = htree;
6597      tvi.mask = TVIF_PARAM;
6598      TreeView_GetItem(hTreeView,&tvi);
6599      return (LPTREEFOLDER)tvi.lParam;
6600   }
6601   return NULL;
6602}
6603
6604static HICON GetSelectedFolderIcon(void)
6605{
6606   HTREEITEM htree;
6607   TVITEM tvi;
6608   HIMAGELIST hSmall_icon;
6609   LPTREEFOLDER folder;
6610   htree = TreeView_GetSelection(hTreeView);
6611
6612   if (htree != NULL)
6613   {
6614      tvi.hItem = htree;
6615      tvi.mask = TVIF_PARAM;
6616      TreeView_GetItem(hTreeView,&tvi);
6617     
6618      folder = (LPTREEFOLDER)tvi.lParam;
6619      //hSmall_icon = TreeView_GetImageList(hTreeView,(int)tvi.iImage);
6620      hSmall_icon = NULL;
6621      return ImageList_GetIcon(hSmall_icon, tvi.iImage, ILD_TRANSPARENT);
6622   }
6623   return NULL;
6624}
6625
6626/* Updates all currently displayed Items in the List with the latest Data*/
6627void UpdateListView(void)
6628{
6629   if( (GetViewMode() == VIEW_GROUPED) || (GetViewMode() == VIEW_DETAILS ) )
6630      ListView_RedrawItems(hwndList,ListView_GetTopIndex(hwndList),
6631                      ListView_GetTopIndex(hwndList)+ ListView_GetCountPerPage(hwndList) );
6632}
6633
6634void CalculateBestScreenShotRect(HWND hWnd, RECT *pRect, BOOL restrict_height)
6635{
6636   int    destX, destY;
6637   int    destW, destH;
6638   int      nBorder;
6639   RECT   rect;
6640   /* for scaling */       
6641   int x, y;
6642   int rWidth, rHeight;
6643   double scale;
6644   BOOL bReduce = FALSE;
6645
6646   GetClientRect(hWnd, &rect);
6647
6648   // Scale the bitmap to the frame specified by the passed in hwnd
6649   if (ScreenShotLoaded())
6650   {
6651      x = GetScreenShotWidth();
6652      y = GetScreenShotHeight();
6653   }
6654   else
6655   {
6656      BITMAP bmp;
6657      GetObject(hMissing_bitmap,sizeof(BITMAP),&bmp);
6658
6659      x = bmp.bmWidth;
6660      y = bmp.bmHeight;
6661   }
6662   rWidth   = (rect.right  - rect.left);
6663   rHeight = (rect.bottom - rect.top);
6664
6665   /* Limit the screen shot to max height of 264 */
6666   if (restrict_height == TRUE && rHeight > 264)
6667   {
6668      rect.bottom = rect.top + 264;
6669      rHeight = 264;
6670   }
6671
6672   /* If the bitmap does NOT fit in the screenshot area */
6673   if (x > rWidth - 10 || y > rHeight - 10)
6674   {
6675      rect.right   -= 10;
6676      rect.bottom -= 10;
6677      rWidth   -= 10;
6678      rHeight -= 10;
6679      bReduce = TRUE;
6680      /* Try to scale it properly */
6681      /*   assumes square pixels, doesn't consider aspect ratio */
6682      if (x > y)
6683         scale = (double)rWidth / x;
6684      else
6685         scale = (double)rHeight / y;
6686
6687      destW = (int)(x * scale);
6688      destH = (int)(y * scale);
6689
6690      /* If it's still too big, scale again */
6691      if (destW > rWidth || destH > rHeight)
6692      {
6693         if (destW > rWidth)
6694            scale = (double)rWidth   / destW;
6695         else
6696            scale = (double)rHeight / destH;
6697
6698         destW = (int)(destW * scale);
6699         destH = (int)(destH * scale);
6700      }
6701   }
6702   else
6703   {
6704      if (GetStretchScreenShotLarger())
6705      {
6706         rect.right   -= 10;
6707         rect.bottom -= 10;
6708         rWidth   -= 10;
6709         rHeight -= 10;
6710         bReduce = TRUE;
6711         // Try to scale it properly
6712         // assumes square pixels, doesn't consider aspect ratio
6713         if (x < y)
6714            scale = (double)rWidth / x;
6715         else
6716            scale = (double)rHeight / y;
6717         
6718         destW = (int)(x * scale);
6719         destH = (int)(y * scale);
6720         
6721         // If it's too big, scale again
6722         if (destW > rWidth || destH > rHeight)
6723         {
6724            if (destW > rWidth)
6725               scale = (double)rWidth   / destW;
6726            else
6727               scale = (double)rHeight / destH;
6728           
6729            destW = (int)(destW * scale);
6730            destH = (int)(destH * scale);
6731         }
6732      }
6733      else
6734      {
6735         // Use the bitmaps size if it fits
6736         destW = x;
6737         destH = y;
6738      }
6739
6740   }
6741
6742
6743   destX = ((rWidth  - destW) / 2);
6744   destY = ((rHeight - destH) / 2);
6745
6746   if (bReduce)
6747   {
6748      destX += 5;
6749      destY += 5;
6750   }
6751   nBorder = GetScreenshotBorderSize();
6752   if( destX > nBorder+1)
6753      pRect->left   = destX - nBorder;
6754   else
6755      pRect->left   = 2;
6756   if( destY > nBorder+1)
6757      pRect->top     = destY - nBorder;
6758   else
6759      pRect->top     = 2;
6760   if( rWidth >= destX + destW + nBorder)
6761      pRect->right  = destX + destW + nBorder;
6762   else
6763      pRect->right  = rWidth - pRect->left;
6764   if( rHeight >= destY + destH + nBorder)
6765      pRect->bottom = destY + destH + nBorder;
6766   else
6767      pRect->bottom = rHeight - pRect->top;
6768}
6769
6770/*
6771  Switches to either fullscreen or normal mode, based on the
6772  current mode.
6773
6774  POSSIBLE BUGS:
6775  Removing the menu might cause problems later if some
6776  function tries to poll info stored in the menu. Don't
6777  know if you've done that, but this was the only way I
6778  knew to remove the menu dynamically.
6779*/
6780
6781void SwitchFullScreenMode(void)
6782{
6783   LONG lMainStyle;
6784   
6785   if (GetRunFullScreen())
6786   {
6787      // Return to normal
6788
6789      // Restore the menu
6790      SetMenu(hMain, LoadMenu(hInst,MAKEINTRESOURCE(IDR_UI_MENU)));
6791     
6792      // Refresh the checkmarks
6793      CheckMenuItem(GetMenu(hMain), ID_VIEW_FOLDERS, GetShowFolderList() ? MF_CHECKED : MF_UNCHECKED);
6794      CheckMenuItem(GetMenu(hMain), ID_VIEW_TOOLBARS, GetShowToolBar() ? MF_CHECKED : MF_UNCHECKED);   
6795      CheckMenuItem(GetMenu(hMain), ID_VIEW_STATUS, GetShowStatusBar() ? MF_CHECKED : MF_UNCHECKED);
6796      CheckMenuItem(GetMenu(hMain), ID_VIEW_PAGETAB, GetShowTabCtrl() ? MF_CHECKED : MF_UNCHECKED);
6797     
6798      // Add frame to dialog again
6799      lMainStyle = GetWindowLong(hMain, GWL_STYLE);
6800      lMainStyle = lMainStyle | WS_BORDER;
6801      SetWindowLong(hMain, GWL_STYLE, lMainStyle);
6802     
6803      // Show the window maximized
6804      if( GetWindowState() == SW_MAXIMIZE )
6805      {
6806         ShowWindow(hMain, SW_NORMAL);
6807         ShowWindow(hMain, SW_MAXIMIZE);
6808      }
6809      else
6810         ShowWindow(hMain, SW_RESTORE);
6811
6812      SetRunFullScreen(FALSE);
6813   }
6814   else
6815   {
6816      // Set to fullscreen
6817     
6818      // Remove menu
6819      SetMenu(hMain,NULL);
6820
6821      // Frameless dialog (fake fullscreen)
6822      lMainStyle = GetWindowLong(hMain, GWL_STYLE);
6823      lMainStyle = lMainStyle & (WS_BORDER ^ 0xffffffff);
6824      SetWindowLong(hMain, GWL_STYLE, lMainStyle);
6825      if( IsMaximized(hMain) )
6826      {
6827         ShowWindow(hMain, SW_NORMAL);
6828         SetWindowState( SW_MAXIMIZE );
6829      }
6830      ShowWindow(hMain, SW_MAXIMIZE);
6831     
6832      SetRunFullScreen(TRUE);
6833   }
6834}
6835
6836/*
6837  Checks to see if the mouse has been moved since this func
6838  was first called (which is at startup). The reason for
6839  storing the startup coordinates of the mouse is that when
6840  a window is created it generates WM_MOUSEOVER events, even
6841  though the user didn't actually move the mouse. So we need
6842  to know when the WM_MOUSEOVER event is user-triggered.
6843
6844  POSSIBLE BUGS:
6845  Gets polled at every WM_MOUSEMOVE so it might cause lag,
6846  but there's probably another way to code this that's
6847  way better?
6848 
6849*/
6850
6851BOOL MouseHasBeenMoved(void)
6852{
6853    static int mouse_x = -1;
6854    static int mouse_y = -1;
6855   POINT p;
6856
6857   GetCursorPos(&p);
6858
6859    if (mouse_x == -1) // First time
6860    {
6861      mouse_x = p.x;
6862      mouse_y = p.y;
6863    }
6864   
6865   return (p.x != mouse_x || p.y != mouse_y);       
6866}
6867
6868/* End of source file */
src/osd/windows/ui/history.c
r995r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11***************************************************************************/
12 
13/***************************************************************************
14
15  history.c
16
17    history functions.
18
19***************************************************************************/
20
21#define WIN32_LEAN_AND_MEAN
22#include <windows.h>
23#include <stdio.h>
24
25#include <driver.h>
26#include "m32util.h"
27
28#include "datafile.h"
29#include "history.h"
30
31
32/**************************************************************
33 * functions
34 **************************************************************/
35
36// Load indexes from history.dat if found
37char * GetGameHistory(int driver_index)
38{
39   static char buffer[32768];
40   buffer[0] = '\0';
41
42   if (load_driver_history(drivers[driver_index],buffer,sizeof(buffer)) != 0)
43      return buffer;
44
45   return ConvertToWindowsNewlines(buffer);
46}
src/osd/windows/ui/properties.h
r995r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11 ***************************************************************************/
12
13#ifndef PROPERTIES_H
14#define PROPERTIES_H
15
16/* Get title string to display in the top of the property page,
17 * Called also in Audit32.c
18 */
19char * GameInfoTitle(UINT nIndex);
20
21typedef enum
22{
23   SRC_GAME = 0,
24   SRC_FOLDER,
25} PROP_SOURCE;
26
27enum
28{
29   SOURCE_GLOBAL = 0,
30   SOURCE_VECTOR,
31   SOURCE_FOLDER,
32   SOURCE_GAME,
33   SOURCE_MAX
34};
35
36/* Called in win32ui.c to create the property page */
37void    InitPropertyPage(HINSTANCE hInst, HWND hwnd, int game_num, HICON hIcon, int folder_index, PROP_SOURCE source);
38
39#define PROPERTIES_PAGE 0
40#define AUDIT_PAGE      1   
41
42void    InitPropertyPageToPage(HINSTANCE hInst, HWND hwnd, int game_num, HICON hIcon, int start_page, int folder_index, PROP_SOURCE source);
43void    InitDefaultPropertyPage(HINSTANCE hInst, HWND hWnd);
44
45/* Get Help ID array for WM_HELP and WM_CONTEXTMENU */
46DWORD   GetHelpIDs(void);
47
48/* Get Game status text string */
49const char *GameInfoStatus(int driver_index, BOOL bRomStatus);
50
51/* Property sheet info for layout.c */
52typedef struct
53{
54   BOOL bOnDefaultPage;
55   BOOL (*pfnFilterProc)(const machine_config *drv, const game_driver *gamedrv);
56   DWORD dwDlgID;
57   DLGPROC pfnDlgProc;
58} PROPERTYSHEETINFO;
59
60extern const PROPERTYSHEETINFO g_propSheets[];
61
62BOOL PropSheetFilter_Vector(const machine_config *drv, const game_driver *gamedrv);
63
64INT_PTR CALLBACK GamePropertiesDialogProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam);
65INT_PTR CALLBACK GameOptionsProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam);
66
67void PropertiesInit(void);
68int PropertiesCurrentGame(HWND hDlg);
69
70#endif
src/osd/windows/ui/tabview.c
r995r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11 ***************************************************************************/
12
13#define WIN32_LEAN_AND_MEAN
14#include <windows.h>
15#include <windowsx.h>
16#include <shellapi.h>
17#include <stdio.h>
18#include <ctype.h>
19#include <io.h>
20#include <fcntl.h>
21#include <commctrl.h>
22#include <commdlg.h>
23#include <string.h>
24#include <sys/stat.h>
25#include <wingdi.h>
26#include <time.h>
27#include <assert.h>
28#include <tchar.h>
29#include <stdlib.h>
30
31#include "tabview.h"
32#include "m32util.h"
33#include "strconv.h"
34
35
36struct TabViewInfo
37{
38   const struct TabViewCallbacks *pCallbacks;
39   int nTabCount;
40   WNDPROC pfnParentWndProc;
41};
42
43
44
45static struct TabViewInfo *GetTabViewInfo(HWND hWnd)
46{
47   LONG_PTR l;
48   l = GetWindowLongPtr(hWnd, GWLP_USERDATA);
49   return (struct TabViewInfo *) l;
50}
51
52
53
54static LRESULT CallParentWndProc(WNDPROC pfnParentWndProc,
55   HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
56{
57   LRESULT rc;
58
59   if (!pfnParentWndProc)
60      pfnParentWndProc = GetTabViewInfo(hWnd)->pfnParentWndProc;
61
62   if (IsWindowUnicode(hWnd))
63      rc = CallWindowProcW(pfnParentWndProc, hWnd, message, wParam, lParam);
64   else
65      rc = CallWindowProcA(pfnParentWndProc, hWnd, message, wParam, lParam);
66   return rc;
67}
68
69
70
71static LRESULT CALLBACK TabViewWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
72{
73   struct TabViewInfo *pTabViewInfo;
74   WNDPROC pfnParentWndProc;
75   BOOL bHandled = FALSE;
76   LRESULT rc = 0;
77
78   pTabViewInfo = GetTabViewInfo(hWnd);
79   pfnParentWndProc = pTabViewInfo->pfnParentWndProc;
80
81   switch(message)
82   {
83      case WM_DESTROY:
84         free(pTabViewInfo);
85         SetWindowLongPtr(hWnd, GWLP_WNDPROC, (LONG_PTR) pfnParentWndProc);
86         SetWindowLongPtr(hWnd, GWLP_USERDATA, (LONG_PTR) NULL);
87         break;
88   }
89
90   if (!bHandled)
91      rc = CallParentWndProc(pfnParentWndProc, hWnd, message, wParam, lParam);
92
93   switch(message)
94   {
95      case WM_MOVE:
96      case WM_SIZE:
97         if (pTabViewInfo->pCallbacks->pfnOnMoveSize)
98            pTabViewInfo->pCallbacks->pfnOnMoveSize();
99         break;
100   }
101
102   return rc;
103}
104
105
106
107static int TabView_GetTabFromTabIndex(HWND hwndTabView, int tab_index)
108{
109   int shown_tabs = -1;
110   int i;
111   struct TabViewInfo *pTabViewInfo;
112
113   pTabViewInfo = GetTabViewInfo(hwndTabView);
114
115   for (i = 0; i < pTabViewInfo->nTabCount; i++)
116   {
117      if (!pTabViewInfo->pCallbacks->pfnGetShowTab || pTabViewInfo->pCallbacks->pfnGetShowTab(i))
118      {
119         shown_tabs++;
120         if (shown_tabs == tab_index)
121            return i;
122      }
123   }
124   dprintf("invalid tab index %i", tab_index);
125   return 0;
126}
127
128
129
130int TabView_GetCurrentTab(HWND hwndTabView)
131{
132   struct TabViewInfo *pTabViewInfo;
133   LPCSTR pszTab = NULL;
134   LPCSTR pszThatTab;
135   int i, nTab = -1;
136
137   pTabViewInfo = GetTabViewInfo(hwndTabView);
138
139   if (pTabViewInfo->pCallbacks->pfnGetCurrentTab)
140      pszTab = pTabViewInfo->pCallbacks->pfnGetCurrentTab();
141
142   if (pszTab)
143   {
144      if (pTabViewInfo->pCallbacks->pfnGetTabShortName)
145      {
146         for (i = 0; i < pTabViewInfo->nTabCount; i++)
147         {
148            pszThatTab = pTabViewInfo->pCallbacks->pfnGetTabShortName(i);
149            if (pszThatTab && !mame_stricmp(pszTab, pszThatTab))
150            {
151               nTab = i;
152               break;
153            }
154         }
155      }
156      if (nTab < 0)
157      {
158         nTab = 0;
159         sscanf(pszTab, "%d", &nTab);
160      }
161   }
162   else
163   {
164      nTab = 0;
165   }
166   return nTab;
167}
168
169
170
171void TabView_SetCurrentTab(HWND hwndTabView, int nTab)
172{
173   struct TabViewInfo *pTabViewInfo;
174   LPCSTR pszName;
175   char szBuffer[16];
176
177   pTabViewInfo = GetTabViewInfo(hwndTabView);
178
179   if (pTabViewInfo->pCallbacks->pfnGetTabShortName)
180   {
181      pszName = pTabViewInfo->pCallbacks->pfnGetTabShortName(nTab);
182   }
183   else
184   {
185      snprintf(szBuffer, sizeof(szBuffer) / sizeof(szBuffer[0]),
186         "%d", nTab);
187      pszName = szBuffer;
188   }
189
190   if (pTabViewInfo->pCallbacks->pfnSetCurrentTab)
191      pTabViewInfo->pCallbacks->pfnSetCurrentTab(pszName);
192}
193
194
195
196static int TabView_GetCurrentTabIndex(HWND hwndTabView)
197{
198   int shown_tabs = 0;
199   int i;
200   int nCurrentTab;
201   struct TabViewInfo *pTabViewInfo;
202
203   pTabViewInfo = GetTabViewInfo(hwndTabView);
204   nCurrentTab = TabView_GetCurrentTab(hwndTabView);
205
206   for (i = 0; i < pTabViewInfo->nTabCount; i++)
207   {
208      if (i == nCurrentTab)
209         break;
210
211      if (!pTabViewInfo->pCallbacks->pfnGetShowTab || pTabViewInfo->pCallbacks->pfnGetShowTab(i))
212         shown_tabs++;
213   }
214   return shown_tabs;
215}
216
217
218
219void TabView_UpdateSelection(HWND hwndTabView)
220{
221   TabCtrl_SetCurSel(hwndTabView, TabView_GetCurrentTabIndex(hwndTabView));
222}
223
224
225
226BOOL TabView_HandleNotify(LPNMHDR lpNmHdr)
227{
228   HWND hwndTabView;
229   struct TabViewInfo *pTabViewInfo;
230   BOOL bResult = FALSE;
231   int nTabIndex, nTab;
232
233   hwndTabView = lpNmHdr->hwndFrom;
234   pTabViewInfo = GetTabViewInfo(hwndTabView);
235
236   switch (lpNmHdr->code)
237   {
238      case TCN_SELCHANGE:
239         nTabIndex = TabCtrl_GetCurSel(hwndTabView);
240         nTab = TabView_GetTabFromTabIndex(hwndTabView, nTabIndex);
241         TabView_SetCurrentTab(hwndTabView, nTab);
242         if (pTabViewInfo->pCallbacks->pfnOnSelectionChanged)
243            pTabViewInfo->pCallbacks->pfnOnSelectionChanged();
244         bResult = TRUE;
245         break;
246   }
247   return bResult;
248}
249
250
251
252void TabView_CalculateNextTab(HWND hwndTabView)
253{
254   struct TabViewInfo *pTabViewInfo;
255   int i;
256   int nCurrentTab;
257
258   pTabViewInfo = GetTabViewInfo(hwndTabView);
259
260   // at most loop once through all options
261   for (i = 0; i < pTabViewInfo->nTabCount; i++)
262   {
263      nCurrentTab = TabView_GetCurrentTab(hwndTabView);
264      TabView_SetCurrentTab(hwndTabView, (nCurrentTab + 1) % pTabViewInfo->nTabCount);
265      nCurrentTab = TabView_GetCurrentTab(hwndTabView);
266
267      if (!pTabViewInfo->pCallbacks->pfnGetShowTab || pTabViewInfo->pCallbacks->pfnGetShowTab(nCurrentTab))
268      {
269         // this tab is being shown, so we're all set
270         return;
271      }
272   }
273}
274
275
276
277void TabView_Reset(HWND hwndTabView)
278{
279   struct TabViewInfo *pTabViewInfo;
280   TC_ITEM tci;
281   int i;
282   TCHAR* t_text;
283
284   pTabViewInfo = GetTabViewInfo(hwndTabView);
285
286   TabCtrl_DeleteAllItems(hwndTabView);
287
288   memset(&tci, 0, sizeof(tci));
289   tci.mask = TCIF_TEXT;
290   tci.cchTextMax = 20;
291
292   for (i = 0; i < pTabViewInfo->nTabCount; i++)
293   {
294      if (!pTabViewInfo->pCallbacks->pfnGetShowTab || pTabViewInfo->pCallbacks->pfnGetShowTab(i))
295      {
296         t_text = tstring_from_utf8(pTabViewInfo->pCallbacks->pfnGetTabLongName(i));
297         if( !t_text )
298            return;
299         tci.pszText = t_text;
300         TabCtrl_InsertItem(hwndTabView, i, &tci);
301         free(t_text);
302      }
303   }
304   TabView_UpdateSelection(hwndTabView);
305}
306
307
308
309BOOL SetupTabView(HWND hwndTabView, const struct TabViewOptions *pOptions)
310{
311   struct TabViewInfo *pTabViewInfo;
312   LONG_PTR l;
313   BOOL bShowTabView;
314
315   assert(hwndTabView);
316
317   // Allocate the list view struct
318   pTabViewInfo = (struct TabViewInfo *) malloc(sizeof(struct TabViewInfo));
319   if (!pTabViewInfo)
320      return FALSE;
321
322   // And fill it out
323   memset(pTabViewInfo, 0, sizeof(*pTabViewInfo));
324   pTabViewInfo->pCallbacks = pOptions->pCallbacks;
325   pTabViewInfo->nTabCount = pOptions->nTabCount;
326
327   // Hook in our wndproc and userdata pointer
328   l = GetWindowLongPtr(hwndTabView, GWLP_WNDPROC);
329   pTabViewInfo->pfnParentWndProc = (WNDPROC) l;
330   SetWindowLongPtr(hwndTabView, GWLP_USERDATA, (LONG_PTR) pTabViewInfo);
331   SetWindowLongPtr(hwndTabView, GWLP_WNDPROC, (LONG_PTR) TabViewWndProc);
332
333   bShowTabView = pTabViewInfo->pCallbacks->pfnGetShowTabCtrl ?
334      pTabViewInfo->pCallbacks->pfnGetShowTabCtrl() : TRUE;
335   ShowWindow(hwndTabView, bShowTabView ? SW_SHOW : SW_HIDE);
336
337   TabView_Reset(hwndTabView);
338   if (pTabViewInfo->pCallbacks->pfnOnSelectionChanged)
339      pTabViewInfo->pCallbacks->pfnOnSelectionChanged();
340   return TRUE;
341}
342
343
src/osd/windows/ui/columnedit.c
r995r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11***************************************************************************/
12 
13/***************************************************************************
14
15  ColumnEdit.c
16
17  Column Edit dialog
18
19***************************************************************************/
20
21#define WIN32_LEAN_AND_MEAN
22#include <windows.h>
23#include <windowsx.h>
24#include <shellapi.h>
25#include <commctrl.h>
26#include <commdlg.h>
27
28#include "resource.h"
29#include "bitmask.h"
30#include "m32opts.h"
31#include "screenshot.h"
32#include "win32ui.h"
33
34// Returns TRUE if successful
35int DoExchangeItem(HWND hFrom, HWND hTo, int nMinItem)
36{
37   LV_ITEM lvi;
38   TCHAR   buf[80];
39   int    nFrom, nTo;
40
41   nFrom = ListView_GetItemCount(hFrom);
42   nTo   = ListView_GetItemCount(hTo);
43
44   lvi.iItem = ListView_GetNextItem(hFrom, -1, LVIS_SELECTED | LVIS_FOCUSED);
45   if (lvi.iItem < nMinItem)
46   {
47      if (lvi.iItem != -1) // Can't remove the first column
48         MessageBox(0, TEXT("Cannot Move Selected Item"), TEXT("Move Item"), IDOK);
49      SetFocus(hFrom);
50      return FALSE;
51   }
52   lvi.iSubItem   = 0;
53   lvi.mask      = LVIF_PARAM | LVIF_TEXT;
54   lvi.pszText    = buf;
55   lvi.cchTextMax = sizeof(buf);
56   if (ListView_GetItem(hFrom, &lvi))
57   {
58      // Add this item to the Show and delete it from Available
59      ListView_DeleteItem(hFrom, lvi.iItem);
60      lvi.iItem = ListView_GetItemCount(hTo);
61      ListView_InsertItem(hTo, &lvi);
62      ListView_SetItemState(hTo, lvi.iItem,
63                       LVIS_FOCUSED | LVIS_SELECTED,
64                       LVIS_FOCUSED | LVIS_SELECTED);
65      SetFocus(hTo);
66      return lvi.iItem;
67   }
68   return FALSE;
69}
70
71void DoMoveItem( HWND hWnd, BOOL bDown)
72{
73   LV_ITEM lvi;
74   TCHAR   buf[80];
75   int    nMaxpos;
76   
77   lvi.iItem = ListView_GetNextItem(hWnd, -1, LVIS_SELECTED | LVIS_FOCUSED);
78   nMaxpos = ListView_GetItemCount(hWnd);
79   if (lvi.iItem == -1 ||
80      (lvi.iItem <  2 && bDown == FALSE) || // Disallow moving First column
81      (lvi.iItem == 0 && bDown == TRUE)  || // ""
82      (lvi.iItem == nMaxpos - 1 && bDown == TRUE))
83   {
84      SetFocus(hWnd);
85      return;
86   }
87   lvi.iSubItem   = 0;
88   lvi.mask      = LVIF_PARAM | LVIF_TEXT;
89   lvi.pszText    = buf;
90   lvi.cchTextMax = sizeof(buf);
91   if (ListView_GetItem(hWnd, &lvi))
92   {
93      // Add this item to the Show and delete it from Available
94      ListView_DeleteItem(hWnd, lvi.iItem);
95      lvi.iItem += (bDown) ? 1 : -1;
96      ListView_InsertItem(hWnd,&lvi);
97      ListView_SetItemState(hWnd, lvi.iItem,
98                       LVIS_FOCUSED | LVIS_SELECTED,
99                       LVIS_FOCUSED | LVIS_SELECTED);
100      if (lvi.iItem == nMaxpos - 1)
101         EnableWindow(GetDlgItem(GetParent(hWnd), IDC_BUTTONMOVEDOWN), FALSE);
102      else
103         EnableWindow(GetDlgItem(GetParent(hWnd), IDC_BUTTONMOVEDOWN), TRUE);
104
105      if (lvi.iItem < 2)
106         EnableWindow(GetDlgItem(GetParent(hWnd), IDC_BUTTONMOVEUP),   FALSE);
107      else
108         EnableWindow(GetDlgItem(GetParent(hWnd), IDC_BUTTONMOVEUP),   TRUE);
109
110      SetFocus(hWnd);
111   }
112}
113
114INT_PTR InternalColumnDialogProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam,
115   int nColumnMax, int *shown, int *order,
116   LPCTSTR *names, void (*pfnGetRealColumnOrder)(int *),
117   void (*pfnGetColumnInfo)(int *pnOrder, int *pnShown),
118   void (*pfnSetColumnInfo)(int *pnOrder, int *pnShown))
119{
120   static HWND hShown;
121   static HWND hAvailable;
122   static BOOL showMsg = FALSE;
123   int         nShown;
124   int         nAvail;
125   int         i, nCount = 0;
126   LV_ITEM     lvi;
127   DWORD dwShowStyle, dwAvailableStyle, dwView;
128
129   switch (Msg)
130   {
131   case WM_INITDIALOG:
132      hShown      = GetDlgItem(hDlg, IDC_LISTSHOWCOLUMNS);
133      hAvailable = GetDlgItem(hDlg, IDC_LISTAVAILABLECOLUMNS);
134      /*Change Style to Always Show Selection */
135      dwShowStyle = GetWindowLong(hShown, GWL_STYLE);
136      dwAvailableStyle = GetWindowLong(hAvailable, GWL_STYLE);
137      dwView = LVS_SHOWSELALWAYS | LVS_LIST;
138
139      /* Only set the window style if the view bits have changed. */
140      if ((dwShowStyle & LVS_TYPEMASK) != dwView)
141      SetWindowLong(hShown, GWL_STYLE,
142         (dwShowStyle & ~LVS_TYPEMASK) | dwView);
143      if ((dwAvailableStyle & LVS_TYPEMASK) != dwView)
144      SetWindowLong(hAvailable, GWL_STYLE,
145         (dwAvailableStyle & ~LVS_TYPEMASK) | dwView);
146
147      pfnGetColumnInfo(order, shown);
148
149      showMsg = TRUE;
150      nShown   = 0;
151      nAvail   = 0;
152                 
153      lvi.mask     = LVIF_TEXT | LVIF_PARAM;
154      lvi.stateMask = 0;               
155      lvi.iSubItem  = 0;
156      lvi.iImage     = -1;
157
158      /* Get the Column Order and save it */
159      pfnGetRealColumnOrder(order);
160
161#if 0
162        {
163            char tmp[80];
164           
165            sprintf(tmp,"ColumnOrder: %d,%d,%d,%d,%d,%d,%d,%d,%d,%d, %d",
166                order[0], order[1], order[2], order[3], order[4],
167                order[5], order[6], order[7], order[8], order[9], order[10]);
168            MessageBox(0, tmp, "Column Order", IDOK);
169        }
170#endif
171      for (i = 0 ; i < nColumnMax; i++)
172      {       
173         lvi.pszText = (TCHAR *) names[order[i]];
174         lvi.lParam   = order[i];
175
176         if (shown[order[i]])
177         {
178            lvi.iItem = nShown;
179            ListView_InsertItem(hShown, &lvi);
180            nShown++;
181         }
182         else
183         {
184            lvi.iItem = nAvail;
185            ListView_InsertItem(hAvailable, &lvi);
186            nAvail++;
187         }
188      }
189      if( nShown > 0)
190      {
191         /*Set to Second, because first is not allowed*/
192         ListView_SetItemState(hShown, 1,
193            LVIS_FOCUSED | LVIS_SELECTED, LVIS_FOCUSED | LVIS_SELECTED);
194      }
195      if( nAvail > 0)
196      {
197         ListView_SetItemState(hAvailable, 0,
198            LVIS_FOCUSED | LVIS_SELECTED, LVIS_FOCUSED | LVIS_SELECTED);
199      }
200      EnableWindow(GetDlgItem(hDlg, IDC_BUTTONADD)  ,    TRUE);
201      return TRUE;
202
203   case WM_NOTIFY:
204      {
205         NMHDR *nm = (NMHDR *)lParam;
206         NM_LISTVIEW *pnmv;
207         int       nPos;
208         
209         switch (nm->code)
210         {
211         case NM_DBLCLK:
212            // Do Data Exchange here, which ListView was double clicked?
213            switch (nm->idFrom)
214            {
215            case IDC_LISTAVAILABLECOLUMNS:
216               // Move selected Item from Available to Shown column
217               nPos = DoExchangeItem(hAvailable, hShown, 0);
218               if (nPos)
219               {
220                  EnableWindow(GetDlgItem(hDlg, IDC_BUTTONADD),      FALSE);
221                  EnableWindow(GetDlgItem(hDlg, IDC_BUTTONREMOVE),   TRUE);
222                  EnableWindow(GetDlgItem(hDlg, IDC_BUTTONMOVEUP),   TRUE);
223                  EnableWindow(GetDlgItem(hDlg, IDC_BUTTONMOVEDOWN), FALSE);
224               }
225               break;
226
227            case IDC_LISTSHOWCOLUMNS:
228               // Move selected Item from Show to Available column
229               if (DoExchangeItem(hShown, hAvailable, 1))
230               {
231                  EnableWindow(GetDlgItem(hDlg, IDC_BUTTONADD)  ,    TRUE);
232                  EnableWindow(GetDlgItem(hDlg, IDC_BUTTONREMOVE),   FALSE);
233                  EnableWindow(GetDlgItem(hDlg, IDC_BUTTONMOVEUP),   FALSE);
234                  EnableWindow(GetDlgItem(hDlg, IDC_BUTTONMOVEDOWN), FALSE);
235               }
236               break;
237            }
238            return TRUE;
239           
240         case LVN_ITEMCHANGED:
241            // Don't handle this message for now
242            pnmv = (NM_LISTVIEW *)nm;
243            if (//!(pnmv->uOldState & LVIS_SELECTED) &&
244               (pnmv->uNewState  & LVIS_SELECTED))
245            {
246               if (pnmv->iItem == 0 && pnmv->hdr.idFrom == IDC_LISTSHOWCOLUMNS)
247               {
248                  // Don't allow selecting the first item
249                  ListView_SetItemState(hShown, pnmv->iItem,
250                     LVIS_FOCUSED | LVIS_SELECTED, LVIS_FOCUSED | LVIS_SELECTED);
251                  if (showMsg)
252                  {
253                     MessageBox(0, TEXT("Changing this item is not permitted"), TEXT("Select Item"), IDOK);
254                     showMsg = FALSE;
255                  }
256                  EnableWindow(GetDlgItem(hDlg, IDC_BUTTONREMOVE),   FALSE);
257                  EnableWindow(GetDlgItem(hDlg, IDC_BUTTONMOVEUP),   FALSE);
258                  EnableWindow(GetDlgItem(hDlg, IDC_BUTTONMOVEDOWN), FALSE);
259                  /*Leave Focus on Control*/
260                  //SetFocus(GetDlgItem(hDlg,IDOK));
261                  return TRUE;
262               }
263               else
264                  showMsg = TRUE;
265            }
266            if( pnmv->uOldState & LVIS_SELECTED && pnmv->iItem == 0 && pnmv->hdr.idFrom == IDC_LISTSHOWCOLUMNS )
267            {
268               /*we enable the buttons again, if the first Entry loses selection*/
269               EnableWindow(GetDlgItem(hDlg, IDC_BUTTONREMOVE),   TRUE);
270               EnableWindow(GetDlgItem(hDlg, IDC_BUTTONMOVEUP),   TRUE);
271               EnableWindow(GetDlgItem(hDlg, IDC_BUTTONMOVEDOWN), TRUE);
272               //SetFocus(GetDlgItem(hDlg,IDOK));
273            }
274            break;
275         case NM_SETFOCUS:
276            {
277               switch (nm->idFrom)
278               {
279               case IDC_LISTAVAILABLECOLUMNS:
280                  if (ListView_GetItemCount(nm->hwndFrom) != 0)
281                  {
282                     EnableWindow(GetDlgItem(hDlg, IDC_BUTTONADD),      TRUE);
283                     EnableWindow(GetDlgItem(hDlg, IDC_BUTTONREMOVE),   FALSE);
284                     EnableWindow(GetDlgItem(hDlg, IDC_BUTTONMOVEDOWN), FALSE);
285                     EnableWindow(GetDlgItem(hDlg, IDC_BUTTONMOVEUP),   FALSE);
286                  }
287                  break;
288               case IDC_LISTSHOWCOLUMNS:
289                  if (ListView_GetItemCount(nm->hwndFrom) != 0)
290                  {
291                     EnableWindow(GetDlgItem(hDlg, IDC_BUTTONADD),      FALSE);
292                     
293                     if (ListView_GetNextItem(hShown, -1, LVIS_SELECTED | LVIS_FOCUSED) == 0 )
294                     {
295                        EnableWindow(GetDlgItem(hDlg, IDC_BUTTONREMOVE),   FALSE);
296                        EnableWindow(GetDlgItem(hDlg, IDC_BUTTONMOVEDOWN), FALSE);
297                        EnableWindow(GetDlgItem(hDlg, IDC_BUTTONMOVEUP),   FALSE);
298                     }
299                     else
300                     {
301                        EnableWindow(GetDlgItem(hDlg, IDC_BUTTONREMOVE),   TRUE);
302                        EnableWindow(GetDlgItem(hDlg, IDC_BUTTONMOVEDOWN), TRUE);
303                        EnableWindow(GetDlgItem(hDlg, IDC_BUTTONMOVEUP),   TRUE);
304                     }
305                  }
306                  break;
307               }
308            }
309            break;
310         case LVN_KEYDOWN:
311         case NM_CLICK:
312            pnmv = (NM_LISTVIEW *)nm;
313            if (//!(pnmv->uOldState & LVIS_SELECTED) &&
314               (pnmv->uNewState  & LVIS_SELECTED))
315            {
316               if (pnmv->iItem == 0 && pnmv->hdr.idFrom == IDC_LISTSHOWCOLUMNS)
317               {
318               }
319            }
320            switch (nm->idFrom)
321            {
322            case IDC_LISTAVAILABLECOLUMNS:
323               if (ListView_GetItemCount(nm->hwndFrom) != 0)
324               {
325                  EnableWindow(GetDlgItem(hDlg, IDC_BUTTONADD),      TRUE);
326                  EnableWindow(GetDlgItem(hDlg, IDC_BUTTONREMOVE),   FALSE);
327                  EnableWindow(GetDlgItem(hDlg, IDC_BUTTONMOVEDOWN), FALSE);
328                  EnableWindow(GetDlgItem(hDlg, IDC_BUTTONMOVEUP),   FALSE);
329               }
330               break;
331
332            case IDC_LISTSHOWCOLUMNS:
333               if (ListView_GetItemCount(nm->hwndFrom) != 0)
334               {
335                  EnableWindow(GetDlgItem(hDlg, IDC_BUTTONADD),      FALSE);
336                  if (ListView_GetNextItem(hShown, -1, LVIS_SELECTED | LVIS_FOCUSED) == 0 )
337                  {
338                     EnableWindow(GetDlgItem(hDlg, IDC_BUTTONREMOVE),   FALSE);
339                     EnableWindow(GetDlgItem(hDlg, IDC_BUTTONMOVEDOWN), FALSE);
340                     EnableWindow(GetDlgItem(hDlg, IDC_BUTTONMOVEUP),   FALSE);
341                  }
342                  else
343                  {
344                     EnableWindow(GetDlgItem(hDlg, IDC_BUTTONREMOVE),   TRUE);
345                     EnableWindow(GetDlgItem(hDlg, IDC_BUTTONMOVEDOWN), TRUE);
346                     EnableWindow(GetDlgItem(hDlg, IDC_BUTTONMOVEUP),   TRUE);
347                  }
348               }
349               break;
350            }
351            //SetFocus( nm->hwndFrom );
352            return TRUE;
353         }
354      }
355      return FALSE;
356   case WM_COMMAND:
357      {
358         WORD wID     = GET_WM_COMMAND_ID(wParam, lParam);
359         HWND hWndCtrl = GET_WM_COMMAND_HWND(wParam, lParam);
360         int  nPos = 0;
361
362         switch (wID)
363         {
364            case IDC_LISTSHOWCOLUMNS:
365               break;
366            case IDC_BUTTONADD:
367               // Move selected Item in Available to Shown
368               nPos = DoExchangeItem(hAvailable, hShown, 0);
369               if (nPos)
370               {
371                  EnableWindow(hWndCtrl,FALSE);
372                  EnableWindow(GetDlgItem(hDlg, IDC_BUTTONREMOVE),   TRUE);
373                  EnableWindow(GetDlgItem(hDlg, IDC_BUTTONMOVEUP),   TRUE);
374                  EnableWindow(GetDlgItem(hDlg, IDC_BUTTONMOVEDOWN), FALSE);
375               }
376               break;
377
378            case IDC_BUTTONREMOVE:
379               // Move selected Item in Show to Available
380               if (DoExchangeItem( hShown, hAvailable, 1))
381               {
382                  EnableWindow(hWndCtrl,FALSE);
383                  EnableWindow(GetDlgItem(hDlg, IDC_BUTTONADD),      TRUE);
384                  EnableWindow(GetDlgItem(hDlg, IDC_BUTTONMOVEUP),   FALSE);
385                  EnableWindow(GetDlgItem(hDlg, IDC_BUTTONMOVEDOWN), FALSE);
386               }
387               break;
388
389            case IDC_BUTTONMOVEDOWN:
390               // Move selected item in the Show window up 1 item
391               DoMoveItem(hShown, TRUE);
392               break;
393
394            case IDC_BUTTONMOVEUP:
395               // Move selected item in the Show window down 1 item
396               DoMoveItem(hShown, FALSE);
397               break;
398
399            case IDOK:
400               // Save users choices
401               nShown = ListView_GetItemCount(hShown);
402               nAvail = ListView_GetItemCount(hAvailable);
403               nCount = 0;
404               for (i = 0; i < nShown; i++)
405               {
406                  lvi.iSubItem = 0;
407                  lvi.mask     = LVIF_PARAM;
408                  lvi.pszText  = 0;
409                  lvi.iItem    = i;
410                  ListView_GetItem(hShown, &lvi);
411                  order[nCount++]   = lvi.lParam;
412                  shown[lvi.lParam] = TRUE;
413               }
414               for (i = 0; i < nAvail; i++)
415               {
416                  lvi.iSubItem = 0;
417                  lvi.mask     = LVIF_PARAM;
418                  lvi.pszText  = 0;
419                  lvi.iItem    = i;
420                  ListView_GetItem(hAvailable, &lvi);
421                  order[nCount++]   = lvi.lParam;
422                  shown[lvi.lParam] = FALSE;
423               }
424#if 0
425               {
426                  char tmp[80];
427                  sprintf(tmp,"Shown (%d) - Hidden (%d)",nShown,nAvail);
428                  MessageBox(0,tmp,"List Counts",IDOK);
429                  sprintf(tmp,"ColumnOrder: %d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d",
430                     order[0], order[1], order[2], order[3], order[4],
431                     order[5], order[6], order[7], order[8], order[9], shown[10]);
432                  MessageBox(0,tmp,"Column Order", IDOK);
433                  sprintf(tmp,"ColumnShown: %d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d",
434                     shown[0], shown[1], shown[2], shown[3], shown[4],
435                     shown[5], shown[6], shown[7], shown[8], shown[9], shown[10]);
436                  MessageBox(0,tmp,"Column Shown", IDOK);
437               }
438#endif
439               pfnSetColumnInfo(order, shown);
440               EndDialog(hDlg, 1);
441               return TRUE;
442
443            case IDCANCEL:
444               EndDialog(hDlg, 0);
445               return TRUE;
446         }
447      }
448      break;
449   }
450   return 0;
451}
452
453static void GetColumnInfo(int *order, int *shown)
454{
455   GetColumnOrder(order);
456   GetColumnShown(shown);
457}
458
459static void SetColumnInfo(int *order, int *shown)
460{
461   SetColumnOrder(order);
462   SetColumnShown(shown);
463}
464
465INT_PTR CALLBACK ColumnDialogProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam)
466{
467   static int shown[COLUMN_MAX];
468   static int order[COLUMN_MAX];
469   extern LPCTSTR column_names[COLUMN_MAX]; // from win32ui.c, should improve
470
471
472   return InternalColumnDialogProc(hDlg, Msg, wParam, lParam, COLUMN_MAX,
473      shown, order, column_names, GetRealColumnOrder, GetColumnInfo, SetColumnInfo);
474}
475
476
477
src/osd/windows/ui/ui.mak
r995r996
1#####################################################################
2# make SUFFIX=32
3#####################################################################
4
5#-------------------------------------------------
6# object and source roots
7#-------------------------------------------------
8
9WINUISRC = $(SRC)/osd/$(OSD)/ui
10WINUIOBJ = $(OBJ)/osd/$(OSD)/ui
11
12OBJDIRS += $(WINUIOBJ)
13   
14ifdef MESS
15MESS_WINUISRC = $(SRC)/mess/osd/$(OSD)/ui
16MESS_WINUIOBJ = $(OBJ)/mess/osd/$(OSD)/ui
17OBJDIRS += $(MESS_WINUIOBJ)
18endif
19
20
21
22#-------------------------------------------------
23# Windows UI object files
24#-------------------------------------------------
25
26WINUIOBJS += \
27   $(WINUIOBJ)/m32util.o \
28   $(WINUIOBJ)/directinput.o \
29   $(WINUIOBJ)/dijoystick.o \
30   $(WINUIOBJ)/directdraw.o \
31   $(WINUIOBJ)/directories.o \
32   $(WINUIOBJ)/audit32.o \
33   $(WINUIOBJ)/columnedit.o \
34   $(WINUIOBJ)/screenshot.o \
35   $(WINUIOBJ)/treeview.o \
36   $(WINUIOBJ)/splitters.o \
37   $(WINUIOBJ)/bitmask.o \
38   $(WINUIOBJ)/datamap.o \
39   $(WINUIOBJ)/dxdecode.o \
40   $(WINUIOBJ)/picker.o \
41   $(WINUIOBJ)/properties.o \
42   $(WINUIOBJ)/tabview.o \
43   $(WINUIOBJ)/help.o \
44   $(WINUIOBJ)/history.o \
45   $(WINUIOBJ)/dialogs.o \
46   $(WINUIOBJ)/dirwatch.o   \
47   $(WINUIOBJ)/datafile.o   \
48   $(WINUIOBJ)/m32opts.o \
49   $(WINUIOBJ)/win32ui.o \
50
51ifdef MESS
52WINUIOBJS += \
53   $(MESS_WINUIOBJ)/mess32ui.o \
54   $(MESS_WINUIOBJ)/optionsms.o \
55    $(MESS_WINUIOBJ)/layoutms.o \
56   $(MESS_WINUIOBJ)/ms32util.o \
57   $(MESS_WINUIOBJ)/propertiesms.o \
58   $(MESS_WINUIOBJ)/softwarepicker.o \
59   $(MESS_WINUIOBJ)/devview.o
60else
61WINUIOBJS += \
62    $(WINUIOBJ)/layout.o \
63   $(WINUIOBJ)/m32main.o \
64   $(WINUIOBJ)/mame32.res
65endif
66
67ifdef MESS
68# extra dependencies
69# $(MESS_WINUIOBJ)/mess32ui.o:   $(WINUISRC)/win32ui.c $(MESS_WINUISRC)/mess32ui.c
70# $(MESS_WINUIOBJ)/optionsms.o:   $(WINUISRC)/options.c $(MESS_WINUISRC)/optionsms.c
71endif
72   
73# add resource file
74ifdef MESS
75GUIRESFILE = $(MESS_WINUIOBJ)/mess32.res
76endif
77
78$(LIBOSD): $(WINUIOBJS)
79
80
81
82#####################################################################
83# compiler
84
85#
86# Preprocessor Definitions
87#
88
89ifdef MSVC_BUILD
90DEFS += -DWINVER=0x0500 -D_CRT_NON_CONFORMING_SWPRINTFS
91else
92DEFS += -DWINVER=0x0400
93endif
94
95DEFS += \
96   -D_WIN32_IE=0x0500 \
97   -DDECL_SPEC= \
98   -DZEXTERN=extern \
99
100#   -DSHOW_UNAVAILABLE_FOLDER
101
102
103#####################################################################
104# Resources
105
106ifndef MESS
107UI_RC = @windres --use-temp-file
108
109UI_RCDEFS = -DNDEBUG -D_WIN32_IE=0x0400
110
111UI_RCFLAGS = -O coff --include-dir $(WINUISRC)
112
113$(WINUIOBJ)/%.res: $(WINUISRC)/%.rc
114   @echo Compiling mame32 resources $<...
115   $(UI_RC) $(UI_RCDEFS) $(UI_RCFLAGS) -o $@ -i $<
116endif
117
118#####################################################################
119# Linker
120
121ifndef MSVC
122LIBS += -lkernel32 \
123        -lshell32 \
124        -lcomctl32 \
125        -lcomdlg32 \
126        -ladvapi32 \
127
128endif
129
130ifndef MESS
131LDFLAGS += -mwindows
132endif
133
134#####################################################################
135
136ifdef MESS
137
138$(MESS_WINUIOBJ)/mess32.res:   $(WINUISRC)/mame32.rc $(MESS_WINUISRC)/mess32.rc $(WINUISRC)/resource.h $(MESS_WINUISRC)/resourcems.h
139   @echo Compiling resources $<...
140   $(RC) $(RCDEFS) $(RCFLAGS) --include-dir $(WINUISRC) --include-dir $(MESS_WINUISRC) -o $@ -i $(MESS_WINUISRC)/mess32.rc
141
142endif
src/osd/windows/ui/m32util.h
r995r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5 
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11 ***************************************************************************/
12
13#ifndef M32UTIL_H
14#define M32UTIL_H
15
16extern void __cdecl ErrorMsg(const char* fmt, ...);
17extern void __cdecl dprintf(const char* fmt, ...);
18
19extern UINT GetDepth(HWND hWnd);
20
21/* Open a text file */
22extern void DisplayTextFile(HWND hWnd, const char *cName);
23
24#define PACKVERSION(major,minor) MAKELONG(minor,major)
25
26/* Check for old version of comctl32.dll */
27extern LONG GetCommonControlVersion(void);
28
29extern char * MyStrStrI(const char* pFirst, const char* pSrch);
30extern char * ConvertToWindowsNewlines(const char *source);
31
32extern const char * GetDriverFilename(int nIndex);
33
34BOOL DriverIsClone(int driver_index);
35BOOL DriverIsBroken(int driver_index);
36BOOL DriverIsHarddisk(int driver_index);
37BOOL DriverHasOptionalBIOS(int driver_index);
38BOOL DriverIsStereo(int driver_index);
39BOOL DriverIsMultiMon(int driver_index);
40BOOL DriverIsVector(int driver_index);
41BOOL DriverIsBios(int driver_index);
42BOOL DriverUsesRoms(int driver_index);
43BOOL DriverUsesSamples(int driver_index);
44BOOL DriverUsesTrackball(int driver_index);
45BOOL DriverUsesLightGun(int driver_index);
46BOOL DriverSupportsSaveState(int driver_index);
47
48void FlushFileCaches(void);
49
50void FreeIfAllocated(char **s);
51
52BOOL StringIsSuffixedBy(const char *s, const char *suffix);
53
54BOOL SafeIsAppThemed(void);
55
56HICON win_extract_icon_utf8(HINSTANCE inst, const char* exefilename, UINT iconindex);
57TCHAR* win_tstring_strdup(LPCTSTR str);
58HANDLE win_create_file_utf8(const char* filename, DWORD desiredmode, DWORD sharemode,
59                        LPSECURITY_ATTRIBUTES securityattributes, DWORD creationdisposition,
60                        DWORD flagsandattributes, HANDLE templatehandle);
61DWORD win_get_current_directory_utf8(DWORD bufferlength, char* buffer);
62HANDLE win_find_first_file_utf8(const char* filename, LPWIN32_FIND_DATA findfiledata);
63
64#endif /* MAME32UTIL_H */
src/osd/windows/ui/win32ui.h
r995r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5   
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11 ***************************************************************************/
12
13#ifndef WIN32UI_H
14#define WIN32UI_H
15
16#define WIN32_LEAN_AND_MEAN
17#include <commctrl.h>
18#include <commdlg.h>
19#include <driver.h>
20#include "screenshot.h"
21#include "pool.h"
22
23enum
24{
25   TAB_PICKER = 0,
26   TAB_DISPLAY,
27   TAB_MISC,
28   NUM_TABS
29};
30
31enum
32{
33   FILETYPE_INPUT_FILES = 1,
34   FILETYPE_SAVESTATE_FILES = 2,
35   FILETYPE_WAVE_FILES = 3,
36   FILETYPE_MNG_FILES = 5,
37   FILETYPE_EFFECT_FILES = 6
38};
39
40
41typedef struct
42{
43   INT resource;
44   const char *icon_name;
45} ICONDATA;
46
47extern TCHAR last_directory[MAX_PATH];
48
49typedef BOOL (WINAPI *common_file_dialog_proc)(LPOPENFILENAME lpofn);
50BOOL CommonFileDialog(common_file_dialog_proc cfd,char *filename, int filetype);
51
52HWND GetMainWindow(void);
53HWND GetTreeView(void);
54HIMAGELIST GetLargeImageList(void);
55HIMAGELIST GetSmallImageList(void);
56int GetNumOptionFolders(void);
57void SetNumOptionFolders(int count);
58void GetRealColumnOrder(int order[]);
59HICON LoadIconFromFile(const char *iconname);
60void UpdateScreenShot(void);
61void ResizePickerControls(HWND hWnd);
62void MamePlayGame(void);
63int FindIconIndex(int nIconResource);
64int FindIconIndexByName(const char *icon_name);
65int GetSelectedPick(void);
66object_pool *GetMame32MemoryPool(void);
67
68void UpdateListView(void);
69
70// Move The in "The Title (notes)" to "Title, The (notes)"
71char * ModifyThe(const char *str);
72
73// Convert Ampersand so it can display in a static control
74char * ConvertAmpersandString(const char *s);
75
76// globalized for painting tree control
77HBITMAP GetBackgroundBitmap(void);
78HPALETTE GetBackgroundPalette(void);
79MYBITMAPINFO* GetBackgroundInfo(void);
80BOOL GetUseOldControl(void);
81BOOL GetUseXPControl(void);
82
83int GetMinimumScreenShotWindowWidth(void);
84
85// we maintain an array of drivers sorted by name, useful all around
86int GetDriverIndex(const game_driver *driver);
87int GetParentIndex(const game_driver *driver);
88int GetParentRomSetIndex(const game_driver *driver);
89int GetGameNameIndex(const char *name);
90int GetIndexFromSortedIndex(int sorted_index);
91
92// sets text in part of the status bar on the main window
93void SetStatusBarText(int part_index, const char *message);
94void SetStatusBarTextF(int part_index, const char *fmt, ...);
95
96int Mame32Main(HINSTANCE    hInstance,
97                   LPSTR        lpCmdLine,
98                   int          nCmdShow);
99
100BOOL MouseHasBeenMoved(void);
101
102#endif
src/osd/windows/ui/history.h
r995r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11 ***************************************************************************/
12
13#ifndef HISTORY_H
14#define HISTORY_H
15
16char * GetGameHistory(int driver_index);
17
18#endif
19
src/osd/windows/ui/mame32.rc
r995r996
1//Microsoft Developer Studio generated resource script.
2//
3#include "resource.h"
4
5#ifdef MESS
6#include "resourcems.h"
7#endif
8
9// Generated Help ID header file
10#define APSTUDIO_HIDDEN_SYMBOLS
11#include "resource.hm"
12#undef APSTUDIO_HIDDEN_SYMBOLS
13
14#define APSTUDIO_READONLY_SYMBOLS
15/////////////////////////////////////////////////////////////////////////////
16//
17// Generated from the TEXTINCLUDE 2 resource.
18//
19#define NOWINRES
20#include "windows.h"
21#include "commctrl.h"
22
23/////////////////////////////////////////////////////////////////////////////
24#undef APSTUDIO_READONLY_SYMBOLS
25
26/////////////////////////////////////////////////////////////////////////////
27// Englisch (USA) resources
28
29#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
30#ifdef _WIN32
31LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
32#pragma code_page(1252)
33#endif //_WIN32
34
35/////////////////////////////////////////////////////////////////////////////
36//
37// Menu
38//
39
40IDR_MAIN_MENU MENU DISCARDABLE
41BEGIN
42    POPUP "&File"
43    BEGIN
44        MENUITEM "&Exit",                       ID_FILE_EXIT
45    END
46    POPUP "&Help"
47    BEGIN
48#ifdef MESS
49        MENUITEM "&About MESS",               ID_ABOUT
50#else
51        MENUITEM "&About MAME32",               ID_ABOUT
52#endif
53    END
54END
55
56IDR_UI_MENU MENU DISCARDABLE
57BEGIN
58    POPUP "&File"
59    BEGIN
60        MENUITEM "&Play",                       ID_FILE_PLAY
61        MENUITEM SEPARATOR
62        MENUITEM "Play and &Record Input...",   ID_FILE_PLAY_RECORD
63        MENUITEM "P&layback Input...",          ID_FILE_PLAY_BACK
64        MENUITEM SEPARATOR
65        MENUITEM "Play and Record &Wave Output...", ID_FILE_PLAY_RECORD_WAVE
66        MENUITEM SEPARATOR
67        MENUITEM "Play and Record &MNG Output...", ID_FILE_PLAY_RECORD_MNG
68        MENUITEM SEPARATOR
69        MENUITEM "Loa&d Savestate...",          ID_FILE_LOADSTATE
70        MENUITEM SEPARATOR
71#ifdef MESS
72        MENUITEM "&Select Random System",       ID_CONTEXT_SELECT_RANDOM
73        MENUITEM SEPARATOR
74        MENUITEM "Op&en Other Software...",     ID_MESS_OPEN_SOFTWARE
75        MENUITEM "&Create Image...",         ID_MESS_CREATE_SOFTWARE
76#ifdef MAME_DEBUG
77        MENUITEM SEPARATOR
78        MENUITEM "Run Tests",               ID_MESS_RUN_TESTS
79#endif
80#else /* !MESS */
81        MENUITEM "&Select Random Game",         ID_CONTEXT_SELECT_RANDOM
82#endif /* MESS */
83        MENUITEM SEPARATOR
84        MENUITEM "Pr&operties",                 ID_GAME_PROPERTIES
85        MENUITEM SEPARATOR
86#ifdef MESS
87        MENUITEM "&Audit all systems",          ID_FILE_AUDIT
88#else
89        MENUITEM "&Audit all games",            ID_FILE_AUDIT
90#endif /* MESS */
91        MENUITEM SEPARATOR
92        MENUITEM "E&xit",                       ID_FILE_EXIT
93    END
94    POPUP "&View"
95    BEGIN
96        MENUITEM "&Toolbar\tAlt+T",             ID_VIEW_TOOLBARS
97        MENUITEM "&Status bar\tAlt+S",          ID_VIEW_STATUS
98        MENUITEM "Fold&er List\tAlt+D",         ID_VIEW_FOLDERS
99        MENUITEM "&Picture Area\tAlt+P",        ID_VIEW_PICTURE_AREA
100        MENUITEM "Screenshot Ta&b\tAlt+B",      ID_VIEW_PAGETAB
101        MENUITEM SEPARATOR
102        MENUITEM "&Fullscreen\tF11",            ID_VIEW_FULLSCREEN
103        MENUITEM SEPARATOR
104        POPUP "S&how Pictures"
105        BEGIN
106            MENUITEM "&Snapshot",                   ID_TOGGLE_TAB_SCREENSHOT
107            MENUITEM "&Flyer",                      ID_TOGGLE_TAB_FLYER
108            MENUITEM "&Cabinet",                    ID_TOGGLE_TAB_CABINET
109            MENUITEM "&Marquee",                    ID_TOGGLE_TAB_MARQUEE
110            MENUITEM "&Title",                      ID_TOGGLE_TAB_TITLE
111            MENUITEM "Control &Panel",              ID_TOGGLE_TAB_CONTROL_PANEL
112
113            MENUITEM "&History",                    ID_TOGGLE_TAB_HISTORY
114        END
115        MENUITEM SEPARATOR
116        MENUITEM "L&arge Icons",                ID_VIEW_LARGE_ICON
117        MENUITEM "S&mall Icons",                ID_VIEW_SMALL_ICON
118        MENUITEM "&List",                       ID_VIEW_LIST_MENU
119        MENUITEM "&Details",                    ID_VIEW_DETAIL
120        MENUITEM "&Grouped",                    ID_VIEW_GROUPED
121        MENUITEM SEPARATOR
122        POPUP "Arrange &Icons"
123        BEGIN
124            MENUITEM "by &Name",                    ID_VIEW_BYGAME
125            MENUITEM "by D&irectory",               ID_VIEW_BYDIRECTORY
126            MENUITEM "by &Manufacturer",            ID_VIEW_BYMANUFACTURER
127            MENUITEM "by Times &Played",            ID_VIEW_BYTIMESPLAYED
128            MENUITEM "by &Type",                    ID_VIEW_BYTYPE
129            MENUITEM "by &Date",                    ID_VIEW_BYYEAR
130        END
131        MENUITEM "Line &Up Icons",              ID_VIEW_LINEUPICONS
132        MENUITEM SEPARATOR
133        MENUITEM "&Refresh\tF5",                ID_UPDATE_GAMELIST
134        MENUITEM "&Custom Filters...\tCtrl+F",  ID_CONTEXT_FILTERS
135        MENUITEM "Customi&ze Fields...",        ID_CUSTOMIZE_FIELDS
136    END
137    POPUP "&Options"
138    BEGIN
139#ifdef MESS
140        MENUITEM "System List &Font...",          ID_OPTIONS_FONT
141        MENUITEM "System List &Clone Color...",   ID_OPTIONS_CLONE_COLOR
142        MENUITEM "&Directories...",             ID_OPTIONS_DIR
143        MENUITEM "Default System &Options...",    ID_OPTIONS_DEFAULTS
144#else
145        MENUITEM "Game List &Font...",          ID_OPTIONS_FONT
146        MENUITEM "Game List &Clone Color...",   ID_OPTIONS_CLONE_COLOR
147        MENUITEM "&Directories...",             ID_OPTIONS_DIR
148        MENUITEM "Default Game &Options...",    ID_OPTIONS_DEFAULTS
149#endif
150        MENUITEM "&Reset to Default...",        ID_OPTIONS_RESET_DEFAULTS
151        MENUITEM "&Interface Options...",       ID_OPTIONS_INTERFACE
152        MENUITEM "&Background Image...",        ID_OPTIONS_BG
153    END
154    POPUP "&Help"
155    BEGIN
156#ifdef MESS
157        MENUITEM "&Mess Release Notes",         ID_HELP_RELEASE
158        MENUITEM "&New Mess Features",          ID_HELP_WHATS_NEW
159#else
160        MENUITEM "&Contents\tF1",               ID_HELP_CONTENTS
161        MENUITEM "&Troubleshooting",            ID_HELP_TROUBLE
162        MENUITEM SEPARATOR
163        MENUITEM "&New Game Changes",           ID_HELP_WHATS_NEW32
164        MENUITEM "&Mame Release Notes",         ID_HELP_WHATS_NEW
165#endif
166        MENUITEM SEPARATOR
167        MENUITEM "&About",                      ID_HELP_ABOUT
168    END
169END
170
171IDR_CONTEXT_MENU MENU DISCARDABLE
172BEGIN
173    POPUP "Context Menu"
174    BEGIN
175        MENUITEM "&Play",                       ID_FILE_PLAY
176        MENUITEM SEPARATOR
177        MENUITEM "Play and &Record Input...",   ID_FILE_PLAY_RECORD
178        MENUITEM SEPARATOR
179        MENUITEM "&Add to Custom Folder...",    ID_CONTEXT_ADD_CUSTOM
180        MENUITEM "R&emove From This Folder",    ID_CONTEXT_REMOVE_CUSTOM
181        MENUITEM "&Custom Filters...",          ID_CONTEXT_FILTERS
182        MENUITEM SEPARATOR
183#ifdef MESS
184        MENUITEM "&Select Random System",         ID_CONTEXT_SELECT_RANDOM
185#else
186        MENUITEM "&Select Random Game",         ID_CONTEXT_SELECT_RANDOM
187#endif
188        MENUITEM SEPARATOR
189        MENUITEM "Rese&t Playcount",            ID_CONTEXT_RESET_PLAYCOUNT
190        MENUITEM "Reset Pla&y Time",            ID_CONTEXT_RESET_PLAYTIME
191        MENUITEM SEPARATOR
192        MENUITEM "A&udit",                      ID_GAME_AUDIT
193        MENUITEM SEPARATOR
194        MENUITEM "Pr&operties",                 ID_GAME_PROPERTIES
195        MENUITEM "Source propert&ies",          ID_FOLDER_SOURCEPROPERTIES
196        MENUITEM "&Vector properties",          ID_FOLDER_VECTORPROPERTIES
197    END
198END
199
200IDR_CONTEXT_HEADER MENU DISCARDABLE
201BEGIN
202    POPUP "Header Context Menu"
203    BEGIN
204        MENUITEM "Sort &Ascending",             ID_SORT_ASCENDING
205        MENUITEM "Sort &Descending",            ID_SORT_DESCENDING
206        MENUITEM SEPARATOR
207        MENUITEM "Customi&ze Fields...",        ID_CUSTOMIZE_FIELDS
208    END
209END
210
211IDR_CONTEXT_TREE MENU DISCARDABLE
212BEGIN
213    POPUP "Context Menu Tree"
214    BEGIN
215        MENUITEM "&Rename",                     ID_CONTEXT_RENAME_CUSTOM
216        MENUITEM "&Custom Filters...",          ID_CONTEXT_FILTERS
217        MENUITEM SEPARATOR
218        POPUP "&Show Folders"
219        BEGIN
220            MENUITEM "overridden by code",          ID_CONTEXT_SHOW_FOLDER_START
221
222        END
223        MENUITEM SEPARATOR
224        MENUITEM "&Audit",                      ID_FOLDER_AUDIT
225        MENUITEM SEPARATOR
226        MENUITEM "&Properties",                 ID_FOLDER_PROPERTIES
227    END
228END
229
230IDR_CONTEXT_SCREENSHOT MENU DISCARDABLE
231BEGIN
232    POPUP "Context Screen Shot"
233    BEGIN
234        MENUITEM "Show Tab &Control",           ID_VIEW_PAGETAB
235        MENUITEM SEPARATOR
236        POPUP "S&how Pictures"
237        BEGIN
238            MENUITEM "&Snapshot",                   ID_TOGGLE_TAB_SCREENSHOT
239            MENUITEM "&Flyer",                      ID_TOGGLE_TAB_FLYER
240            MENUITEM "&Cabinet",                    ID_TOGGLE_TAB_CABINET
241            MENUITEM "&Marquee",                    ID_TOGGLE_TAB_MARQUEE
242            MENUITEM "&Title",                      ID_TOGGLE_TAB_TITLE
243            MENUITEM "Control &Panel",              ID_TOGGLE_TAB_CONTROL_PANEL
244
245            MENUITEM "&History",                    ID_TOGGLE_TAB_HISTORY
246        END
247        MENUITEM SEPARATOR
248        MENUITEM "&Snapshot",                   ID_VIEW_TAB_SCREENSHOT
249        MENUITEM "&Flyer",                      ID_VIEW_TAB_FLYER
250        MENUITEM "&Cabinet",                    ID_VIEW_TAB_CABINET
251        MENUITEM "&Marquee",                    ID_VIEW_TAB_MARQUEE
252        MENUITEM "&Title",                      ID_VIEW_TAB_TITLE
253        MENUITEM "Control &Panel",              ID_VIEW_TAB_CONTROL_PANEL
254        MENUITEM "&History",                    ID_VIEW_TAB_HISTORY
255    END
256END
257
258
259#ifdef APSTUDIO_INVOKED
260/////////////////////////////////////////////////////////////////////////////
261//
262// TEXTINCLUDE
263//
264
2651 TEXTINCLUDE MOVEABLE PURE
266BEGIN
267    "resource.h\0"
268END
269
2702 TEXTINCLUDE MOVEABLE PURE
271BEGIN
272    "#define NOWINRES\r\n"
273    "#include ""windows.h""\r\n"
274    "#include ""commctrl.h""\r\n"
275    "\0"
276END
277
2783 TEXTINCLUDE MOVEABLE PURE
279BEGIN
280    "\r\n"
281    "\0"
282END
283
284#endif    // APSTUDIO_INVOKED
285
286
287#ifndef _MAC
288/////////////////////////////////////////////////////////////////////////////
289//
290// Version
291//
292
293VS_VERSION_INFO VERSIONINFO
294 FILEVERSION 0,119,0,0
295 PRODUCTVERSION 0,119,0,0
296 FILEFLAGSMASK 0x3fL
297#ifdef _DEBUG
298 FILEFLAGS 0x1L
299#else
300 FILEFLAGS 0x0L
301#endif
302 FILEOS 0x40004L
303 FILETYPE 0x1L
304 FILESUBTYPE 0x0L
305BEGIN
306    BLOCK "StringFileInfo"
307    BEGIN
308        BLOCK "040904b0"
309        BEGIN
310#ifdef MESS
311            VALUE "Author", "Michael Soderstrom and Christopher Kirmse\0"
312            VALUE "Comments", "Multiple Emulation Super System for Win32\0"
313            VALUE "CompanyName", "MESS Team\0"
314            VALUE "FileDescription", "Multiple Emulation Super System for Win32\0"
315#else
316            VALUE "Author", "Christopher Kirmse and Michael Soderstrom"
317            VALUE "Comments", "Multiple Arcade Machine Emulator for Win32"
318            VALUE "CompanyName", "MAME Team"
319            VALUE "FileDescription", "Multiple Arcade Machine Emulator for Win32"
320#endif
321            VALUE "FileVersion", "0, 119, 0, 0"
322            VALUE "InternalName", "MAME32"
323            VALUE "LegalCopyright", "Copyright 1997-2007 Nicola Salmoria and the MAME team"
324#ifdef MESS
325            VALUE "OriginalFilename", "MESS.exe\0"
326            VALUE "ProductName", "MESS\0"
327#else
328            VALUE "OriginalFilename", "MAME32.exe\0"
329            VALUE "ProductName", "MAME32"
330#endif
331            VALUE "ProductVersion", "0, 119, 0, 0"
332        END
333    END
334    BLOCK "VarFileInfo"
335    BEGIN
336        VALUE "Translation", 0x409, 1200
337    END
338END
339
340#endif    // !_MAC
341
342
343/////////////////////////////////////////////////////////////////////////////
344//
345// Icon
346//
347
348// Icon with lowest ID value placed first to ensure application icon
349// remains consistent on all systems.
350#ifdef MESS
351IDI_MAME32_ICON         ICON                    "res/mess.ico"
352#else
353IDI_MAME32_ICON         ICON    DISCARDABLE     "res\\mame32.ico"
354#endif
355IDI_WIN_ROMS            ICON    DISCARDABLE     "res\\win_roms.ico"
356IDI_WIN_NOROMS          ICON    DISCARDABLE     "res\\win_noro.ico"
357IDI_WIN_UNKNOWN         ICON    DISCARDABLE     "res\\win_unkn.ico"
358IDI_WIN_CLONE           ICON    DISCARDABLE     "res\\win_clone.ico"
359IDI_WIN_REDX            ICON    DISCARDABLE     "res/win_redx.ico"
360IDI_FOLDER_AVAILABLE    ICON    DISCARDABLE     "res\\foldavail.ico"
361IDI_FOLDER              ICON    DISCARDABLE     "res\\folder.ico"
362IDI_FOLDER_MANUFACTURER ICON    DISCARDABLE     "res\\foldmanu.ico"
363IDI_FOLDER_OPEN         ICON    DISCARDABLE     "res\\foldopen.ico"
364IDI_FOLDER_UNAVAILABLE  ICON    DISCARDABLE     "res\\foldunav.ico"
365IDI_MANUFACTURER        ICON    DISCARDABLE     "res\\manufact.ico"
366IDI_FOLDER_YEAR         ICON    DISCARDABLE     "res\\foldyear.ico"
367IDI_FOLDER_SOURCE       ICON    DISCARDABLE     "Res\\foldsrc.ico"
368IDI_WORKING             ICON    DISCARDABLE     "res\\working.ico"
369IDI_NONWORKING          ICON    DISCARDABLE     "res\\nonwork.ico"
370IDI_YEAR                ICON    DISCARDABLE     "res\\year.ico"
371IDI_KEYBOARD            ICON    DISCARDABLE     "Res\\keyboard.ico"
372IDI_JOYSTICK            ICON    DISCARDABLE     "Res\\joystick.ico"
373IDI_CPU                 ICON    DISCARDABLE     "Res\\cpu.ico"
374IDI_SOUND               ICON    DISCARDABLE     "Res\\samples.ico"
375IDI_SOUNDTAB            ICON    DISCARDABLE     "res\\sound.ico"
376IDI_SOURCE              ICON    DISCARDABLE     "res\\source.ico"
377IDI_HARDDISK            ICON    DISCARDABLE     "res\\harddisk.ico"
378IDI_DISPLAY             ICON    DISCARDABLE     "Res\\display.ico"
379IDI_CHECKMARK           ICON    DISCARDABLE     "Res\\checkmark.ico"
380IDI_HEADER_UP           ICON    DISCARDABLE     "res\\header_up.ico"
381IDI_HEADER_DOWN         ICON    DISCARDABLE     "res\\header_down.ico"
382
383#ifdef MESS
384IDI_WIN_NOROMSNEEDED    ICON                    "res/win_nrnd.ico"
385IDI_WIN_MISSINGOPTROM   ICON                  "res/win_noor.ico"
386IDI_WIN_FLOP            ICON    DISCARDABLE     "res/win_flop.ico"
387IDI_WIN_CASS            ICON    DISCARDABLE     "res/win_cass.ico"
388IDI_WIN_SERL            ICON    DISCARDABLE     "res/win_serl.ico"
389IDI_WIN_SNAP            ICON    DISCARDABLE     "res/win_snap.ico"
390IDI_WIN_PRIN            ICON    DISCARDABLE     "res/win_prin.ico"
391IDI_WIN_HARD            ICON    DISCARDABLE     "res/win_hard.ico"
392IDI_WIN_CYLN            ICON    DISCARDABLE     "res/win_cyln.ico"
393IDI_WIN_PTAP            ICON    DISCARDABLE     "res/win_ptap.ico"
394IDI_WIN_PCRD            ICON    DISCARDABLE     "res/win_pcrd.ico"
395
396#endif
397
398/////////////////////////////////////////////////////////////////////////////
399//
400// Dialog
401//
402
403IDD_ABOUT DIALOG DISCARDABLE  0, 0, 296, 129
404STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU
405#ifdef MESS
406CAPTION "About MESS"
407#else
408CAPTION "About MAME32"
409#endif
410FONT 8, "MS Shell Dlg"
411BEGIN
412    DEFPUSHBUTTON   "&OK",IDOK,200,109,50,14,WS_GROUP
413#ifdef MESS
414    CTEXT           "Multi Emulator Super System",IDC_STATIC,147,7,142,
415                    11,NOT WS_GROUP
416    CTEXT           "Version 0",IDC_VERSION,147,18,142,11,NOT WS_GROUP
417    CTEXT           "Copyright (C) 1998-2005 The MESS Team",IDC_STATIC,147,
418                    29,142,10,NOT WS_GROUP
419    CTEXT           "MESS GUI based on MAME32 version by",IDC_STATIC,147,51,142,10,NOT
420                    WS_GROUP
421    CONTROL         "",IDC_STATIC,"Static",SS_ETCHEDHORZ,147,44,142,1
422    CTEXT           "Additional MAME32 code by",IDC_STATIC,147,74,142,9
423    CTEXT           "Robert Schlabbach, Dan Miller (Help file)",IDC_STATIC,
424                    147,96,142,9
425    CTEXT           "Michael Soderstrom and Christopher Kirmse",IDC_STATIC,
426                    147,62,142,9,NOT WS_GROUP
427    CTEXT           "Mike Haaland, Andrew Kirmse, Jeff Miller",IDC_STATIC,
428                    147,85,142,9
429#else
430    CTEXT           "Multiple Arcade Machine Emulator",IDC_STATIC,147,7,142,
431                    11,NOT WS_GROUP
432    CTEXT           "Version 0",IDC_VERSION,147,18,142,11,NOT WS_GROUP
433    CTEXT           "Copyright (C) 1997-2005 The MAME Team",IDC_STATIC,147,
434                    29,142,10,NOT WS_GROUP
435    CTEXT           "MAME32 version by",IDC_STATIC,147,51,142,10,NOT
436                    WS_GROUP
437    CONTROL         "",IDC_STATIC,"Static",SS_ETCHEDHORZ,147,44,142,1
438    CTEXT           "Additional MAME32 code by",IDC_STATIC,147,74,142,9
439    CTEXT           "Christopher Kirmse and Michael Soderstrom",IDC_STATIC,
440                    147,62,142,9,NOT WS_GROUP
441    CTEXT           "Mike Haaland, Andrew Kirmse, Jeff Miller",IDC_STATIC,
442                    147,85,142,9
443    CTEXT           "and John Hardy IV",IDC_STATIC,147,96,142,9
444#endif
445    CONTROL         "",IDC_ABOUT,"Static",SS_BITMAP | SS_SUNKEN,7,7,16,14
446END
447
448IDD_DIRECTX DIALOG DISCARDABLE  0, 0, 236, 69
449STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU
450#ifdef MESS
451CAPTION "MESS"
452#else
453CAPTION "MAME32"
454#endif
455FONT 8, "MS Shell Dlg"
456BEGIN
457    DEFPUSHBUTTON   "Go to Microsoft's DirectX Web Page",IDB_WEB_PAGE,48,52,
458                    140,14
459    EDITTEXT        IDC_DIRECTX_HELP,7,0,222,48,ES_MULTILINE |
460                    ES_AUTOHSCROLL | ES_READONLY
461END
462
463IDD_AUDIT DIALOG DISCARDABLE  0, 0, 283, 188
464STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU
465CAPTION "File Audit"
466FONT 8, "MS Shell Dlg"
467BEGIN
468    PUSHBUTTON      "&Pause",IDPAUSE,98,168,40,14
469    PUSHBUTTON      "&Cancel",IDCANCEL,144,168,40,14
470    GROUPBOX        "ROMs",IDC_STATIC,6,4,132,65
471    LTEXT           "Correct:",IDC_STATIC,51,28,32,8
472    CONTROL         "Progress1",IDC_ROMS_PROGRESS,"msctls_progress32",
473                    PBS_SMOOTH | WS_BORDER,14,16,116,8
474    LTEXT           "Incorrect:",IDC_STATIC,51,42,32,8
475    LTEXT           "Total:",IDC_STATIC,51,56,32,8
476    LTEXT           "0",IDC_ROMS_CORRECT,87,28,20,8
477    LTEXT           "0",IDC_ROMS_INCORRECT,87,42,20,8
478    LTEXT           "0",IDC_ROMS_TOTAL,87,56,20,8
479    GROUPBOX        "Samples",IDC_STATIC,145,4,132,65
480    CONTROL         "Progress1",IDC_SAMPLES_PROGRESS,"msctls_progress32",
481                    PBS_SMOOTH | WS_BORDER,153,16,116,8
482    LTEXT           "Correct:",IDC_STATIC,191,28,33,8
483    LTEXT           "Incorrect:",IDC_STATIC,191,42,33,8
484    LTEXT           "Total:",IDC_STATIC,191,56,33,8
485    LTEXT           "0",IDC_SAMPLES_CORRECT,227,28,20,8
486    LTEXT           "0",IDC_SAMPLES_INCORRECT,227,42,20,8
487    LTEXT           "0",IDC_SAMPLES_TOTAL,227,56,20,8
488    GROUPBOX        "Details",IDC_STATIC,6,72,271,90
489    EDITTEXT        IDC_AUDIT_DETAILS,12,82,259,74,ES_MULTILINE |
490                    ES_AUTOVSCROLL | ES_READONLY | WS_VSCROLL | WS_HSCROLL |
491                    NOT WS_TABSTOP
492END
493
494IDD_DIRECTORIES DIALOG DISCARDABLE  0, 0, 230, 107
495STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU
496CAPTION "Directories"
497FONT 8, "MS Shell Dlg"
498BEGIN
499    LTEXT           "Show directories for:",IDC_STATIC,6,6,67,10
500    COMBOBOX        IDC_DIR_COMBO,6,18,160,79,CBS_DROPDOWNLIST | CBS_SORT |
501                    WS_VSCROLL | WS_TABSTOP
502    LTEXT           "Directories:",IDC_STATIC,6,38,38,10
503    CONTROL         "List1",IDC_DIR_LIST,"SysListView32",LVS_REPORT |
504                    LVS_SINGLESEL | LVS_SHOWSELALWAYS | LVS_EDITLABELS |
505                    LVS_ALIGNLEFT | LVS_NOCOLUMNHEADER | WS_BORDER |
506                    WS_TABSTOP,6,50,160,51
507    DEFPUSHBUTTON   "OK",IDOK,173,8,50,14
508    PUSHBUTTON      "Cancel",IDCANCEL,173,26,50,14
509    PUSHBUTTON      "Browse...",IDC_DIR_BROWSE,173,50,50,14
510    PUSHBUTTON      "Insert",IDC_DIR_INSERT,173,68,50,14
511    PUSHBUTTON      "Delete",IDC_DIR_DELETE,173,87,50,14
512END
513
514IDD_COLUMNS DIALOG DISCARDABLE  0, 0, 302, 145
515STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU
516CAPTION "Customize Fields"
517FONT 8, "MS Shell Dlg"
518BEGIN
519    LTEXT           "Available fields:",IDC_STATIC,6,6,80,10,SS_CENTERIMAGE
520    CONTROL         "List1",IDC_LISTAVAILABLECOLUMNS,"SysListView32",
521                    LVS_LIST | LVS_SINGLESEL | LVS_NOCOLUMNHEADER |
522                    LVS_NOSORTHEADER | WS_BORDER | WS_HSCROLL | WS_TABSTOP,6,
523                    18,90,100
524    PUSHBUTTON      "Add ->",IDC_BUTTONADD,102,18,46,14,WS_DISABLED
525    PUSHBUTTON      "<- Remove",IDC_BUTTONREMOVE,102,36,46,14,WS_DISABLED
526    LTEXT           "Show these fields in this order:",IDC_STATIC,154,6,96,
527                    10,SS_CENTERIMAGE
528    CONTROL         "List1",IDC_LISTSHOWCOLUMNS,"SysListView32",LVS_LIST |
529                    LVS_SINGLESEL | LVS_NOCOLUMNHEADER | LVS_NOSORTHEADER |
530                    WS_BORDER | WS_HSCROLL | WS_TABSTOP,154,18,90,100
531    PUSHBUTTON      "Move Up",IDC_BUTTONMOVEUP,250,18,46,14,WS_DISABLED
532    PUSHBUTTON      "Move Down",IDC_BUTTONMOVEDOWN,250,36,46,14,WS_DISABLED
533    DEFPUSHBUTTON   "OK",IDOK,105,124,44,14
534    PUSHBUTTON      "Cancel",IDCANCEL,155,124,44,14
535END
536
537IDD_PROP_GAME DIALOG DISCARDABLE  0, 0, 220, 240
538STYLE WS_CHILD | WS_CAPTION
539CAPTION "General"
540FONT 8, "MS Shell Dlg"
541BEGIN
542    ICON            IDI_MAME32_ICON,IDC_GAME_ICON,20,10,20,20
543    LTEXT           "Title\nDirectory\nExtra",IDC_PROP_TITLE,52,9,161,25,
544                    SS_NOPREFIX
545    CONTROL         "",IDC_STATIC,"Static",SS_ETCHEDHORZ,20,38,178,1
546    LTEXT           "Manufactured:",IDC_STATIC,18,45,47,8
547    LTEXT           "Static",IDC_PROP_MANUFACTURED,75,45,139,9,SS_NOPREFIX
548    LTEXT           "Status:",IDC_STATIC,18,55,47,8
549    LTEXT           "Static",IDC_PROP_STATUS,75,55,139,30
550    CONTROL         "",IDC_STATIC,"Static",SS_ETCHEDHORZ,18,85,178,1
551    LTEXT           "CPU:",IDC_STATIC,18,90,47,8
552    LTEXT           "Static\nStatic\nStatic\nStatic\nStatic",IDC_PROP_CPU,75,
553                    90,139,40
554    CONTROL         "",IDC_STATIC,"Static",SS_ETCHEDHORZ,18,130,178,1
555    LTEXT           "Sound:",IDC_STATIC,18,135,47,8
556    LTEXT           "Static\nStatic\nStatic\nStatic\nStatic",IDC_PROP_SOUND,
557                    75,135,139,45
558    CONTROL         "",IDC_STATIC,"Static",SS_ETCHEDHORZ,18,181,178,1
559    LTEXT           "Screen:",IDC_STATIC,18,188,47,8
560    LTEXT           "Static",IDC_PROP_SCREEN,75,188,139,8
561    LTEXT           "Colors:",IDC_STATIC,18,198,47,8
562    LTEXT           "Static",IDC_PROP_COLORS,75,198,139,8
563    LTEXT           "Clone of:",IDC_PROP_CLONEOF_TEXT,18,218,50,8
564    LTEXT           "Static",IDC_PROP_CLONEOF,75,218,130,18
565    LTEXT           "Source:",IDC_STATIC,18,208,47,8
566    LTEXT           "Static",IDC_PROP_SOURCE,75,208,139,8
567END
568
569IDD_PROP_AUDIT DIALOG DISCARDABLE  0, 0, 220, 240
570STYLE WS_CHILD | WS_CAPTION
571CAPTION "Audit"
572FONT 8, "MS Shell Dlg"
573BEGIN
574    ICON            IDI_CHECKMARK,IDC_STATIC,20,10,20,20
575    LTEXT           "Title\nDirectory\nExtra",IDC_PROP_TITLE,52,9,161,25,
576                    SS_NOPREFIX
577    LTEXT           "ROM check:",IDC_STATIC,10,40,50,8
578    LTEXT           "Checking...",IDC_PROP_ROMS,66,40,139,8
579    LTEXT           "Sample check:",IDC_STATIC,10,52,50,8
580    LTEXT           "Checking...",IDC_PROP_SAMPLES,66,52,139,8
581    GROUPBOX        "Details",IDC_STATIC,4,64,211,171
582    EDITTEXT        IDC_AUDIT_DETAILS_PROP,10,74,199,155,ES_MULTILINE |
583                    ES_AUTOVSCROLL | ES_READONLY | WS_VSCROLL | WS_HSCROLL |
584                    NOT WS_TABSTOP
585END
586
587IDD_PROP_DISPLAY DIALOGEX 0, 0, 220, 240
588STYLE WS_CHILD | WS_CAPTION
589CAPTION "Display"
590FONT 8, "MS Shell Dlg", 0, 0, 0x1
591BEGIN
592    ICON            IDI_DISPLAY,IDC_STATIC,20,10,20,20
593    LTEXT           "Title\nDirectory\nExtra",IDC_PROP_TITLE,52,9,169,25,
594                    SS_NOPREFIX
595    CONTROL         "Run in a window",IDC_WINDOWED,"Button",BS_AUTOCHECKBOX |
596                    WS_TABSTOP,10,40,69,10,0,HIDC_WINDOWED
597    CONTROL         "Start out maximized",IDC_MAXIMIZE,"Button",
598                    BS_AUTOCHECKBOX | WS_TABSTOP,10,52,74,10,0,HIDC_MAXIMIZE
599    CONTROL         "Enforce aspect ratio",IDC_KEEPASPECT,"Button",
600                    BS_AUTOCHECKBOX | WS_TABSTOP,10,64,77,10,0,
601                    HIDC_KEEPASPECT
602    CONTROL         "Throttle",IDC_THROTTLE,"Button",BS_AUTOCHECKBOX |
603                    WS_TABSTOP,10,76,39,10,0,HIDC_THROTTLE
604    GROUPBOX        "Bitmap prescaling",IDC_STATIC,4,89,103,24
605    CONTROL         "GammaSlider",IDC_PRESCALE,"msctls_trackbar32",TBS_BOTH |
606                    TBS_NOTICKS | WS_TABSTOP,10,99,71,10,0,HIDC_PRESCALE
607    RTEXT           "1.00",IDC_PRESCALEDISP,84,98,14,11,SS_CENTERIMAGE | NOT
608                    WS_GROUP
609    GROUPBOX        "Gamma Correction",IDC_STATIC,4,115,103,24
610    CONTROL         "GammaSlider",IDC_GAMMA,"msctls_trackbar32",TBS_BOTH |
611                    TBS_NOTICKS | WS_TABSTOP,10,125,71,10,0,HIDC_GAMMA
612    RTEXT           "2.00",IDC_GAMMADISP,84,124,14,10,SS_CENTERIMAGE | NOT
613                    WS_GROUP
614    GROUPBOX        "Brightness Correction",IDC_STATIC,4,141,103,24
615    CONTROL         "GammaSlider",IDC_BRIGHTCORRECT,"msctls_trackbar32",
616                    TBS_BOTH | TBS_NOTICKS | WS_TABSTOP,10,151,71,10,0,
617                    HIDC_BRIGHTCORRECT
618    RTEXT           "1.00",IDC_BRIGHTCORRECTDISP,84,150,14,10,SS_CENTERIMAGE |
619                    NOT WS_GROUP
620    GROUPBOX        "Contrast Correction",IDC_STATIC,4,167,103,24
621    CONTROL         "GammaSlider",IDC_CONTRAST,"msctls_trackbar32",TBS_BOTH |
622                    TBS_NOTICKS | WS_TABSTOP,10,176,71,10,0,HIDC_CONTRAST
623    RTEXT           "1.00",IDC_CONTRASTDISP,84,175,14,11,SS_CENTERIMAGE |
624                    NOT WS_GROUP
625    GROUPBOX        "Pause Brightness",IDC_STATIC,4,193,103,24
626    CONTROL         "Slider1",IDC_PAUSEBRIGHT,"msctls_trackbar32",TBS_BOTH |
627                    TBS_NOTICKS | WS_TABSTOP,10,203,71,10,0,HIDC_PAUSEBRIGHT
628    RTEXT           "0.65",IDC_PAUSEBRIGHTDISP,84,202,14,11,SS_CENTERIMAGE |
629                    NOT WS_GROUP
630    GROUPBOX        "Videomode",IDC_STATIC,113,40,102,28
631    COMBOBOX        IDC_VIDEO_MODE,119,50,90,50,CBS_DROPDOWNLIST | CBS_SORT |
632                    WS_VSCROLL | WS_TABSTOP,0,HIDC_VIDEO_MODE
633    GROUPBOX        "Rotation",IDC_STATIC,113,71,102,55
634    COMBOBOX        IDC_ROTATE,119,81,90,57,CBS_DROPDOWNLIST | WS_VSCROLL |
635                    WS_TABSTOP,0,HIDC_ROTATE
636    CONTROL         "Flip screen upside-down",IDC_FLIPY,"Button",
637                    BS_AUTOCHECKBOX | WS_TABSTOP,119,98,91,10,0,HIDC_FLIPY
638    CONTROL         "Flip screen left-right",IDC_FLIPX,"Button",
639                    BS_AUTOCHECKBOX | WS_TABSTOP,119,110,77,10,0,HIDC_FLIPX
640    GROUPBOX        "Direct3D",IDC_STATIC,113,128,102,57
641    CONTROL         "Use Bilinear filtering",IDC_D3D_FILTER,"Button",
642                    BS_AUTOCHECKBOX | WS_TABSTOP,119,138,85,10,0,
643                    HIDC_D3D_FILTER
644    GROUPBOX        "Version",IDC_STATIC,119,150,90,28
645    COMBOBOX        IDC_D3D_VERSION,125,160,78,95,CBS_DROPDOWNLIST |
646                    WS_VSCROLL | WS_TABSTOP,0,HIDC_D3D_VERSION
647    GROUPBOX        "DirectDraw",IDC_STATIC,113,187,102,26
648    CONTROL         "Stretch using hardware",IDC_HWSTRETCH,"Button",
649                    BS_AUTOCHECKBOX | WS_TABSTOP,119,197,85,10,0,
650                    HIDC_HWSTRETCH
651    PUSHBUTTON      "Reset",IDC_PROP_RESET,4,222,97,14,0,0,HIDC_PROP_RESET
652    PUSHBUTTON      "Restore Default Settings",IDC_USE_DEFAULT,118,222,97,14,
653                    0,0,HIDC_USE_DEFAULT
654END
655
656IDD_PROP_SOUND DIALOGEX 0, 0, 220, 240
657STYLE WS_CHILD | WS_CAPTION
658CAPTION "Sound"
659FONT 8, "MS Shell Dlg", 0, 0, 0x1
660BEGIN
661    ICON            IDI_SOUNDTAB,IDC_STATIC,20,10,20,20
662    LTEXT           "Title\nDirectory\nExtra",IDC_PROP_TITLE,52,9,161,25,
663                    SS_NOPREFIX
664    GROUPBOX        "",IDC_STATIC,4,40,211,122
665    CONTROL         "Enable sound and sound CPUs",IDC_USE_SOUND,"Button",
666                    BS_AUTOCHECKBOX | WS_TABSTOP,10,40,112,10,0,
667                    HIDC_USE_SOUND
668    CONTROL         "Use samples",IDC_SAMPLES,"Button",BS_AUTOCHECKBOX |
669                    WS_TABSTOP,10,52,55,10,0,HIDC_SAMPLES
670    GROUPBOX        "Sample rate",IDC_RATETEXT,60,65,100,28
671    COMBOBOX        IDC_SAMPLERATE,66,75,88,60,CBS_DROPDOWNLIST |
672                    WS_VSCROLL | WS_TABSTOP,0,
673                    HIDC_SAMPLERATE
674    GROUPBOX        "Volume attenuation",IDC_STATIC,60,96,100,28
675    CONTROL         "Slider1",IDC_VOLUME,"msctls_trackbar32",TBS_BOTH |
676                    TBS_NOTICKS | WS_TABSTOP,66,108,68,10,0,HIDC_VOLUME
677    RTEXT           "0dB",IDC_VOLUMEDISP,132,107,20,11,SS_CENTERIMAGE
678    GROUPBOX        "Audio latency",IDC_AUDIO_LATENCY_TEXT,60,127,100,28
679    CONTROL         "Slider1",IDC_AUDIO_LATENCY,"msctls_trackbar32",TBS_BOTH |
680                    TBS_NOTICKS | WS_TABSTOP,66,139,68,10,0,
681                    HIDC_AUDIO_LATENCY
682    RTEXT           "1/5",IDC_AUDIO_LATENCY_DISP,132,138,20,11,
683                    SS_CENTERIMAGE
684    PUSHBUTTON      "Reset",IDC_PROP_RESET,4,222,97,14,0,0,HIDC_PROP_RESET
685    PUSHBUTTON      "Restore Default Settings",IDC_USE_DEFAULT,118,222,97,14,
686                    0,0,HIDC_USE_DEFAULT
687END
688
689IDD_PROP_ADVANCED DIALOGEX 0, 0, 220, 240
690STYLE WS_CHILD | WS_CAPTION
691CAPTION "Advanced"
692FONT 8, "MS Shell Dlg", 0, 0, 0x1
693BEGIN
694    ICON            IDI_DISPLAY,IDC_STATIC,20,10,20,20
695    LTEXT           "Title\nDirectory\nExtra",IDC_PROP_TITLE,52,9,161,25,
696                    SS_NOPREFIX
697    CONTROL         "Triple buffering",IDC_TRIPLE_BUFFER,"Button",
698                    BS_AUTOCHECKBOX | WS_TABSTOP,10,40,93,10,0,
699                    HIDC_TRIPLE_BUFFER
700    CONTROL         "Sync to monitor refresh",IDC_SYNCREFRESH,"Button",
701                    BS_AUTOCHECKBOX | WS_TABSTOP,10,52,93,10,0,
702                    HIDC_SYNCREFRESH
703    CONTROL         "Wait for vertical sync",IDC_WAITVSYNC,"Button",
704                    BS_AUTOCHECKBOX | WS_TABSTOP,10,64,93,10,0,
705                    HIDC_WAITVSYNC
706    GROUPBOX        "Frame skipping",IDC_STATIC,4,76,103,42
707    CONTROL         "Automatic",IDC_AUTOFRAMESKIP,"Button",BS_AUTOCHECKBOX |
708                    WS_TABSTOP,10,86,77,10,0,HIDC_AUTOFRAMESKIP
709    COMBOBOX        IDC_FRAMESKIP,10,99,91,88,CBS_DROPDOWNLIST | WS_VSCROLL |
710                    WS_TABSTOP,0,HIDC_FRAMESKIP
711    GROUPBOX        "Full screen gamma",IDC_FSGAMMATEXT,113,40,102,24
712    CONTROL         "Slider1",IDC_FSGAMMA,"msctls_trackbar32",TBS_BOTH |
713                    TBS_NOTICKS | WS_TABSTOP,119,50,71,10,0,HIDC_FSGAMMA
714    RTEXT           "2.00",IDC_FSGAMMADISP,193,49,14,10,SS_CENTERIMAGE | NOT
715                    WS_GROUP
716    GROUPBOX        "Full screen brightness",IDC_FSBRIGHTNESSTEXT,113,67,102,
717                    24
718    CONTROL         "Slider1",IDC_FSBRIGHTNESS,"msctls_trackbar32",TBS_BOTH |
719                    TBS_NOTICKS | WS_TABSTOP,119,77,71,10,0,
720                    HIDC_FSBRIGHTNESS
721    RTEXT           "2.00",IDC_FSBRIGHTNESSDISP,193,76,14,10,SS_CENTERIMAGE |
722                    NOT WS_GROUP
723    GROUPBOX        "Full screen contrast",IDC_FSCONTRASTTEXT,113,94,102,24
724    CONTROL         "Slider1",IDC_FSCONTRAST,"msctls_trackbar32",TBS_BOTH |
725                    TBS_NOTICKS | WS_TABSTOP,119,104,71,10,0,HIDC_FSCONTRAST
726    RTEXT           "2.00",IDC_FSCONTRASTDISP,193,103,14,11,SS_CENTERIMAGE |
727                    NOT WS_GROUP
728    EDITTEXT        IDC_EFFECT,10,123,200,14,ES_AUTOHSCROLL | WS_DISABLED
729    PUSHBUTTON      "Select Effect",IDC_SELECT_EFFECT,10,142,60,14,0,0,
730                    HIDC_SELECT_EFFECT
731    PUSHBUTTON      "Reset Effect",IDC_RESET_EFFECT,150,142,60,14,0,0,
732                    HIDC_RESET_EFFECT
733    PUSHBUTTON      "Reset",IDC_PROP_RESET,4,222,97,14,0,0,HIDC_PROP_RESET
734    PUSHBUTTON      "Restore Default Settings",IDC_USE_DEFAULT,118,222,97,14,
735                    0,0,HIDC_USE_DEFAULT
736END
737
738IDD_PROP_INPUT DIALOGEX 0, 0, 220, 263
739STYLE WS_CHILD | WS_CAPTION
740CAPTION "Controllers"
741FONT 8, "MS Shell Dlg"
742BEGIN
743    ICON            IDI_JOYSTICK,IDC_STATIC,20,10,21,20
744    LTEXT           "Title\nDirectory\nExtra",IDC_PROP_TITLE,52,9,161,25,
745                    SS_NOPREFIX
746    CONTROL         "Enable mouse input",IDC_USE_MOUSE,"Button",
747                    BS_AUTOCHECKBOX | WS_TABSTOP,10,40,86,10,0,
748                    HIDC_USE_MOUSE
749    CONTROL         "Enable steadykey support",IDC_STEADYKEY,"Button",
750                    BS_AUTOCHECKBOX | WS_TABSTOP,10,52,95,10,0,
751                    HIDC_STEADYKEY
752    GROUPBOX        "",IDC_STATIC,4,64,103,74
753    CONTROL         "Enable joystick input",IDC_JOYSTICK,"Button",
754                    BS_AUTOCHECKBOX | WS_GROUP | WS_TABSTOP,10,64,78,10,0,
755                    HIDC_JOYSTICK
756    GROUPBOX        "Joystick deadzone",IDC_JDZTEXT,10,76,91,28
757    CONTROL         "IntensitySlider",IDC_JDZ,"msctls_trackbar32",TBS_BOTH |
758                    TBS_NOTICKS | WS_TABSTOP,15,88,60,10,0,HIDC_JDZ
759    RTEXT           "0.3",IDC_JDZDISP,76,87,16,11,SS_CENTERIMAGE | NOT
760                    WS_GROUP
761    GROUPBOX        "Default input layout",IDC_STATIC,113,40,102,28
762    COMBOBOX        IDC_DEFAULT_INPUT,119,50,90,53,CBS_DROPDOWNLIST |
763                    WS_VSCROLL | WS_TABSTOP,0,HIDC_DEFAULT_INPUT
764    GROUPBOX        "",IDC_STATIC,113,71,102,66
765    CONTROL         "Enable lightgun input",IDC_LIGHTGUN,"Button",
766                    BS_AUTOCHECKBOX | WS_TABSTOP,119,71,80,10,0,
767                    HIDC_LIGHTGUN
768    CONTROL         "Offscreen shots reload",IDC_RELOAD,"Button",
769                    BS_AUTOCHECKBOX | WS_TABSTOP,119,83,86,10,0,HIDC_RELOAD
770    CONTROL         "Dual lightguns",IDC_DUAL_LIGHTGUN,"Button",
771                    BS_AUTOCHECKBOX | WS_TABSTOP,119,96,86,10,0,
772                    HIDC_DUAL_LIGHTGUN
773    CONTROL         "Multiple keyboards",IDC_MULTIKEYBOARD,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,119,109,75,10
774    CONTROL         "Multiple mice",IDC_MULTIMOUSE,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,119,122,56,10
775    PUSHBUTTON      "Reset",IDC_PROP_RESET,4,243,97,14,0,0,HIDC_PROP_RESET
776    PUSHBUTTON      "Restore Default Settings",IDC_USE_DEFAULT,118,243,97,14,
777                    0,0,HIDC_USE_DEFAULT
778    GROUPBOX        "Joystick saturation",IDC_JSATTEXT,10,106,91,28
779    CONTROL         "IntensitySlider",IDC_JSAT,"msctls_trackbar32",TBS_BOTH |
780                    TBS_NOTICKS | WS_TABSTOP,16,118,60,10,0,HIDC_JSAT
781    RTEXT           "0.85",IDC_JSATDISP,76,116,16,11,SS_CENTERIMAGE | NOT
782                    WS_GROUP
783END
784
785IDD_PROP_MISC DIALOGEX 0, 0, 220, 240
786STYLE WS_CHILD | WS_CAPTION
787CAPTION "Miscellaneous"
788FONT 8, "MS Shell Dlg", 0, 0, 0x1
789BEGIN
790    ICON            IDI_MAME32_ICON,IDC_STATIC,20,10,21,20
791    LTEXT           "Title\nDirectory\nExtra",IDC_PROP_TITLE,52,9,161,25,
792                    SS_NOPREFIX
793#ifdef MESS
794    CONTROL         "Enable system cheats",IDC_CHEAT,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,10,40,86,10,0,HIDC_CHEAT
795#else
796    CONTROL         "Enable game cheats",IDC_CHEAT,"Button",BS_AUTOCHECKBOX |
797                    WS_TABSTOP,10,40,86,10,0,HIDC_CHEAT
798#endif
799    CONTROL         "Error log (for developers)",IDC_LOG,"Button",
800                    BS_AUTOCHECKBOX | WS_TABSTOP,10,52,96,10,0,HIDC_LOG
801    CONTROL         "Sleep when possible",IDC_SLEEP,"Button",BS_AUTOCHECKBOX |
802                    WS_TABSTOP,10,64,86,10,0,HIDC_SLEEP
803#ifdef MESS
804    CONTROL         "Skip system info",IDC_SKIP_GAME_INFO,"Button",
805                    BS_AUTOCHECKBOX | WS_TABSTOP,10,88,96,10,0,
806                    HIDC_SKIP_GAME_INFO
807#else
808    CONTROL         "Skip game info",IDC_SKIP_GAME_INFO,"Button",
809                    BS_AUTOCHECKBOX | WS_TABSTOP,10,88,96,10,0,
810                    HIDC_SKIP_GAME_INFO
811#endif
812    CONTROL         "Save game state on exit",IDC_ENABLE_AUTOSAVE,"Button",
813                    BS_AUTOCHECKBOX | WS_TABSTOP,10,100,96,10,0,
814                    HIDC_ENABLE_AUTOSAVE
815    CONTROL         "Multi-threaded rendering",IDC_MULTITHREAD_RENDERING,
816                    "Button",BS_AUTOCHECKBOX | WS_TABSTOP,10,112,96,10,0,
817                    HIDC_MULTITHREAD_RENDERING
818    GROUPBOX        "Thread Priority",IDC_HIGH_PRIORITY_TEXT,4,124,103,34
819    CONTROL         "Slider1",IDC_HIGH_PRIORITY,"msctls_trackbar32",TBS_BOTH |
820                    TBS_NOTICKS | WS_TABSTOP,10,135,75,10,0,
821                    HIDC_HIGH_PRIORITY
822    LTEXT           "idle",IDC_STATIC,13,144,12,8
823    RTEXT           "-15",IDC_HIGH_PRIORITYTXT,84,134,14,10,SS_CENTERIMAGE
824    RTEXT           "real-time",IDC_STATIC,53,144,28,8
825    GROUPBOX        "Artwork options",IDC_STATIC,113,40,102,61
826    CONTROL         "Backdrops",IDC_BACKDROPS,"Button",BS_AUTOCHECKBOX |
827                    WS_TABSTOP,119,50,86,10,0,HIDC_BACKDROPS
828    CONTROL         "Bezels",IDC_BEZELS,"Button",BS_AUTOCHECKBOX |
829                    WS_TABSTOP,119,62,86,10,0,HIDC_BEZELS
830    CONTROL         "Overlays",IDC_OVERLAYS,"Button",BS_AUTOCHECKBOX |
831                    WS_TABSTOP,119,74,84,10,0,HIDC_OVERLAYS
832    CONTROL         "Crop artwork",IDC_ARTWORK_CROP,"Button",BS_AUTOCHECKBOX |
833                    WS_TABSTOP,119,86,53,10,0,HIDC_ARTWORK_CROP
834    GROUPBOX        "BIOS",IDC_STATIC,113,104,102,28
835    COMBOBOX        IDC_BIOS,119,114,90,60,CBS_DROPDOWNLIST | WS_VSCROLL |
836                    WS_TABSTOP,0,HIDC_BIOS
837    PUSHBUTTON      "Reset",IDC_PROP_RESET,4,222,97,14,0,0,HIDC_PROP_RESET
838    PUSHBUTTON      "Restore Default Settings",IDC_USE_DEFAULT,118,222,97,14,
839                    0,0,HIDC_USE_DEFAULT
840#ifdef MESS
841    CONTROL         "Skip warnings",IDC_SKIP_WARNINGS,"Button",
842                    BS_AUTOCHECKBOX | WS_TABSTOP,10,180,86,10,0
843    CONTROL         "Use New UI",IDC_USE_NEW_UI,"Button",
844                    BS_AUTOCHECKBOX | WS_TABSTOP,10,192,86,10,0
845#endif
846END
847
848IDD_PROP_VECTOR DIALOGEX 0, 0, 220, 240
849STYLE WS_CHILD | WS_CAPTION
850CAPTION "Vector"
851FONT 8, "MS Shell Dlg", 0, 0, 0x1
852BEGIN
853    ICON            IDI_MAME32_ICON,IDC_STATIC,20,10,20,20
854    LTEXT           "Title\nDirectory\nExtra",IDC_PROP_TITLE,52,9,161,25,
855                    SS_NOPREFIX
856    CONTROL         "Draw antialiased vectors",IDC_ANTIALIAS,"Button",
857                    BS_AUTOCHECKBOX | WS_TABSTOP,10,40,92,10,0,
858                    HIDC_ANTIALIAS
859    GROUPBOX        "Beam width",IDC_BEAMTEXT,60,53,100,28
860    CONTROL         "BeamSlider",IDC_BEAM,"msctls_trackbar32",TBS_BOTH |
861                    TBS_NOTICKS | WS_TABSTOP,66,65,64,10,0,HIDC_BEAM
862    RTEXT           "16.00",IDC_BEAMDISP,132,64,20,11,SS_CENTERIMAGE
863    GROUPBOX        "Flicker",IDC_FLICKERTEXT,60,84,100,28
864    CONTROL         "FlickerSlider",IDC_FLICKER,"msctls_trackbar32",TBS_BOTH |
865                    TBS_NOTICKS | WS_TABSTOP,66,96,64,10,0,HIDC_FLICKER
866    RTEXT           "100.00",IDC_FLICKERDISP,128,95,24,11,SS_CENTERIMAGE |
867                    NOT WS_GROUP
868    PUSHBUTTON      "Reset",IDC_PROP_RESET,4,222,97,14,0,0,HIDC_PROP_RESET
869    PUSHBUTTON      "Restore Default Settings",IDC_USE_DEFAULT,118,222,97,14,
870                    0,0,HIDC_USE_DEFAULT
871END
872
873
874#ifdef MESS
875IDD_MAIN DIALOGEX 0, 0, 364, 206
876#else
877IDD_MAIN DIALOGEX 0, 0, 304, 206
878#endif
879STYLE DS_3DLOOK | DS_NOFAILCREATE | WS_MINIMIZEBOX | WS_MAXIMIZEBOX |
880    WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME
881EXSTYLE WS_EX_CONTROLPARENT
882CAPTION "MAME32 - overwritten at runtime"
883CLASS "MainClass"
884FONT 8, "MS Shell Dlg", 0, 0, 0x1
885BEGIN
886    CONTROL         "",IDC_DIVIDER,"Static",SS_ETCHEDHORZ,0,5,304,1
887    CONTROL         "Tree1",IDC_TREE,"SysTreeView32",TVS_HASBUTTONS |
888                    TVS_HASLINES | TVS_LINESATROOT | TVS_EDITLABELS |
889                    TVS_SHOWSELALWAYS | TVS_FULLROWSELECT | WS_BORDER |
890                    WS_TABSTOP,5,28,48,172
891    CONTROL         "List1",IDC_LIST,"SysListView32",LVS_REPORT |
892                    LVS_SINGLESEL | LVS_SHOWSELALWAYS | LVS_AUTOARRANGE |
893                    LVS_OWNERDRAWFIXED | WS_BORDER | WS_TABSTOP,65,28,42,172
894    GROUPBOX        "",IDC_SPLITTER,55,28,8,172,BS_NOTIFY | NOT WS_VISIBLE
895    GROUPBOX        "",IDC_SPLITTER2,109,28,8,172,BS_NOTIFY | NOT WS_VISIBLE
896#ifdef MESS
897    CONTROL         "",IDC_SSTAB,"SysTabControl32",TCS_HOTTRACK,121,0,181,18
898    CONTROL         "",IDC_SWTAB,"SysTabControl32",TCS_HOTTRACK,119,0,200,100
899    CONTROL         "List2",IDC_SWLIST,"SysListView32",LVS_REPORT |
900                    LVS_SHOWSELALWAYS | LVS_OWNERDRAWFIXED | WS_BORDER |
901               WS_TABSTOP,119,60,42,140
902   CONTROL         "",IDC_SWDEVVIEW,"MessSoftwareDevView",WS_VISIBLE,119,0,200,100
903    GROUPBOX        "",IDC_SPLITTER3,163,28,8,172,BS_NOTIFY | NOT WS_VISIBLE
904    CONTROL         "",IDC_SSFRAME,"Static",SS_ETCHEDFRAME,175,11,181,194
905    CONTROL         "",IDC_SSPICTURE,"Static",SS_BITMAP | SS_NOTIFY |
906                    SS_CENTERIMAGE | NOT WS_VISIBLE,195,18,141,127
907    EDITTEXT        IDC_HISTORY,183,150,167,49,ES_MULTILINE | ES_READONLY |
908                    WS_VSCROLL,WS_EX_STATICEDGE,HIDC_HISTORY
909#else
910    CONTROL         "",IDC_SSFRAME,"Static",SS_ETCHEDFRAME | SS_NOTIFY,121,
911                    11,181,194
912    CONTROL         "",IDC_SSTAB,"SysTabControl32",TCS_HOTTRACK,121,0,181,18
913    CONTROL         "",IDC_SSPICTURE,"Static",SS_BITMAP | NOT WS_VISIBLE,141,
914                    18,141,127
915    EDITTEXT        IDC_HISTORY,129,150,167,49,ES_MULTILINE | ES_READONLY |
916                    NOT WS_BORDER | WS_VSCROLL | NOT WS_TABSTOP,0,
917                    HIDC_HISTORY
918#endif
919END
920
921IDD_FILTERS DIALOGEX 0, 0, 190, 182
922STYLE DS_MODALFRAME | DS_3DLOOK | WS_POPUP | WS_CAPTION | WS_SYSMENU
923EXSTYLE WS_EX_CONTEXTHELP
924#ifdef MESS
925CAPTION "System Filters"
926#else
927CAPTION "Game Filters"
928#endif
929FONT 8, "MS Shell Dlg", 0, 0, 0x1
930BEGIN
931#ifdef MESS
932    GROUPBOX        "System filters",IDC_STATIC,6,4,178,85
933#else
934    GROUPBOX        "Game filters",IDC_STATIC,6,4,178,85
935#endif
936    CONTROL         "&Vector Graphics",IDC_FILTER_VECTOR,"Button",
937                    BS_AUTOCHECKBOX | WS_TABSTOP,14,16,70,10,0,
938                    HIDC_FILTER_VECTOR
939    CONTROL         "C&lones",IDC_FILTER_CLONES,"Button",BS_AUTOCHECKBOX |
940                    WS_TABSTOP,14,30,41,10,0,HIDC_FILTER_CLONES
941    CONTROL         "Non-Wor&king",IDC_FILTER_NONWORKING,"Button",
942                    BS_AUTOCHECKBOX | WS_TABSTOP,14,44,61,10,0,
943                    HIDC_FILTER_NONWORKING
944    CONTROL         "&Unavailable",IDC_FILTER_UNAVAILABLE,"Button",
945                    BS_AUTOCHECKBOX | WS_TABSTOP,14,58,57,10,0,
946                    HIDC_FILTER_UNAVAILABLE
947#ifdef MESS
948    CONTROL         "&Computers",IDC_FILTER_COMPUTER,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,14,72,57,10,0,HIDC_FILTER_UNAVAILABLE
949    CONTROL         "C&onsoles",IDC_FILTER_CONSOLE,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,100,58,57,10,0,HIDC_FILTER_UNAVAILABLE
950#endif
951    CONTROL         "&Raster Graphics",IDC_FILTER_RASTER,"Button",
952                    BS_AUTOCHECKBOX | WS_TABSTOP,100,16,70,10,0,
953                    HIDC_FILTER_RASTER
954    CONTROL         "Ori&ginals",IDC_FILTER_ORIGINALS,"Button",
955                    BS_AUTOCHECKBOX | WS_TABSTOP,100,30,47,10,0,
956                    HIDC_FILTER_ORIGINALS
957    CONTROL         "&Working",IDC_FILTER_WORKING,"Button",BS_AUTOCHECKBOX |
958                    WS_TABSTOP,100,44,47,10,0,HIDC_FILTER_WORKING
959    LTEXT           "(*) = inherited from parent folder",IDC_INHERITED,14,72,
960                    99,10
961#ifdef MESS
962    CTEXT           "System filters allow customizing the systems that are displayed in each folder by hiding games that match the filters applied.",IDC_STATIC,6,94,178,27
963#else
964    CTEXT           "Game filters allow customizing the games that are displayed in each folder by hiding games that match the filters applied.",
965                    IDC_STATIC,6,94,178,27
966#endif
967    GROUPBOX        "&Description filter",IDC_STATIC,6,122,178,33
968    EDITTEXT        IDC_FILTER_EDIT,14,134,162,13,ES_AUTOHSCROLL,0,
969                    HIDC_FILTER_EDIT
970    DEFPUSHBUTTON   "&OK",IDOK,42,161,50,14
971    PUSHBUTTON      "&Cancel",IDCANCEL,98,161,50,14
972END
973
974IDD_RESET DIALOGEX 0, 0, 190, 122
975STYLE DS_MODALFRAME | DS_3DLOOK | WS_POPUP | WS_CAPTION | WS_SYSMENU
976EXSTYLE WS_EX_CONTEXTHELP
977CAPTION "Reset Options"
978FONT 8, "MS Shell Dlg", 0, 0, 0x1
979BEGIN
980    GROUPBOX        "Categories",IDC_STATIC,6,4,178,70
981    CONTROL         "&User Interface (Fonts, Colors, Sizes)",IDC_RESET_UI,
982                    "Button",BS_AUTOCHECKBOX | WS_TABSTOP,14,16,146,10,0,
983                    HIDC_RESET_UI
984#ifdef MESS
985    CONTROL         "&Default system options",IDC_RESET_DEFAULT,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,14,30,146,10,0,HIDC_RESET_DEFAULT
986    CONTROL         "&All systems to use default options",IDC_RESET_GAMES,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,14,44,146,10,0,HIDC_RESET_GAMES
987#else
988    CONTROL         "&Default game options",IDC_RESET_DEFAULT,"Button",
989                    BS_AUTOCHECKBOX | WS_TABSTOP,14,30,146,10,0,
990                    HIDC_RESET_DEFAULT
991    CONTROL         "&All games to use default options",IDC_RESET_GAMES,
992                    "Button",BS_AUTOCHECKBOX | WS_TABSTOP,14,44,146,10,0,
993                    HIDC_RESET_GAMES
994#endif
995    CONTROL         "&Folder 'filters'",IDC_RESET_FILTERS,"Button",
996                    BS_AUTOCHECKBOX | WS_TABSTOP,14,58,146,10,0,
997                    HIDC_RESET_FILTERS
998    CTEXT           "Select the options to be restored to the default settings.\nThe options will be restored when MAME32 is run next.",
999                    IDC_STATIC,6,79,178,20
1000    DEFPUSHBUTTON   "&OK",IDOK,42,101,50,14
1001    PUSHBUTTON      "&Cancel",IDCANCEL,98,101,50,14
1002END
1003
1004IDD_LOAD_PROGRESS DIALOGEX 0, 0, 260, 187
1005STYLE DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU
1006EXSTYLE WS_EX_CONTROLPARENT
1007FONT 8, "MS Shell Dlg", 0, 0, 0x1
1008BEGIN
1009    CONTROL         "Progress1",IDC_LOAD_PROGRESS,"msctls_progress32",
1010                    PBS_SMOOTH | WS_BORDER,6,7,248,12
1011    CTEXT           "",IDC_LOAD_ROMNAME,6,21,248,10,SS_CENTERIMAGE | NOT
1012                    WS_GROUP
1013    EDITTEXT        IDC_LOAD_STATUS,6,32,248,116,ES_MULTILINE | ES_READONLY |
1014                    WS_VSCROLL
1015    CTEXT           "",IDC_ERROR_TEXT,6,150,248,13,SS_NOPREFIX |
1016                    SS_CENTERIMAGE
1017    PUSHBUTTON      "&OK",IDOK,77,166,50,14,WS_DISABLED
1018    PUSHBUTTON      "&Cancel",IDCANCEL,133,166,50,14
1019END
1020
1021IDD_INTERFACE_OPTIONS DIALOGEX 0, 0, 378, 225
1022STYLE DS_MODALFRAME | DS_3DLOOK | WS_POPUP | WS_CAPTION | WS_SYSMENU
1023EXSTYLE WS_EX_CONTEXTHELP
1024CAPTION "Interface Options"
1025FONT 8, "MS Shell Dlg", 0, 0, 0x1
1026BEGIN
1027#ifdef MESS
1028    GROUPBOX        "System Selection",IDC_STATIC,6,4,189,194
1029    CONTROL         "&Search for new systems on start",IDC_START_GAME_CHECK,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,14,16,112,10,0,HIDC_START_GAME_CHECK
1030    CONTROL         "Allow system selection by a &joystick (requires restart)",IDC_JOY_GUI,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,14,30,178,10,0,HIDC_JOY_GUI
1031    CONTROL         "Allow system selection by custom &key sequences",IDC_KEY_GUI,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,14,44,166,10
1032#else
1033    GROUPBOX        "Game Selection",IDC_STATIC,6,4,189,194
1034    CONTROL         "&Search for new games on start",IDC_START_GAME_CHECK,
1035                    "Button",BS_AUTOCHECKBOX | WS_TABSTOP,14,16,111,10,0,
1036                    HIDC_START_GAME_CHECK
1037    CONTROL         "Allow game selection by a &joystick (requires restart)",
1038                    IDC_JOY_GUI,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,14,30,
1039                    174,10,0,HIDC_JOY_GUI
1040    CONTROL         "Allow game selection by custom &key sequences",
1041                    IDC_KEY_GUI,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,14,44,
1042                    166,10
1043#endif
1044    CONTROL         "Select &random background image",IDC_RANDOM_BG,"Button",
1045                    BS_AUTOCHECKBOX | WS_TABSTOP,14,58,122,10,0,
1046                    HIDC_RANDOM_BG
1047    CONTROL         "&Broadcast selected game to all windows",IDC_BROADCAST,
1048                    "Button",BS_AUTOCHECKBOX | WS_TABSTOP,14,72,141,10,0,
1049                    HIDC_BROADCAST
1050    CONTROL         "Hide &mouse cursor (requires restart)",IDC_HIDE_MOUSE,
1051                    "Button",BS_AUTOCHECKBOX | WS_TABSTOP,14,86,126,10,0,
1052                    HIDC_HIDE_MOUSE
1053    CONTROL         "Inheritable Filters",IDC_FILTER_INHERIT,"Button",
1054                    BS_AUTOCHECKBOX | WS_TABSTOP,14,100,68,10
1055    CONTROL         "No offset for clones missing parent in view",
1056                    IDC_NOOFFSET_CLONES,"Button",BS_AUTOCHECKBOX |
1057                    WS_TABSTOP,14,114,148,10
1058    GROUPBOX        "Show History on Tab",IDC_STATIC,14,128,173,28
1059    COMBOBOX        IDC_HISTORY_TAB,57,138,88,50,CBS_DROPDOWNLIST |
1060                    WS_VSCROLL | WS_TABSTOP
1061    GROUPBOX        "Emulation",IDC_STATIC,202,4,170,28
1062#ifdef MESS
1063    CONTROL         "Show System Ca&ption",IDC_GAME_CAPTION,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,210,16,81,10
1064#else
1065    CONTROL         "Show Game Ca&ption",IDC_GAME_CAPTION,"Button",
1066                    BS_AUTOCHECKBOX | WS_TABSTOP,210,16,80,10,0,
1067                    HIDC_GAME_CAPTION
1068#endif
1069    GROUPBOX        "Bookkeeping",IDC_STATIC,202,36,170,43
1070    CONTROL         "Reset all Playcounts",IDC_RESET_PLAYCOUNT,"Button",
1071                    BS_AUTOCHECKBOX | WS_TABSTOP,210,48,80,10
1072    CONTROL         "Reset all Play Times",IDC_RESET_PLAYTIME,"Button",
1073                    BS_AUTOCHECKBOX | WS_TABSTOP,210,62,79,10
1074    GROUPBOX        "Screenshot Area",IDC_STATIC,202,83,170,115
1075    CONTROL         "S&tretch screenshot larger than natural size",
1076                    IDC_STRETCH_SCREENSHOT_LARGER,"Button",BS_AUTOCHECKBOX |
1077                    WS_TABSTOP,210,95,148,10,0,
1078                    HIDC_STRETCH_SCREENSHOT_LARGER
1079    GROUPBOX        "Screenshot Cycletime in Seconds",IDC_STATIC,210,109,154,
1080                    28
1081    CONTROL         "Slider1",IDC_CYCLETIMESEC,"msctls_trackbar32",TBS_BOTH |
1082                    TBS_NOTICKS | WS_TABSTOP,218,121,120,10,0,
1083                    HIDC_CYCLETIMESEC
1084    RTEXT           "60",IDC_CYCLETIMESECTXT,340,120,13,10,SS_CENTERIMAGE
1085    GROUPBOX        "Screenshot Bordersize",IDC_STATIC,210,141,154,28
1086    CONTROL         "Slider1",IDC_SCREENSHOT_BORDERSIZE,"msctls_trackbar32",
1087                    TBS_BOTH | TBS_NOTICKS | WS_TABSTOP,218,153,120,10
1088    RTEXT           "100",IDC_SCREENSHOT_BORDERSIZETXT,340,152,13,10,
1089                    SS_CENTERIMAGE
1090    PUSHBUTTON      "Set Screenshot Border Color",IDC_SCREENSHOT_BORDERCOLOR,
1091                    210,176,154,14
1092    DEFPUSHBUTTON   "&OK",IDOK,136,204,50,14
1093    PUSHBUTTON      "&Cancel",IDCANCEL,192,204,50,14
1094END
1095
1096IDD_LANGUAGE DIALOGEX 0, 0, 190, 66
1097STYLE DS_MODALFRAME | DS_CONTEXTHELP | WS_POPUP | WS_CAPTION | WS_SYSMENU
1098EXSTYLE WS_EX_CONTEXTHELP
1099CAPTION "Language"
1100FONT 8, "MS Shell Dlg", 0, 0, 0x1
1101BEGIN
1102    GROUPBOX        "",IDC_STATIC,6,4,178,34
1103    CONTROL         "Use language file",IDC_LANGUAGECHECK,"Button",
1104                    BS_AUTOCHECKBOX | WS_TABSTOP,12,4,66,10,0,
1105                    HIDC_LANGUAGECHECK
1106    EDITTEXT        IDC_LANGUAGEEDIT,14,17,142,13,ES_AUTOHSCROLL,0,
1107                    HIDC_LANGUAGEEDIT
1108    PUSHBUTTON      "...",IDC_LANGUAGEBROWSE,162,17,14,13
1109    DEFPUSHBUTTON   "OK",IDOK,42,45,50,14
1110    PUSHBUTTON      "Cancel",IDCANCEL,98,45,50,14
1111END
1112
1113IDD_CUSTOM_FILE DIALOG DISCARDABLE  0, 0, 190, 135
1114STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU
1115CAPTION "Add Game To Custom Folder"
1116FONT 8, "MS Shell Dlg"
1117BEGIN
1118    LTEXT           "",IDC_CUSTOMFILE_GAME,6,6,175,10,SS_NOPREFIX |
1119                    SS_CENTERIMAGE
1120    CONTROL         "CustomTree",IDC_CUSTOM_TREE,"SysTreeView32",
1121                    TVS_HASBUTTONS | TVS_HASLINES | TVS_LINESATROOT |
1122                    TVS_DISABLEDRAGDROP | TVS_SHOWSELALWAYS |
1123                    TVS_FULLROWSELECT | WS_BORDER | WS_TABSTOP,6,18,178,90
1124    DEFPUSHBUTTON   "OK",IDOK,42,114,50,14
1125    PUSHBUTTON      "Cancel",IDCANCEL,98,114,50,14
1126END
1127
1128IDD_PROP_CONTROLLER DIALOGEX 0, 0, 220, 240
1129STYLE WS_CHILD | WS_DISABLED | WS_CAPTION
1130CAPTION "Controller Mapping"
1131FONT 8, "MS Shell Dlg", 0, 0, 0x1
1132BEGIN
1133    ICON            IDI_JOYSTICK,IDC_STATIC,20,10,20,20
1134    LTEXT           "Title\nDirectory\nExtra",IDC_PROP_TITLE,52,9,161,25,
1135                    SS_NOPREFIX
1136    GROUPBOX        "Paddle device",IDC_STATIC,4,40,103,28
1137    COMBOBOX        IDC_PADDLE,10,50,91,62,CBS_DROPDOWNLIST | WS_VSCROLL |
1138                    WS_TABSTOP,0,HIDC_PADDLE
1139    GROUPBOX        "ADStick device",IDC_STATIC,4,71,103,28
1140    COMBOBOX        IDC_ADSTICK,10,80,91,62,CBS_DROPDOWNLIST | WS_VSCROLL |
1141                    WS_TABSTOP,0,HIDC_ADSTICK
1142    GROUPBOX        "Pedal device",IDC_STATIC,4,102,103,28
1143    COMBOBOX        IDC_PEDAL,10,112,91,62,CBS_DROPDOWNLIST | WS_VSCROLL |
1144                    WS_TABSTOP,0,HIDC_PEDAL
1145    GROUPBOX        "Dial device",IDC_STATIC,113,40,102,28
1146    COMBOBOX        IDC_DIAL,119,50,90,62,CBS_DROPDOWNLIST | WS_VSCROLL |
1147                    WS_TABSTOP,0,HIDC_DIAL
1148    GROUPBOX        "Trackball device",IDC_STATIC,113,71,102,28
1149    COMBOBOX        IDC_TRACKBALL,119,80,90,62,CBS_DROPDOWNLIST | WS_VSCROLL |
1150                    WS_TABSTOP,0,HIDC_TRACKBALL
1151    GROUPBOX        "Lightgun device",IDC_STATIC,113,102,102,28
1152    COMBOBOX        IDC_LIGHTGUNDEVICE,119,112,90,62,CBS_DROPDOWNLIST |
1153                    WS_VSCROLL | WS_TABSTOP,0,HIDC_LIGHTGUNDEVICE
1154    PUSHBUTTON      "Reset",IDC_PROP_RESET,4,222,97,14,0,0,HIDC_PROP_RESET
1155    PUSHBUTTON      "Restore Default Settings",IDC_USE_DEFAULT,118,222,97,14,
1156                    0,0,HIDC_USE_DEFAULT
1157END
1158
1159IDD_PROP_SCREEN DIALOGEX 0, 0, 220, 240
1160STYLE WS_CHILD | WS_CAPTION
1161CAPTION "Screen"
1162FONT 8, "MS Shell Dlg", 0, 0, 0x1
1163BEGIN
1164    ICON            IDI_DISPLAY,IDC_STATIC,20,10,21,20
1165    LTEXT           "Title\nDirectory\nExtra",IDC_PROP_TITLE,52,9,161,25,
1166                    SS_NOPREFIX
1167    GROUPBOX        "Number of screens",IDC_STATIC,4,40,103,24
1168    CONTROL         "GammaSlider",IDC_NUMSCREENS,"msctls_trackbar32",
1169                    TBS_BOTH | TBS_NOTICKS | WS_TABSTOP,10,50,75,10,0,
1170                    HIDC_NUMSCREENS
1171    RTEXT           "1",IDC_NUMSCREENSDISP,84,49,14,10,SS_CENTERIMAGE | NOT
1172                    WS_GROUP
1173    GROUPBOX        "Screen",IDC_STATIC,4,66,103,29
1174    COMBOBOX        IDC_SCREEN,10,76,91,64,CBS_DROPDOWNLIST | WS_VSCROLL |
1175                    WS_TABSTOP,0,HIDC_SCREEN
1176    GROUPBOX        "",IDC_STATIC,4,97,103,28
1177    CONTROL         "Autoselect aspect",IDC_ASPECT,"Button",BS_AUTOCHECKBOX |
1178                    WS_TABSTOP,10,97,73,10,0,HIDC_ASPECT
1179    LTEXT           "Aspect ratio",IDC_ASPECTRATIOTEXT,17,108,40,11,
1180                    SS_CENTERIMAGE | NOT WS_GROUP
1181    EDITTEXT        IDC_ASPECTRATION,60,108,14,12,ES_RIGHT | ES_AUTOHSCROLL |
1182                    ES_NUMBER,0,HIDC_ASPECTRATION
1183    LTEXT           ":",IDC_STATIC,76,108,8,10,SS_CENTERIMAGE | NOT WS_GROUP
1184    EDITTEXT        IDC_ASPECTRATIOD,80,108,14,12,ES_RIGHT | ES_AUTOHSCROLL |
1185                    ES_NUMBER,0,HIDC_ASPECTRATIOD
1186    GROUPBOX        "View",IDC_STATIC,4,128,103,28
1187    COMBOBOX        IDC_VIEW,10,137,91,64,CBS_DROPDOWNLIST | WS_VSCROLL |
1188                    WS_TABSTOP,0,HIDC_VIEW
1189    GROUPBOX        "Screennumber",IDC_SCREENSELECTTEXT,113,40,102,28
1190    COMBOBOX        IDC_SCREENSELECT,119,50,90,64,CBS_DROPDOWNLIST |
1191                    WS_VSCROLL | WS_TABSTOP,0,HIDC_SCREENSELECT
1192    GROUPBOX        "Resolution",IDC_STATIC,113,71,102,76,WS_GROUP
1193    GROUPBOX        "Size",IDC_STATIC,119,81,90,28,WS_GROUP
1194    COMBOBOX        IDC_SIZES,126,91,77,70,CBS_DROPDOWNLIST | WS_VSCROLL |
1195                    WS_TABSTOP,0,HIDC_SIZES
1196    GROUPBOX        "Refresh",IDC_REFRESHTEXT,119,112,90,28,WS_GROUP
1197    COMBOBOX        IDC_REFRESH,126,121,77,76,CBS_DROPDOWNLIST | WS_VSCROLL |
1198                    WS_TABSTOP,0,HIDC_REFRESH
1199    CONTROL         "Switch resolutions to fit",IDC_SWITCHRES,"Button",
1200                    BS_AUTOCHECKBOX | WS_TABSTOP,119,151,93,10,0,
1201                    HIDC_SWITCHRES
1202    PUSHBUTTON      "Reset",IDC_PROP_RESET,4,222,97,14,0,0,HIDC_PROP_RESET
1203    PUSHBUTTON      "Restore Default Settings",IDC_USE_DEFAULT,118,222,97,14,
1204                    0,0,HIDC_USE_DEFAULT
1205END
1206
1207
1208/////////////////////////////////////////////////////////////////////////////
1209//
1210// Accelerator
1211//
1212
1213IDA_TAB_KEYS ACCELERATORS MOVEABLE PURE
1214BEGIN
1215    "1",            ID_VIEW_TAB_SCREENSHOT, VIRTKEY, ALT, NOINVERT
1216    "2",            ID_VIEW_TAB_FLYER,      VIRTKEY, ALT, NOINVERT
1217    "3",            ID_VIEW_TAB_CABINET,    VIRTKEY, ALT, NOINVERT
1218    "4",            ID_VIEW_TAB_MARQUEE,    VIRTKEY, ALT, NOINVERT
1219    "5",            ID_VIEW_TAB_TITLE,      VIRTKEY, ALT, NOINVERT
1220    "6",            ID_VIEW_TAB_CONTROL_PANEL, VIRTKEY, ALT, NOINVERT
1221    "7",            ID_VIEW_TAB_HISTORY,    VIRTKEY, ALT, NOINVERT
1222    "A",            ID_GAME_AUDIT,          VIRTKEY, ALT, NOINVERT
1223    "B",            ID_VIEW_PAGETAB,        VIRTKEY, ALT, NOINVERT
1224    "D",            ID_VIEW_FOLDERS,        VIRTKEY, ALT, NOINVERT
1225    "F",            ID_CONTEXT_FILTERS,     VIRTKEY, CONTROL, NOINVERT
1226    "U",            ID_FOLDER_AUDIT,        VIRTKEY, ALT, NOINVERT
1227    "P",            ID_VIEW_PICTURE_AREA,   VIRTKEY, ALT, NOINVERT
1228    "R",            ID_CONTEXT_SELECT_RANDOM, VIRTKEY, CONTROL, NOINVERT
1229    "S",            ID_VIEW_STATUS,         VIRTKEY, ALT, NOINVERT
1230    "T",            ID_VIEW_TOOLBARS,       VIRTKEY, ALT, NOINVERT
1231    VK_F1,          ID_HELP_CONTENTS,       VIRTKEY, NOINVERT
1232    VK_F11,         ID_VIEW_FULLSCREEN,     VIRTKEY, NOINVERT
1233    VK_F5,          ID_UPDATE_GAMELIST,     VIRTKEY, NOINVERT
1234    VK_NEXT,        ID_UI_HISTORY_DOWN,     VIRTKEY, CONTROL, NOINVERT
1235    VK_PRIOR,       ID_UI_HISTORY_UP,       VIRTKEY, CONTROL, NOINVERT
1236    VK_RETURN,      ID_GAME_PROPERTIES,     VIRTKEY, ALT, NOINVERT
1237END
1238
1239
1240/////////////////////////////////////////////////////////////////////////////
1241//
1242// DESIGNINFO
1243//
1244
1245#ifdef APSTUDIO_INVOKED
1246GUIDELINES DESIGNINFO MOVEABLE PURE
1247BEGIN
1248    IDD_ABOUT, DIALOG
1249    BEGIN
1250        LEFTMARGIN, 7
1251        RIGHTMARGIN, 289
1252        TOPMARGIN, 7
1253        BOTTOMMARGIN, 123
1254    END
1255
1256    IDD_DIRECTX, DIALOG
1257    BEGIN
1258        LEFTMARGIN, 7
1259        RIGHTMARGIN, 229
1260        TOPMARGIN, 7
1261        BOTTOMMARGIN, 62
1262    END
1263
1264    IDD_AUDIT, DIALOG
1265    BEGIN
1266        LEFTMARGIN, 7
1267        RIGHTMARGIN, 280
1268        TOPMARGIN, 7
1269        BOTTOMMARGIN, 187
1270        HORZGUIDE, 19
1271    END
1272
1273    IDD_DIRECTORIES, DIALOG
1274    BEGIN
1275        LEFTMARGIN, 7
1276        RIGHTMARGIN, 224
1277        TOPMARGIN, 7
1278        BOTTOMMARGIN, 98
1279    END
1280
1281    IDD_COLUMNS, DIALOG
1282    BEGIN
1283        LEFTMARGIN, 7
1284        RIGHTMARGIN, 301
1285        TOPMARGIN, 7
1286        BOTTOMMARGIN, 143
1287    END
1288
1289    IDD_PROP_GAME, DIALOG
1290    BEGIN
1291        LEFTMARGIN, 7
1292        RIGHTMARGIN, 213
1293        VERTGUIDE, 19
1294        VERTGUIDE, 66
1295        VERTGUIDE, 74
1296        VERTGUIDE, 201
1297        BOTTOMMARGIN, 232
1298    END
1299
1300    IDD_PROP_AUDIT, DIALOG
1301    BEGIN
1302        LEFTMARGIN, 7
1303        RIGHTMARGIN, 213
1304        VERTGUIDE, 12
1305        VERTGUIDE, 208
1306        BOTTOMMARGIN, 198
1307        HORZGUIDE, 38
1308    END
1309
1310    IDD_PROP_DISPLAY, DIALOG
1311    BEGIN
1312        LEFTMARGIN, 4
1313        RIGHTMARGIN, 223
1314        VERTGUIDE, 7
1315        VERTGUIDE, 123
1316        BOTTOMMARGIN, 257
1317        HORZGUIDE, 179
1318    END
1319
1320    IDD_PROP_SOUND, DIALOG
1321    BEGIN
1322        LEFTMARGIN, 7
1323        RIGHTMARGIN, 213
1324        VERTGUIDE, 50
1325        BOTTOMMARGIN, 198
1326    END
1327
1328    IDD_PROP_ADVANCED, DIALOG
1329    BEGIN
1330        LEFTMARGIN, 7
1331        RIGHTMARGIN, 230
1332        BOTTOMMARGIN, 211
1333    END
1334
1335    IDD_PROP_INPUT, DIALOG
1336    BEGIN
1337        LEFTMARGIN, 4
1338        RIGHTMARGIN, 215
1339        VERTGUIDE, 50
1340        VERTGUIDE, 170
1341        BOTTOMMARGIN, 257
1342    END
1343
1344    IDD_PROP_MISC, DIALOG
1345    BEGIN
1346        LEFTMARGIN, 7
1347        RIGHTMARGIN, 213
1348        VERTGUIDE, 25
1349        VERTGUIDE, 40
1350        VERTGUIDE, 104
1351        VERTGUIDE, 114
1352        VERTGUIDE, 204
1353        BOTTOMMARGIN, 183
1354    END
1355
1356    IDD_PROP_VECTOR, DIALOG
1357    BEGIN
1358        LEFTMARGIN, 7
1359        RIGHTMARGIN, 213
1360        VERTGUIDE, 50
1361        BOTTOMMARGIN, 198
1362    END
1363
1364    IDD_FILTERS, DIALOG
1365    BEGIN
1366        LEFTMARGIN, 7
1367        TOPMARGIN, 7
1368        BOTTOMMARGIN, 178
1369    END
1370
1371    IDD_RESET, DIALOG
1372    BEGIN
1373        LEFTMARGIN, 7
1374        RIGHTMARGIN, 175
1375        VERTGUIDE, 18
1376        VERTGUIDE, 164
1377        TOPMARGIN, 7
1378    END
1379
1380    IDD_LANGUAGE, DIALOG
1381    BEGIN
1382        LEFTMARGIN, 7
1383        RIGHTMARGIN, 179
1384        TOPMARGIN, 7
1385        BOTTOMMARGIN, 59
1386    END
1387
1388    IDD_PROP_CONTROLLER, DIALOG
1389    BEGIN
1390        RIGHTMARGIN, 210
1391        BOTTOMMARGIN, 154
1392    END
1393
1394    IDD_PROP_SCREEN, DIALOG
1395    BEGIN
1396        LEFTMARGIN, 4
1397        RIGHTMARGIN, 223
1398        VERTGUIDE, 7
1399        VERTGUIDE, 123
1400        BOTTOMMARGIN, 199
1401        HORZGUIDE, 179
1402    END
1403END
1404#endif    // APSTUDIO_INVOKED
1405
1406
1407/////////////////////////////////////////////////////////////////////////////
1408//
1409// Bitmap
1410//
1411
1412#ifdef MESS
1413IDB_ABOUT               BITMAP  DISCARDABLE     "res\\about_mess.bmp"
1414#else
1415IDB_ABOUT               BITMAP  MOVEABLE PURE   "res\\about.bmp"
1416#endif
1417IDB_TOOLBAR             BITMAP  MOVEABLE PURE   "res\\toolbar.bmp"
1418
1419/////////////////////////////////////////////////////////////////////////////
1420//
1421// Cursor
1422//
1423
1424IDC_CURSOR_HSPLIT       CURSOR  DISCARDABLE     "Res\\Splith.cur"
1425
1426/////////////////////////////////////////////////////////////////////////////
1427//
1428// 24
1429//
1430
14311                       24      MOVEABLE PURE   "res\\mame32.manifest"
1432
1433/////////////////////////////////////////////////////////////////////////////
1434//
1435// String Table
1436//
1437
1438STRINGTABLE DISCARDABLE
1439BEGIN
1440    IDS_UI_FILE             "Contains commands for working with the selected items"
1441    IDS_UI_VIEW             "Contains commands for manupulating the view"
1442    IDS_UI_OPTIONS          "Contains commands for user interface options"
1443    IDS_UI_HELP             "Contains commands for displaying help"
1444END
1445
1446STRINGTABLE DISCARDABLE
1447BEGIN
1448    IDS_UI_TOOLBAR          "Show or hide the toolbar"
1449    IDS_UI_STATUSBAR        "Show or hide the status bar"
1450    IDS_UI_FOLDERLIST       "Show or hide the folder list"
1451    IDS_UI_SCREENSHOT       "Show or hide the screen shot"
1452    IDS_UI_SPACER1          "Spacer"
1453    IDS_UI_LARGEICONS       "Display items by using large icons."
1454    IDS_UI_SMALLICONS       "Display items by using small icons."
1455    IDS_UI_LIST             "Displays items in a list."
1456    IDS_UI_DETAILS          "Displays detailed information about each item in the window."
1457    IDS_UI_SPACER2          "Spacer"
1458    IDS_UI_ARRANGE          "Contains commands for sorting by various columns"
1459    IDS_UI_LINEUPICONS      "Arranges icons in a grid"
1460#ifdef MESS
1461    IDS_UI_REFRESH          "Refresh system list"
1462    IDS_UI_CUSTOMIZE        "Customize which columns are used in the system list"
1463#else
1464    IDS_UI_REFRESH          "Refresh game list"
1465    IDS_UI_CUSTOMIZE        "Customize which columns are used in the game list"
1466#endif
1467END
1468
1469STRINGTABLE DISCARDABLE
1470BEGIN
1471    ID_FILE_EXIT            "Exit the application"
1472#ifdef MESS
1473    ID_FILE_PLAY            "Play currently selected system"
1474#else
1475    ID_FILE_PLAY            "Play currently selected game"
1476#endif
1477    ID_HELP_ABOUT           "Displays program and copyright information"
1478    ID_VIEW_LARGE_ICON      "Display items by using large icons."
1479    ID_VIEW_SMALL_ICON      "Display items by using small icons."
1480    ID_VIEW_LIST_MENU       "Displays items in a list."
1481    ID_VIEW_DETAIL          "Displays detailed information about each item in the window."
1482#ifdef MESS
1483    ID_OPTIONS_FONT         "Set system list and folder list font"
1484    ID_OPTIONS_DIR          "Set directory configuration"
1485    ID_OPTIONS_DEFAULTS     "Set default system options"
1486#else
1487    ID_OPTIONS_FONT         "Set game list and folder list font"
1488    ID_OPTIONS_DIR          "Set directory configuration"
1489    ID_OPTIONS_DEFAULTS     "Set default game options"
1490#endif
1491END
1492
1493STRINGTABLE DISCARDABLE
1494BEGIN
1495#ifdef MESS
1496    ID_FILE_LOADSTATE       "Run a system starting with the given savestate"
1497#else
1498    ID_FILE_LOADSTATE       "Play a game starting with the given savestate"
1499#endif
1500END
1501
1502STRINGTABLE DISCARDABLE
1503BEGIN
1504    ID_OPTIONS_RESET_DEFAULTS "Allow restoring options to 'sane' values."
1505    ID_OPTIONS_INTERFACE    "Customize interface options."
1506    ID_FILE_AUDIT           "Audit ROM and samples sets"
1507#ifdef MESS
1508    ID_FILE_PLAY_RECORD     "Record a system for later playback"
1509    ID_FILE_PLAY_BACK       "Playback a recorded system"
1510    ID_FILE_PLAY_RECORD_WAVE "Record the sound output of a system"
1511#else
1512    ID_FILE_PLAY_RECORD     "Record a game for later playback"
1513    ID_FILE_PLAY_BACK       "Playback a recorded game"
1514    ID_FILE_PLAY_RECORD_MNG "Record the video output of a game"
1515#endif
1516    ID_VIEW_PICTURE_AREA    "Show or hide the picture area"
1517    ID_HELP_CONTENTS        "Display help contents"
1518#ifdef MESS
1519    ID_HELP_WHATS_NEW32     "Recent changes"
1520    ID_HELP_TROUBLE         "Troubleshooting Documentation"
1521    ID_HELP_RELEASE         "MESS release notes"
1522    ID_HELP_WHATS_NEW       "What's new in MESS"
1523    ID_HELP_CHEATS          "How cheats work"
1524#else
1525    ID_HELP_WHATS_NEW32     "New game changes"
1526    ID_HELP_TROUBLE         "Troubleshooting Documentation"
1527    ID_HELP_RELEASE         "MAME release notes"
1528    ID_HELP_WHATS_NEW       "What's new in MAME"
1529    ID_HELP_CHEATS          "How cheats work"
1530#endif
1531END
1532
1533STRINGTABLE DISCARDABLE
1534BEGIN
1535#ifdef MESS
1536    ID_CUSTOMIZE_FIELDS     "Customize which columns are used in the system list"
1537#else
1538    ID_CUSTOMIZE_FIELDS     "Customize which columns are used in the game list"
1539#endif
1540    ID_GAME_PROPERTIES      "Display the properties of the selected items"
1541    ID_VIEW_FOLDERS         "Show or hide the folder list"
1542    ID_VIEW_TOOLBARS        "Show or hide the toolbar"
1543    ID_VIEW_STATUS          "Show or hide the status bar"
1544#ifdef MESS
1545    ID_CONTEXT_FILTERS      "Allows filtering out systems from a folder"
1546    ID_CONTEXT_SELECT_RANDOM "Randomly select a system."
1547#else
1548    ID_CONTEXT_FILTERS      "Allows filtering out games from a folder"
1549    ID_CONTEXT_SELECT_RANDOM "Randomly select a game."
1550#endif
1551END
1552
1553STRINGTABLE DISCARDABLE
1554BEGIN
1555#ifdef MESS
1556    ID_VIEW_BYGAME          "Sort items by system"
1557#else
1558    ID_VIEW_BYGAME          "Sort items by game"
1559#endif
1560    ID_VIEW_BYDIRECTORY     "Sort items by directories"
1561    ID_VIEW_BYMANUFACTURER  "Sort items by manufacturer"
1562    ID_VIEW_BYYEAR          "Sort items by year"
1563    ID_VIEW_BYTYPE          "Sort items by type"
1564    ID_VIEW_BYTIMESPLAYED   "Sort by number of plays"
1565    ID_VIEW_LINEUPICONS     "Arranges icons in a grid"
1566#ifdef MESS
1567    ID_UPDATE_GAMELIST      "Refresh system list"
1568#else
1569    ID_UPDATE_GAMELIST      "Refresh game list"
1570#endif
1571    ID_SORT_ASCENDING       "Sort column in ascending (A-Z) order"
1572    ID_SORT_DESCENDING      "Sort column in descending (Z-A) order"
1573END
1574
1575#endif    // Englisch (USA) resources
1576/////////////////////////////////////////////////////////////////////////////
1577
1578
1579
1580#ifndef APSTUDIO_INVOKED
1581/////////////////////////////////////////////////////////////////////////////
1582//
1583// Generated from the TEXTINCLUDE 3 resource.
1584//
1585
1586
1587/////////////////////////////////////////////////////////////////////////////
1588#endif    // not APSTUDIO_INVOKED
1589
src/osd/windows/ui/tabview.h
r995r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11 ***************************************************************************/
12
13#ifndef TABVIEW_H
14#define TABVIEW_H
15
16struct TabViewCallbacks
17{
18   // Options retrieval
19   BOOL (*pfnGetShowTabCtrl)(void);
20   void (*pfnSetCurrentTab)(LPCSTR pszShortName);
21   LPCSTR (*pfnGetCurrentTab)(void);
22   void (*pfnSetShowTab)(int nTab, BOOL show);
23   int (*pfnGetShowTab)(int nTab);
24
25   // Accessors
26   LPCSTR (*pfnGetTabShortName)(int nTab);
27   LPCSTR (*pfnGetTabLongName)(int nTab);
28
29   // Callbacks
30   void (*pfnOnSelectionChanged)(void);
31   void (*pfnOnMoveSize)(void);
32};
33
34struct TabViewOptions
35{
36   const struct TabViewCallbacks *pCallbacks;
37   int nTabCount;
38};
39
40
41BOOL SetupTabView(HWND hwndTabView, const struct TabViewOptions *pOptions);
42
43void TabView_Reset(HWND hwndTabView);
44void TabView_CalculateNextTab(HWND hwndTabView);
45int TabView_GetCurrentTab(HWND hwndTabView);
46void TabView_SetCurrentTab(HWND hwndTabView, int nTab);
47void TabView_UpdateSelection(HWND hwndTabView);
48
49// These are used to handle events received by the parent regarding
50// tabview controls
51BOOL TabView_HandleNotify(LPNMHDR lpNmHdr);
52
53#endif // TABVIEW_H
src/osd/windows/ui/datamap.c
r995r996
1//============================================================
2//
3//  datamap.c - Win32 dialog and options bridge code
4//
5//============================================================
6
7// standard windows headers
8#define WIN32_LEAN_AND_MEAN
9#include <windows.h>
10#include <windowsx.h>
11#include <commctrl.h>
12#include <tchar.h>
13
14// standard C headers
15#include <stdarg.h>
16#include <ctype.h>
17#include <assert.h>
18#include <math.h>
19
20// MAME/MAME32 headers
21#include "corestr.h"
22#include "strconv.h"
23#include "datamap.h"
24#include "winutf8.h"
25#include "emuopts.h"
26
27
28
29//============================================================
30//  TYPE DEFINITIONS
31//============================================================
32
33typedef enum _control_type control_type;
34enum _control_type
35{
36   CT_UNKNOWN,
37   CT_BUTTON,
38   CT_STATIC,
39   CT_EDIT,
40   CT_COMBOBOX,
41   CT_TRACKBAR,
42   CT_LISTVIEW
43};
44
45
46
47typedef struct _datamap_entry datamap_entry;
48struct _datamap_entry
49{
50   // the basics about the entry
51   int dlgitem;
52   datamap_entry_type type;
53   const char *option_name;
54
55   // callbacks
56   datamap_callback callbacks[DCT_COUNT];
57   get_option_name_callback get_option_name;
58
59   // formats
60   const char *int_format;
61   const char *float_format;
62
63   // trackbar options
64   BOOL use_trackbar_options;
65   float trackbar_min;
66   float trackbar_max;
67   float trackbar_increments;
68};
69
70
71struct _datamap
72{
73   int entry_count;
74   datamap_entry entries[256];
75};
76
77typedef void (*datamap_default_callback)(datamap *map, HWND control, core_options *opts, datamap_entry *entry, const char *option_name);
78
79
80
81//============================================================
82//  PROTOTYPES
83//============================================================
84
85static datamap_entry *find_entry(datamap *map, int dlgitem);
86static control_type get_control_type(HWND control);
87static int control_operation(datamap *map, HWND dialog, core_options *opts,
88   datamap_entry *entry, datamap_callback_type callback_type);
89static void read_control(datamap *map, HWND control, core_options *opts, datamap_entry *entry, const char *option_name);
90static void populate_control(datamap *map, HWND control, core_options *opts, datamap_entry *entry, const char *option_name);
91
92
93
94//============================================================
95//  datamap_create
96//============================================================
97
98datamap *datamap_create(void)
99{
100   datamap *map = malloc(sizeof(*map));
101   if (!map)
102      return NULL;
103
104   map->entry_count = 0;
105   return map;
106}
107
108
109
110//============================================================
111//  datamap_free
112//============================================================
113
114void datamap_free(datamap *map)
115{
116   free(map);
117}
118
119
120
121//============================================================
122//  datamap_add
123//============================================================
124
125void datamap_add(datamap *map, int dlgitem, datamap_entry_type type, const char *option_name)
126{
127   // sanity check for too many entries
128   assert(map->entry_count < ARRAY_LENGTH(map->entries));
129
130   // add entry to the datamap
131   memset(&map->entries[map->entry_count], 0, sizeof(map->entries[map->entry_count]));
132   map->entries[map->entry_count].dlgitem = dlgitem;
133   map->entries[map->entry_count].type = type;
134   map->entries[map->entry_count].option_name = option_name;
135   map->entry_count++;
136}
137
138
139
140//============================================================
141//  datamap_set_callback
142//============================================================
143
144void datamap_set_callback(datamap *map, int dlgitem, datamap_callback_type callback_type, datamap_callback callback)
145{
146   datamap_entry *entry;
147
148   assert((0 <= callback_type) && (callback_type < DCT_COUNT));
149
150   entry = find_entry(map, dlgitem);
151   entry->callbacks[callback_type] = callback;
152}
153
154
155
156//============================================================
157//  datamap_set_option_name_callback
158//============================================================
159
160void datamap_set_option_name_callback(datamap *map, int dlgitem, get_option_name_callback get_option_name)
161{
162   datamap_entry *entry;
163   entry = find_entry(map, dlgitem);
164   entry->get_option_name = get_option_name;
165}
166
167
168
169//============================================================
170//  datamap_set_trackbar_range
171//============================================================
172
173void datamap_set_trackbar_range(datamap *map, int dlgitem, float min, float max, float increments)
174{
175   datamap_entry *entry = find_entry(map, dlgitem);
176   entry->use_trackbar_options = TRUE;
177   entry->trackbar_min = min;
178   entry->trackbar_max = max;
179   entry->trackbar_increments = increments;
180}
181
182
183
184//============================================================
185//  datamap_set_int_format
186//============================================================
187
188void datamap_set_int_format(datamap *map, int dlgitem, const char *format)
189{
190   datamap_entry *entry = find_entry(map, dlgitem);
191   entry->int_format = format;
192}
193
194
195
196//============================================================
197//  datamap_set_float_format
198//============================================================
199
200void datamap_set_float_format(datamap *map, int dlgitem, const char *format)
201{
202   datamap_entry *entry = find_entry(map, dlgitem);
203   entry->float_format = format;
204}
205
206
207
208//============================================================
209//  datamap_read_control
210//============================================================
211
212BOOL datamap_read_control(datamap *map, HWND dialog, core_options *opts, int dlgitem)
213{
214   datamap_entry *entry = find_entry(map, dlgitem);
215   return control_operation(map, dialog, opts, entry, DCT_READ_CONTROL);
216}
217
218
219
220//============================================================
221//  datamap_read_all_controls
222//============================================================
223
224void datamap_read_all_controls(datamap *map, HWND dialog, core_options *opts)
225{
226   int i;
227   for (i = 0; i < map->entry_count; i++)
228      control_operation(map, dialog, opts, &map->entries[i], DCT_READ_CONTROL);
229}
230
231
232
233//============================================================
234//  datamap_populate_control
235//============================================================
236
237void datamap_populate_control(datamap *map, HWND dialog, core_options *opts, int dlgitem)
238{
239   datamap_entry *entry = find_entry(map, dlgitem);
240   control_operation(map, dialog, opts, entry, DCT_POPULATE_CONTROL);
241}
242
243
244
245//============================================================
246//  datamap_populate_all_controls
247//============================================================
248
249void datamap_populate_all_controls(datamap *map, HWND dialog, core_options *opts)
250{
251   int i;
252   for (i = 0; i < map->entry_count; i++)
253      control_operation(map, dialog, opts, &map->entries[i], DCT_POPULATE_CONTROL);
254}
255
256
257
258//============================================================
259//  datamap_update_control
260//============================================================
261
262void datamap_update_control(datamap *map, HWND dialog, core_options *opts, int dlgitem)
263{
264   datamap_entry *entry = find_entry(map, dlgitem);
265   control_operation(map, dialog, opts, entry, DCT_UPDATE_STATUS);
266}
267
268
269
270//============================================================
271//  datamap_update_all_controls
272//============================================================
273
274void datamap_update_all_controls(datamap *map, HWND dialog, core_options *opts)
275{
276   int i;
277   for (i = 0; i < map->entry_count; i++)
278      control_operation(map, dialog, opts, &map->entries[i], DCT_UPDATE_STATUS);
279}
280
281
282
283//============================================================
284//  find_entry
285//============================================================
286
287static datamap_entry *find_entry(datamap *map, int dlgitem)
288{
289   int i;
290   for (i = 0; i < map->entry_count; i++)
291   {
292      if (map->entries[i].dlgitem == dlgitem)
293         return &map->entries[i];
294   }
295   
296   // should not reach here
297   assert(FALSE);
298   return NULL;
299}
300
301
302
303//============================================================
304//  get_control_type
305//============================================================
306
307static control_type get_control_type(HWND control)
308{
309   control_type type;
310   TCHAR class_name[256];
311
312   GetClassName(control, class_name, ARRAY_LENGTH(class_name));
313   if (!_tcscmp(class_name, WC_BUTTON))
314      type = CT_BUTTON;
315   else if (!_tcscmp(class_name, WC_STATIC))
316      type = CT_STATIC;
317   else if (!_tcscmp(class_name, WC_EDIT))
318      type = CT_EDIT;
319   else if (!_tcscmp(class_name, WC_COMBOBOX))
320      type = CT_COMBOBOX;
321   else if (!_tcscmp(class_name, TRACKBAR_CLASS))
322      type = CT_TRACKBAR;
323   else if (!_tcscmp(class_name, WC_LISTVIEW))
324      type = CT_LISTVIEW;
325   else
326      type = CT_UNKNOWN;
327
328   assert(type != CT_UNKNOWN);
329   return type;
330}
331
332
333
334//============================================================
335//  is_control_displayonly
336//============================================================
337
338static BOOL is_control_displayonly(HWND control)
339{
340   BOOL displayonly;
341   switch(get_control_type(control))
342   {
343      case CT_STATIC:
344         displayonly = TRUE;
345         break;
346
347      case CT_EDIT:
348         displayonly = (GetWindowLong(control, GWL_STYLE) & ES_READONLY) ? TRUE : FALSE;
349         break;
350
351      default:
352         displayonly = FALSE;
353         break;
354   }
355
356   if (!IsWindowEnabled(control))
357      displayonly = TRUE;
358   return displayonly;
359}
360
361
362
363//============================================================
364//  broadcast_changes
365//============================================================
366
367static void broadcast_changes(datamap *map, HWND dialog, core_options *opts, datamap_entry *entry, const char *option_name)
368{
369   HWND other_control;
370   const char *that_option_name;
371   int i;
372
373   for (i = 0; i < map->entry_count; i++)
374   {
375      // search for an entry with the same option_name, but is not the exact
376      // same entry
377      that_option_name = map->entries[i].option_name;
378      if (map->entries[i].option_name && (&map->entries[i] != entry) && !strcmp(that_option_name, option_name))
379      {
380         // we've found a control sharing the same option; populate it
381         other_control = GetDlgItem(dialog, map->entries[i].dlgitem);
382         if (other_control != NULL)
383            populate_control(map, other_control, opts, &map->entries[i], that_option_name);
384      }
385   }
386}
387
388
389
390//============================================================
391//  control_operation
392//============================================================
393
394static int control_operation(datamap *map, HWND dialog, core_options *opts,
395   datamap_entry *entry, datamap_callback_type callback_type)
396{
397   static const datamap_default_callback default_callbacks[DCT_COUNT] =
398   {
399      read_control,
400      populate_control,
401      NULL
402   };
403   HWND control;
404   int result = 0;
405   const char *option_name;
406   char option_name_buffer[64];
407   char option_value[1024] = {0, };
408
409   control = GetDlgItem(dialog, entry->dlgitem);
410   if (control != NULL)
411   {
412      // don't do anything if we're reading from a display-only control
413      if ((callback_type != DCT_READ_CONTROL) || !is_control_displayonly(control))
414      {
415         // figure out the option_name
416         if (entry->get_option_name != NULL)
417         {
418            option_name_buffer[0] = '\0';
419            entry->get_option_name(map, dialog, control, option_name_buffer, ARRAY_LENGTH(option_name_buffer));
420            option_name = option_name_buffer;
421         }
422         else
423         {
424            option_name = entry->option_name;
425         }
426
427         // if reading, get the option value, solely for the purposes of comparison
428         if ((callback_type == DCT_READ_CONTROL) && (option_name != NULL))
429            snprintf(option_value, ARRAY_LENGTH(option_value), "%s", options_get_string(opts, option_name));
430
431         if (entry->callbacks[callback_type] != NULL)
432         {
433            // use custom callback
434            entry->callbacks[callback_type](map, dialog, control, opts, option_name);
435         }
436         else if (default_callbacks[callback_type] && (option_name != NULL))
437         {
438            // use default callback
439            default_callbacks[callback_type](map, control, opts, entry, option_name);
440         }
441
442         // the result is dependent on the type of control
443         switch(callback_type)
444         {
445            case DCT_READ_CONTROL:
446               // do a check to see if the control changed
447               result = (option_name != NULL) && (strcmp(option_value, options_get_string(opts, option_name)) != 0);
448               if (result)
449               {
450                  // the value has changed; we may need to broadcast the change
451                  broadcast_changes(map, dialog, opts, entry, option_name);
452               }
453               break;
454
455            default:
456               // do nothing
457               break;
458         }
459      }
460   }
461   return result;
462}
463
464
465
466//============================================================
467//  trackbar_value_from_position
468//============================================================
469
470static float trackbar_value_from_position(datamap_entry *entry, int position)
471{
472   float position_f = position;
473
474   if (entry->use_trackbar_options)
475   {
476      position_f = (position_f * entry->trackbar_increments) + entry->trackbar_min;
477   }
478   return position_f;
479}
480
481
482
483//============================================================
484//  trackbar_position_from_value
485//============================================================
486
487static int trackbar_position_from_value(datamap_entry *entry, float value)
488{
489   if (entry->use_trackbar_options)
490   {
491      value = floor((value - entry->trackbar_min) / entry->trackbar_increments + 0.5);
492   }
493   return (int) value;
494}
495
496
497
498//============================================================
499//  read_control
500//============================================================
501
502static void read_control(datamap *map, HWND control, core_options *opts, datamap_entry *entry, const char *option_name)
503{
504   BOOL bool_value;
505   int int_value;
506   float float_value;
507   const char *string_value;
508   int selected_index;
509   int trackbar_pos;
510   
511   // use default read value behavior
512   switch(get_control_type(control))
513   {
514      case CT_BUTTON:
515         assert(entry->type == DM_BOOL);
516         bool_value = Button_GetCheck(control);
517         options_set_bool(opts, option_name, bool_value, OPTION_PRIORITY_CMDLINE);
518         break;
519
520      case CT_COMBOBOX:
521         selected_index = ComboBox_GetCurSel(control);
522         if (selected_index >= 0)
523         {
524            switch(entry->type)
525            {
526               case DM_INT:
527                  int_value = (int) ComboBox_GetItemData(control, selected_index);
528                  options_set_int(opts, option_name, int_value, OPTION_PRIORITY_CMDLINE);
529                  break;
530
531               case DM_STRING:
532                  string_value = (const char *) ComboBox_GetItemData(control, selected_index);
533                  options_set_string(opts, option_name, string_value ? string_value : "", OPTION_PRIORITY_CMDLINE);
534                  break;
535
536               default:
537                  assert(FALSE);
538                  break;
539            }
540         }
541         break;
542
543      case CT_TRACKBAR:
544         trackbar_pos = SendMessage(control, TBM_GETPOS, 0, 0);
545         float_value = trackbar_value_from_position(entry, trackbar_pos);
546         switch(entry->type)
547         {
548            case DM_INT:
549               int_value = (int) float_value;
550               if (int_value != options_get_int(opts, option_name))
551                  options_set_int(opts, option_name, int_value, OPTION_PRIORITY_CMDLINE);
552               break;
553
554            case DM_FLOAT:
555               if (float_value != options_get_float(opts, option_name))
556                  options_set_float(opts, option_name, float_value, OPTION_PRIORITY_CMDLINE);
557               break;
558
559            default:
560               assert(FALSE);
561               break;
562         }
563         break;
564
565      case CT_EDIT:
566         // NYI
567         break;
568
569      case CT_STATIC:
570      case CT_LISTVIEW:
571      case CT_UNKNOWN:
572         // non applicable
573         break;
574   }
575}
576
577
578
579//============================================================
580//  populate_control
581//============================================================
582
583static void populate_control(datamap *map, HWND control, core_options *opts, datamap_entry *entry, const char *option_name)
584{
585   int i;
586   BOOL bool_value;
587   int int_value;
588   float float_value;
589   const char *string_value;
590   const char *item_string;
591   int selected_index;
592   char buffer[128];
593   int trackbar_range;
594   int trackbar_pos;
595   double trackbar_range_d;
596   int minval_int, maxval_int;
597   float minval_float, maxval_float;
598
599   // use default populate control value
600   switch(get_control_type(control))
601   {
602      case CT_BUTTON:
603         assert(entry->type == DM_BOOL);
604         bool_value = options_get_bool(opts, option_name);
605         Button_SetCheck(control, bool_value);
606         break;
607
608      case CT_EDIT:
609      case CT_STATIC:
610         switch(entry->type)
611         {
612            case DM_STRING:
613               string_value = options_get_string(opts, option_name);
614               break;
615
616            case DM_INT:
617               int_value = options_get_int(opts, option_name);
618               if (entry->int_format != NULL)
619                  snprintf(buffer, ARRAY_LENGTH(buffer), entry->int_format, int_value);
620               else
621                  snprintf(buffer, ARRAY_LENGTH(buffer), "%d", int_value);
622               string_value = buffer;
623               break;
624
625            case DM_FLOAT:
626               float_value = options_get_float(opts, option_name);
627               if (entry->float_format != NULL)
628                  snprintf(buffer, ARRAY_LENGTH(buffer), entry->float_format, float_value);
629               else
630                  snprintf(buffer, ARRAY_LENGTH(buffer), "%f", float_value);
631               string_value = buffer;
632               break;
633
634            default:
635               string_value = "";
636               break;
637         }
638         win_set_window_text_utf8(control, string_value);
639         break;
640
641      case CT_COMBOBOX:
642         selected_index = 0;
643         switch(entry->type)
644         {
645            case DM_INT:
646               int_value = options_get_int(opts, option_name);
647               for (i = 0; i < ComboBox_GetCount(control); i++)
648               {
649                  if (int_value == (int) ComboBox_GetItemData(control, i))
650                  {
651                     selected_index = i;
652                     break;
653                  }
654               }
655               break;
656
657            case DM_STRING:
658               string_value = options_get_string(opts, option_name);
659               for (i = 0; i < ComboBox_GetCount(control); i++)
660               {
661                  item_string = (const char *) ComboBox_GetItemData(control, i);
662                  if (!core_stricmp(string_value, item_string ? item_string : ""))
663                  {
664                     selected_index = i;
665                     break;
666                  }
667               }
668               break;
669
670            default:
671               assert(FALSE);
672               break;
673         }
674         (void) ComboBox_SetCurSel(control, selected_index);
675         break;
676
677      case CT_TRACKBAR:
678         // do we need to set the trackbar options?
679         if (!entry->use_trackbar_options)
680         {
681            switch(options_get_range_type(opts, option_name))
682            {
683               case OPTION_RANGE_NONE:
684                  // do nothing
685                  break;
686
687               case OPTION_RANGE_INT:
688                  options_get_range_int(opts, option_name, &minval_int, &maxval_int);
689                  entry->use_trackbar_options = TRUE;
690                  entry->trackbar_min = minval_int;
691                  entry->trackbar_max = maxval_int;
692                  entry->trackbar_increments = 1;
693                  break;
694
695               case OPTION_RANGE_FLOAT:
696                  options_get_range_float(opts, option_name, &minval_float, &maxval_float);
697                  entry->use_trackbar_options = TRUE;
698                  entry->trackbar_min = minval_float;
699                  entry->trackbar_max = maxval_float;
700                  entry->trackbar_increments = 0.05;
701                  break;
702            }
703         }
704
705         // do we specify default options for this control?  if so, we need to specify
706         // the range
707         if (entry->use_trackbar_options)
708         {
709            trackbar_range_d = floor(((entry->trackbar_max - entry->trackbar_min)
710               / entry->trackbar_increments) + 0.5);
711            trackbar_range = (int) trackbar_range_d;
712            SendMessage(control, TBM_SETRANGEMIN, (WPARAM) FALSE, (LPARAM) 0);
713            SendMessage(control, TBM_SETRANGEMAX, (WPARAM) FALSE, (LPARAM) trackbar_range);
714         }
715
716         switch(entry->type)
717         {
718            case DM_INT:
719               int_value = options_get_int(opts, option_name);
720               trackbar_pos = trackbar_position_from_value(entry, int_value);
721               break;
722
723            case DM_FLOAT:
724               float_value = options_get_float(opts, option_name);
725               trackbar_pos = trackbar_position_from_value(entry, float_value);
726               break;
727
728            default:
729               trackbar_pos = 0;
730               assert(FALSE);
731               break;
732         }
733         SendMessage(control, TBM_SETPOS, (WPARAM) TRUE, (LPARAM) trackbar_pos);
734         break;
735
736      case CT_LISTVIEW:
737      case CT_UNKNOWN:
738         // non applicable
739         break;
740   }
741}
src/osd/windows/ui/columnedit.h
r995r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11 ***************************************************************************/
12
13#ifndef COLUMNEDIT_H
14#define COLUMNEDIT_H
15
16INT_PTR InternalColumnDialogProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam,
17   int nColumnMax, int *shown, int *order,
18   LPCTSTR *names, void (*pfnGetRealColumnOrder)(int *),
19   void (*pfnGetColumnInfo)(int *pnOrder, int *pnShown),
20   void (*pfnSetColumnInfo)(int *pnOrder, int *pnShown));
21
22INT_PTR CALLBACK ColumnDialogProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam);
23
24#endif
src/osd/windows/ui/verinfo.c
r995r996
1#include <stdio.h>
2#include <ctype.h>
3
4static int read_version_integer(const char *s, int *position)
5{
6   int value = 0;
7
8   if (isdigit(s[*position]))
9   {
10      while(isdigit(s[*position]))
11      {
12         value *= 10;
13         value += s[(*position)++] - '0';
14      }
15
16      if ((s[*position] == '.') || (s[*position] == 'u'))
17         (*position)++;
18   }
19   return value;
20}
21
22
23
24int main(int argc, char *argv[])
25{
26   extern char build_version[];
27   int version_major;
28   int version_minor;
29   int version_build;
30   int version_subbuild;
31   int year = 2006;
32   const char *author;
33   const char *comments;
34   const char *company_name;
35   const char *file_description;
36   const char *internal_name;
37   const char *product_name;
38   const char *legal_trademarks;
39   const char *original_filename;
40   char legal_copyright[256];
41   int position = 0;
42
43   version_major      = read_version_integer(build_version, &position);
44   version_minor      = read_version_integer(build_version, &position);
45   version_build      = read_version_integer(build_version, &position);
46   version_subbuild   = read_version_integer(build_version, &position);
47
48#ifdef MESS
49   file_description = "Multiple Emulation Super System for Win32";
50   company_name = "MESS Team";
51   product_name = "MESS";
52   sprintf(legal_copyright, "Copyright 1997-%d Nicola Salmoria and the MAME team", year);
53   original_filename = "MESS.exe";
54#else
55   file_description = "Multiple Arcade Machine Emulator for Win32";
56   company_name = "MAME Team";
57   product_name = "MAME32";
58   sprintf(legal_copyright, "Copyright 1997-%d Nicola Salmoria and the MAME team", year);
59   original_filename = "MAME32.exe";
60#endif
61   author = "Christopher Kirmse and Michael Soderstrom";
62   comments = file_description;
63   internal_name = product_name;
64   legal_trademarks = "";
65   
66   printf("VS_VERSION_INFO VERSIONINFO\n");
67   printf(" FILEVERSION %d,%d,%d,%d\n", version_major, version_minor, version_build, version_subbuild);
68   printf(" PRODUCTVERSION %d,%d,%d,%d\n", version_major, version_minor, version_build, version_subbuild);
69   printf(" FILEFLAGSMASK 0x3fL\n");
70   printf("#ifdef _DEBUG\n");
71   printf(" FILEFLAGS 0x1L\n");
72   printf("#else\n");
73   printf(" FILEFLAGS 0x0L\n");
74   printf("#endif\n");
75   printf(" FILEOS 0x40004L\n");
76   printf(" FILETYPE 0x1L\n");
77   printf(" FILESUBTYPE 0x0L\n");
78   printf("BEGIN\n");
79   printf("    BLOCK \"StringFileInfo\"\n");
80   printf("    BEGIN\n");
81   printf("        BLOCK \"040904b0\"\n");
82   printf("        BEGIN\n");
83   printf("            VALUE \"Author\", \"%s\\0\"\n", author);
84   printf("            VALUE \"Comments\", \"%s\\0\"\n", comments);
85   printf("            VALUE \"CompanyName\", \"%s\\0\"\n", company_name);
86   printf("            VALUE \"FileDescription\", \"%s\\0\"\n", file_description);
87   printf("            VALUE \"FileVersion\", \"%d, %d, %d, %d\\0\"\n", version_major, version_minor, version_build, version_subbuild);
88   printf("            VALUE \"InternalName\", \"%s\\0\"\n", internal_name);
89   printf("            VALUE \"LegalCopyright\", \"%s\\0\"\n", legal_copyright);
90   printf("            VALUE \"LegalTrademarks\", \"%s\\0\"\n", legal_trademarks);
91   printf("            VALUE \"OriginalFilename\", \"%s\\0\"\n", original_filename);
92   printf("            VALUE \"ProductName\", \"%s\\0\"\n", product_name);
93   printf("            VALUE \"ProductVersion\", \"%d, %d, %d, %d\\0\"\n", version_major, version_minor, version_build, version_subbuild);
94   printf("        END\n");
95   printf("    END\n");
96   printf("    BLOCK \"VarFileInfo\"\n");
97   printf("    BEGIN\n");
98   printf("        VALUE \"Translation\", 0x409, 1200\n");
99   printf("    END\n");
100   printf("END\n");
101
102   return 0;
103}
src/osd/windows/ui/datafile.c
r995r996
1/****************************************************************************
2 *      datafile.c
3 *      History database engine
4 *
5 *      Token parsing by Neil Bradley
6 *      Modifications and higher-level functions by John Butler
7 ****************************************************************************/
8
9#include <assert.h>
10#include <ctype.h>
11#include <windows.h>
12#include "osdcomm.h"
13#include "osd_cpu.h"
14#include "driver.h"
15#include "datafile.h"
16#include "m32opts.h"
17
18/****************************************************************************
19 *      token parsing constants
20 ****************************************************************************/
21
22#define CR      0x0d    /* '\n' and '\r' meanings are swapped in some */
23#define LF      0x0a    /*     compilers (e.g., Mac compilers) */
24
25enum
26{
27        TOKEN_COMMA,
28        TOKEN_EQUALS,
29        TOKEN_SYMBOL,
30        TOKEN_LINEBREAK,
31        TOKEN_INVALID=-1
32};
33
34#define MAX_TOKEN_LENGTH        256
35
36
37/****************************************************************************
38 *      datafile constants
39 ****************************************************************************/
40#define DATAFILE_TAG '$'
41
42const char *DATAFILE_TAG_KEY = "$info";
43const char *DATAFILE_TAG_BIO = "$bio";
44const char *DATAFILE_TAG_MAME = "$mame";
45
46const char *history_filename = NULL;
47const char *mameinfo_filename = NULL;
48
49
50/****************************************************************************
51 *      private data for parsing functions
52 ****************************************************************************/
53static mame_file *fp;                                       /* Our file pointer */
54static long dwFilePos;                                          /* file position */
55static UINT8 bToken[MAX_TOKEN_LENGTH];          /* Our current token */
56
57/* an array of driver name/drivers array index sorted by driver name
58   for fast look up by name */
59typedef struct
60{
61    const char *name;
62    int index;
63} driver_data_type;
64static driver_data_type *sorted_drivers = NULL;
65static int num_games;
66
67
68/**************************************************************************
69 **************************************************************************
70 *
71 *              Parsing functions
72 *
73 **************************************************************************
74 **************************************************************************/
75
76/*
77 * DriverDataCompareFunc -- compare function for GetGameNameIndex
78 */
79static int CLIB_DECL DriverDataCompareFunc(const void *arg1,const void *arg2)
80{
81    return strcmp( ((driver_data_type *)arg1)->name, ((driver_data_type *)arg2)->name );
82}
83
84/*
85 * GetGameNameIndex -- given a driver name (in lowercase), return
86 * its index in the main drivers[] array, or -1 if it's not found.
87 */
88static int GetGameNameIndex(const char *name)
89{
90    driver_data_type *driver_index_info;
91   driver_data_type key;
92   key.name = name;
93
94   if (sorted_drivers == NULL)
95   {
96      /* initialize array of game names/indices */
97      int i;
98
99      sorted_drivers = (driver_data_type *)malloc(sizeof(driver_data_type) * num_games);
100      for (i=0;i<num_games;i++)
101      {
102         sorted_drivers[i].name = drivers[i]->name;
103         sorted_drivers[i].index = i;
104      }
105      qsort(sorted_drivers,num_games,sizeof(driver_data_type),DriverDataCompareFunc);
106   }
107
108   /* uses our sorted array of driver names to get the index in log time */
109   driver_index_info = bsearch(&key,sorted_drivers,num_games,sizeof(driver_data_type),
110                        DriverDataCompareFunc);
111
112   if (driver_index_info == NULL)
113      return -1;
114
115   return driver_index_info->index;
116
117}
118
119/****************************************************************************
120 *      GetNextToken - Pointer to the token string pointer
121 *                                 Pointer to position within file
122 *
123 *      Returns token, or TOKEN_INVALID if at end of file
124 ****************************************************************************/
125static UINT32 GetNextToken(UINT8 **ppszTokenText, long *pdwPosition)
126{
127        UINT32 dwLength;                                                /* Length of symbol */
128        long dwPos;                                                             /* Temporary position */
129        UINT8 *pbTokenPtr = bToken;                             /* Point to the beginning */
130        UINT8 bData;                                                    /* Temporary data byte */
131
132        while (1)
133        {
134                bData = mame_fgetc(fp);                                  /* Get next character */
135
136                /* If we're at the end of the file, bail out */
137
138                if (mame_feof(fp))
139                        return(TOKEN_INVALID);
140
141                /* If it's not whitespace, then let's start eating characters */
142
143                if (' ' != bData && '\t' != bData)
144                {
145                        /* Store away our file position (if given on input) */
146
147                        if (pdwPosition)
148                                *pdwPosition = dwFilePos;
149
150                        /* If it's a separator, special case it */
151
152                        if (',' == bData || '=' == bData)
153                        {
154                                *pbTokenPtr++ = bData;
155                                *pbTokenPtr = '\0';
156                                ++dwFilePos;
157
158                                if (',' == bData)
159                                        return(TOKEN_COMMA);
160                                else
161                                        return(TOKEN_EQUALS);
162                        }
163
164                        /* Otherwise, let's try for a symbol */
165
166                        if (bData > ' ')
167                        {
168                                dwLength = 0;                   /* Assume we're 0 length to start with */
169
170                                /* Loop until we've hit something we don't understand */
171
172                                while (bData != ',' &&
173                                                 bData != '=' &&
174                                                 bData != ' ' &&
175                                                 bData != '\t' &&
176                                                 bData != '\n' &&
177                                                 bData != '\r' &&
178                                                 mame_feof(fp) == 0)
179                                {
180                                        ++dwFilePos;
181                                        *pbTokenPtr++ = bData;  /* Store our byte */
182                                        ++dwLength;
183                                        assert(dwLength < MAX_TOKEN_LENGTH);
184                                        bData = mame_fgetc(fp);
185                                }
186
187                                /* If it's not the end of the file, put the last received byte */
188                                /* back. We don't want to touch the file position, though if */
189                                /* we're past the end of the file. Otherwise, adjust it. */
190
191                                if (0 == mame_feof(fp))
192                                {
193                                        mame_ungetc(bData, fp);
194                                }
195
196                                /* Null terminate the token */
197
198                                *pbTokenPtr = '\0';
199
200                                /* Connect up the */
201
202                                if (ppszTokenText)
203                                        *ppszTokenText = bToken;
204
205                                return(TOKEN_SYMBOL);
206                        }
207
208                        /* Not a symbol. Let's see if it's a cr/cr, lf/lf, or cr/lf/cr/lf */
209                        /* sequence */
210
211                        if (LF == bData)
212                        {
213                                /* Unix style perhaps? */
214
215                                bData = mame_fgetc(fp);          /* Peek ahead */
216                                mame_ungetc(bData, fp);          /* Force a retrigger if subsequent LF's */
217
218                                if (LF == bData)                /* Two LF's in a row - it's a UNIX hard CR */
219                                {
220                                        ++dwFilePos;
221                                        *pbTokenPtr++ = bData;  /* A real linefeed */
222                                        *pbTokenPtr = '\0';
223                                        return(TOKEN_LINEBREAK);
224                                }
225
226                                /* Otherwise, fall through and keep parsing. */
227
228                        }
229                        else
230                        if (CR == bData)                /* Carriage return? */
231                        {
232                                /* Figure out if it's Mac or MSDOS format */
233
234                                ++dwFilePos;
235                                bData = mame_fgetc(fp);          /* Peek ahead */
236
237                                /* We don't need to bother with EOF checking. It will be 0xff if */
238                                /* it's the end of the file and will be caught by the outer loop. */
239
240                                if (CR == bData)                /* Mac style hard return! */
241                                {
242                                        /* Do not advance the file pointer in case there are successive */
243                                        /* CR/CR sequences */
244
245                                        /* Stuff our character back upstream for successive CR's */
246
247                                        mame_ungetc(bData, fp);
248
249                                        *pbTokenPtr++ = bData;  /* A real carriage return (hard) */
250                                        *pbTokenPtr = '\0';
251                                        return(TOKEN_LINEBREAK);
252                                }
253                                else
254                                if (LF == bData)        /* MSDOS format! */
255                                {
256                                        ++dwFilePos;                    /* Our file position to reset to */
257                                        dwPos = dwFilePos;              /* Here so we can reposition things */
258
259                                        /* Look for a followup CR/LF */
260
261                                        bData = mame_fgetc(fp);  /* Get the next byte */
262
263                                        if (CR == bData)        /* CR! Good! */
264                                        {
265                                                bData = mame_fgetc(fp);  /* Get the next byte */
266
267                                                /* We need to do this to pick up subsequent CR/LF sequences */
268
269                                                mame_fseek(fp, dwPos, SEEK_SET);
270
271                                                if (pdwPosition)
272                                                        *pdwPosition = dwPos;
273
274                                                if (LF == bData)        /* LF? Good! */
275                                                {
276                                                        *pbTokenPtr++ = '\r';
277                                                        *pbTokenPtr++ = '\n';
278                                                        *pbTokenPtr = '\0';
279
280                                                        return(TOKEN_LINEBREAK);
281                                                }
282                                        }
283                                        else
284                                        {
285                                                --dwFilePos;
286                                                mame_ungetc(bData, fp);  /* Put the character back. No good */
287                                        }
288                                }
289                                else
290                                {
291                                        --dwFilePos;
292                                        mame_ungetc(bData, fp);  /* Put the character back. No good */
293                                }
294
295                                /* Otherwise, fall through and keep parsing */
296                        }
297                }
298
299                ++dwFilePos;
300        }
301}
302
303
304/****************************************************************************
305 *      ParseClose - Closes the existing opened file (if any)
306 ****************************************************************************/
307static void ParseClose(void)
308{
309        /* If the file is open, time for fclose. */
310
311        if (fp)
312        {
313                mame_fclose(fp);
314        }
315
316        fp = NULL;
317}
318
319
320/****************************************************************************
321 *      ParseOpen - Open up file for reading
322 ****************************************************************************/
323static UINT8 ParseOpen(const char *pszFilename)
324{
325        /* Open file up in binary mode */
326
327        mame_fopen_options(Mame32Global(), NULL, pszFilename, OPEN_FLAG_READ, &fp);
328
329        /* If this is NULL, return FALSE. We can't open it */
330
331        if (NULL == fp)
332        {
333                return(FALSE);
334        }
335
336        /* Otherwise, prepare! */
337
338        dwFilePos = 0;
339        return(TRUE);
340}
341
342
343/****************************************************************************
344 *      ParseSeek - Move the file position indicator
345 ****************************************************************************/
346static UINT8 ParseSeek(long offset, int whence)
347{
348        int result = mame_fseek(fp, offset, whence);
349
350        if (0 == result)
351        {
352                dwFilePos = mame_ftell(fp);
353        }
354        return (UINT8)result;
355}
356
357
358
359/**************************************************************************
360 **************************************************************************
361 *
362 *              Datafile functions
363 *
364 **************************************************************************
365 **************************************************************************/
366
367
368/**************************************************************************
369 *      ci_strncmp - case insensitive character array compare
370 *
371 *      Returns zero if the first n characters of s1 and s2 are equal,
372 *      ignoring case.
373 **************************************************************************/
374static int ci_strncmp (const char *s1, const char *s2, int n)
375{
376        int c1, c2;
377
378        while (n)
379        {
380                if ((c1 = tolower (*s1)) != (c2 = tolower (*s2)))
381                        return (c1 - c2);
382                else if (!c1)
383                        break;
384                --n;
385
386                s1++;
387                s2++;
388        }
389        return 0;
390}
391
392
393/**************************************************************************
394 *      index_datafile
395 *      Create an index for the records in the currently open datafile.
396 *
397 *      Returns 0 on error, or the number of index entries created.
398 **************************************************************************/
399static int index_datafile (struct tDatafileIndex **_index)
400{
401        struct tDatafileIndex *idx;
402        int count = 0;
403        UINT32 token = TOKEN_SYMBOL;
404      num_games = 0;
405      while (drivers[num_games] != NULL)
406         num_games++;
407        /* rewind file */
408        if (ParseSeek (0L, SEEK_SET)) return 0;
409
410        /* allocate index */
411        idx = *_index = malloc (num_games * sizeof (struct tDatafileIndex));
412        if (NULL == idx) return 0;
413
414        /* loop through datafile */
415        while ((count < (num_games - 1)) && TOKEN_INVALID != token)
416        {
417                long tell;
418                UINT8 *s;
419
420                token = GetNextToken (&s, &tell);
421                if (TOKEN_SYMBOL != token) continue;
422
423                /* DATAFILE_TAG_KEY identifies the driver */
424                if (!ci_strncmp (DATAFILE_TAG_KEY, (char *)s, strlen (DATAFILE_TAG_KEY)))
425                {
426                        token = GetNextToken (&s, &tell);
427                        if (TOKEN_EQUALS == token)
428                        {
429                                int done = 0;
430
431                                token = GetNextToken (&s, &tell);
432                                while (!done && TOKEN_SYMBOL == token)
433                                {
434                           int game_index;
435                           UINT8 *p;
436                           for (p = s; *p; p++)
437                              *p = tolower(*p);
438
439                           game_index = GetGameNameIndex((char *)s);
440                           if (game_index >= 0)
441                           {
442                              idx->driver = drivers[game_index];
443                              idx->offset = tell;
444                              idx++;
445                              count++;
446                              /* done = 1;  Not done, as we must process other clones in list */
447
448                           }
449                           if (!done)
450                           {
451                              token = GetNextToken (&s, &tell);
452
453                              if (TOKEN_COMMA == token)
454                                 token = GetNextToken (&s, &tell);
455                              else
456                                 done = 1; /* end of key field */
457                           }
458                                }
459                        }
460                }
461        }
462
463        /* mark end of index */
464        idx->offset = 0L;
465        idx->driver = 0;
466        return count;
467}
468
469
470/**************************************************************************
471 *      load_datafile_text
472 *
473 *      Loads text field for a driver into the buffer specified. Specify the
474 *      driver, a pointer to the buffer, the buffer size, the index created by
475 *      index_datafile(), and the desired text field (e.g., DATAFILE_TAG_BIO).
476 *
477 *      Returns 0 if successful.
478 **************************************************************************/
479static int load_datafile_text (const game_driver *drv, char *buffer, int bufsize,
480        struct tDatafileIndex *idx, const char *tag)
481{
482        int     offset = 0;
483        int found = 0;
484        UINT32  token = TOKEN_SYMBOL;
485        UINT32  prev_token = TOKEN_SYMBOL;
486
487        *buffer = '\0';
488
489        /* find driver in datafile index */
490        while (idx->driver)
491        {
492
493                if (idx->driver == drv) break;
494
495                idx++;
496        }
497        if (idx->driver == 0) return 1; /* driver not found in index */
498
499        /* seek to correct point in datafile */
500        if (ParseSeek (idx->offset, SEEK_SET)) return 1;
501
502        /* read text until buffer is full or end of entry is encountered */
503        while (TOKEN_INVALID != token)
504        {
505                UINT8 *s;
506                int len;
507                long tell;
508
509                token = GetNextToken (&s, &tell);
510                if (TOKEN_INVALID == token) continue;
511
512                if (found)
513                {
514                        /* end entry when a tag is encountered */
515                        if (TOKEN_SYMBOL == token && DATAFILE_TAG == s[0] && TOKEN_LINEBREAK == prev_token) break;
516
517                        prev_token = token;
518
519                        /* translate platform-specific linebreaks to '\n' */
520                        if (TOKEN_LINEBREAK == token)
521                     strcpy ((char *)s, "\n");
522
523                        /* append a space to words */
524                        if (TOKEN_LINEBREAK != token)
525                     strcat ((char *)s, " ");
526
527                        /* remove extraneous space before commas */
528                        if (TOKEN_COMMA == token)
529                        {
530                                --buffer;
531                                --offset;
532                                *buffer = '\0';
533                        }
534
535                        /* Get length of text to add to the buffer */
536                        len = strlen ((char *)s);
537
538                        /* Check for buffer overflow */
539                        /* For some reason we can get a crash if we try */
540                        /* to use the last 30 characters of the buffer  */
541                        if ((bufsize - offset) - len <= 45)
542                        {
543                            strcpy ((char *)s, " ...[TRUNCATED]");
544                            len = strlen((char *)s);
545                            strcpy (buffer, (char *)s);
546                            buffer += len;
547                            offset += len;
548                            break;
549                        }
550
551                        /* add this word to the buffer */
552                        strcpy (buffer, (char *)s);
553                        buffer += len;
554                        offset += len;
555                }
556                else
557                {
558                        if (TOKEN_SYMBOL == token)
559                        {
560                                /* looking for requested tag */
561                                if (!ci_strncmp (tag, (char *)s, strlen (tag)))
562                                        found = 1;
563                                else if (!ci_strncmp (DATAFILE_TAG_KEY, (char *)s, strlen (DATAFILE_TAG_KEY)))
564                                        break; /* error: tag missing */
565                        }
566                }
567        }
568        return (!found);
569}
570
571
572/**************************************************************************
573 *      load_driver_history
574 *      Load history text for the specified driver into the specified buffer.
575 *      Combines $bio field of HISTORY.DAT with $mame field of MAMEINFO.DAT.
576 *
577 *      Returns 0 if successful.
578 *
579 *      NOTE: For efficiency the indices are never freed (intentional leak).
580 **************************************************************************/
581int load_driver_history (const game_driver *drv, char *buffer, int bufsize)
582{
583        static struct tDatafileIndex *hist_idx = 0;
584        static struct tDatafileIndex *mame_idx = 0;
585//   const game_driver *clone_of = NULL;
586        int history = 0, mameinfo = 0;
587        int err = 0;
588
589        *buffer = 0;
590
591
592        if (!history_filename || !*history_filename)
593                history_filename = "history.dat";
594
595        /* try to open history datafile */
596        if (ParseOpen (history_filename))
597        {
598                /* create index if necessary */
599                if (hist_idx)
600                        history = 1;
601                else
602                        history = (index_datafile (&hist_idx) != 0);
603
604                /* load history text */
605                if (hist_idx)
606                {
607                        const game_driver *gdrv;
608
609                        gdrv = drv;
610                        do
611                        {
612                                if ( ( gdrv->flags & GAME_IS_BIOS_ROOT) == 1 )
613               break;
614                                err = load_datafile_text (gdrv, buffer, bufsize,
615                                                                                  hist_idx, DATAFILE_TAG_BIO);
616            gdrv = driver_get_clone(gdrv);
617                        } while (err && gdrv);
618
619                        if (err) history = 0;
620                }
621                ParseClose ();
622        }
623
624        if (!mameinfo_filename || !*mameinfo_filename)
625                mameinfo_filename = "mameinfo.dat";
626
627        /* try to open mameinfo datafile */
628        if (ParseOpen (mameinfo_filename))
629        {
630                /* create index if necessary */
631                if (mame_idx)
632                        mameinfo = 1;
633                else
634                        mameinfo = (index_datafile (&mame_idx) != 0);
635
636                /* load informational text (append) */
637                if (mame_idx)
638                {
639         int len = strlen (buffer);
640                        const game_driver *gdrv;
641
642                        gdrv = drv;
643                        do
644                        {
645                                if ( (gdrv->flags & GAME_IS_BIOS_ROOT) == 1 )
646               break;
647            err = load_datafile_text (gdrv, buffer+len, bufsize-len,
648                                                                                  mame_idx, DATAFILE_TAG_MAME);
649           
650            gdrv = driver_get_clone(gdrv);
651                        } while (err && gdrv);
652
653                        if (err) mameinfo = 0;
654                }
655                ParseClose ();
656        }
657
658        return (history == 0 && mameinfo == 0);
659}
src/osd/windows/ui/resource.hm
r995r996
1// Microsoft Developer Studio generated Help ID include file.
2// Used by mame32.rc
3//
4#define HIDC_ADSTICK                    0x806a04d2    // IDD_PROP_CONTROLLER [Englisch (USA)]
5#define HIDC_ANALOG_AXES                0x809d04bf    // IDD_PROP_INPUT [Englisch (USA)]
6#define HIDC_ANTIALIAS                  0x809f0405    // IDD_PROP_VECTOR [Englisch (USA)]
7#define HIDC_ARTWORK_CROP               0x809e03fa    // IDD_PROP_MISC [Englisch (USA)]
8#define HIDC_ASPECT                     0x80bb04c4    // IDD_PROP_SCREEN [Englisch (USA)]
9#define HIDC_ASPECTRATIOD               0x80bb0483    // IDD_PROP_SCREEN [Englisch (USA)]
10#define HIDC_ASPECTRATION               0x80bb0482    // IDD_PROP_SCREEN [Englisch (USA)]
11#define HIDC_AUDIO_LATENCY              0x809b04a2    // IDD_PROP_SOUND [Englisch (USA)]
12#define HIDC_AUTOFRAMESKIP              0x809c0443    // IDD_PROP_ADVANCED [Englisch (USA)]
13#define HIDC_BACKDROPS                  0x809e040a    // IDD_PROP_MISC [Englisch (USA)]
14#define HIDC_BEAM                       0x809f0406    // IDD_PROP_VECTOR [Englisch (USA)]
15#define HIDC_BEZELS                     0x809e03fd    // IDD_PROP_MISC [Englisch (USA)]
16#define HIDC_BIOS                       0x809e049f    // IDD_PROP_MISC [Englisch (USA)]
17#define HIDC_BRIGHTCORRECT              0x809a0400    // IDD_PROP_DISPLAY [Englisch (USA)]
18#define HIDC_BROADCAST                  0x80ad0486    // IDD_INTERFACE_OPTIONS [Englisch (USA)]
19#define HIDC_CHEAT                      0x809e03f8    // IDD_PROP_MISC [Englisch (USA)]
20#define HIDC_CONTRAST                   0x809a0402    // IDD_PROP_DISPLAY [Englisch (USA)]
21#define HIDC_CYCLETIMESEC               0x80ad04bb    // IDD_INTERFACE_OPTIONS [Englisch (USA)]
22#define HIDC_D3D_FILTER                 0x809a04a0    // IDD_PROP_DISPLAY [Englisch (USA)]
23#define HIDC_D3D_VERSION                0x809a04a3    // IDD_PROP_DISPLAY [Englisch (USA)]
24#define HIDC_DEFAULT_INPUT              0x809d0463    // IDD_PROP_INPUT [Englisch (USA)]
25#define HIDC_DIAL                       0x806a04d4    // IDD_PROP_CONTROLLER [Englisch (USA)]
26#define HIDC_DUAL_LIGHTGUN              0x809d04af    // IDD_PROP_INPUT [Englisch (USA)]
27#define HIDC_ENABLE_AUTOSAVE            0x809e0498    // IDD_PROP_MISC [Englisch (USA)]
28#define HIDC_FILTER_CLONES              0x80a9049a    // IDD_FILTERS [Englisch (USA)]
29#define HIDC_FILTER_EDIT                0x80a904d5    // IDD_FILTERS [Englisch (USA)]
30#define HIDC_FILTER_NONWORKING          0x80a90499    // IDD_FILTERS [Englisch (USA)]
31#define HIDC_FILTER_ORIGINALS           0x80a904a3    // IDD_FILTERS [Englisch (USA)]
32#define HIDC_FILTER_RASTER              0x80a90496    // IDD_FILTERS [Englisch (USA)]
33#define HIDC_FILTER_UNAVAILABLE         0x80a90498    // IDD_FILTERS [Englisch (USA)]
34#define HIDC_FILTER_VECTOR              0x80a90495    // IDD_FILTERS [Englisch (USA)]
35#define HIDC_FILTER_WORKING             0x80a904a4    // IDD_FILTERS [Englisch (USA)]
36#define HIDC_FLICKER                    0x809f0407    // IDD_PROP_VECTOR [Englisch (USA)]
37#define HIDC_FLIPX                      0x809a0408    // IDD_PROP_DISPLAY [Englisch (USA)]
38#define HIDC_FLIPY                      0x809a0409    // IDD_PROP_DISPLAY [Englisch (USA)]
39#define HIDC_FRAMESKIP                  0x809c03f1    // IDD_PROP_ADVANCED [Englisch (USA)]
40#define HIDC_FSBRIGHTNESS               0x809c043e    // IDD_PROP_ADVANCED [Englisch (USA)]
41#define HIDC_FSCONTRAST                 0x809c040c    // IDD_PROP_ADVANCED [Englisch (USA)]
42#define HIDC_FSGAMMA                    0x809c043c    // IDD_PROP_ADVANCED [Englisch (USA)]
43#define HIDC_GAME_CAPTION               0x80ad04c8    // IDD_INTERFACE_OPTIONS [Englisch (USA)]
44#define HIDC_GAMMA                      0x809a03ff    // IDD_PROP_DISPLAY [Englisch (USA)]
45#define HIDC_HIDE_MOUSE                 0x80ad04b5    // IDD_INTERFACE_OPTIONS [Englisch (USA)]
46#define HIDC_HIGH_PRIORITY              0x809e049e    // IDD_PROP_MISC [Englisch (USA)]
47#define HIDC_HISTORY                    0x806504cb    // IDD_MAIN [Englisch (USA)]
48#define HIDC_HWSTRETCH                  0x809a046c    // IDD_PROP_DISPLAY [Englisch (USA)]
49#define HIDC_JDZ                        0x809d0488    // IDD_PROP_INPUT [Englisch (USA)]
50#define HIDC_JOYSTICK                   0x809d03eb    // IDD_PROP_INPUT [Englisch (USA)]
51#define HIDC_JOY_GUI                    0x80ad0485    // IDD_INTERFACE_OPTIONS [Englisch (USA)]
52#define HIDC_JSAT                       0x809d048c    // IDD_PROP_INPUT [Englisch (USA)]
53#define HIDC_KEEPASPECT                 0x809a0474    // IDD_PROP_DISPLAY [Englisch (USA)]
54#define HIDC_LANGUAGECHECK              0x80b204d1    // IDD_LANGUAGE [Englisch (USA)]
55#define HIDC_LANGUAGEEDIT               0x80b204d4    // IDD_LANGUAGE [Englisch (USA)]
56#define HIDC_LIGHTGUN                   0x809d048d    // IDD_PROP_INPUT [Englisch (USA)]
57#define HIDC_LIGHTGUNDEVICE             0x806a04d6    // IDD_PROP_CONTROLLER [Englisch (USA)]
58#define HIDC_LOG                        0x809e03f9    // IDD_PROP_MISC [Englisch (USA)]
59#define HIDC_MAXIMIZE                   0x809a046e    // IDD_PROP_DISPLAY [Englisch (USA)]
60#define HIDC_MULTITHREAD_RENDERING      0x809e049a    // IDD_PROP_MISC [Englisch (USA)]
61#define HIDC_NUMSCREENS                 0x80bb0404    // IDD_PROP_SCREEN [Englisch (USA)]
62#define HIDC_OLD_TIMING                 0x809e049b    // IDD_PROP_MISC [Englisch (USA)]
63#define HIDC_OVERLAYS                   0x809e03fb    // IDD_PROP_MISC [Englisch (USA)]
64#define HIDC_PADDLE                     0x806a04d1    // IDD_PROP_CONTROLLER [Englisch (USA)]
65#define HIDC_PAUSEBRIGHT                0x809a049c    // IDD_PROP_DISPLAY [Englisch (USA)]
66#define HIDC_PEDAL                      0x806a04d3    // IDD_PROP_CONTROLLER [Englisch (USA)]
67#define HIDC_PRESCALE                   0x809a041f    // IDD_PROP_DISPLAY [Englisch (USA)]
68#define HIDC_PROP_RESET                 0x809c0447    // IDD_PROP_ADVANCED [Englisch (USA)]
69#define HIDC_RANDOM_BG                  0x80ad0491    // IDD_INTERFACE_OPTIONS [Englisch (USA)]
70#define HIDC_REFRESH                    0x80bb047c    // IDD_PROP_SCREEN [Englisch (USA)]
71#define HIDC_RELOAD                     0x809d04ae    // IDD_PROP_INPUT [Englisch (USA)]
72#define HIDC_RESET_DEFAULT              0x80aa04a2    // IDD_RESET [Englisch (USA)]
73#define HIDC_RESET_EFFECT               0x809c0453    // IDD_PROP_ADVANCED [Englisch (USA)]
74#define HIDC_RESET_FILTERS              0x80aa049f    // IDD_RESET [Englisch (USA)]
75#define HIDC_RESET_GAMES                0x80aa049d    // IDD_RESET [Englisch (USA)]
76#define HIDC_RESET_UI                   0x80aa049e    // IDD_RESET [Englisch (USA)]
77#define HIDC_ROTATE                     0x809a03f2    // IDD_PROP_DISPLAY [Englisch (USA)]
78#define HIDC_SAMPLERATE                 0x809b0403    // IDD_PROP_SOUND [Englisch (USA)]
79#define HIDC_SAMPLES                    0x809b0461    // IDD_PROP_SOUND [Englisch (USA)]
80#define HIDC_SCREEN                     0x80bb03f4    // IDD_PROP_SCREEN [Englisch (USA)]
81#define HIDC_SCREENSELECT               0x80bb03f7    // IDD_PROP_SCREEN [Englisch (USA)]
82#define HIDC_SELECT_EFFECT              0x809c04c2    // IDD_PROP_ADVANCED [Englisch (USA)]
83#define HIDC_SIZES                      0x80bb03ed    // IDD_PROP_SCREEN [Englisch (USA)]
84#define HIDC_SKIP_GAME_INFO             0x809e0499    // IDD_PROP_MISC [Englisch (USA)]
85#define HIDC_SLEEP                      0x809e03fe    // IDD_PROP_MISC [Englisch (USA)]
86#define HIDC_START_GAME_CHECK           0x80ad045b    // IDD_INTERFACE_OPTIONS [Englisch (USA)]
87#define HIDC_STEADYKEY                  0x809d0480    // IDD_PROP_INPUT [Englisch (USA)]
88#define HIDC_STRETCH_SCREENSHOT_LARGER  0x80ad04bd    // IDD_INTERFACE_OPTIONS [Englisch (USA)]
89#define HIDC_SWITCHRES                  0x80bb046d    // IDD_PROP_SCREEN [Englisch (USA)]
90#define HIDC_SYNCREFRESH                0x809c0475    // IDD_PROP_ADVANCED [Englisch (USA)]
91#define HIDC_THROTTLE                   0x809a0478    // IDD_PROP_DISPLAY [Englisch (USA)]
92#define HIDC_TRACKBALL                  0x806a04d5    // IDD_PROP_CONTROLLER [Englisch (USA)]
93#define HIDC_TRIPLE_BUFFER              0x809c0461    // IDD_PROP_ADVANCED [Englisch (USA)]
94#define HIDC_USE_DEFAULT                0x809c0401    // IDD_PROP_ADVANCED [Englisch (USA)]
95#define HIDC_USE_MOUSE                  0x809d0477    // IDD_PROP_INPUT [Englisch (USA)]
96#define HIDC_USE_SOUND                  0x809b046d    // IDD_PROP_SOUND [Englisch (USA)]
97#define HIDC_VIDEO_MODE                 0x809a04ca    // IDD_PROP_DISPLAY [Englisch (USA)]
98#define HIDC_VIEW                       0x80bb03f6    // IDD_PROP_SCREEN [Englisch (USA)]
99#define HIDC_VOLUME                     0x809b045d    // IDD_PROP_SOUND [Englisch (USA)]
100#define HIDC_WAITVSYNC                  0x809c046b    // IDD_PROP_ADVANCED [Englisch (USA)]
101#define HIDC_WINDOWED                   0x809a0497    // IDD_PROP_DISPLAY [Englisch (USA)]
src/osd/windows/ui/directories.c
r995r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11 ***************************************************************************/
12
13/***************************************************************************
14
15  Directories.c
16
17***************************************************************************/
18
19#define COBJMACROS
20#define WIN32_LEAN_AND_MEAN
21#include <windows.h>
22#include <windowsx.h>
23#include <shlobj.h>
24#include <sys/stat.h>
25#include <assert.h>
26#include <tchar.h>
27
28#include "screenshot.h"
29#include "MAME32.h"
30#include "Directories.h"
31#include "resource.h"
32#include "strconv.h"
33#include "ui/m32util.h"
34
35#define MAX_DIRS 20
36
37/***************************************************************************
38    Internal structures
39 ***************************************************************************/
40
41typedef struct
42{
43   TCHAR   m_Directories[MAX_DIRS][MAX_PATH];
44   int     m_NumDirectories;
45   BOOL    m_bModified;
46} tPath;
47
48typedef struct
49{
50   tPath   *m_Path;
51   TCHAR   *m_Directory;
52} tDirInfo;
53
54/***************************************************************************
55    Function prototypes
56 ***************************************************************************/
57
58static int CALLBACK BrowseCallbackProc(HWND hwnd, UINT uMsg, LPARAM lParam, LPARAM lpData);
59#ifdef MESS
60BOOL            BrowseForDirectory(HWND hwnd, LPCTSTR pStartDir, TCHAR* pResult);
61#else
62static BOOL     BrowseForDirectory(HWND hwnd, LPCTSTR pStartDir, TCHAR* pResult);
63#endif
64
65static void     DirInfo_SetDir(tDirInfo *pInfo, int nType, int nItem, LPCTSTR pText);
66static TCHAR*   DirInfo_Dir(tDirInfo *pInfo, int nType);
67static TCHAR*   DirInfo_Path(tDirInfo *pInfo, int nType, int nItem);
68static void     DirInfo_SetModified(tDirInfo *pInfo, int nType, BOOL bModified);
69static BOOL     DirInfo_Modified(tDirInfo *pInfo, int nType);
70static TCHAR*   FixSlash(TCHAR *s);
71
72static void     UpdateDirectoryList(HWND hDlg);
73
74static void     Directories_OnSelChange(HWND hDlg);
75static BOOL     Directories_OnInitDialog(HWND hDlg, HWND hwndFocus, LPARAM lParam);
76static void     Directories_OnDestroy(HWND hDlg);
77static void     Directories_OnClose(HWND hDlg);
78static void     Directories_OnOk(HWND hDlg);
79static void     Directories_OnCancel(HWND hDlg);
80static void     Directories_OnInsert(HWND hDlg);
81static void     Directories_OnBrowse(HWND hDlg);
82static void     Directories_OnDelete(HWND hDlg);
83static BOOL     Directories_OnBeginLabelEdit(HWND hDlg, NMHDR* pNMHDR);
84static BOOL     Directories_OnEndLabelEdit(HWND hDlg, NMHDR* pNMHDR);
85static void     Directories_OnCommand(HWND hDlg, int id, HWND hwndCtl, UINT codeNotify);
86static BOOL     Directories_OnNotify(HWND hDlg, int id, NMHDR* pNMHDR);
87
88/***************************************************************************
89    External variables
90 ***************************************************************************/
91
92/***************************************************************************
93    Internal variables
94 ***************************************************************************/
95
96static tDirInfo *g_pDirInfo;
97
98/***************************************************************************
99    External function definitions
100 ***************************************************************************/
101
102INT_PTR CALLBACK DirectoriesDialogProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam)
103{
104   BOOL bReturn = FALSE;
105
106   switch (Msg)
107   {
108   case WM_INITDIALOG:
109      return (BOOL)HANDLE_WM_INITDIALOG(hDlg, wParam, lParam, Directories_OnInitDialog);
110
111   case WM_COMMAND:
112      HANDLE_WM_COMMAND(hDlg, wParam, lParam, Directories_OnCommand);
113      bReturn = TRUE;
114      break;
115
116   case WM_NOTIFY:
117      return (BOOL)HANDLE_WM_NOTIFY(hDlg, wParam, lParam, Directories_OnNotify);
118      break;
119
120   case WM_CLOSE:
121      HANDLE_WM_CLOSE(hDlg, wParam, lParam, Directories_OnClose);
122      break;
123
124   case WM_DESTROY:
125      HANDLE_WM_DESTROY(hDlg, wParam, lParam, Directories_OnDestroy);
126      break;
127
128   default:
129      bReturn = FALSE;
130   }
131   return bReturn;
132}
133
134/***************************************************************************
135   Internal function definitions
136 ***************************************************************************/
137
138static BOOL IsMultiDir(int nType)
139{
140   return g_directoryInfo[nType].bMulti;
141}
142
143static void DirInfo_SetDir(tDirInfo *pInfo, int nType, int nItem, LPCTSTR pText)
144{
145   TCHAR *s;
146   TCHAR *pOldText;
147
148   if (IsMultiDir(nType))
149   {
150      assert(nItem >= 0);
151      _tcscpy(DirInfo_Path(pInfo, nType, nItem), pText);
152      DirInfo_SetModified(pInfo, nType, TRUE);
153   }
154   else
155   {
156      s = win_tstring_strdup(pText);
157      if (!s)
158         return;
159      pOldText = pInfo[nType].m_Directory;
160      if (pOldText)
161         free(pOldText);
162      pInfo[nType].m_Directory = s;
163   }
164}
165
166static TCHAR* DirInfo_Dir(tDirInfo *pInfo, int nType)
167{
168   assert(!IsMultiDir(nType));
169   return pInfo[nType].m_Directory;
170}
171
172static TCHAR* DirInfo_Path(tDirInfo *pInfo, int nType, int nItem)
173{
174   return pInfo[nType].m_Path->m_Directories[nItem];
175}
176
177static void DirInfo_SetModified(tDirInfo *pInfo, int nType, BOOL bModified)
178{
179   assert(IsMultiDir(nType));
180   pInfo[nType].m_Path->m_bModified = bModified;
181}
182
183static BOOL DirInfo_Modified(tDirInfo *pInfo, int nType)
184{
185   assert(IsMultiDir(nType));
186   return pInfo[nType].m_Path->m_bModified;
187}
188
189#define DirInfo_NumDir(pInfo, path) \
190   ((pInfo)[(path)].m_Path->m_NumDirectories)
191
192/* lop off trailing backslash if it exists */
193static TCHAR * FixSlash(TCHAR *s)
194{
195   int len = 0;
196   
197   if (s)
198      len = _tcslen(s);
199
200   if (len && s[len - 1] == '\\')
201      s[len - 1] = '\0';
202
203   return s;
204}
205
206static void UpdateDirectoryList(HWND hDlg)
207{
208   int    i;
209   int    nType;
210   LV_ITEM Item;
211   HWND   hList  = GetDlgItem(hDlg, IDC_DIR_LIST);
212   HWND   hCombo = GetDlgItem(hDlg, IDC_DIR_COMBO);
213
214   /* Remove previous */
215
216   ListView_DeleteAllItems(hList);
217
218   /* Update list */
219
220   memset(&Item, 0, sizeof(LV_ITEM));
221   Item.mask = LVIF_TEXT;
222
223   nType = ComboBox_GetCurSel(hCombo);
224   if (IsMultiDir(nType))
225   {
226      Item.pszText = (TCHAR*) TEXT(DIRLIST_NEWENTRYTEXT);
227      ListView_InsertItem(hList, &Item);
228      for (i = DirInfo_NumDir(g_pDirInfo, nType) - 1; 0 <= i; i--)
229      {
230         Item.pszText = DirInfo_Path(g_pDirInfo, nType, i);
231         ListView_InsertItem(hList, &Item);
232      }
233   }
234   else
235   {
236      Item.pszText = DirInfo_Dir(g_pDirInfo, nType);
237      ListView_InsertItem(hList, &Item);
238   }
239
240   /* select first one */
241
242   ListView_SetItemState(hList, 0, LVIS_SELECTED, LVIS_SELECTED);
243}
244
245static void Directories_OnSelChange(HWND hDlg)
246{
247   UpdateDirectoryList(hDlg);
248   
249   if (ComboBox_GetCurSel(GetDlgItem(hDlg, IDC_DIR_COMBO)) == 0
250   ||   ComboBox_GetCurSel(GetDlgItem(hDlg, IDC_DIR_COMBO)) == 1)
251   {
252      EnableWindow(GetDlgItem(hDlg, IDC_DIR_DELETE), TRUE);
253      EnableWindow(GetDlgItem(hDlg, IDC_DIR_INSERT), TRUE);
254   }
255   else
256   {
257      EnableWindow(GetDlgItem(hDlg, IDC_DIR_DELETE), FALSE);
258      EnableWindow(GetDlgItem(hDlg, IDC_DIR_INSERT), FALSE);
259   }
260}
261
262static BOOL Directories_OnInitDialog(HWND hDlg, HWND hwndFocus, LPARAM lParam)
263{
264   RECT      rectClient;
265   LVCOLUMN   LVCol;
266   int       i;
267   int         nDirInfoCount;
268   LPCSTR      s;
269   TCHAR       *token;
270   TCHAR       buf[MAX_PATH * MAX_DIRS];
271   TCHAR*      t_s = NULL;
272
273   /* count how many dirinfos there are */
274   nDirInfoCount = 0;
275   while(g_directoryInfo[nDirInfoCount].lpName)
276      nDirInfoCount++;
277
278   g_pDirInfo = (tDirInfo *) malloc(sizeof(tDirInfo) * nDirInfoCount);
279   if (!g_pDirInfo) /* bummer */
280      goto error;
281   memset(g_pDirInfo, 0, sizeof(tDirInfo) * nDirInfoCount);
282
283   for (i = nDirInfoCount - 1; i >= 0; i--)
284   {
285      t_s = tstring_from_utf8(g_directoryInfo[i].lpName);
286      if( !t_s )
287         return FALSE;
288      (void) ComboBox_InsertString(GetDlgItem(hDlg, IDC_DIR_COMBO), 0, win_tstring_strdup(t_s));
289      free(t_s);
290      t_s = NULL;
291   }
292
293   (void) ComboBox_SetCurSel(GetDlgItem(hDlg, IDC_DIR_COMBO), 0);
294
295   GetClientRect(GetDlgItem(hDlg, IDC_DIR_LIST), &rectClient);
296
297   memset(&LVCol, 0, sizeof(LVCOLUMN));
298   LVCol.mask     = LVCF_WIDTH;
299   LVCol.cx     = rectClient.right - rectClient.left - GetSystemMetrics(SM_CXHSCROLL);
300   
301   ListView_InsertColumn(GetDlgItem(hDlg, IDC_DIR_LIST), 0, &LVCol);
302
303   /* Keep a temporary copy of the directory strings in g_pDirInfo. */
304   for (i = 0; i < nDirInfoCount; i++)
305   {
306      s = g_directoryInfo[i].pfnGetTheseDirs();
307      t_s = tstring_from_utf8(s);
308      if( !t_s )
309         return FALSE;
310      if (g_directoryInfo[i].bMulti)
311      {
312         /* Copy the string to our own buffer so that we can mutilate it */
313         _tcscpy(buf, t_s);
314
315         g_pDirInfo[i].m_Path = malloc(sizeof(tPath));
316         if (!g_pDirInfo[i].m_Path)
317            goto error;
318
319         g_pDirInfo[i].m_Path->m_NumDirectories = 0;
320         token = _tcstok(buf, TEXT(";"));
321         while ((DirInfo_NumDir(g_pDirInfo, i) < MAX_DIRS) && token)
322         {
323            _tcscpy(DirInfo_Path(g_pDirInfo, i, DirInfo_NumDir(g_pDirInfo, i)), token);
324            DirInfo_NumDir(g_pDirInfo, i)++;
325            token = _tcstok(NULL, TEXT(";"));
326         }
327         DirInfo_SetModified(g_pDirInfo, i, FALSE);
328      }
329      else
330      {
331         DirInfo_SetDir(g_pDirInfo, i, -1, t_s);
332      }
333      free(t_s);
334      t_s = NULL;
335   }
336
337   UpdateDirectoryList(hDlg);
338   return TRUE;
339
340error:
341   if( t_s )
342      free(t_s);
343   Directories_OnDestroy(hDlg);
344   EndDialog(hDlg, -1);
345   return FALSE;
346}
347
348static void Directories_OnDestroy(HWND hDlg)
349{
350   int nDirInfoCount, i;
351
352   if (g_pDirInfo)
353   {
354      /* count how many dirinfos there are */
355      nDirInfoCount = 0;
356      while(g_directoryInfo[nDirInfoCount].lpName)
357         nDirInfoCount++;
358
359      for (i = 0; i < nDirInfoCount; i++)
360      {
361         if (g_pDirInfo[i].m_Path)
362            free(g_pDirInfo[i].m_Path);
363         if (g_pDirInfo[i].m_Directory)
364            free(g_pDirInfo[i].m_Directory);         
365      }
366      free(g_pDirInfo);
367      g_pDirInfo = NULL;
368   }
369}
370
371static void Directories_OnClose(HWND hDlg)
372{
373   EndDialog(hDlg, IDCANCEL);
374}
375
376static int RetrieveDirList(int nDir, int nFlagResult, void (*SetTheseDirs)(const char *s))
377{
378   int i;
379   int nResult = 0;
380   int nPaths;
381   TCHAR buf[MAX_PATH * MAX_DIRS];
382   char* utf8_buf;
383
384   if (DirInfo_Modified(g_pDirInfo, nDir))
385   {
386      memset(buf, 0, sizeof(buf));
387      nPaths = DirInfo_NumDir(g_pDirInfo, nDir);
388      for (i = 0; i < nPaths; i++)
389      {
390         _tcscat(buf, FixSlash(DirInfo_Path(g_pDirInfo, nDir, i)));
391
392         if (i < nPaths - 1)
393            _tcscat(buf, TEXT(";"));
394      }
395      utf8_buf = utf8_from_tstring(buf);
396      SetTheseDirs(utf8_buf);
397      free(utf8_buf);
398
399      nResult |= nFlagResult;
400    }
401   return nResult;
402}
403
404static void Directories_OnOk(HWND hDlg)
405{
406   int i;
407   int nResult = 0;
408   LPTSTR s;
409   char* utf8_s;
410
411   for (i = 0; g_directoryInfo[i].lpName; i++)
412   {
413      if (g_directoryInfo[i].bMulti)
414      {
415         nResult |= RetrieveDirList(i, g_directoryInfo[i].nDirDlgFlags, g_directoryInfo[i].pfnSetTheseDirs);
416      }
417      else
418      {
419         s = FixSlash(DirInfo_Dir(g_pDirInfo, i));
420         utf8_s = utf8_from_tstring(s);
421         g_directoryInfo[i].pfnSetTheseDirs(utf8_s);
422         free(utf8_s);
423      }
424   }
425   EndDialog(hDlg, nResult);
426}
427
428static void Directories_OnCancel(HWND hDlg)
429{
430   EndDialog(hDlg, IDCANCEL);
431}
432
433static void Directories_OnInsert(HWND hDlg)
434{
435   int    nItem;
436   TCHAR   buf[MAX_PATH];
437   HWND   hList;
438
439   hList = GetDlgItem(hDlg, IDC_DIR_LIST);
440   nItem = ListView_GetNextItem(hList, -1, LVNI_SELECTED);
441
442   if (BrowseForDirectory(hDlg, NULL, buf) == TRUE)
443   {
444      int    i;
445      int    nType;
446
447      /* list was empty */
448      if (nItem == -1)
449         nItem = 0;
450
451      nType = ComboBox_GetCurSel(GetDlgItem(hDlg, IDC_DIR_COMBO));
452      if (IsMultiDir(nType))
453      {
454         if (MAX_DIRS <= DirInfo_NumDir(g_pDirInfo, nType))
455            return;
456
457         for (i = DirInfo_NumDir(g_pDirInfo, nType); nItem < i; i--)
458            _tcscpy(DirInfo_Path(g_pDirInfo, nType, i),
459                  DirInfo_Path(g_pDirInfo, nType, i - 1));
460
461         _tcscpy(DirInfo_Path(g_pDirInfo, nType, nItem), buf);
462         DirInfo_NumDir(g_pDirInfo, nType)++;
463         DirInfo_SetModified(g_pDirInfo, nType, TRUE);
464      }
465
466      UpdateDirectoryList(hDlg);
467
468      ListView_SetItemState(hList, nItem, LVIS_FOCUSED | LVIS_SELECTED, LVIS_FOCUSED | LVIS_SELECTED);
469   }
470}
471
472static void Directories_OnBrowse(HWND hDlg)
473{
474   int    nType;
475   int    nItem;
476   TCHAR   inbuf[MAX_PATH];
477   TCHAR   outbuf[MAX_PATH];
478   HWND   hList;
479
480   hList = GetDlgItem(hDlg, IDC_DIR_LIST);
481   nItem = ListView_GetNextItem(hList, -1, LVNI_SELECTED);
482
483   if (nItem == -1)
484      return;
485
486   nType = ComboBox_GetCurSel(GetDlgItem(hDlg, IDC_DIR_COMBO));
487   if (IsMultiDir(nType))
488   {
489      /* Last item is placeholder for append */
490      if (nItem == ListView_GetItemCount(hList) - 1)
491      {
492         Directories_OnInsert(hDlg);
493         return;
494      }
495   }
496
497   ListView_GetItemText(hList, nItem, 0, inbuf, MAX_PATH);
498
499   if (BrowseForDirectory(hDlg, inbuf, outbuf) == TRUE)
500   {
501      nType = ComboBox_GetCurSel(GetDlgItem(hDlg, IDC_DIR_COMBO));
502      DirInfo_SetDir(g_pDirInfo, nType, nItem, outbuf);
503      UpdateDirectoryList(hDlg);
504   }
505}
506
507static void Directories_OnDelete(HWND hDlg)
508{
509   int    nType;
510   int    nCount;
511   int    nSelect;
512   int    i;
513   int    nItem;
514   HWND   hList = GetDlgItem(hDlg, IDC_DIR_LIST);
515
516   nItem = ListView_GetNextItem(hList, -1, LVNI_SELECTED | LVNI_ALL);
517
518   if (nItem == -1)
519      return;
520
521   /* Don't delete "Append" placeholder. */
522   if (nItem == ListView_GetItemCount(hList) - 1)
523      return;
524
525   nType = ComboBox_GetCurSel(GetDlgItem(hDlg, IDC_DIR_COMBO));
526   if (IsMultiDir(nType))
527   {
528      for (i = nItem; i < DirInfo_NumDir(g_pDirInfo, nType) - 1; i++)
529         _tcscpy(DirInfo_Path(g_pDirInfo, nType, i),
530               DirInfo_Path(g_pDirInfo, nType, i + 1));
531
532      _tcscpy(DirInfo_Path(g_pDirInfo, nType, DirInfo_NumDir(g_pDirInfo, nType) - 1), TEXT(""));
533      DirInfo_NumDir(g_pDirInfo, nType)--;
534
535      DirInfo_SetModified(g_pDirInfo, nType, TRUE);
536   }
537
538   UpdateDirectoryList(hDlg);
539   
540
541   nCount = ListView_GetItemCount(hList);
542   if (nCount <= 1)
543      return;
544
545   /* If the last item was removed, select the item above. */
546   if (nItem == nCount - 1)
547      nSelect = nCount - 2;
548   else
549      nSelect = nItem;
550
551   ListView_SetItemState(hList, nSelect, LVIS_FOCUSED | LVIS_SELECTED, LVIS_FOCUSED | LVIS_SELECTED);
552}
553
554static BOOL Directories_OnBeginLabelEdit(HWND hDlg, NMHDR* pNMHDR)
555{
556   int         nType;
557   BOOL        bResult = FALSE;
558   NMLVDISPINFO* pDispInfo = (NMLVDISPINFO*)pNMHDR;
559   LVITEM*      pItem = &pDispInfo->item;
560
561   nType = ComboBox_GetCurSel(GetDlgItem(hDlg, IDC_DIR_COMBO));
562   if (IsMultiDir(nType))
563   {
564      /* Last item is placeholder for append */
565      if (pItem->iItem == ListView_GetItemCount(GetDlgItem(hDlg, IDC_DIR_LIST)) - 1)
566      {
567         HWND hEdit;
568
569         if (MAX_DIRS <= DirInfo_NumDir(g_pDirInfo, nType))
570            return TRUE; /* don't edit */
571
572         hEdit = (HWND)(LRESULT)(int)SendDlgItemMessage(hDlg, IDC_DIR_LIST, LVM_GETEDITCONTROL, 0, 0);
573         Edit_SetText(hEdit, TEXT(""));
574      }
575   }
576
577   return bResult;
578}
579
580static BOOL Directories_OnEndLabelEdit(HWND hDlg, NMHDR* pNMHDR)
581{
582   BOOL        bResult = FALSE;
583   NMLVDISPINFO* pDispInfo = (NMLVDISPINFO*)pNMHDR;
584   LVITEM*      pItem = &pDispInfo->item;
585
586   if (pItem->pszText != NULL)
587   {
588      struct _stat file_stat;
589
590      /* Don't allow empty entries. */
591      if (!_tcscmp(pItem->pszText, TEXT("")))
592      {
593         return FALSE;
594      }
595
596      /* Check validity of edited directory. */
597      if (_tstat(pItem->pszText, &file_stat) == 0
598      &&   (file_stat.st_mode & S_IFDIR))
599      {
600         bResult = TRUE;
601      }
602      else
603      {
604         if (MessageBox(NULL, TEXT("Directory does not exist, continue anyway?"), TEXT(MAME32NAME), MB_OKCANCEL) == IDOK)
605            bResult = TRUE;
606      }
607   }
608
609   if (bResult == TRUE)
610   {
611      int nType;
612      int i;
613
614      nType = ComboBox_GetCurSel(GetDlgItem(hDlg, IDC_DIR_COMBO));
615      if (IsMultiDir(nType))
616      {
617         /* Last item is placeholder for append */
618         if (pItem->iItem == ListView_GetItemCount(GetDlgItem(hDlg, IDC_DIR_LIST)) - 1)
619         {
620            if (MAX_DIRS <= DirInfo_NumDir(g_pDirInfo, nType))
621               return FALSE;
622
623            for (i = DirInfo_NumDir(g_pDirInfo, nType); pItem->iItem < i; i--)
624               _tcscpy(DirInfo_Path(g_pDirInfo, nType, i),
625                     DirInfo_Path(g_pDirInfo, nType, i - 1));
626
627            _tcscpy(DirInfo_Path(g_pDirInfo, nType, pItem->iItem), pItem->pszText);
628
629            DirInfo_SetModified(g_pDirInfo, nType, TRUE);
630            DirInfo_NumDir(g_pDirInfo, nType)++;
631         }
632         else
633            DirInfo_SetDir(g_pDirInfo, nType, pItem->iItem, pItem->pszText);
634      }
635      else
636      {
637         DirInfo_SetDir(g_pDirInfo, nType, pItem->iItem, pItem->pszText);
638      }
639
640      UpdateDirectoryList(hDlg);
641      ListView_SetItemState(GetDlgItem(hDlg, IDC_DIR_LIST), pItem->iItem,
642                       LVIS_FOCUSED | LVIS_SELECTED, LVIS_FOCUSED | LVIS_SELECTED);
643
644   }
645
646   return bResult;
647}
648
649static void Directories_OnCommand(HWND hDlg, int id, HWND hwndCtl, UINT codeNotify)
650{
651   switch (id)
652   {
653   case IDOK:
654      if (codeNotify == BN_CLICKED)
655         Directories_OnOk(hDlg);
656      break;
657
658   case IDCANCEL:
659      if (codeNotify == BN_CLICKED)
660         Directories_OnCancel(hDlg);
661      break;
662
663   case IDC_DIR_BROWSE:
664      if (codeNotify == BN_CLICKED)
665         Directories_OnBrowse(hDlg);
666      break;
667
668   case IDC_DIR_INSERT:
669      if (codeNotify == BN_CLICKED)
670         Directories_OnInsert(hDlg);
671      break;
672
673   case IDC_DIR_DELETE:
674      if (codeNotify == BN_CLICKED)
675         Directories_OnDelete(hDlg);
676      break;
677
678   case IDC_DIR_COMBO:
679      switch (codeNotify)
680      {
681      case CBN_SELCHANGE:
682         Directories_OnSelChange(hDlg);
683         break;
684      }
685      break;
686   }
687}
688
689static BOOL Directories_OnNotify(HWND hDlg, int id, NMHDR* pNMHDR)
690{
691   switch (id)
692   {
693   case IDC_DIR_LIST:
694      switch (pNMHDR->code)
695      {
696      case LVN_ENDLABELEDIT:
697         return Directories_OnEndLabelEdit(hDlg, pNMHDR);
698
699      case LVN_BEGINLABELEDIT:
700         return Directories_OnBeginLabelEdit(hDlg, pNMHDR);
701      }
702   }
703   return FALSE;
704}
705
706/**************************************************************************
707
708   Use the shell to select a Directory.
709
710 **************************************************************************/
711
712static int CALLBACK BrowseCallbackProc(HWND hwnd, UINT uMsg, LPARAM lParam, LPARAM lpData)
713{
714   /*
715      Called just after the dialog is initialized
716      Select the dir passed in BROWSEINFO.lParam
717   */
718   if (uMsg == BFFM_INITIALIZED)
719   {
720      if ((const char*)lpData != NULL)
721         SendMessage(hwnd, BFFM_SETSELECTION, TRUE, lpData);
722   }
723
724   return 0;
725}
726
727BOOL BrowseForDirectory(HWND hwnd, LPCTSTR pStartDir, TCHAR* pResult)
728{
729   BOOL      bResult = FALSE;
730   IMalloc*   piMalloc = 0;
731   BROWSEINFO   Info;
732   ITEMIDLIST* pItemIDList = NULL;
733   TCHAR      buf[MAX_PATH];
734   
735   if (!SUCCEEDED(SHGetMalloc(&piMalloc)))
736      return FALSE;
737
738   Info.hwndOwner      = hwnd;
739   Info.pidlRoot      = NULL;
740   Info.pszDisplayName = buf;
741   Info.lpszTitle      = TEXT("Directory name:");
742   Info.ulFlags      = BIF_RETURNONLYFSDIRS;
743   Info.lpfn         = BrowseCallbackProc;
744   Info.lParam       = (LPARAM)pStartDir;
745
746   pItemIDList = SHBrowseForFolder(&Info);
747
748   if (pItemIDList != NULL)
749   {
750      if (SHGetPathFromIDList(pItemIDList, buf) == TRUE)
751      {
752         _sntprintf(pResult, MAX_PATH, TEXT("%s"), buf);
753         bResult = TRUE;
754      }
755      IMalloc_Free(piMalloc, pItemIDList);
756   }
757   else
758   {
759      bResult = FALSE;
760   }
761
762   IMalloc_Release(piMalloc);
763   return bResult;
764}
765
766/**************************************************************************/
767
768
src/osd/windows/ui/datamap.h
r995r996
1//============================================================
2//
3//  datamap.c - Win32 dialog and options bridge code
4//
5//============================================================
6
7#ifndef _DATAMAP_H_
8#define _DATAMAP_H_
9
10#include "options.h"
11
12
13//============================================================
14//  TYPE DEFINITIONS
15//============================================================
16
17typedef enum _datamap_entry_type datamap_entry_type;
18enum _datamap_entry_type
19{
20   DM_NONE = 0,
21   DM_BOOL,
22   DM_INT,
23   DM_FLOAT,
24   DM_STRING
25};
26
27
28typedef enum _datamap_callback_type datamap_callback_type;
29enum _datamap_callback_type
30{
31   DCT_READ_CONTROL,
32   DCT_POPULATE_CONTROL,
33   DCT_UPDATE_STATUS,
34
35   DCT_COUNT
36};
37
38
39typedef struct _datamap datamap;
40typedef void (*datamap_callback)(datamap *map, HWND dialog, HWND control, core_options *opts, const char *option_name);
41typedef void (*get_option_name_callback)(datamap *map, HWND dialog, HWND control, char *buffer, size_t buffer_size);
42
43
44//============================================================
45//  PROTOTYPES
46//============================================================
47
48// datamap creation and disposal
49datamap *datamap_create(void);
50void datamap_free(datamap *map);
51
52// datamap setup
53void datamap_add(datamap *map, int dlgitem, datamap_entry_type type, const char *option_name);
54void datamap_set_callback(datamap *map, int dlgitem, datamap_callback_type callback_type, datamap_callback callback);
55void datamap_set_option_name_callback(datamap *map, int dlgitem, get_option_name_callback get_option_name);
56void datamap_set_trackbar_range(datamap *map, int dlgitem, float min, float max, float increments);
57void datamap_set_int_format(datamap *map, int dlgitem, const char *format);
58void datamap_set_float_format(datamap *map, int dlgitem, const char *format);
59
60// datamap operations
61BOOL datamap_read_control(datamap *map, HWND dialog, core_options *opts, int dlgitem);
62void datamap_read_all_controls(datamap *map, HWND dialog, core_options *opts);
63void datamap_populate_control(datamap *map, HWND dialog, core_options *opts, int dlgitem);
64void datamap_populate_all_controls(datamap *map, HWND dialog, core_options *opts);
65void datamap_update_control(datamap *map, HWND dialog, core_options *opts, int dlgitem);
66void datamap_update_all_controls(datamap *map, HWND dialog, core_options *opts);
67
68#endif // _DATAMAP_H_
src/osd/windows/ui/dijoystick.c
r995r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11 ***************************************************************************/
12
13/***************************************************************************
14
15  DIJoystick.c
16
17 ***************************************************************************/
18
19#define WIN32_LEAN_AND_MEAN
20#include <windows.h>
21#include <assert.h>
22#include <stdio.h>
23#include <math.h>
24#include <tchar.h>
25
26// undef WINNT for dinput.h to prevent duplicate definition
27#undef WINNT
28#undef DIRECTINPUT_VERSION
29#define DIRECTINPUT_VERSION 0x0700
30#include <dinput.h>
31
32#include "screenshot.h"
33#include "MAME32.h"
34#include "DirectInput.h"
35#include "DIJoystick.h"
36#include "M32Util.h"
37#include "dxdecode.h"
38
39/***************************************************************************
40    function prototypes
41 ***************************************************************************/
42
43static int  DIJoystick_init(void);
44static void DIJoystick_exit(void);
45static void DIJoystick_poll_joysticks(void);
46static int  DIJoystick_is_joy_pressed(int joycode);
47static BOOL DIJoystick_Available(void);
48
49static BOOL CALLBACK DIJoystick_EnumDeviceProc(LPDIDEVICEINSTANCE pdidi, LPVOID pv);
50
51/***************************************************************************
52    External variables
53 ***************************************************************************/
54
55struct OSDJoystick  DIJoystick =
56{
57   DIJoystick_init,                /* init              */
58   DIJoystick_exit,                /* exit              */
59   DIJoystick_is_joy_pressed,      /* joy_pressed       */
60   DIJoystick_poll_joysticks,      /* poll_joysticks    */
61   DIJoystick_Available,           /* Available         */
62};
63
64/***************************************************************************
65    Internal structures
66 ***************************************************************************/
67
68#define MAX_PHYSICAL_JOYSTICKS 20
69#define MAX_AXES               20
70
71typedef struct
72{
73   GUID guid;
74   TCHAR *name;
75
76   int offset; /* offset in dijoystate */
77} axis_type;
78
79typedef struct
80{
81   BOOL use_joystick;
82
83   GUID guidDevice;
84   TCHAR *name;
85
86   BOOL is_light_gun;
87
88   LPDIRECTINPUTDEVICE2 did;
89
90   DWORD num_axes;
91   axis_type axes[MAX_AXES];
92
93   DWORD num_pov;
94   DWORD num_buttons;
95
96   DIJOYSTATE dijs;
97
98} joystick_type;
99
100struct tDIJoystick_private
101{
102   int   use_count; /* the gui and game can both init/exit us, so keep track */
103   BOOL  m_bCoinSlot;
104
105   DWORD num_joysticks;
106   joystick_type joysticks[MAX_PHYSICAL_JOYSTICKS]; /* actual joystick data! */
107};
108
109/* internal functions needing our declarations */
110static BOOL CALLBACK DIJoystick_EnumAxisObjectsProc(LPCDIDEVICEOBJECTINSTANCE lpddoi, LPVOID pvRef);
111static BOOL CALLBACK DIJoystick_EnumPOVObjectsProc(LPCDIDEVICEOBJECTINSTANCE lpddoi, LPVOID pvRef);
112static BOOL CALLBACK DIJoystick_EnumButtonObjectsProc(LPCDIDEVICEOBJECTINSTANCE lpddoi, LPVOID pvRef);
113static void ClearJoyState(DIJOYSTATE *pdijs);
114
115static void InitJoystick(joystick_type *joystick);
116static void ExitJoystick(joystick_type *joystick);
117
118/***************************************************************************
119    Internal variables
120 ***************************************************************************/
121
122static struct tDIJoystick_private   This;
123
124static const GUID guidNULL = {0, 0, 0, {0, 0, 0, 0, 0, 0, 0, 0}};
125
126/***************************************************************************
127    External OSD functions 
128 ***************************************************************************/
129/*
130    put here anything you need to do when the program is started. Return 0 if
131    initialization was successful, nonzero otherwise.
132*/
133static int DIJoystick_init(void)
134{
135   DWORD i;
136   HRESULT hr;
137   LPDIRECTINPUT di = GetDirectInput();
138
139   This.use_count++;
140
141   This.num_joysticks = 0;
142
143   if (di == NULL)
144   {
145      ErrorMsg("DirectInput not initialized");
146      return 0;
147   }
148
149   /* enumerate for joystick devices */
150   hr = IDirectInput_EnumDevices(di, DIDEVTYPE_JOYSTICK,
151             (LPDIENUMDEVICESCALLBACK)DIJoystick_EnumDeviceProc,
152             NULL,
153             DIEDFL_ATTACHEDONLY  );
154   if (FAILED(hr))
155   {
156      ErrorMsg("DirectInput EnumDevices() failed: %s", DirectXDecodeError(hr));
157      return 0;
158   }
159
160   /* create each joystick device, enumerate each joystick for axes, etc */
161   for (i = 0; i < This.num_joysticks; i++)
162   {
163      InitJoystick(&This.joysticks[i]);
164   }
165
166   /* Are there any joysticks attached? */
167   if (This.num_joysticks < 1)
168   {
169      /*ErrorMsg("DirectInput EnumDevices didn't find any joysticks");*/
170      return 0;
171   }
172   
173   return 0;
174}
175
176/*
177   put here cleanup routines to be executed when the program is terminated.
178*/
179static void DIJoystick_exit(void)
180{
181   DWORD i;
182
183   This.use_count--;
184
185   if (This.use_count > 0)
186      return;
187
188   for (i = 0; i < This.num_joysticks; i++)
189      ExitJoystick(&This.joysticks[i]);
190   
191   This.num_joysticks = 0;
192}
193
194static void DIJoystick_poll_joysticks(void)
195{
196   HRESULT hr;
197   DWORD   i;
198   
199   This.m_bCoinSlot = 0;
200
201   for (i = 0; i < This.num_joysticks; i++)
202   {
203      /* start by clearing the structure, then fill it in if possible */
204
205      ClearJoyState(&This.joysticks[i].dijs);
206
207      if (This.joysticks[i].did == NULL)
208         continue;
209
210      if (This.joysticks[i].use_joystick == FALSE)
211         continue;
212
213      hr = IDirectInputDevice2_Poll(This.joysticks[i].did);
214
215      hr = IDirectInputDevice2_GetDeviceState(This.joysticks[i].did,sizeof(DIJOYSTATE),
216                                    &This.joysticks[i].dijs);
217      if (FAILED(hr))
218      {
219         if (hr == DIERR_INPUTLOST || hr == DIERR_NOTACQUIRED)
220         {
221            hr = IDirectInputDevice2_Acquire(This.joysticks[i].did);
222         }
223         continue;
224      }
225   }
226}
227
228/*
229   check if the DIJoystick is moved in the specified direction, defined in
230   osdepend.h. Return 0 if it is not pressed, nonzero otherwise.
231*/
232
233static int DIJoystick_is_joy_pressed(int joycode)
234{
235   int joy_num;
236   int stick;
237   int axis;
238   int dir;
239
240   DIJOYSTATE dijs;
241
242   int value;
243   int dz = 60;
244
245   joy_num = GET_JOYCODE_JOY(joycode);
246
247   /* do we have as many sticks? */
248   if (joy_num == 0 || This.num_joysticks < joy_num)
249      return 0;
250   joy_num--;
251   
252   if (This.joysticks[joy_num].use_joystick == FALSE)
253      return 0;
254
255   dijs = This.joysticks[joy_num].dijs;
256
257   stick = GET_JOYCODE_STICK(joycode);
258
259   if (stick == JOYCODE_STICK_BTN)
260   {
261      /* buttons */
262      int button;
263
264      button = GET_JOYCODE_BUTTON(joycode);
265      button--;
266
267      if (button >= This.joysticks[joy_num].num_buttons
268      ||   GET_JOYCODE_DIR(joycode) != JOYCODE_DIR_BTN)
269         return 0;
270
271      return dijs.rgbButtons[button] != 0;
272   }
273
274   if (stick == JOYCODE_STICK_POV)
275   {
276      /* POV */
277      int pov_value;
278      int angle;
279      int axis_value;
280
281      int num_pov = GET_JOYCODE_BUTTON(joycode) / 4;
282      int code   = GET_JOYCODE_BUTTON(joycode) % 4;
283      axis = code / 2;
284      dir  = code % 2;
285
286      if (num_pov >= This.joysticks[joy_num].num_pov)
287         return 0;
288
289      pov_value = dijs.rgdwPOV[num_pov];
290      if (LOWORD(pov_value) == 0xffff)
291         return 0;
292
293      angle = (pov_value + 27000) % 36000;
294      angle = (36000 - angle) % 36000;
295      angle /= 100;
296
297      /* angle is now in degrees counterclockwise from x axis*/
298      if (axis == 1)
299         axis_value = 128 + (int)(127 * cos(2 * M_PI * angle / 360.0)); /* x */
300      else
301         axis_value = 128 + (int)(127 * sin(2 * M_PI * angle / 360.0)); /* y */
302
303      if (dir == 1)
304         return axis_value <= (128 - 128 * dz / 100);
305      else
306         return axis_value >= (128 + 128 * dz / 100);
307   }
308
309   /* sticks */
310   
311   axis = GET_JOYCODE_AXIS(joycode);
312   dir  = GET_JOYCODE_DIR(joycode);
313   
314   if (axis == 0 || This.joysticks[joy_num].num_axes < axis)
315      return 0;
316   axis--;
317
318   value = *(int *)(((byte *)&dijs) + This.joysticks[joy_num].axes[axis].offset);
319
320   if (dir == JOYCODE_DIR_NEG)
321      return value <= (128 - 128 * dz / 100);
322   else
323      return value >= (128 + 128 * dz / 100);
324}
325
326static BOOL DIJoystick_Available(void)
327{
328   static BOOL bBeenHere = FALSE;
329   static BOOL bAvailable = FALSE;
330   HRESULT    hr;
331   GUID      guidDevice = guidNULL;
332   LPDIRECTINPUTDEVICE didTemp;
333   LPDIRECTINPUTDEVICE didJoystick;
334   LPDIRECTINPUT di = GetDirectInput();
335
336   if (di == NULL)
337   {
338      return FALSE;
339   }
340
341   if (bBeenHere == FALSE)
342      bBeenHere = TRUE;
343   else
344      return bAvailable;
345
346   /* enumerate for joystick devices */
347   hr = IDirectInput_EnumDevices(di, DIDEVTYPE_JOYSTICK,
348                          inputEnumDeviceProc,
349                          &guidDevice,
350                          DIEDFL_ATTACHEDONLY);
351   if (FAILED(hr))
352   {
353      return FALSE;
354   }
355
356   /* Are there any joysticks attached? */
357   if (IsEqualGUID(&guidDevice, &guidNULL))
358   {
359      return FALSE;
360   }
361
362   hr = IDirectInput_CreateDevice(di, &guidDevice, &didTemp, NULL);
363   if (FAILED(hr))
364   {
365      return FALSE;
366   }
367
368   /* Determine if DX5 is available by a QI for a DX5 interface. */
369   hr = IDirectInputDevice_QueryInterface(didTemp,
370                                 &IID_IDirectInputDevice2,
371                                 (void**)&didJoystick);
372   if (FAILED(hr))
373   {
374      bAvailable = FALSE;
375   }
376   else
377   {
378      bAvailable = TRUE;
379      IDirectInputDevice_Release(didJoystick);
380   }
381
382   /* dispose of the temp interface */
383   IDirectInputDevice_Release(didTemp);
384
385   return bAvailable;
386}
387
388int DIJoystick_GetNumPhysicalJoysticks()
389{
390   return This.num_joysticks;
391}
392
393TCHAR* DIJoystick_GetPhysicalJoystickName(int num_joystick)
394{
395   return This.joysticks[num_joystick].name;
396}
397
398int DIJoystick_GetNumPhysicalJoystickAxes(int num_joystick)
399{
400   return This.joysticks[num_joystick].num_axes;
401}
402
403TCHAR* DIJoystick_GetPhysicalJoystickAxisName(int num_joystick, int num_axis)
404{
405   return This.joysticks[num_joystick].axes[num_axis].name;
406}
407
408/***************************************************************************
409   Internal functions
410 ***************************************************************************/
411
412BOOL CALLBACK DIJoystick_EnumDeviceProc(LPDIDEVICEINSTANCE pdidi, LPVOID pv)
413{
414   TCHAR buffer[5000];
415
416   This.joysticks[This.num_joysticks].guidDevice = pdidi->guidInstance;
417
418   _stprintf(buffer, TEXT("%s (%s)"), pdidi->tszProductName, pdidi->tszInstanceName);
419   This.joysticks[This.num_joysticks].name = (TCHAR *)malloc((_tcslen(buffer) + 1) * sizeof(TCHAR));
420   _tcscpy(This.joysticks[This.num_joysticks].name, buffer);
421
422   This.num_joysticks++;
423
424   return DIENUM_CONTINUE;
425   }
426
427static BOOL CALLBACK DIJoystick_EnumAxisObjectsProc(LPCDIDEVICEOBJECTINSTANCE lpddoi,
428                                       LPVOID pvRef)
429{
430   joystick_type* joystick = (joystick_type*)pvRef;
431   DIPROPRANGE diprg;
432   HRESULT hr;
433
434   joystick->axes[joystick->num_axes].guid = lpddoi->guidType;
435
436   joystick->axes[joystick->num_axes].name = (TCHAR *)malloc((_tcslen(lpddoi->tszName) + 1) * sizeof(TCHAR));
437   _tcscpy(joystick->axes[joystick->num_axes].name, lpddoi->tszName);
438
439   joystick->axes[joystick->num_axes].offset = lpddoi->dwOfs;
440
441   /*ErrorMsg("got axis %s, offset %i",lpddoi->tszName, lpddoi->dwOfs);*/
442
443   diprg.diph.dwSize      = sizeof(diprg);
444   diprg.diph.dwHeaderSize = sizeof(diprg.diph);
445   diprg.diph.dwObj      = lpddoi->dwOfs;
446   diprg.diph.dwHow      = DIPH_BYOFFSET;
447   diprg.lMin            = 0;
448   diprg.lMax            = 255;
449
450   hr = IDirectInputDevice2_SetProperty(joystick->did, DIPROP_RANGE, &diprg.diph);
451   if (FAILED(hr)) /* if this fails, don't use this axis */
452   {
453      free(joystick->axes[joystick->num_axes].name);
454      joystick->axes[joystick->num_axes].name = NULL;
455      return DIENUM_CONTINUE;
456   }
457
458#ifdef JOY_DEBUG
459   if (FAILED(hr))
460   {
461      ErrorMsg("DirectInput SetProperty() joystick axis %s failed - %s\n",
462             joystick->axes[joystick->num_axes].name,
463             DirectXDecodeError(hr));
464   }
465#endif
466   
467   /* Set axis dead zone to 0; we need accurate #'s for analog joystick reading. */
468
469   hr = SetDIDwordProperty(joystick->did, DIPROP_DEADZONE, lpddoi->dwOfs, DIPH_BYOFFSET, 0);
470
471#ifdef JOY_DEBUG
472   if (FAILED(hr))
473   {
474      ErrorMsg("DirectInput SetProperty() joystick axis %s dead zone failed - %s\n",
475             joystick->axes[joystick->num_axes].name,
476             DirectXDecodeError(hr));
477   }
478#endif
479
480   joystick->num_axes++;
481
482   return DIENUM_CONTINUE;
483}
484
485static BOOL CALLBACK DIJoystick_EnumPOVObjectsProc(LPCDIDEVICEOBJECTINSTANCE lpddoi, LPVOID pvRef)
486{
487   joystick_type* joystick = (joystick_type*)pvRef;
488   joystick->num_pov++;
489
490   return DIENUM_CONTINUE;
491}
492
493static BOOL CALLBACK DIJoystick_EnumButtonObjectsProc(LPCDIDEVICEOBJECTINSTANCE lpddoi, LPVOID pvRef)
494{
495   joystick_type* joystick = (joystick_type*)pvRef;
496   joystick->num_buttons++;
497
498   return DIENUM_CONTINUE;
499}
500
501static void ClearJoyState(DIJOYSTATE *pdijs)
502{
503   memset(pdijs, 0, sizeof(DIJOYSTATE));
504   pdijs->lX         = 128;
505   pdijs->lY         = 128;
506   pdijs->lZ         = 128;
507   pdijs->lRx         = 128;
508   pdijs->lRy         = 128;
509   pdijs->lRz         = 128;
510   pdijs->rglSlider[0] = 128;
511   pdijs->rglSlider[1] = 128;
512   pdijs->rgdwPOV[0]   = -1;
513   pdijs->rgdwPOV[1]   = -1;
514   pdijs->rgdwPOV[2]   = -1;
515   pdijs->rgdwPOV[3]   = -1;
516}
517
518static void InitJoystick(joystick_type *joystick)
519{
520   LPDIRECTINPUTDEVICE didTemp;
521   HRESULT hr;
522   LPDIRECTINPUT di = GetDirectInput();
523
524   joystick->use_joystick = FALSE;
525
526   joystick->did      = NULL;
527   joystick->num_axes = 0;
528
529   joystick->is_light_gun = (_tcscmp(joystick->name, TEXT("ACT LABS GS (ACT LABS GS)")) == 0);
530
531   /* get a did1 interface first... */
532   hr = IDirectInput_CreateDevice(di, &joystick->guidDevice, &didTemp, NULL);
533   if (FAILED(hr))
534   {
535      ErrorMsg("DirectInput CreateDevice() joystick failed: %s\n", DirectXDecodeError(hr));
536      return;
537   }
538   
539   /* get a did2 interface to work with polling (most) joysticks */
540   hr = IDirectInputDevice_QueryInterface(didTemp,
541                                 &IID_IDirectInputDevice2,
542                                 (void**)&joystick->did);
543
544   /* dispose of the temp interface */
545   IDirectInputDevice_Release(didTemp);
546
547   /* check result of getting the did2 */
548   if (FAILED(hr))
549   {
550      /* no error message because this happens in dx3 */
551      /* ErrorMsg("DirectInput QueryInterface joystick failed\n"); */
552      joystick->did = NULL;
553      return;
554   }
555
556   
557   hr = IDirectInputDevice2_SetCooperativeLevel(joystick->did, GetMainWindow(),
558                                     DISCL_NONEXCLUSIVE | DISCL_BACKGROUND);
559   if (FAILED(hr))
560   {
561      ErrorMsg("DirectInput SetCooperativeLevel() joystick failed: %s\n", DirectXDecodeError(hr));
562      return;
563   }
564
565
566   hr = IDirectInputDevice2_SetDataFormat(joystick->did, &c_dfDIJoystick);
567   if (FAILED(hr))
568   {
569      ErrorMsg("DirectInput SetDataFormat() joystick failed: %s\n", DirectXDecodeError(hr));
570      return;
571   }
572
573   if (joystick->is_light_gun)
574   {
575      /* setup light gun to report raw screen pixel data */
576
577      DIPROPDWORD diprop;
578      memset(&diprop, 0, sizeof(diprop));
579      diprop.diph.dwSize       = sizeof(DIPROPDWORD);
580      diprop.diph.dwHeaderSize = sizeof(DIPROPHEADER);
581      diprop.diph.dwObj       = 0;
582      diprop.diph.dwHow       = DIPH_DEVICE;
583      diprop.dwData          = DIPROPCALIBRATIONMODE_RAW;
584
585      IDirectInputDevice2_SetProperty(joystick->did, DIPROP_CALIBRATIONMODE, &diprop.diph);
586   }
587   else
588   {
589      /* enumerate our axes */
590      hr = IDirectInputDevice_EnumObjects(joystick->did,
591                                 DIJoystick_EnumAxisObjectsProc,
592                                 joystick,
593                                 DIDFT_AXIS);
594      if (FAILED(hr))
595      {
596         ErrorMsg("DirectInput EnumObjects() Axes failed: %s\n", DirectXDecodeError(hr));
597         return;
598      }
599
600      /* enumerate our POV hats */
601      joystick->num_pov = 0;
602      hr = IDirectInputDevice_EnumObjects(joystick->did,
603                                 DIJoystick_EnumPOVObjectsProc,
604                                 joystick,
605                                 DIDFT_POV);
606      if (FAILED(hr))
607      {
608         ErrorMsg("DirectInput EnumObjects() POVs failed: %s\n", DirectXDecodeError(hr));
609         return;
610      }
611   }
612
613   /* enumerate our buttons */
614
615   joystick->num_buttons = 0;
616   hr = IDirectInputDevice_EnumObjects(joystick->did,
617                              DIJoystick_EnumButtonObjectsProc,
618                              joystick,
619                              DIDFT_BUTTON);
620   if (FAILED(hr))
621   {
622      ErrorMsg("DirectInput EnumObjects() Buttons failed: %s\n", DirectXDecodeError(hr));
623      return;
624   }
625
626   hr = IDirectInputDevice2_Acquire(joystick->did);
627   if (FAILED(hr))
628   {
629      ErrorMsg("DirectInputDevice Acquire joystick failed!\n");
630      return;
631   }
632
633   /* start by clearing the structures */
634
635   ClearJoyState(&joystick->dijs);
636
637   joystick->use_joystick = TRUE;
638}
639
640static void ExitJoystick(joystick_type *joystick)
641{
642   DWORD i;
643   
644   if (joystick->did != NULL)
645   {
646      IDirectInputDevice_Unacquire(joystick->did);
647      IDirectInputDevice_Release(joystick->did);
648      joystick->did = NULL;
649   }
650   
651   for (i = 0; i < joystick->num_axes; i++)
652   {
653      if (joystick->axes[i].name)
654         free(joystick->axes[i].name);
655      joystick->axes[i].name = NULL;
656   }
657   
658   if (joystick->name != NULL)
659   {
660      free(joystick->name);
661      joystick->name = NULL;
662   }
663}
664
src/osd/windows/ui/picker.c
r995r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11 ***************************************************************************/
12
13#define WIN32_LEAN_AND_MEAN
14#define _WIN32_IE 0x0500
15#include <windows.h>
16#include <windowsx.h>
17#include <shellapi.h>
18#include <stdio.h>
19#include <ctype.h>
20#include <commctrl.h>
21#include <commdlg.h>
22#include <string.h>
23#include <sys/stat.h>
24#include <wingdi.h>
25#include <time.h>
26#include <tchar.h>
27
28#include "picker.h"
29#include "resource.h"
30#include "screenshot.h"
31#include "win32ui.h"
32#include "bitmask.h"
33#include "m32util.h"
34#include "m32opts.h"
35
36
37// fix warning: cast does not match function type
38#if defined(__GNUC__) && defined(ListView_GetHeader)
39#undef ListView_GetHeader
40#endif
41#if defined(__GNUC__) && defined(ListView_GetImageList)
42#undef ListView_GetImageList
43#undef ListView_GetItemRect
44#endif
45
46#ifndef ListView_GetItemRect
47#define ListView_GetItemRect(w,i,p,c) \
48   (BOOL)SNDMSG((w),LVM_GETITEMRECT,i,((p != NULL)?(((LPRECT)(p))->left=(c),(LPARAM)(LPRECT)(p)):0))
49#endif
50
51#ifndef ListView_GetImageList
52#define ListView_GetImageList(w,i) (HIMAGELIST)(LRESULT)(int)SendMessage((w),LVM_GETIMAGELIST,(i),0)
53#endif // ListView_GetImageList
54
55#ifndef ListView_GetHeader
56#define ListView_GetHeader(w) (HWND)(LRESULT)(int)SNDMSG((w),LVM_GETHEADER,0,0)
57#endif // ListView_GetHeader
58
59#ifndef HDM_SETIMAGELIST
60#define HDM_SETIMAGELIST        (HDM_FIRST + 8)
61#endif // HDM_SETIMAGELIST
62
63#ifndef Header_SetImageList
64#define Header_SetImageList(h,i) (HIMAGELIST)(LRESULT)(int)SNDMSG((h), HDM_SETIMAGELIST, 0, (LPARAM)i)
65#endif // Header_SetImageList
66
67#ifndef HDF_SORTUP
68#define HDF_SORTUP 0x400
69#endif
70
71#ifndef HDF_SORTDOWN
72#define HDF_SORTDOWN 0x200
73#endif
74
75
76
77struct PickerInfo
78{
79   const struct PickerCallbacks *pCallbacks;
80   WNDPROC pfnParentWndProc;
81   int nCurrentViewID;
82   int nLastItem;
83   int nColumnCount;
84   int *pnColumnsShown;
85   int *pnColumnsOrder;
86   UINT_PTR nTimer;
87   LPCTSTR *ppszColumnNames;
88};
89
90
91static struct PickerInfo *GetPickerInfo(HWND hWnd)
92{
93   LONG_PTR l;
94   l = GetWindowLongPtr(hWnd, GWLP_USERDATA);
95   return (struct PickerInfo *) l;
96}
97
98
99
100static LRESULT CallParentWndProc(WNDPROC pfnParentWndProc,
101   HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
102{
103   LRESULT rc;
104
105   if (!pfnParentWndProc)
106      pfnParentWndProc = GetPickerInfo(hWnd)->pfnParentWndProc;
107
108   if (IsWindowUnicode(hWnd))
109      rc = CallWindowProcW(pfnParentWndProc, hWnd, message, wParam, lParam);
110   else
111      rc = CallWindowProcA(pfnParentWndProc, hWnd, message, wParam, lParam);
112   return rc;
113}
114
115static BOOL ListViewOnErase(HWND hWnd, HDC hDC)
116{
117   RECT      rcClient;
118   HRGN      rgnBitmap;
119   HPALETTE   hPAL;
120
121   int       i, j;
122   HDC       htempDC;
123   POINT      ptOrigin;
124   POINT      pt = {0,0};
125   HBITMAP    hOldBitmap;
126   MYBITMAPINFO *pbmDesc = GetBackgroundInfo();
127   HBITMAP      hBackground = GetBackgroundBitmap();
128   HPALETTE   hPALbg = GetBackgroundPalette();
129
130   // this does not draw the background properly in report view
131
132   GetClientRect(hWnd, &rcClient);
133
134   htempDC = CreateCompatibleDC(hDC);
135   hOldBitmap = SelectObject(htempDC, hBackground);
136
137   rgnBitmap = CreateRectRgnIndirect(&rcClient);
138   SelectClipRgn(hDC, rgnBitmap);
139   DeleteObject(rgnBitmap);
140
141   hPAL = (!hPALbg) ? CreateHalftonePalette(hDC) : hPALbg;
142
143   if (GetDeviceCaps(htempDC, RASTERCAPS) & RC_PALETTE && hPAL != NULL)
144   {
145      SelectPalette(htempDC, hPAL, FALSE);
146      RealizePalette(htempDC);
147   }
148
149   // Get x and y offset
150   MapWindowPoints(hWnd, GetTreeView(), &pt, 1);
151   GetDCOrgEx(hDC, &ptOrigin);
152   ptOrigin.x -= pt.x;
153   ptOrigin.y -= pt.y;
154   ptOrigin.x = -GetScrollPos(hWnd, SB_HORZ);
155   ptOrigin.y = -GetScrollPos(hWnd, SB_VERT);
156
157   if (pbmDesc->bmWidth && pbmDesc->bmHeight)
158   {
159      for (i = ptOrigin.x; i < rcClient.right; i += pbmDesc->bmWidth)
160         for (j = ptOrigin.y; j < rcClient.bottom; j += pbmDesc->bmHeight)
161            BitBlt(hDC, i, j, pbmDesc->bmWidth, pbmDesc->bmHeight, htempDC, 0, 0, SRCCOPY);
162   }
163
164   SelectObject(htempDC, hOldBitmap);
165   DeleteDC(htempDC);
166
167   if (!pbmDesc->bmColors)
168   {
169      DeleteObject(hPAL);
170      hPAL = 0;
171   }
172
173   return TRUE;
174}
175
176
177
178static BOOL ListViewNotify(HWND hWnd, LPNMHDR lpNmHdr)
179{
180   RECT rcClient;
181   DWORD dwPos;
182   POINT pt;
183
184   // This code is for using bitmap in the background
185   // Invalidate the right side of the control when a column is resized         
186   if (lpNmHdr->code == HDN_ITEMCHANGINGA || lpNmHdr->code == HDN_ITEMCHANGINGW)
187   {
188      dwPos = GetMessagePos();
189      pt.x = LOWORD(dwPos);
190      pt.y = HIWORD(dwPos);
191
192      GetClientRect(hWnd, &rcClient);
193      ScreenToClient(hWnd, &pt);
194      rcClient.left = pt.x;
195      InvalidateRect(hWnd, &rcClient, FALSE);
196   }
197   return FALSE;
198}
199
200
201
202static BOOL ListViewContextMenu(HWND hwndPicker, LPARAM lParam)
203{
204   struct PickerInfo *pPickerInfo;
205   POINT pt, headerPt;
206   int i, nViewID, nColumn = -1;
207   HWND hwndHeader;
208   RECT rcCol;
209
210   pPickerInfo = GetPickerInfo(hwndPicker);
211
212   // Extract the point out of the lparam
213   pt.x = GET_X_LPARAM(lParam);
214   pt.y = GET_Y_LPARAM(lParam);
215   if (pt.x < 0 && pt.y < 0)
216      GetCursorPos(&pt);
217
218   // Figure out which header column was clicked, if at all
219   nViewID = Picker_GetViewID(hwndPicker);
220   if ((nViewID == VIEW_REPORT) || (nViewID == VIEW_GROUPED))
221   {
222      hwndHeader = ListView_GetHeader(hwndPicker);
223      headerPt = pt;
224      ScreenToClient(hwndHeader, &headerPt);
225
226      for (i = 0; Header_GetItemRect(hwndHeader, i, &rcCol); i++)
227      {
228         if (PtInRect(&rcCol, headerPt))
229         {
230            nColumn = i;
231            break;
232         }
233      }
234   }
235
236   if (nColumn >= 0)
237   {
238      // A column header was clicked
239      if (pPickerInfo->pCallbacks->pfnOnHeaderContextMenu)
240         pPickerInfo->pCallbacks->pfnOnHeaderContextMenu(pt, nColumn);
241   }
242   else
243   {
244      // The body was clicked
245      if (pPickerInfo->pCallbacks->pfnOnBodyContextMenu)
246         pPickerInfo->pCallbacks->pfnOnBodyContextMenu(pt);
247   }
248   return TRUE;
249}
250
251
252
253static void Picker_Free(struct PickerInfo *pPickerInfo)
254{
255   // Free up all resources associated with this picker structure
256   if (pPickerInfo->pnColumnsShown)
257      free(pPickerInfo->pnColumnsShown);
258   if (pPickerInfo->pnColumnsOrder)
259      free(pPickerInfo->pnColumnsOrder);
260   free(pPickerInfo);
261}
262
263
264
265static LRESULT CALLBACK ListViewWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
266{
267   struct PickerInfo *pPickerInfo;
268   LRESULT rc = 0;
269   BOOL bHandled = FALSE;
270   WNDPROC pfnParentWndProc;
271   HWND hwndHeaderCtrl  = NULL;
272   HFONT hHeaderCtrlFont = NULL;
273
274   pPickerInfo = GetPickerInfo(hWnd);
275   pfnParentWndProc = pPickerInfo->pfnParentWndProc;
276
277   switch(message)
278   {
279       case WM_MOUSEMOVE:
280         if (MouseHasBeenMoved())
281            ShowCursor(TRUE);
282         break;
283
284      case WM_ERASEBKGND:
285         if (GetBackgroundBitmap())
286         {
287            rc = ListViewOnErase(hWnd, (HDC) wParam);
288            bHandled = TRUE;
289         }
290         break;
291
292      case WM_NOTIFY:
293         bHandled = ListViewNotify(hWnd, (LPNMHDR) lParam);
294         break;
295
296      case WM_SETFONT:
297         hwndHeaderCtrl = ListView_GetHeader(hWnd);
298         if (hwndHeaderCtrl)
299            hHeaderCtrlFont = GetWindowFont(hwndHeaderCtrl);
300         break;
301
302      case WM_CONTEXTMENU:
303         bHandled = ListViewContextMenu(hWnd, lParam);
304         break;
305
306      case WM_DESTROY:
307         // Received WM_DESTROY; time to clean up
308         if (pPickerInfo->pCallbacks->pfnSetViewMode)
309            pPickerInfo->pCallbacks->pfnSetViewMode(pPickerInfo->nCurrentViewID);
310         Picker_Free(pPickerInfo);
311         SetWindowLongPtr(hWnd, GWLP_WNDPROC, (LONG_PTR) pfnParentWndProc);
312         SetWindowLongPtr(hWnd, GWLP_USERDATA, (LONG_PTR) NULL);
313         break;
314   }
315
316   if (!bHandled)
317      rc = CallParentWndProc(pfnParentWndProc, hWnd, message, wParam, lParam);
318
319    // If we received WM_SETFONT, reset header ctrl font back to original font
320   if (hwndHeaderCtrl)
321      SetWindowFont(hwndHeaderCtrl, hHeaderCtrlFont, TRUE);
322
323   return rc;
324}
325
326
327
328// Re/initialize the ListControl Columns
329static void Picker_InternalResetColumnDisplay(HWND hWnd, BOOL bFirstTime)
330{
331   LV_COLUMN   lvc;
332   int         i;
333   int         nColumn;
334   int         *widths;
335   int         *order;
336   int         *shown;
337   int shown_columns;
338   LVCOLUMN col;
339   struct PickerInfo *pPickerInfo;
340
341   pPickerInfo = GetPickerInfo(hWnd);
342
343   widths = malloc(pPickerInfo->nColumnCount * sizeof(*widths));
344   order = malloc(pPickerInfo->nColumnCount * sizeof(*order));
345   shown = malloc(pPickerInfo->nColumnCount * sizeof(*shown));
346   if (!widths || !order || !shown)
347      goto done;
348
349   memset(widths, 0, pPickerInfo->nColumnCount * sizeof(*widths));
350   memset(order, 0, pPickerInfo->nColumnCount * sizeof(*order));
351   memset(shown, 0, pPickerInfo->nColumnCount * sizeof(*shown));
352   pPickerInfo->pCallbacks->pfnGetColumnWidths(widths);
353   pPickerInfo->pCallbacks->pfnGetColumnOrder(order);
354   pPickerInfo->pCallbacks->pfnGetColumnShown(shown);
355
356   if (!bFirstTime)
357   {
358      DWORD style = GetWindowLong(hWnd, GWL_STYLE);
359
360      // switch the list view to LVS_REPORT style so column widths reported correctly
361      SetWindowLong(hWnd, GWL_STYLE,
362                 (GetWindowLong(hWnd, GWL_STYLE) & ~LVS_TYPEMASK) | LVS_REPORT);
363
364      // Retrieve each of the column widths
365      i = 0;
366      memset(&col, 0, sizeof(col));
367      col.mask = LVCF_WIDTH;
368      while(ListView_GetColumn(hWnd, 0, &col))
369      {
370         nColumn = Picker_GetRealColumnFromViewColumn(hWnd, i++);
371         widths[nColumn] = col.cx;
372         ListView_DeleteColumn(hWnd, 0);
373      }
374
375      pPickerInfo->pCallbacks->pfnSetColumnWidths(widths);
376
377      // restore old style
378      SetWindowLong(hWnd, GWL_STYLE, style);
379   }
380
381   nColumn = 0;
382   for (i = 0; i < pPickerInfo->nColumnCount; i++)
383   {
384      if (shown[order[i]])
385      {
386         lvc.mask = LVCF_FMT | LVCF_WIDTH | LVCF_SUBITEM | LVCF_TEXT;
387         lvc.pszText = (LPTSTR) pPickerInfo->ppszColumnNames[order[i]];
388         lvc.iSubItem = nColumn;
389         lvc.cx = widths[order[i]];
390         lvc.fmt = LVCFMT_LEFT;
391         ListView_InsertColumn(hWnd, nColumn, &lvc);
392         pPickerInfo->pnColumnsOrder[nColumn] = order[i];
393
394         dprintf("Visible column %d: Logical column %d; Width=%d\n", nColumn, order[i], widths[order[i]]);
395
396         nColumn++;
397      }
398   }
399
400   shown_columns = nColumn;
401
402   /* Fill this in so we can still sort on columns NOT shown */
403   for (i = 0; i < pPickerInfo->nColumnCount && nColumn < pPickerInfo->nColumnCount; i++)
404   {
405      if (!shown[order[i]])
406      {
407         pPickerInfo->pnColumnsOrder[nColumn] = order[i];
408         nColumn++;
409      }
410   }
411
412   if (GetListFontColor() == RGB(255, 255, 255))
413      ListView_SetTextColor(hWnd, RGB(240, 240, 240));
414   else
415      ListView_SetTextColor(hWnd, GetListFontColor());
416
417done:     
418   if (widths)
419      free(widths);
420   if (order)
421      free(order);
422   if (shown)
423      free(shown);
424}
425
426
427
428void Picker_ResetColumnDisplay(HWND hWnd)
429{
430   Picker_InternalResetColumnDisplay(hWnd, FALSE);
431}
432
433
434
435void Picker_ClearIdle(HWND hwndPicker)
436{
437   struct PickerInfo *pPickerInfo;
438
439   pPickerInfo = GetPickerInfo(hwndPicker);
440   if (pPickerInfo->nTimer)
441   {
442      KillTimer(hwndPicker, 0);
443      pPickerInfo->nTimer = 0;
444   }
445}
446
447
448
449static void CALLBACK Picker_TimerProc(HWND hwndPicker, UINT uMsg,
450  UINT_PTR idEvent, DWORD dwTime)
451{
452   struct PickerInfo *pPickerInfo;
453   BOOL bContinueIdle;
454   DWORD nTickCount, nBaseTickCount;
455   DWORD nMaxIdleTicks = 50;
456
457   pPickerInfo = GetPickerInfo(hwndPicker);
458   bContinueIdle = FALSE;
459   nBaseTickCount = GetTickCount();
460
461   // This idle procedure will loop until either idling is over, or until
462   // a specified amount of time elapses (in this case, 50ms).  This frees
463   // idle callbacks of any responsibility for balancing their workloads; the
464   // picker code will
465   do
466   {
467      if (pPickerInfo->pCallbacks->pfnOnIdle)
468         bContinueIdle = pPickerInfo->pCallbacks->pfnOnIdle(hwndPicker);
469      nTickCount = GetTickCount();
470   }
471   while(bContinueIdle && ((nTickCount - nBaseTickCount) < nMaxIdleTicks));
472
473   if (!bContinueIdle)
474      Picker_ClearIdle(hwndPicker);
475}
476
477
478
479// Instructs this picker to reset idling; idling will continue until the
480// idle function returns FALSE
481void Picker_ResetIdle(HWND hwndPicker)
482{
483   struct PickerInfo *pPickerInfo;
484
485   pPickerInfo = GetPickerInfo(hwndPicker);
486
487   Picker_ClearIdle(hwndPicker);
488   if (pPickerInfo->pCallbacks->pfnOnIdle)
489      pPickerInfo->nTimer = SetTimer(hwndPicker, 0, 0, Picker_TimerProc);
490}
491
492
493
494BOOL Picker_IsIdling(HWND hwndPicker)
495{
496   struct PickerInfo *pPickerInfo;
497   pPickerInfo = GetPickerInfo(hwndPicker);
498   return pPickerInfo->nTimer != 0;
499}
500
501
502
503BOOL SetupPicker(HWND hwndPicker, const struct PickerOptions *pOptions)
504{
505   struct PickerInfo *pPickerInfo;
506   int i;
507   LONG_PTR l;
508
509   assert(hwndPicker);
510
511   // Allocate the list view struct
512   pPickerInfo = (struct PickerInfo *) malloc(sizeof(struct PickerInfo));
513   if (!pPickerInfo)
514      return FALSE;
515
516   // And fill it out
517   memset(pPickerInfo, 0, sizeof(*pPickerInfo));
518   pPickerInfo->pCallbacks = pOptions->pCallbacks;
519   pPickerInfo->nColumnCount = pOptions->nColumnCount;
520   pPickerInfo->ppszColumnNames = pOptions->ppszColumnNames;
521   pPickerInfo->nLastItem = -1;
522
523   if (pPickerInfo->nColumnCount)
524   {
525      // Allocate space for the column order and columns shown array
526      pPickerInfo->pnColumnsOrder = malloc(pPickerInfo->nColumnCount *
527         sizeof(*pPickerInfo->pnColumnsOrder));
528      pPickerInfo->pnColumnsShown = malloc(pPickerInfo->nColumnCount *
529         sizeof(*pPickerInfo->pnColumnsShown));
530      if (!pPickerInfo->pnColumnsOrder || !pPickerInfo->pnColumnsShown)
531         goto error;
532
533      // set up initial values
534      for (i = 0; i < pPickerInfo->nColumnCount; i++)
535      {
536         pPickerInfo->pnColumnsOrder[i] = i;
537         pPickerInfo->pnColumnsShown[i] = TRUE;
538      }
539
540      if (GetUseOldControl())
541      {
542         if (pPickerInfo->pCallbacks->pfnSetColumnOrder)
543            pPickerInfo->pCallbacks->pfnSetColumnOrder(pPickerInfo->pnColumnsOrder);
544         if (pPickerInfo->pCallbacks->pfnSetColumnShown)
545            pPickerInfo->pCallbacks->pfnSetColumnShown(pPickerInfo->pnColumnsShown);
546      }
547      else
548      {
549         if (pPickerInfo->pCallbacks->pfnGetColumnOrder)
550            pPickerInfo->pCallbacks->pfnGetColumnOrder(pPickerInfo->pnColumnsOrder);
551         if (pPickerInfo->pCallbacks->pfnGetColumnShown)
552            pPickerInfo->pCallbacks->pfnGetColumnShown(pPickerInfo->pnColumnsShown);
553      }
554   }
555
556   // Hook in our wndproc and userdata pointer
557   l = GetWindowLongPtr(hwndPicker, GWLP_WNDPROC);
558   pPickerInfo->pfnParentWndProc = (WNDPROC) l;
559   SetWindowLongPtr(hwndPicker, GWLP_USERDATA, (LONG_PTR) pPickerInfo);
560   SetWindowLongPtr(hwndPicker, GWLP_WNDPROC, (LONG_PTR) ListViewWndProc);
561
562   ListView_SetExtendedListViewStyle(hwndPicker, LVS_EX_FULLROWSELECT | LVS_EX_HEADERDRAGDROP |
563      LVS_EX_UNDERLINEHOT | LVS_EX_UNDERLINECOLD | LVS_EX_LABELTIP);
564
565   Picker_InternalResetColumnDisplay(hwndPicker, TRUE);
566   Picker_ResetIdle(hwndPicker);
567   return TRUE;
568
569error:
570   if (pPickerInfo)
571      Picker_Free(pPickerInfo);
572   return FALSE;
573}
574
575
576
577int Picker_GetViewID(HWND hwndPicker)
578{
579   struct PickerInfo *pPickerInfo;
580   pPickerInfo = GetPickerInfo(hwndPicker);
581   return pPickerInfo->nCurrentViewID;
582}
583
584
585
586void Picker_SetViewID(HWND hwndPicker, int nViewID)
587{
588   struct PickerInfo *pPickerInfo;
589   LONG_PTR nListViewStyle;
590   DWORD dwStyle;
591
592   pPickerInfo = GetPickerInfo(hwndPicker);
593
594   // Change the nCurrentViewID member
595   pPickerInfo->nCurrentViewID = nViewID;
596   if (pPickerInfo->pCallbacks->pfnSetViewMode)
597      pPickerInfo->pCallbacks->pfnSetViewMode(pPickerInfo->nCurrentViewID);
598
599   // Change the ListView flags in accordance
600   switch(nViewID)
601   {
602      case VIEW_LARGE_ICONS:
603         nListViewStyle = LVS_ICON;
604         break;
605      case VIEW_SMALL_ICONS:
606         nListViewStyle = LVS_SMALLICON;
607         break;
608      case VIEW_INLIST:
609         nListViewStyle = LVS_LIST;
610         break;
611      case VIEW_GROUPED:
612      case VIEW_REPORT:
613      default:
614         nListViewStyle = LVS_REPORT;
615         break;
616   }
617
618   dwStyle = GetWindowLong(hwndPicker, GWL_STYLE);
619   if (GetUseXPControl())
620   {
621      // RS Microsoft must have changed something in the Ownerdraw handling with Version 6 of the Common Controls
622      // as on all other OSes it works without this...
623      if (nViewID == VIEW_LARGE_ICONS || nViewID == VIEW_SMALL_ICONS)
624      {
625         // remove Ownerdraw style for Icon views
626         dwStyle &= ~LVS_OWNERDRAWFIXED;
627         if( nViewID == VIEW_SMALL_ICONS )
628         {
629            // to properly get them to arrange, otherwise the entries might overlap
630            // we have to call SetWindowLong to get it into effect !!
631            // It's no use just setting the Style, as it's changed again further down...
632            SetWindowLong(hwndPicker, GWL_STYLE, (GetWindowLong(hwndPicker, GWL_STYLE)
633               & ~LVS_TYPEMASK) | LVS_ICON);
634         }
635      }
636      else
637      {
638         // add again..
639         dwStyle |= LVS_OWNERDRAWFIXED;
640      }
641   }
642
643   dwStyle &= ~LVS_TYPEMASK;
644   dwStyle |= nListViewStyle;
645   SetWindowLong(hwndPicker, GWL_STYLE, dwStyle);
646   RedrawWindow(hwndPicker, NULL, NULL, RDW_ERASE | RDW_INVALIDATE | RDW_FRAME);
647}
648
649
650
651static BOOL PickerHitTest(HWND hWnd)
652{
653   RECT         rect;
654   POINTS         p;
655   DWORD         res = GetMessagePos();
656   LVHITTESTINFO   htInfo;
657
658    memset(&htInfo, 0, sizeof(htInfo));
659   p = MAKEPOINTS(res);
660   GetWindowRect(hWnd, &rect);
661   htInfo.pt.x = p.x - rect.left;
662   htInfo.pt.y = p.y - rect.top;
663   ListView_HitTest(hWnd, &htInfo);
664
665   return (! (htInfo.flags & LVHT_NOWHERE));
666}
667
668
669
670int Picker_GetSelectedItem(HWND hWnd)
671{
672   int nItem;
673   LV_ITEM lvi;
674
675   nItem = ListView_GetNextItem(hWnd, -1, LVIS_SELECTED | LVIS_FOCUSED);
676   if (nItem < 0)
677      return 0;
678
679   memset(&lvi, 0, sizeof(lvi));
680   lvi.iItem = nItem;
681   lvi.mask = LVIF_PARAM;
682   ListView_GetItem(hWnd, &lvi);
683   return lvi.lParam;
684}
685
686
687
688void Picker_SetSelectedPick(HWND hWnd, int nIndex)
689{
690   if (nIndex < 0)
691      nIndex = 0;
692
693   ListView_SetItemState(hWnd, nIndex, LVIS_FOCUSED | LVIS_SELECTED,
694      LVIS_FOCUSED | LVIS_SELECTED);
695   ListView_EnsureVisible(hWnd, nIndex, FALSE);
696}
697
698
699
700void Picker_SetSelectedItem(HWND hWnd, int nItem)
701{
702   int i;
703   LV_FINDINFO lvfi;
704
705   if (nItem < 0)
706      return;
707
708   lvfi.flags = LVFI_PARAM;
709   lvfi.lParam = nItem;
710   i = ListView_FindItem(hWnd, -1, &lvfi);
711   if (i == -1)
712   {
713      POINT p = {0,0};
714      lvfi.flags = LVFI_NEARESTXY;
715      lvfi.pt = p;
716      i = ListView_FindItem(hWnd, -1, &lvfi);
717   }
718   Picker_SetSelectedPick(hWnd, (i == -1) ? 0 : i);
719}
720
721
722
723static const TCHAR *Picker_CallGetItemString(HWND hwndPicker,
724   int nItem, int nColumn, TCHAR *pszBuffer, UINT nBufferLength)
725{
726   // this call wraps the pfnGetItemString callback to properly set up the
727   // buffers, and normalize the results
728   struct PickerInfo *pPickerInfo;
729   const TCHAR *s;
730
731   pPickerInfo = GetPickerInfo(hwndPicker);
732   pszBuffer[0] = '\0';
733   s = NULL;
734
735   if (pPickerInfo->pCallbacks->pfnGetItemString)
736   {
737      s = pPickerInfo->pCallbacks->pfnGetItemString(hwndPicker,
738         nItem, nColumn, pszBuffer, nBufferLength);
739   }
740   if (!s)
741      s = pszBuffer;
742   return s;
743}
744
745
746
747// put the arrow on the new sort column
748static void Picker_ResetHeaderSortIcon(HWND hwndPicker)
749{
750   struct PickerInfo *pPickerInfo;
751   HWND hwndHeader;
752   HD_ITEM hdi;
753   int i, nViewColumn;
754
755   pPickerInfo = GetPickerInfo(hwndPicker);
756
757   hwndHeader = ListView_GetHeader(hwndPicker);
758
759   // take arrow off non-current columns
760   hdi.mask = HDI_FORMAT;
761   hdi.fmt = HDF_STRING;
762   for (i = 0; i < pPickerInfo->nColumnCount; i++)
763   {
764      if (i != pPickerInfo->pCallbacks->pfnGetSortColumn())
765         Header_SetItem(hwndHeader, Picker_GetViewColumnFromRealColumn(hwndPicker, i), &hdi);
766   }
767
768   if (GetUseXPControl())
769   {
770      // use built in sort arrows
771      hdi.mask = HDI_FORMAT;
772      hdi.fmt = HDF_STRING | (pPickerInfo->pCallbacks->pfnGetSortReverse() ? HDF_SORTDOWN : HDF_SORTUP);
773   }
774   else
775   {
776      // put our arrow icon next to the text
777      hdi.mask = HDI_FORMAT | HDI_IMAGE;
778      hdi.fmt = HDF_STRING | HDF_IMAGE | HDF_BITMAP_ON_RIGHT;
779      hdi.iImage = pPickerInfo->pCallbacks->pfnGetSortReverse() ? 1 : 0;
780   }
781
782   nViewColumn = Picker_GetViewColumnFromRealColumn(hwndPicker, pPickerInfo->pCallbacks->pfnGetSortColumn());
783   Header_SetItem(hwndHeader, nViewColumn, &hdi);
784}
785
786
787
788struct CompareProcParams
789{
790   HWND hwndPicker;
791   struct PickerInfo *pPickerInfo;
792   int nSortColumn;
793   int nViewMode;
794   BOOL bReverse;
795};
796
797
798
799static void Picker_PopulateCompareProcParams(HWND hwndPicker,
800   struct CompareProcParams *pParams)
801{
802   struct PickerInfo *pPickerInfo;
803
804   pPickerInfo = GetPickerInfo(hwndPicker);
805
806   // populate the CompareProcParams structure
807   memset(pParams, 0, sizeof(*pParams));
808   pParams->hwndPicker = hwndPicker;
809   pParams->pPickerInfo = pPickerInfo;
810   pParams->nViewMode = pPickerInfo->pCallbacks->pfnGetViewMode();
811   if (pPickerInfo->pCallbacks->pfnGetSortColumn)
812      pParams->nSortColumn = pPickerInfo->pCallbacks->pfnGetSortColumn();
813   if (pPickerInfo->pCallbacks->pfnGetSortReverse)
814      pParams->bReverse = pPickerInfo->pCallbacks->pfnGetSortReverse();
815}
816
817
818
819static int CALLBACK Picker_CompareProc(LPARAM index1, LPARAM index2, LPARAM nParamSort)
820{
821   struct CompareProcParams *pcpp = (struct CompareProcParams *) nParamSort;
822   struct PickerInfo *pPickerInfo = pcpp->pPickerInfo;
823   BOOL bCallCompare = TRUE;
824   int nResult = 0, nParent1, nParent2;
825   TCHAR szBuffer1[256], szBuffer2[256];
826   const TCHAR *s1, *s2;
827
828   if (pcpp->nViewMode == VIEW_GROUPED)
829   {
830      // do our fancy compare, with clones grouped under parents
831      // first thing we need to do is identify both item's parents
832      if (pPickerInfo->pCallbacks->pfnFindItemParent)
833      {
834         nParent1 = pPickerInfo->pCallbacks->pfnFindItemParent(pcpp->hwndPicker, index1);
835         nParent2 = pPickerInfo->pCallbacks->pfnFindItemParent(pcpp->hwndPicker, index2);
836      }
837      else
838      {
839         nParent1 = nParent2 = -1;
840      }
841
842      if ((nParent1 < 0) && (nParent2 < 0))
843      {
844         // if both entries are both parents, we just do a basic sort
845      }
846      else if ((nParent1 >= 0) && (nParent2 >= 0))
847      {
848         // if both entries are children and the parents are different,
849         // sort on their parents
850         if (nParent1 != nParent2)
851         {
852            index1 = nParent1;
853            index2 = nParent2;
854         }
855      }
856      else
857      {
858         // one parent, one child
859         if (nParent1 >= 0)
860         {
861            // first one is a child
862            if (nParent1 == index2)
863            {
864               // if this is a child and its parent, put child after
865               nResult = 1;
866               bCallCompare = FALSE;
867            }
868            else
869            {
870               // sort on parent
871               index1 = nParent1;
872            }
873         }
874         else
875         {
876            // second one is a child
877            if (nParent2 == index1)
878            {
879               // if this is a child and its parent, put child after
880               nResult = -1;
881               bCallCompare = FALSE;
882            }
883            else
884            {
885               // sort on parent
886               index2 = nParent2;
887            }
888         }
889      }
890   }
891
892   if (bCallCompare)
893   {
894      if (pPickerInfo->pCallbacks->pfnCompare)
895      {
896         nResult = pPickerInfo->pCallbacks->pfnCompare(pcpp->hwndPicker,
897            index1, index2, pcpp->nSortColumn);
898      }
899      else
900      {
901         // no default sort proc, just get the string and compare them
902         s1 = Picker_CallGetItemString(pcpp->hwndPicker, index1, pcpp->nSortColumn,
903            szBuffer1, sizeof(szBuffer1) / sizeof(szBuffer1[0]));
904         s2 = Picker_CallGetItemString(pcpp->hwndPicker, index2, pcpp->nSortColumn,
905            szBuffer2, sizeof(szBuffer2) / sizeof(szBuffer2[0]));
906         nResult = _tcsicmp(s1, s2);
907      }
908
909      if (pcpp->bReverse)
910         nResult = -nResult;
911   }
912   return nResult;
913}
914
915
916
917void Picker_Sort(HWND hwndPicker)
918{
919   LV_FINDINFO lvfi;
920   struct PickerInfo *pPickerInfo;
921   struct CompareProcParams params;
922   int nItem;
923
924   pPickerInfo = GetPickerInfo(hwndPicker);
925
926   // populate the CompareProcParams structure
927   Picker_PopulateCompareProcParams(hwndPicker, &params);
928
929   ListView_SortItems(hwndPicker, Picker_CompareProc, (LPARAM) &params);
930
931   Picker_ResetHeaderSortIcon(hwndPicker);
932
933   memset(&lvfi, 0, sizeof(lvfi));
934   lvfi.flags = LVFI_PARAM;
935   lvfi.lParam = Picker_GetSelectedItem(hwndPicker);
936   nItem = ListView_FindItem(hwndPicker, -1, &lvfi);
937
938   ListView_EnsureVisible(hwndPicker, nItem, FALSE);
939}
940
941
942
943int Picker_InsertItemSorted(HWND hwndPicker, int nParam)
944{
945   struct PickerInfo *pPickerInfo;
946   int nHigh, nLow, nMid;
947   struct CompareProcParams params;
948   int nCompareResult;
949   LVITEM lvi;
950
951   pPickerInfo = GetPickerInfo(hwndPicker);
952
953   nLow = 0;
954   nHigh = ListView_GetItemCount(hwndPicker);
955
956   // populate the CompareProcParams structure
957   Picker_PopulateCompareProcParams(hwndPicker, &params);
958
959   while(nLow < nHigh)
960   {
961      nMid = (nHigh + nLow) / 2;
962
963      memset(&lvi, 0, sizeof(lvi));
964      lvi.mask = LVIF_PARAM;
965      lvi.iItem = nMid;
966      ListView_GetItem(hwndPicker, &lvi);
967
968      nCompareResult = Picker_CompareProc(nParam, lvi.lParam, (LPARAM) &params);
969
970      if (nCompareResult > 0)
971         nLow  = nMid + 1;
972      else if (nCompareResult < 0)
973         nHigh = nMid;
974      else
975      {
976         nLow = nMid;
977         break;
978      }
979   }
980
981   memset(&lvi, 0, sizeof(lvi));
982   lvi.mask     = LVIF_IMAGE | LVIF_TEXT | LVIF_PARAM;
983   lvi.iItem    = nLow;
984   lvi.iSubItem = 0;
985   lvi.lParam    = nParam;
986   lvi.pszText  = LPSTR_TEXTCALLBACK;
987   lvi.iImage    = I_IMAGECALLBACK;
988
989   return ListView_InsertItem(hwndPicker, &lvi);
990}
991
992
993
994int Picker_GetRealColumnFromViewColumn(HWND hWnd, int nViewColumn)
995{
996   struct PickerInfo *pPickerInfo;
997   int nRealColumn = 0;
998
999   pPickerInfo = GetPickerInfo(hWnd);
1000   if (nViewColumn >= 0 && nViewColumn < pPickerInfo->nColumnCount)
1001      nRealColumn = pPickerInfo->pnColumnsOrder[nViewColumn];
1002   return nRealColumn;
1003}
1004
1005
1006
1007int Picker_GetViewColumnFromRealColumn(HWND hWnd, int nRealColumn)
1008{
1009   struct PickerInfo *pPickerInfo;
1010   int i;
1011
1012   pPickerInfo = GetPickerInfo(hWnd);
1013   for (i = 0; i < pPickerInfo->nColumnCount; i++)
1014   {
1015      if (pPickerInfo->pnColumnsOrder[i] == nRealColumn)
1016         return i;
1017   }
1018
1019   // major error, shouldn't be possible, but no good way to warn
1020   return 0;
1021}
1022
1023
1024
1025BOOL Picker_HandleNotify(LPNMHDR lpNmHdr)
1026{
1027   struct PickerInfo *pPickerInfo;
1028   HWND hWnd;
1029   BOOL bResult = FALSE;
1030   NM_LISTVIEW *pnmv;
1031   LV_DISPINFO *pDispInfo;
1032   int nItem, nColumn;
1033   const TCHAR *s;
1034   BOOL bReverse;
1035
1036   hWnd = lpNmHdr->hwndFrom;
1037   pPickerInfo = GetPickerInfo(hWnd);
1038   pnmv = (NM_LISTVIEW *) lpNmHdr;
1039
1040   switch(lpNmHdr->code)
1041   {
1042      case NM_RCLICK:
1043      case NM_CLICK:
1044      case NM_DBLCLK:
1045         // don't allow selection of blank spaces in the listview
1046         if (!PickerHitTest(hWnd))
1047         {
1048            // we have no current item selected
1049            if (pPickerInfo->nLastItem != -1)
1050            {
1051               Picker_SetSelectedItem(hWnd, pPickerInfo->nLastItem);
1052            }
1053            bResult = TRUE;
1054         }
1055         else if ((lpNmHdr->code == NM_DBLCLK) && (pPickerInfo->pCallbacks->pfnDoubleClick))
1056         {
1057            // double click!
1058            pPickerInfo->pCallbacks->pfnDoubleClick();
1059            bResult = TRUE;
1060         }
1061         break;
1062
1063      case LVN_GETDISPINFO:
1064         pDispInfo = (LV_DISPINFO *) lpNmHdr;
1065         nItem = (int) pDispInfo->item.lParam;
1066
1067         if (pDispInfo->item.mask & LVIF_IMAGE)
1068         {
1069            // retrieve item image
1070            if (pPickerInfo->pCallbacks->pfnGetItemImage)
1071               pDispInfo->item.iImage = pPickerInfo->pCallbacks->pfnGetItemImage(hWnd, nItem);
1072            else
1073               pDispInfo->item.iImage = 0;
1074            bResult = TRUE;
1075         }
1076
1077         if (pDispInfo->item.mask & LVIF_STATE)
1078         {
1079            pDispInfo->item.state = 0;
1080            bResult = TRUE;
1081         }
1082
1083         if (pDispInfo->item.mask & LVIF_TEXT)
1084         {
1085            // retrieve item text
1086            nColumn = Picker_GetRealColumnFromViewColumn(hWnd, pDispInfo->item.iSubItem);
1087           
1088            s = Picker_CallGetItemString(hWnd, nItem, nColumn,
1089               pDispInfo->item.pszText, pDispInfo->item.cchTextMax);
1090
1091            pDispInfo->item.pszText = (TCHAR *) s;
1092            bResult = TRUE;
1093         }
1094         break;
1095
1096      case LVN_ITEMCHANGED:
1097         if ((pnmv->uOldState & LVIS_SELECTED)
1098            && !(pnmv->uNewState & LVIS_SELECTED))
1099         {
1100            if (pnmv->lParam != -1)
1101               pPickerInfo->nLastItem = pnmv->lParam;
1102            if (pPickerInfo->pCallbacks->pfnLeavingItem)
1103               pPickerInfo->pCallbacks->pfnLeavingItem(hWnd, pnmv->lParam);
1104         }
1105         if (!(pnmv->uOldState & LVIS_SELECTED)
1106            && (pnmv->uNewState & LVIS_SELECTED))
1107         {
1108            if (pPickerInfo->pCallbacks->pfnEnteringItem)
1109               pPickerInfo->pCallbacks->pfnEnteringItem(hWnd, pnmv->lParam);
1110         }
1111         bResult = TRUE;
1112         break;
1113
1114      case LVN_COLUMNCLICK:
1115         // if clicked on the same column we're sorting by, reverse it
1116         if (pPickerInfo->pCallbacks->pfnGetSortColumn() == Picker_GetRealColumnFromViewColumn(hWnd, pnmv->iSubItem))
1117            bReverse = !pPickerInfo->pCallbacks->pfnGetSortReverse();
1118         else
1119            bReverse = FALSE;
1120         pPickerInfo->pCallbacks->pfnSetSortReverse(bReverse);
1121         pPickerInfo->pCallbacks->pfnSetSortColumn(Picker_GetRealColumnFromViewColumn(hWnd, pnmv->iSubItem));
1122         Picker_Sort(hWnd);
1123         bResult = TRUE;
1124         break;
1125
1126      case LVN_BEGINDRAG:
1127         if (pPickerInfo->pCallbacks->pfnBeginListViewDrag)
1128            pPickerInfo->pCallbacks->pfnBeginListViewDrag(pnmv);
1129         break;
1130   }
1131   return bResult;
1132}
1133
1134
1135
1136int Picker_GetNumColumns(HWND hWnd)
1137{
1138   int  nColumnCount = 0;
1139   int  i;
1140   HWND hwndHeader;
1141   int  *shown;
1142   struct PickerInfo *pPickerInfo;
1143
1144   pPickerInfo = GetPickerInfo(hWnd);
1145
1146   shown = malloc(pPickerInfo->nColumnCount * sizeof(*shown));
1147   if (!shown)
1148      return -1;
1149
1150   pPickerInfo->pCallbacks->pfnGetColumnShown(shown);
1151   hwndHeader = ListView_GetHeader(hWnd);
1152
1153   if (GetUseOldControl() || (nColumnCount = Header_GetItemCount(hWnd)) < 1)
1154   {
1155      nColumnCount = 0;
1156      for (i = 0; i < pPickerInfo->nColumnCount ; i++ )
1157      {
1158         if (shown[i])
1159            nColumnCount++;
1160      }
1161   }
1162   
1163   free(shown);
1164   return nColumnCount;
1165}
1166
1167
1168
1169/* Add ... to Items in ListView if needed */
1170static LPCTSTR MakeShortString(HDC hDC, LPCTSTR lpszLong, int nColumnLen, int nOffset)
1171{
1172   static const TCHAR szThreeDots[] = TEXT("...");
1173   static TCHAR szShort[MAX_PATH];
1174   int nStringLen = lstrlen(lpszLong);
1175   int nAddLen;
1176   SIZE size;
1177   int i;
1178
1179   GetTextExtentPoint32(hDC, lpszLong, nStringLen, &size);
1180   if (nStringLen == 0 || size.cx + nOffset <= nColumnLen)
1181      return lpszLong;
1182
1183   lstrcpy(szShort, lpszLong);
1184   GetTextExtentPoint32(hDC, szThreeDots, sizeof(szThreeDots), &size);
1185   nAddLen = size.cx;
1186
1187   for (i = nStringLen - 1; i > 0; i--)
1188   {
1189      szShort[i] = 0;
1190      GetTextExtentPoint32(hDC, szShort, i, &size);
1191      if (size.cx + nOffset + nAddLen <= nColumnLen)
1192         break;
1193   }
1194
1195   lstrcat(szShort, szThreeDots);
1196
1197   return szShort;
1198}
1199
1200
1201
1202void Picker_HandleDrawItem(HWND hWnd, LPDRAWITEMSTRUCT lpDrawItemStruct)
1203{
1204   struct PickerInfo *pPickerInfo;
1205   HDC         hDC = lpDrawItemStruct->hDC;
1206   RECT        rcItem = lpDrawItemStruct->rcItem;
1207   UINT        uiFlags = ILD_TRANSPARENT;
1208   HIMAGELIST  hImageList;
1209   int         nItem = lpDrawItemStruct->itemID;
1210   COLORREF    clrTextSave = 0;
1211   COLORREF    clrBkSave = 0;
1212   COLORREF    clrImage = GetSysColor(COLOR_WINDOW);
1213   static TCHAR szBuff[MAX_PATH];
1214   BOOL        bFocus = (GetFocus() == hWnd);
1215   LPCTSTR     pszText;
1216   UINT        nStateImageMask;
1217   BOOL        bSelected;
1218   LV_COLUMN   lvc;
1219   LV_ITEM     lvi;
1220   RECT        rcAllLabels;
1221   RECT        rcLabel;
1222   RECT        rcIcon;
1223   int         offset;
1224   SIZE        size;
1225   int         i, j;
1226   int         nColumn;
1227   int         nColumnMax = 0;
1228   int         *order;
1229   BOOL        bDrawAsChild;
1230   int         indent_space;
1231   BOOL      bColorChild = FALSE;
1232   BOOL      bParentFound = FALSE;
1233   int         nParent;
1234   HBITMAP      hBackground = GetBackgroundBitmap();
1235   MYBITMAPINFO *pbmDesc = GetBackgroundInfo();
1236
1237   pPickerInfo = GetPickerInfo(hWnd);
1238
1239   order = malloc(pPickerInfo->nColumnCount * sizeof(*order));
1240   if (!order)
1241      return;
1242   nColumnMax = Picker_GetNumColumns(hWnd);
1243
1244   if (GetUseOldControl())
1245   {
1246      pPickerInfo->pCallbacks->pfnGetColumnOrder(order);
1247   }
1248   else
1249   {
1250      /* Get the Column Order and save it */
1251      ListView_GetColumnOrderArray(hWnd, nColumnMax, order);
1252
1253      /* Disallow moving column 0 */
1254      if (order[0] != 0)
1255      {
1256         for (i = 0; i < nColumnMax; i++)
1257         {
1258            if (order[i] == 0)
1259            {
1260               order[i] = order[0];
1261               order[0] = 0;
1262            }
1263         }
1264         ListView_SetColumnOrderArray(hWnd, nColumnMax, order);
1265      }
1266   }
1267
1268   /* Labels are offset by a certain amount */
1269   /* This offset is related to the width of a space character */
1270   GetTextExtentPoint32(hDC, TEXT(" "), 1 , &size);
1271   offset = size.cx;
1272
1273   lvi.mask      = LVIF_TEXT | LVIF_IMAGE | LVIF_STATE | LVIF_PARAM;
1274   lvi.iItem      = nItem;
1275   lvi.iSubItem   = order[0];
1276   lvi.pszText      = szBuff;
1277   lvi.cchTextMax = sizeof(szBuff) / sizeof(szBuff[0]);
1278   lvi.stateMask  = 0xFFFF;      /* get all state flags */
1279   ListView_GetItem(hWnd, &lvi);
1280
1281   bSelected = ((lvi.state & LVIS_DROPHILITED) || ( (lvi.state & LVIS_SELECTED)
1282      && ((bFocus) || (GetWindowLong(hWnd, GWL_STYLE) & LVS_SHOWSELALWAYS))));
1283
1284   /* figure out if we indent and draw grayed */
1285   if (pPickerInfo->pCallbacks->pfnFindItemParent)
1286      nParent = pPickerInfo->pCallbacks->pfnFindItemParent(hWnd, lvi.lParam);
1287   else
1288      nParent = -1;
1289   bDrawAsChild = (pPickerInfo->pCallbacks->pfnGetViewMode() == VIEW_GROUPED && (nParent >= 0));
1290
1291   /* only indent if parent is also in this view */
1292   if ((nParent >= 0) && bDrawAsChild)
1293   {
1294      for (i = 0; i < ListView_GetItemCount(hWnd); i++)
1295      {
1296         lvi.mask = LVIF_PARAM;
1297         lvi.iItem = i;
1298         ListView_GetItem(hWnd, &lvi);
1299
1300         if (lvi.lParam == nParent)
1301         {
1302            bParentFound = TRUE;
1303            break;
1304         }
1305      }
1306   }
1307
1308   if (pPickerInfo->pCallbacks->pfnGetOffsetChildren && pPickerInfo->pCallbacks->pfnGetOffsetChildren())
1309   {
1310      if (!bParentFound && bDrawAsChild)
1311      {
1312         /*Reset it, as no Parent is there*/
1313         bDrawAsChild = FALSE;
1314         bColorChild = TRUE;
1315      }
1316      else
1317      {
1318         nParent = -1;
1319         bParentFound = FALSE;
1320      }
1321   }
1322
1323   ListView_GetItemRect(hWnd, nItem, &rcAllLabels, LVIR_BOUNDS);
1324   ListView_GetItemRect(hWnd, nItem, &rcLabel, LVIR_LABEL);
1325
1326   rcAllLabels.left = rcLabel.left;
1327
1328   if (hBackground != NULL)
1329   {
1330      RECT      rcClient;
1331      HRGN      rgnBitmap;
1332      RECT      rcTmpBmp = rcItem;
1333      RECT      rcFirstItem;
1334      HPALETTE   hPAL;
1335      HDC       htempDC;
1336      HBITMAP    oldBitmap;
1337
1338      htempDC = CreateCompatibleDC(hDC);
1339
1340      oldBitmap = SelectObject(htempDC, hBackground);
1341
1342      GetClientRect(hWnd, &rcClient);
1343      rcTmpBmp.right = rcClient.right;
1344      /* We also need to check whether it is the last item
1345         The update region has to be extended to the bottom if it is */
1346      if (nItem == ListView_GetItemCount(hWnd) - 1)
1347         rcTmpBmp.bottom = rcClient.bottom;
1348
1349      rgnBitmap = CreateRectRgnIndirect(&rcTmpBmp);
1350      SelectClipRgn(hDC, rgnBitmap);
1351      DeleteObject(rgnBitmap);
1352
1353      hPAL = GetBackgroundPalette();
1354      if (hPAL == NULL)
1355         hPAL = CreateHalftonePalette(hDC);
1356
1357      if (GetDeviceCaps(htempDC, RASTERCAPS) & RC_PALETTE && hPAL != NULL)
1358      {
1359         SelectPalette(htempDC, hPAL, FALSE);
1360         RealizePalette(htempDC);
1361      }
1362
1363      ListView_GetItemRect(hWnd, 0, &rcFirstItem, LVIR_BOUNDS);
1364
1365      for (i = rcFirstItem.left; i < rcClient.right; i += pbmDesc->bmWidth)
1366         for (j = rcFirstItem.top; j < rcClient.bottom; j +=  pbmDesc->bmHeight)
1367            BitBlt(hDC, i, j, pbmDesc->bmWidth, pbmDesc->bmHeight, htempDC, 0, 0, SRCCOPY);
1368
1369      SelectObject(htempDC, oldBitmap);
1370      DeleteDC(htempDC);
1371
1372      if (GetBackgroundPalette() == NULL)
1373      {
1374         DeleteObject(hPAL);
1375         hPAL = NULL;
1376      }
1377   }
1378
1379   indent_space = 0;
1380
1381   if (bDrawAsChild)
1382   {
1383      RECT rect;
1384     
1385      ListView_GetItemRect(hWnd, nItem, &rect, LVIR_ICON);
1386
1387      /* indent width of icon + the space between the icon and text
1388       * so left of clone icon starts at text of parent
1389         */
1390      indent_space = rect.right - rect.left + offset;
1391   }
1392
1393   rcAllLabels.left += indent_space;
1394
1395   if (bSelected)
1396   {
1397      HBRUSH hBrush;
1398      HBRUSH hOldBrush;
1399
1400      if (bFocus)
1401      {
1402         clrTextSave = SetTextColor(hDC, GetSysColor(COLOR_HIGHLIGHTTEXT));
1403         clrBkSave   = SetBkColor(hDC, GetSysColor(COLOR_HIGHLIGHT));
1404         hBrush      = CreateSolidBrush(GetSysColor(COLOR_HIGHLIGHT));
1405      }
1406      else
1407      {
1408         clrTextSave = SetTextColor(hDC, GetSysColor(COLOR_BTNTEXT));
1409         clrBkSave   = SetBkColor(hDC, GetSysColor(COLOR_BTNFACE));
1410         hBrush      = CreateSolidBrush(GetSysColor(COLOR_BTNFACE));
1411      }
1412
1413      hOldBrush = SelectObject(hDC, hBrush);
1414      FillRect(hDC, &rcAllLabels, hBrush);
1415      SelectObject(hDC, hOldBrush);
1416      DeleteObject(hBrush);
1417   }
1418   else
1419   {
1420      if (hBackground == NULL)
1421      {
1422         HBRUSH hBrush;
1423         
1424         hBrush = CreateSolidBrush(GetSysColor(COLOR_WINDOW));
1425         FillRect(hDC, &rcAllLabels, hBrush);
1426         DeleteObject(hBrush);
1427      }
1428     
1429      if (pPickerInfo->pCallbacks->pfnGetOffsetChildren && pPickerInfo->pCallbacks->pfnGetOffsetChildren())
1430      {
1431         if (bDrawAsChild || bColorChild)
1432            clrTextSave = SetTextColor(hDC, GetListCloneColor());
1433         else
1434            clrTextSave = SetTextColor(hDC, GetListFontColor());
1435      }
1436      else
1437      {
1438         if (bDrawAsChild)
1439            clrTextSave = SetTextColor(hDC, GetListCloneColor());
1440         else
1441            clrTextSave = SetTextColor(hDC, GetListFontColor());
1442      }
1443
1444      clrBkSave = SetBkColor(hDC, GetSysColor(COLOR_WINDOW));
1445   }
1446
1447
1448   if (lvi.state & LVIS_CUT)
1449   {
1450      clrImage = GetSysColor(COLOR_WINDOW);
1451      uiFlags |= ILD_BLEND50;
1452   }
1453   else if (bSelected)
1454   {
1455      if (bFocus)
1456         clrImage = GetSysColor(COLOR_HIGHLIGHT);
1457      else
1458         clrImage = GetSysColor(COLOR_BTNFACE);
1459
1460      uiFlags |= ILD_BLEND50;
1461   }
1462
1463   nStateImageMask = lvi.state & LVIS_STATEIMAGEMASK;
1464
1465   if (nStateImageMask)
1466   {
1467      int nImage = (nStateImageMask >> 12) - 1;
1468      hImageList = ListView_GetImageList(hWnd, LVSIL_STATE);
1469      if (hImageList)
1470         ImageList_Draw(hImageList, nImage, hDC, rcItem.left, rcItem.top, ILD_TRANSPARENT);
1471   }
1472
1473   ListView_GetItemRect(hWnd, nItem, &rcIcon, LVIR_ICON);
1474
1475   rcIcon.left += indent_space;
1476
1477   ListView_GetItemRect(hWnd, nItem, &rcItem, LVIR_LABEL);
1478
1479   hImageList = ListView_GetImageList(hWnd, LVSIL_SMALL);
1480   if (hImageList)
1481   {
1482      UINT nOvlImageMask = lvi.state & LVIS_OVERLAYMASK;
1483      if (rcIcon.left + 16 + indent_space < rcItem.right)
1484      {
1485         ImageList_DrawEx(hImageList, lvi.iImage, hDC, rcIcon.left, rcIcon.top, 16, 16,
1486                      GetSysColor(COLOR_WINDOW), clrImage, uiFlags | nOvlImageMask);
1487      }
1488   }
1489
1490   ListView_GetItemRect(hWnd, nItem, &rcItem, LVIR_LABEL);
1491
1492   pszText = MakeShortString(hDC, szBuff, rcItem.right - rcItem.left, 2*offset + indent_space);
1493
1494   rcLabel = rcItem;
1495   rcLabel.left  += offset + indent_space;
1496   rcLabel.right -= offset;
1497
1498   DrawText(hDC, pszText, -1, &rcLabel,
1499          DT_LEFT | DT_SINGLELINE | DT_NOPREFIX | DT_VCENTER);
1500
1501   for (nColumn = 1; nColumn < nColumnMax; nColumn++)
1502   {
1503      int    nRetLen;
1504      UINT   nJustify;
1505      LV_ITEM lvItem;
1506
1507      lvc.mask = LVCF_FMT | LVCF_WIDTH;
1508      ListView_GetColumn(hWnd, order[nColumn], &lvc);
1509
1510      lvItem.mask      = LVIF_TEXT;
1511      lvItem.iItem     = nItem;
1512      lvItem.iSubItem   = order[nColumn];
1513      lvItem.pszText     = szBuff;
1514      lvItem.cchTextMax = sizeof(szBuff) / sizeof(szBuff[0]);
1515
1516      if (ListView_GetItem(hWnd, &lvItem) == FALSE)
1517         continue;
1518
1519      rcItem.left   = rcItem.right;
1520      rcItem.right += lvc.cx;
1521
1522      nRetLen = _tcslen(szBuff);
1523      if (nRetLen == 0)
1524         continue;
1525
1526      pszText = MakeShortString(hDC, szBuff, rcItem.right - rcItem.left, 2 * offset);
1527
1528      nJustify = DT_LEFT;
1529
1530      if (pszText == szBuff)
1531      {
1532         switch (lvc.fmt & LVCFMT_JUSTIFYMASK)
1533         {
1534         case LVCFMT_RIGHT:
1535            nJustify = DT_RIGHT;
1536            break;
1537
1538         case LVCFMT_CENTER:
1539            nJustify = DT_CENTER;
1540            break;
1541
1542         default:
1543            break;
1544         }
1545      }
1546
1547      rcLabel = rcItem;
1548      rcLabel.left  += offset;
1549      rcLabel.right -= offset;
1550      DrawText(hDC, pszText, -1, &rcLabel,
1551             nJustify | DT_SINGLELINE | DT_NOPREFIX | DT_VCENTER);
1552   }
1553
1554   if (lvi.state & LVIS_FOCUSED && bFocus)
1555      DrawFocusRect(hDC, &rcAllLabels);
1556
1557   SetTextColor(hDC, clrTextSave);
1558   SetBkColor(hDC, clrBkSave);
1559   free(order);
1560}
1561
1562
1563
1564const struct PickerCallbacks *Picker_GetCallbacks(HWND hwndPicker)
1565{
1566   struct PickerInfo *pPickerInfo;
1567   pPickerInfo = GetPickerInfo(hwndPicker);
1568   return pPickerInfo->pCallbacks;
1569}
1570
1571
1572
1573int Picker_GetColumnCount(HWND hwndPicker)
1574{
1575   struct PickerInfo *pPickerInfo;
1576   pPickerInfo = GetPickerInfo(hwndPicker);
1577   return pPickerInfo->nColumnCount;
1578}
1579
1580
1581
1582LPCTSTR *Picker_GetColumnNames(HWND hwndPicker)
1583{
1584   struct PickerInfo *pPickerInfo;
1585   pPickerInfo = GetPickerInfo(hwndPicker);
1586   return pPickerInfo->ppszColumnNames;
1587}
1588
1589
1590
1591void Picker_SetHeaderImageList(HWND hwndPicker, HIMAGELIST hHeaderImages)
1592{
1593   HWND hwndHeader;
1594   hwndHeader = ListView_GetHeader(hwndPicker);
1595   SendMessage(hwndHeader, HDM_SETIMAGELIST, 0, (LPARAM) (void *) hHeaderImages);
1596}
1597
1598
1599
1600BOOL Picker_SaveColumnWidths(HWND hwndPicker)
1601{
1602   struct PickerInfo *pPickerInfo;
1603   int *widths;
1604   int *order;
1605   int *tmpOrder;
1606   int nColumnMax, i;
1607   BOOL bSuccess = FALSE;
1608
1609   pPickerInfo = GetPickerInfo(hwndPicker);
1610
1611   /* allocate space for the column info */
1612   widths = malloc(pPickerInfo->nColumnCount * sizeof(*widths));
1613   order = malloc(pPickerInfo->nColumnCount * sizeof(*order));
1614   tmpOrder = malloc(pPickerInfo->nColumnCount * sizeof(*tmpOrder));
1615   if (!widths || !order || !tmpOrder)
1616      goto done;
1617
1618   /* retrieve the values */
1619   memset(widths, 0, pPickerInfo->nColumnCount * sizeof(*widths));
1620   memset(order, 0, pPickerInfo->nColumnCount * sizeof(*order));
1621   pPickerInfo->pCallbacks->pfnGetColumnWidths(widths);
1622   pPickerInfo->pCallbacks->pfnGetColumnOrder(order);
1623
1624   /* switch the list view to LVS_REPORT style so column widths reported correctly */
1625   SetWindowLong(hwndPicker, GWL_STYLE,
1626               (GetWindowLong(hwndPicker, GWL_STYLE) & ~LVS_TYPEMASK) | LVS_REPORT);
1627
1628   nColumnMax = Picker_GetNumColumns(hwndPicker);
1629
1630   if (GetUseOldControl())
1631   {
1632      for (i = 0; i < nColumnMax; i++)
1633      {
1634         widths[Picker_GetRealColumnFromViewColumn(hwndPicker, i)] =
1635            ListView_GetColumnWidth(hwndPicker, i);
1636      }
1637   }
1638   else
1639   {
1640      /* Get the Column Order and save it */
1641      ListView_GetColumnOrderArray(hwndPicker, nColumnMax, tmpOrder);
1642
1643      for (i = 0; i < nColumnMax; i++)
1644      {
1645         widths[Picker_GetRealColumnFromViewColumn(hwndPicker, i)]
1646            = ListView_GetColumnWidth(hwndPicker, i);
1647         order[i] = Picker_GetRealColumnFromViewColumn(hwndPicker, tmpOrder[i]);
1648      }
1649   }
1650
1651   pPickerInfo->pCallbacks->pfnSetColumnWidths(widths);
1652   pPickerInfo->pCallbacks->pfnSetColumnOrder(order);
1653   bSuccess = TRUE;
1654
1655done:
1656   if (widths)
1657      free(widths);
1658   if (order)
1659      free(order);
1660   if (tmpOrder)
1661      free(tmpOrder);
1662   return bSuccess;
1663}
src/osd/windows/ui/screenshot.c
r995r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10   
11***************************************************************************/
12
13/***************************************************************************
14
15  Screenshot.c
16 
17    Win32 DIB handling.
18   
19      Created 7/1/98 by Mike Haaland (mhaaland@hypertech.com)
20     
21***************************************************************************/
22
23#define WIN32_LEAN_AND_MEAN
24#include <windows.h>
25#include <stdlib.h>
26#include <io.h>
27#include <fcntl.h>
28#include <driver.h>
29#include <png.h>
30#include <osdepend.h>
31#include <tchar.h>
32
33#include "screenshot.h"
34#include "file.h"
35#include "bitmask.h"
36#include "m32opts.h"
37#include "m32util.h"
38#include "win32ui.h"
39#include "unzip.h"
40#include "strconv.h"
41
42/***************************************************************************
43    function prototypes
44***************************************************************************/
45
46static BOOL     AllocatePNG(png_info *p, HGLOBAL *phDIB, HPALETTE* pPal);
47
48static int png_read_bitmap_gui(LPVOID mfile, HGLOBAL *phDIB, HPALETTE *pPAL);
49/***************************************************************************
50    Static global variables
51***************************************************************************/
52
53/* these refer to the single image currently loaded by the ScreenShot functions */
54static HGLOBAL   m_hDIB = NULL;
55static HPALETTE  m_hPal = NULL;
56static HANDLE m_hDDB = NULL;
57static int current_image_game = -1;
58static int current_image_type = -1;
59
60#define WIDTHBYTES(width) ((width) / 8)
61
62/* PNG variables */
63
64static int   copy_size = 0;
65static char* pixel_ptr = 0;
66static int   row = 0;
67static int   effWidth;
68
69/***************************************************************************
70    Functions
71***************************************************************************/
72
73BOOL ScreenShotLoaded(void)
74{
75   return m_hDDB != NULL;
76}
77
78#ifdef MESS
79static BOOL LoadSoftwareScreenShot(const game_driver *drv, LPCSTR lpSoftwareName, int nType)
80{
81   BOOL result;
82   char *s = alloca(strlen(drv->name) + 1 + strlen(lpSoftwareName) + 5);
83   sprintf(s, "%s/%s.png", drv->name, lpSoftwareName);
84   result = LoadDIB(s, &m_hDIB, &m_hPal, nType);
85   return result;
86}
87#endif /* MESS */
88
89/* Allow us to pre-load the DIB once for future draws */
90#ifdef MESS
91BOOL LoadScreenShotEx(int nGame, LPCSTR lpSoftwareName, int nType)
92#else /* !MESS */
93BOOL LoadScreenShot(int nGame, int nType)
94#endif /* MESS */
95{
96   BOOL loaded = FALSE;
97   /* No need to reload the same one again */
98#ifndef MESS
99   if (nGame == current_image_game && nType == current_image_type)
100      return TRUE;
101#endif
102
103   /* Delete the last ones */
104   FreeScreenShot();
105
106   /* Load the DIB */
107#ifdef MESS
108   if (lpSoftwareName)
109   {
110      int nParentIndex = -1;
111      loaded = LoadSoftwareScreenShot(drivers[nGame], lpSoftwareName, nType);
112      if (!loaded && DriverIsClone(nGame) == TRUE)
113      {
114         nParentIndex = GetParentIndex(drivers[nGame]);
115         loaded = LoadSoftwareScreenShot(drivers[nParentIndex], lpSoftwareName, nType);
116      }
117   }
118   if (!loaded)
119#endif /* MESS */
120   {
121      loaded = LoadDIB(drivers[nGame]->name, &m_hDIB, &m_hPal, nType);
122   }
123
124   /* If not loaded, see if there is a clone and try that */
125   if (!loaded)
126   {
127      int nParentIndex = GetParentIndex(drivers[nGame]);
128      if( nParentIndex >= 0)
129      {
130         loaded = LoadDIB(drivers[nParentIndex]->name, &m_hDIB, &m_hPal, nType);
131         nParentIndex = GetParentIndex(drivers[nParentIndex]);
132         if (!loaded && nParentIndex >= 0)
133            loaded = LoadDIB(drivers[nParentIndex]->name, &m_hDIB, &m_hPal, nType);
134      }
135   }
136
137   if (loaded)
138   {
139      HDC hdc = GetDC(GetMainWindow());
140      m_hDDB = DIBToDDB(hdc, m_hDIB, NULL);
141      ReleaseDC(GetMainWindow(),hdc);
142     
143      current_image_game = nGame;
144      current_image_type = nType;
145
146   }
147
148   return (loaded) ? TRUE : FALSE;
149}
150
151HANDLE GetScreenShotHandle()
152{
153   return m_hDDB;
154}
155
156int GetScreenShotWidth(void)
157{
158   return ((LPBITMAPINFO)m_hDIB)->bmiHeader.biWidth;
159}
160
161int GetScreenShotHeight(void)
162{
163   return ((LPBITMAPINFO)m_hDIB)->bmiHeader.biHeight;
164}
165
166/* Delete the HPALETTE and Free the HDIB memory */
167void FreeScreenShot(void)
168{
169   if (m_hDIB != NULL)
170      GlobalFree(m_hDIB);
171   m_hDIB = NULL;
172
173   if (m_hPal != NULL)
174      DeleteObject(m_hPal);
175   m_hPal = NULL;
176
177   if (m_hDDB != NULL)
178      DeleteObject(m_hDDB);
179   m_hDDB = NULL;
180
181   current_image_game = -1;
182   current_image_type = -1;
183}
184
185static const zip_file_header *zip_file_seek_file(zip_file *zip, const char *filename)
186{
187   const zip_file_header *header;
188   char *new_filename;
189   int i;
190
191   // we need to change filename; allocate a copy
192   new_filename = malloc(strlen(filename) + 1);
193   if (!new_filename)
194      return NULL;
195   
196   // change all backslashes to forward slashes
197   for (i = 0; filename[i]; i++)
198      new_filename[i] = (filename[i] != '\\') ? filename[i] : '/';
199   new_filename[i] = '\0';
200
201   // find the entry
202   header = zip_file_first_file(zip);
203   while(header && mame_stricmp(header->filename, new_filename))
204   {
205      header = zip_file_next_file(zip);
206   }
207
208   free(new_filename);
209   return header;
210}
211
212static file_error OpenDIBFile(const char *dir_name, const char *zip_name, const char *filename,
213   core_file **file, void **buffer)
214{
215   file_error filerr;
216   zip_error ziperr;
217   zip_file *zip;
218   const zip_file_header *zip_header;
219   astring *fname;
220
221   // clear out result
222   *file = NULL;
223
224   // look for the raw file
225   fname = astring_assemble_3(astring_alloc(), dir_name, PATH_SEPARATOR, filename);
226   filerr = core_fopen(astring_c(fname), OPEN_FLAG_READ, file);
227   astring_free(fname);
228
229   // did the raw file not exist?
230   if (filerr != FILERR_NONE)
231   {
232      // look into zip file
233      fname = astring_assemble_4(astring_alloc(), dir_name, PATH_SEPARATOR, zip_name, ".zip");
234      ziperr = zip_file_open(astring_c(fname), &zip);
235      astring_free(fname);
236      if (ziperr == ZIPERR_NONE)
237      {
238         zip_header = zip_file_seek_file(zip, filename);
239         if (zip_header != NULL)
240         {
241            *buffer = malloc(zip_header->uncompressed_length);
242            ziperr = zip_file_decompress(zip, *buffer, zip_header->uncompressed_length);
243            if (ziperr == ZIPERR_NONE)
244            {
245               filerr = core_fopen_ram(*buffer, zip_header->uncompressed_length, OPEN_FLAG_READ, file);
246            }
247         }
248         zip_file_close(zip);
249      }
250   }
251   return filerr;
252}
253
254BOOL LoadDIB(const char *filename, HGLOBAL *phDIB, HPALETTE *pPal, int pic_type)
255{
256   file_error filerr;
257   core_file *file = NULL;
258   BOOL success = FALSE;
259   const char *dir_name;
260   const char *zip_name;
261   astring *fname;
262   void *buffer = NULL;
263
264   switch (pic_type)
265   {
266      case TAB_SCREENSHOT:
267         dir_name = GetImgDir();
268         zip_name = "snap";
269         break;
270      case TAB_FLYER:
271         dir_name = GetFlyerDir();
272         zip_name = "flyers";
273         break;
274      case TAB_CABINET:
275         dir_name = GetCabinetDir();
276         zip_name = "cabinets";
277         break;
278      case TAB_MARQUEE:
279         dir_name = GetMarqueeDir();
280         zip_name = "marquees";
281         break;
282      case TAB_TITLE:
283         dir_name = GetTitlesDir();
284         zip_name = "titles";
285         break;
286      case TAB_CONTROL_PANEL:
287         dir_name = GetControlPanelDir();
288         zip_name = "cpanel";
289         break;
290      case BACKGROUND:
291         dir_name = GetBgDir();
292         zip_name = "bkground";
293         break;
294      default :
295         // in case a non-image tab gets here, which can happen
296         return FALSE;
297   }
298
299   fname = astring_assemble_2(astring_alloc(), filename, ".png");
300   filerr = OpenDIBFile(dir_name, zip_name, astring_c(fname), &file, &buffer);
301   astring_free(fname);
302
303   if (filerr != FILERR_NONE)
304   {
305      fname = astring_assemble_3(astring_alloc(), filename, PATH_SEPARATOR, "0000.png");
306      filerr = OpenDIBFile(dir_name, zip_name, astring_c(fname), &file, &buffer);
307      astring_free(fname);
308   }
309
310   if (filerr == FILERR_NONE)
311   {
312      success = png_read_bitmap_gui(file, phDIB, pPal);
313      core_fclose(file);
314   }
315
316   // free the buffer if we have to
317   if (buffer != NULL)
318      free(buffer);
319
320   return success;
321}
322
323HBITMAP DIBToDDB(HDC hDC, HANDLE hDIB, LPMYBITMAPINFO desc)
324{
325   LPBITMAPINFOHEADER   lpbi;
326   HBITMAP          hBM;
327   int             nColors;
328   BITMAPINFO *      bmInfo = (LPBITMAPINFO)hDIB;
329   LPVOID            lpDIBBits;
330
331   if (hDIB == NULL)
332      return NULL;
333
334   lpbi = (LPBITMAPINFOHEADER)hDIB;
335   nColors = lpbi->biClrUsed ? lpbi->biClrUsed : 1 << lpbi->biBitCount;
336
337   if (bmInfo->bmiHeader.biBitCount > 8)
338      lpDIBBits = (LPVOID)((LPDWORD)(bmInfo->bmiColors +
339         bmInfo->bmiHeader.biClrUsed) +
340         ((bmInfo->bmiHeader.biCompression == BI_BITFIELDS) ? 3 : 0));
341   else
342      lpDIBBits = (LPVOID)(bmInfo->bmiColors + nColors);
343
344   if (desc != 0)
345   {
346      /* Store for easy retrieval later */
347      desc->bmWidth  = bmInfo->bmiHeader.biWidth;
348      desc->bmHeight = bmInfo->bmiHeader.biHeight;
349      desc->bmColors = (nColors <= 256) ? nColors : 0;
350   }
351
352   hBM = CreateDIBitmap(hDC,                 /* handle to device context */
353                  (LPBITMAPINFOHEADER)lpbi, /* pointer to bitmap info header   */
354                  (LONG)CBM_INIT,         /* initialization flag */
355                  lpDIBBits,              /* pointer to initialization data  */
356                  (LPBITMAPINFO)lpbi,      /* pointer to bitmap info */
357                  DIB_RGB_COLORS);        /* color-data usage  */
358
359   return hBM;
360}
361
362
363/***************************************************************************
364    PNG graphics handling functions
365***************************************************************************/
366
367static void store_pixels(UINT8 *buf, int len)
368{
369   if (pixel_ptr && copy_size)
370   {
371      memcpy(&pixel_ptr[row * effWidth], buf, len);
372      row--;
373      copy_size -= len;
374   }
375}
376
377BOOL AllocatePNG(png_info *p, HGLOBAL *phDIB, HPALETTE *pPal)
378{
379   int             dibSize;
380   HGLOBAL          hDIB;
381   BITMAPINFOHEADER   bi;
382   LPBITMAPINFOHEADER   lpbi;
383   LPBITMAPINFO      bmInfo;
384   LPVOID            lpDIBBits = 0;
385   int             lineWidth = 0;
386   int             nColors = 0;
387   RGBQUAD*         pRgb;
388   copy_size = 0;
389   pixel_ptr = 0;
390   row      = p->height - 1;
391   lineWidth = p->width;
392   
393   if (p->color_type != 2 && p->num_palette <= 256)
394      nColors =  p->num_palette;
395
396   bi.biSize         = sizeof(BITMAPINFOHEADER);
397   bi.biWidth         = p->width;
398   bi.biHeight       = p->height;
399   bi.biPlanes       = 1;
400   bi.biBitCount      = (p->color_type == 3) ? 8 : 24; /* bit_depth; */
401   
402   bi.biCompression   = BI_RGB;
403   bi.biSizeImage      = 0;
404   bi.biXPelsPerMeter   = 0;
405   bi.biYPelsPerMeter   = 0;
406   bi.biClrUsed      = nColors;
407   bi.biClrImportant   = nColors;
408   
409   effWidth = (long)(((long)lineWidth*bi.biBitCount + 31) / 32) * 4;
410   
411   dibSize = (effWidth * bi.biHeight);
412   hDIB = GlobalAlloc(GMEM_FIXED, bi.biSize + (nColors * sizeof(RGBQUAD)) + dibSize);
413   
414   if (!hDIB)
415   {
416      return FALSE;
417   }
418
419   lpbi = (LPVOID)hDIB;
420   memcpy(lpbi, &bi, sizeof(BITMAPINFOHEADER));
421   pRgb = (RGBQUAD*)((LPSTR)lpbi + bi.biSize);
422   lpDIBBits = (LPVOID)((LPSTR)lpbi + bi.biSize + (nColors * sizeof(RGBQUAD)));
423   if (nColors)
424   {
425      int i;
426      /*
427        Convert a PNG palette (3 byte RGBTRIPLEs) to a new
428        color table (4 byte RGBQUADs)
429      */
430      for (i = 0; i < nColors; i++)
431      {
432         RGBQUAD rgb;
433         
434         rgb.rgbRed      = p->palette[i * 3 + 0];
435         rgb.rgbGreen   = p->palette[i * 3 + 1];
436         rgb.rgbBlue    = p->palette[i * 3 + 2];
437         rgb.rgbReserved = (BYTE)0;
438         
439         pRgb[i] = rgb;
440      }
441   }
442   
443   bmInfo = (LPBITMAPINFO)hDIB;
444   
445   /* Create a halftone palette if colors > 256. */
446   if (0 == nColors || nColors > 256)
447   {
448      HDC hDC = CreateCompatibleDC(0); /* Desktop DC */
449      *pPal = CreateHalftonePalette(hDC);
450      DeleteDC(hDC);
451   }
452   else
453   {
454      UINT nSize = sizeof(LOGPALETTE) + (sizeof(PALETTEENTRY) * nColors);
455      LOGPALETTE *pLP = (LOGPALETTE *)malloc(nSize);
456      int  i;
457     
458      pLP->palVersion    = 0x300;
459      pLP->palNumEntries   = nColors;
460     
461      for (i = 0; i < nColors; i++)
462      {
463         pLP->palPalEntry[i].peRed   = bmInfo->bmiColors[i].rgbRed;
464         pLP->palPalEntry[i].peGreen = bmInfo->bmiColors[i].rgbGreen;
465         pLP->palPalEntry[i].peBlue   = bmInfo->bmiColors[i].rgbBlue;
466         pLP->palPalEntry[i].peFlags = 0;
467      }
468     
469      *pPal = CreatePalette(pLP);
470     
471      free (pLP);
472   }
473   
474   copy_size = dibSize;
475   pixel_ptr = lpDIBBits;
476   *phDIB = hDIB;
477   return TRUE;
478}
479
480/* Copied and modified from png.c */
481static int png_read_bitmap_gui(LPVOID mfile, HGLOBAL *phDIB, HPALETTE *pPAL)
482{
483   png_info p;
484   UINT32 i;
485   int bytespp;
486   
487   if (png_read_file(mfile, &p) != PNGERR_NONE)
488      return 0;
489
490   if (p.color_type != 3 && p.color_type != 2)
491   {
492      logerror("Unsupported color type %i (has to be 3)\n", p.color_type);
493      free(p.image);
494      return 0;
495   }
496   if (p.interlace_method != 0)
497   {
498      logerror("Interlace unsupported\n");
499      free (p.image);
500      return 0;
501   }
502 
503   /* Convert < 8 bit to 8 bit */
504   png_expand_buffer_8bit(&p);
505   
506   if (!AllocatePNG(&p, phDIB, pPAL))
507   {
508      logerror("Unable to allocate memory for artwork\n");
509      free(p.image);
510      return 0;
511   }
512
513   bytespp = (p.color_type == 2) ? 3 : 1;
514
515   for (i = 0; i < p.height; i++)
516   {
517      UINT8 *ptr = p.image + i * (p.width * bytespp);
518
519      if (p.color_type == 2) /*(p->bit_depth > 8) */
520      {
521         int j;
522         UINT8 bTmp;
523
524         for (j = 0; j < p.width; j++)
525         {
526            bTmp = ptr[0];
527            ptr[0] = ptr[2];
528            ptr[2] = bTmp;
529            ptr += 3;
530         }
531      }   
532      store_pixels(p.image + i * (p.width * bytespp), p.width * bytespp);
533   }
534
535   free(p.image);
536
537   return 1;
538}
539
540#ifdef MESS
541BOOL LoadScreenShot(int nGame, int nType)
542{
543   return LoadScreenShotEx(nGame, NULL, nType);
544}
545#endif
546
547/* End of source */
src/osd/windows/ui/datafile.h
r995r996
1#ifndef DATAFILE_H
2#define DATAFILE_H
3
4struct tDatafileIndex
5{
6   long offset;
7   const game_driver *driver;
8};
9
10extern int load_driver_history (const game_driver *drv, char *buffer, int bufsize);
11
12#endif
src/osd/windows/ui/directories.h
r995r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11 ***************************************************************************/
12
13#ifndef DIRECTORIES_H
14#define DIRECTORIES_H
15
16/* Dialog return codes */
17#define DIRDLG_ROMS         0x0010
18#define DIRDLG_SAMPLES      0x0020
19#define DIRDLG_INI          0x0040
20#define DIRDLG_CFG          0x0100
21#define DIRDLG_IMG          0x0400
22#define DIRDLG_INP          0x0800
23#define DIRDLG_CTRLR        0x1000
24#define DIRDLG_SOFTWARE      0x2000
25#define DIRDLG_COMMENT      0x4000
26
27#define DIRLIST_NEWENTRYTEXT "<               >"
28
29typedef struct
30{
31   LPCSTR   lpName;
32   LPCSTR   (*pfnGetTheseDirs)(void);
33   void     (*pfnSetTheseDirs)(LPCSTR lpDirs);
34   BOOL     bMulti;
35   int      nDirDlgFlags;
36}
37DIRECTORYINFO;
38
39/* in layout[ms].c */
40extern DIRECTORYINFO g_directoryInfo[];
41
42INT_PTR CALLBACK DirectoriesDialogProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam);
43
44#endif /* DIRECTORIES_H */
45
46
src/osd/windows/ui/dijoystick.h
r995r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11 ***************************************************************************/
12
13#ifndef DIJOYSTICK_H
14#define DIJOYSTICK_H
15
16/*
17  limits:
18  - 7 joysticks
19  - 15 sticks on each joystick (15?)
20  - 63 buttons on each joystick
21
22  - 256 total inputs
23
24
25   1 1 1 1 1 1
26   5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
27  +---+-----------+---------+-----+
28  |Dir|Axis/Button|   Stick | Joy |
29  +---+-----------+---------+-----+
30
31    Stick:  0 for buttons 1 for axis
32    Joy:    1 for Mouse/track buttons
33
34*/
35#define JOYCODE(joy, stick, axis_or_button, dir) \
36        ((((dir)            & 0x03) << 14) |     \
37         (((axis_or_button) & 0x3f) <<  8) |     \
38         (((stick)          & 0x1f) <<  3) |     \
39         (((joy)            & 0x07) <<  0))
40
41#define GET_JOYCODE_JOY(code)    (((code) >> 0) & 0x07)
42#define GET_JOYCODE_STICK(code)  (((code) >> 3) & 0x1f)
43#define GET_JOYCODE_AXIS(code)   (((code) >> 8) & 0x3f)
44#define GET_JOYCODE_BUTTON(code) GET_JOYCODE_AXIS(code)
45#define GET_JOYCODE_DIR(code)    (((code) >>14) & 0x03)
46
47#define JOYCODE_STICK_BTN    0
48#define JOYCODE_STICK_AXIS   1
49#define JOYCODE_STICK_POV    2
50
51#define JOYCODE_DIR_BTN      0
52#define JOYCODE_DIR_NEG      1
53#define JOYCODE_DIR_POS      2
54
55struct OSDJoystick
56{
57   int  (*init)(void);
58   void (*exit)(void);
59   int  (*is_joy_pressed)(int joycode);
60   void (*poll_joysticks)(void);
61   BOOL (*Available)(void);
62};
63
64extern struct OSDJoystick DIJoystick;
65
66extern int    DIJoystick_GetNumPhysicalJoysticks(void);
67extern TCHAR* DIJoystick_GetPhysicalJoystickName(int num_joystick);
68
69extern int    DIJoystick_GetNumPhysicalJoystickAxes(int num_joystick);
70extern TCHAR* DIJoystick_GetPhysicalJoystickAxisName(int num_joystick, int num_axis);
71
72#endif
src/osd/windows/ui/picker.h
r995r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11 ***************************************************************************/
12
13#ifndef PICKER_H
14#define PICKER_H
15
16struct PickerCallbacks
17{
18   // Options retrieval
19   void (*pfnSetSortColumn)(int column);
20   int (*pfnGetSortColumn)(void);
21   void (*pfnSetSortReverse)(BOOL reverse);
22   BOOL (*pfnGetSortReverse)(void);
23   void (*pfnSetViewMode)(int val);
24   int (*pfnGetViewMode)(void);
25   void (*pfnSetColumnWidths)(int widths[]);
26   void (*pfnGetColumnWidths)(int widths[]);
27   void (*pfnSetColumnOrder)(int order[]);
28   void (*pfnGetColumnOrder)(int order[]);
29   void (*pfnSetColumnShown)(int shown[]);
30   void (*pfnGetColumnShown)(int shown[]);
31   BOOL (*pfnGetOffsetChildren)(void);
32
33   int (*pfnCompare)(HWND hwndPicker, int nIndex1, int nIndex2, int nSortSubItem);
34   void (*pfnDoubleClick)(void);
35   const TCHAR *(*pfnGetItemString)(HWND hwndPicker, int nItem, int nColumn,
36      TCHAR *pszBuffer, UINT nBufferLength);
37   int (*pfnGetItemImage)(HWND hwndPicker, int nItem);
38   void (*pfnLeavingItem)(HWND hwndPicker, int nItem);
39   void (*pfnEnteringItem)(HWND hwndPicker, int nItem);
40   void (*pfnBeginListViewDrag)(NM_LISTVIEW *pnlv);
41   int (*pfnFindItemParent)(HWND hwndPicker, int nItem);
42   BOOL (*pfnOnIdle)(HWND hwndPicker);
43   void (*pfnOnHeaderContextMenu)(POINT pt, int nColumn);
44   void (*pfnOnBodyContextMenu)(POINT pt);
45};
46
47struct PickerOptions
48{
49   const struct PickerCallbacks *pCallbacks;
50   BOOL bOldControl;
51   BOOL bXPControl;
52   int nColumnCount;
53   LPCTSTR *ppszColumnNames;
54};
55
56enum
57{
58   VIEW_LARGE_ICONS = 0,
59   VIEW_SMALL_ICONS,
60   VIEW_INLIST,
61   VIEW_REPORT,
62   VIEW_GROUPED,
63   VIEW_MAX
64};
65
66
67
68BOOL SetupPicker(HWND hwndPicker, const struct PickerOptions *pOptions);
69
70int Picker_GetViewID(HWND hwndPicker);
71void Picker_SetViewID(HWND hwndPicker, int nViewID);
72int Picker_GetRealColumnFromViewColumn(HWND hwndPicker, int nViewColumn);
73int Picker_GetViewColumnFromRealColumn(HWND hwndPicker, int nRealColumn);
74void Picker_Sort(HWND hwndPicker);
75void Picker_ResetColumnDisplay(HWND hwndPicker);
76int Picker_GetSelectedItem(HWND hwndPicker);
77void Picker_SetSelectedItem(HWND hwndPicker, int nItem);
78void Picker_SetSelectedPick(HWND hwndPicker, int nIndex);
79int Picker_GetNumColumns(HWND hWnd);
80void Picker_ClearIdle(HWND hwndPicker);
81void Picker_ResetIdle(HWND hwndPicker);
82BOOL Picker_IsIdling(HWND hwndPicker);
83void Picker_SetHeaderImageList(HWND hwndPicker, HIMAGELIST hHeaderImages);
84int Picker_InsertItemSorted(HWND hwndPicker, int nParam);
85BOOL Picker_SaveColumnWidths(HWND hwndPicker);
86
87// These are used to handle events received by the parent regarding
88// picker controls
89BOOL Picker_HandleNotify(LPNMHDR lpNmHdr);
90void Picker_HandleDrawItem(HWND hwndPicker, LPDRAWITEMSTRUCT lpDrawItemStruct);
91
92// Accessors
93const struct PickerCallbacks *Picker_GetCallbacks(HWND hwndPicker);
94int Picker_GetColumnCount(HWND hwndPicker);
95LPCTSTR *Picker_GetColumnNames(HWND hwndPicker);
96
97#endif // PICKER_H
src/osd/windows/ui/screenshot.h
r995r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11 ***************************************************************************/
12
13#ifndef SCREENSHOT_H
14#define SCREENSHOT_H
15
16typedef struct _mybitmapinfo
17{
18   int bmWidth;
19   int bmHeight;
20   int bmColors;
21} MYBITMAPINFO, *LPMYBITMAPINFO;
22
23#ifdef MESS
24extern BOOL LoadScreenShotEx(int nGame, LPCSTR lpSoftwareName, int nType);
25#endif /* MESS */
26
27extern BOOL LoadScreenShot(int nGame, int nType);
28extern HANDLE GetScreenShotHandle(void);
29extern int GetScreenShotWidth(void);
30extern int GetScreenShotHeight(void);
31
32extern void FreeScreenShot(void);
33extern BOOL ScreenShotLoaded(void);
34
35extern BOOL LoadDIB(const char *filename, HGLOBAL *phDIB, HPALETTE *pPal, BOOL flyer);
36extern HBITMAP DIBToDDB(HDC hDC, HANDLE hDIB, LPMYBITMAPINFO desc);
37
38#endif
src/osd/windows/ui/splitters.c
r995r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Splitter code Copyright (C) 1997-98 Mike Haaland
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11 ***************************************************************************/
12 
13 /***************************************************************************
14
15  Splitters.c
16
17  Splitter GUI code.
18
19  Created 12/03/98 (C) by Mike Haaland (mhaaland@hypertech.com)
20
21***************************************************************************/
22
23/*
24
25  Tree, spliiter, list, splitter, pict
26
27*/
28 
29
30#define WIN32_LEAN_AND_MEAN
31#include <windows.h>
32#include <windowsx.h>
33#include <commctrl.h>
34
35#include "splitters.h"
36#include "bitmask.h"
37#include "m32opts.h"
38#include "resource.h"
39#include "screenshot.h"
40#include "win32ui.h"
41
42/* Local Variables */
43static BOOL         bTracking = 0;
44static int          numSplitters = 0;
45static int          currentSplitter = 0;
46static HZSPLITTER   *splitter;
47static LPHZSPLITTER lpCurSpltr = 0;
48static HCURSOR      hSplitterCursor = 0;
49
50int *nSplitterOffset;
51
52BOOL InitSplitters(void)
53{
54   int nSplitterCount;
55
56   /* load the cursor for the splitter */
57   hSplitterCursor = LoadCursor(GetModuleHandle(0), MAKEINTRESOURCE(IDC_CURSOR_HSPLIT));
58
59   nSplitterCount = GetSplitterCount();
60
61   splitter = malloc(sizeof(HZSPLITTER) * nSplitterCount);
62   if (!splitter)
63      goto error;     
64   memset(splitter, 0, sizeof(HZSPLITTER) * nSplitterCount);
65
66   nSplitterOffset = malloc(sizeof(int) * nSplitterCount);
67   if (!nSplitterOffset)
68      goto error;     
69   memset(nSplitterOffset, 0, sizeof(int) * nSplitterCount);   
70
71   return TRUE;
72
73error:
74   SplittersExit();
75   return FALSE;
76}
77
78void SplittersExit(void)
79{
80   if (splitter)
81   {
82      free(splitter);
83      splitter = NULL;
84   }
85   if (nSplitterOffset)
86   {
87      free(nSplitterOffset);
88      nSplitterOffset = NULL;
89   }
90}
91
92
93/* Called with hWnd = Parent Window */
94void CalcSplitter(HWND hWnd, LPHZSPLITTER lpSplitter)
95{
96   POINT   p = {0,0};
97   RECT   leftRect, rightRect;
98   int    dragWidth;
99
100   ClientToScreen(hWnd, &p);
101
102   GetWindowRect(lpSplitter->m_hWnd,      &lpSplitter->m_dragRect);
103   GetWindowRect(lpSplitter->m_hWndLeft,   &leftRect);
104   GetWindowRect(lpSplitter->m_hWndRight,   &rightRect);
105
106   OffsetRect(&lpSplitter->m_dragRect, -p.x, -p.y);
107   OffsetRect(&leftRect, -p.x, -p.y);
108   OffsetRect(&rightRect, -p.x, -p.y);
109
110   dragWidth = lpSplitter->m_dragRect.right - lpSplitter->m_dragRect.left;
111
112   lpSplitter->m_limitRect.left   = leftRect.left + 20;
113   lpSplitter->m_limitRect.right   = rightRect.right - 20;
114   lpSplitter->m_limitRect.top    = lpSplitter->m_dragRect.top;
115   lpSplitter->m_limitRect.bottom   = lpSplitter->m_dragRect.bottom;
116   if (lpSplitter->m_func)
117      lpSplitter->m_func(hWnd, &lpSplitter->m_limitRect);
118
119   if (lpSplitter->m_dragRect.left < lpSplitter->m_limitRect.left)
120      lpSplitter->m_dragRect.left = lpSplitter->m_limitRect.left;
121
122   if (lpSplitter->m_dragRect.right > lpSplitter->m_limitRect.right)
123      lpSplitter->m_dragRect.left = lpSplitter->m_limitRect.right - dragWidth;
124
125   lpSplitter->m_dragRect.right = lpSplitter->m_dragRect.left + dragWidth;
126}
127
128void AdjustSplitter2Rect(HWND hWnd, LPRECT lpRect)
129{
130   RECT pRect;
131
132   GetClientRect(hWnd, &pRect);
133
134   if (lpRect->right > pRect.right)
135      lpRect->right = pRect.right;
136
137   lpRect->right = MIN(lpRect->right - GetMinimumScreenShotWindowWidth(), lpRect->right);
138
139   lpRect->left = MAX((pRect.right - (pRect.right - pRect.left)) / 2, lpRect->left);
140}
141
142void AdjustSplitter1Rect(HWND hWnd, LPRECT lpRect)
143{
144}
145
146void RecalcSplitters(void)
147{
148   int    i;
149   
150   for (i = 0; i < numSplitters; i++)
151   {
152      CalcSplitter(GetParent(splitter[i].m_hWnd), &splitter[i]);
153      nSplitterOffset[i] = splitter[i].m_dragRect.left;
154   }
155   
156   for (i = numSplitters - 1; i >= 0; i--)
157   {
158      CalcSplitter(GetParent(splitter[i].m_hWnd), &splitter[i]);
159      nSplitterOffset[i] = splitter[i].m_dragRect.left;
160   }
161
162}
163
164void OnSizeSplitter(HWND hWnd)
165{
166   static int firstTime = TRUE;
167   int changed = FALSE;
168   RECT rWindowRect;
169   POINT p = {0,0};
170   int i;
171   int nSplitterCount;
172   BOOL bMustChange;
173
174   nSplitterCount = GetSplitterCount();
175
176   if (firstTime)
177   {
178      for (i = 0; i < nSplitterCount; i++)
179         nSplitterOffset[i] = GetSplitterPos(i);
180      changed = TRUE;
181      firstTime = FALSE;
182   }
183
184   GetWindowRect(hWnd, &rWindowRect);
185
186   for (i = 0; i < nSplitterCount; i++)
187   {
188      p.x = 0;
189      p.y = 0;
190      ClientToScreen(splitter[i].m_hWnd, &p);
191
192      /* We must change if our window is not in the window rect */
193      bMustChange = !PtInRect(&rWindowRect, p);
194
195      /* We should also change if we are ahead the next splitter */
196      if ((i < nSplitterCount-1) && (nSplitterOffset[i] >= nSplitterOffset[i+1]))
197         bMustChange = TRUE;
198
199      /* ...or if we are behind the previous splitter */
200      if ((i > 0) && (nSplitterOffset[i] <= nSplitterOffset[i-1]))
201         bMustChange = TRUE;
202
203      if (bMustChange)
204      {
205         nSplitterOffset[i] = (rWindowRect.right - rWindowRect.left) * g_splitterInfo[i].dPosition;
206         changed = TRUE;
207      }
208   }
209
210   if (changed)
211   {
212      ResizePickerControls(hWnd);
213      RecalcSplitters();
214      //UpdateScreenShot();
215   }
216}
217
218void AddSplitter(HWND hWnd, HWND hWndLeft, HWND hWndRight, void (*func)(HWND hWnd,LPRECT lpRect))
219{
220   LPHZSPLITTER lpSpltr = &splitter[numSplitters];
221
222   if (numSplitters >= GetSplitterCount())
223      return;
224
225   lpSpltr->m_hWnd = hWnd;
226   lpSpltr->m_hWndLeft = hWndLeft;
227   lpSpltr->m_hWndRight = hWndRight;
228   lpSpltr->m_func = func;
229   CalcSplitter(GetParent(hWnd), lpSpltr);
230
231   numSplitters++;
232}
233
234void OnInvertTracker(HWND hWnd, const RECT *rect)
235{
236   HDC    hDC = GetDC(hWnd);
237   HBRUSH   hBrush = CreateSolidBrush(RGB(0xFF, 0xFF, 0xFF));
238   HBRUSH   hOldBrush = 0;
239
240   if (hBrush != 0)
241      hOldBrush = (HBRUSH)SelectObject(hDC, hBrush);
242   PatBlt(hDC, rect->left, rect->top, rect->right - rect->left, rect->bottom - rect->top, DSTINVERT);
243   if (hOldBrush != 0)
244      SelectObject(hDC, hOldBrush);
245   ReleaseDC(hWnd, hDC);
246   DeleteObject(hBrush);
247}
248
249void StartTracking(HWND hWnd, UINT hitArea)
250{
251   if (!bTracking && lpCurSpltr != 0 && hitArea == SPLITTER_HITITEM)
252   {
253      // Ensure we have and updated cursor structure
254      CalcSplitter(hWnd, lpCurSpltr);
255      // Draw the first splitter shadow
256      OnInvertTracker(hWnd, &lpCurSpltr->m_dragRect);
257      // Capture the mouse
258      SetCapture(hWnd);
259      // Set tracking to TRUE
260      bTracking = TRUE;
261      SetCursor(hSplitterCursor);
262   }
263}
264
265void StopTracking(HWND hWnd)
266{
267   if (bTracking)
268   {
269      // erase the tracking image
270      OnInvertTracker(hWnd, &lpCurSpltr->m_dragRect);
271      // Release the mouse
272      ReleaseCapture();
273      // set tracking to false
274      bTracking = FALSE;
275      SetCursor(LoadCursor(0, IDC_ARROW));
276      // set the new splitter position
277      nSplitterOffset[currentSplitter] = lpCurSpltr->m_dragRect.left;
278      // Redraw the screen area
279      ResizePickerControls(hWnd);
280      UpdateScreenShot();
281      InvalidateRect(GetMainWindow(),NULL,TRUE);
282   }
283}
284
285UINT SplitterHitTest(HWND hWnd, POINTS p)
286{
287   RECT  rect;
288   POINT pt;
289   int   i;
290
291   pt.x = p.x;
292   pt.y = p.y;
293
294   // Check which area we hit
295   ClientToScreen(hWnd, &pt);
296
297   for (i = 0; i < numSplitters; i++)
298   {
299      GetWindowRect(splitter[i].m_hWnd, &rect);
300      if (PtInRect(&rect, pt))
301      {
302         lpCurSpltr = &splitter[i];
303         currentSplitter = i;
304         // We hit the splitter
305         return SPLITTER_HITITEM;
306      }
307   }
308   lpCurSpltr = 0;
309   // We missed the splitter
310   return SPLITTER_HITNOTHING;
311}
312
313void OnMouseMove(HWND hWnd, UINT nFlags, POINTS p)
314{
315   if (bTracking)   // move the tracking image
316   {
317      int    nWidth;
318      RECT   rect;
319      POINT   pt;
320
321      pt.x = (int)p.x;
322      pt.y = (int)p.y;
323
324      ClientToScreen(hWnd, &pt);
325      GetWindowRect(hWnd, &rect);
326      if (! PtInRect(&rect, pt))
327      {
328         if ((short)pt.x < (short)rect.left)
329            pt.x = rect.left;
330         if ((short)pt.x > (short)rect.right)
331            pt.x = rect.right;
332         pt.y = rect.top + 1;
333      }
334
335      ScreenToClient(hWnd, &pt);
336
337      // Erase the old tracking image
338      OnInvertTracker(hWnd, &lpCurSpltr->m_dragRect);
339     
340      // calc the new one based on p.x draw it
341      nWidth = lpCurSpltr->m_dragRect.right - lpCurSpltr->m_dragRect.left;
342      lpCurSpltr->m_dragRect.right = pt.x + nWidth / 2;
343      lpCurSpltr->m_dragRect.left  = pt.x - nWidth / 2;
344
345      if (pt.x - nWidth / 2 > lpCurSpltr->m_limitRect.right)
346      {
347         lpCurSpltr->m_dragRect.right = lpCurSpltr->m_limitRect.right;
348         lpCurSpltr->m_dragRect.left  = lpCurSpltr->m_dragRect.right - nWidth;
349      }
350      if (pt.x + nWidth / 2 < lpCurSpltr->m_limitRect.left)
351      {
352         lpCurSpltr->m_dragRect.left  = lpCurSpltr->m_limitRect.left;
353         lpCurSpltr->m_dragRect.right = lpCurSpltr->m_dragRect.left + nWidth;
354      }
355      OnInvertTracker(hWnd, &lpCurSpltr->m_dragRect);
356   }
357   else
358   {
359      switch(SplitterHitTest(hWnd, p))
360      {
361      case SPLITTER_HITNOTHING:
362         SetCursor(LoadCursor(0, IDC_ARROW));
363         break;
364      case SPLITTER_HITITEM:
365         SetCursor(hSplitterCursor);
366         break;
367      }
368   }
369}
370
371void OnLButtonDown(HWND hWnd, UINT nFlags, POINTS p)
372{
373   if (!bTracking) // See if we need to start a splitter drag
374   {
375      StartTracking(hWnd, SplitterHitTest(hWnd, p));
376   }
377}
378
379void OnLButtonUp(HWND hWnd, UINT nFlags, POINTS p)
380{
381   if (bTracking)
382   {
383      StopTracking(hWnd);
384   }
385}
386
387int GetSplitterCount(void)
388{
389   int nSplitterCount = 0;
390   while(g_splitterInfo[nSplitterCount].dPosition > 0)
391      nSplitterCount++;
392   return nSplitterCount;
393}
394
395/* End of file */
src/osd/windows/ui/directinput.c
r995r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11 ***************************************************************************/
12
13/***************************************************************************
14   
15  directinput.c
16
17  Direct Input routines.
18 
19 ***************************************************************************/
20
21#define WIN32_LEAN_AND_MEAN
22#include <windows.h>
23
24// undef WINNT for dinput.h to prevent duplicate definition
25#undef WINNT
26#undef DIRECTINPUT_VERSION
27#define DIRECTINPUT_VERSION 0x0700
28#include <dinput.h>
29
30#include "DirectInput.h"
31#include "M32Util.h"
32
33/***************************************************************************
34   function prototypes
35 ***************************************************************************/
36
37/***************************************************************************
38   External variables
39 ***************************************************************************/
40
41/***************************************************************************
42   Internal structures
43 ***************************************************************************/
44
45/***************************************************************************
46   Internal variables
47 ***************************************************************************/
48
49static LPDIRECTINPUT di = NULL;
50
51static HANDLE hDLL = NULL;
52
53/***************************************************************************
54   External functions   
55 ***************************************************************************/
56
57/****************************************************************************
58 *      DirectInputInitialize
59 *
60 *      Initialize the DirectInput variables.
61 *
62 *      This entails the following functions:
63 *
64 *         DirectInputCreate
65 *
66 ****************************************************************************/
67
68typedef HRESULT (WINAPI *dic_proc)(HINSTANCE hinst, DWORD dwVersion, LPDIRECTINPUT *ppDI,
69                           LPUNKNOWN punkOuter);
70
71BOOL DirectInputInitialize()
72{
73   HRESULT   hr;
74   UINT     error_mode;
75   dic_proc  dic;
76
77   if (hDLL != NULL)
78      return TRUE;
79
80   hDLL = NULL;
81
82   /* Turn off error dialog for this call */
83   error_mode = SetErrorMode(0);
84   hDLL = LoadLibrary(TEXT("dinput.dll"));
85   SetErrorMode(error_mode);
86
87   if (hDLL == NULL)
88      return FALSE;
89
90#ifdef UNICODE
91   dic = (dic_proc)GetProcAddress(hDLL, "DirectInputCreateW");
92#else
93   dic = (dic_proc)GetProcAddress(hDLL, "DirectInputCreateA");
94#endif
95   if (dic == NULL)
96      return FALSE;
97
98   hr = dic(GetModuleHandle(NULL), DIRECTINPUT_VERSION, &di, NULL);
99
100   if (FAILED(hr))
101   {
102      hr = dic(GetModuleHandle(NULL), 0x0300, &di, NULL);
103
104      if (FAILED(hr))
105      {
106         ErrorMsg("DirectInputCreate failed! error=%x\n", hr);
107         di = NULL;
108         return FALSE;
109      }
110   }
111   return TRUE;
112}
113
114/****************************************************************************
115 *
116 *      DirectInputClose
117 *
118 *      Terminate our usage of DirectInput.
119 *
120 ****************************************************************************/
121
122void DirectInputClose()
123{
124   /*
125      Release any lingering IDirectInput object.
126   */
127   if (di)
128   {
129      IDirectInput_Release(di);
130      di = NULL;
131   }
132}
133
134BOOL CALLBACK inputEnumDeviceProc(LPCDIDEVICEINSTANCE pdidi, LPVOID pv)
135{
136   GUID *pguidDevice;
137
138   /* report back the instance guid of the device we enumerated */
139   if (pv)
140   {
141      pguidDevice  = (GUID *)pv;
142      *pguidDevice = pdidi->guidInstance;
143   }
144
145   /* BUGBUG for now, stop after the first device has been found */
146   return DIENUM_STOP;
147}
148
149HRESULT SetDIDwordProperty(LPDIRECTINPUTDEVICE2 pdev, REFGUID guidProperty,
150                     DWORD dwObject, DWORD dwHow, DWORD dwValue)
151{
152   DIPROPDWORD dipdw;
153
154   dipdw.diph.dwSize      = sizeof(dipdw);
155   dipdw.diph.dwHeaderSize = sizeof(dipdw.diph);
156   dipdw.diph.dwObj      = dwObject;
157   dipdw.diph.dwHow      = dwHow;
158   dipdw.dwData         = dwValue;
159
160   return IDirectInputDevice2_SetProperty(pdev, guidProperty, &dipdw.diph);
161}
162
163LPDIRECTINPUT GetDirectInput(void)
164{
165   return di;
166}
167/***************************************************************************
168   Internal functions
169 ***************************************************************************/
src/osd/windows/ui/bitmask.c
r995r996
1/* Bitmask.c - Bitmask support routines - MSH 11/19/1998 */
2
3#define WIN32_LEAN_AND_MEAN
4#include <windows.h>
5
6#include "bitmask.h"
7#include <stdlib.h> /* For malloc and free */
8
9/* Bit routines */
10static UCHAR maskTable[8] = {
11   0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01
12};
13
14/* Create a new LPBITS struct and return the new structure
15 * initialized to 'all bits cleared'
16 *
17 * nLength is the number of desired bits
18 */
19LPBITS NewBits(UINT nLength)
20{
21   LPBITS lpBits = 0;
22   UINT   nSize = (nLength+7) / 8;
23
24   lpBits = (LPBITS)malloc(sizeof(BITS));
25   if (lpBits)
26   {
27      lpBits->m_lpBits = (UCHAR *)malloc(nSize);
28      if (lpBits->m_lpBits)
29      {
30         memset(lpBits->m_lpBits, '\0', nSize);
31         lpBits->m_nSize = nSize;
32      }
33      else
34      {
35         free(lpBits);
36         lpBits = 0;
37      }
38   }
39
40   return lpBits;
41}
42
43void DeleteBits(LPBITS lpBits)
44{
45   if (!lpBits)
46      return;
47
48   if (lpBits->m_nSize && lpBits->m_lpBits)
49      free(lpBits->m_lpBits);
50
51   free(lpBits);
52}
53
54/* Test the 'nBit'th bit */
55BOOL TestBit(LPBITS lpBits, UINT nBit)
56{
57   UINT   offset;
58   UCHAR   mask;
59
60   if (nBit < 0 || !lpBits || !lpBits->m_lpBits)
61      return FALSE;
62
63   offset = nBit >> 3;
64
65   if (offset >= lpBits->m_nSize)
66   {
67      return FALSE;
68   }
69
70   mask = maskTable[nBit & 7];
71   return   (lpBits->m_lpBits[offset] & mask) ? TRUE : FALSE;
72}
73
74/* Set the 'nBit'th bit */
75void SetBit(LPBITS lpBits, UINT nBit)
76{
77   UINT   offset;
78   UCHAR   mask;
79
80   if (nBit < 0 || !lpBits || !lpBits->m_lpBits)
81      return;
82
83   offset = nBit >> 3;
84
85   if (offset >= lpBits->m_nSize)
86   {
87      return;
88   }
89
90   mask = maskTable[nBit & 7];
91   lpBits->m_lpBits[offset] |= mask;
92}
93
94/* Clear the 'nBit'th bit */
95void ClearBit(LPBITS lpBits, UINT nBit)
96{
97   UINT   offset;
98   UCHAR   mask;
99
100   if (nBit < 0 || !lpBits || !lpBits->m_lpBits)
101      return;
102
103   offset = nBit >> 3;
104
105   if (offset >= lpBits->m_nSize)
106   {
107      return;
108   }
109
110   mask = maskTable[nBit & 7];
111   lpBits->m_lpBits[offset] &= ~mask;
112}
113
114/* Set or Clear all bits as specified by 'bSet' */
115void SetAllBits(LPBITS lpBits, BOOL bSet)
116{
117   if (lpBits && lpBits->m_nSize != 0 && lpBits->m_lpBits)
118      memset(lpBits->m_lpBits, (!bSet) ? '\0' : '\xFF', lpBits->m_nSize);
119}
120
121/* Find next bit that matches 'bSet'
122 *
123 * 'nStartPos' specifies the bit to start search after
124 * 'bSet' specifies to search for a set or unset bit
125 *
126 * Returns -1 if no bits are found
127 */
128int FindBit(LPBITS lpBits, int nStartPos, BOOL bSet)
129{
130   UINT   end;
131   UINT   i;
132   BOOL   res;
133
134   if (!lpBits || !lpBits->m_nSize || !lpBits->m_lpBits)
135      return -1;
136
137   end = lpBits->m_nSize << 3;
138
139   if (nStartPos < 0)
140      nStartPos = 0;
141
142   for (i = nStartPos; i < end; i++)
143   {
144      res = (TestBit(lpBits, i)) ? TRUE : FALSE;
145      if ((res && bSet) || (!res && !bSet))
146         return i;
147   }
148
149   return -1;
150}
151
152/* End of source file */
src/osd/windows/ui/resource.h
r995r996
1//{{NO_DEPENDENCIES}}
2// Microsoft Visual C++ generated include file.
3// Used by mame32.rc
4//
5#define IDPAUSE                         3
6#define IDAPPLY                         4
7#define IDS_UI_FILE                     71
8#define IDS_UI_VIEW                     72
9#define IDS_UI_OPTIONS                  73
10#define IDS_UI_HELP                     74
11#define IDS_UI_TOOLBAR                  81
12#define IDS_UI_STATUSBAR                82
13#define IDS_UI_FOLDERLIST               83
14#define IDS_UI_SCREENSHOT               84
15#define IDS_UI_SPACER1                  85
16#define IDS_UI_LARGEICONS               86
17#define IDS_UI_SMALLICONS               87
18#define IDS_UI_LIST                     88
19#define IDS_UI_DETAILS                  89
20#define IDS_UI_SPACER2                  90
21#define IDS_UI_ARRANGE                  91
22#define IDS_UI_LINEUPICONS              92
23#define IDS_UI_REFRESH                  93
24#define IDS_UI_CUSTOMIZE                94
25#define IDD_MAIN                        101
26#define IDA_TAB_KEYS                    106
27#define IDI_MAME32_ICON                 107
28#define IDD_ABOUT                       108
29#define IDR_MAIN_MENU                   109
30#define IDR_UI_MENU                     110
31#define IDW_STATUS                      112
32#define IDB_ABOUT                       113
33#define IDD_DIRECTX                     114
34#define IDD_AUDIT                       115
35#define IDD_DIRECTORIES                 116
36#define IDD_CUSTOM_FILE                 117
37#define IDR_CONTEXT_MENU                118
38#define IDI_WIN_NOROMS                  119
39#define IDI_WIN_ROMS                    120
40#define IDI_WIN_UNKNOWN                 121
41#define IDI_WIN_CLONE                   122
42#define IDI_WIN_REDX                    123
43#define IDI_FOLDER_OPEN                 124
44#define IDI_FOLDER                      125
45#define IDI_FOLDER_AVAILABLE            126
46#define IDI_FOLDER_MANUFACTURER         127
47#define IDI_FOLDER_UNAVAILABLE          128
48#define IDI_FOLDER_YEAR                 129
49#define IDI_FOLDER_SOURCE               130
50#define IDI_MANUFACTURER                131
51#define IDI_WORKING                     132
52#define IDI_NONWORKING                  133
53#define IDI_YEAR                        134
54#define IDI_SOUND                       135
55#define IDI_CPU                         136
56#define IDI_HARDDISK                    137
57#define IDI_SOURCE                      138
58#define IDR_CONTEXT_HEADER              151
59#define IDD_PROP_GAME                   152
60#define IDD_PROP_AUDIT                  153
61#define IDD_PROP_DISPLAY                154
62#define IDD_PROP_SOUND                  155
63#define IDD_PROP_ADVANCED               156
64#define IDD_PROP_INPUT                  157
65#define IDD_PROP_MISC                   158
66#define IDD_PROP_VECTOR                 159
67#define IDD_COLUMNS                     160
68#define IDI_KEYBOARD                    161
69#define IDI_JOYSTICK                    162
70#define IDI_DISPLAY                     163
71#define IDI_CHECKMARK                   164
72#define IDC_CURSOR_HSPLIT               165
73#define IDB_TOOLBAR                     166
74#define IDB_PROP_DISPLAY                167
75#define IDR_CONTEXT_TREE                168
76#define IDD_FILTERS                     169
77#define IDD_RESET                       170
78#define IDD_LOAD_PROGRESS               171
79#define IDD_INTERFACE_OPTIONS           173
80#define IDD_PROP_HISTORY                176
81#define IDD_ROM_ERROR                   177
82#define IDD_LANGUAGE                    178
83#define IDD_ERROR                       179
84#define IDR_CONTEXT_SCREENSHOT          181
85#define IDI_HEADER_UP                   182
86#define IDI_HEADER_DOWN                 183
87#define IDD_PROP_DIRECT3D               184
88#define IDD_PROP_CONTROLLER             185
89#define IDD_PROP_SCREEN                 187
90#define IDI_SOUNDTAB                    666
91#define IDC_LIST                        1000
92#define IDC_PLAY                        1001
93#define IDC_DISPLAYS                    1002
94#define IDC_JOYSTICK                    1003
95#define IDC_VECTORTEXT                  1004
96#define IDC_SIZES                       1005
97#define IDC_USE_TRAK                    1006
98#define IDC_DISPLAYTYPE                 1007
99#define IDC_TRAK_SENSITIVITY            1008
100#define IDC_FRAMESKIP                   1009
101#define IDC_ROTATE                      1010
102#define IDC_HELP_TEXT                   1011
103#define IDC_SCREEN                      1012
104#define IDC_TAB                         1013
105#define IDC_VIEW                        1014
106#define IDC_SCREEN2                     1015
107#define IDC_SCREENSELECT                1015
108#define IDC_CHEAT                       1016
109#define IDC_LOG                         1017
110#define IDC_ARTWORK_CROP                1018
111#define IDC_OVERLAYS                    1019
112#define IDC_BEZELS                      1021
113#define IDC_SLEEP                       1022
114#define IDC_GAMMA                       1023
115#define IDC_BRIGHTCORRECT               1024
116#define IDC_USE_DEFAULT                 1025
117#define IDC_CONTRAST                    1026
118#define IDC_SAMPLERATE                  1027
119#define IDC_NUMSCREENS                  1028
120#define IDC_ANTIALIAS                   1029
121#define IDC_BEAM                        1030
122#define IDC_FLICKER                     1031
123#define IDC_FLIPX                       1032
124#define IDC_FLIPY                       1033
125#define IDC_BACKDROPS                   1034
126#define IDC_DIRECTX_HELP                1035
127#define IDC_FLICKERDISP                 1035
128#define IDB_WEB_PAGE                    1036
129#define IDC_FSCONTRAST                  1036
130#define IDC_ROMS_PROGRESS               1037
131#define IDC_CONTRASTDISP                1037
132#define IDC_ROMS_CORRECT                1038
133#define IDC_FSCONTRASTDISP              1038
134#define IDC_ROMS_INCORRECT              1039
135#define IDC_NUMSCREENSDISP              1039
136#define IDC_ROMS_TOTAL                  1040
137#define IDC_SAMPLES_PROGRESS            1041
138#define IDC_SAMPLES_CORRECT             1042
139#define IDC_BEAMDISP                    1042
140#define IDC_SAMPLES_INCORRECT           1043
141#define IDC_SAMPLES_TOTAL               1044
142#define IDC_AUDIT_DETAILS               1045
143#define IDC_USE_FM_YM3812               1046
144#define IDC_DIR_COMBO                   1047
145#define IDC_DIR_LIST                    1048
146#define IDC_DIR_BROWSE                  1049
147#define IDC_DIR_INSERT                  1050
148#define IDC_DIR_DELETE                  1051
149#define IDC_FLICKERTEXT                 1052
150#define IDC_SSFRAME                     1054
151#define IDC_PRESCALE                    1055
152#define IDC_SSNONE                      1056
153#define IDC_SSPICTURE                   1057
154#define IDC_BEAMTEXT                    1058
155#define IDC_COLORSTEXT                  1059
156#define IDC_MULTIKEYBOARD               1059
157#define IDC_SIZETEXT                    1060
158#define IDC_TRACKSPINTEXT               1061
159#define IDC_INPUTDEVTEXT                1062
160#define IDC_RATETEXT                    1063
161#define IDC_LISTAVAILABLECOLUMNS        1064
162#define IDC_LISTSHOWCOLUMNS             1065
163#define IDC_BUTTONADD                   1066
164#define IDC_BUTTONREMOVE                1067
165#define IDC_BUTTONMOVEDOWN              1068
166#define IDC_BUTTONMOVEUP                1069
167#define IDC_PROP_SOUND                  1070
168#define IDC_PROP_CPU                    1071
169#define IDC_PROP_TITLE                  1072
170#define IDC_PROP_MANUFACTURED           1073
171#define IDC_PROP_STATUS                 1074
172#define IDC_PROP_SCREEN                 1075
173#define IDC_PROP_COLORS                 1076
174#define IDC_PROP_ROMS                   1077
175#define IDC_PROP_SAMPLES                1078
176#define IDC_PROP_CLONEOF_TEXT           1079
177#define IDC_PROP_CLONEOF                1080
178#define IDC_DEPTH                       1081
179#define IDC_VERSION                     1082
180#define IDC_ARTWORK                     1083
181#define IDC_FSGAMMA                     1084
182#define IDC_GAMMADISP                   1085
183#define IDC_FSBRIGHTNESS                1086
184#define IDC_FSGAMMADISP                 1087
185#define IDC_PRESCALEDISP                1088
186#define IDC_BRIGHTCORRECTDISP           1089
187#define IDC_FSBRIGHTNESSDISP            1090
188#define IDC_AUTOFRAMESKIP               1091
189#define IDC_TREE                        1092
190#define IDC_WINDOWED                    1093
191#define IDC_STEREO                      1094
192#define IDC_PROP_RESET                  1095
193#define IDC_SPLITTER                    1096
194#define IDC_SPLITTER2                   1097
195#define IDC_DIVIDER                     1098
196#define IDC_FILTER_VECTOR               1099
197#define IDC_FILTER_RASTER               1100
198#define IDC_FILTER_UNAVAILABLE          1101
199#define IDC_FILTER_NONWORKING           1102
200#define IDC_FILTER_CLONES               1103
201#define IDC_RESET_GAMES                 1104
202#define IDC_RESET_UI                    1105
203#define IDC_RESET_FILTERS               1106
204#define IDC_RESET_EFFECT                1107
205#define IDC_RESET_DEFAULT               1108
206#define IDC_FILTER_ORIGINALS            1109
207#define IDC_FILTER_WORKING              1110
208#define IDC_FILTER_AVAILABLE            1111
209#define IDC_CONFIGURETEXT               1112
210#define IDC_JOYMAPTEXT                  1113
211#define IDC_START_GAME_CHECK            1114
212#define IDC_VOLUME                      1115
213#define IDC_VOLUMEDISP                  1116
214#define IDC_PROP_HISTORY                1117
215#define IDC_HISTORY                     1118
216#define IDC_SAMPLES                     1119
217#define IDC_ERROR_DETAILS               1120
218#define IDC_TRIPLE_BUFFER               1121
219#define IDC_LOAD_ROMNAME                1122
220#define IDC_DEFAULT_INPUT               1123
221#define IDC_LANGUAGECHECK               1124
222#define IDC_LANGUAGEBROWSE              1125
223#define IDC_LANGUAGEEDIT                1126
224#define IDC_FILTER_EDIT                 1127
225#define IDC_ABOUT                       1128
226#define IDC_PROP_DISPLAY                1129
227#define IDC_USE_SOUND                   1130
228#define IDC_WAITVSYNC                   1131
229#define IDC_HWSTRETCH                   1132
230#define IDC_SWITCHRES                   1133
231#define IDC_MAXIMIZE                    1134
232#define IDC_KEEPASPECT                  1140
233#define IDC_SYNCREFRESH                 1141
234#define IDC_USE_MOUSE                   1143
235#define IDC_THROTTLE                    1144
236#define IDC_VOLUMETEXT                  1146
237#define IDC_REFRESH                     1148
238#define IDC_REFRESHTEXT                 1149
239#define IDC_EFFECT                      1150
240#define IDC_FSGAMMATEXT                 1151
241#define IDC_STEADYKEY                   1152
242#define IDC_ASPECTRATIO                 1153
243#define IDC_ASPECTRATION                1154
244#define IDC_ASPECTRATIOD                1155
245#define IDC_ASPECTRATIOTEXT             1156
246#define IDC_JOY_GUI                     1157
247#define IDC_BROADCAST                   1158
248#define IDC_JDZ                         1159
249#define IDC_JDZDISP                     1160
250#define IDC_JDZTEXT                     1161
251#define IDC_JSATTEXT                    1162
252#define IDC_JSAT                        1163
253#define IDC_JSATDISP                    1164
254#define IDC_AUDIO_LATENCY_DISP          1165
255#define IDC_PLAY_GAME                   1166
256#define IDC_LIGHTGUN                    1167
257#define IDC_SSTAB                       1168
258#define IDC_GAME_ICON                   1169
259#define IDC_RANDOM_BG                   1170
260#define IDC_CUSTOM_TREE                 1171
261#define IDC_CUSTOMFILEBROWSE            1172
262#define IDC_CUSTOMFILE_GAME             1173
263#define IDC_LOAD_STATUS                 1174
264#define IDC_ERROR_TEXT                  1175
265#define IDC_ARTMISCTEXT                 1176
266#define IDC_ENABLE_AUTOSAVE             1177
267#define IDC_SKIP_GAME_INFO              1178
268#define IDC_PROP_SOURCE                 1179
269#define IDC_PAUSEBRIGHT                 1181
270#define IDC_PAUSEBRIGHTDISP             1182
271#define IDC_HIGH_PRIORITY               1183
272#define IDC_D3D_FILTER                  1184
273#define IDC_HIDE_MOUSE                  1185
274#define IDC_AUDIO_LATENCY               1186
275#define IDC_D3D_VERSION                 1187
276#define IDC_AUDIT_DETAILS_PROP          1188
277#define IDC_CYCLETIME                   1189
278#define IDC_CYCLETIMESEC                1190
279#define IDC_AUDIO_LATENCY_TEXT          1191
280#define IDC_STRETCH_SCREENSHOT_LARGER   1192
281#define IDC_FILTER_INHERIT              1193
282#define IDC_RESET_PLAYTIME              1194
283#define IDC_RESET_PLAYCOUNT             1195
284#define IDC_INHERITED                   1196
285#define IDC_KEY_GUI                     1197
286#define IDC_RELOAD                      1198
287#define IDC_DUAL_LIGHTGUN               1199
288#define IDC_NOOFFSET_CLONES             1200
289#define IDC_BIOS                        1201
290#define IDC_HISTORY_TAB                 1202
291#define IDC_GAME_CAPTION                1203
292#define IDC_SCREENSHOT_BORDERSIZE       1204
293#define IDC_SCREENSHOT_BORDERCOLOR      1205
294#define IDC_CYCLETIMESECTXT             1206
295#define IDC_SCREENSHOT_BORDERSIZETXT    1207
296#define IDC_PADDLE                      1208
297#define IDC_ADSTICK                     1209
298#define IDC_PEDAL                       1210
299#define IDC_DIAL                        1211
300#define IDC_TRACKBALL                   1212
301#define IDC_LIGHTGUNDEVICE              1213
302#define IDC_HIGH_PRIORITY_TEXT          1216
303#define IDC_HIGH_PRIORITYTXT            1217
304#define IDC_SELECT_EFFECT               1218
305#define IDC_MULTITHREAD_RENDERING       1219
306#define IDC_ASPECT                      1220
307#define IDC_RESOLUTION                  1221
308#define IDC_LOAD_PROGRESS               1223
309#define IDC_FSBRIGHTNESSTEXT            1224
310#define IDC_FSCONTRASTTEXT              1225
311#define IDC_VIDEO_MODE                  1226
312#define IDC_SCREENSELECTTEXT            1227
313#define IDC_CHECK2                      1229
314#define IDC_MULTIMOUSE                  1229
315#define ID_CONTEXT_SHOW_FOLDER_START    39000
316#define ID_CONTEXT_SHOW_FOLDER_END      39200
317#define ID_FILE_EXIT                    40001
318#define ID_ABOUT                        40003
319#define ID_FILE_PLAY                    40004
320#define ID_HELP_ABOUT                   40006
321#define ID_VIEW_LARGE_ICON              40007
322#define ID_VIEW_SMALL_ICON              40008
323#define ID_VIEW_LIST_MENU               40009
324#define ID_VIEW_DETAIL                  40010
325#define ID_VIEW_GROUPED                 40011
326#define ID_OPTIONS_FONT                 40012
327#define ID_OPTIONS_CLONE_COLOR          40013
328#define ID_OPTIONS_DIR                  40014
329#define ID_OPTIONS_DEFAULTS             40015
330#define ID_OPTIONS_RESET_DEFAULTS       40016
331#define ID_OPTIONS_INTERFACE            40017
332#define ID_FILE_AUDIT                   40018
333#define ID_FILE_PLAY_RECORD             40019
334#define ID_FILE_PLAY_BACK               40020
335#define ID_FILE_PLAY_RECORD_WAVE        40021
336#define ID_FILE_PLAY_RECORD_MNG         40022
337#define ID_VIEW_PICTURE_AREA            40023
338#define ID_HELP_CONTENTS                40025
339#define ID_HELP_WHATS_NEW32             40026
340#define ID_HELP_TROUBLE                 40027
341#define ID_HELP_RELEASE                 40028
342#define ID_HELP_WHATS_NEW               40029
343#define ID_HELP_CHEATS                  40030
344#define ID_VIEW_BYGAME                  40034
345#define ID_VIEW_BYDIRECTORY             40035
346#define ID_VIEW_BYMANUFACTURER          40036
347#define ID_VIEW_BYYEAR                  40037
348#define ID_VIEW_BYTYPE                  40038
349#define ID_VIEW_BYTIMESPLAYED           40039
350#define ID_VIEW_LINEUPICONS             40040
351#define ID_UPDATE_GAMELIST              40042
352#define ID_SORT_ASCENDING               40045
353#define ID_SORT_DESCENDING              40046
354#define ID_CUSTOMIZE_FIELDS             40048
355#define ID_GAME_PROPERTIES              40049
356#define ID_VIEW_PAGETAB                 40050
357#define ID_VIEW_FOLDERS                 40051
358#define ID_VIEW_TOOLBARS                40052
359#define ID_VIEW_STATUS                  40053
360#define ID_CONTEXT_FILTERS              40054
361#define ID_CONTEXT_RENAME_CUSTOM        40055
362#define ID_CONTEXT_ADD_CUSTOM           40057
363#define ID_CONTEXT_REMOVE_CUSTOM        40058
364#define ID_GAME_AUDIT                   40059
365#define ID_CONTEXT_SELECT_RANDOM        40060
366#define ID_OPTIONS_LANGUAGE             40061
367#define ID_VIEW_TAB_SCREENSHOT          40062
368#define ID_VIEW_TAB_FLYER               40063
369#define ID_VIEW_TAB_CABINET             40064
370#define ID_VIEW_TAB_MARQUEE             40065
371#define ID_VIEW_TAB_TITLE               40066
372#define ID_VIEW_TAB_CONTROL_PANEL       40067
373#define ID_VIEW_TAB_HISTORY             40068
374#define ID_OPTIONS_BG                   40070
375#define ID_TOGGLE_TAB_SCREENSHOT        40071
376#define ID_TOGGLE_TAB_FLYER             40072
377#define ID_TOGGLE_TAB_CABINET           40073
378#define ID_TOGGLE_TAB_MARQUEE           40074
379#define ID_TOGGLE_TAB_TITLE             40075
380#define ID_TOGGLE_TAB_CONTROL_PANEL     40076
381#define ID_TOGGLE_TAB_HISTORY           40077
382#define ID_VIEW_FULLSCREEN              40079
383#define ID_CONTEXT_RESET_PLAYTIME       40080
384#define ID_CONTEXT_RESET_PLAYCOUNT      40081
385#define ID_FOLDER_PROPERTIES            40082
386#define ID_FOLDER_AUDIT                 40083
387#define ID_UI_UP                        40084
388#define ID_UI_DOWN                      40085
389#define ID_UI_LEFT                      40086
390#define ID_UI_RIGHT                     40087
391#define ID_UI_START                     40088
392#define ID_UI_PGUP                      40089
393#define ID_UI_PGDOWN                    40090
394#define ID_UI_HOME                      40091
395#define ID_UI_END                       40092
396#define ID_UI_HISTORY_UP                40093
397#define ID_UI_HISTORY_DOWN              40094
398#define ID_FILE_LOADSTATE               40095
399#define ID_FOLDER_SOURCEPROPERTIES      40096
400#define ID_FOLDER_VECTORPROPERTIES      40097
401#define IDC_STATIC                      -1
402
403// Next default values for new objects
404//
405#ifdef APSTUDIO_INVOKED
406#ifndef APSTUDIO_READONLY_SYMBOLS
407#define _APS_NO_MFC                     1
408#define _APS_3D_CONTROLS                     1
409#define _APS_NEXT_RESOURCE_VALUE        188
410#define _APS_NEXT_COMMAND_VALUE         40098
411#define _APS_NEXT_CONTROL_VALUE         1230
412#define _APS_NEXT_SYMED_VALUE           101
413#endif
414#endif
src/osd/windows/ui/splitters.h
r995r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Splitter Code (C) 1998 Mike Haaland <mhaaland@hypertech.com>
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11 ***************************************************************************/
12
13/* Written by Mike Haaland <mhaaland@hypertech.com> */
14
15#ifndef SPLITTER_H
16#define SPLITTER_H
17
18#if !defined(MAX)
19#define MIN(a, b) ((a) < (b) ? (a) : (b))
20#define MAX(a, b) ((a) > (b) ? (a) : (b))
21#endif
22
23enum eSplitterHits
24{
25   SPLITTER_HITNOTHING = 0,
26   SPLITTER_HITITEM
27};
28
29typedef struct horzSplitter
30{
31   HWND m_hWnd;
32   HWND m_hWndLeft;
33   HWND m_hWndRight;
34   RECT m_limitRect;
35   RECT m_dragRect;
36   void (*m_func)(HWND hWnd, LPRECT lpRect);
37} HZSPLITTER, *LPHZSPLITTER;
38
39/* Splitter routines */
40void    OnMouseMove(HWND hWnd, UINT nFlags, POINTS p);
41void    OnLButtonDown(HWND hWnd, UINT nFlags, POINTS p);
42void    OnLButtonUp(HWND hWnd, UINT nFlags, POINTS p);
43void    OnSizeSplitter(HWND hWnd);
44void    AddSplitter(HWND hWnd, HWND hWndLeft, HWND hWndRight,
45                    void (*func)(HWND hWnd,LPRECT lpRect));
46void    RecalcSplitters(void);
47void    AdjustSplitter2Rect(HWND hWnd, LPRECT lpRect);
48void    AdjustSplitter1Rect(HWND hWnd, LPRECT lpRect);
49BOOL    InitSplitters(void);
50void    SplittersExit(void);
51int     GetSplitterCount(void);
52
53extern int *nSplitterOffset;
54
55typedef struct
56{
57   double dPosition;
58   int nSplitterWindow;
59   int nLeftWindow;
60   int nRightWindow;
61   void (*pfnAdjust)(HWND hWnd,LPRECT lpRect);
62} SPLITTERINFO;
63
64extern const SPLITTERINFO g_splitterInfo[];
65
66
67#endif /* SPLITTER_H */
src/osd/windows/ui/directinput.h
r995r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5 
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11 ***************************************************************************/
12
13#ifndef DIRECTINPUT_H
14#define DIRECTINPUT_H
15
16#include <dinput.h>
17
18extern BOOL DirectInputInitialize(void);
19extern void DirectInputClose(void);
20
21extern BOOL CALLBACK inputEnumDeviceProc(LPCDIDEVICEINSTANCE pdidi, LPVOID pv);
22
23extern HRESULT SetDIDwordProperty(LPDIRECTINPUTDEVICE2 pdev, REFGUID guidProperty,
24                          DWORD dwObject, DWORD dwHow, DWORD dwValue);
25
26LPDIRECTINPUT GetDirectInput(void);
27
28#endif
src/osd/windows/ui/bitmask.h
r995r996
1#ifndef BITMASK_H
2#define BITMASK_H
3
4/* Bit array type */
5typedef struct
6{
7   UINT   m_nSize;
8   UCHAR*   m_lpBits;
9} BITS, * LPBITS;
10
11/* Bit functions */
12LPBITS   NewBits(UINT nLength /* in bits */);
13void   DeleteBits(LPBITS lpBits);
14BOOL   TestBit(LPBITS lpBits, UINT nBit);
15void   SetBit(LPBITS lpBits, UINT nBit);
16void   ClearBit(LPBITS lpBits, UINT nBit);
17void   SetAllBits(LPBITS lpBits, BOOL bSet);
18int    FindBit(LPBITS lpBits, int nStartPos, BOOL bSet);
19
20/* Linked list type */
21typedef struct
22{
23   LPVOID  data;
24   LPVOID  next;
25   LPVOID  prev;
26} NODE, * LPNODE;
27
28/* Linked list functions */
29
30#endif /* BITMASK_H */
src/osd/windows/ui/dirwatch.c
r995r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11 ***************************************************************************/
12
13#include <windows.h>
14#include <string.h>
15#include <tchar.h>
16#include "dirwatch.h"
17#include "ui/m32util.h"
18#include "strconv.h"
19
20typedef BOOL (WINAPI *READDIRECTORYCHANGESFUNC)(HANDLE hDirectory, LPVOID lpBuffer,
21      DWORD nBufferLength, BOOL bWatchSubtree, DWORD dwNotifyFilter,
22      LPDWORD lpBytesReturned, LPOVERLAPPED lpOverlapped,
23      LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine);
24
25
26struct DirWatcherEntry
27{
28   struct DirWatcherEntry *pNext;
29   HANDLE hDir;
30   WORD nIndex;
31   WORD nSubIndex;
32   BOOL bWatchSubtree;
33   OVERLAPPED overlapped;
34
35   union
36   {
37      FILE_NOTIFY_INFORMATION notify;
38      BYTE buffer[1024];
39   } u;
40
41   char szDirPath[1];
42};
43
44
45
46struct DirWatcher
47{
48   HMODULE hKernelModule;
49   READDIRECTORYCHANGESFUNC pfnReadDirectoryChanges;
50   
51   HWND hwndTarget;
52   UINT nMessage;
53
54   HANDLE hRequestEvent;
55   HANDLE hResponseEvent;
56   HANDLE hThread;
57   CRITICAL_SECTION crit;
58   struct DirWatcherEntry *pEntries;
59
60   // These are posted externally
61   BOOL bQuit;
62   BOOL bWatchSubtree;
63   WORD nIndex;
64   LPCSTR pszPathList;
65};
66
67
68
69static void DirWatcher_SetupWatch(PDIRWATCHER pWatcher, struct DirWatcherEntry *pEntry)
70{
71   DWORD nDummy;
72
73   memset(&pEntry->u, 0, sizeof(pEntry->u));
74
75   pWatcher->pfnReadDirectoryChanges(pEntry->hDir,
76      &pEntry->u,
77      sizeof(pEntry->u),
78      pEntry->bWatchSubtree,
79      FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_LAST_WRITE | FILE_NOTIFY_CHANGE_SIZE,
80      &nDummy,
81      &pEntry->overlapped,
82      NULL);
83}
84
85
86
87static void DirWatcher_FreeEntry(struct DirWatcherEntry *pEntry)
88{
89   if (pEntry->hDir)
90      CloseHandle(pEntry->hDir);
91   free(pEntry);
92}
93
94
95
96static BOOL DirWatcher_WatchDirectory(PDIRWATCHER pWatcher, int nIndex, int nSubIndex,
97   LPCSTR pszPath, BOOL bWatchSubtree)
98{
99   struct DirWatcherEntry *pEntry;
100   HANDLE hDir;
101
102   pEntry = malloc(sizeof(*pEntry) + strlen(pszPath));
103   if (!pEntry)
104      goto error;
105   memset(pEntry, 0, sizeof(*pEntry));
106   strcpy(pEntry->szDirPath, pszPath);
107   pEntry->overlapped.hEvent = pWatcher->hRequestEvent;
108
109   hDir = win_create_file_utf8(pszPath, FILE_LIST_DIRECTORY,
110      FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
111      NULL, OPEN_EXISTING,
112      FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED, NULL);
113   if (!hDir || (hDir == INVALID_HANDLE_VALUE))
114      goto error;
115
116   // Populate the entry
117   pEntry->hDir = hDir;
118   pEntry->bWatchSubtree = bWatchSubtree;
119   pEntry->nIndex = nIndex;
120   pEntry->nSubIndex = nSubIndex;
121
122   // Link in the entry
123   pEntry->pNext = pWatcher->pEntries;
124   pWatcher->pEntries = pEntry;
125
126   DirWatcher_SetupWatch(pWatcher, pEntry);
127   return TRUE;
128
129error:
130   if (pEntry)
131      DirWatcher_FreeEntry(pEntry);
132   return FALSE;
133}
134
135
136
137static void DirWatcher_Signal(PDIRWATCHER pWatcher, struct DirWatcherEntry *pEntry)
138{
139   LPSTR pszFileName;
140   LPSTR pszFullFileName;
141   BOOL bPause;
142   HANDLE hFile;
143   int nTries;
144   TCHAR* t_filename;
145
146   {
147      int nLength;
148      nLength = WideCharToMultiByte(CP_ACP, 0, pEntry->u.notify.FileName, -1, NULL, 0, NULL, NULL);
149      pszFileName = (LPSTR) alloca(nLength * sizeof(*pszFileName));
150      WideCharToMultiByte(CP_ACP, 0, pEntry->u.notify.FileName, -1, pszFileName, nLength, NULL, NULL);
151   }
152
153   // get the full path to this new file
154   pszFullFileName = (LPSTR) alloca(strlen(pEntry->szDirPath) + strlen(pszFileName) + 2);
155   strcpy(pszFullFileName, pEntry->szDirPath);
156   strcat(pszFullFileName, "\\");
157   strcat(pszFullFileName, pszFileName);
158
159   // attempt to busy wait until any result other than ERROR_SHARING_VIOLATION
160   // is generated
161   nTries = 100;
162   do
163   {
164      hFile = win_create_file_utf8(pszFullFileName, GENERIC_READ,
165         FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
166      if (hFile != INVALID_HANDLE_VALUE)
167         CloseHandle(hFile);
168
169      bPause = (nTries--) && (hFile == INVALID_HANDLE_VALUE)
170         && (GetLastError() == ERROR_SHARING_VIOLATION);
171      if (bPause)
172         Sleep(10);
173   }
174   while(bPause);
175
176   // send the message (assuming that we have a target)
177   if (pWatcher->hwndTarget)
178   {
179      t_filename = tstring_from_utf8(pszFileName);
180      if( !t_filename )
181         return;
182      SendMessage(pWatcher->hwndTarget,
183         pWatcher->nMessage,
184         (pEntry->nIndex << 16) | (pEntry->nSubIndex << 0),
185         (LPARAM)(LPCTSTR) win_tstring_strdup(t_filename));
186      free(t_filename);
187   }
188
189   DirWatcher_SetupWatch(pWatcher, pEntry);
190}
191
192
193
194static DWORD WINAPI DirWatcher_ThreadProc(LPVOID lpParameter)
195{
196   LPSTR pszPathList;
197   LPSTR s;
198   int nSubIndex;
199   PDIRWATCHER pWatcher = (PDIRWATCHER) lpParameter;
200   struct DirWatcherEntry *pEntry;
201   struct DirWatcherEntry **ppEntry;
202
203   do
204   {
205      WaitForSingleObject(pWatcher->hRequestEvent, INFINITE);
206
207      if (pWatcher->pszPathList)
208      {
209         // remove any entries with the same nIndex
210         ppEntry = &pWatcher->pEntries;
211         while(*ppEntry)
212         {
213            if ((*ppEntry)->nIndex == pWatcher->nIndex)
214            {
215               pEntry = *ppEntry;
216               *ppEntry = pEntry->pNext;
217               DirWatcher_FreeEntry(pEntry);
218            }
219            else
220            {
221               ppEntry = &(*ppEntry)->pNext;
222            }
223         }
224
225         // allocate our own copy of the path list
226         pszPathList = (LPSTR) alloca(strlen(pWatcher->pszPathList) + 1);
227         strcpy(pszPathList, pWatcher->pszPathList);
228         
229         nSubIndex = 0;
230         do
231         {
232            s = strchr(pszPathList, ';');
233            if (s)
234               *s = '\0';
235
236            if (*pszPathList)
237            {
238               DirWatcher_WatchDirectory(pWatcher, pWatcher->nIndex,
239                  nSubIndex++, pszPathList, pWatcher->bWatchSubtree);
240            }
241
242            pszPathList = s ? s + 1 : NULL;
243         }
244         while(pszPathList);
245
246         pWatcher->pszPathList = NULL;
247         pWatcher->bWatchSubtree = FALSE;
248      }
249      else
250      {
251         // we have to go through the list and find what has been hit
252         for (pEntry = pWatcher->pEntries; pEntry; pEntry = pEntry->pNext)
253         {
254            if (pEntry->u.notify.Action != 0)
255            {
256               DirWatcher_Signal(pWatcher, pEntry);
257            }
258         }
259      }
260
261      SetEvent(pWatcher->hResponseEvent);
262   }
263   while(!pWatcher->bQuit);
264   return 0;
265}
266
267
268
269PDIRWATCHER DirWatcher_Init(HWND hwndTarget, UINT nMessage)
270{
271   struct DirWatcher *pWatcher = NULL;
272   DWORD nThreadID;
273
274   // This feature does not exist on Win9x
275   if (GetVersion() >= 0x80000000)
276      goto error;
277
278   pWatcher = malloc(sizeof(struct DirWatcher));
279   if (!pWatcher)
280      goto error;
281   memset(pWatcher, 0, sizeof(*pWatcher));
282   InitializeCriticalSection(&pWatcher->crit);
283
284   pWatcher->hKernelModule = LoadLibrary(TEXT("kernel32.dll"));
285   if (!pWatcher->hKernelModule)
286      goto error;
287
288   pWatcher->pfnReadDirectoryChanges = (READDIRECTORYCHANGESFUNC)
289      GetProcAddress(pWatcher->hKernelModule, "ReadDirectoryChangesW");
290   if (!pWatcher->pfnReadDirectoryChanges)
291      goto error;
292
293   pWatcher->hRequestEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
294   if (!pWatcher->hRequestEvent)
295      goto error;
296
297   pWatcher->hResponseEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
298   if (!pWatcher->hRequestEvent)
299      goto error;
300
301   pWatcher->hThread = CreateThread(NULL, 0, DirWatcher_ThreadProc,
302      (LPVOID) pWatcher, 0, &nThreadID);
303
304   pWatcher->hwndTarget = hwndTarget;
305   pWatcher->nMessage = nMessage;
306   return pWatcher;
307
308error:
309   if (pWatcher)
310      DirWatcher_Free(pWatcher);
311   return NULL;
312}
313
314
315
316BOOL DirWatcher_Watch(PDIRWATCHER pWatcher, WORD nIndex, LPCSTR pszPathList, BOOL bWatchSubtrees)
317{
318   EnterCriticalSection(&pWatcher->crit);
319
320   pWatcher->nIndex = nIndex;
321   pWatcher->pszPathList = pszPathList;
322   pWatcher->bWatchSubtree = bWatchSubtrees;
323   SetEvent(pWatcher->hRequestEvent);
324
325   WaitForSingleObject(pWatcher->hResponseEvent, INFINITE);
326   LeaveCriticalSection(&pWatcher->crit);
327   return TRUE;
328}
329
330
331
332void DirWatcher_Free(PDIRWATCHER pWatcher)
333{
334   struct DirWatcherEntry *pEntry;
335   struct DirWatcherEntry *pNextEntry;
336
337   if (pWatcher->hThread)
338   {
339      EnterCriticalSection(&pWatcher->crit);
340      pWatcher->bQuit = TRUE;
341      SetEvent(pWatcher->hRequestEvent);
342      WaitForSingleObject(pWatcher->hThread, 1000);
343      LeaveCriticalSection(&pWatcher->crit);
344      CloseHandle(pWatcher->hThread);
345   }
346
347   DeleteCriticalSection(&pWatcher->crit);
348
349   pEntry = pWatcher->pEntries;
350   while(pEntry)
351   {
352      pNextEntry = pEntry->pNext;
353      DirWatcher_FreeEntry(pEntry);
354      pEntry = pNextEntry;
355   }
356
357   if (pWatcher->hKernelModule)
358      FreeLibrary(pWatcher->hKernelModule);
359   if (pWatcher->hRequestEvent)
360      CloseHandle(pWatcher->hRequestEvent);
361   if (pWatcher->hResponseEvent)
362      CloseHandle(pWatcher->hResponseEvent);
363   free(pWatcher);
364}
365
366
367
src/osd/windows/ui/m32main.c
r995r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11***************************************************************************/
12
13// import the main() from MAME, but rename it so we can call it indirectly
14#define main mame_main
15#include "windows/main.c"
16#undef main
17
18#include "screenshot.h"
19#include "win32ui.h"
20
21
22int WINAPI WinMain(HINSTANCE    hInstance,
23                   HINSTANCE    hPrevInstance,
24                   LPSTR        lpCmdLine,
25                   int          nCmdShow)
26{
27   return Mame32Main(hInstance, lpCmdLine, nCmdShow);
28}
src/osd/windows/ui/m32opts.c
r995r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11 ***************************************************************************/
12 
13 /***************************************************************************
14
15  options.c
16
17  Stores global options and per-game options;
18
19***************************************************************************/
20
21#define WIN32_LEAN_AND_MEAN
22
23#include <windows.h>
24#include <windowsx.h>
25#include <winreg.h>
26#include <commctrl.h>
27#include <assert.h>
28#include <stdio.h>
29#include <sys/stat.h>
30#include <math.h>
31#include <direct.h>
32#include <driver.h>
33#include <stddef.h>
34#include <tchar.h>
35
36#include "screenshot.h"
37#include "bitmask.h"
38#include "mame32.h"
39#include "m32util.h"
40#include "resource.h"
41#include "treeview.h"
42#include "file.h"
43#include "splitters.h"
44#include "dijoystick.h"
45#include "audit.h"
46#include "m32opts.h"
47#include "picker.h"
48#include "winmain.h"
49#include "windows/winutf8.h"
50#include "windows/strconv.h"
51
52#ifdef MESS
53#include "osd/windows/ui/optionsms.h"
54#endif // MESS
55
56#ifdef _MSC_VER
57#define snprintf _snprintf
58#endif
59
60/***************************************************************************
61    Internal function prototypes
62 ***************************************************************************/
63
64static void LoadFolderFilter(int folder_index,int filters);
65
66static file_error LoadSettingsFile(core_options *opts, const char *filename);
67static file_error SaveSettingsFile(core_options *opts, const char *filename);
68
69static void LoadOptionsAndSettings(void);
70
71static void  CusColorEncodeString(const COLORREF *value, char* str);
72static void  CusColorDecodeString(const char* str, COLORREF *value);
73
74static void  SplitterEncodeString(const int *value, char* str);
75static void  SplitterDecodeString(const char *str, int *value);
76
77static void  FontEncodeString(const LOGFONT *f, char *str);
78static void  FontDecodeString(const char* str, LOGFONT *f);
79
80static void TabFlagsEncodeString(int data, char *str);
81static void TabFlagsDecodeString(const char *str, int *data);
82
83#ifdef _MSC_VER
84#define snprintf _snprintf
85#endif
86
87/***************************************************************************
88    Internal defines
89 ***************************************************************************/
90
91#define UI_INI_FILENAME MAME32NAME "ui.ini"
92#define DEFAULT_OPTIONS_INI_FILENAME MAME32NAME ".ini"
93
94#define M32OPTION_LIST_MODE                  "list_mode"
95#define M32OPTION_CHECK_GAME               "check_game"
96#define M32OPTION_JOYSTICK_IN_INTERFACE         "joystick_in_interface"
97#define M32OPTION_KEYBOARD_IN_INTERFACE         "keyboard_in_interface"
98#define M32OPTION_CYCLE_SCREENSHOT            "cycle_screenshot"
99#define M32OPTION_STRETCH_SCREENSHOT_LARGER      "stretch_screenshot_larger"
100#define M32OPTION_SCREENSHOT_BORDER_SIZE      "screenshot_bordersize"
101#define M32OPTION_SCREENSHOT_BORDER_COLOR      "screenshot_bordercolor"
102#define M32OPTION_INHERIT_FILTER            "inherit_filter"
103#define M32OPTION_OFFSET_CLONES               "offset_clones"
104#define M32OPTION_GAME_CAPTION               "game_caption"
105#define M32OPTION_BROADCAST_GAME_NAME         "broadcast_game_name"
106#define M32OPTION_RANDOM_BACKGROUND            "random_background"
107#define M32OPTION_DEFAULT_FOLDER_ID            "default_folder_id"
108#define M32OPTION_SHOW_IMAGE_SECTION         "show_image_section"
109#define M32OPTION_SHOW_FOLDER_SECTION         "show_folder_section"
110#define M32OPTION_HIDE_FOLDERS               "hide_folders"
111#define M32OPTION_SHOW_STATUS_BAR            "show_status_bar"
112#define M32OPTION_SHOW_TABS                  "show_tabs"
113#define M32OPTION_SHOW_TOOLBAR               "show_tool_bar"
114#define M32OPTION_CURRENT_TAB               "current_tab"
115#define M32OPTION_WINDOW_X                  "window_x"
116#define M32OPTION_WINDOW_Y                  "window_y"
117#define M32OPTION_WINDOW_WIDTH               "window_width"
118#define M32OPTION_WINDOW_HEIGHT               "window_height"
119#define M32OPTION_WINDOW_STATE               "window_state"
120#define M32OPTION_CUSTOM_COLOR               "custom_color"
121#define M32OPTION_LIST_FONT                  "list_font"
122#define M32OPTION_TEXT_COLOR               "text_color"
123#define M32OPTION_CLONE_COLOR               "clone_color"
124#define M32OPTION_HIDE_TABS                  "hide_tabs"
125#define M32OPTION_HISTORY_TAB               "history_tab"
126#define M32OPTION_COLUMN_WIDTHS               "column_widths"
127#define M32OPTION_COLUMN_ORDER               "column_order"
128#define M32OPTION_COLUMN_SHOWN               "column_shown"
129#define M32OPTION_SPLITTERS                  "splitters"
130#define M32OPTION_SORT_COLUMN               "sort_column"
131#define M32OPTION_SORT_REVERSED               "sort_reversed"
132#define M32OPTION_LANGUAGE                  "language"
133#define M32OPTION_FLYER_DIRECTORY            "flyer_directory"
134#define M32OPTION_CABINET_DIRECTORY            "cabinet_directory"
135#define M32OPTION_MARQUEE_DIRECTORY            "marquee_directory"
136#define M32OPTION_TITLE_DIRECTORY            "title_directory"
137#define M32OPTION_CPANEL_DIRECTORY            "cpanel_directory"
138#define M32OPTION_ICONS_DIRECTORY            "icons_directory"
139#define M32OPTION_BACKGROUND_DIRECTORY         "background_directory"
140#define M32OPTION_FOLDER_DIRECTORY            "folder_directory"
141#define M32OPTION_UI_KEY_UP                  "ui_key_up"
142#define M32OPTION_UI_KEY_DOWN               "ui_key_down"
143#define M32OPTION_UI_KEY_LEFT               "ui_key_left"
144#define M32OPTION_UI_KEY_RIGHT               "ui_key_right"
145#define M32OPTION_UI_KEY_START               "ui_key_start"
146#define M32OPTION_UI_KEY_PGUP               "ui_key_pgup"
147#define M32OPTION_UI_KEY_PGDWN               "ui_key_pgdwn"
148#define M32OPTION_UI_KEY_HOME               "ui_key_home"
149#define M32OPTION_UI_KEY_END               "ui_key_end"
150#define M32OPTION_UI_KEY_SS_CHANGE            "ui_key_ss_change"
151#define M32OPTION_UI_KEY_HISTORY_UP            "ui_key_history_up"
152#define M32OPTION_UI_KEY_HISTORY_DOWN         "ui_key_history_down"
153#define M32OPTION_UI_KEY_CONTEXT_FILTERS      "ui_key_context_filters"
154#define M32OPTION_UI_KEY_SELECT_RANDOM         "ui_key_select_random"
155#define M32OPTION_UI_KEY_GAME_AUDIT            "ui_key_game_audit"
156#define M32OPTION_UI_KEY_GAME_PROPERTIES      "ui_key_game_properties"
157#define M32OPTION_UI_KEY_HELP_CONTENTS         "ui_key_help_contents"
158#define M32OPTION_UI_KEY_UPDATE_GAMELIST      "ui_key_update_gamelist"
159#define M32OPTION_UI_KEY_VIEW_FOLDERS         "ui_key_view_folders"
160#define M32OPTION_UI_KEY_VIEW_FULLSCREEN      "ui_key_view_fullscreen"
161#define M32OPTION_UI_KEY_VIEW_PAGETAB         "ui_key_view_pagetab"
162#define M32OPTION_UI_KEY_VIEW_PICTURE_AREA      "ui_key_view_picture_area"
163#define M32OPTION_UI_KEY_VIEW_STATUS         "ui_key_view_status"
164#define M32OPTION_UI_KEY_VIEW_TOOLBARS         "ui_key_view_toolbars"
165#define M32OPTION_UI_KEY_VIEW_TAB_CABINET      "ui_key_view_tab_cabinet"
166#define M32OPTION_UI_KEY_VIEW_TAB_CPANEL      "ui_key_view_tab_cpanel"
167#define M32OPTION_UI_KEY_VIEW_TAB_FLYER         "ui_key_view_tab_flyer"
168#define M32OPTION_UI_KEY_VIEW_TAB_HISTORY      "ui_key_view_tab_history"
169#define M32OPTION_UI_KEY_VIEW_TAB_MARQUEE      "ui_key_view_tab_marquee"
170#define M32OPTION_UI_KEY_VIEW_TAB_SCREENSHOT   "ui_key_view_tab_screenshot"
171#define M32OPTION_UI_KEY_VIEW_TAB_TITLE         "ui_key_view_tab_title"
172#define M32OPTION_UI_KEY_QUIT               "ui_key_quit"
173#define M32OPTION_UI_JOY_UP                  "ui_joy_up"
174#define M32OPTION_UI_JOY_DOWN               "ui_joy_down"
175#define M32OPTION_UI_JOY_LEFT               "ui_joy_left"
176#define M32OPTION_UI_JOY_RIGHT               "ui_joy_right"
177#define M32OPTION_UI_JOY_START               "ui_joy_start"
178#define M32OPTION_UI_JOY_PGUP               "ui_joy_pgup"
179#define M32OPTION_UI_JOY_PGDWN               "ui_joy_pgdwn"
180#define M32OPTION_UI_JOY_HOME               "ui_joy_home"
181#define M32OPTION_UI_JOY_END               "ui_joy_end"
182#define M32OPTION_UI_JOY_SS_CHANGE            "ui_joy_ss_change"
183#define M32OPTION_UI_JOY_HISTORY_UP            "ui_joy_history_up"
184#define M32OPTION_UI_JOY_HISTORY_DOWN         "ui_joy_history_down"
185#define M32OPTION_UI_JOY_EXEC               "ui_joy_exec"
186#define M32OPTION_EXEC_COMMAND               "exec_command"
187#define M32OPTION_EXEC_WAIT                  "exec_wait"
188#define M32OPTION_HIDE_MOUSE               "hide_mouse"
189#define M32OPTION_FULL_SCREEN               "full_screen"
190
191#ifdef MESS
192#define M32OPTION_DEFAULT_GAME               "default_system"
193#define M32OPTION_HISTORY_FILE               "sysinfo_file"
194#define M32OPTION_MAMEINFO_FILE               "messinfo_file"
195#else
196#define M32OPTION_DEFAULT_GAME               "default_game"
197#define M32OPTION_HISTORY_FILE               "history_file"
198#define M32OPTION_MAMEINFO_FILE               "mameinfo_file"
199#endif
200
201
202
203/***************************************************************************
204    Internal structures
205 ***************************************************************************/
206
207typedef struct
208{
209   int folder_index;
210   int filters;
211} folder_filter_type;
212
213/***************************************************************************
214    Internal variables
215 ***************************************************************************/
216
217static object_pool *options_memory_pool;
218
219static core_options *settings;
220
221static core_options *global;            // Global 'default' options
222static core_options *vector_options;      // Vector options
223static core_options **game_options;         // Array of Game specific options
224static core_options **folder_options;      // Array of Folder specific options
225static int *folder_options_redirect;      // Array of Folder Ids for redirecting Folder specific options
226
227// UI options in mame32ui.ini
228static const options_entry regSettings[] =
229{
230   // UI options
231   { NULL,                           NULL,       OPTION_HEADER,     "UI OPTIONS" },
232#ifdef MESS
233   { M32OPTION_DEFAULT_GAME,            "nes",      0,                 NULL },
234#else
235   { M32OPTION_DEFAULT_GAME,            "puckman",  0,                 NULL },
236#endif
237   { M32OPTION_DEFAULT_FOLDER_ID,         "0",        0,                 NULL },
238   { M32OPTION_SHOW_IMAGE_SECTION,         "1",        OPTION_BOOLEAN,    NULL },
239   { M32OPTION_CURRENT_TAB,            "0",        0,                 NULL },
240   { M32OPTION_SHOW_TOOLBAR,            "1",        OPTION_BOOLEAN,    NULL },
241   { M32OPTION_SHOW_STATUS_BAR,         "1",        OPTION_BOOLEAN,    NULL },
242#ifdef MESS
243   { M32OPTION_SHOW_FOLDER_SECTION,      "0",        OPTION_BOOLEAN,    NULL },
244#else
245   { M32OPTION_SHOW_FOLDER_SECTION,      "1",        OPTION_BOOLEAN,    NULL },
246#endif
247   { M32OPTION_HIDE_FOLDERS,            "",         0,                 NULL },
248
249#ifdef MESS
250   { M32OPTION_SHOW_TABS,               "0",        OPTION_BOOLEAN,    NULL },
251   { M32OPTION_HIDE_TABS,               "flyer, cabinet, marquee, title, cpanel", 0, NULL },
252   { M32OPTION_HISTORY_TAB,            "1",        0,                 NULL },
253#else
254   { M32OPTION_SHOW_TABS,               "1",        OPTION_BOOLEAN,    NULL },
255   { M32OPTION_HIDE_TABS,               "marquee, title, cpanel, history", 0, NULL },
256   { M32OPTION_HISTORY_TAB,            "0",        0,                 NULL },
257#endif
258
259   { M32OPTION_CHECK_GAME,               "1",        OPTION_BOOLEAN,    NULL },
260   { M32OPTION_JOYSTICK_IN_INTERFACE,      "0",        OPTION_BOOLEAN,    NULL },
261   { M32OPTION_KEYBOARD_IN_INTERFACE,      "0",        OPTION_BOOLEAN,    NULL },
262   { M32OPTION_BROADCAST_GAME_NAME,      "0",        OPTION_BOOLEAN,    NULL },
263   { M32OPTION_RANDOM_BACKGROUND,         "0",        OPTION_BOOLEAN,    NULL },
264
265   { M32OPTION_SORT_COLUMN,            "0",        0,                 NULL },
266   { M32OPTION_SORT_REVERSED,            "0",        OPTION_BOOLEAN,    NULL },
267   { M32OPTION_WINDOW_X,               "0",        0,                 NULL },
268   { M32OPTION_WINDOW_Y,               "0",        0,                 NULL },
269   { M32OPTION_WINDOW_WIDTH,            "640",      0,                 NULL },
270   { M32OPTION_WINDOW_HEIGHT,            "400",      0,                 NULL },
271   { M32OPTION_WINDOW_STATE,            "1",        0,                 NULL },
272
273   { M32OPTION_TEXT_COLOR,               "-1",       0,                 NULL },
274   { M32OPTION_CLONE_COLOR,            "-1",       0,                 NULL },
275   { M32OPTION_CUSTOM_COLOR,            "0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0", 0, NULL },
276   /* ListMode needs to be before ColumnWidths settings */
277   { M32OPTION_LIST_MODE,               "5",        0,                 NULL },
278#ifdef MESS
279   { M32OPTION_SPLITTERS,               "152,310,468", 0,              NULL },
280#else
281   { M32OPTION_SPLITTERS,               "152,362",  0,                 NULL },
282#endif
283   { M32OPTION_LIST_FONT,               "-8,0,0,0,400,0,0,0,0,0,0,0,0,MS Sans Serif", 0, NULL },
284   { M32OPTION_COLUMN_WIDTHS,            "185,68,84,84,64,88,74,108,60,144,84,60", 0, NULL },
285   { M32OPTION_COLUMN_ORDER,            "0,2,3,4,5,6,7,8,9,1,10,11", 0, NULL },
286   { M32OPTION_COLUMN_SHOWN,            "1,0,1,1,1,1,1,1,1,1,0,0", 0,  NULL },
287
288   { M32OPTION_UI_KEY_UP,               "KEYCODE_UP", 0,               NULL },
289   { M32OPTION_UI_KEY_DOWN,            "KEYCODE_DOWN", 0,             NULL },
290   { M32OPTION_UI_KEY_LEFT,            "KEYCODE_LEFT", 0,             NULL },
291   { M32OPTION_UI_KEY_RIGHT,            "KEYCODE_RIGHT", 0,            NULL },
292   { M32OPTION_UI_KEY_START,            "KEYCODE_ENTER NOT KEYCODE_LALT", 0, NULL },
293   { M32OPTION_UI_KEY_PGUP,            "KEYCODE_PGUP", 0,             NULL },
294   { M32OPTION_UI_KEY_PGDWN,            "KEYCODE_PGDN", 0,             NULL },
295   { M32OPTION_UI_KEY_HOME,            "KEYCODE_HOME", 0,             NULL },
296   { M32OPTION_UI_KEY_END,               "KEYCODE_END", 0,              NULL },
297   { M32OPTION_UI_KEY_SS_CHANGE,         "KEYCODE_INSERT", 0,           NULL },
298   { M32OPTION_UI_KEY_HISTORY_UP,         "KEYCODE_DEL", 0,              NULL },
299   { M32OPTION_UI_KEY_HISTORY_DOWN,      "KEYCODE_LALT KEYCODE_0", 0,   NULL },
300
301   { M32OPTION_UI_KEY_CONTEXT_FILTERS,      "KEYCODE_LCONTROL KEYCODE_F", 0, NULL },
302   { M32OPTION_UI_KEY_SELECT_RANDOM,      "KEYCODE_LCONTROL KEYCODE_R", 0, NULL },
303   { M32OPTION_UI_KEY_GAME_AUDIT,         "KEYCODE_LALT KEYCODE_A",     0, NULL },
304   { M32OPTION_UI_KEY_GAME_PROPERTIES,      "KEYCODE_LALT KEYCODE_ENTER", 0, NULL },
305   { M32OPTION_UI_KEY_HELP_CONTENTS,      "KEYCODE_F1",                 0, NULL },
306   { M32OPTION_UI_KEY_UPDATE_GAMELIST,      "KEYCODE_F5",                 0, NULL },
307   { M32OPTION_UI_KEY_VIEW_FOLDERS,      "KEYCODE_LALT KEYCODE_D",     0, NULL },
308   { M32OPTION_UI_KEY_VIEW_FULLSCREEN,      "KEYCODE_F11",                0, NULL },
309   { M32OPTION_UI_KEY_VIEW_PAGETAB,      "KEYCODE_LALT KEYCODE_B",     0, NULL },
310   { M32OPTION_UI_KEY_VIEW_PICTURE_AREA,   "KEYCODE_LALT KEYCODE_P",     0, NULL },
311   { M32OPTION_UI_KEY_VIEW_STATUS,         "KEYCODE_LALT KEYCODE_S",     0, NULL },
312    { M32OPTION_UI_KEY_VIEW_TOOLBARS,      "KEYCODE_LALT KEYCODE_T",     0, NULL },
313
314    { M32OPTION_UI_KEY_VIEW_TAB_CABINET,   "KEYCODE_LALT KEYCODE_3",     0, NULL },
315    { M32OPTION_UI_KEY_VIEW_TAB_CPANEL,      "KEYCODE_LALT KEYCODE_6",     0, NULL },
316    { M32OPTION_UI_KEY_VIEW_TAB_FLYER,      "KEYCODE_LALT KEYCODE_2",     0, NULL },
317    { M32OPTION_UI_KEY_VIEW_TAB_HISTORY,   "KEYCODE_LALT KEYCODE_7",     0, NULL },
318    { M32OPTION_UI_KEY_VIEW_TAB_MARQUEE,   "KEYCODE_LALT KEYCODE_4",     0, NULL },
319    { M32OPTION_UI_KEY_VIEW_TAB_SCREENSHOT,   "KEYCODE_LALT KEYCODE_1",   0, NULL },
320    { M32OPTION_UI_KEY_VIEW_TAB_TITLE,      "KEYCODE_LALT KEYCODE_5",     0, NULL },
321    { M32OPTION_UI_KEY_QUIT,            "KEYCODE_LALT KEYCODE_Q",     0, NULL },
322
323   { M32OPTION_UI_JOY_UP,               "",         0,                 NULL },
324   { M32OPTION_UI_JOY_DOWN,            "",         0,                 NULL },
325   { M32OPTION_UI_JOY_LEFT,            "",         0,                 NULL },
326   { M32OPTION_UI_JOY_RIGHT,            "",         0,                 NULL },
327   { M32OPTION_UI_JOY_START,            "",         0,                 NULL },
328   { M32OPTION_UI_JOY_PGUP,            "",         0,                 NULL },
329   { M32OPTION_UI_JOY_PGDWN,            "",         0,                 NULL },
330   { M32OPTION_UI_JOY_HOME,            "0,0,0,0",  0,                 NULL },
331   { M32OPTION_UI_JOY_END,               "0,0,0,0",  0,                 NULL },
332   { M32OPTION_UI_JOY_SS_CHANGE,         "",         0,                 NULL },
333   { M32OPTION_UI_JOY_HISTORY_UP,         "",         0,                 NULL },
334   { M32OPTION_UI_JOY_HISTORY_DOWN,      "",         0,                 NULL },
335   { M32OPTION_UI_JOY_EXEC,            "0,0,0,0",  0,                 NULL },
336   { M32OPTION_EXEC_COMMAND,            "",         0,                 NULL },
337   { M32OPTION_EXEC_WAIT,               "0",        0,                 NULL },
338   { M32OPTION_HIDE_MOUSE,               "0",        OPTION_BOOLEAN,    NULL },
339   { M32OPTION_FULL_SCREEN,            "0",        OPTION_BOOLEAN,    NULL },
340   { M32OPTION_CYCLE_SCREENSHOT,         "0",        0,                 NULL },
341   { M32OPTION_STRETCH_SCREENSHOT_LARGER,   "0",        OPTION_BOOLEAN,    NULL },
342    { M32OPTION_SCREENSHOT_BORDER_SIZE,      "11",       0,                 NULL },
343    { M32OPTION_SCREENSHOT_BORDER_COLOR,   "-1",       0,                 NULL },
344   { M32OPTION_INHERIT_FILTER,            "0",        OPTION_BOOLEAN,    NULL },
345   { M32OPTION_OFFSET_CLONES,            "0",        OPTION_BOOLEAN,    NULL },
346   { M32OPTION_GAME_CAPTION,            "1",        OPTION_BOOLEAN,    NULL },
347
348   { M32OPTION_LANGUAGE,               "english",  0,                 NULL },
349   { M32OPTION_FLYER_DIRECTORY,         "flyers",   0,                 NULL },
350   { M32OPTION_CABINET_DIRECTORY,         "cabinets", 0,                 NULL },
351   { M32OPTION_MARQUEE_DIRECTORY,         "marquees", 0,                 NULL },
352   { M32OPTION_TITLE_DIRECTORY,         "titles",   0,                 NULL },
353   { M32OPTION_CPANEL_DIRECTORY,         "cpanel",   0,                 NULL },
354   { M32OPTION_BACKGROUND_DIRECTORY,      "bkground", 0,                 NULL },
355   { M32OPTION_FOLDER_DIRECTORY,         "folders",  0,                 NULL },
356   { M32OPTION_ICONS_DIRECTORY,         "icons",    0,                 NULL },
357#ifdef MESS
358   { M32OPTION_HISTORY_FILE,            "sysinfo.dat", 0,              NULL },
359   { M32OPTION_MAMEINFO_FILE,            "messinfo.dat", 0,             NULL },
360#else
361   { M32OPTION_HISTORY_FILE,            "history.dat", 0,              NULL },
362   { M32OPTION_MAMEINFO_FILE,            "mameinfo.dat", 0,             NULL },
363#endif
364   { NULL }
365};
366
367static const options_entry perGameOptions[] =
368{
369   // per game options
370   { "_play_count",             "0",        0,                 NULL },
371   { "_play_time",              "0",        0,                 NULL },
372   { "_rom_audit",              "-1",       0,                 NULL },
373   { "_samples_audit",          "-1",       0,                 NULL },
374#ifdef MESS
375   { "_extra_software",         "",         0,                 NULL },
376#endif
377
378   // filters
379   { "_filters",                "0",        0,                 NULL },
380
381   { NULL }
382};
383
384
385
386// Screen shot Page tab control text
387// these must match the order of the options flags in options.h
388// (TAB_...)
389const char* image_tabs_long_name[MAX_TAB_TYPES] =
390{
391   "Snapshot ",
392   "Flyer ",
393   "Cabinet ",
394   "Marquee",
395   "Title",
396   "Control Panel",
397   "History ",
398};
399
400const char* image_tabs_short_name[MAX_TAB_TYPES] =
401{
402   "snapshot",
403   "flyer",
404   "cabinet",
405   "marquee",
406   "title",
407   "cpanel",
408   "history"
409};
410
411
412static BOOL save_gui_settings = TRUE;
413static BOOL save_default_options = TRUE;
414
415folder_filter_type *folder_filters;
416int size_folder_filters;
417int num_folder_filters;
418
419/***************************************************************************
420    External functions 
421 ***************************************************************************/
422
423static void memory_error(const char *message)
424{
425   win_message_box_utf8(NULL, message, NULL, MB_OK);
426   exit(-1);
427}
428
429
430
431void AddOptions(core_options *opts, const options_entry *entrylist, BOOL is_global)
432{
433   static const char *blacklist[] =
434   {
435      WINOPTION_SCREEN,
436      WINOPTION_ASPECT,
437      WINOPTION_RESOLUTION,
438      WINOPTION_VIEW
439   };
440   options_entry entries[2];
441   BOOL good_option;
442   int i;
443
444   for ( ; entrylist->name != NULL || (entrylist->flags & OPTION_HEADER); entrylist++)
445   {
446      good_option = TRUE;
447
448      // check blacklist
449      if (entrylist->name != NULL)
450      {
451         for (i = 0; i < ARRAY_LENGTH(blacklist); i++)
452         {
453            if (!strcmp(entrylist->name, blacklist[i]))
454            {
455               good_option = FALSE;
456               break;
457            }
458         }
459      }
460
461      // if is_global is FALSE, blacklist global options
462      if (entrylist->name && !is_global && IsGlobalOption(entrylist->name))
463         good_option = FALSE;
464
465      if (good_option)
466      {
467         memcpy(entries, entrylist, sizeof(options_entry));
468         memset(&entries[1], 0, sizeof(entries[1]));
469         options_add_entries(opts, entries);
470      }
471   }
472}
473
474
475
476core_options *CreateGameOptions(int driver_index)
477{
478   core_options *opts;
479   BOOL is_global = (driver_index == OPTIONS_TYPE_GLOBAL);
480   extern const options_entry mame_win_options[];
481
482   // create the options
483   opts = options_create(memory_error);
484
485   // add the options
486   AddOptions(opts, mame_core_options, is_global);
487   AddOptions(opts, mame_win_options, is_global);
488
489   // customize certain options
490   if (is_global)
491      options_set_option_default_value(opts, OPTION_INIPATH, "ini");
492
493#ifdef MESS
494   MessSetupGameOptions(opts, driver_index);
495#endif // MESS
496
497   return opts;
498}
499
500
501
502BOOL OptionsInit()
503{
504   // create a memory pool for our data
505   options_memory_pool = pool_alloc(memory_error);
506   if (!options_memory_pool)
507      return FALSE;
508
509   // set up the MAME32 settings (these get placed in MAME32ui.ini
510   settings = options_create(memory_error);
511   options_add_entries(settings, regSettings);
512#ifdef MESS
513   MessSetupSettings(settings);
514#endif
515
516   // set up per game options
517   {
518      char buffer[128];
519      int i, j;
520      int game_option_count = 0;
521      options_entry *driver_per_game_options;
522      options_entry *ent;
523
524      while(perGameOptions[game_option_count].name)
525         game_option_count++;
526
527      driver_per_game_options = (options_entry *) pool_malloc(options_memory_pool,
528         (game_option_count * driver_list_get_count(drivers) + 1) * sizeof(*driver_per_game_options));
529
530      for (i = 0; i < driver_list_get_count(drivers); i++)
531      {
532         for (j = 0; j < game_option_count; j++)
533         {
534            ent = &driver_per_game_options[i * game_option_count + j];
535
536            snprintf(buffer, ARRAY_LENGTH(buffer), "%s%s", drivers[i]->name, perGameOptions[j].name);
537
538            memset(ent, 0, sizeof(*ent));
539            ent->name = pool_strdup(options_memory_pool, buffer);
540            ent->defvalue = perGameOptions[j].defvalue;
541            ent->flags = perGameOptions[j].flags;
542            ent->description = perGameOptions[j].description;
543         }
544      }
545      ent = &driver_per_game_options[driver_list_get_count(drivers) * game_option_count];
546      memset(ent, 0, sizeof(*ent));
547      options_add_entries(settings, driver_per_game_options);
548   }
549
550   // set up global options
551   global = CreateGameOptions(OPTIONS_TYPE_GLOBAL);
552
553   // set up game options
554   game_options = (core_options **) pool_malloc(options_memory_pool, driver_list_get_count(drivers) * sizeof(*game_options));
555   memset(game_options, 0, driver_list_get_count(drivers) * sizeof(*game_options));
556
557   // set up folders
558   size_folder_filters = 1;
559   num_folder_filters = 0;
560   folder_filters = (folder_filter_type *) pool_malloc(options_memory_pool, size_folder_filters * sizeof(*folder_filters));
561
562   // now load the options and settings
563   LoadOptionsAndSettings();
564
565   return TRUE;
566
567}
568
569void FolderOptionsInit()
570{
571   //Get Number of Folder Entries with options from folder_options_redirect
572   int i=GetNumOptionFolders();
573
574   folder_options = (core_options **) pool_malloc(options_memory_pool, i * sizeof(*folder_options));
575   memset(folder_options, 0, i * sizeof(*folder_options));
576}
577
578void OptionsExit(void)
579{
580   int i;
581
582   // free all game specific options
583   for (i = 0; i < driver_list_get_count(drivers); i++)
584   {
585      if (game_options[i] != NULL)
586      {
587         options_free(game_options[i]);
588         game_options[i] = NULL;
589      }
590   }
591
592   // free all folder specific options
593   for (i = 0; i < GetNumOptionFolders(); i++)
594   {
595      if (folder_options[i] != NULL)
596      {
597         options_free(folder_options[i]);
598         folder_options[i] = NULL;
599      }
600   }
601
602   // free global options
603   options_free(global);
604   global = NULL;
605
606   // free settings
607   options_free(settings);
608   settings = NULL;
609
610   // free vector options
611   if (vector_options != NULL)
612   {
613      options_free(vector_options);
614      vector_options = NULL;
615   }
616
617   // free the memory pool
618   pool_free(options_memory_pool);
619   options_memory_pool = NULL;
620}
621
622
623
624int GetRedirectIndex(int folder_index)
625{
626   int i=0;
627   int *redirect_arr = GetFolderOptionsRedirectArr();
628   //Use the redirect array, to get correct folder
629   for( i=0; i<GetNumOptionFolders();i++)
630   {
631     
632      if( redirect_arr[i] == folder_index)
633      {
634         //found correct folderId
635         return i;
636      }
637   }
638   return -1;
639}
640
641int GetRedirectValue(int index)
642{
643   int *redirect_arr = GetFolderOptionsRedirectArr();
644   //Use the redirect array, to get correct folder
645   if( GetNumOptionFolders() < index )
646      return redirect_arr[index];
647   else
648      return -1;
649}
650
651
652
653static void GetDriverSettingsFileName(int driver_index, char *filename, size_t filename_len)
654{
655   char title[32];
656   char *s;
657
658   snprintf(title, ARRAY_LENGTH(title), "%s", GetDriverFilename(driver_index));
659   s = strrchr(title, '.');
660   if (s)
661      *s = '\0';
662
663   snprintf(filename, filename_len, "%s\\drivers\\%s.ini", GetIniDir(), title);
664}
665
666
667
668static BOOL GetFolderSettingsFileName(int folder_index, char *filename, size_t filename_len)
669{
670   extern FOLDERDATA g_folderData[];
671   extern LPEXFOLDERDATA ExtraFolderData[];
672   extern int numExtraFolders;
673   int i, j;
674   const char *pParent;
675   BOOL result = FALSE;
676
677   filename[0] = '\0';
678
679   if (folder_index < MAX_FOLDERS)
680   {
681      for (i = 0; g_folderData[i].m_lpTitle; i++)
682      {
683         if (g_folderData[i].m_nFolderId == folder_index)
684         {
685            snprintf(filename, filename_len, "%s\\%s.ini", GetIniDir(), g_folderData[i].m_lpTitle);
686            result = TRUE;
687            break;
688         }
689      }
690   }
691   else if (folder_index < MAX_FOLDERS + numExtraFolders)
692   {
693      for (i = 0; i < MAX_EXTRA_FOLDERS * MAX_EXTRA_SUBFOLDERS; i++)
694      {
695         if (ExtraFolderData[i])
696         {
697            snprintf(filename, filename_len, "%s\\%s.ini", GetIniDir(), ExtraFolderData[i]->m_szTitle);
698            result = TRUE;
699            break;
700         }
701      }
702   }
703   else
704   {
705      //we jump to the corresponding folderData
706      if( ExtraFolderData[folder_index] )
707      {
708         //SubDirName is ParentFolderName
709         pParent = GetFolderNameByID(ExtraFolderData[folder_index]->m_nParent);
710         if( pParent )
711         {
712            if( ExtraFolderData[folder_index]->m_nParent == FOLDER_SOURCE )
713            {
714               for (j = 0; drivers[j]; j++)
715               {
716                  if (!strcmp(GetDriverFilename(j), ExtraFolderData[folder_index]->m_szTitle))
717                  {
718                     GetDriverSettingsFileName(j, filename, filename_len);
719                     result = TRUE;
720                     break;
721                  }
722               }
723            }
724            else
725            {
726               pParent = GetFolderNameByID(ExtraFolderData[folder_index]->m_nParent);
727               snprintf(filename, filename_len, "%s\\%s\\%s.ini", GetIniDir(), pParent, ExtraFolderData[folder_index]->m_szTitle );
728               result = TRUE;
729            }
730         }
731      }
732   }
733   return result;
734}
735
736// sync in the options specified in filename
737void SyncInFolderOptions(core_options *opts, int folder_index)
738{
739   char filename[MAX_PATH];
740
741   if (GetFolderSettingsFileName(folder_index, filename, ARRAY_LENGTH(filename)))
742   {
743      LoadSettingsFile(opts, filename);
744   }
745}
746
747
748core_options * GetDefaultOptions(int iProperty, BOOL bVectorFolder )
749{
750   if( iProperty == GLOBAL_OPTIONS)
751      return global;
752   else if( iProperty == FOLDER_OPTIONS)
753   {
754      if (bVectorFolder)
755         return global;
756      else
757         return GetVectorOptions();
758   }
759   else
760   {
761      assert(0 <= iProperty && iProperty < driver_list_get_count(drivers));
762      return GetSourceOptions( iProperty );
763   }
764}
765
766core_options * GetFolderOptions(int folder_index, BOOL bIsVector)
767{
768   int redirect_index=0;
769   if( folder_index >= (MAX_FOLDERS + (MAX_EXTRA_FOLDERS * MAX_EXTRA_SUBFOLDERS) ) )
770   {
771      dprintf("Folder Index out of bounds");
772      return NULL;
773   }
774   //Use the redirect array, to get correct folder
775   redirect_index = GetRedirectIndex(folder_index);
776   if( redirect_index < 0)
777      return NULL;
778   if (folder_options[redirect_index] == NULL)
779      folder_options[redirect_index] = CreateGameOptions(OPTIONS_TYPE_FOLDER);
780   options_copy(folder_options[redirect_index], global);
781   LoadFolderOptions(folder_index);
782   if( bIsVector)
783   {
784      SyncInFolderOptions(folder_options[redirect_index], FOLDER_VECTOR);
785   }
786   return folder_options[redirect_index];
787}
788
789int * GetFolderOptionsRedirectArr(void)
790{
791   return &folder_options_redirect[0];
792}
793
794void SetFolderOptionsRedirectArr(int *redirect_arr)
795{
796   folder_options_redirect = redirect_arr;
797}
798
799
800core_options * GetVectorOptions(void)
801{
802   if (vector_options == NULL)
803   {
804      vector_options = CreateGameOptions(OPTIONS_TYPE_FOLDER);
805      options_copy(vector_options, global);
806   }
807   
808   //If it is a Vector game sync in the Vector.ini settings
809   SyncInFolderOptions(vector_options, FOLDER_VECTOR);
810
811   return vector_options;
812}
813
814core_options * GetSourceOptions(int driver_index )
815{
816   static core_options *source_opts;
817   char filename[MAX_PATH];
818
819   assert(0 <= driver_index && driver_index < driver_list_get_count(drivers));
820
821   if (source_opts != NULL)
822   {
823      options_free(source_opts);
824      source_opts = NULL;
825   }
826
827   source_opts = CreateGameOptions(OPTIONS_TYPE_FOLDER);
828
829   //initialize source_opts with global settings, we accumulate all settings there and copy them
830   //to game_options[driver_index] in the end
831   options_copy(source_opts, global);
832   
833   if( DriverIsVector(driver_index) )
834   {
835      //If it is a Vector game sync in the Vector.ini settings
836      SyncInFolderOptions(source_opts, FOLDER_VECTOR);
837   }
838
839   //If it has source folder settings sync in the source\sourcefile.ini settings
840   GetDriverSettingsFileName(driver_index, filename, ARRAY_LENGTH(filename));
841   LoadSettingsFile(source_opts, filename);
842
843   return source_opts;
844}
845
846core_options * GetGameOptions(int driver_index, int folder_index )
847{
848   int parent_index;
849   char filename[MAX_PATH];
850
851   assert(0 <= driver_index && driver_index < driver_list_get_count(drivers));
852
853   // do we have to load these options?
854   if (game_options[driver_index] == NULL)
855   {
856      game_options[driver_index] = CreateGameOptions(driver_index);
857      options_copy(game_options[driver_index], global);
858   
859      if (DriverIsVector(driver_index))
860      {
861         //If it is a Vector game sync in the Vector.ini settings
862         SyncInFolderOptions(game_options[driver_index], FOLDER_VECTOR);
863      }
864   
865      //If it has source folder settings sync in the source\sourcefile.ini settings
866      GetDriverSettingsFileName(driver_index, filename, ARRAY_LENGTH(filename));
867      LoadSettingsFile(game_options[driver_index], filename);
868   
869      //Sync in parent settings if it has one
870      if( DriverIsClone(driver_index))
871      {
872         parent_index = GetParentIndex(drivers[driver_index]);
873         snprintf(filename, ARRAY_LENGTH(filename), "%s\\%s.ini", GetIniDir(), drivers[parent_index]->name);
874         LoadSettingsFile(game_options[driver_index], filename);
875      }
876
877      // last but not least, sync in game specific settings
878      snprintf(filename, ARRAY_LENGTH(filename), "%s\\%s.ini", GetIniDir(), drivers[driver_index]->name);
879      LoadSettingsFile(game_options[driver_index], filename);
880   }
881
882   // return the result
883   return game_options[driver_index];
884}
885
886core_options * Mame32Settings(void)
887{
888   return settings;
889}
890
891core_options * Mame32Global(void)
892{
893   return global;
894}
895
896void SetGameUsesDefaults(int driver_index,BOOL use_defaults)
897{
898   assert((0 <= driver_index) && (driver_index < driver_list_get_count(drivers)));
899
900   if (use_defaults && (game_options[driver_index] != NULL))
901   {
902      options_free(game_options[driver_index]);
903      game_options[driver_index] = NULL;
904   }
905}
906
907void LoadFolderFilter(int folder_index,int filters)
908{
909   //dprintf("loaded folder filter %i %i",folder_index,filters);
910
911   if (num_folder_filters == size_folder_filters)
912   {
913      size_folder_filters *= 2;
914      folder_filters = (folder_filter_type *)realloc(
915         folder_filters,size_folder_filters * sizeof(folder_filter_type));
916   }
917   folder_filters[num_folder_filters].folder_index = folder_index;
918   folder_filters[num_folder_filters].filters = filters;
919
920   num_folder_filters++;
921}
922
923void ResetGUI(void)
924{
925   save_gui_settings = FALSE;
926}
927
928const char * GetImageTabLongName(int tab_index)
929{
930   assert((0 <= tab_index) && (tab_index < ARRAY_LENGTH(image_tabs_long_name)));
931   return image_tabs_long_name[tab_index];
932}
933
934const char * GetImageTabShortName(int tab_index)
935{
936   assert((0 <= tab_index) && (tab_index < ARRAY_LENGTH(image_tabs_short_name)));
937   return image_tabs_short_name[tab_index];
938}
939
940//============================================================
941//  OPTIONS WRAPPERS
942//============================================================
943
944static COLORREF options_get_color(core_options *opts, const char *name)
945{
946   const char *value_str;
947   unsigned int r, g, b;
948   COLORREF value;
949
950   value_str = options_get_string(opts, name);
951
952   if (sscanf(value_str, "%u,%u,%u", &r, &g, &b) == 3)
953      value = RGB(r,g,b);
954   else
955      value = (COLORREF) - 1;
956   return value;
957}
958
959static void options_set_color(core_options *opts, const char *name, COLORREF value)
960{
961   char value_str[32];
962
963   if (value == (COLORREF) -1)
964   {
965      snprintf(value_str, ARRAY_LENGTH(value_str), "%d", (int) value);
966   }
967   else
968   {
969      snprintf(value_str, ARRAY_LENGTH(value_str), "%d,%d,%d",
970         (((int) value) >>  0) & 0xFF,
971         (((int) value) >>  8) & 0xFF,
972         (((int) value) >> 16) & 0xFF);
973   }
974   options_set_string(opts, name, value_str, OPTION_PRIORITY_CMDLINE);
975}
976
977static COLORREF options_get_color_default(core_options *opts, const char *name, int default_color)
978{
979   COLORREF value = options_get_color(opts, name);
980   if (value == (COLORREF) -1)
981      value = GetSysColor(default_color);
982   return value;
983}
984
985static void options_set_color_default(core_options *opts, const char *name, COLORREF value, int default_color)
986{
987   if (value == GetSysColor(default_color))
988      options_set_color(settings, name, (COLORREF) -1);
989   else
990      options_set_color(settings, name, value);
991}
992
993static input_seq *options_get_input_seq(core_options *opts, const char *name)
994{
995   static input_seq seq;
996   const char *seq_string;
997
998   seq_string = options_get_string(opts, name);
999   input_seq_from_tokens(seq_string, &seq);
1000   return &seq;
1001}
1002
1003
1004
1005//============================================================
1006//  OPTIONS CALLS
1007//============================================================
1008
1009void SetViewMode(int val)
1010{
1011   options_set_int(settings, M32OPTION_LIST_MODE, val, OPTION_PRIORITY_CMDLINE);
1012}
1013
1014int GetViewMode(void)
1015{
1016   return options_get_int(settings, M32OPTION_LIST_MODE);
1017}
1018
1019void SetGameCheck(BOOL game_check)
1020{
1021   options_set_bool(settings, M32OPTION_CHECK_GAME, game_check, OPTION_PRIORITY_CMDLINE);
1022}
1023
1024BOOL GetGameCheck(void)
1025{
1026   return options_get_bool(settings,M32OPTION_CHECK_GAME);
1027}
1028
1029void SetJoyGUI(BOOL use_joygui)
1030{
1031   options_set_bool(settings, M32OPTION_JOYSTICK_IN_INTERFACE, use_joygui, OPTION_PRIORITY_CMDLINE);
1032}
1033
1034BOOL GetJoyGUI(void)
1035{
1036   return options_get_bool(settings, M32OPTION_JOYSTICK_IN_INTERFACE);
1037}
1038
1039void SetKeyGUI(BOOL use_keygui)
1040{
1041   options_set_bool(settings, M32OPTION_KEYBOARD_IN_INTERFACE, use_keygui, OPTION_PRIORITY_CMDLINE);
1042}
1043
1044BOOL GetKeyGUI(void)
1045{
1046   return options_get_bool(settings, M32OPTION_KEYBOARD_IN_INTERFACE);
1047}
1048
1049void SetCycleScreenshot(int cycle_screenshot)
1050{
1051   options_set_int(settings, M32OPTION_CYCLE_SCREENSHOT, cycle_screenshot, OPTION_PRIORITY_CMDLINE);
1052}
1053
1054int GetCycleScreenshot(void)
1055{
1056   return options_get_int(settings, M32OPTION_CYCLE_SCREENSHOT);
1057}
1058
1059void SetStretchScreenShotLarger(BOOL stretch)
1060{
1061   options_set_bool(settings, M32OPTION_STRETCH_SCREENSHOT_LARGER, stretch, OPTION_PRIORITY_CMDLINE);
1062}
1063
1064BOOL GetStretchScreenShotLarger(void)
1065{
1066   return options_get_bool(settings, M32OPTION_STRETCH_SCREENSHOT_LARGER);
1067}
1068
1069void SetScreenshotBorderSize(int size)
1070{
1071   options_set_int(settings, M32OPTION_SCREENSHOT_BORDER_SIZE, size, OPTION_PRIORITY_CMDLINE);
1072}
1073
1074int GetScreenshotBorderSize(void)
1075{
1076   return options_get_int(settings, M32OPTION_SCREENSHOT_BORDER_SIZE);
1077}
1078
1079void SetScreenshotBorderColor(COLORREF uColor)
1080{
1081   options_set_color_default(settings, M32OPTION_SCREENSHOT_BORDER_COLOR, uColor, COLOR_3DFACE);
1082}
1083
1084COLORREF GetScreenshotBorderColor(void)
1085{
1086   return options_get_color_default(settings, M32OPTION_SCREENSHOT_BORDER_COLOR, COLOR_3DFACE);
1087}
1088
1089void SetFilterInherit(BOOL inherit)
1090{
1091   options_set_bool(settings, M32OPTION_INHERIT_FILTER, inherit, OPTION_PRIORITY_CMDLINE);
1092}
1093
1094BOOL GetFilterInherit(void)
1095{
1096   return options_get_bool(settings, M32OPTION_INHERIT_FILTER);
1097}
1098
1099void SetOffsetClones(BOOL offset)
1100{
1101   options_set_bool(settings, M32OPTION_OFFSET_CLONES, offset, OPTION_PRIORITY_CMDLINE);
1102}
1103
1104BOOL GetOffsetClones(void)
1105{
1106   return options_get_bool(settings, M32OPTION_OFFSET_CLONES);
1107}
1108
1109void SetGameCaption(BOOL caption)
1110{
1111   options_set_bool(settings, M32OPTION_GAME_CAPTION, caption, OPTION_PRIORITY_CMDLINE);
1112}
1113
1114BOOL GetGameCaption(void)
1115{
1116   return options_get_bool(settings, M32OPTION_GAME_CAPTION);
1117}
1118
1119void SetBroadcast(BOOL broadcast)
1120{
1121   options_set_bool(settings, M32OPTION_BROADCAST_GAME_NAME, broadcast, OPTION_PRIORITY_CMDLINE);
1122}
1123
1124BOOL GetBroadcast(void)
1125{
1126   return options_get_bool(settings, M32OPTION_BROADCAST_GAME_NAME);
1127}
1128
1129void SetRandomBackground(BOOL random_bg)
1130{
1131   options_set_bool(settings, M32OPTION_RANDOM_BACKGROUND, random_bg, OPTION_PRIORITY_CMDLINE);
1132}
1133
1134BOOL GetRandomBackground(void)
1135{
1136   return options_get_bool(settings, M32OPTION_RANDOM_BACKGROUND);
1137}
1138
1139void SetSavedFolderID(UINT val)
1140{
1141   options_set_int(settings, M32OPTION_DEFAULT_FOLDER_ID, (int) val, OPTION_PRIORITY_CMDLINE);
1142}
1143
1144UINT GetSavedFolderID(void)
1145{
1146   return (UINT) options_get_int(settings, M32OPTION_DEFAULT_FOLDER_ID);
1147}
1148
1149void SetShowScreenShot(BOOL val)
1150{
1151   options_set_bool(settings, M32OPTION_SHOW_IMAGE_SECTION, val, OPTION_PRIORITY_CMDLINE);
1152}
1153
1154BOOL GetShowScreenShot(void)
1155{
1156   return options_get_bool(settings, M32OPTION_SHOW_IMAGE_SECTION);
1157}
1158
1159void SetShowFolderList(BOOL val)
1160{
1161   options_set_bool(settings, M32OPTION_SHOW_FOLDER_SECTION, val, OPTION_PRIORITY_CMDLINE);
1162}
1163
1164BOOL GetShowFolderList(void)
1165{
1166   return options_get_bool(settings, M32OPTION_SHOW_FOLDER_SECTION);
1167}
1168
1169static void GetsShowFolderFlags(LPBITS bits)
1170{
1171   char s[2000];
1172   extern FOLDERDATA g_folderData[];
1173   char *token;
1174
1175   snprintf(s, ARRAY_LENGTH(s), "%s", options_get_string(settings, M32OPTION_HIDE_FOLDERS));
1176
1177   SetAllBits(bits, TRUE);
1178
1179   token = strtok(s,", \t");
1180   while (token != NULL)
1181   {
1182      int j;
1183
1184      for (j=0;g_folderData[j].m_lpTitle != NULL;j++)
1185      {
1186         if (strcmp(g_folderData[j].short_name,token) == 0)
1187         {
1188            ClearBit(bits, g_folderData[j].m_nFolderId);
1189            break;
1190         }
1191      }
1192      token = strtok(NULL,", \t");
1193   }
1194}
1195
1196BOOL GetShowFolder(int folder)
1197{
1198   BOOL result;
1199   LPBITS show_folder_flags = NewBits(MAX_FOLDERS);
1200   GetsShowFolderFlags(show_folder_flags);
1201   result = TestBit(show_folder_flags, folder);
1202   DeleteBits(show_folder_flags);
1203   return result;
1204}
1205
1206void SetShowFolder(int folder,BOOL show)
1207{
1208   LPBITS show_folder_flags = NewBits(MAX_FOLDERS);
1209   int i;
1210   int num_saved = 0;
1211   char str[10000];
1212   extern FOLDERDATA g_folderData[];
1213
1214   GetsShowFolderFlags(show_folder_flags);
1215
1216   if (show)
1217      SetBit(show_folder_flags, folder);
1218   else
1219      ClearBit(show_folder_flags, folder);
1220
1221   strcpy(str, "");
1222
1223   // we save the ones that are NOT displayed, so we can add new ones
1224   // and upgraders will see them
1225   for (i=0;i<MAX_FOLDERS;i++)
1226   {
1227      if (TestBit(show_folder_flags, i) == FALSE)
1228      {
1229         int j;
1230
1231         if (num_saved != 0)
1232            strcat(str,", ");
1233
1234         for (j=0;g_folderData[j].m_lpTitle != NULL;j++)
1235         {
1236            if (g_folderData[j].m_nFolderId == i)
1237            {
1238               strcat(str,g_folderData[j].short_name);
1239               num_saved++;
1240               break;
1241            }
1242         }
1243      }
1244   }
1245   options_set_string(settings, M32OPTION_HIDE_FOLDERS, str, OPTION_PRIORITY_CMDLINE);
1246   DeleteBits(show_folder_flags);
1247}
1248
1249void SetShowStatusBar(BOOL val)
1250{
1251   options_set_bool(settings, M32OPTION_SHOW_STATUS_BAR, val, OPTION_PRIORITY_CMDLINE);
1252}
1253
1254BOOL GetShowStatusBar(void)
1255{
1256   return options_get_bool(settings, M32OPTION_SHOW_STATUS_BAR);
1257}
1258
1259void SetShowTabCtrl (BOOL val)
1260{
1261   options_set_bool(settings, M32OPTION_SHOW_TABS, val, OPTION_PRIORITY_CMDLINE);
1262}
1263
1264BOOL GetShowTabCtrl (void)
1265{
1266   return options_get_bool(settings, M32OPTION_SHOW_TABS);
1267}
1268
1269void SetShowToolBar(BOOL val)
1270{
1271   options_set_bool(settings, M32OPTION_SHOW_TOOLBAR, val, OPTION_PRIORITY_CMDLINE);
1272}
1273
1274BOOL GetShowToolBar(void)
1275{
1276   return options_get_bool(settings, M32OPTION_SHOW_TOOLBAR);
1277}
1278
1279void SetCurrentTab(const char *shortname)
1280{
1281   options_set_string(settings, M32OPTION_CURRENT_TAB, shortname, OPTION_PRIORITY_CMDLINE);
1282}
1283
1284const char *GetCurrentTab(void)
1285{
1286   return options_get_string(settings, M32OPTION_CURRENT_TAB);
1287}
1288
1289void SetDefaultGame(const char *name)
1290{
1291   options_set_string(settings, M32OPTION_DEFAULT_GAME, name, OPTION_PRIORITY_CMDLINE);
1292}
1293
1294const char *GetDefaultGame(void)
1295{
1296   return options_get_string(settings, M32OPTION_DEFAULT_GAME);
1297}
1298
1299void SetWindowArea(const AREA *area)
1300{
1301   options_set_int(settings, M32OPTION_WINDOW_X,      area->x, OPTION_PRIORITY_CMDLINE);
1302   options_set_int(settings, M32OPTION_WINDOW_Y,      area->y, OPTION_PRIORITY_CMDLINE);
1303   options_set_int(settings, M32OPTION_WINDOW_WIDTH,   area->width, OPTION_PRIORITY_CMDLINE);
1304   options_set_int(settings, M32OPTION_WINDOW_HEIGHT,   area->height, OPTION_PRIORITY_CMDLINE);
1305}
1306
1307void GetWindowArea(AREA *area)
1308{
1309   area->x      = options_get_int(settings, M32OPTION_WINDOW_X);
1310   area->y      = options_get_int(settings, M32OPTION_WINDOW_Y);
1311   area->width  = options_get_int(settings, M32OPTION_WINDOW_WIDTH);
1312   area->height = options_get_int(settings, M32OPTION_WINDOW_HEIGHT);
1313}
1314
1315void SetWindowState(UINT state)
1316{
1317   options_set_int(settings, M32OPTION_WINDOW_STATE, state, OPTION_PRIORITY_CMDLINE);
1318}
1319
1320UINT GetWindowState(void)
1321{
1322   return options_get_int(settings, M32OPTION_WINDOW_STATE);
1323}
1324
1325void SetCustomColor(int iIndex, COLORREF uColor)
1326{
1327   const char *custom_color_string;
1328   COLORREF custom_color[256];
1329   char buffer[10000];
1330
1331   custom_color_string = options_get_string(settings, M32OPTION_CUSTOM_COLOR);
1332   CusColorDecodeString(custom_color_string, custom_color);
1333
1334   custom_color[iIndex] = uColor;
1335
1336   CusColorEncodeString(custom_color, buffer);
1337   options_set_string(settings, M32OPTION_CUSTOM_COLOR, buffer, OPTION_PRIORITY_CMDLINE);
1338}
1339
1340COLORREF GetCustomColor(int iIndex)
1341{
1342   const char *custom_color_string;
1343   COLORREF custom_color[256];
1344
1345   custom_color_string = options_get_string(settings, M32OPTION_CUSTOM_COLOR);
1346   CusColorDecodeString(custom_color_string, custom_color);
1347
1348   if (custom_color[iIndex] == (COLORREF)-1)
1349      return (COLORREF)RGB(0,0,0);
1350
1351   return custom_color[iIndex];
1352}
1353
1354void SetListFont(const LOGFONT *font)
1355{
1356   char font_string[10000];
1357   FontEncodeString(font, font_string);
1358   options_set_string(settings, M32OPTION_LIST_FONT, font_string, OPTION_PRIORITY_CMDLINE);
1359}
1360
1361void GetListFont(LOGFONT *font)
1362{
1363   const char *font_string = options_get_string(settings, M32OPTION_LIST_FONT);
1364   FontDecodeString(font_string, font);
1365}
1366
1367void SetListFontColor(COLORREF uColor)
1368{
1369   options_set_color_default(settings, M32OPTION_TEXT_COLOR, uColor, COLOR_WINDOWTEXT);
1370}
1371
1372COLORREF GetListFontColor(void)
1373{
1374   return options_get_color_default(settings, M32OPTION_TEXT_COLOR, COLOR_WINDOWTEXT);
1375}
1376
1377void SetListCloneColor(COLORREF uColor)
1378{
1379   options_set_color_default(settings, M32OPTION_CLONE_COLOR, uColor, COLOR_WINDOWTEXT);
1380}
1381
1382COLORREF GetListCloneColor(void)
1383{
1384   return options_get_color_default(settings, M32OPTION_CLONE_COLOR, COLOR_WINDOWTEXT);
1385}
1386
1387int GetShowTab(int tab)
1388{
1389   const char *show_tabs_string;
1390   int show_tab_flags;
1391   
1392   show_tabs_string = options_get_string(settings, M32OPTION_HIDE_TABS);
1393   TabFlagsDecodeString(show_tabs_string, &show_tab_flags);
1394   return (show_tab_flags & (1 << tab)) != 0;
1395}
1396
1397void SetShowTab(int tab,BOOL show)
1398{
1399   const char *show_tabs_string;
1400   int show_tab_flags;
1401   char buffer[10000];
1402   
1403   show_tabs_string = options_get_string(settings, M32OPTION_HIDE_TABS);
1404   TabFlagsDecodeString(show_tabs_string, &show_tab_flags);
1405
1406   if (show)
1407      show_tab_flags |= 1 << tab;
1408   else
1409      show_tab_flags &= ~(1 << tab);
1410
1411   TabFlagsEncodeString(show_tab_flags, buffer);
1412   options_set_string(settings, M32OPTION_HIDE_TABS, buffer, OPTION_PRIORITY_CMDLINE);
1413}
1414
1415// don't delete the last one
1416BOOL AllowedToSetShowTab(int tab,BOOL show)
1417{
1418   const char *show_tabs_string;
1419   int show_tab_flags;
1420
1421   if (show == TRUE)
1422      return TRUE;
1423
1424   show_tabs_string = options_get_string(settings, M32OPTION_HIDE_TABS);
1425   TabFlagsDecodeString(show_tabs_string, &show_tab_flags);
1426
1427   show_tab_flags &= ~(1 << tab);
1428   return show_tab_flags != 0;
1429}
1430
1431int GetHistoryTab(void)
1432{
1433   return options_get_int(settings, M32OPTION_HISTORY_TAB);
1434}
1435
1436void SetHistoryTab(int tab, BOOL show)
1437{
1438   if (show)
1439      options_set_int(settings, M32OPTION_HISTORY_TAB, tab, OPTION_PRIORITY_CMDLINE);
1440   else
1441      options_set_int(settings, M32OPTION_HISTORY_TAB, TAB_NONE, OPTION_PRIORITY_CMDLINE);
1442}
1443
1444void SetColumnWidths(int width[])
1445{
1446   char column_width_string[10000];
1447   ColumnEncodeStringWithCount(width, column_width_string, COLUMN_MAX);
1448   options_set_string(settings, M32OPTION_COLUMN_WIDTHS, column_width_string, OPTION_PRIORITY_CMDLINE);
1449}
1450
1451void GetColumnWidths(int width[])
1452{
1453   const char *column_width_string;
1454   column_width_string = options_get_string(settings, M32OPTION_COLUMN_WIDTHS);
1455   ColumnDecodeStringWithCount(column_width_string, width, COLUMN_MAX);
1456}
1457
1458void SetSplitterPos(int splitterId, int pos)
1459{
1460   const char *splitter_string;
1461   int *splitter;
1462   char buffer[10000];
1463
1464   if (splitterId < GetSplitterCount())
1465   {
1466      splitter_string = options_get_string(settings, M32OPTION_SPLITTERS);
1467      splitter = (int *) alloca(GetSplitterCount() * sizeof(*splitter));
1468      SplitterDecodeString(splitter_string, splitter);
1469
1470      splitter[splitterId] = pos;
1471
1472      SplitterEncodeString(splitter, buffer);
1473      options_set_string(settings, M32OPTION_SPLITTERS, buffer, OPTION_PRIORITY_CMDLINE);
1474   }
1475}
1476
1477int  GetSplitterPos(int splitterId)
1478{
1479   const char *splitter_string;
1480   int *splitter;
1481
1482   splitter_string = options_get_string(settings, M32OPTION_SPLITTERS);
1483   splitter = (int *) alloca(GetSplitterCount() * sizeof(*splitter));
1484   SplitterDecodeString(splitter_string, splitter);
1485
1486   if (splitterId < GetSplitterCount())
1487      return splitter[splitterId];
1488
1489   return -1; /* Error */
1490}
1491
1492void SetColumnOrder(int order[])
1493{
1494   char column_order_string[10000];
1495   ColumnEncodeStringWithCount(order, column_order_string, COLUMN_MAX);
1496   options_set_string(settings, M32OPTION_COLUMN_ORDER, column_order_string, OPTION_PRIORITY_CMDLINE);
1497}
1498
1499void GetColumnOrder(int order[])
1500{
1501   const char *column_order_string;
1502   column_order_string = options_get_string(settings, M32OPTION_COLUMN_ORDER);
1503   ColumnDecodeStringWithCount(column_order_string, order, COLUMN_MAX);
1504}
1505
1506void SetColumnShown(int shown[])
1507{
1508   char column_shown_string[10000];
1509   ColumnEncodeStringWithCount(shown, column_shown_string, COLUMN_MAX);
1510   options_set_string(settings, M32OPTION_COLUMN_SHOWN, column_shown_string, OPTION_PRIORITY_CMDLINE);
1511}
1512
1513void GetColumnShown(int shown[])
1514{
1515   const char *column_shown_string;
1516   column_shown_string = options_get_string(settings, M32OPTION_COLUMN_SHOWN);
1517   ColumnDecodeStringWithCount(column_shown_string, shown, COLUMN_MAX);
1518}
1519
1520void SetSortColumn(int column)
1521{
1522   options_set_int(settings, M32OPTION_SORT_COLUMN, column, OPTION_PRIORITY_CMDLINE);
1523}
1524
1525int GetSortColumn(void)
1526{
1527   return options_get_int(settings, M32OPTION_SORT_COLUMN);
1528}
1529
1530void SetSortReverse(BOOL reverse)
1531{
1532   options_set_bool(settings, M32OPTION_SORT_REVERSED, reverse, OPTION_PRIORITY_CMDLINE);
1533}
1534
1535BOOL GetSortReverse(void)
1536{
1537   return options_get_bool(settings, M32OPTION_SORT_REVERSED);
1538}
1539
1540const char* GetLanguage(void)
1541{
1542   return options_get_string(settings, M32OPTION_LANGUAGE);
1543}
1544
1545void SetLanguage(const char* lang)
1546{
1547   options_set_string(settings, M32OPTION_LANGUAGE, lang, OPTION_PRIORITY_CMDLINE);
1548}
1549
1550const char* GetRomDirs(void)
1551{
1552   return options_get_string(global, OPTION_ROMPATH);
1553}
1554
1555void SetRomDirs(const char* paths)
1556{
1557   options_set_string(global, OPTION_ROMPATH, paths, OPTION_PRIORITY_CMDLINE);
1558}
1559
1560const char* GetSampleDirs(void)
1561{
1562   return options_get_string(global, OPTION_SAMPLEPATH);
1563}
1564
1565void SetSampleDirs(const char* paths)
1566{
1567   options_set_string(global, OPTION_SAMPLEPATH, paths, OPTION_PRIORITY_CMDLINE);
1568}
1569
1570const char * GetIniDir(void)
1571{
1572   const char *ini_dir;
1573   const char *s;
1574   
1575   ini_dir = options_get_string(global, OPTION_INIPATH);
1576   while((s = strchr(ini_dir, ';')) != NULL)
1577   {
1578      ini_dir = s + 1;
1579   }
1580   return ini_dir;
1581
1582}
1583
1584void SetIniDir(const char *path)
1585{
1586   options_set_string(global, OPTION_INIPATH, path, OPTION_PRIORITY_CMDLINE);
1587}
1588
1589const char* GetCtrlrDir(void)
1590{
1591   return options_get_string(global, OPTION_CTRLRPATH);
1592}
1593
1594void SetCtrlrDir(const char* path)
1595{
1596   options_set_string(global, OPTION_CTRLRPATH, path, OPTION_PRIORITY_CMDLINE);
1597}
1598
1599const char* GetCommentDir(void)
1600{
1601   return options_get_string(global, OPTION_COMMENT_DIRECTORY);
1602}
1603
1604void SetCommentDir(const char* path)
1605{
1606   options_set_string(global, OPTION_COMMENT_DIRECTORY, path, OPTION_PRIORITY_CMDLINE);
1607}
1608
1609const char* GetCfgDir(void)
1610{
1611   return options_get_string(global, OPTION_CFG_DIRECTORY);
1612}
1613
1614void SetCfgDir(const char* path)
1615{
1616   options_set_string(global, OPTION_CFG_DIRECTORY, path, OPTION_PRIORITY_CMDLINE);
1617}
1618
1619const char* GetNvramDir(void)
1620{
1621   return options_get_string(global, OPTION_NVRAM_DIRECTORY);
1622}
1623
1624void SetNvramDir(const char* path)
1625{
1626   options_set_string(global, OPTION_NVRAM_DIRECTORY, path, OPTION_PRIORITY_CMDLINE);
1627}
1628
1629const char* GetInpDir(void)
1630{
1631   return options_get_string(global, OPTION_INPUT_DIRECTORY);
1632}
1633
1634void SetInpDir(const char* path)
1635{
1636   options_set_string(global, OPTION_INPUT_DIRECTORY, path, OPTION_PRIORITY_CMDLINE);
1637}
1638
1639const char* GetImgDir(void)
1640{
1641   return options_get_string(global, OPTION_SNAPSHOT_DIRECTORY);
1642}
1643
1644void SetImgDir(const char* path)
1645{
1646   options_set_string(global, OPTION_SNAPSHOT_DIRECTORY, path, OPTION_PRIORITY_CMDLINE);
1647}
1648
1649const char* GetStateDir(void)
1650{
1651   return options_get_string(global, OPTION_STATE_DIRECTORY);
1652}
1653
1654void SetStateDir(const char* path)
1655{
1656   options_set_string(global, OPTION_STATE_DIRECTORY, path, OPTION_PRIORITY_CMDLINE);
1657}
1658
1659const char* GetArtDir(void)
1660{
1661   return options_get_string(global, OPTION_ARTPATH);
1662}
1663
1664void SetArtDir(const char* path)
1665{
1666   options_set_string(global, OPTION_ARTPATH, path, OPTION_PRIORITY_CMDLINE);
1667}
1668
1669const char* GetMemcardDir(void)
1670{
1671   return options_get_string(global, OPTION_MEMCARD_DIRECTORY);
1672}
1673
1674void SetMemcardDir(const char* path)
1675{
1676   options_set_string(global, OPTION_MEMCARD_DIRECTORY, path, OPTION_PRIORITY_CMDLINE);
1677}
1678
1679const char* GetFlyerDir(void)
1680{
1681   return options_get_string(settings, M32OPTION_FLYER_DIRECTORY);
1682}
1683
1684void SetFlyerDir(const char* path)
1685{
1686   options_set_string(settings, M32OPTION_FLYER_DIRECTORY, path, OPTION_PRIORITY_CMDLINE);
1687}
1688
1689const char* GetCabinetDir(void)
1690{
1691   return options_get_string(settings, M32OPTION_CABINET_DIRECTORY);
1692}
1693
1694void SetCabinetDir(const char* path)
1695{
1696   options_set_string(settings, M32OPTION_CABINET_DIRECTORY, path, OPTION_PRIORITY_CMDLINE);
1697}
1698
1699const char* GetMarqueeDir(void)
1700{
1701   return options_get_string(settings, M32OPTION_MARQUEE_DIRECTORY);
1702}
1703
1704void SetMarqueeDir(const char* path)
1705{
1706   options_set_string(settings, M32OPTION_MARQUEE_DIRECTORY, path, OPTION_PRIORITY_CMDLINE);
1707}
1708
1709const char* GetTitlesDir(void)
1710{
1711   return options_get_string(settings, M32OPTION_TITLE_DIRECTORY);
1712}
1713
1714void SetTitlesDir(const char* path)
1715{
1716   options_set_string(settings, M32OPTION_TITLE_DIRECTORY, path, OPTION_PRIORITY_CMDLINE);
1717}
1718
1719const char * GetControlPanelDir(void)
1720{
1721   return options_get_string(settings, M32OPTION_CPANEL_DIRECTORY);
1722}
1723
1724void SetControlPanelDir(const char *path)
1725{
1726   options_set_string(settings, M32OPTION_CPANEL_DIRECTORY, path, OPTION_PRIORITY_CMDLINE);
1727}
1728
1729const char * GetDiffDir(void)
1730{
1731   return options_get_string(global, OPTION_DIFF_DIRECTORY);
1732}
1733
1734void SetDiffDir(const char* path)
1735{
1736   options_set_string(global, OPTION_DIFF_DIRECTORY, path, OPTION_PRIORITY_CMDLINE);
1737}
1738
1739const char* GetIconsDir(void)
1740{
1741   return options_get_string(settings, M32OPTION_ICONS_DIRECTORY);
1742}
1743
1744void SetIconsDir(const char* path)
1745{
1746   options_set_string(settings, M32OPTION_ICONS_DIRECTORY, path, OPTION_PRIORITY_CMDLINE);
1747}
1748
1749const char* GetBgDir (void)
1750{
1751   return options_get_string(settings, M32OPTION_BACKGROUND_DIRECTORY);
1752}
1753
1754void SetBgDir (const char* path)
1755{
1756   options_set_string(settings, M32OPTION_BACKGROUND_DIRECTORY, path, OPTION_PRIORITY_CMDLINE);
1757}
1758
1759const char* GetFolderDir(void)
1760{
1761   return options_get_string(settings, M32OPTION_FOLDER_DIRECTORY);
1762}
1763
1764void SetFolderDir(const char* path)
1765{
1766   options_set_string(settings, M32OPTION_FOLDER_DIRECTORY, path, OPTION_PRIORITY_CMDLINE);
1767}
1768
1769const char* GetCheatFileName(void)
1770{
1771   return options_get_string(global, OPTION_CHEAT_FILE);
1772}
1773
1774void SetCheatFileName(const char* path)
1775{
1776   options_set_string(global, OPTION_CHEAT_FILE, path, OPTION_PRIORITY_CMDLINE);
1777}
1778
1779const char* GetHistoryFileName(void)
1780{
1781   return options_get_string(settings, M32OPTION_HISTORY_FILE);
1782}
1783
1784void SetHistoryFileName(const char* path)
1785{
1786   options_set_string(settings, M32OPTION_HISTORY_FILE, path, OPTION_PRIORITY_CMDLINE);
1787}
1788
1789
1790const char* GetMAMEInfoFileName(void)
1791{
1792   return options_get_string(settings, M32OPTION_MAMEINFO_FILE);
1793}
1794
1795void SetMAMEInfoFileName(const char* path)
1796{
1797   options_set_string(settings, M32OPTION_MAMEINFO_FILE, path, OPTION_PRIORITY_CMDLINE);
1798}
1799
1800void ResetGameOptions(int driver_index)
1801{
1802   assert(0 <= driver_index && driver_index < driver_list_get_count(drivers));
1803
1804   // make sure it's all loaded up.
1805   GetGameOptions(driver_index, GLOBAL_OPTIONS);
1806
1807   if (game_options[driver_index] != NULL)
1808   {
1809      options_free(game_options[driver_index]);
1810      game_options[driver_index] = NULL;
1811     
1812      // this will delete the custom file
1813      SaveGameOptions(driver_index);
1814   }
1815}
1816
1817void ResetGameDefaults(void)
1818{
1819   save_default_options = FALSE;
1820}
1821
1822void ResetAllGameOptions(void)
1823{
1824   int i;
1825   int redirect_value = 0;
1826
1827   for (i = 0; i < driver_list_get_count(drivers); i++)
1828   {
1829      ResetGameOptions(i);
1830   }
1831
1832   //with our new code we also need to delete the Source Folder Options and the Vector Options
1833   //Reset the Folder Options, can be done in one step
1834   for (i=0;i<GetNumOptionFolders();i++)
1835   {
1836      //Use the redirect array, to get correct folder
1837      redirect_value = GetRedirectValue(i);
1838      if( redirect_value < 0)
1839         continue;
1840       options_copy(folder_options[i], GetDefaultOptions(GLOBAL_OPTIONS, FALSE));
1841       SaveFolderOptions(redirect_value, 0);
1842   }
1843}
1844
1845static void GetDriverOptionName(int driver_index, const char *option_name, char *buffer, size_t buffer_len)
1846{
1847   assert(0 <= driver_index && driver_index < driver_list_get_count(drivers));
1848   snprintf(buffer, buffer_len, "%s_%s", drivers[driver_index]->name, option_name);
1849}
1850
1851int GetRomAuditResults(int driver_index)
1852{
1853   char buffer[128];
1854   GetDriverOptionName(driver_index, "rom_audit", buffer, ARRAY_LENGTH(buffer));
1855   return options_get_int(settings, buffer);
1856}
1857
1858void SetRomAuditResults(int driver_index, int audit_results)
1859{
1860   char buffer[128];
1861   GetDriverOptionName(driver_index, "rom_audit", buffer, ARRAY_LENGTH(buffer));
1862   options_set_int(settings, buffer, audit_results, OPTION_PRIORITY_CMDLINE);
1863}
1864
1865int  GetSampleAuditResults(int driver_index)
1866{
1867   char buffer[128];
1868   GetDriverOptionName(driver_index, "samples_audit", buffer, ARRAY_LENGTH(buffer));
1869   return options_get_int(settings, buffer);
1870}
1871
1872void SetSampleAuditResults(int driver_index, int audit_results)
1873{
1874   char buffer[128];
1875   GetDriverOptionName(driver_index, "samples_audit", buffer, ARRAY_LENGTH(buffer));
1876   options_set_int(settings, buffer, audit_results, OPTION_PRIORITY_CMDLINE);
1877}
1878
1879static void IncrementPlayVariable(int driver_index, const char *play_variable, int increment)
1880{
1881   char buffer[128];
1882   int count;
1883
1884   GetDriverOptionName(driver_index, play_variable, buffer, ARRAY_LENGTH(buffer));
1885   count = options_get_int(settings, buffer);
1886   options_set_int(settings, buffer, count + increment, OPTION_PRIORITY_CMDLINE);
1887}
1888
1889void IncrementPlayCount(int driver_index)
1890{
1891   IncrementPlayVariable(driver_index, "play_count", 1);
1892}
1893
1894int GetPlayCount(int driver_index)
1895{
1896   char buffer[128];
1897   GetDriverOptionName(driver_index, "play_count", buffer, ARRAY_LENGTH(buffer));
1898   return options_get_int(settings, buffer);
1899}
1900
1901static void ResetPlayVariable(int driver_index, const char *play_variable)
1902{
1903   int i;
1904   if (driver_index < 0)
1905   {
1906      // all games
1907      for (i = 0; i< driver_list_get_count(drivers); i++)
1908      {
1909         ResetPlayVariable(driver_index, play_variable);
1910      }
1911   }
1912   else
1913   {
1914      char buffer[128];
1915      GetDriverOptionName(driver_index, play_variable, buffer, ARRAY_LENGTH(buffer));
1916      options_set_int(settings, buffer, 0, OPTION_PRIORITY_CMDLINE);
1917   }
1918}
1919
1920void ResetPlayCount(int driver_index)
1921{
1922   ResetPlayVariable(driver_index, "play_count");
1923}
1924
1925void ResetPlayTime(int driver_index)
1926{
1927   ResetPlayVariable(driver_index, "play_time");
1928}
1929
1930int GetPlayTime(int driver_index)
1931{
1932   char buffer[128];
1933   GetDriverOptionName(driver_index, "play_time", buffer, ARRAY_LENGTH(buffer));
1934   return options_get_int(settings, buffer);
1935}
1936
1937void IncrementPlayTime(int driver_index,int playtime)
1938{
1939   IncrementPlayVariable(driver_index, "play_time", playtime);
1940}
1941
1942void GetTextPlayTime(int driver_index,char *buf)
1943{
1944   int hour, minute, second;
1945   int temp = GetPlayTime(driver_index);
1946
1947   assert(0 <= driver_index && driver_index < driver_list_get_count(drivers));
1948
1949   hour = temp / 3600;
1950   temp = temp - 3600*hour;
1951   minute = temp / 60; //Calc Minutes
1952   second = temp - 60*minute;
1953
1954   if (hour == 0)
1955      sprintf(buf, "%d:%02d", minute, second );
1956   else
1957      sprintf(buf, "%d:%02d:%02d", hour, minute, second );
1958}
1959
1960input_seq* Get_ui_key_up(void)
1961{
1962   return options_get_input_seq(settings, M32OPTION_UI_KEY_UP);
1963}
1964input_seq* Get_ui_key_down(void)
1965{
1966   return options_get_input_seq(settings, M32OPTION_UI_KEY_DOWN);
1967}
1968input_seq* Get_ui_key_left(void)
1969{
1970   return options_get_input_seq(settings, M32OPTION_UI_KEY_LEFT);
1971}
1972input_seq* Get_ui_key_right(void)
1973{
1974   return options_get_input_seq(settings, M32OPTION_UI_KEY_RIGHT);
1975}
1976input_seq* Get_ui_key_start(void)
1977{
1978   return options_get_input_seq(settings, M32OPTION_UI_KEY_START);
1979}
1980input_seq* Get_ui_key_pgup(void)
1981{
1982   return options_get_input_seq(settings, M32OPTION_UI_KEY_PGUP);
1983}
1984input_seq* Get_ui_key_pgdwn(void)
1985{
1986   return options_get_input_seq(settings, M32OPTION_UI_KEY_PGDWN);
1987}
1988input_seq* Get_ui_key_home(void)
1989{
1990   return options_get_input_seq(settings, M32OPTION_UI_KEY_HOME);
1991}
1992input_seq* Get_ui_key_end(void)
1993{
1994   return options_get_input_seq(settings, M32OPTION_UI_KEY_END);
1995}
1996input_seq* Get_ui_key_ss_change(void)
1997{
1998   return options_get_input_seq(settings, M32OPTION_UI_KEY_SS_CHANGE);
1999}
2000input_seq* Get_ui_key_history_up(void)
2001{
2002   return options_get_input_seq(settings, M32OPTION_UI_KEY_HISTORY_UP);
2003}
2004input_seq* Get_ui_key_history_down(void)
2005{
2006   return options_get_input_seq(settings, M32OPTION_UI_KEY_HISTORY_DOWN);
2007}
2008
2009
2010input_seq* Get_ui_key_context_filters(void)
2011{
2012   return options_get_input_seq(settings, M32OPTION_UI_KEY_CONTEXT_FILTERS);
2013}
2014input_seq* Get_ui_key_select_random(void)
2015{
2016   return options_get_input_seq(settings, M32OPTION_UI_KEY_SELECT_RANDOM);
2017}
2018input_seq* Get_ui_key_game_audit(void)
2019{
2020   return options_get_input_seq(settings, M32OPTION_UI_KEY_GAME_AUDIT);
2021}
2022input_seq* Get_ui_key_game_properties(void)
2023{
2024   return options_get_input_seq(settings, M32OPTION_UI_KEY_GAME_PROPERTIES);
2025}
2026input_seq* Get_ui_key_help_contents(void)
2027{
2028   return options_get_input_seq(settings, M32OPTION_UI_KEY_HELP_CONTENTS);
2029}
2030input_seq* Get_ui_key_update_gamelist(void)
2031{
2032   return options_get_input_seq(settings, M32OPTION_UI_KEY_UPDATE_GAMELIST);
2033}
2034input_seq* Get_ui_key_view_folders(void)
2035{
2036   return options_get_input_seq(settings, M32OPTION_UI_KEY_VIEW_FOLDERS);
2037}
2038input_seq* Get_ui_key_view_fullscreen(void)
2039{
2040   return options_get_input_seq(settings, M32OPTION_UI_KEY_VIEW_FULLSCREEN);
2041}
2042input_seq* Get_ui_key_view_pagetab(void)
2043{
2044   return options_get_input_seq(settings, M32OPTION_UI_KEY_VIEW_PAGETAB);
2045}
2046input_seq* Get_ui_key_view_picture_area(void)
2047{
2048   return options_get_input_seq(settings, M32OPTION_UI_KEY_VIEW_PICTURE_AREA);
2049}
2050input_seq* Get_ui_key_view_status(void)
2051{
2052   return options_get_input_seq(settings, M32OPTION_UI_KEY_VIEW_STATUS);
2053}
2054input_seq* Get_ui_key_view_toolbars(void)
2055{
2056   return options_get_input_seq(settings, M32OPTION_UI_KEY_VIEW_TOOLBARS);
2057}
2058
2059input_seq* Get_ui_key_view_tab_cabinet(void)
2060{
2061   return options_get_input_seq(settings, M32OPTION_UI_KEY_VIEW_TAB_CABINET);
2062}
2063input_seq* Get_ui_key_view_tab_cpanel(void)
2064{
2065   return options_get_input_seq(settings, M32OPTION_UI_KEY_VIEW_TAB_CPANEL);
2066}
2067input_seq* Get_ui_key_view_tab_flyer(void)
2068{
2069   return options_get_input_seq(settings, M32OPTION_UI_KEY_VIEW_TAB_FLYER);
2070}
2071input_seq* Get_ui_key_view_tab_history(void)
2072{
2073   return options_get_input_seq(settings, M32OPTION_UI_KEY_VIEW_TAB_HISTORY);
2074}
2075input_seq* Get_ui_key_view_tab_marquee(void)
2076{
2077   return options_get_input_seq(settings, M32OPTION_UI_KEY_VIEW_TAB_MARQUEE);
2078}
2079input_seq* Get_ui_key_view_tab_screenshot(void)
2080{
2081   return options_get_input_seq(settings, M32OPTION_UI_KEY_VIEW_TAB_SCREENSHOT);
2082}
2083input_seq* Get_ui_key_view_tab_title(void)
2084{
2085   return options_get_input_seq(settings, M32OPTION_UI_KEY_VIEW_TAB_TITLE);
2086}
2087input_seq* Get_ui_key_quit(void)
2088{
2089   return options_get_input_seq(settings, M32OPTION_UI_KEY_QUIT);
2090}
2091
2092
2093
2094static int GetUIJoy(const char *option_name, int joycodeIndex)
2095{
2096   const char *joycodes_string;
2097   int joycodes[4];
2098
2099   assert(0 <= joycodeIndex && joycodeIndex < 4);
2100   joycodes_string = options_get_string(settings, option_name);
2101   ColumnDecodeStringWithCount(joycodes_string, joycodes, ARRAY_LENGTH(joycodes));
2102   return joycodes[joycodeIndex];
2103}
2104
2105static void SetUIJoy(const char *option_name, int joycodeIndex, int val)
2106{
2107   const char *joycodes_string;
2108   int joycodes[4];
2109   char buffer[1024];
2110
2111   assert(0 <= joycodeIndex && joycodeIndex < 4);
2112   joycodes_string = options_get_string(settings, option_name);
2113   ColumnDecodeStringWithCount(joycodes_string, joycodes, ARRAY_LENGTH(joycodes));
2114
2115   joycodes[joycodeIndex] = val;
2116   ColumnEncodeStringWithCount(joycodes, buffer, ARRAY_LENGTH(joycodes));
2117   options_set_string(settings, option_name, buffer, OPTION_PRIORITY_CMDLINE);
2118
2119
2120}
2121
2122int GetUIJoyUp(int joycodeIndex)
2123{
2124   return GetUIJoy(M32OPTION_UI_JOY_UP, joycodeIndex);
2125}
2126
2127void SetUIJoyUp(int joycodeIndex, int val)
2128{
2129   SetUIJoy(M32OPTION_UI_JOY_UP, joycodeIndex, val);
2130}
2131
2132int GetUIJoyDown(int joycodeIndex)
2133{
2134   return GetUIJoy(M32OPTION_UI_JOY_DOWN, joycodeIndex);
2135}
2136
2137void SetUIJoyDown(int joycodeIndex, int val)
2138{
2139   SetUIJoy(M32OPTION_UI_JOY_DOWN, joycodeIndex, val);
2140}
2141
2142int GetUIJoyLeft(int joycodeIndex)
2143{
2144   return GetUIJoy(M32OPTION_UI_JOY_LEFT, joycodeIndex);
2145}
2146
2147void SetUIJoyLeft(int joycodeIndex, int val)
2148{
2149   SetUIJoy(M32OPTION_UI_JOY_LEFT, joycodeIndex, val);
2150}
2151
2152int GetUIJoyRight(int joycodeIndex)
2153{
2154   return GetUIJoy(M32OPTION_UI_JOY_RIGHT, joycodeIndex);
2155}
2156
2157void SetUIJoyRight(int joycodeIndex, int val)
2158{
2159   SetUIJoy(M32OPTION_UI_JOY_RIGHT, joycodeIndex, val);
2160}
2161
2162int GetUIJoyStart(int joycodeIndex)
2163{
2164   return GetUIJoy(M32OPTION_UI_JOY_START, joycodeIndex);
2165}
2166
2167void SetUIJoyStart(int joycodeIndex, int val)
2168{
2169   SetUIJoy(M32OPTION_UI_JOY_START, joycodeIndex, val);
2170}
2171
2172int GetUIJoyPageUp(int joycodeIndex)
2173{
2174   return GetUIJoy(M32OPTION_UI_JOY_PGUP, joycodeIndex);
2175}
2176
2177void SetUIJoyPageUp(int joycodeIndex, int val)
2178{
2179   SetUIJoy(M32OPTION_UI_JOY_PGUP, joycodeIndex, val);
2180}
2181
2182int GetUIJoyPageDown(int joycodeIndex)
2183{
2184   return GetUIJoy(M32OPTION_UI_JOY_PGDWN, joycodeIndex);
2185}
2186
2187void SetUIJoyPageDown(int joycodeIndex, int val)
2188{
2189   SetUIJoy(M32OPTION_UI_JOY_PGDWN, joycodeIndex, val);
2190}
2191
2192int GetUIJoyHome(int joycodeIndex)
2193{
2194   return GetUIJoy(M32OPTION_UI_JOY_HOME, joycodeIndex);
2195}
2196
2197void SetUIJoyHome(int joycodeIndex, int val)
2198{
2199   SetUIJoy(M32OPTION_UI_JOY_HOME, joycodeIndex, val);
2200}
2201
2202int GetUIJoyEnd(int joycodeIndex)
2203{
2204   return GetUIJoy(M32OPTION_UI_JOY_END, joycodeIndex);
2205}
2206
2207void SetUIJoyEnd(int joycodeIndex, int val)
2208{
2209   SetUIJoy(M32OPTION_UI_JOY_END, joycodeIndex, val);
2210}
2211
2212int GetUIJoySSChange(int joycodeIndex)
2213{
2214   return GetUIJoy(M32OPTION_UI_JOY_SS_CHANGE, joycodeIndex);
2215}
2216
2217void SetUIJoySSChange(int joycodeIndex, int val)
2218{
2219   SetUIJoy(M32OPTION_UI_JOY_SS_CHANGE, joycodeIndex, val);
2220}
2221
2222int GetUIJoyHistoryUp(int joycodeIndex)
2223{
2224   return GetUIJoy(M32OPTION_UI_JOY_HISTORY_UP, joycodeIndex);
2225}
2226
2227void SetUIJoyHistoryUp(int joycodeIndex, int val)
2228{
2229   SetUIJoy(M32OPTION_UI_JOY_HISTORY_UP, joycodeIndex, val);
2230}
2231
2232int GetUIJoyHistoryDown(int joycodeIndex)
2233{
2234   return GetUIJoy(M32OPTION_UI_JOY_HISTORY_DOWN, joycodeIndex);
2235}
2236
2237void SetUIJoyHistoryDown(int joycodeIndex, int val)
2238{
2239   SetUIJoy(M32OPTION_UI_JOY_HISTORY_DOWN, joycodeIndex, val);
2240}
2241
2242void SetUIJoyExec(int joycodeIndex, int val)
2243{
2244   SetUIJoy(M32OPTION_UI_JOY_EXEC, joycodeIndex, val);
2245}
2246
2247int GetUIJoyExec(int joycodeIndex)
2248{
2249   return GetUIJoy(M32OPTION_UI_JOY_EXEC, joycodeIndex);
2250}
2251
2252const char * GetExecCommand(void)
2253{
2254   return options_get_string(settings, M32OPTION_EXEC_COMMAND);
2255}
2256
2257void SetExecCommand(char *cmd)
2258{
2259   options_set_string(settings, M32OPTION_EXEC_COMMAND, cmd, OPTION_PRIORITY_CMDLINE);
2260}
2261
2262int GetExecWait(void)
2263{
2264   return options_get_int(settings, M32OPTION_EXEC_WAIT);
2265}
2266
2267void SetExecWait(int wait)
2268{
2269   options_set_int(settings, M32OPTION_EXEC_WAIT, wait, OPTION_PRIORITY_CMDLINE);
2270}
2271 
2272BOOL GetHideMouseOnStartup(void)
2273{
2274   return options_get_bool(settings, M32OPTION_HIDE_MOUSE);
2275}
2276
2277void SetHideMouseOnStartup(BOOL hide)
2278{
2279   options_set_bool(settings, M32OPTION_HIDE_MOUSE, hide, OPTION_PRIORITY_CMDLINE);
2280}
2281
2282BOOL GetRunFullScreen(void)
2283{
2284   return options_get_bool(settings, M32OPTION_FULL_SCREEN);
2285}
2286
2287void SetRunFullScreen(BOOL fullScreen)
2288{
2289   options_set_bool(settings, M32OPTION_FULL_SCREEN, fullScreen, OPTION_PRIORITY_CMDLINE);
2290}
2291
2292/***************************************************************************
2293    Internal functions
2294 ***************************************************************************/
2295
2296static void  CusColorEncodeString(const COLORREF *value, char* str)
2297{
2298   int  i;
2299   char tmpStr[256];
2300
2301   sprintf(tmpStr, "%u", (int) value[0]);
2302   
2303   strcpy(str, tmpStr);
2304
2305   for (i = 1; i < 16; i++)
2306   {
2307      sprintf(tmpStr, ",%u", (unsigned) value[i]);
2308      strcat(str, tmpStr);
2309   }
2310}
2311
2312static void CusColorDecodeString(const char* str, COLORREF *value)
2313{
2314   int  i;
2315   char *s, *p;
2316   char tmpStr[256];
2317
2318   strcpy(tmpStr, str);
2319   p = tmpStr;
2320   
2321   for (i = 0; p && i < 16; i++)
2322   {
2323      s = p;
2324     
2325      if ((p = strchr(s,',')) != NULL && *p == ',')
2326      {
2327         *p = '\0';
2328         p++;
2329      }
2330      value[i] = atoi(s);
2331   }
2332}
2333
2334
2335void ColumnEncodeStringWithCount(const int *value, char *str, int count)
2336{
2337   int  i;
2338   char buffer[100];
2339
2340   snprintf(buffer,sizeof(buffer),"%d",value[0]);
2341   
2342   strcpy(str,buffer);
2343
2344    for (i = 1; i < count; i++)
2345   {
2346      snprintf(buffer,sizeof(buffer),",%d",value[i]);
2347      strcat(str,buffer);
2348   }
2349}
2350
2351void ColumnDecodeStringWithCount(const char* str, int *value, int count)
2352{
2353   int  i;
2354   char *s, *p;
2355   char tmpStr[100];
2356
2357   if (str == NULL)
2358      return;
2359
2360   strcpy(tmpStr, str);
2361   p = tmpStr;
2362   
2363    for (i = 0; p && i < count; i++)
2364   {
2365      s = p;
2366     
2367      if ((p = strchr(s,',')) != NULL && *p == ',')
2368      {
2369         *p = '\0';
2370         p++;
2371      }
2372      value[i] = atoi(s);
2373    }
2374   }
2375
2376static void SplitterEncodeString(const int *value, char* str)
2377{
2378   int  i;
2379   char tmpStr[100];
2380
2381   sprintf(tmpStr, "%d", value[0]);
2382   
2383   strcpy(str, tmpStr);
2384
2385   for (i = 1; i < GetSplitterCount(); i++)
2386   {
2387      sprintf(tmpStr, ",%d", value[i]);
2388      strcat(str, tmpStr);
2389   }
2390}
2391
2392static void SplitterDecodeString(const char *str, int *value)
2393{
2394   int  i;
2395   char *s, *p;
2396   char tmpStr[100];
2397
2398   strcpy(tmpStr, str);
2399   p = tmpStr;
2400   
2401   for (i = 0; p && i < GetSplitterCount(); i++)
2402   {
2403      s = p;
2404     
2405      if ((p = strchr(s,',')) != NULL && *p == ',')
2406      {
2407         *p = '\0';
2408         p++;
2409      }
2410      value[i] = atoi(s);
2411   }
2412}
2413
2414/* Parse the given comma-delimited string into a LOGFONT structure */
2415static void FontDecodeString(const char* str, LOGFONT *f)
2416{
2417   char*    ptr;
2418   TCHAR*     t_ptr;
2419   
2420   sscanf(str, "%li,%li,%li,%li,%li,%i,%i,%i,%i,%i,%i,%i,%i",
2421         &f->lfHeight,
2422         &f->lfWidth,
2423         &f->lfEscapement,
2424         &f->lfOrientation,
2425         &f->lfWeight,
2426         (int*)&f->lfItalic,
2427         (int*)&f->lfUnderline,
2428         (int*)&f->lfStrikeOut,
2429         (int*)&f->lfCharSet,
2430         (int*)&f->lfOutPrecision,
2431         (int*)&f->lfClipPrecision,
2432         (int*)&f->lfQuality,
2433         (int*)&f->lfPitchAndFamily);
2434   ptr = strrchr(str, ',');
2435   if (ptr != NULL) {
2436      t_ptr = tstring_from_utf8(ptr + 1);
2437      if( !t_ptr )
2438         return;
2439      _tcscpy(f->lfFaceName, t_ptr);
2440      free(t_ptr);
2441   }
2442}
2443
2444/* Encode the given LOGFONT structure into a comma-delimited string */
2445static void FontEncodeString(const LOGFONT *f, char *str)
2446{
2447   char* utf8_FaceName = utf8_from_tstring(f->lfFaceName);
2448   if( !utf8_FaceName )
2449      return;
2450   
2451   sprintf(str, "%li,%li,%li,%li,%li,%i,%i,%i,%i,%i,%i,%i,%i,%s",
2452         f->lfHeight,
2453         f->lfWidth,
2454         f->lfEscapement,
2455         f->lfOrientation,
2456         f->lfWeight,
2457         f->lfItalic,
2458         f->lfUnderline,
2459         f->lfStrikeOut,
2460         f->lfCharSet,
2461         f->lfOutPrecision,
2462         f->lfClipPrecision,
2463         f->lfQuality,
2464         f->lfPitchAndFamily,
2465         utf8_FaceName);
2466         
2467   free(utf8_FaceName);
2468}
2469
2470static void TabFlagsEncodeString(int data, char *str)
2471{
2472   int i;
2473   int num_saved = 0;
2474
2475   strcpy(str,"");
2476
2477   // we save the ones that are NOT displayed, so we can add new ones
2478   // and upgraders will see them
2479   for (i=0;i<MAX_TAB_TYPES;i++)
2480   {
2481      if (((data & (1 << i)) == 0) && GetImageTabShortName(i))
2482      {
2483         if (num_saved != 0)
2484            strcat(str, ", ");
2485
2486         strcat(str,GetImageTabShortName(i));
2487         num_saved++;
2488      }
2489   }
2490}
2491
2492static void TabFlagsDecodeString(const char *str, int *data)
2493{
2494   char s[2000];
2495   char *token;
2496
2497   snprintf(s, ARRAY_LENGTH(s), "%s", str);
2498
2499   // simple way to set all tab bits "on"
2500   *data = (1 << MAX_TAB_TYPES) - 1;
2501
2502   token = strtok(s,", \t");
2503   while (token != NULL)
2504   {
2505      int j;
2506
2507      for (j=0;j<MAX_TAB_TYPES;j++)
2508      {
2509         if (!GetImageTabShortName(j) || (strcmp(GetImageTabShortName(j), token) == 0))
2510         {
2511            // turn off this bit
2512            *data &= ~(1 << j);
2513            break;
2514         }
2515      }
2516      token = strtok(NULL,", \t");
2517   }
2518
2519   if (*data == 0)
2520   {
2521      // not allowed to hide all tabs, because then why even show the area?
2522      *data = (1 << TAB_SCREENSHOT);
2523   }
2524}
2525
2526
2527
2528static file_error LoadSettingsFile(core_options *opts, const char *filename)
2529{
2530   core_file *file;
2531   file_error filerr;
2532
2533   filerr = core_fopen(filename, OPEN_FLAG_READ, &file);
2534   if (filerr == FILERR_NONE)
2535   {
2536      options_parse_ini_file(opts, file, OPTION_PRIORITY_CMDLINE);
2537      core_fclose(file);
2538   }
2539   return filerr;
2540}
2541
2542
2543
2544static file_error SaveSettingsFile(core_options *opts, const char *filename)
2545{
2546   core_file *file;
2547   file_error filerr;
2548
2549   if (opts != NULL)
2550   {
2551      filerr = core_fopen(filename, OPEN_FLAG_WRITE | OPEN_FLAG_CREATE | OPEN_FLAG_CREATE_PATHS, &file);
2552      if (filerr == FILERR_NONE)
2553      {
2554         options_output_ini_file(opts, file);
2555         core_fclose(file);
2556      }
2557   }
2558   else
2559   {
2560      filerr = osd_rmfile(filename);
2561   }
2562
2563   return filerr;
2564}
2565
2566
2567
2568static void GetGlobalOptionsFileName(char *filename, size_t filename_size)
2569{
2570   char buffer[MAX_PATH];
2571   char *base;
2572   char *s;
2573
2574   // retrieve filename of executable
2575   win_get_module_file_name_utf8(GetModuleHandle(NULL), buffer, ARRAY_LENGTH(buffer));
2576
2577   // locate base filename
2578   base = strrchr(buffer, '\\');
2579   base = base ? base + 1 : buffer;
2580
2581   // remove ".exe"
2582   s = strstr(base, ".exe");
2583   if (s)
2584      *s = '\0';
2585
2586   // copy INI directory
2587   snprintf(filename, filename_size, "%s\\%s.ini", GetIniDir(), base);
2588}
2589
2590
2591
2592/* Register access functions below */
2593static void LoadOptionsAndSettings(void)
2594{
2595   char buffer[MAX_PATH];
2596
2597   // parse MAME32.ini
2598   LoadSettingsFile(settings, UI_INI_FILENAME);
2599
2600   // parse global options
2601   GetGlobalOptionsFileName(buffer, ARRAY_LENGTH(buffer));
2602   LoadSettingsFile(global, buffer);
2603}
2604
2605void LoadGameOptions(int driver_index)
2606{
2607   char filename[MAX_PATH];
2608
2609   options_copy(game_options[driver_index], global);
2610
2611   snprintf(filename, ARRAY_LENGTH(filename), "%s\\%s.ini", GetIniDir(), drivers[driver_index]->name);
2612   LoadSettingsFile(game_options[driver_index], filename);
2613}
2614
2615const char * GetFolderNameByID(UINT nID)
2616{
2617   UINT i;
2618   extern FOLDERDATA g_folderData[];
2619   extern LPEXFOLDERDATA ExtraFolderData[];
2620
2621   for (i = 0; i < MAX_EXTRA_FOLDERS * MAX_EXTRA_SUBFOLDERS; i++)
2622   {
2623      if( ExtraFolderData[i] )
2624      {
2625         if (ExtraFolderData[i]->m_nFolderId == nID)
2626         {
2627            return ExtraFolderData[i]->m_szTitle;
2628         }
2629      }
2630   }
2631   for( i = 0; i < MAX_FOLDERS; i++)
2632   {
2633      if (g_folderData[i].m_nFolderId == nID)
2634      {
2635         
2636         return g_folderData[i].m_lpTitle;
2637      }
2638   }
2639   return NULL;
2640}
2641
2642void LoadFolderOptions(int folder_index )
2643{
2644   int redirect_index;
2645   char filename[MAX_PATH];
2646
2647   GetFolderSettingsFileName(folder_index, filename, ARRAY_LENGTH(filename));
2648   
2649   //Use the redirect array, to get correct folder
2650   redirect_index = GetRedirectIndex(folder_index);
2651   if( redirect_index < 0)
2652      return;
2653
2654   options_copy(folder_options[redirect_index], global);
2655   LoadSettingsFile(folder_options[redirect_index], filename);
2656}
2657
2658DWORD GetFolderFlags(int folder_index)
2659{
2660   int i;
2661
2662   for (i=0;i<num_folder_filters;i++)
2663   {
2664      if (folder_filters[i].folder_index == folder_index)
2665      {
2666         //dprintf("found folder filter %i %i",folder_index,folder_filters[i].filters);
2667         return folder_filters[i].filters;
2668      }
2669   }
2670   return 0;
2671}
2672
2673
2674
2675void SaveOptions(void)
2676{
2677   SaveSettingsFile(settings, UI_INI_FILENAME);
2678}
2679
2680//returns true if same
2681BOOL GetVectorUsesDefaults(void)
2682{
2683   int redirect_index = 0;
2684
2685   //Use the redirect array, to get correct folder
2686   redirect_index = GetRedirectIndex(FOLDER_VECTOR);
2687   if( redirect_index < 0)
2688      return TRUE;
2689
2690   return options_equal(folder_options[redirect_index], global);
2691}
2692
2693//returns true if same
2694BOOL GetFolderUsesDefaults(int folder_index, int driver_index)
2695{
2696   core_options *opts;
2697   int redirect_index;
2698
2699   if (DriverIsVector(driver_index) && (folder_index != FOLDER_VECTOR))
2700      opts = GetVectorOptions();
2701   else
2702      opts = global;
2703
2704   //Use the redirect array, to get correct folder
2705   redirect_index = GetRedirectIndex(folder_index);
2706   if( redirect_index < 0)
2707      return TRUE;
2708
2709   return options_equal(folder_options[redirect_index], opts);
2710}
2711
2712//returns true if same
2713BOOL GetGameUsesDefaults(int driver_index)
2714{
2715   core_options *opts = NULL;
2716   int nParentIndex = -1;
2717   BOOL bUsesDefaults = TRUE;
2718
2719   assert(0 <= driver_index && driver_index < driver_list_get_count(drivers));
2720
2721   if (game_options[driver_index] != NULL)
2722   {
2723      if ((driver_index >= 0) && DriverIsClone(driver_index))
2724      {
2725         nParentIndex = GetParentIndex(drivers[driver_index]);
2726         if( nParentIndex >= 0)
2727            opts = GetGameOptions(nParentIndex, FALSE);
2728         else
2729            //No Parent found, use source
2730            opts = GetSourceOptions(driver_index);
2731      }
2732      else
2733         opts = GetSourceOptions(driver_index);
2734
2735      bUsesDefaults = options_equal(game_options[driver_index], opts);
2736   }
2737   return bUsesDefaults;
2738}
2739
2740void SaveGameOptions(int driver_index)
2741{
2742   core_options *opts;
2743   char filename[MAX_PATH];
2744
2745   // save out the actual settings file
2746   snprintf(filename, ARRAY_LENGTH(filename), "%s\\%s.ini", GetIniDir(), drivers[driver_index]->name);
2747   opts = GetGameUsesDefaults(driver_index) ? NULL : game_options[driver_index];
2748   SaveSettingsFile(opts, filename);
2749}
2750
2751void SaveFolderOptions(int folder_index, int game_index)
2752{
2753   int redirect_index;
2754   char filename[MAX_PATH];
2755   core_options *opts;
2756
2757   GetFolderSettingsFileName(folder_index, filename, ARRAY_LENGTH(filename));
2758   
2759   //Use the redirect array, to get correct folder
2760   redirect_index = GetRedirectIndex(folder_index);
2761   if( redirect_index < 0)
2762      return;
2763
2764   opts = GetFolderUsesDefaults(folder_index, game_index) ? NULL : folder_options[redirect_index];
2765   SaveSettingsFile(opts, filename);
2766}
2767
2768
2769void SaveDefaultOptions(void)
2770{
2771   char buffer[MAX_PATH];
2772   GetGlobalOptionsFileName(buffer, ARRAY_LENGTH(buffer));
2773   SaveSettingsFile(global, buffer);
2774}
2775
2776char * GetVersionString(void)
2777{
2778   return build_version;
2779}
2780
2781
2782BOOL IsGlobalOption(const char *option_name)
2783{
2784   static const char *global_options[] =
2785   {
2786      OPTION_ROMPATH,
2787#ifdef MESS
2788      OPTION_HASHPATH,
2789#endif // MESS
2790      OPTION_SAMPLEPATH,
2791      OPTION_ARTPATH,
2792      OPTION_CTRLRPATH,
2793      OPTION_INIPATH,
2794      OPTION_FONTPATH,
2795      OPTION_CFG_DIRECTORY,
2796      OPTION_NVRAM_DIRECTORY,
2797      OPTION_MEMCARD_DIRECTORY,
2798      OPTION_INPUT_DIRECTORY,
2799      OPTION_STATE_DIRECTORY,
2800      OPTION_SNAPSHOT_DIRECTORY,
2801      OPTION_DIFF_DIRECTORY,
2802      OPTION_COMMENT_DIRECTORY
2803   };
2804   int i;
2805   char command_name[128];
2806   char *s;
2807
2808   // determine command name
2809   snprintf(command_name, ARRAY_LENGTH(command_name), "%s", option_name);
2810   s = strchr(command_name, ';');
2811   if (s)
2812      *s = '\0';
2813
2814   for (i = 0; i < ARRAY_LENGTH(global_options); i++)
2815   {
2816      if (!strcmp(command_name, global_options[i]))
2817         return TRUE;
2818   }
2819   return FALSE;
2820}
2821
src/osd/windows/ui/dirwatch.h
r995r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11 ***************************************************************************/
12
13typedef struct DirWatcher *PDIRWATCHER;
14
15PDIRWATCHER DirWatcher_Init(HWND hwndTarget, UINT nMessage);
16BOOL DirWatcher_Watch(PDIRWATCHER pWatcher, WORD nIndex, LPCSTR pszPathList, BOOL bWatchSubtrees);
17void DirWatcher_Free(PDIRWATCHER pWatcher);
src/osd/windows/ui/audit32.c
r995r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11 ***************************************************************************/
12 
13 /***************************************************************************
14
15  audit32.c
16
17  Audit dialog
18
19***************************************************************************/
20
21#define WIN32_LEAN_AND_MEAN
22#include <windows.h>
23#include <windowsx.h>
24#include <commctrl.h>
25#include <stdio.h>
26#include <richedit.h>
27#include <tchar.h>
28
29#include "screenshot.h"
30#include "win32ui.h"
31#include "winutf8.h"
32
33#include <audit.h>
34#include <unzip.h>
35
36#include "resource.h"
37
38#include "bitmask.h"
39#include "m32opts.h"
40#include "m32util.h"
41#include "audit32.h"
42#include "Properties.h"
43#include "emuopts.h"
44#include "winmain.h"
45#include "strconv.h"
46
47/***************************************************************************
48    function prototypes
49 ***************************************************************************/
50
51static DWORD WINAPI AuditThreadProc(LPVOID hDlg);
52static INT_PTR CALLBACK AuditWindowProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam);
53static void ProcessNextRom(void);
54static void ProcessNextSample(void);
55static void CLIB_DECL DetailsPrintf(const char *fmt, ...);
56static const char * StatusString(int iStatus);
57
58/***************************************************************************
59    Internal variables
60 ***************************************************************************/
61
62#define SAMPLES_NOT_USED    3
63#define MAX_TEXT         2147483647
64
65HWND hAudit;
66static int rom_index;
67static int roms_correct;
68static int roms_incorrect;
69static int sample_index;
70static int samples_correct;
71static int samples_incorrect;
72
73static BOOL bPaused = FALSE;
74static BOOL bCancel = FALSE;
75
76/***************************************************************************
77    External functions 
78 ***************************************************************************/
79
80void AuditDialog(HWND hParent)
81{
82   HMODULE hModule = NULL;
83   rom_index         = 0;
84   roms_correct      = 0;
85   roms_incorrect    = 0;
86   sample_index      = 0;
87   samples_correct   = 0;
88   samples_incorrect = 0;
89
90   //RS use Riched32.dll
91   hModule = LoadLibrary(TEXT("Riched32.dll"));
92   if( hModule )
93   {
94      DialogBox(GetModuleHandle(NULL),MAKEINTRESOURCE(IDD_AUDIT),hParent,AuditWindowProc);
95      FreeLibrary( hModule );
96      hModule = NULL;
97   }
98   else
99   {
100       MessageBox(GetMainWindow(),TEXT("Unable to Load Riched32.dll"),TEXT("Error"),
101               MB_OK | MB_ICONERROR);
102   }
103   
104}
105
106void InitGameAudit(int gameIndex)
107{
108   rom_index = gameIndex;
109}
110
111const char * GetAuditString(int audit_result)
112{
113   switch (audit_result)
114   {
115   case CORRECT :
116   case BEST_AVAILABLE :
117      return "Yes";
118
119   case NOTFOUND :
120   case INCORRECT :
121      return "No";
122      break;
123
124   case UNKNOWN :
125      return "?";
126
127   default:
128      dprintf("unknown audit value %i",audit_result);
129   }
130
131   return "?";
132}
133
134BOOL IsAuditResultKnown(int audit_result)
135{
136   return audit_result != UNKNOWN;
137}
138
139BOOL IsAuditResultYes(int audit_result)
140{
141   return audit_result == CORRECT || audit_result == BEST_AVAILABLE;
142}
143
144BOOL IsAuditResultNo(int audit_result)
145{
146   return audit_result == NOTFOUND || audit_result == INCORRECT;
147}
148
149
150/***************************************************************************
151    Internal functions
152 ***************************************************************************/
153
154static void Mame32Output(void *param, const char *format, va_list argptr)
155{
156   char buffer[512];
157   vsnprintf(buffer, sizeof(buffer) / sizeof(buffer[0]), format, argptr);
158   DetailsPrintf("%s", buffer);
159}
160
161static int ProcessAuditResults(int game, audit_record *audit, int audit_records)
162{
163   output_callback prevcb;
164   void *prevparam;
165   int res;
166
167   mame_set_output_channel(OUTPUT_CHANNEL_INFO, Mame32Output, NULL, &prevcb, &prevparam);
168   res = audit_summary(drivers[game], audit_records, audit, TRUE);
169   mame_set_output_channel(OUTPUT_CHANNEL_INFO, prevcb ? prevcb : mame_null_output_callback, prevparam, NULL, NULL);
170
171   return res;
172}
173
174// Verifies the ROM set while calling SetRomAuditResults   
175int Mame32VerifyRomSet(int game)
176{
177   audit_record *audit;
178   int audit_records;
179   int res;
180   core_options *opts;
181
182   opts = mame_options_init(mame_win_options);
183   options_set_string(opts, OPTION_ROMPATH, GetRomDirs(), OPTION_PRIORITY_CMDLINE);
184   options_set_string(opts, OPTION_SAMPLEPATH, GetSampleDirs(), OPTION_PRIORITY_CMDLINE);
185
186   // perform the audit
187   audit_records = audit_images(opts, drivers[game], AUDIT_VALIDATE_FAST, &audit);
188   res = ProcessAuditResults(game, audit, audit_records);
189   if (audit_records > 0)
190      free(audit);
191
192   SetRomAuditResults(game, res);
193   options_free(opts);
194   return res;
195}
196
197// Verifies the Sample set while calling SetSampleAuditResults   
198int Mame32VerifySampleSet(int game)
199{
200   audit_record *audit;
201   int audit_records;
202   int res;
203   core_options *opts;
204
205   opts = mame_options_init(mame_win_options);
206   options_set_string(opts, OPTION_ROMPATH, GetRomDirs(), OPTION_PRIORITY_CMDLINE);
207   options_set_string(opts, OPTION_SAMPLEPATH, GetSampleDirs(), OPTION_PRIORITY_CMDLINE);
208
209   // perform the audit
210   audit_records = audit_samples(opts, drivers[game], &audit);
211   res = ProcessAuditResults(game, audit, audit_records);
212   if (audit_records > 0)
213      free(audit);
214
215   SetSampleAuditResults(game, res);
216   options_free(opts);
217   return res;
218}
219
220static DWORD WINAPI AuditThreadProc(LPVOID hDlg)
221{
222   char buffer[200];
223
224   while (!bCancel)
225   {
226      if (!bPaused)
227      {
228         if (rom_index != -1)
229         {
230            sprintf(buffer, "Checking Game %s - %s",
231               drivers[rom_index]->name, drivers[rom_index]->description);
232            win_set_window_text_utf8(hDlg, buffer);
233            ProcessNextRom();
234         }
235         else
236         {
237            if (sample_index != -1)
238            {
239               sprintf(buffer, "Checking Game %s - %s",
240                  drivers[sample_index]->name, drivers[sample_index]->description);
241               win_set_window_text_utf8(hDlg, buffer);
242               ProcessNextSample();
243            }
244            else
245            {
246               win_set_window_text_utf8(hDlg, "File Audit");
247               EnableWindow(GetDlgItem(hDlg, IDPAUSE), FALSE);
248               ExitThread(1);
249            }
250         }
251      }
252   }
253   return 0;
254}
255
256static INT_PTR CALLBACK AuditWindowProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam)
257{
258   static HANDLE hThread;
259   static DWORD dwThreadID;
260   DWORD dwExitCode;
261   HWND hEdit;
262
263   switch (Msg)
264   {
265   case WM_INITDIALOG:
266      hAudit = hDlg;
267      //RS 20030613 Set Bkg of RichEdit Ctrl
268      hEdit = GetDlgItem(hAudit, IDC_AUDIT_DETAILS);
269      if (hEdit != NULL)
270      {
271         SendMessage( hEdit, EM_SETBKGNDCOLOR, FALSE, GetSysColor(COLOR_BTNFACE) );
272         //RS Standard is MAX_UINT, which seems not to be enough, so we use a higher Number...
273         SendMessage( hEdit, EM_EXLIMITTEXT, 0, MAX_TEXT );
274      }
275      SendDlgItemMessage(hDlg, IDC_ROMS_PROGRESS,    PBM_SETRANGE, 0, MAKELPARAM(0, driver_list_get_count(drivers)));
276      SendDlgItemMessage(hDlg, IDC_SAMPLES_PROGRESS, PBM_SETRANGE, 0, MAKELPARAM(0, driver_list_get_count(drivers)));
277      bPaused = FALSE;
278      bCancel = FALSE;
279      rom_index = 0;
280      hThread = CreateThread(NULL, 0, AuditThreadProc, hDlg, 0, &dwThreadID);
281      return 1;
282
283   case WM_COMMAND:
284      switch (LOWORD(wParam))
285      {
286      case IDCANCEL:
287            bPaused = FALSE;
288         if (hThread)
289         {
290            bCancel = TRUE;
291            if (GetExitCodeThread(hThread, &dwExitCode) && dwExitCode == STILL_ACTIVE)
292            {
293               PostMessage(hDlg, WM_COMMAND, wParam, lParam);
294               return 1;
295            }
296            CloseHandle(hThread);
297         }
298         EndDialog(hDlg,0);
299         break;
300
301      case IDPAUSE:
302         if (bPaused)
303         {
304            SendDlgItemMessage(hAudit, IDPAUSE, WM_SETTEXT, 0, (LPARAM)TEXT("Pause"));
305            bPaused = FALSE;
306         }
307         else
308         {
309            SendDlgItemMessage(hAudit, IDPAUSE, WM_SETTEXT, 0, (LPARAM)TEXT("Continue"));
310            bPaused = TRUE;
311         }
312         break;
313      }
314      return 1;
315   }
316   return 0;
317}
318
319/* Callback for the Audit property sheet */
320INT_PTR CALLBACK GameAuditDialogProc(HWND hDlg,UINT Msg,WPARAM wParam,LPARAM lParam)
321{
322   switch (Msg)
323   {
324   case WM_INITDIALOG:
325      FlushFileCaches();
326      hAudit = hDlg;
327      win_set_window_text_utf8(GetDlgItem(hDlg, IDC_PROP_TITLE), GameInfoTitle(rom_index));
328      SetTimer(hDlg, 0, 1, NULL);
329      return 1;
330
331   case WM_TIMER:
332      KillTimer(hDlg, 0);
333      {
334         int iStatus;
335         LPCSTR lpStatus;
336
337         iStatus = Mame32VerifyRomSet(rom_index);
338         lpStatus = DriverUsesRoms(rom_index) ? StatusString(iStatus) : "None required";
339         win_set_window_text_utf8(GetDlgItem(hDlg, IDC_PROP_ROMS), lpStatus);
340
341         iStatus = Mame32VerifySampleSet(rom_index);
342         lpStatus = DriverUsesSamples(rom_index) ? StatusString(iStatus) : "None required";
343         win_set_window_text_utf8(GetDlgItem(hDlg, IDC_PROP_SAMPLES), lpStatus);
344      }
345      ShowWindow(hDlg, SW_SHOW);
346      break;
347   }
348   return 0;
349}
350
351static void ProcessNextRom()
352{
353   int retval;
354   TCHAR buffer[200];
355
356   retval = Mame32VerifyRomSet(rom_index);
357   switch (retval)
358   {
359   case BEST_AVAILABLE: /* correct, incorrect or separate count? */
360   case CORRECT:
361      roms_correct++;
362      _stprintf(buffer, TEXT("%i"), roms_correct);
363      SendDlgItemMessage(hAudit, IDC_ROMS_CORRECT, WM_SETTEXT, 0, (LPARAM)buffer);
364      _stprintf(buffer, TEXT("%i"), roms_correct + roms_incorrect);
365      SendDlgItemMessage(hAudit, IDC_ROMS_TOTAL, WM_SETTEXT, 0, (LPARAM)buffer);
366      break;
367
368   case NOTFOUND:
369      break;
370
371   case INCORRECT:
372      roms_incorrect++;
373      _stprintf(buffer, TEXT("%i"), roms_incorrect);
374      SendDlgItemMessage(hAudit, IDC_ROMS_INCORRECT, WM_SETTEXT, 0, (LPARAM)buffer);
375      _stprintf(buffer, TEXT("%i"), roms_correct + roms_incorrect);
376      SendDlgItemMessage(hAudit, IDC_ROMS_TOTAL, WM_SETTEXT, 0, (LPARAM)buffer);
377      break;
378   }
379
380   rom_index++;
381   SendDlgItemMessage(hAudit, IDC_ROMS_PROGRESS, PBM_SETPOS, rom_index, 0);
382
383   if (rom_index == driver_list_get_count(drivers))
384   {
385      sample_index = 0;
386      rom_index = -1;
387   }
388}
389
390static void ProcessNextSample()
391{
392   int  retval;
393   TCHAR buffer[200];
394   
395   retval = Mame32VerifySampleSet(sample_index);
396   
397   switch (retval)
398   {
399   case CORRECT:
400      if (DriverUsesSamples(sample_index))
401      {
402         samples_correct++;
403         _stprintf(buffer, TEXT("%i"), samples_correct);
404         SendDlgItemMessage(hAudit, IDC_SAMPLES_CORRECT, WM_SETTEXT, 0, (LPARAM)buffer);
405         _stprintf(buffer, TEXT("%i"), samples_correct + samples_incorrect);
406         SendDlgItemMessage(hAudit, IDC_SAMPLES_TOTAL, WM_SETTEXT, 0, (LPARAM)buffer);
407         break;
408      }
409
410   case NOTFOUND:
411      break;
412         
413   case INCORRECT:
414      samples_incorrect++;
415      _stprintf(buffer, TEXT("%i"), samples_incorrect);
416      SendDlgItemMessage(hAudit, IDC_SAMPLES_INCORRECT, WM_SETTEXT, 0, (LPARAM)buffer);
417      _stprintf(buffer, TEXT("%i"), samples_correct + samples_incorrect);
418      SendDlgItemMessage(hAudit, IDC_SAMPLES_TOTAL, WM_SETTEXT, 0, (LPARAM)buffer);
419     
420      break;
421   }
422
423   sample_index++;
424   SendDlgItemMessage(hAudit, IDC_SAMPLES_PROGRESS, PBM_SETPOS, sample_index, 0);
425   
426   if (sample_index == driver_list_get_count(drivers))
427   {
428      DetailsPrintf("Audit complete.\n");
429      SendDlgItemMessage(hAudit, IDCANCEL, WM_SETTEXT, 0, (LPARAM)TEXT("Close"));
430      sample_index = -1;
431   }
432}
433
434static void CLIB_DECL DetailsPrintf(const char *fmt, ...)
435{
436   HWND   hEdit;
437   va_list marker;
438   char   buffer[2000];
439   TCHAR*  t_s;
440
441   //RS 20030613 Different Ids for Property Page and Dialog
442   // so see which one's currently instantiated
443   hEdit = GetDlgItem(hAudit, IDC_AUDIT_DETAILS);
444   if (hEdit ==  NULL)
445      hEdit = GetDlgItem(hAudit, IDC_AUDIT_DETAILS_PROP);
446   
447   if (hEdit == NULL)
448   {
449      dprintf("audit detailsprintf() can't find any audit control");
450      return;
451   }
452
453   va_start(marker, fmt);
454   
455   vsprintf(buffer, fmt, marker);
456   
457   va_end(marker);
458
459   t_s = tstring_from_utf8(ConvertToWindowsNewlines(buffer));
460   if( !t_s )
461      return;
462
463   Edit_SetSel(hEdit, Edit_GetTextLength(hEdit), Edit_GetTextLength(hEdit));
464   SendMessage( hEdit, EM_REPLACESEL, FALSE, (WPARAM)(LPCTSTR)win_tstring_strdup(t_s) );
465   free(t_s);
466}
467
468static const char * StatusString(int iStatus)
469{
470   static const char *ptr;
471
472   ptr = "Unknown";
473
474   switch (iStatus)
475   {
476   case CORRECT:
477      ptr = "Passed";
478      break;
479     
480   case BEST_AVAILABLE:
481      ptr = "Best available";
482      break;
483     
484   case NOTFOUND:
485      ptr = "Not found";
486      break;
487     
488   case INCORRECT:
489      ptr = "Failed";
490      break;
491   }
492
493   return ptr;
494}
src/osd/windows/ui/m32opts.h
r995r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11 ***************************************************************************/
12
13#ifndef OPTIONS_H
14#define OPTIONS_H
15
16#include "osdcomm.h"
17#include "osd_cpu.h"
18#include "bitmask.h"
19#include "options.h"
20#include "inputseq.h" /* for input_seq definition */
21#include <video.h> /* for MAX_SCREENS Definition*/
22
23#ifdef MESS
24#include "ui/optionsms.h"
25#endif
26
27
28
29enum
30{
31   COLUMN_GAMES = 0,
32   COLUMN_ROMS,
33   COLUMN_SAMPLES,
34   COLUMN_DIRECTORY,
35   COLUMN_TYPE,
36   COLUMN_TRACKBALL,
37   COLUMN_PLAYED,
38   COLUMN_MANUFACTURER,
39   COLUMN_YEAR,
40   COLUMN_CLONE,
41   COLUMN_SRCDRIVERS,
42   COLUMN_PLAYTIME,
43   COLUMN_MAX
44};
45
46
47// can't be the same as the VerifyRomSet() results, listed in audit.h
48enum
49{
50   UNKNOWN   = -1
51};
52
53/* Default input */
54enum
55{
56   INPUT_LAYOUT_STD,
57   INPUT_LAYOUT_HR,
58   INPUT_LAYOUT_HRSE
59};
60
61// clean stretch types
62enum
63{
64   // these must match array of strings clean_stretch_long_name in options.c
65   CLEAN_STRETCH_NONE = 0,
66   CLEAN_STRETCH_AUTO = 1,
67
68   MAX_CLEAN_STRETCH = 5,
69};
70
71#define FOLDER_OPTIONS   -2
72#define GLOBAL_OPTIONS   -1
73
74// d3d effect types
75enum
76{
77   // these must match array of strings d3d_effects_long_name in options.c
78   D3D_EFFECT_NONE = 0,
79   D3D_EFFECT_AUTO = 1,
80
81   MAX_D3D_EFFECTS = 17,
82};
83
84// d3d prescale types
85enum
86{
87   D3D_PRESCALE_NONE = 0,
88   D3D_PRESCALE_AUTO = 1,
89   MAX_D3D_PRESCALE = 10,
90};
91
92typedef struct
93{
94   int x, y, width, height;
95} AREA;
96
97typedef struct
98{
99   char* screen;
100   char* aspect;
101   char* resolution;
102   char* view;
103} ScreenParams;
104
105
106
107// List of artwork types to display in the screen shot area
108enum
109{
110   // these must match array of strings image_tabs_long_name in options.c
111   // if you add new Tabs, be sure to also add them to the ComboBox init in dialogs.c
112   TAB_SCREENSHOT = 0,
113   TAB_FLYER,
114   TAB_CABINET,
115   TAB_MARQUEE,
116   TAB_TITLE,
117   TAB_CONTROL_PANEL,
118   TAB_HISTORY,
119
120   MAX_TAB_TYPES,
121   BACKGROUND,
122   TAB_ALL,
123   TAB_NONE
124};
125// Because we have added the Options after MAX_TAB_TYPES, we have to subtract 3 here
126// (that's how many options we have after MAX_TAB_TYPES)
127#define TAB_SUBTRACT 3
128
129BOOL OptionsInit(void);
130void FolderOptionsInit(void);
131void OptionsExit(void);
132
133#define OPTIONS_TYPE_GLOBAL      -1
134#define OPTIONS_TYPE_FOLDER      -2
135
136void AddOptions(core_options *opts, const options_entry *entrylist, BOOL is_global);
137core_options * CreateGameOptions(int driver_index);
138
139void SyncInFolderOptions(core_options *opts, int folder_index);
140core_options * GetDefaultOptions(int iProperty, BOOL bVectorFolder);
141core_options * GetFolderOptions(int folder_index, BOOL bIsVector);
142
143int * GetFolderOptionsRedirectArr(void);
144void SetFolderOptionsRedirectArr(int *redirect_arr);
145int GetRedirectIndex(int folder_index);
146int GetRedirectValue(int index);
147
148core_options * GetVectorOptions(void);
149core_options * GetSourceOptions(int driver_index );
150core_options * GetGameOptions(int driver_index, int folder_index );
151core_options * Mame32Settings(void);
152core_options * Mame32Global(void);
153BOOL GetVectorUsesDefaults(void);
154BOOL GetFolderUsesDefaults(int folder_index, int driver_index);
155BOOL GetGameUsesDefaults(int driver_index);
156BOOL GetGameUsesDefaults(int driver_index);
157void SetGameUsesDefaults(int driver_index, BOOL use_defaults);
158void LoadGameOptions(int driver_index);
159void LoadFolderOptions(int folder_index);
160
161const char* GetFolderNameByID(UINT nID);
162
163void SaveOptions(void);
164void SaveFolderOptions(int folder_index, int game_index);
165
166void ResetGUI(void);
167void ResetGameDefaults(void);
168void ResetAllGameOptions(void);
169
170const char * GetImageTabLongName(int tab_index);
171const char * GetImageTabShortName(int tab_index);
172
173void SetViewMode(int val);
174int  GetViewMode(void);
175
176void SetGameCheck(BOOL game_check);
177BOOL GetGameCheck(void);
178
179void SetVersionCheck(BOOL version_check);
180BOOL GetVersionCheck(void);
181
182void SetJoyGUI(BOOL use_joygui);
183BOOL GetJoyGUI(void);
184
185void SetKeyGUI(BOOL use_keygui);
186BOOL GetKeyGUI(void);
187
188void SetCycleScreenshot(int cycle_screenshot);
189int GetCycleScreenshot(void);
190
191void SetStretchScreenShotLarger(BOOL stretch);
192BOOL GetStretchScreenShotLarger(void);
193
194void SetScreenshotBorderSize(int size);
195int GetScreenshotBorderSize(void);
196
197void SetScreenshotBorderColor(COLORREF uColor);
198COLORREF GetScreenshotBorderColor(void);
199
200void SetFilterInherit(BOOL inherit);
201BOOL GetFilterInherit(void);
202
203void SetOffsetClones(BOOL offset);
204BOOL GetOffsetClones(void);
205
206void SetGameCaption(BOOL caption);
207BOOL GetGameCaption(void);
208
209void SetBroadcast(BOOL broadcast);
210BOOL GetBroadcast(void);
211
212void SetRandomBackground(BOOL random_bg);
213BOOL GetRandomBackground(void);
214
215void SetSavedFolderID(UINT val);
216UINT GetSavedFolderID(void);
217
218void SetShowScreenShot(BOOL val);
219BOOL GetShowScreenShot(void);
220
221void SetShowFolderList(BOOL val);
222BOOL GetShowFolderList(void);
223
224BOOL GetShowFolder(int folder);
225void SetShowFolder(int folder,BOOL show);
226
227
228void SetShowStatusBar(BOOL val);
229BOOL GetShowStatusBar(void);
230
231void SetShowToolBar(BOOL val);
232BOOL GetShowToolBar(void);
233
234void SetShowTabCtrl(BOOL val);
235BOOL GetShowTabCtrl(void);
236
237void SetCurrentTab(const char *shortname);
238const char *GetCurrentTab(void);
239
240void SetDefaultGame(const char *name);
241const char *GetDefaultGame(void);
242
243void SetWindowArea(const AREA *area);
244void GetWindowArea(AREA *area);
245
246void SetWindowState(UINT state);
247UINT GetWindowState(void);
248
249void SetColumnWidths(int widths[]);
250void GetColumnWidths(int widths[]);
251
252void SetColumnOrder(int order[]);
253void GetColumnOrder(int order[]);
254
255void SetColumnShown(int shown[]);
256void GetColumnShown(int shown[]);
257
258void SetSplitterPos(int splitterId, int pos);
259int  GetSplitterPos(int splitterId);
260
261void SetCustomColor(int iIndex, COLORREF uColor);
262COLORREF GetCustomColor(int iIndex);
263
264void SetListFont(const LOGFONT *font);
265void GetListFont(LOGFONT *font);
266
267DWORD GetFolderFlags(int folder_index);
268
269void SetListFontColor(COLORREF uColor);
270COLORREF GetListFontColor(void);
271
272void SetListCloneColor(COLORREF uColor);
273COLORREF GetListCloneColor(void);
274
275int GetHistoryTab(void);
276void SetHistoryTab(int tab,BOOL show);
277
278int GetShowTab(int tab);
279void SetShowTab(int tab,BOOL show);
280BOOL AllowedToSetShowTab(int tab,BOOL show);
281
282void SetSortColumn(int column);
283int  GetSortColumn(void);
284
285void SetSortReverse(BOOL reverse);
286BOOL GetSortReverse(void);
287
288const char* GetLanguage(void);
289void SetLanguage(const char* lang);
290
291const char* GetRomDirs(void);
292void SetRomDirs(const char* paths);
293
294const char* GetSampleDirs(void);
295void  SetSampleDirs(const char* paths);
296
297const char * GetIniDir(void);
298void SetIniDir(const char *path);
299
300const char* GetCfgDir(void);
301void SetCfgDir(const char* path);
302
303const char* GetNvramDir(void);
304void SetNvramDir(const char* path);
305
306const char* GetInpDir(void);
307void SetInpDir(const char* path);
308
309const char* GetImgDir(void);
310void SetImgDir(const char* path);
311
312const char* GetStateDir(void);
313void SetStateDir(const char* path);
314
315const char* GetArtDir(void);
316void SetArtDir(const char* path);
317
318const char* GetMemcardDir(void);
319void SetMemcardDir(const char* path);
320
321const char* GetFlyerDir(void);
322void SetFlyerDir(const char* path);
323
324const char* GetCabinetDir(void);
325void SetCabinetDir(const char* path);
326
327const char* GetMarqueeDir(void);
328void SetMarqueeDir(const char* path);
329
330const char* GetTitlesDir(void);
331void SetTitlesDir(const char* path);
332
333const char * GetControlPanelDir(void);
334void SetControlPanelDir(const char *path);
335
336const char* GetDiffDir(void);
337void SetDiffDir(const char* path);
338
339const char* GetIconsDir(void);
340void SetIconsDir(const char* path);
341
342const char *GetBgDir(void);
343void SetBgDir(const char *path);
344
345const char* GetCtrlrDir(void);
346void SetCtrlrDir(const char* path);
347
348const char* GetCommentDir(void);
349void SetCommentDir(const char* path);
350
351const char* GetFolderDir(void);
352void SetFolderDir(const char* path);
353
354const char* GetCheatFileName(void);
355void SetCheatFileName(const char* path);
356
357const char* GetHistoryFileName(void);
358void SetHistoryFileName(const char* path);
359
360const char* GetMAMEInfoFileName(void);
361void SetMAMEInfoFileName(const char* path);
362
363void ResetGameOptions(int driver_index);
364
365int GetRomAuditResults(int driver_index);
366void SetRomAuditResults(int driver_index, int audit_results);
367
368int GetSampleAuditResults(int driver_index);
369void SetSampleAuditResults(int driver_index, int audit_results);
370
371void IncrementPlayCount(int driver_index);
372int GetPlayCount(int driver_index);
373void ResetPlayCount(int driver_index);
374
375void IncrementPlayTime(int driver_index,int playtime);
376int GetPlayTime(int driver_index);
377void GetTextPlayTime(int driver_index,char *buf);
378void ResetPlayTime(int driver_index);
379
380char * GetVersionString(void);
381
382void SaveGameOptions(int driver_index);
383void SaveDefaultOptions(void);
384
385BOOL IsGlobalOption(const char *option_name);
386
387
388
389// Keyboard control of ui
390input_seq* Get_ui_key_up(void);
391input_seq* Get_ui_key_down(void);
392input_seq* Get_ui_key_left(void);
393input_seq* Get_ui_key_right(void);
394input_seq* Get_ui_key_start(void);
395input_seq* Get_ui_key_pgup(void);
396input_seq* Get_ui_key_pgdwn(void);
397input_seq* Get_ui_key_home(void);
398input_seq* Get_ui_key_end(void);
399input_seq* Get_ui_key_ss_change(void);
400input_seq* Get_ui_key_history_up(void);
401input_seq* Get_ui_key_history_down(void);
402
403input_seq* Get_ui_key_context_filters(void);
404input_seq* Get_ui_key_select_random(void);
405input_seq* Get_ui_key_game_audit(void);
406input_seq* Get_ui_key_game_properties(void);
407input_seq* Get_ui_key_help_contents(void);
408input_seq* Get_ui_key_update_gamelist(void);
409input_seq* Get_ui_key_view_folders(void);
410input_seq* Get_ui_key_view_fullscreen(void);
411input_seq* Get_ui_key_view_pagetab(void);
412input_seq* Get_ui_key_view_picture_area(void);
413input_seq* Get_ui_key_view_status(void);
414input_seq* Get_ui_key_view_toolbars(void);
415
416input_seq* Get_ui_key_view_tab_cabinet(void);
417input_seq* Get_ui_key_view_tab_cpanel(void);
418input_seq* Get_ui_key_view_tab_flyer(void);
419input_seq* Get_ui_key_view_tab_history(void);
420input_seq* Get_ui_key_view_tab_marquee(void);
421input_seq* Get_ui_key_view_tab_screenshot(void);
422input_seq* Get_ui_key_view_tab_title(void);
423input_seq* Get_ui_key_quit(void);
424
425
426int GetUIJoyUp(int joycodeIndex);
427void SetUIJoyUp(int joycodeIndex, int val);
428
429int GetUIJoyDown(int joycodeIndex);
430void SetUIJoyDown(int joycodeIndex, int val);
431
432int GetUIJoyLeft(int joycodeIndex);
433void SetUIJoyLeft(int joycodeIndex, int val);
434
435int GetUIJoyRight(int joycodeIndex);
436void SetUIJoyRight(int joycodeIndex, int val);
437
438int GetUIJoyStart(int joycodeIndex);
439void SetUIJoyStart(int joycodeIndex, int val);
440
441int GetUIJoyPageUp(int joycodeIndex);
442void SetUIJoyPageUp(int joycodeIndex, int val);
443
444int GetUIJoyPageDown(int joycodeIndex);
445void SetUIJoyPageDown(int joycodeIndex, int val);
446
447int GetUIJoyHome(int joycodeIndex);
448void SetUIJoyHome(int joycodeIndex, int val);
449
450int GetUIJoyEnd(int joycodeIndex);
451void SetUIJoyEnd(int joycodeIndex, int val);
452
453int GetUIJoySSChange(int joycodeIndex);
454void SetUIJoySSChange(int joycodeIndex, int val);
455
456int GetUIJoyHistoryUp(int joycodeIndex);
457void SetUIJoyHistoryUp(int joycodeIndex, int val);
458
459int GetUIJoyHistoryDown(int joycodeIndex);
460void SetUIJoyHistoryDown(int joycodeIndex, int val);
461
462int GetUIJoyExec(int joycodeIndex);
463void SetUIJoyExec(int joycodeIndex, int val);
464
465const char* GetExecCommand(void);
466void SetExecCommand(char* cmd);
467
468int GetExecWait(void);
469void SetExecWait(int wait);
470
471BOOL GetHideMouseOnStartup(void);
472void SetHideMouseOnStartup(BOOL hide);
473
474BOOL GetRunFullScreen(void);
475void SetRunFullScreen(BOOL fullScreen);
476
477void ColumnEncodeStringWithCount(const int *value, char *str, int count);
478void ColumnDecodeStringWithCount(const char* str, int *value, int count);
479
480#endif
src/osd/windows/ui/layout.c
r995r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11***************************************************************************/
12
13/***************************************************************************
14
15  layout.c
16
17  MAME specific TreeView definitions (and maybe more in the future)
18
19***************************************************************************/
20
21#define WIN32_LEAN_AND_MEAN
22#include <windows.h>
23#include <windowsx.h>
24#include <shellapi.h>
25#include <commctrl.h>
26#include <stdio.h>  /* for sprintf */
27#include <stdlib.h> /* For malloc and free */
28#include <string.h>
29
30#include "bitmask.h"
31#include "TreeView.h"
32#include "M32Util.h"
33#include "resource.h"
34#include "directories.h"
35#include "m32opts.h"
36#include "splitters.h"
37#include "help.h"
38#include "audit32.h"
39#include "screenshot.h"
40#include "win32ui.h"
41#include "properties.h"
42
43static BOOL FilterAvailable(int driver_index);
44
45FOLDERDATA g_folderData[] =
46{
47   {"All Games",       "allgames",          FOLDER_ALLGAMES,     IDI_FOLDER,            0,             0,            NULL,                       NULL,              TRUE },
48   {"Available",       "available",         FOLDER_AVAILABLE,    IDI_FOLDER_AVAILABLE,     F_AVAILABLE,   0,            NULL,                       FilterAvailable,              TRUE },
49#ifdef SHOW_UNAVAILABLE_FOLDER
50   {"Unavailable",     "unavailable",       FOLDER_UNAVAILABLE,  IDI_FOLDER_UNAVAILABLE,   0,             F_AVAILABLE,  NULL,                       FilterAvailable,              FALSE },
51#endif
52   {"Manufacturer",    "manufacturer",      FOLDER_MANUFACTURER, IDI_FOLDER_MANUFACTURER,  0,             0,            CreateManufacturerFolders },
53   {"Year",            "year",              FOLDER_YEAR,         IDI_FOLDER_YEAR,          0,             0,            CreateYearFolders },
54   {"Source",          "source",            FOLDER_SOURCE,       IDI_FOLDER_SOURCE,        0,             0,            CreateSourceFolders },
55   {"CPU",             "cpu",               FOLDER_CPU,          IDI_FOLDER,               0,             0,            CreateCPUFolders },
56   {"Sound",           "sound",             FOLDER_SND,          IDI_FOLDER,               0,             0,            CreateSoundFolders },
57   {"Orientation",     "orientation",       FOLDER_ORIENTATION,  IDI_FOLDER,               0,             0,            CreateOrientationFolders },
58   {"Imperfect",       "imperfect",         FOLDER_DEFICIENCY,   IDI_FOLDER,               0,             0,            CreateDeficiencyFolders },
59     {"Dumping Status",  "dumping",           FOLDER_DUMPING,      IDI_FOLDER,               0,             0,            CreateDumpingFolders },
60   {"Working",         "working",           FOLDER_WORKING,      IDI_WORKING,              F_WORKING,     F_NONWORKING, NULL,                       DriverIsBroken,    FALSE },
61   {"Not Working",     "nonworking",        FOLDER_NONWORKING,   IDI_NONWORKING,           F_NONWORKING,  F_WORKING,    NULL,                       DriverIsBroken,    TRUE },
62   {"Originals",       "originals",         FOLDER_ORIGINAL,     IDI_FOLDER,               F_ORIGINALS,   F_CLONES,     NULL,                       DriverIsClone,     FALSE },
63   {"Clones",          "clones",            FOLDER_CLONES,       IDI_FOLDER,               F_CLONES,      F_ORIGINALS,  NULL,                       DriverIsClone,     TRUE },
64   {"Raster",          "raster",            FOLDER_RASTER,       IDI_FOLDER,               F_RASTER,      F_VECTOR,     NULL,                       DriverIsVector,    FALSE },
65   {"Vector",          "vector",            FOLDER_VECTOR,       IDI_FOLDER,               F_VECTOR,      F_RASTER,     NULL,                       DriverIsVector,    TRUE },
66   {"Trackball",       "trackball",         FOLDER_TRACKBALL,    IDI_FOLDER,               0,             0,            NULL,                       DriverUsesTrackball,   TRUE },
67   {"Lightgun",        "Lightgun",          FOLDER_LIGHTGUN,     IDI_FOLDER,               0,             0,            NULL,                       DriverUsesLightGun,TRUE },
68   {"Stereo",          "stereo",            FOLDER_STEREO,       IDI_SOUND,                0,             0,            NULL,                       DriverIsStereo,    TRUE },
69//    {"Multi-Monitor",   "multimon",          FOLDER_MULTIMON,     IDI_FOLDER,               0,             0,            NULL,                       DriverIsMultiMon,  TRUE },
70   {"CHD",             "harddisk",          FOLDER_HARDDISK,     IDI_HARDDISK,             0,             0,            NULL,                       DriverIsHarddisk,  TRUE },
71     {"Samples",           "samples",           FOLDER_SAMPLES,      IDI_FOLDER,               0,             0,            NULL,                       DriverUsesSamples,  TRUE },
72     {"Save State",       "savestate",         FOLDER_SAVESTATE,    IDI_FOLDER,               0,             0,            NULL,                       DriverSupportsSaveState,  TRUE },
73     {"BIOS",          "bios",               FOLDER_BIOS,        IDI_FOLDER,               0,             0,            NULL,                       DriverIsBios,  TRUE },
74   { NULL }
75};
76
77/* list of filter/control Id pairs */
78FILTER_ITEM g_filterList[] =
79{
80   { F_CLONES,       IDC_FILTER_CLONES,      DriverIsClone, TRUE },
81   { F_NONWORKING,   IDC_FILTER_NONWORKING,  DriverIsBroken, TRUE },
82   { F_UNAVAILABLE,  IDC_FILTER_UNAVAILABLE, FilterAvailable, FALSE },
83   { F_RASTER,       IDC_FILTER_RASTER,      DriverIsVector, FALSE },
84   { F_VECTOR,       IDC_FILTER_VECTOR,      DriverIsVector, TRUE },
85   { F_ORIGINALS,    IDC_FILTER_ORIGINALS,   DriverIsClone, FALSE },
86   { F_WORKING,      IDC_FILTER_WORKING,     DriverIsBroken, FALSE },
87   { F_AVAILABLE,    IDC_FILTER_AVAILABLE,   FilterAvailable, TRUE },
88   { 0 }
89};
90
91DIRECTORYINFO g_directoryInfo[] =
92{
93   { "ROMs",                  GetRomDirs,      SetRomDirs,      TRUE,  DIRDLG_ROMS },
94   { "Samples",               GetSampleDirs,   SetSampleDirs,   TRUE,  DIRDLG_SAMPLES },
95   { "Ini Files",             GetIniDir,       SetIniDir,       FALSE, DIRDLG_INI },
96   { "Config",                GetCfgDir,       SetCfgDir,       FALSE, DIRDLG_CFG },
97   { "Snapshots",             GetImgDir,       SetImgDir,       FALSE, DIRDLG_IMG },
98   { "Input files (*.inp)",   GetInpDir,       SetInpDir,       FALSE, DIRDLG_INP },
99   { "State",                 GetStateDir,     SetStateDir,     FALSE, 0 },
100   { "Artwork",               GetArtDir,       SetArtDir,       FALSE, 0 },
101   { "Memory Card",           GetMemcardDir,   SetMemcardDir,   FALSE, 0 },
102   { "Flyers",                GetFlyerDir,     SetFlyerDir,     FALSE, 0 },
103   { "Cabinets",              GetCabinetDir,   SetCabinetDir,   FALSE, 0 },
104   { "Marquees",              GetMarqueeDir,   SetMarqueeDir,   FALSE, 0 },
105   { "Titles",                GetTitlesDir,    SetTitlesDir,    FALSE, 0 },
106   { "Control Panels",        GetControlPanelDir,SetControlPanelDir, FALSE, 0 },
107   { "NVRAM",                 GetNvramDir,     SetNvramDir,     FALSE, 0 },
108   { "Controller Files",      GetCtrlrDir,     SetCtrlrDir,     FALSE, DIRDLG_CTRLR },
109   { "Hard Drive Difference", GetDiffDir,      SetDiffDir,      FALSE, 0 },
110   { "Icons",                 GetIconsDir,     SetIconsDir,     FALSE, 0 },
111   { "Background Images",     GetBgDir,        SetBgDir,        FALSE, 0 },
112   { "Comment Files",      GetCommentDir,     SetCommentDir,     FALSE, DIRDLG_COMMENT },
113   { NULL }
114};
115
116const SPLITTERINFO g_splitterInfo[] =
117{
118   { 0.25,   IDC_SPLITTER,   IDC_TREE,   IDC_LIST,      AdjustSplitter1Rect },
119   { 0.5,   IDC_SPLITTER2,   IDC_LIST,   IDC_SSFRAME,   AdjustSplitter2Rect },
120   { -1 }
121};
122
123const MAMEHELPINFO g_helpInfo[] =
124{
125   { ID_HELP_CONTENTS,      TRUE,   MAME32HELP "::/html/mame32_overview.htm" },
126   { ID_HELP_WHATS_NEW32,   TRUE,   MAME32HELP "::/html/mame32_changes.htm" },
127   { ID_HELP_TROUBLE,      TRUE,   MAME32HELP "::/html/mame32_support.htm" },
128   { ID_HELP_RELEASE,      FALSE,   "windows.txt" },
129   { ID_HELP_WHATS_NEW,   TRUE,   MAME32HELP "::/docs/whatsnew.txt" },
130   { -1 }
131};
132
133const PROPERTYSHEETINFO g_propSheets[] =
134{
135   { FALSE,   NULL,               IDD_PROP_GAME,         GamePropertiesDialogProc },
136   { FALSE,   NULL,               IDD_PROP_AUDIT,         GameAuditDialogProc },
137   { TRUE,      NULL,               IDD_PROP_DISPLAY,      GameOptionsProc },
138   { TRUE,      NULL,               IDD_PROP_ADVANCED,      GameOptionsProc },
139   { TRUE,      NULL,               IDD_PROP_SCREEN,      GameOptionsProc },
140   { TRUE,      NULL,               IDD_PROP_SOUND,         GameOptionsProc },
141   { TRUE,      NULL,               IDD_PROP_INPUT,         GameOptionsProc },
142   { TRUE,      NULL,               IDD_PROP_CONTROLLER,   GameOptionsProc },
143   { TRUE,      NULL,               IDD_PROP_MISC,         GameOptionsProc },
144   { TRUE,      PropSheetFilter_Vector,   IDD_PROP_VECTOR,      GameOptionsProc },
145   { FALSE }
146};
147
148const ICONDATA g_iconData[] =
149{
150   { IDI_WIN_NOROMS,         "noroms" },
151   { IDI_WIN_ROMS,            "roms" },
152   { IDI_WIN_UNKNOWN,         "unknown" },
153   { IDI_WIN_CLONE,         "clone" },
154   { IDI_WIN_REDX,            "warning" },
155   { 0 }
156};
157
158const TCHAR g_szPlayGameString[] = TEXT("&Play %s");
159const char g_szGameCountString[] = "%d games";
160const char g_szHistoryFileName[] = "history.dat";
161const char g_szMameInfoFileName[] = "mameinfo.dat";
162
163static BOOL FilterAvailable(int driver_index)
164{
165   return IsAuditResultYes(GetRomAuditResults(driver_index));
166}
src/osd/windows/ui/dxdecode.c
r995r996
1#include <windows.h>
2#include <ddraw.h>
3#include <dinput.h>
4#include <stdio.h>
5
6#include "dxdecode.h"
7
8/***************************************************************/
9
10typedef struct tagERRORCODE
11{
12   HRESULT     hr;
13   const char *szError;
14} ERRORCODE, * LPERRORCODE;
15
16/***************************************************************/
17static ERRORCODE    g_ErrorCode[] =
18{
19   {   DDERR_ALREADYINITIALIZED,           "DDERR_ALREADYINITIALIZED"},
20   {   DDERR_CANNOTATTACHSURFACE,          "DDERR_CANNOTATTACHSURFACE"},
21   {   DDERR_CANNOTDETACHSURFACE,          "DDERR_CANNOTDETACHSURFACE"},
22   {   DDERR_CURRENTLYNOTAVAIL,            "DDERR_CURRENTLYNOTAVAIL"},
23   {   DDERR_EXCEPTION,                    "DDERR_EXCEPTION"},
24   {   DDERR_GENERIC,                      "DDERR_GENERIC"},
25   {   DDERR_HEIGHTALIGN,                  "DDERR_HEIGHTALIGN"},
26   {   DDERR_INCOMPATIBLEPRIMARY,          "DDERR_INCOMPATIBLEPRIMARY"},
27   {   DDERR_INVALIDCAPS,                  "DDERR_INVALIDCAPS"},
28   {   DDERR_INVALIDCLIPLIST,              "DDERR_INVALIDCLIPLIST"},
29   {   DDERR_INVALIDMODE,                  "DDERR_INVALIDMODE"},
30   {   DDERR_INVALIDOBJECT,                "DDERR_INVALIDOBJECT"},
31   {   DDERR_INVALIDPARAMS,                "DDERR_INVALIDPARAMS"},
32   {   DDERR_INVALIDPIXELFORMAT,           "DDERR_INVALIDPIXELFORMAT"},
33   {   DDERR_INVALIDRECT,                  "DDERR_INVALIDRECT"},
34   {   DDERR_LOCKEDSURFACES,               "DDERR_LOCKEDSURFACES"},
35   {   DDERR_NO3D,                         "DDERR_NO3D"},
36   {   DDERR_NOALPHAHW,                    "DDERR_NOALPHAHW"},
37   {   DDERR_NOCLIPLIST,                   "DDERR_NOCLIPLIST"},
38   {   DDERR_NOCOLORCONVHW,                "DDERR_NOCOLORCONVHW"},
39   {   DDERR_NOCOOPERATIVELEVELSET,        "DDERR_NOCOOPERATIVELEVELSET"},
40   {   DDERR_NOCOLORKEY,                   "DDERR_NOCOLORKEY"},
41   {   DDERR_NOCOLORKEYHW,                 "DDERR_NOCOLORKEYHW"},
42   {   DDERR_NODIRECTDRAWSUPPORT,          "DDERR_NODIRECTDRAWSUPPORT"},
43   {   DDERR_NOEXCLUSIVEMODE,              "DDERR_NOEXCLUSIVEMODE"},
44   {   DDERR_NOFLIPHW,                     "DDERR_NOFLIPHW"},
45   {   DDERR_NOGDI,                        "DDERR_NOGDI"},
46   {   DDERR_NOMIRRORHW,                   "DDERR_NOMIRRORHW"},
47   {   DDERR_NOTFOUND,                     "DDERR_NOTFOUND"},
48   {   DDERR_NOOVERLAYHW,                  "DDERR_NOOVERLAYHW"},
49   {   DDERR_NORASTEROPHW,                 "DDERR_NORASTEROPHW"},
50   {   DDERR_NOROTATIONHW,                 "DDERR_NOROTATIONHW"},
51   {   DDERR_NOSTRETCHHW,                  "DDERR_NOSTRETCHHW"},
52   {   DDERR_NOT4BITCOLOR,                 "DDERR_NOT4BITCOLOR"},
53   {   DDERR_NOT4BITCOLORINDEX,            "DDERR_NOT4BITCOLORINDEX"},
54   {   DDERR_NOT8BITCOLOR,                 "DDERR_NOT8BITCOLOR"},
55   {   DDERR_NOTEXTUREHW,                  "DDERR_NOTEXTUREHW"},
56   {   DDERR_NOVSYNCHW,                    "DDERR_NOVSYNCHW"},
57   {   DDERR_NOZBUFFERHW,                  "DDERR_NOZBUFFERHW"},
58   {   DDERR_NOZOVERLAYHW,                 "DDERR_NOZOVERLAYHW"},
59   {   DDERR_OUTOFCAPS,                    "DDERR_OUTOFCAPS"},
60   {   DDERR_OUTOFMEMORY,                  "DDERR_OUTOFMEMORY"},
61   {   DDERR_OUTOFVIDEOMEMORY,             "DDERR_OUTOFVIDEOMEMORY"},
62   {   DDERR_OVERLAYCANTCLIP,              "DDERR_OVERLAYCANTCLIP"},
63   {   DDERR_OVERLAYCOLORKEYONLYONEACTIVE, "DDERR_OVERLAYCOLORKEYONLYONEACTIVE"},
64   {   DDERR_PALETTEBUSY,                  "DDERR_PALETTEBUSY"},
65   {   DDERR_COLORKEYNOTSET,               "DDERR_COLORKEYNOTSET"},
66   {   DDERR_SURFACEALREADYATTACHED,       "DDERR_SURFACEALREADYATTACHED"},
67   {   DDERR_SURFACEALREADYDEPENDENT,      "DDERR_SURFACEALREADYDEPENDENT"},
68   {   DDERR_SURFACEBUSY,                  "DDERR_SURFACEBUSY"},
69   {   DDERR_CANTLOCKSURFACE,              "DDERR_CANTLOCKSURFACE"},
70   {   DDERR_SURFACEISOBSCURED,            "DDERR_SURFACEISOBSCURED"},
71   {   DDERR_SURFACELOST,                  "DDERR_SURFACELOST"},
72   {   DDERR_SURFACENOTATTACHED,           "DDERR_SURFACENOTATTACHED"},
73   {   DDERR_TOOBIGHEIGHT,                 "DDERR_TOOBIGHEIGHT"},
74   {   DDERR_TOOBIGSIZE,                   "DDERR_TOOBIGSIZE"},
75   {   DDERR_TOOBIGWIDTH,                  "DDERR_TOOBIGWIDTH"},
76   {   DDERR_UNSUPPORTED,                  "DDERR_UNSUPPORTED"},
77   {   DDERR_UNSUPPORTEDFORMAT,            "DDERR_UNSUPPORTEDFORMAT"},
78   {   DDERR_UNSUPPORTEDMASK,              "DDERR_UNSUPPORTEDMASK"},
79   {   DDERR_VERTICALBLANKINPROGRESS,      "DDERR_VERTICALBLANKINPROGRESS"},
80   {   DDERR_WASSTILLDRAWING,              "DDERR_WASSTILLDRAWING"},
81   {   DDERR_XALIGN,                       "DDERR_XALIGN"},
82   {   DDERR_INVALIDDIRECTDRAWGUID,        "DDERR_INVALIDDIRECTDRAWGUID"},
83   {   DDERR_DIRECTDRAWALREADYCREATED,     "DDERR_DIRECTDRAWALREADYCREATED"},
84   {   DDERR_NODIRECTDRAWHW,               "DDERR_NODIRECTDRAWHW"},
85   {   DDERR_PRIMARYSURFACEALREADYEXISTS,  "DDERR_PRIMARYSURFACEALREADYEXISTS"},
86   {   DDERR_NOEMULATION,                  "DDERR_NOEMULATION"},
87   {   DDERR_REGIONTOOSMALL,               "DDERR_REGIONTOOSMALL"},
88   {   DDERR_CLIPPERISUSINGHWND,           "DDERR_CLIPPERISUSINGHWND"},
89   {   DDERR_NOCLIPPERATTACHED,            "DDERR_NOCLIPPERATTACHED"},
90   {   DDERR_NOHWND,                       "DDERR_NOHWND"},
91   {   DDERR_HWNDSUBCLASSED,               "DDERR_HWNDSUBCLASSED"},
92   {   DDERR_HWNDALREADYSET,               "DDERR_HWNDALREADYSET"},
93   {   DDERR_NOPALETTEATTACHED,            "DDERR_NOPALETTEATTACHED"},
94   {   DDERR_NOPALETTEHW,                  "DDERR_NOPALETTEHW"},
95   {   DDERR_BLTFASTCANTCLIP,              "DDERR_BLTFASTCANTCLIP"},
96   {   DDERR_NOBLTHW,                      "DDERR_NOBLTHW"},
97   {   DDERR_NODDROPSHW,                   "DDERR_NODDROPSHW"},
98   {   DDERR_OVERLAYNOTVISIBLE,            "DDERR_OVERLAYNOTVISIBLE"},
99   {   DDERR_NOOVERLAYDEST,                "DDERR_NOOVERLAYDEST"},
100   {   DDERR_INVALIDPOSITION,              "DDERR_INVALIDPOSITION"},
101   {   DDERR_NOTAOVERLAYSURFACE,           "DDERR_NOTAOVERLAYSURFACE"},
102   {   DDERR_EXCLUSIVEMODEALREADYSET,      "DDERR_EXCLUSIVEMODEALREADYSET"},
103   {   DDERR_NOTFLIPPABLE,                 "DDERR_NOTFLIPPABLE"},
104   {   DDERR_CANTDUPLICATE,                "DDERR_CANTDUPLICATE"},
105   {   DDERR_NOTLOCKED,                    "DDERR_NOTLOCKED"},
106   {   DDERR_CANTCREATEDC,                 "DDERR_CANTCREATEDC"},
107   {   DDERR_NODC,                         "DDERR_NODC"},
108   {   DDERR_WRONGMODE,                    "DDERR_WRONGMODE"},
109   {   DDERR_IMPLICITLYCREATED,            "DDERR_IMPLICITLYCREATED"},
110   {   DDERR_NOTPALETTIZED,                "DDERR_NOTPALETTIZED"},
111   {   DDERR_UNSUPPORTEDMODE,              "DDERR_UNSUPPORTEDMODE"},
112   {   DDERR_NOMIPMAPHW,                   "DDERR_NOMIPMAPHW"},
113   {   DDERR_INVALIDSURFACETYPE,           "DDERR_INVALIDSURFACETYPE"},
114
115   {   DDERR_NOOPTIMIZEHW,                 "DDERR_NOOPTIMIZEHW"},
116   {   DDERR_NOTLOADED,                    "DDERR_NOTLOADED"},
117
118   {   DDERR_DCALREADYCREATED,             "DDERR_DCALREADYCREATED"},
119
120   {   DDERR_NONONLOCALVIDMEM,             "DDERR_NONONLOCALVIDMEM"},
121   {   DDERR_CANTPAGELOCK,                 "DDERR_CANTPAGELOCK"},
122   {   DDERR_CANTPAGEUNLOCK,               "DDERR_CANTPAGEUNLOCK"},
123   {   DDERR_NOTPAGELOCKED,                "DDERR_NOTPAGELOCKED"},
124
125   {   DDERR_MOREDATA,                     "DDERR_MOREDATA"},
126   {   DDERR_VIDEONOTACTIVE,               "DDERR_VIDEONOTACTIVE"},
127   {   DDERR_DEVICEDOESNTOWNSURFACE,       "DDERR_DEVICEDOESNTOWNSURFACE"},
128   {   DDERR_NOTINITIALIZED,               "DDERR_NOTINITIALIZED"},
129
130   {   DIERR_OLDDIRECTINPUTVERSION,        "DIERR_OLDDIRECTINPUTVERSION" },
131   {   DIERR_BETADIRECTINPUTVERSION,       "DIERR_BETADIRECTINPUTVERSION" },
132   {   DIERR_BADDRIVERVER,                 "DIERR_BADDRIVERVER" },
133   {   DIERR_DEVICENOTREG,                 "DIERR_DEVICENOTREG" },
134   {   DIERR_NOTFOUND,                     "DIERR_NOTFOUND" },
135   {   DIERR_OBJECTNOTFOUND,               "DIERR_OBJECTNOTFOUND" },
136   {   DIERR_INVALIDPARAM,                 "DIERR_INVALIDPARAM" },
137   {   DIERR_NOINTERFACE,                  "DIERR_NOINTERFACE" },
138   {   DIERR_GENERIC,                      "DIERR_GENERIC" },
139   {   DIERR_OUTOFMEMORY,                  "DIERR_OUTOFMEMORY" },
140   {   DIERR_UNSUPPORTED,                  "DIERR_UNSUPPORTED" },
141   {   DIERR_NOTINITIALIZED,               "DIERR_NOTINITIALIZED" },
142   {   DIERR_ALREADYINITIALIZED,           "DIERR_ALREADYINITIALIZED" },
143   {   DIERR_NOAGGREGATION,                "DIERR_NOAGGREGATION" },
144   {   DIERR_OTHERAPPHASPRIO,              "DIERR_OTHERAPPHASPRIO" },
145   {   DIERR_INPUTLOST,                    "DIERR_INPUTLOST" },
146   {   DIERR_ACQUIRED,                     "DIERR_ACQUIRED" },
147   {   DIERR_NOTACQUIRED,                  "DIERR_NOTACQUIRED" },
148   {   DIERR_READONLY,                     "DIERR_READONLY" },
149   {   DIERR_HANDLEEXISTS,                 "DIERR_HANDLEEXISTS" },
150   {   E_PENDING,                          "E_PENDING" },
151   {   DIERR_INSUFFICIENTPRIVS,            "DIERR_INSUFFICIENTPRIVS" },
152   {   DIERR_DEVICEFULL,                   "DIERR_DEVICEFULL" },
153   {   DIERR_MOREDATA,                     "DIERR_MOREDATA" },
154   {   DIERR_NOTDOWNLOADED,                "DIERR_NOTDOWNLOADED" },
155   {   DIERR_HASEFFECTS,                   "DIERR_HASEFFECTS" },
156   {   DIERR_NOTEXCLUSIVEACQUIRED,         "DIERR_NOTEXCLUSIVEACQUIRED" },
157   {   DIERR_INCOMPLETEEFFECT,             "DIERR_INCOMPLETEEFFECT" },
158   {   DIERR_NOTBUFFERED,                  "DIERR_NOTBUFFERED" },
159   {   DIERR_EFFECTPLAYING,                "DIERR_EFFECTPLAYING" },
160//   {   DIERR_UNPLUGGED,                    "DIERR_UNPLUGGED" },
161
162   {   E_NOINTERFACE,                      "E_NOINTERFACE" },
163
164};
165
166/***************************************************************/
167
168/*
169   DirectXDecodeError:  Return a string description of the given DirectX
170   error code.
171*/
172
173const char * DirectXDecodeError(HRESULT errorval)
174{
175   int i;
176   static char tmp[64];
177   
178   for (i = 0; i < (sizeof(g_ErrorCode) / sizeof(g_ErrorCode[0])); i++)
179   {
180      if (g_ErrorCode[i].hr == errorval)
181      {
182         return g_ErrorCode[i].szError;
183      }
184   }
185   sprintf(tmp, "UNKNOWN: 0x%x", (unsigned int)errorval);
186   return tmp;
187}
src/osd/windows/ui/audit32.h
r995r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11 ***************************************************************************/
12
13#ifndef AUDIT32_H
14#define AUDIT32_H
15
16void AuditDialog(HWND hParent);
17
18// For property sheet Game Audit tab
19void InitGameAudit(int gameIndex);
20INT_PTR CALLBACK GameAuditDialogProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam);
21
22int Mame32VerifyRomSet(int game);
23int Mame32VerifySampleSet(int game);
24
25const char * GetAuditString(int audit_result);
26BOOL IsAuditResultKnown(int audit_result);
27BOOL IsAuditResultYes(int audit_result);
28BOOL IsAuditResultNo(int audit_result);
29
30#endif
src/osd/windows/ui/dialogs.c
r995r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11***************************************************************************/
12
13/***************************************************************************
14
15  dialogs.c
16
17  Dialog box procedures go here
18
19***************************************************************************/
20
21#define WIN32_LEAN_AND_MEAN
22
23#ifdef _MSC_VER
24#ifndef NONAMELESSUNION
25#define NONAMELESSUNION
26#endif
27#endif
28
29#include <windows.h>
30#include <windowsx.h>
31#include <shellapi.h>
32#include <commctrl.h>
33#include <commdlg.h>
34#include <string.h>
35#include <tchar.h>
36
37#include "bitmask.h"
38#include "TreeView.h"
39#include "M32Util.h"
40#include "resource.h"
41#include "directories.h"
42#include "m32opts.h"
43#include "splitters.h"
44#include "help.h"
45#include "audit32.h"
46#include "screenshot.h"
47#include "mame32.h"
48#include "properties.h"
49#include "dialogs.h"
50#include "strconv.h"
51#include "winutf8.h"
52
53#ifdef _MSC_VER
54#define snprintf _snprintf
55#endif
56
57#define FILTERTEXT_LEN 256
58
59static char g_FilterText[FILTERTEXT_LEN];
60
61#define NUM_EXCLUSIONS  9
62
63/* Pairs of filters that exclude each other */
64DWORD filterExclusion[NUM_EXCLUSIONS] =
65{
66   IDC_FILTER_CLONES,      IDC_FILTER_ORIGINALS,
67   IDC_FILTER_NONWORKING,  IDC_FILTER_WORKING,
68   IDC_FILTER_UNAVAILABLE, IDC_FILTER_AVAILABLE,
69   IDC_FILTER_RASTER,      IDC_FILTER_VECTOR
70};
71
72static void DisableFilterControls(HWND hWnd, LPFOLDERDATA lpFilterRecord,
73                          LPFILTER_ITEM lpFilterItem, DWORD dwFlags);
74static void EnableFilterExclusions(HWND hWnd, DWORD dwCtrlID);
75static DWORD ValidateFilters(LPFOLDERDATA lpFilterRecord, DWORD dwFlags);
76static void OnHScroll(HWND hWnd, HWND hwndCtl, UINT code, int pos);
77
78/***************************************************************************/
79
80const char * GetFilterText(void)
81{
82   return g_FilterText;
83}
84
85INT_PTR CALLBACK ResetDialogProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam)
86{
87   BOOL resetFilters  = FALSE;
88   BOOL resetGames    = FALSE;
89   BOOL resetUI      = FALSE;
90   BOOL resetDefaults = FALSE;
91
92   switch (Msg)
93   {
94   case WM_INITDIALOG:
95      return TRUE;
96
97   case WM_HELP:
98      /* User clicked the ? from the upper right on a control */
99      HelpFunction(((LPHELPINFO)lParam)->hItemHandle, MAME32CONTEXTHELP, HH_TP_HELP_WM_HELP, GetHelpIDs());
100      break;
101
102   case WM_CONTEXTMENU:
103      HelpFunction((HWND)wParam, MAME32CONTEXTHELP, HH_TP_HELP_CONTEXTMENU, GetHelpIDs());
104
105      break;
106
107   case WM_COMMAND :
108      switch (GET_WM_COMMAND_ID(wParam, lParam))
109      {
110      case IDOK :
111         resetFilters  = Button_GetCheck(GetDlgItem(hDlg, IDC_RESET_FILTERS));
112         resetGames     = Button_GetCheck(GetDlgItem(hDlg, IDC_RESET_GAMES));
113         resetDefaults = Button_GetCheck(GetDlgItem(hDlg, IDC_RESET_DEFAULT));
114         resetUI      = Button_GetCheck(GetDlgItem(hDlg, IDC_RESET_UI));
115         if (resetFilters || resetGames || resetUI || resetDefaults)
116         {
117            TCHAR temp[200];
118            _tcscpy(temp, TEXT(MAME32NAME));
119            _tcscat(temp, TEXT(" will now reset the selected\n"));
120            _tcscat(temp, TEXT("items to the original, installation\n"));
121            _tcscat(temp, TEXT("settings then exit.\n\n"));
122            _tcscat(temp, TEXT("The new settings will take effect\n"));
123            _tcscat(temp, TEXT("the next time "));
124            _tcscat(temp, TEXT(MAME32NAME));
125            _tcscat(temp, TEXT(" is run.\n\n"));
126            _tcscat(temp, TEXT("Do you wish to continue?"));
127            if (MessageBox(hDlg, temp, TEXT("Restore Settings"), IDOK) == IDOK)
128            {
129               if (resetFilters)
130                  ResetFilters();
131
132               if (resetUI)
133                  ResetGUI();
134
135               if (resetDefaults)
136                  ResetGameDefaults();
137
138               if (resetGames)
139                  ResetAllGameOptions();
140
141               EndDialog(hDlg, 1);
142               return TRUE;
143            }
144         }
145         /* Fall through if no options were selected
146          * or the user hit cancel in the popup dialog.
147          */
148      case IDCANCEL :
149         EndDialog(hDlg, 0);
150         return TRUE;
151      }
152      break;
153   }
154   return 0;
155}
156
157INT_PTR CALLBACK InterfaceDialogProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam)
158{
159   CHOOSECOLOR cc;
160   COLORREF choice_colors[16];
161   TCHAR tmp[4];
162   int i;
163   BOOL bRedrawList = FALSE;
164   int nCurSelection = 0;
165   int nHistoryTab = 0;
166   int nCount = 0;
167   int value;
168
169   switch (Msg)
170   {
171   case WM_INITDIALOG:
172      Button_SetCheck(GetDlgItem(hDlg,IDC_START_GAME_CHECK),GetGameCheck());
173      Button_SetCheck(GetDlgItem(hDlg,IDC_JOY_GUI),GetJoyGUI());
174      Button_SetCheck(GetDlgItem(hDlg,IDC_KEY_GUI),GetKeyGUI());
175      Button_SetCheck(GetDlgItem(hDlg,IDC_BROADCAST),GetBroadcast());
176      Button_SetCheck(GetDlgItem(hDlg,IDC_RANDOM_BG),GetRandomBackground());
177      Button_SetCheck(GetDlgItem(hDlg,IDC_GAME_CAPTION),GetGameCaption());
178     
179      Button_SetCheck(GetDlgItem(hDlg,IDC_HIDE_MOUSE),GetHideMouseOnStartup());
180
181      // Get the current value of the control
182      SendDlgItemMessage(hDlg, IDC_CYCLETIMESEC, TBM_SETRANGE,
183               (WPARAM)FALSE,
184               (LPARAM)MAKELONG(0, 60)); /* [0, 60] */
185      value = GetCycleScreenshot();
186      SendDlgItemMessage(hDlg,IDC_CYCLETIMESEC, TBM_SETPOS, TRUE, value);
187      _itot(value,tmp,10);
188      SendDlgItemMessage(hDlg,IDC_CYCLETIMESECTXT,WM_SETTEXT,0, (WPARAM)tmp);
189
190      Button_SetCheck(GetDlgItem(hDlg,IDC_STRETCH_SCREENSHOT_LARGER),
191                  GetStretchScreenShotLarger());
192      Button_SetCheck(GetDlgItem(hDlg,IDC_FILTER_INHERIT),
193                  GetFilterInherit());
194      Button_SetCheck(GetDlgItem(hDlg,IDC_NOOFFSET_CLONES),
195                  GetOffsetClones());
196      (void)ComboBox_AddString(GetDlgItem(hDlg, IDC_HISTORY_TAB), TEXT("Snapshot"));
197      (void)ComboBox_SetItemData(GetDlgItem(hDlg, IDC_HISTORY_TAB), nCount++, TAB_SCREENSHOT);
198      (void)ComboBox_AddString(GetDlgItem(hDlg, IDC_HISTORY_TAB), TEXT("Flyer"));
199      (void)ComboBox_SetItemData(GetDlgItem(hDlg, IDC_HISTORY_TAB), nCount++, TAB_FLYER);
200      (void)ComboBox_AddString(GetDlgItem(hDlg, IDC_HISTORY_TAB), TEXT("Cabinet"));
201      (void)ComboBox_SetItemData(GetDlgItem(hDlg, IDC_HISTORY_TAB), nCount++, TAB_CABINET);
202      (void)ComboBox_AddString(GetDlgItem(hDlg, IDC_HISTORY_TAB), TEXT("Marquee"));
203      (void)ComboBox_SetItemData(GetDlgItem(hDlg, IDC_HISTORY_TAB), nCount++, TAB_MARQUEE);
204      (void)ComboBox_AddString(GetDlgItem(hDlg, IDC_HISTORY_TAB), TEXT("Title"));
205      (void)ComboBox_SetItemData(GetDlgItem(hDlg, IDC_HISTORY_TAB), nCount++, TAB_TITLE);
206      (void)ComboBox_AddString(GetDlgItem(hDlg, IDC_HISTORY_TAB), TEXT("Control Panel"));
207      (void)ComboBox_SetItemData(GetDlgItem(hDlg, IDC_HISTORY_TAB), nCount++, TAB_CONTROL_PANEL);
208      (void)ComboBox_AddString(GetDlgItem(hDlg, IDC_HISTORY_TAB), TEXT("All"));
209      (void)ComboBox_SetItemData(GetDlgItem(hDlg, IDC_HISTORY_TAB), nCount++, TAB_ALL);
210      (void)ComboBox_AddString(GetDlgItem(hDlg, IDC_HISTORY_TAB), TEXT("None"));
211      (void)ComboBox_SetItemData(GetDlgItem(hDlg, IDC_HISTORY_TAB), nCount++, TAB_NONE);
212      if( GetHistoryTab() < MAX_TAB_TYPES )
213         (void)ComboBox_SetCurSel(GetDlgItem(hDlg, IDC_HISTORY_TAB), GetHistoryTab());
214      else
215         (void)ComboBox_SetCurSel(GetDlgItem(hDlg, IDC_HISTORY_TAB), GetHistoryTab()-TAB_SUBTRACT);
216
217      SendDlgItemMessage(hDlg, IDC_SCREENSHOT_BORDERSIZE, TBM_SETRANGE,
218               (WPARAM)FALSE,
219               (LPARAM)MAKELONG(0, 100)); /* [0, 100] */
220      value = GetScreenshotBorderSize();
221      SendDlgItemMessage(hDlg,IDC_SCREENSHOT_BORDERSIZE, TBM_SETPOS, TRUE, value);
222      _itot(value,tmp,10);
223      SendDlgItemMessage(hDlg,IDC_SCREENSHOT_BORDERSIZETXT,WM_SETTEXT,0, (WPARAM)tmp);
224
225      //return TRUE;
226      break;
227
228   case WM_HELP:
229      /* User clicked the ? from the upper right on a control */
230      HelpFunction(((LPHELPINFO)lParam)->hItemHandle, MAME32CONTEXTHELP, HH_TP_HELP_WM_HELP, GetHelpIDs());
231      break;
232
233   case WM_CONTEXTMENU:
234      HelpFunction((HWND)wParam, MAME32CONTEXTHELP, HH_TP_HELP_CONTEXTMENU, GetHelpIDs());
235      break;
236   case WM_HSCROLL:
237      HANDLE_WM_HSCROLL(hDlg, wParam, lParam, OnHScroll);
238      break;
239   case WM_COMMAND :
240      switch (GET_WM_COMMAND_ID(wParam, lParam))
241      {
242      case IDC_SCREENSHOT_BORDERCOLOR:
243      {
244         for (i=0;i<16;i++)
245             choice_colors[i] = GetCustomColor(i);
246
247         cc.lStructSize = sizeof(CHOOSECOLOR);
248         cc.hwndOwner   = hDlg;
249         cc.rgbResult   = GetScreenshotBorderColor();
250         cc.lpCustColors = choice_colors;
251         cc.Flags       = CC_ANYCOLOR | CC_RGBINIT | CC_SOLIDCOLOR;
252         if (!ChooseColor(&cc))
253            return TRUE;
254          for (i=0;i<16;i++)
255             SetCustomColor(i,choice_colors[i]);
256         SetScreenshotBorderColor(cc.rgbResult);
257         UpdateScreenShot();
258         return TRUE;
259      }
260      case IDOK :
261      {
262         BOOL checked = FALSE;
263
264         SetGameCheck(Button_GetCheck(GetDlgItem(hDlg, IDC_START_GAME_CHECK)));
265         SetJoyGUI(Button_GetCheck(GetDlgItem(hDlg, IDC_JOY_GUI)));
266         SetKeyGUI(Button_GetCheck(GetDlgItem(hDlg, IDC_KEY_GUI)));
267         SetBroadcast(Button_GetCheck(GetDlgItem(hDlg, IDC_BROADCAST)));
268         SetRandomBackground(Button_GetCheck(GetDlgItem(hDlg, IDC_RANDOM_BG)));
269         SetGameCaption(Button_GetCheck(GetDlgItem(hDlg, IDC_GAME_CAPTION)));
270         
271         SetHideMouseOnStartup(Button_GetCheck(GetDlgItem(hDlg,IDC_HIDE_MOUSE)));
272
273         if( Button_GetCheck(GetDlgItem(hDlg,IDC_RESET_PLAYCOUNT ) ) )
274         {
275            ResetPlayCount( -1 );
276            bRedrawList = TRUE;
277         }
278         if( Button_GetCheck(GetDlgItem(hDlg,IDC_RESET_PLAYTIME ) ) )
279         {
280            ResetPlayTime( -1 );
281            bRedrawList = TRUE;
282         }
283         value = SendDlgItemMessage(hDlg,IDC_CYCLETIMESEC, TBM_GETPOS, 0, 0);
284         if( GetCycleScreenshot() != value )
285         {
286            SetCycleScreenshot(value);
287         }
288         value = SendDlgItemMessage(hDlg,IDC_SCREENSHOT_BORDERSIZE, TBM_GETPOS, 0, 0);
289         if( GetScreenshotBorderSize() != value )
290         {
291            SetScreenshotBorderSize(value);
292            UpdateScreenShot();
293         }
294         value = SendDlgItemMessage(hDlg,IDC_HIGH_PRIORITY, TBM_GETPOS, 0, 0);
295         checked = Button_GetCheck(GetDlgItem(hDlg,IDC_STRETCH_SCREENSHOT_LARGER));
296         if (checked != GetStretchScreenShotLarger())
297         {
298            SetStretchScreenShotLarger(checked);
299            UpdateScreenShot();
300         }
301         checked = Button_GetCheck(GetDlgItem(hDlg,IDC_FILTER_INHERIT));
302         if (checked != GetFilterInherit())
303         {
304            SetFilterInherit(checked);
305            // LineUpIcons does just a ResetListView(), which is what we want here
306            PostMessage(GetMainWindow(),WM_COMMAND, MAKEWPARAM(ID_VIEW_LINEUPICONS, FALSE),(LPARAM)NULL);
307          }
308         checked = Button_GetCheck(GetDlgItem(hDlg,IDC_NOOFFSET_CLONES));
309         if (checked != GetOffsetClones())
310         {
311            SetOffsetClones(checked);
312            // LineUpIcons does just a ResetListView(), which is what we want here
313            PostMessage(GetMainWindow(),WM_COMMAND, MAKEWPARAM(ID_VIEW_LINEUPICONS, FALSE),(LPARAM)NULL);
314          }
315         nCurSelection = ComboBox_GetCurSel(GetDlgItem(hDlg,IDC_HISTORY_TAB));
316         if (nCurSelection != CB_ERR)
317            nHistoryTab = ComboBox_GetItemData(GetDlgItem(hDlg,IDC_HISTORY_TAB), nCurSelection);
318         EndDialog(hDlg, 0);
319         if( GetHistoryTab() != nHistoryTab )
320         {
321            SetHistoryTab(nHistoryTab, TRUE);
322            ResizePickerControls(GetMainWindow());
323            UpdateScreenShot();
324         }
325         if( bRedrawList )
326         {
327            UpdateListView();
328         }
329         return TRUE;
330      }
331      case IDCANCEL :
332         EndDialog(hDlg, 0);
333         return TRUE;
334      }
335      break;
336   }
337   return 0;
338}
339
340INT_PTR CALLBACK FilterDialogProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam)
341{
342   static DWORD         dwFilters;
343   static DWORD         dwpFilters;
344   static LPFOLDERDATA      lpFilterRecord;
345   char                strText[250];
346   int                i;
347
348   switch (Msg)
349   {
350   case WM_INITDIALOG:
351   {
352      LPTREEFOLDER folder = GetCurrentFolder();
353      LPTREEFOLDER lpParent = NULL;
354      LPFILTER_ITEM g_lpFilterList = GetFilterList();
355
356      dwFilters = 0;
357
358      if (folder != NULL)
359      {
360         char tmp[80];
361         
362         win_set_window_text_utf8(GetDlgItem(hDlg, IDC_FILTER_EDIT), g_FilterText);
363         Edit_SetSel(GetDlgItem(hDlg, IDC_FILTER_EDIT), 0, -1);
364         // Mask out non filter flags
365         dwFilters = folder->m_dwFlags & F_MASK;
366         // Display current folder name in dialog titlebar
367         snprintf(tmp,ARRAY_LENGTH(tmp),"Filters for %s Folder",folder->m_lpTitle);
368         win_set_window_text_utf8(hDlg, tmp);
369         if ( GetFilterInherit() )
370         {
371            if( folder )
372            {
373               BOOL bShowExplanation = FALSE;
374               lpParent = GetFolder( folder->m_nParent );
375               if( lpParent )
376               {
377                  /* Check the Parent Filters and inherit them on child,
378                   * No need to promote all games to parent folder, works as is */
379                  dwpFilters = lpParent->m_dwFlags & F_MASK;
380                  /*Check all possible Filters if inherited solely from parent, e.g. not being set explicitly on our folder*/
381                  if( (dwpFilters & F_CLONES) && !(dwFilters & F_CLONES) )
382                  {
383                     /*Add a Specifier to the Checkbox to show it was inherited from the parent*/
384                     win_get_window_text_utf8(GetDlgItem(hDlg, IDC_FILTER_CLONES), strText, 250);
385                     strcat(strText, " (*)");
386                     win_set_window_text_utf8(GetDlgItem(hDlg, IDC_FILTER_CLONES), strText);
387                     bShowExplanation = TRUE;
388                  }
389                  if( (dwpFilters & F_NONWORKING) && !(dwFilters & F_NONWORKING) )
390                  {
391                     /*Add a Specifier to the Checkbox to show it was inherited from the parent*/
392                     win_get_window_text_utf8(GetDlgItem(hDlg, IDC_FILTER_NONWORKING), strText, 250);
393                     strcat(strText, " (*)");
394                     win_set_window_text_utf8(GetDlgItem(hDlg, IDC_FILTER_NONWORKING), strText);
395                     bShowExplanation = TRUE;
396                  }
397                  if( (dwpFilters & F_UNAVAILABLE) && !(dwFilters & F_UNAVAILABLE) )
398                  {
399                     /*Add a Specifier to the Checkbox to show it was inherited from the parent*/
400                     win_get_window_text_utf8(GetDlgItem(hDlg, IDC_FILTER_UNAVAILABLE), strText, 250);
401                     strcat(strText, " (*)");
402                     win_set_window_text_utf8(GetDlgItem(hDlg, IDC_FILTER_UNAVAILABLE), strText);
403                     bShowExplanation = TRUE;
404                  }
405                  if( (dwpFilters & F_VECTOR) && !(dwFilters & F_VECTOR) )
406                  {
407                     /*Add a Specifier to the Checkbox to show it was inherited from the parent*/
408                     win_get_window_text_utf8(GetDlgItem(hDlg, IDC_FILTER_VECTOR), strText, 250);
409                     strcat(strText, " (*)");
410                     win_set_window_text_utf8(GetDlgItem(hDlg, IDC_FILTER_VECTOR), strText);
411                     bShowExplanation = TRUE;
412                  }
413                  if( (dwpFilters & F_RASTER) && !(dwFilters & F_RASTER) )
414                  {
415                     /*Add a Specifier to the Checkbox to show it was inherited from the parent*/
416                     win_get_window_text_utf8(GetDlgItem(hDlg, IDC_FILTER_RASTER), strText, 250);
417                     strcat(strText, " (*)");
418                     win_set_window_text_utf8(GetDlgItem(hDlg, IDC_FILTER_RASTER), strText);
419                     bShowExplanation = TRUE;
420                  }
421                  if( (dwpFilters & F_ORIGINALS) && !(dwFilters & F_ORIGINALS) )
422                  {
423                     /*Add a Specifier to the Checkbox to show it was inherited from the parent*/
424                     win_get_window_text_utf8(GetDlgItem(hDlg, IDC_FILTER_ORIGINALS), strText, 250);
425                     strcat(strText, " (*)");
426                     win_set_window_text_utf8(GetDlgItem(hDlg, IDC_FILTER_ORIGINALS), strText);
427                     bShowExplanation = TRUE;
428                  }
429                  if( (dwpFilters & F_WORKING) && !(dwFilters & F_WORKING) )
430                  {
431                     /*Add a Specifier to the Checkbox to show it was inherited from the parent*/
432                     win_get_window_text_utf8(GetDlgItem(hDlg, IDC_FILTER_WORKING), strText, 250);
433                     strcat(strText, " (*)");
434                     win_set_window_text_utf8(GetDlgItem(hDlg, IDC_FILTER_WORKING), strText);
435                     bShowExplanation = TRUE;
436                  }
437                  if( (dwpFilters & F_AVAILABLE) && !(dwFilters & F_AVAILABLE) )
438                  {
439                     /*Add a Specifier to the Checkbox to show it was inherited from the parent*/
440                     win_get_window_text_utf8(GetDlgItem(hDlg, IDC_FILTER_AVAILABLE), strText, 250);
441                     strcat(strText, " (*)");
442                     win_set_window_text_utf8(GetDlgItem(hDlg, IDC_FILTER_AVAILABLE), strText);
443                     bShowExplanation = TRUE;
444                  }
445                  /*Do not or in the Values of the parent, so that the values of the folder still can be set*/
446                  //dwFilters |= dwpFilters;
447               }
448               if( ! bShowExplanation )
449               {
450                  ShowWindow(GetDlgItem(hDlg, IDC_INHERITED), FALSE );
451               }
452            }
453         }
454         else
455         {
456            ShowWindow(GetDlgItem(hDlg, IDC_INHERITED), FALSE );
457         }
458         // Find the matching filter record if it exists
459         lpFilterRecord = FindFilter(folder->m_nFolderId);
460
461         // initialize and disable appropriate controls
462         for (i = 0; g_lpFilterList[i].m_dwFilterType; i++)
463         {
464            DisableFilterControls(hDlg, lpFilterRecord, &g_lpFilterList[i], dwFilters);
465         }
466      }
467      SetFocus(GetDlgItem(hDlg, IDC_FILTER_EDIT));
468      return FALSE;
469   }
470   case WM_HELP:
471      // User clicked the ? from the upper right on a control
472      HelpFunction(((LPHELPINFO)lParam)->hItemHandle, MAME32CONTEXTHELP,
473                HH_TP_HELP_WM_HELP, GetHelpIDs());
474      break;
475
476   case WM_CONTEXTMENU:
477      HelpFunction((HWND)wParam, MAME32CONTEXTHELP, HH_TP_HELP_CONTEXTMENU, GetHelpIDs());
478      break;
479
480   case WM_COMMAND:
481   {
482      WORD wID       = GET_WM_COMMAND_ID(wParam, lParam);
483      WORD wNotifyCode = GET_WM_COMMAND_CMD(wParam, lParam);
484      LPTREEFOLDER folder = GetCurrentFolder();
485      LPFILTER_ITEM g_lpFilterList = GetFilterList();
486
487      switch (wID)
488      {
489      case IDOK:
490         dwFilters = 0;
491         
492         win_get_window_text_utf8(GetDlgItem(hDlg, IDC_FILTER_EDIT), g_FilterText, FILTERTEXT_LEN);
493         
494         // see which buttons are checked
495         for (i = 0; g_lpFilterList[i].m_dwFilterType; i++)
496         {
497            if (Button_GetCheck(GetDlgItem(hDlg, g_lpFilterList[i].m_dwCtrlID)))
498               dwFilters |= g_lpFilterList[i].m_dwFilterType;
499         }
500
501         // Mask out invalid filters
502         dwFilters = ValidateFilters(lpFilterRecord, dwFilters);
503
504         // Keep non filter flags
505         folder->m_dwFlags &= ~F_MASK;
506
507         // put in the set filters
508         folder->m_dwFlags |= dwFilters;
509
510         EndDialog(hDlg, 1);
511         return TRUE;
512
513      case IDCANCEL:
514         EndDialog(hDlg, 0);
515         return TRUE;
516         
517      default:
518         // Handle unchecking mutually exclusive filters
519         if (wNotifyCode == BN_CLICKED)
520            EnableFilterExclusions(hDlg, wID);
521      }
522   }
523   break;
524   }
525   return 0;
526}
527
528INT_PTR CALLBACK AboutDialogProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam)
529{
530   switch (Msg)
531   {
532   case WM_INITDIALOG:
533      {
534         HBITMAP hBmp;
535         hBmp = (HBITMAP)LoadImage(GetModuleHandle(NULL),
536                             MAKEINTRESOURCE(IDB_ABOUT),
537                             IMAGE_BITMAP, 0, 0, LR_SHARED);
538         SendDlgItemMessage(hDlg, IDC_ABOUT, STM_SETIMAGE,
539                  (WPARAM)IMAGE_BITMAP, (LPARAM)hBmp);
540         win_set_window_text_utf8(GetDlgItem(hDlg, IDC_VERSION), GetVersionString());
541      }
542      return 1;
543
544   case WM_COMMAND:
545      EndDialog(hDlg, 0);
546      return 1;
547   }
548   return 0;
549}
550
551INT_PTR CALLBACK AddCustomFileDialogProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam)
552{
553    static LPTREEFOLDER default_selection = NULL;
554   static int driver_index;
555
556   switch (Msg)
557   {
558   case WM_INITDIALOG:
559   {
560       TREEFOLDER **folders;
561      int num_folders;
562      int i;
563      TVINSERTSTRUCT tvis;
564      TVITEM tvi;
565      BOOL first_entry = TRUE;
566      HIMAGELIST treeview_icons = GetTreeViewIconList();
567
568      // current game passed in using DialogBoxParam()
569      driver_index = lParam;
570
571      (void)TreeView_SetImageList(GetDlgItem(hDlg,IDC_CUSTOM_TREE), treeview_icons, LVSIL_NORMAL);
572
573      GetFolders(&folders,&num_folders);
574
575      // should add "New..."
576
577      // insert custom folders into our tree view
578      for (i=0;i<num_folders;i++)
579      {
580          if (folders[i]->m_dwFlags & F_CUSTOM)
581         {
582             HTREEITEM hti;
583            int jj;
584
585            if (folders[i]->m_nParent == -1)
586            {
587               memset(&tvi, '\0', sizeof(tvi));
588                tvis.hParent = TVI_ROOT;
589               tvis.hInsertAfter = TVI_SORT;
590               tvi.mask = TVIF_TEXT | TVIF_PARAM | TVIF_IMAGE | TVIF_SELECTEDIMAGE;
591               tvi.pszText = folders[i]->m_lptTitle;
592               tvi.lParam = (LPARAM)folders[i];
593               tvi.iImage = GetTreeViewIconIndex(folders[i]->m_nIconId);
594               tvi.iSelectedImage = 0;
595#if defined(__GNUC__) /* bug in commctrl.h */
596               tvis.item = tvi;
597#else
598               tvis.DUMMYUNIONNAME.item = tvi;
599#endif
600               
601               hti = TreeView_InsertItem(GetDlgItem(hDlg,IDC_CUSTOM_TREE),&tvis);
602
603               /* look for children of this custom folder */
604               for (jj=0;jj<num_folders;jj++)
605               {
606                   if (folders[jj]->m_nParent == i)
607                  {
608                      HTREEITEM hti_child;
609                      tvis.hParent = hti;
610                     tvis.hInsertAfter = TVI_SORT;
611                     tvi.mask = TVIF_TEXT | TVIF_PARAM | TVIF_IMAGE | TVIF_SELECTEDIMAGE;
612                     tvi.pszText = folders[jj]->m_lptTitle;
613                     tvi.lParam = (LPARAM)folders[jj];
614                     tvi.iImage = GetTreeViewIconIndex(folders[jj]->m_nIconId);
615                     tvi.iSelectedImage = 0;
616#if defined(__GNUC__) /* bug in commctrl.h */
617                       tvis.item = tvi;
618#else
619                       tvis.DUMMYUNIONNAME.item = tvi;
620#endif                     
621                     hti_child = TreeView_InsertItem(GetDlgItem(hDlg,IDC_CUSTOM_TREE),&tvis);
622                     if (folders[jj] == default_selection)
623                         TreeView_SelectItem(GetDlgItem(hDlg,IDC_CUSTOM_TREE),hti_child);
624                  }
625               }
626
627               /*TreeView_Expand(GetDlgItem(hDlg,IDC_CUSTOM_TREE),hti,TVE_EXPAND);*/
628               if (first_entry || folders[i] == default_selection)
629               {
630                   TreeView_SelectItem(GetDlgItem(hDlg,IDC_CUSTOM_TREE),hti);
631                  first_entry = FALSE;
632               }
633
634            }
635           
636         }
637      }
638     
639      win_set_window_text_utf8(GetDlgItem(hDlg,IDC_CUSTOMFILE_GAME),
640                 ModifyThe(drivers[driver_index]->description));
641
642      return TRUE;
643   }
644   case WM_COMMAND:
645      switch (GET_WM_COMMAND_ID(wParam, lParam))
646      {
647      case IDOK:
648      {
649         TVITEM tvi;
650         tvi.hItem = TreeView_GetSelection(GetDlgItem(hDlg,IDC_CUSTOM_TREE));
651         tvi.mask = TVIF_PARAM;
652         if (TreeView_GetItem(GetDlgItem(hDlg,IDC_CUSTOM_TREE),&tvi) == TRUE)
653         {
654           /* should look for New... */
655         
656           default_selection = (LPTREEFOLDER)tvi.lParam; /* start here next time */
657
658           AddToCustomFolder((LPTREEFOLDER)tvi.lParam,driver_index);
659         }
660
661         EndDialog(hDlg, 0);
662         return TRUE;
663
664         break;
665      }
666      case IDCANCEL:
667         EndDialog(hDlg, 0);
668         return TRUE;
669
670      }
671      break;
672   }
673   return 0;
674}
675
676INT_PTR CALLBACK DirectXDialogProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam)
677{
678   HWND hEdit;
679
680   const char *directx_help =
681      MAME32NAME " requires DirectX version 3 or later, which is a set of operating\r\n"
682      "system extensions by Microsoft for Windows 9x, NT and 2000.\r\n\r\n"
683      "Visit Microsoft's DirectX web page at http://www.microsoft.com/directx\r\n"
684      "download DirectX, install it, and then run " MAME32NAME " again.\r\n";
685
686   switch (Msg)
687   {
688   case WM_INITDIALOG:
689      hEdit = GetDlgItem(hDlg, IDC_DIRECTX_HELP);
690      Edit_SetSel(hEdit, Edit_GetTextLength(hEdit), Edit_GetTextLength(hEdit));
691      Edit_ReplaceSel(hEdit, directx_help);
692      return 1;
693
694   case WM_COMMAND:
695      if (LOWORD(wParam) == IDB_WEB_PAGE)
696         ShellExecute(GetMainWindow(), NULL, TEXT("http://www.microsoft.com/directx"),
697                   NULL, NULL, SW_SHOWNORMAL);
698
699      if (LOWORD(wParam) == IDCANCEL || LOWORD(wParam) == IDB_WEB_PAGE)
700         EndDialog(hDlg, 0);
701      return 1;
702   }
703   return 0;
704}
705
706/***************************************************************************
707    private functions
708 ***************************************************************************/
709
710static void DisableFilterControls(HWND hWnd, LPFOLDERDATA lpFilterRecord,
711                          LPFILTER_ITEM lpFilterItem, DWORD dwFlags)
712{
713   HWND  hWndCtrl = GetDlgItem(hWnd, lpFilterItem->m_dwCtrlID);
714   DWORD dwFilterType = lpFilterItem->m_dwFilterType;
715
716   /* Check the appropriate control */
717   if (dwFilterType & dwFlags)
718      Button_SetCheck(hWndCtrl, MF_CHECKED);
719
720   /* No special rules for this folder? */
721   if (!lpFilterRecord)
722      return;
723
724   /* If this is an excluded filter */
725   if (lpFilterRecord->m_dwUnset & dwFilterType)
726   {
727      /* uncheck it and disable the control */
728      Button_SetCheck(hWndCtrl, MF_UNCHECKED);
729      EnableWindow(hWndCtrl, FALSE);
730   }
731
732   /* If this is an implied filter, check it and disable the control */
733   if (lpFilterRecord->m_dwSet & dwFilterType)
734   {
735      Button_SetCheck(hWndCtrl, MF_CHECKED);
736      EnableWindow(hWndCtrl, FALSE);
737   }
738}
739
740// Handle disabling mutually exclusive controls
741static void EnableFilterExclusions(HWND hWnd, DWORD dwCtrlID)
742{
743   int    i;
744   DWORD   id;
745
746   for (i = 0; i < NUM_EXCLUSIONS; i++)
747   {
748      // is this control in the list?
749      if (filterExclusion[i] == dwCtrlID)
750      {
751         // found the control id
752         break;
753      }
754   }
755
756   // if the control was found
757   if (i < NUM_EXCLUSIONS)
758   {
759      // find the opposing control id
760      if (i % 2)
761         id = filterExclusion[i - 1];
762      else
763         id = filterExclusion[i + 1];
764
765      // Uncheck the other control
766      Button_SetCheck(GetDlgItem(hWnd, id), MF_UNCHECKED);
767   }
768}
769
770// Validate filter setting, mask out inappropriate filters for this folder
771static DWORD ValidateFilters(LPFOLDERDATA lpFilterRecord, DWORD dwFlags)
772{
773   DWORD dwFilters;
774
775   if (lpFilterRecord != (LPFOLDERDATA)0)
776   {
777      // Mask out implied and excluded filters
778      dwFilters = lpFilterRecord->m_dwSet | lpFilterRecord->m_dwUnset;
779      return dwFlags & ~dwFilters;
780   }
781
782   // No special cases - all filters apply
783   return dwFlags;
784}
785
786static void OnHScroll(HWND hwnd, HWND hwndCtl, UINT code, int pos)
787{
788   int value;
789   TCHAR tmp[4];
790   if (hwndCtl == GetDlgItem(hwnd, IDC_CYCLETIMESEC))
791   {
792      value = SendDlgItemMessage(hwnd,IDC_CYCLETIMESEC, TBM_GETPOS, 0, 0);
793      _itot(value,tmp,10);
794      SendDlgItemMessage(hwnd,IDC_CYCLETIMESECTXT,WM_SETTEXT,0, (WPARAM)tmp);
795   }
796   else
797   if (hwndCtl == GetDlgItem(hwnd, IDC_SCREENSHOT_BORDERSIZE))
798   {
799      value = SendDlgItemMessage(hwnd,IDC_SCREENSHOT_BORDERSIZE, TBM_GETPOS, 0, 0);
800      _itot(value,tmp,10);
801      SendDlgItemMessage(hwnd,IDC_SCREENSHOT_BORDERSIZETXT,WM_SETTEXT,0, (WPARAM)tmp);
802   }
803}
src/osd/windows/ui/file.h
r995r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11 ***************************************************************************/
12
13#ifndef FILE_H
14#define FILE_H
15
16// from windows fileio.c
17extern void set_pathlist(int file_type,const char *new_rawpath);
18
19#define OSD_FILETYPE_ICON 1001
20
21#endif
src/osd/windows/ui/dxdecode.h
r995r996
1/* Copyright 1998 Invasion Games.  All Rights Reserved.  Do NOT distribute. */
2
3/* dxdecode.h for client */
4
5/* Main header file for dxdecode.cpp */
6
7#ifndef DXDECODE_H
8#define DXDECODE_H
9
10extern const char* DirectXDecodeError(HRESULT errorval);
11
12#endif /* DXDECODE_H */
src/osd/windows/ui/dialogs.h
r995r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11 ***************************************************************************/
12
13#ifndef DIALOGS_H
14#define DIALOGS_H
15
16const char * GetFilterText(void);
17
18INT_PTR CALLBACK ResetDialogProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam);
19INT_PTR CALLBACK InterfaceDialogProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam);
20INT_PTR CALLBACK FilterDialogProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam);
21INT_PTR CALLBACK AboutDialogProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam);
22INT_PTR CALLBACK AddCustomFileDialogProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam);
23INT_PTR CALLBACK DirectXDialogProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam);
24
25
26#endif
27
src/osd/windows/ui/help.c
r995r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10   
11***************************************************************************/
12
13/***************************************************************************
14
15  help.c
16 
17   Help wrapper code.
18   
19***************************************************************************/
20
21#define WIN32_LEAN_AND_MEAN
22#include <windows.h>
23#include "help.h"
24
25typedef HWND (WINAPI *HtmlHelpProc)(HWND hwndCaller, LPCSTR pszFile, UINT uCommand, DWORD_PTR dwData);
26
27/***************************************************************************
28 Internal structures
29***************************************************************************/
30
31/***************************************************************************
32 function prototypes
33***************************************************************************/
34
35static void Help_Load(void);
36
37/***************************************************************************
38 External function prototypes
39***************************************************************************/
40
41/***************************************************************************
42 External variables
43***************************************************************************/
44
45/***************************************************************************
46 Internal variables
47***************************************************************************/
48
49static HtmlHelpProc g_pHtmlHelp;
50static HMODULE      g_hHelpLib;
51static DWORD        g_dwCookie;
52
53/**************************************************************************
54 External functions
55***************************************************************************/
56
57int HelpInit(void)
58{
59   g_pHtmlHelp = NULL;
60   g_hHelpLib  = NULL;
61
62   g_dwCookie = 0;
63   HelpFunction(NULL, NULL, HH_INITIALIZE, (DWORD)&g_dwCookie);
64   return 0;
65}
66
67void HelpExit(void)
68{
69   HelpFunction(NULL, NULL, HH_CLOSE_ALL, 0);
70   HelpFunction(NULL, NULL, HH_UNINITIALIZE, (DWORD)g_dwCookie);
71
72   g_dwCookie  = 0;
73   g_pHtmlHelp = NULL;
74
75   if (g_hHelpLib)
76   {
77      FreeLibrary(g_hHelpLib);
78      g_hHelpLib = NULL;
79   }
80}
81
82HWND HelpFunction(HWND hwndCaller, LPCSTR pszFile, UINT uCommand, DWORD_PTR dwData)
83{
84   if (g_pHtmlHelp == NULL)
85      Help_Load();
86
87   if (g_pHtmlHelp)
88      return g_pHtmlHelp(hwndCaller, pszFile, uCommand, dwData);
89   else
90      return NULL;
91}
92
93/***************************************************************************
94 Internal functions 
95***************************************************************************/
96
97static void Help_Load(void)
98{
99   g_hHelpLib = LoadLibrary(TEXT("hhctrl.ocx"));
100   if (g_hHelpLib)
101   {
102      FARPROC pProc = NULL;
103      pProc = GetProcAddress(g_hHelpLib, "HtmlHelpA");
104      if (pProc)
105      {
106         g_pHtmlHelp = (HtmlHelpProc)pProc;
107      }
108      else
109      {
110         FreeLibrary(g_hHelpLib);
111         g_hHelpLib = NULL;
112      }
113   }
114}
src/osd/windows/ui/directdraw.c
r995r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11 ***************************************************************************/
12
13/***************************************************************************
14
15   directdraw.c
16
17   Direct Draw routines.
18 
19 ***************************************************************************/
20
21#define WIN32_LEAN_AND_MEAN
22
23#include <windows.h>
24
25#ifndef _MSC_VER
26#ifdef __GNUC__
27#define NONAMELESSUNION
28#else
29#include <multidef.h>
30#endif
31#else
32#ifndef NONAMELESSUNION
33#define NONAMELESSUNION
34#endif
35
36#endif
37#include <ddraw.h>
38#include <tchar.h>
39
40#include "M32Util.h"
41#include "screenshot.h"
42#include "mame32.h"
43#include "dxdecode.h"
44#include "DirectDraw.h"
45
46/***************************************************************************
47   function prototypes
48 ***************************************************************************/
49
50static BOOL WINAPI DDEnumInfo(GUID FAR *lpGUID,
51                       LPTSTR    lpDriverDescription,
52                       LPTSTR    lpDriverName,       
53                       LPVOID   lpContext,
54                       HMONITOR   hm);
55
56static BOOL WINAPI DDEnumOldInfo(GUID FAR *lpGUID,
57                         LPTSTR      lpDriverDescription,
58                         LPTSTR      lpDriverName,     
59                         LPVOID    lpContext);
60
61static void CalculateDisplayModes(void);
62static HRESULT CALLBACK EnumDisplayModesCallback(LPDDSURFACEDESC pddsd, LPVOID Context);
63static HRESULT CALLBACK EnumDisplayModesCallback2(DDSURFACEDESC2* pddsd, LPVOID Context);
64
65/***************************************************************************
66   External variables
67 ***************************************************************************/
68
69/***************************************************************************
70   Internal structures
71 ***************************************************************************/
72
73typedef struct
74{
75   TCHAR* name;
76   GUID* lpguid;
77} display_type;
78
79typedef HRESULT (WINAPI *ddc_proc)(GUID FAR *lpGUID, LPDIRECTDRAW FAR *lplpDD,
80                           IUnknown FAR *pUnkOuter);
81
82/***************************************************************************
83   Internal variables
84 ***************************************************************************/
85
86#define MAX_DISPLAYS 100
87static int               g_nNumDisplays;
88static display_type       g_Displays[MAX_DISPLAYS];
89
90static HANDLE            g_hDLL;
91static BOOL             g_bHWStretch;
92static BOOL             g_bRefresh;
93static struct tDisplayModes g_DisplayModes;
94static IDirectDraw2*      g_pDirectDraw2;
95static IDirectDraw4*      g_pDirectDraw4;
96
97/***************************************************************************
98   External functions   
99 ***************************************************************************/
100
101/****************************************************************************
102 *      DirectDrawInitialize
103 *
104 *      Initialize the DirectDraw variables.
105 *
106 *      This entails the following functions:
107 *
108 *         DirectDrawCreate
109 *
110 ****************************************************************************/
111
112#if !defined(LPDIRECTDRAWENUMERATE)
113#if defined(UNICODE)
114
115typedef HRESULT (WINAPI* LPDIRECTDRAWENUMERATEW)(LPDDENUMCALLBACKW lpCallback, LPVOID lpContext);
116
117#define LPDIRECTDRAWENUMERATE   LPDIRECTDRAWENUMERATEW
118
119#define SDirectDrawEnumerateEx "DirectDrawEnumerateExW"
120#define SDirectDrawEnumerate   "DirectDrawEnumerateW"
121
122#else
123
124typedef HRESULT (WINAPI* LPDIRECTDRAWENUMERATEA)(LPDDENUMCALLBACKA lpCallback, LPVOID lpContext);
125
126#define LPDIRECTDRAWENUMERATE   LPDIRECTDRAWENUMERATEA
127
128#define SDirectDrawEnumerateEx "DirectDrawEnumerateExA"
129#define SDirectDrawEnumerate   "DirectDrawEnumerateA"
130
131#endif
132#endif /* LPDIRECTDRAWENUMERATE */
133
134/****************************************************************************/
135
136BOOL DirectDraw_Initialize(void)
137{
138   HRESULT  hr;
139   UINT    error_mode;
140   ddc_proc ddc;
141   DDCAPS    ddCaps;
142   DDCAPS    ddHelCaps;
143   IDirectDraw* pDirectDraw1;
144   LPDIRECTDRAWENUMERATEEX pDDEnumEx;
145
146   if (g_hDLL != NULL)
147      return TRUE;
148
149   g_nNumDisplays = 0;
150   g_hDLL         = NULL;
151   g_bHWStretch   = FALSE;
152   g_bRefresh      = FALSE;
153   g_pDirectDraw2 = NULL;
154   g_pDirectDraw4 = NULL;
155
156   /* Turn off error dialog for this call */
157   error_mode = SetErrorMode(0);
158   g_hDLL = LoadLibrary(TEXT("ddraw.dll"));
159   SetErrorMode(error_mode);
160
161   if (g_hDLL == NULL)
162      return FALSE;
163
164   ddc = (ddc_proc)GetProcAddress(g_hDLL, "DirectDrawCreate");
165   if (ddc == NULL)
166      return FALSE;
167
168   pDirectDraw1   = NULL;
169   g_pDirectDraw2 = NULL;
170   g_pDirectDraw4 = NULL;
171   hr = ddc(NULL, &pDirectDraw1, NULL);
172   if (FAILED(hr))
173   {
174      ErrorMsg("DirectDrawCreate failed: %s", DirectXDecodeError(hr));
175      return FALSE;
176   }
177
178   hr = IDirectDraw_QueryInterface(pDirectDraw1, &IID_IDirectDraw4, (void**)&g_pDirectDraw4);
179   if (FAILED(hr))
180   {
181      g_pDirectDraw4 = NULL;
182      hr = IDirectDraw_QueryInterface(pDirectDraw1, &IID_IDirectDraw2, (void**)&g_pDirectDraw2);
183      if (FAILED(hr))
184      {
185         ErrorMsg("Query Interface for DirectDraw 2 failed: %s", DirectXDecodeError(hr));
186         g_pDirectDraw2 = NULL;
187         IDirectDraw_Release(pDirectDraw1);
188         return FALSE;
189      }
190   }
191   
192   memset(&ddCaps,    0, sizeof(DDCAPS));
193   memset(&ddHelCaps, 0, sizeof(DDCAPS));
194   ddCaps.dwSize    = sizeof(DDCAPS);
195   ddHelCaps.dwSize = sizeof(DDCAPS);
196   hr = IDirectDraw_GetCaps(pDirectDraw1, &ddCaps, &ddHelCaps); /* 1 2 or 4? */
197   if (FAILED(hr))
198   {
199      ErrorMsg("Error getting DirectDraw capabilities: %s", DirectXDecodeError(hr));
200   }
201   else
202      g_bHWStretch = ((ddCaps.dwCaps & DDCAPS_BLTSTRETCH) != 0) ? TRUE : FALSE;
203
204   IDirectDraw_Release(pDirectDraw1);
205
206   /*
207      Note that you must know which version of the
208      function to retrieve (see the following text).
209      For this example, we use the ANSI version.
210    */
211   pDDEnumEx = (LPDIRECTDRAWENUMERATEEX) GetProcAddress(g_hDLL, SDirectDrawEnumerateEx);
212
213   /*
214      If the function is there, call it to enumerate all display devices
215      attached to the desktop, and any non-display DirectDraw devices.
216    */
217   if (pDDEnumEx)
218   {
219      pDDEnumEx(DDEnumInfo, NULL,
220              DDENUM_ATTACHEDSECONDARYDEVICES | DDENUM_DETACHEDSECONDARYDEVICES);
221   }
222   else
223   {
224      LPDIRECTDRAWENUMERATE lpDDEnum;
225
226      lpDDEnum = (LPDIRECTDRAWENUMERATE) GetProcAddress(g_hDLL, SDirectDrawEnumerate);
227      /*
228       * We must be running on an old version of ddraw. Therefore,
229       * by definiton, multimon isn't supported. Fall back on
230       * DirectDrawEnumerate to enumerate standard devices on a
231       * single monitor system.
232       */
233      if (lpDDEnum)
234      {
235         lpDDEnum(DDEnumOldInfo, NULL);
236      }
237      else
238      {
239         return FALSE;
240      }
241   }
242
243   return TRUE;
244}
245
246/****************************************************************************
247 *
248 *      DirectDraw_Close
249 *
250 *      Terminate our usage of DirectDraw.
251 *
252 ****************************************************************************/
253
254void DirectDraw_Close(void)
255{
256   int i;
257   
258   for (i = 0; i < g_nNumDisplays; i++)
259   {
260      free(g_Displays[i].name);
261      g_Displays[i].name = NULL;
262      if (g_Displays[i].lpguid != NULL)
263      {
264         free(g_Displays[i].lpguid);
265         g_Displays[i].lpguid = NULL;
266      }
267     
268   }
269   g_nNumDisplays = 0;
270   
271   /*
272      Destroy any lingering IDirectDraw object.
273   */
274   if (g_pDirectDraw2)
275   {
276      IDirectDraw2_Release(g_pDirectDraw2);
277      g_pDirectDraw2 = NULL;
278   }
279
280   if (g_pDirectDraw4)
281   {
282      IDirectDraw4_Release(g_pDirectDraw4);
283      g_pDirectDraw4 = NULL;
284   }
285
286   if (g_hDLL)
287   {
288      FreeLibrary(g_hDLL);
289      g_hDLL = NULL;
290   }
291}
292
293/****************************************************************************/
294/*
295   Return a list of 16, 24 and 32 bit DirectDraw modes.
296*/
297struct tDisplayModes* DirectDraw_GetDisplayModes(void)
298{
299   if (g_DisplayModes.m_nNumModes == 0)
300      CalculateDisplayModes();
301
302   return &g_DisplayModes;
303}
304
305int DirectDraw_GetNumDisplays(void)
306{
307   return g_nNumDisplays;
308}
309
310BOOL DirectDraw_HasHWStretch(void)
311{
312   return g_bHWStretch;
313}
314
315BOOL DirectDraw_HasRefresh(void)
316{
317   return g_bRefresh;
318}
319
320LPCTSTR DirectDraw_GetDisplayName(int num_display)
321{
322   return g_Displays[num_display].name;
323}
324
325/****************************************************************************/
326/* internal functions */
327/****************************************************************************/
328
329static BOOL WINAPI DDEnumInfo(GUID FAR *lpGUID,
330                       LPTSTR    lpDriverDescription,
331                       LPTSTR    lpDriverName,       
332                       LPVOID   lpContext,
333                       HMONITOR   hm)
334{
335   g_Displays[g_nNumDisplays].name = malloc((_tcslen(lpDriverDescription) + 1) * sizeof(TCHAR));
336   _tcscpy(g_Displays[g_nNumDisplays].name, lpDriverDescription);
337   
338   if (lpGUID == NULL)
339      g_Displays[g_nNumDisplays].lpguid = NULL;
340   else
341   {
342      g_Displays[g_nNumDisplays].lpguid = (LPGUID)malloc(sizeof(GUID));
343      memcpy(g_Displays[g_nNumDisplays].lpguid, lpGUID, sizeof(GUID));
344   }
345   
346   g_nNumDisplays++;
347   if (g_nNumDisplays == MAX_DISPLAYS)
348      return DDENUMRET_CANCEL;
349   else
350      return DDENUMRET_OK;
351}
352
353static BOOL WINAPI DDEnumOldInfo(GUID FAR *lpGUID,
354                         LPTSTR      lpDriverDescription,
355                         LPTSTR      lpDriverName,     
356                         LPVOID    lpContext)
357{
358   return DDEnumInfo(lpGUID, lpDriverDescription, lpDriverName, lpContext, NULL);
359}
360
361static HRESULT CALLBACK EnumDisplayModesCallback(LPDDSURFACEDESC pddsd, LPVOID Context)
362{
363   DWORD dwDepth = pddsd->ddpfPixelFormat.DUMMYUNIONNAMEN(1).dwRGBBitCount;
364
365   struct tDisplayModes* pDisplayModes = (struct tDisplayModes*)Context;
366   if (dwDepth == 16
367   ||   dwDepth == 24
368   ||   dwDepth == 32)
369   {
370      pDisplayModes->m_Modes[pDisplayModes->m_nNumModes].m_dwWidth   = pddsd->dwWidth;
371      pDisplayModes->m_Modes[pDisplayModes->m_nNumModes].m_dwHeight  = pddsd->dwHeight;
372      pDisplayModes->m_Modes[pDisplayModes->m_nNumModes].m_dwBPP      = dwDepth;
373      pDisplayModes->m_Modes[pDisplayModes->m_nNumModes].m_dwRefresh = 0;
374      pDisplayModes->m_nNumModes++;
375   }
376
377   if (pDisplayModes->m_nNumModes == MAXMODES)
378      return DDENUMRET_CANCEL;
379   else
380      return DDENUMRET_OK;
381}
382
383static HRESULT CALLBACK EnumDisplayModesCallback2(DDSURFACEDESC2* pddsd2, LPVOID Context)
384{
385   struct tDisplayModes* pDisplayModes = (struct tDisplayModes*)Context;
386
387   DWORD dwDepth = pddsd2->DUMMYUNIONNAMEN(4).ddpfPixelFormat.DUMMYUNIONNAMEN(1).dwRGBBitCount;
388
389   if (dwDepth == 16
390   ||   dwDepth == 24
391   ||   dwDepth == 32)
392   {
393      pDisplayModes->m_Modes[pDisplayModes->m_nNumModes].m_dwWidth   = pddsd2->dwWidth;
394      pDisplayModes->m_Modes[pDisplayModes->m_nNumModes].m_dwHeight  = pddsd2->dwHeight;
395      pDisplayModes->m_Modes[pDisplayModes->m_nNumModes].m_dwBPP      = dwDepth;
396      pDisplayModes->m_Modes[pDisplayModes->m_nNumModes].m_dwRefresh = pddsd2->DUMMYUNIONNAMEN(2).dwRefreshRate;
397      pDisplayModes->m_nNumModes++;
398
399      if (pddsd2->DUMMYUNIONNAMEN(2).dwRefreshRate != 0)
400         g_bRefresh = TRUE;
401   }
402   
403   if (pDisplayModes->m_nNumModes == MAXMODES)
404      return DDENUMRET_CANCEL;
405   else
406      return DDENUMRET_OK;
407}
408
409static void CalculateDisplayModes(void)
410{
411   g_DisplayModes.m_nNumModes = 0;
412
413   if (g_pDirectDraw4)
414      IDirectDraw4_EnumDisplayModes(g_pDirectDraw4, DDEDM_REFRESHRATES, NULL, &g_DisplayModes, EnumDisplayModesCallback2);
415   else
416   if (g_pDirectDraw2)
417      IDirectDraw2_EnumDisplayModes(g_pDirectDraw2, 0, NULL, &g_DisplayModes, EnumDisplayModesCallback);
418}
419
420
src/osd/windows/ui/mame32.h
r995r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11 ***************************************************************************/
12
13#ifndef MAME32_H
14#define MAME32_H
15
16#include "win32ui.h"
17
18#ifndef MESS
19#define MAME32NAME   "MAME32"
20#define MAMENAME   "MAME"
21#else
22#define MAME32NAME   "MESS"
23#define MAMENAME   "MESS"
24#endif
25
26#endif
src/osd/windows/ui/treeview.c
r995r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11***************************************************************************/
12
13/***************************************************************************
14
15  TreeView.c
16
17  TreeView support routines - MSH 11/19/1998
18
19***************************************************************************/
20
21#define WIN32_LEAN_AND_MEAN
22
23#ifdef _MSC_VER
24#ifndef NONAMELESSUNION
25#define NONAMELESSUNION
26#endif
27#endif
28
29
30#include <windows.h>
31#include <windowsx.h>
32#include <shellapi.h>
33#include <commctrl.h>
34#include <stdio.h>  /* for sprintf */
35#include <stdlib.h> /* For malloc and free */
36#include <ctype.h> /* For tolower */
37#include <string.h>
38#include <sys/stat.h>
39#include <sys/types.h>
40#ifdef _MSC_VER
41#include <direct.h>
42#endif
43#include <tchar.h>
44
45#include <io.h>
46#include <driver.h>
47#include "hash.h"
48#include "M32Util.h"
49#include "bitmask.h"
50#include "screenshot.h"
51#include "mame32.h"
52#include "TreeView.h"
53#include "resource.h"
54#include "properties.h"
55#include "m32opts.h"
56#include "help.h"
57#include "dialogs.h"
58#include "winutf8.h"
59#include "strconv.h"
60
61#ifdef _MSC_VER
62#if _MSC_VER > 1200
63#define HAS_DUMMYUNIONNAME
64#endif
65#endif
66
67#ifdef _MSC_VER
68#define snprintf _snprintf
69#endif
70
71#define MAX_EXTRA_FOLDERS 256
72
73/***************************************************************************
74    public structures
75 ***************************************************************************/
76
77#define ICON_MAX (sizeof(treeIconNames) / sizeof(treeIconNames[0]))
78
79/* Name used for user-defined custom icons */
80/* external *.ico file to look for. */
81
82typedef struct
83{
84   int      nResourceID;
85   LPCSTR   lpName;
86} TREEICON;
87
88static TREEICON treeIconNames[] =
89{
90   { IDI_FOLDER_OPEN,         "foldopen" },
91   { IDI_FOLDER,              "folder" },
92   { IDI_FOLDER_AVAILABLE,    "foldavail" },
93   { IDI_FOLDER_MANUFACTURER, "foldmanu" },
94   { IDI_FOLDER_UNAVAILABLE,  "foldunav" },
95   { IDI_FOLDER_YEAR,         "foldyear" },
96    { IDI_FOLDER_SOURCE,       "foldsrc" },
97   { IDI_MANUFACTURER,        "manufact" },
98   { IDI_WORKING,             "working" },
99   { IDI_NONWORKING,          "nonwork" },
100   { IDI_YEAR,                "year" },
101   { IDI_SOUND,               "sound" },
102    { IDI_CPU,                 "cpu" },
103   { IDI_HARDDISK,            "harddisk" },
104    { IDI_SOURCE,              "source" }
105};
106
107/***************************************************************************
108    private variables
109 ***************************************************************************/
110
111/* this has an entry for every folder eventually in the UI, including subfolders */
112static TREEFOLDER **treeFolders = 0;
113static UINT         numFolders  = 0;        /* Number of folder in the folder array */
114static UINT         next_folder_id = MAX_FOLDERS;
115static UINT         folderArrayLength = 0;  /* Size of the folder array */
116static LPTREEFOLDER lpCurrentFolder = 0;    /* Currently selected folder */
117static UINT         nCurrentFolder = 0;     /* Current folder ID */
118static WNDPROC      g_lpTreeWndProc = 0;    /* for subclassing the TreeView */
119static HIMAGELIST   hTreeSmall = 0;         /* TreeView Image list of icons */
120
121/* this only has an entry for each TOP LEVEL extra folder + SubFolders*/
122LPEXFOLDERDATA ExtraFolderData[MAX_EXTRA_FOLDERS * MAX_EXTRA_SUBFOLDERS];
123int                   numExtraFolders = 0;
124static int            numExtraIcons = 0;
125static char           *ExtraFolderIcons[MAX_EXTRA_FOLDERS];
126
127// built in folders and filters
128static LPFOLDERDATA  g_lpFolderData;
129static LPFILTER_ITEM g_lpFilterList;   
130
131/***************************************************************************
132    private function prototypes
133 ***************************************************************************/
134
135extern BOOL InitFolders(void);
136static BOOL         CreateTreeIcons(void);
137static void         TreeCtrlOnPaint(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
138static const char* ParseManufacturer(const char *s, int *pParsedChars );
139static const char* TrimManufacturer(const char *s);
140static void CreateAllChildFolders(void);
141static BOOL         AddFolder(LPTREEFOLDER lpFolder);
142static LPTREEFOLDER NewFolder(const char *lpTitle,
143                              UINT nFolderId, int nParent, UINT nIconId,
144                              DWORD dwFlags);
145static void         DeleteFolder(LPTREEFOLDER lpFolder);
146
147static LRESULT CALLBACK TreeWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
148
149static int InitExtraFolders(void);
150static void FreeExtraFolders(void);
151static void SetExtraIcons(char *name, int *id);
152static BOOL TryAddExtraFolderAndChildren(int parent_index);
153
154static BOOL TrySaveExtraFolder(LPTREEFOLDER lpFolder);
155
156/***************************************************************************
157    public functions
158 ***************************************************************************/
159
160/**************************************************************************
161 *      ci_strncmp - case insensitive character array compare
162 *
163 *      Returns zero if the first n characters of s1 and s2 are equal,
164 *      ignoring case.
165 *      stolen from datafile.c
166 **************************************************************************/
167static int ci_strncmp (const char *s1, const char *s2, int n)
168{
169        int c1, c2;
170
171        while (n)
172        {
173                if ((c1 = tolower (*s1)) != (c2 = tolower (*s2)))
174                        return (c1 - c2);
175                else if (!c1)
176                        break;
177                --n;
178
179                s1++;
180                s2++;
181        }
182        return 0;
183}
184
185
186
187/* De-allocate all folder memory */
188void FreeFolders(void)
189{
190   int i = 0;
191
192   if (treeFolders != NULL)
193   {
194      if (numExtraFolders)
195      {
196         FreeExtraFolders();
197         numFolders -= numExtraFolders;
198      }
199
200      for (i = numFolders - 1; i >= 0; i--)
201      {
202         DeleteFolder(treeFolders[i]);
203         treeFolders[i] = NULL;
204         numFolders--;
205      }
206      free(treeFolders);
207      treeFolders = NULL;
208   }
209   numFolders = 0;
210}
211
212/* Reset folder filters */
213void ResetFilters(void)
214{
215   int i = 0;
216
217   if (treeFolders != 0)
218   {
219      for (i = 0; i < (int)numFolders; i++)
220      {
221         treeFolders[i]->m_dwFlags &= ~F_MASK;
222      }
223   }
224}
225
226void InitTree(LPFOLDERDATA lpFolderData, LPFILTER_ITEM lpFilterList)
227{
228   g_lpFolderData = lpFolderData;
229   g_lpFilterList = lpFilterList;
230
231   InitFolders();
232
233   /* this will subclass the treeview (where WM_DRAWITEM gets sent for
234      the header control) */
235   g_lpTreeWndProc = (WNDPROC)(LONG)(int)GetWindowLong(GetTreeView(), GWL_WNDPROC);
236   SetWindowLong(GetTreeView(), GWL_WNDPROC, (LONG)TreeWndProc);
237}
238
239void DestroyTree(HWND hWnd)
240{
241    if ( hTreeSmall )
242    {
243        ImageList_Destroy( hTreeSmall );
244        hTreeSmall = NULL;
245    }
246}
247
248void SetCurrentFolder(LPTREEFOLDER lpFolder)
249{
250   lpCurrentFolder = (lpFolder == 0) ? treeFolders[0] : lpFolder;
251   nCurrentFolder = (lpCurrentFolder) ? lpCurrentFolder->m_nFolderId : 0;
252}
253
254LPTREEFOLDER GetCurrentFolder(void)
255{
256   return lpCurrentFolder;
257}
258
259UINT GetCurrentFolderID(void)
260{
261   return nCurrentFolder;
262}
263
264int GetNumFolders(void)
265{
266   return numFolders;
267}
268
269LPTREEFOLDER GetFolder(UINT nFolder)
270{
271   return (nFolder < numFolders) ? treeFolders[nFolder] : NULL;
272}
273
274LPTREEFOLDER GetFolderByID(UINT nID)
275{
276   UINT i;
277
278   for (i = 0; i < numFolders; i++)
279   {
280      if (treeFolders[i]->m_nFolderId == nID)
281      {
282         return treeFolders[i];
283      }
284   }
285
286   return (LPTREEFOLDER)0;
287}
288
289void AddGame(LPTREEFOLDER lpFolder, UINT nGame)
290{
291   SetBit(lpFolder->m_lpGameBits, nGame);
292}
293
294void RemoveGame(LPTREEFOLDER lpFolder, UINT nGame)
295{
296   ClearBit(lpFolder->m_lpGameBits, nGame);
297}
298
299int FindGame(LPTREEFOLDER lpFolder, int nGame)
300{
301   return FindBit(lpFolder->m_lpGameBits, nGame, TRUE);
302}
303
304// Called to re-associate games with folders
305void ResetWhichGamesInFolders(void)
306{
307   UINT   i, jj, k;
308   BOOL b;
309   int nGames = driver_list_get_count(drivers);
310
311   for (i = 0; i < numFolders; i++)
312   {
313      LPTREEFOLDER lpFolder = treeFolders[i];
314
315      // setup the games in our built-in folders
316      for (k = 0; g_lpFolderData[k].m_lpTitle; k++)
317      {
318         if (lpFolder->m_nFolderId == g_lpFolderData[k].m_nFolderId)
319         {
320            if (g_lpFolderData[k].m_pfnQuery || g_lpFolderData[k].m_bExpectedResult)
321            {
322               SetAllBits(lpFolder->m_lpGameBits, FALSE);
323               for (jj = 0; jj < nGames; jj++)
324               {
325                  // invoke the query function
326                  b = g_lpFolderData[k].m_pfnQuery ? g_lpFolderData[k].m_pfnQuery(jj) : TRUE;
327
328                  // if we expect FALSE, flip the result
329                  if (!g_lpFolderData[k].m_bExpectedResult)
330                     b = !b;
331
332                  // if we like what we hear, add the game
333                  if (b)
334                     AddGame(lpFolder, jj);
335               }
336            }
337            break;
338         }
339      }
340   }
341}
342
343
344/* Used to build the GameList */
345BOOL GameFiltered(int nGame, DWORD dwMask)
346{
347   int i;
348   LPTREEFOLDER lpFolder = GetCurrentFolder();
349   LPTREEFOLDER lpParent = NULL;
350
351   //Filter out the Bioses on all Folders, except for the Bios Folder
352   if( lpFolder->m_nFolderId != FOLDER_BIOS )
353   {
354      if( !( (drivers[nGame]->flags & GAME_IS_BIOS_ROOT ) == 0) )
355         return TRUE;
356   }
357    // Filter games--return TRUE if the game should be HIDDEN in this view
358   if( GetFilterInherit() )
359   {
360      if( lpFolder )
361      {
362         lpParent = GetFolder( lpFolder->m_nParent );
363         if( lpParent )
364         {
365            /* Check the Parent Filters and inherit them on child,
366             * The inherited filters don't display on the custom Filter Dialog for the Child folder
367             * No need to promote all games to parent folder, works as is */
368            dwMask |= lpParent->m_dwFlags;
369         }
370      }
371   }
372   /*Filter Text is already global*/
373
374   if (MyStrStrI(drivers[nGame]->description,GetFilterText()) == NULL &&
375      MyStrStrI(drivers[nGame]->name,GetFilterText()) == NULL &&
376      MyStrStrI(drivers[nGame]->source_file,GetFilterText()) == NULL &&
377      MyStrStrI(drivers[nGame]->manufacturer,GetFilterText()) == NULL)
378   {
379      return TRUE;
380   }
381   // Are there filters set on this folder?
382   if ((dwMask & F_MASK) == 0)
383      return FALSE;
384
385   // Filter out clones?
386   if (dwMask & F_CLONES && DriverIsClone(nGame))
387      return TRUE;
388
389   for (i = 0; g_lpFilterList[i].m_dwFilterType; i++)
390   {
391      if (dwMask & g_lpFilterList[i].m_dwFilterType)
392      {
393         if (g_lpFilterList[i].m_pfnQuery(nGame) == g_lpFilterList[i].m_bExpectedResult)
394            return TRUE;
395      }
396   }
397   return FALSE;
398}
399
400/* Get the parent of game in this view */
401BOOL GetParentFound(int nGame)
402{
403   int nParentIndex = -1;
404   LPTREEFOLDER lpFolder = GetCurrentFolder();
405
406   if( lpFolder )
407   {
408      nParentIndex = GetParentIndex(drivers[nGame]);
409
410      /* return FALSE if no parent is there in this view */
411      if( nParentIndex == -1)
412         return FALSE;
413
414      /* return FALSE if the folder should be HIDDEN in this view */
415      if (TestBit(lpFolder->m_lpGameBits, nParentIndex) == 0)
416         return FALSE;
417
418      /* return FALSE if the game should be HIDDEN in this view */
419      if (GameFiltered(nParentIndex, lpFolder->m_dwFlags))
420         return FALSE;
421
422      return TRUE;
423   }
424
425   return FALSE;
426}
427
428LPFILTER_ITEM GetFilterList(void)
429{
430   return g_lpFilterList;
431}
432
433/***************************************************************************
434   private functions
435 ***************************************************************************/
436
437void CreateSourceFolders(int parent_index)
438{
439   int i,jj, k=0;
440   int nGames = driver_list_get_count(drivers);
441   int start_folder = numFolders;
442   LPTREEFOLDER lpFolder = treeFolders[parent_index];
443   int *redirect_arr = GetFolderOptionsRedirectArr();
444   // no games in top level folder
445   SetAllBits(lpFolder->m_lpGameBits,FALSE);
446   if( redirect_arr == NULL)
447   {
448      redirect_arr = (int*)malloc(sizeof(int*) );
449      memset(redirect_arr, '\0', sizeof (int*));
450   }   
451   //We also allow setting of options for the Vector Folder
452   redirect_arr = realloc(redirect_arr, ((k+1)* sizeof(int)) );
453   redirect_arr[k++] = FOLDER_VECTOR;
454   for (jj = 0; jj < nGames; jj++)
455   {
456      const char *s = GetDriverFilename(jj);
457                         
458      if (s == NULL || s[0] == '\0')
459         continue;
460
461      // look for an existant source treefolder for this game
462      // (likely to be the previous one, so start at the end)
463      for (i=numFolders-1;i>=start_folder;i--)
464      {
465         if (strcmp(treeFolders[i]->m_lpTitle,s) == 0)
466         {
467            AddGame(treeFolders[i],jj);
468            break;
469         }
470      }
471      if (i == start_folder-1)
472      {
473         // nope, it's a source file we haven't seen before, make it.
474         LPTREEFOLDER lpTemp;
475         lpTemp = NewFolder(s, next_folder_id, parent_index, IDI_SOURCE,
476                         GetFolderFlags(numFolders));
477         ExtraFolderData[next_folder_id] = malloc(sizeof(EXFOLDERDATA) );
478         memset(ExtraFolderData[next_folder_id], 0, sizeof(EXFOLDERDATA));
479
480         ExtraFolderData[next_folder_id]->m_nFolderId = next_folder_id;
481         ExtraFolderData[next_folder_id]->m_nIconId = IDI_SOURCE;
482         ExtraFolderData[next_folder_id]->m_nParent = lpFolder->m_nFolderId;
483         ExtraFolderData[next_folder_id]->m_nSubIconId = -1;
484         strcpy( ExtraFolderData[next_folder_id]->m_szTitle, s );
485         //Add it to the FolderOptionsRedirectArray
486         redirect_arr = realloc(redirect_arr, ((k+1)* sizeof(int)) );
487         redirect_arr[k++] = next_folder_id;
488         ExtraFolderData[next_folder_id++]->m_dwFlags = 0;
489
490         AddFolder(lpTemp);
491         AddGame(lpTemp,jj);
492      }
493   }
494   SetNumOptionFolders(k-1);
495   SetFolderOptionsRedirectArr(redirect_arr);
496}
497
498void CreateManufacturerFolders(int parent_index)
499{
500   int i,jj;
501   int nGames = driver_list_get_count(drivers);
502   int start_folder = numFolders;
503   LPTREEFOLDER lpFolder = treeFolders[parent_index];
504    LPTREEFOLDER lpTemp;
505
506   // no games in top level folder
507   SetAllBits(lpFolder->m_lpGameBits,FALSE);
508
509   for (jj = 0; jj < nGames; jj++)
510   {
511      const char *manufacturer = drivers[jj]->manufacturer;
512      int iChars = 0;
513      while( manufacturer != NULL && manufacturer[0] != '\0' )
514      {
515         const char *s = ParseManufacturer(manufacturer, &iChars);
516         manufacturer += iChars;
517         //shift to next start char
518         if( s != NULL && strlen(s) > 0 )
519          {
520            const char *t = TrimManufacturer(s);
521            for (i=numFolders-1;i>=start_folder;i--)
522            {
523               //RS Made it case insensitive
524               if (ci_strncmp(treeFolders[i]->m_lpTitle,t,20) == 0 )
525               {
526                  AddGame(treeFolders[i],jj);
527                  break;
528               }
529            }
530            if (i == start_folder-1)
531            {
532               // nope, it's a manufacturer we haven't seen before, make it.
533               lpTemp = NewFolder(t, next_folder_id, parent_index, IDI_MANUFACTURER,
534                              GetFolderFlags(numFolders));
535               ExtraFolderData[next_folder_id] = malloc(sizeof(EXFOLDERDATA) );
536               memset(ExtraFolderData[next_folder_id], 0, sizeof(EXFOLDERDATA));
537
538               ExtraFolderData[next_folder_id]->m_nFolderId = next_folder_id;
539               ExtraFolderData[next_folder_id]->m_nIconId = IDI_MANUFACTURER;
540               ExtraFolderData[next_folder_id]->m_nParent = lpFolder->m_nFolderId;
541               ExtraFolderData[next_folder_id]->m_nSubIconId = -1;
542               strcpy( ExtraFolderData[next_folder_id]->m_szTitle, s );
543               ExtraFolderData[next_folder_id++]->m_dwFlags = 0;
544               AddFolder(lpTemp);
545               AddGame(lpTemp,jj);
546            }
547         }
548      }
549   }
550}
551
552/* Make a reasonable name out of the one found in the driver array */
553static const char* ParseManufacturer(const char *s, int *pParsedChars )
554{
555   static char tmp[256];
556    char* ptmp;
557   char *t;
558   *pParsedChars= 0;
559
560   if ( *s == '?' || *s == '<' || s[3] == '?' )
561    {
562      (*pParsedChars) = strlen(s);
563      return "<unknown>";
564    }
565
566    ptmp = tmp;
567   /*if first char is a space, skip it*/
568   if( *s == ' ' )
569   {
570      (*pParsedChars)++;
571        ++s;
572   }
573   while( *s )
574   {
575        /* combinations where to end string */
576     
577      if (
578            ( (*s == ' ') && ( s[1] == '(' || s[1] == '/' || s[1] == '+' ) ) ||
579            ( *s == ']' ) ||
580            ( *s == '/' ) ||
581            ( *s == '?' )
582            )
583        {
584      (*pParsedChars)++;
585         if( s[1] == '/' || s[1] == '+' )
586            (*pParsedChars)++;
587         break;
588        }
589      if( s[0] == ' ' && s[1] == '?' )
590      {
591         (*pParsedChars) += 2;
592         s+=2;
593      }
594
595        /* skip over opening braces*/
596
597      if ( *s != '[' )
598        {
599         *ptmp++ = *s;
600       }
601      (*pParsedChars)++;
602      /*for "distributed by" and "supported by" handling*/
603      if( ( (s[1] == ',') && (s[2] == ' ') && ( (s[3] == 's') || (s[3] == 'd') ) ) )
604      {
605         //*ptmp++ = *s;
606         ++s;
607         break;
608   }
609        ++s;
610   }
611   *ptmp = '\0';
612   t = tmp;
613   if( tmp[0] == '(' || tmp[strlen(tmp)-1] == ')' || tmp[0] == ',')
614   {
615      ptmp = strchr( tmp,'(' );
616      if ( ptmp == NULL )
617      {
618         ptmp = strchr( tmp,',' );
619         if( ptmp != NULL)
620         {
621            //parse the new "supported by" and "distributed by"
622            ptmp++;
623
624            if (ci_strncmp(ptmp, " supported by", 13) == 0)
625            {
626               ptmp += 13;
627            }
628            else if (ci_strncmp(ptmp, " distributed by", 15) == 0)
629            {
630               ptmp += 15;
631            }
632            else
633            {
634               return NULL;
635            }
636         }
637         else
638         {
639            ptmp = tmp;
640            if ( ptmp == NULL )
641            {
642               return NULL;
643            }
644         }
645      }
646      if( tmp[0] == '(' || tmp[0] == ',')
647      {
648         ptmp++;
649      }
650      if (ci_strncmp(ptmp, "licensed from ", 14) == 0)
651      {
652         ptmp += 14;
653      }
654      // for the licenced from case
655      if (ci_strncmp(ptmp, "licenced from ", 14) == 0)
656      {
657         ptmp += 14;
658      }
659     
660      while ( (*ptmp != ')' ) && (*ptmp != '/' ) && *ptmp != '\0')
661      {
662         if (*ptmp == ' ' && ci_strncmp(ptmp, " license", 8) == 0)
663         {
664            break;
665         }
666         if (*ptmp == ' ' && ci_strncmp(ptmp, " licence", 8) == 0)
667         {
668            break;
669         }
670         *t++ = *ptmp++;
671      }
672     
673      *t = '\0';
674   }
675
676   *ptmp = '\0';
677   return tmp;
678}
679
680/* Analyze Manufacturer Names for typical patterns, that don't distinguish between companies (e.g. Co., Ltd., Inc., etc. */
681static const char* TrimManufacturer(const char *s)
682{
683   //Also remove Country specific suffixes (e.g. Japan, Italy, America, USA, ...)
684   int i=0;
685   char strTemp[256];
686   static char strTemp2[256];
687   int j=0;
688   int k=0;
689   int l = 0;
690   memset(strTemp, '\0', 256 );
691   memset(strTemp2, '\0', 256 );
692   //start analyzing from the back, as these are usually suffixes
693   for(i=strlen(s)-1; i>=0;i-- )
694   {
695     
696      l = strlen(strTemp);
697      for(k=l;k>=0; k--)
698         strTemp[k+1] = strTemp[k];
699      strTemp[0] = s[i];
700      strTemp[++l] = '\0';
701      switch (l)
702      {
703         case 2:
704            if( ci_strncmp(strTemp, "co", 2) == 0 )
705            {
706               j=l;
707               while( s[strlen(s)-j-1] == ' ' || s[strlen(s)-j-1] == ',' )
708               {
709                  j++;
710               }
711               if( j!=l)
712               {
713                  memset(strTemp2, '\0', 256 );
714                  strncpy(strTemp2, s, strlen(s)-j );   
715               }
716            }
717            break;
718         case 3:
719            if( ci_strncmp(strTemp, "co.", 3) == 0 || ci_strncmp(strTemp, "ltd", 3) == 0 || ci_strncmp(strTemp, "inc", 3) == 0  || ci_strncmp(strTemp, "SRL", 3) == 0 || ci_strncmp(strTemp, "USA", 3) == 0)
720            {
721               j=l;
722               while( s[strlen(s)-j-1] == ' ' || s[strlen(s)-j-1] == ',' )
723               {
724                  j++;
725               }
726               if( j!=l)
727               {
728                  memset(strTemp2, '\0', 256 );
729                  strncpy(strTemp2, s, strlen(s)-j );   
730               }
731            }
732            break;
733         case 4:
734            if( ci_strncmp(strTemp, "inc.", 4) == 0 || ci_strncmp(strTemp, "ltd.", 4) == 0 || ci_strncmp(strTemp, "corp", 4) == 0 || ci_strncmp(strTemp, "game", 4) == 0)
735            {
736               j=l;
737               while( s[strlen(s)-j-1] == ' ' || s[strlen(s)-j-1] == ',' )
738               {
739                  j++;
740               }
741               if( j!=l)
742               {
743                  memset(strTemp2, '\0', 256 );
744                  strncpy(strTemp2, s, strlen(s)-j );   
745               }
746            }
747            break;
748         case 5:
749            if( ci_strncmp(strTemp, "corp.", 5) == 0 || ci_strncmp(strTemp, "Games", 5) == 0 || ci_strncmp(strTemp, "Italy", 5) == 0 || ci_strncmp(strTemp, "Japan", 5) == 0)
750            {
751               j=l;
752               while( s[strlen(s)-j-1] == ' ' || s[strlen(s)-j-1] == ',' )
753               {
754                  j++;
755               }
756               if( j!=l)
757               {
758                  memset(strTemp2, '\0', 256 );
759                  strncpy(strTemp2, s, strlen(s)-j );   
760               }
761            }
762            break;
763         case 6:
764            if( ci_strncmp(strTemp, "co-ltd", 6) == 0 || ci_strncmp(strTemp, "S.R.L.", 6) == 0)
765            {
766               j=l;
767               while( s[strlen(s)-j-1] == ' ' || s[strlen(s)-j-1] == ',' )
768               {
769                  j++;
770               }
771               if( j!=l)
772               {
773                  memset(strTemp2, '\0', 256 );
774                  strncpy(strTemp2, s, strlen(s)-j );   
775               }
776            }
777            break;
778         case 7:
779            if( ci_strncmp(strTemp, "co. ltd", 7) == 0  || ci_strncmp(strTemp, "America", 7) == 0)
780            {
781               j=l;
782               while( s[strlen(s)-j-1] == ' ' || s[strlen(s)-j-1] == ',' )
783               {
784                  j++;
785               }
786               if( j!=l)
787               {
788                  memset(strTemp2, '\0', 256 );
789                  strncpy(strTemp2, s, strlen(s)-j );   
790               }
791            }
792            break;
793         case 8:
794            if( ci_strncmp(strTemp, "co. ltd.", 8) == 0  )
795            {
796               j=l;
797               while( s[strlen(s)-j-1] == ' ' || s[strlen(s)-j-1] == ',' )
798               {
799                  j++;
800               }
801               if( j!=l)
802               {
803                  memset(strTemp2, '\0', 256 );
804                  strncpy(strTemp2, s, strlen(s)-j );   
805               }
806            }
807            break;
808         case 9:
809            if( ci_strncmp(strTemp, "co., ltd.", 9) == 0 || ci_strncmp(strTemp, "gmbh & co", 9) == 0 )
810            {
811               j=l;
812               while( s[strlen(s)-j-1] == ' ' || s[strlen(s)-j-1] == ',' )
813               {
814                  j++;
815               }
816               if( j!=l)
817               {
818                  memset(strTemp2, '\0', 256 );
819                  strncpy(strTemp2, s, strlen(s)-j );   
820               }
821            }
822            break;
823         case 10:
824            if( ci_strncmp(strTemp, "corp, ltd.", 10) == 0  || ci_strncmp(strTemp, "industries", 10) == 0  || ci_strncmp(strTemp, "of America", 10) == 0)
825            {
826               j=l;
827               while( s[strlen(s)-j-1] == ' ' || s[strlen(s)-j-1] == ',' )
828               {
829                  j++;
830               }
831               if( j!=l)
832               {
833                  memset(strTemp2, '\0', 256 );
834                  strncpy(strTemp2, s, strlen(s)-j );   
835               }
836            }
837            break;
838         case 11:
839            if( ci_strncmp(strTemp, "corporation", 11) == 0 || ci_strncmp(strTemp, "enterprises", 11) == 0 )
840            {
841               j=l;
842               while( s[strlen(s)-j-1] == ' ' || s[strlen(s)-j-1] == ',' )
843               {
844                  j++;
845               }
846               if( j!=l)
847               {
848                  memset(strTemp2, '\0', 256 );
849                  strncpy(strTemp2, s, strlen(s)-j );   
850               }
851            }
852            break;
853         case 16:
854            if( ci_strncmp(strTemp, "industries japan", 16) == 0 )
855            {
856               j=l;
857               while( s[strlen(s)-j-1] == ' ' || s[strlen(s)-j-1] == ',' )
858               {
859                  j++;
860               }
861               if( j!=l)
862               {
863                  memset(strTemp2, '\0', 256 );
864                  strncpy(strTemp2, s, strlen(s)-j );   
865               }
866            }
867            break;
868         default:
869            break;
870      }
871   }
872   if( strlen(strTemp2) == 0 )
873      return s;
874   return strTemp2;
875}
876
877
878
879void CreateCPUFolders(int parent_index)
880{
881   int i,jj;
882   int nGames = driver_list_get_count(drivers);
883   int nFolder = numFolders;
884   LPTREEFOLDER lpFolder = treeFolders[parent_index];
885   LPTREEFOLDER map[CPU_COUNT];
886
887   ZeroMemory(map, sizeof(map));
888   cpuintrf_init(NULL);
889
890   // no games in top level folder
891   SetAllBits(lpFolder->m_lpGameBits,FALSE);
892
893   for (i=1;i<CPU_COUNT;i++)
894   {
895      LPTREEFOLDER lpTemp;
896
897      for (jj = 1; jj < i; jj++)
898         if (!strcmp(cputype_name(i), cputype_name(jj)))
899            break;
900
901      if (i != jj)
902      {
903         map[i] = map[jj];
904         continue;
905      }
906      if( strlen( cputype_name(i) ) <=0 )
907         continue;
908      lpTemp = NewFolder(cputype_name(i), next_folder_id, parent_index, IDI_CPU,
909                      GetFolderFlags(numFolders));
910      ExtraFolderData[next_folder_id] = malloc(sizeof(EXFOLDERDATA) );
911      memset(ExtraFolderData[next_folder_id], 0, sizeof(EXFOLDERDATA));
912
913      ExtraFolderData[next_folder_id]->m_nFolderId = next_folder_id;
914      ExtraFolderData[next_folder_id]->m_nIconId = IDI_CPU;
915      ExtraFolderData[next_folder_id]->m_nParent = lpFolder->m_nFolderId;
916      ExtraFolderData[next_folder_id]->m_nSubIconId = -1;
917      strcpy( ExtraFolderData[next_folder_id]->m_szTitle, cputype_name(i) );
918      ExtraFolderData[next_folder_id++]->m_dwFlags = 0;
919      AddFolder(lpTemp);
920      map[i] = treeFolders[nFolder++];
921   }
922
923   for (jj = 0; jj < nGames; jj++)
924   {
925      int n;
926      machine_config drv;
927      expand_machine_driver(drivers[jj]->drv,&drv);
928      for (n = 0; n < MAX_CPU; n++)
929         if (drv.cpu[n].cpu_type != CPU_DUMMY)
930         {
931            // cpu type #'s are one-based
932            AddGame(map[drv.cpu[n].cpu_type],jj);
933         }
934   }
935}
936
937void CreateSoundFolders(int parent_index)
938{
939   int i,jj;
940   int nGames = driver_list_get_count(drivers);
941   int nFolder = numFolders;
942   LPTREEFOLDER lpFolder = treeFolders[parent_index];
943   LPTREEFOLDER map[SOUND_COUNT];
944
945   sndintrf_init(NULL);
946
947   // no games in top level folder
948   SetAllBits(lpFolder->m_lpGameBits,FALSE);
949
950   for (i=1;i<SOUND_COUNT;i++)
951   {
952      LPTREEFOLDER lpTemp;
953
954      // empty fields get filled in with SOUND_DUMMY, so check for this and
955      // don't add it
956      if (strcmp(sndtype_name(SOUND_DUMMY),sndtype_name(i)) == 0)
957         continue;
958
959      //dprintf("%i %s\n",i,sndtype_name(i));
960      lpTemp = NewFolder(sndtype_name(i), next_folder_id, parent_index, IDI_SOUND,
961                      GetFolderFlags(numFolders));
962      ExtraFolderData[next_folder_id] = malloc(sizeof(EXFOLDERDATA) );
963      memset(ExtraFolderData[next_folder_id], 0, sizeof(EXFOLDERDATA));
964
965      ExtraFolderData[next_folder_id]->m_nFolderId = next_folder_id;
966      ExtraFolderData[next_folder_id]->m_nIconId = IDI_SOUND;
967      ExtraFolderData[next_folder_id]->m_nParent = lpFolder->m_nFolderId;
968      ExtraFolderData[next_folder_id]->m_nSubIconId = -1;
969      strcpy( ExtraFolderData[next_folder_id]->m_szTitle, sndtype_name(i) );
970      ExtraFolderData[next_folder_id++]->m_dwFlags = 0;
971      AddFolder(lpTemp);
972      map[i] = treeFolders[nFolder++];
973   }
974
975   for (jj = 0; jj < nGames; jj++)
976   {
977      int n;
978      machine_config drv;
979      expand_machine_driver(drivers[jj]->drv,&drv);
980     
981      for (n = 0; n < MAX_SOUND; n++)
982         if (drv.sound[n].sound_type != SOUND_DUMMY)
983         {
984            // sound type #'s are one-based, though that doesn't affect us here
985            AddGame(map[drv.sound[n].sound_type],jj);
986         }
987   }
988
989}
990
991void CreateOrientationFolders(int parent_index)
992{
993   int jj;
994   int nGames = driver_list_get_count(drivers);
995   LPTREEFOLDER lpFolder = treeFolders[parent_index];
996
997   // create our two subfolders
998   LPTREEFOLDER lpVert, lpHorz;
999   lpVert = NewFolder("Vertical", next_folder_id, parent_index, IDI_FOLDER,
1000                   GetFolderFlags(numFolders));
1001   ExtraFolderData[next_folder_id] = malloc(sizeof(EXFOLDERDATA) );
1002   memset(ExtraFolderData[next_folder_id], 0, sizeof(EXFOLDERDATA));
1003
1004   ExtraFolderData[next_folder_id]->m_nFolderId = next_folder_id;
1005   ExtraFolderData[next_folder_id]->m_nIconId = IDI_FOLDER;
1006   ExtraFolderData[next_folder_id]->m_nParent = lpFolder->m_nFolderId;
1007   ExtraFolderData[next_folder_id]->m_nSubIconId = -1;
1008   strcpy( ExtraFolderData[next_folder_id]->m_szTitle, "Vertical" );
1009   ExtraFolderData[next_folder_id++]->m_dwFlags = 0;
1010   AddFolder(lpVert);
1011   lpHorz = NewFolder("Horizontal", next_folder_id, parent_index, IDI_FOLDER,
1012                   GetFolderFlags(numFolders));
1013   ExtraFolderData[next_folder_id] = malloc(sizeof(EXFOLDERDATA) );
1014   memset(ExtraFolderData[next_folder_id], 0, sizeof(EXFOLDERDATA));
1015
1016   ExtraFolderData[next_folder_id]->m_nFolderId = next_folder_id;
1017   ExtraFolderData[next_folder_id]->m_nIconId = IDI_FOLDER;
1018   ExtraFolderData[next_folder_id]->m_nParent = lpFolder->m_nFolderId;
1019   ExtraFolderData[next_folder_id]->m_nSubIconId = -1;
1020   strcpy( ExtraFolderData[next_folder_id]->m_szTitle, "Horizontal" );
1021   ExtraFolderData[next_folder_id++]->m_dwFlags = 0;
1022   AddFolder(lpHorz);
1023
1024   // no games in top level folder
1025   SetAllBits(lpFolder->m_lpGameBits,FALSE);
1026
1027   for (jj = 0; jj < nGames; jj++)
1028   {
1029      if (drivers[jj]->flags & ORIENTATION_SWAP_XY)
1030      {
1031         AddGame(lpVert,jj);
1032      }
1033      else
1034      {
1035         AddGame(lpHorz,jj);
1036      }
1037   }
1038}
1039
1040void CreateDeficiencyFolders(int parent_index)
1041{
1042   int jj;
1043   int nGames = driver_list_get_count(drivers);
1044   LPTREEFOLDER lpFolder = treeFolders[parent_index];
1045
1046   // create our two subfolders
1047   LPTREEFOLDER lpProt, lpWrongCol, lpImpCol, lpImpGraph, lpMissSnd, lpImpSnd, lpFlip;
1048   lpProt = NewFolder("Unemulated Protection", next_folder_id, parent_index, IDI_FOLDER,
1049                   GetFolderFlags(numFolders));
1050   ExtraFolderData[next_folder_id] = malloc(sizeof(EXFOLDERDATA) );
1051   memset(ExtraFolderData[next_folder_id], 0, sizeof(EXFOLDERDATA));
1052
1053   ExtraFolderData[next_folder_id]->m_nFolderId = next_folder_id;
1054   ExtraFolderData[next_folder_id]->m_nIconId = IDI_FOLDER;
1055   ExtraFolderData[next_folder_id]->m_nParent = lpFolder->m_nFolderId;
1056   ExtraFolderData[next_folder_id]->m_nSubIconId = -1;
1057   strcpy( ExtraFolderData[next_folder_id]->m_szTitle, "Unemulated Protection" );
1058   ExtraFolderData[next_folder_id++]->m_dwFlags = 0;
1059   AddFolder(lpProt);
1060   lpWrongCol = NewFolder("Wrong Colors", next_folder_id, parent_index, IDI_FOLDER,
1061                   GetFolderFlags(numFolders));
1062   ExtraFolderData[next_folder_id] = malloc(sizeof(EXFOLDERDATA) );
1063   memset(ExtraFolderData[next_folder_id], 0, sizeof(EXFOLDERDATA));
1064
1065   ExtraFolderData[next_folder_id]->m_nFolderId = next_folder_id;
1066   ExtraFolderData[next_folder_id]->m_nIconId = IDI_FOLDER;
1067   ExtraFolderData[next_folder_id]->m_nParent = lpFolder->m_nFolderId;
1068   ExtraFolderData[next_folder_id]->m_nSubIconId = -1;
1069   strcpy( ExtraFolderData[next_folder_id]->m_szTitle, "Wrong Colors" );
1070   ExtraFolderData[next_folder_id++]->m_dwFlags = 0;
1071   AddFolder(lpWrongCol);
1072
1073   lpImpCol = NewFolder("Imperfect Colors", next_folder_id, parent_index, IDI_FOLDER,
1074                   GetFolderFlags(numFolders));
1075   ExtraFolderData[next_folder_id] = malloc(sizeof(EXFOLDERDATA) );
1076   memset(ExtraFolderData[next_folder_id], 0, sizeof(EXFOLDERDATA));
1077
1078   ExtraFolderData[next_folder_id]->m_nFolderId = next_folder_id;
1079   ExtraFolderData[next_folder_id]->m_nIconId = IDI_FOLDER;
1080   ExtraFolderData[next_folder_id]->m_nParent = lpFolder->m_nFolderId;
1081   ExtraFolderData[next_folder_id]->m_nSubIconId = -1;
1082   strcpy( ExtraFolderData[next_folder_id]->m_szTitle, "Imperfect Colors" );
1083   ExtraFolderData[next_folder_id++]->m_dwFlags = 0;
1084   AddFolder(lpImpCol);
1085
1086   lpImpGraph = NewFolder("Imperfect Graphics", next_folder_id, parent_index, IDI_FOLDER,
1087                   GetFolderFlags(numFolders));
1088   ExtraFolderData[next_folder_id] = malloc(sizeof(EXFOLDERDATA) );
1089   memset(ExtraFolderData[next_folder_id], 0, sizeof(EXFOLDERDATA));
1090
1091   ExtraFolderData[next_folder_id]->m_nFolderId = next_folder_id;
1092   ExtraFolderData[next_folder_id]->m_nIconId = IDI_FOLDER;
1093   ExtraFolderData[next_folder_id]->m_nParent = lpFolder->m_nFolderId;
1094   ExtraFolderData[next_folder_id]->m_nSubIconId = -1;
1095   strcpy( ExtraFolderData[next_folder_id]->m_szTitle, "Imperfect Graphics" );
1096   ExtraFolderData[next_folder_id++]->m_dwFlags = 0;
1097   AddFolder(lpImpGraph);
1098
1099   lpMissSnd = NewFolder("Missing Sound", next_folder_id, parent_index, IDI_FOLDER,
1100                   GetFolderFlags(numFolders));
1101   ExtraFolderData[next_folder_id] = malloc(sizeof(EXFOLDERDATA) );
1102   memset(ExtraFolderData[next_folder_id], 0, sizeof(EXFOLDERDATA));
1103
1104   ExtraFolderData[next_folder_id]->m_nFolderId = next_folder_id;
1105   ExtraFolderData[next_folder_id]->m_nIconId = IDI_FOLDER;
1106   ExtraFolderData[next_folder_id]->m_nParent = lpFolder->m_nFolderId;
1107   ExtraFolderData[next_folder_id]->m_nSubIconId = -1;
1108   strcpy( ExtraFolderData[next_folder_id]->m_szTitle, "Missing Sound" );
1109   ExtraFolderData[next_folder_id++]->m_dwFlags = 0;
1110   AddFolder(lpMissSnd);
1111
1112   lpImpSnd = NewFolder("Imperfect Sound", next_folder_id, parent_index, IDI_FOLDER,
1113                   GetFolderFlags(numFolders));
1114   ExtraFolderData[next_folder_id] = malloc(sizeof(EXFOLDERDATA) );
1115   memset(ExtraFolderData[next_folder_id], 0, sizeof(EXFOLDERDATA));
1116
1117   ExtraFolderData[next_folder_id]->m_nFolderId = next_folder_id;
1118   ExtraFolderData[next_folder_id]->m_nIconId = IDI_FOLDER;
1119   ExtraFolderData[next_folder_id]->m_nParent = lpFolder->m_nFolderId;
1120   ExtraFolderData[next_folder_id]->m_nSubIconId = -1;
1121   strcpy( ExtraFolderData[next_folder_id]->m_szTitle, "Imperfect Sound" );
1122   ExtraFolderData[next_folder_id++]->m_dwFlags = 0;
1123   AddFolder(lpImpSnd);
1124
1125   lpFlip = NewFolder("No Cocktail", next_folder_id, parent_index, IDI_FOLDER,
1126                   GetFolderFlags(numFolders));
1127   ExtraFolderData[next_folder_id] = malloc(sizeof(EXFOLDERDATA) );
1128   memset(ExtraFolderData[next_folder_id], 0, sizeof(EXFOLDERDATA));
1129
1130   ExtraFolderData[next_folder_id]->m_nFolderId = next_folder_id;
1131   ExtraFolderData[next_folder_id]->m_nIconId = IDI_FOLDER;
1132   ExtraFolderData[next_folder_id]->m_nParent = lpFolder->m_nFolderId;
1133   ExtraFolderData[next_folder_id]->m_nSubIconId = -1;
1134   strcpy( ExtraFolderData[next_folder_id]->m_szTitle, "No Cocktail" );
1135   ExtraFolderData[next_folder_id++]->m_dwFlags = 0;
1136   AddFolder(lpFlip);
1137
1138   // no games in top level folder
1139   SetAllBits(lpFolder->m_lpGameBits,FALSE);
1140
1141   for (jj = 0; jj < nGames; jj++)
1142   {
1143      if (drivers[jj]->flags & GAME_WRONG_COLORS)
1144      {
1145         AddGame(lpWrongCol,jj);
1146      }
1147      if (drivers[jj]->flags & GAME_UNEMULATED_PROTECTION)
1148      {
1149         AddGame(lpProt,jj);
1150      }
1151      if (drivers[jj]->flags & GAME_IMPERFECT_COLORS)
1152      {
1153         AddGame(lpImpCol,jj);
1154      }
1155      if (drivers[jj]->flags & GAME_IMPERFECT_GRAPHICS)
1156      {
1157         AddGame(lpImpGraph,jj);
1158      }
1159      if (drivers[jj]->flags & GAME_NO_SOUND)
1160      {
1161         AddGame(lpMissSnd,jj);
1162      }
1163      if (drivers[jj]->flags & GAME_IMPERFECT_SOUND)
1164      {
1165         AddGame(lpImpSnd,jj);
1166      }
1167      if (drivers[jj]->flags & GAME_NO_COCKTAIL)
1168      {
1169         AddGame(lpFlip,jj);
1170      }
1171   }
1172}
1173
1174void CreateDumpingFolders(int parent_index)
1175{
1176   int jj;
1177   BOOL bBadDump  = FALSE;
1178   BOOL bNoDump = FALSE;
1179   int nGames = driver_list_get_count(drivers);
1180   LPTREEFOLDER lpFolder = treeFolders[parent_index];
1181   const rom_entry *region, *rom;
1182   const char *name;
1183   const game_driver *gamedrv;
1184
1185   // create our two subfolders
1186   LPTREEFOLDER lpBad, lpNo;
1187   lpBad = NewFolder("Bad Dump", next_folder_id, parent_index, IDI_FOLDER,
1188                   GetFolderFlags(numFolders));
1189   ExtraFolderData[next_folder_id] = malloc(sizeof(EXFOLDERDATA) );
1190   memset(ExtraFolderData[next_folder_id], 0, sizeof(EXFOLDERDATA));
1191
1192   ExtraFolderData[next_folder_id]->m_nFolderId = next_folder_id;
1193   ExtraFolderData[next_folder_id]->m_nIconId = IDI_FOLDER;
1194   ExtraFolderData[next_folder_id]->m_nParent = lpFolder->m_nFolderId;
1195   ExtraFolderData[next_folder_id]->m_nSubIconId = -1;
1196   strcpy( ExtraFolderData[next_folder_id]->m_szTitle, "Bad Dump" );
1197   ExtraFolderData[next_folder_id++]->m_dwFlags = 0;
1198   AddFolder(lpBad);
1199   lpNo = NewFolder("No Dump", next_folder_id, parent_index, IDI_FOLDER,
1200                   GetFolderFlags(numFolders));
1201   ExtraFolderData[next_folder_id] = malloc(sizeof(EXFOLDERDATA) );
1202   memset(ExtraFolderData[next_folder_id], 0, sizeof(EXFOLDERDATA));
1203
1204   ExtraFolderData[next_folder_id]->m_nFolderId = next_folder_id;
1205   ExtraFolderData[next_folder_id]->m_nIconId = IDI_FOLDER;
1206   ExtraFolderData[next_folder_id]->m_nParent = lpFolder->m_nFolderId;
1207   ExtraFolderData[next_folder_id]->m_nSubIconId = -1;
1208   strcpy( ExtraFolderData[next_folder_id]->m_szTitle, "No Dump" );
1209   ExtraFolderData[next_folder_id++]->m_dwFlags = 0;
1210   AddFolder(lpNo);
1211
1212   // no games in top level folder
1213   SetAllBits(lpFolder->m_lpGameBits,FALSE);
1214
1215   for (jj = 0; jj < nGames; jj++)
1216   {
1217      gamedrv = drivers[jj];
1218
1219      if (!gamedrv->rom)
1220         continue;
1221      bBadDump = FALSE;
1222      bNoDump = FALSE;
1223      for (region = rom_first_region(gamedrv); region; region = rom_next_region(region))
1224      {
1225         for (rom = rom_first_file(region); rom; rom = rom_next_file(rom))
1226         {
1227            if (ROMREGION_ISROMDATA(region) || ROMREGION_ISDISKDATA(region) )
1228            {
1229               name = ROM_GETNAME(rom);
1230               if (hash_data_has_info(ROM_GETHASHDATA(rom), HASH_INFO_BAD_DUMP))           
1231                  bBadDump = TRUE;
1232               if (hash_data_has_info(ROM_GETHASHDATA(rom), HASH_INFO_NO_DUMP))           
1233                  bNoDump = TRUE;
1234            }
1235         }
1236      }
1237      if (bBadDump)
1238      {
1239         AddGame(lpBad,jj);
1240      }
1241      if (bNoDump)
1242      {
1243         AddGame(lpNo,jj);
1244      }
1245   }
1246}
1247
1248
1249void CreateYearFolders(int parent_index)
1250{
1251   int i,jj;
1252   int nGames = driver_list_get_count(drivers);
1253   int start_folder = numFolders;
1254   LPTREEFOLDER lpFolder = treeFolders[parent_index];
1255
1256   // no games in top level folder
1257   SetAllBits(lpFolder->m_lpGameBits,FALSE);
1258
1259   for (jj = 0; jj < nGames; jj++)
1260   {
1261      char s[100];
1262      strcpy(s,drivers[jj]->year);
1263
1264      if (s[0] == '\0')
1265         continue;
1266
1267      if (s[4] == '?')
1268         s[4] = '\0';
1269     
1270      // look for an extant year treefolder for this game
1271      // (likely to be the previous one, so start at the end)
1272      for (i=numFolders-1;i>=start_folder;i--)
1273      {
1274         if (strncmp(treeFolders[i]->m_lpTitle,s,4) == 0)
1275         {
1276            AddGame(treeFolders[i],jj);
1277            break;
1278         }
1279      }
1280      if (i == start_folder-1)
1281      {
1282         // nope, it's a year we haven't seen before, make it.
1283         LPTREEFOLDER lpTemp;
1284         lpTemp = NewFolder(s, next_folder_id, parent_index, IDI_YEAR,
1285                         GetFolderFlags(numFolders));
1286         ExtraFolderData[next_folder_id] = malloc(sizeof(EXFOLDERDATA) );
1287         memset(ExtraFolderData[next_folder_id], 0, sizeof(EXFOLDERDATA));
1288
1289         ExtraFolderData[next_folder_id]->m_nFolderId = next_folder_id;
1290         ExtraFolderData[next_folder_id]->m_nIconId = IDI_YEAR;
1291         ExtraFolderData[next_folder_id]->m_nParent = lpFolder->m_nFolderId;
1292         ExtraFolderData[next_folder_id]->m_nSubIconId = -1;
1293         strcpy( ExtraFolderData[next_folder_id]->m_szTitle, s );
1294         ExtraFolderData[next_folder_id++]->m_dwFlags = 0;
1295         AddFolder(lpTemp);
1296         AddGame(lpTemp,jj);
1297      }
1298   }
1299}
1300
1301// creates child folders of all the top level folders, including custom ones
1302void CreateAllChildFolders(void)
1303{
1304   int num_top_level_folders = numFolders;
1305   int i, j;
1306
1307   for (i = 0; i < num_top_level_folders; i++)
1308   {
1309      LPTREEFOLDER lpFolder = treeFolders[i];
1310      LPFOLDERDATA lpFolderData = NULL;
1311
1312      for (j = 0; g_lpFolderData[j].m_lpTitle; j++)
1313      {
1314         if (g_lpFolderData[j].m_nFolderId == lpFolder->m_nFolderId)
1315         {
1316            lpFolderData = &g_lpFolderData[j];
1317            break;
1318         }
1319      }
1320
1321      if (lpFolderData != NULL)
1322      {
1323         //dprintf("Found built-in-folder id %i %i",i,lpFolder->m_nFolderId);
1324         if (lpFolderData->m_pfnCreateFolders != NULL)
1325            lpFolderData->m_pfnCreateFolders(i);
1326      }
1327      else
1328      {
1329         if ((lpFolder->m_dwFlags & F_CUSTOM) == 0)
1330         {
1331            dprintf("Internal inconsistency with non-built-in folder, but not custom");
1332            continue;
1333         }
1334
1335         //dprintf("Loading custom folder %i %i",i,lpFolder->m_nFolderId);
1336
1337         // load the extra folder files, which also adds children
1338         if (TryAddExtraFolderAndChildren(i) == FALSE)
1339         {
1340            lpFolder->m_nFolderId = FOLDER_NONE;
1341         }
1342      }
1343   }
1344}
1345
1346// adds these folders to the treeview
1347void ResetTreeViewFolders(void)
1348{
1349   HWND hTreeView = GetTreeView();
1350   int i;
1351   TVITEM tvi;
1352   TVINSERTSTRUCT   tvs;
1353
1354   HTREEITEM shti; // for current child branches
1355
1356   // currently "cached" parent
1357   HTREEITEM hti_parent = NULL;
1358   int index_parent = -1;         
1359
1360   TreeView_DeleteAllItems(hTreeView);
1361
1362   //dprintf("Adding folders to tree ui indices %i to %i",start_index,end_index);
1363
1364   tvs.hInsertAfter = TVI_SORT;
1365
1366   for (i=0;i<numFolders;i++)
1367   {
1368      LPTREEFOLDER lpFolder = treeFolders[i];
1369
1370      if (lpFolder->m_nParent == -1)
1371      {
1372         if (lpFolder->m_nFolderId < MAX_FOLDERS)
1373         {
1374            // it's a built in folder, let's see if we should show it
1375            if (GetShowFolder(lpFolder->m_nFolderId) == FALSE)
1376            {
1377               continue;
1378            }
1379         }
1380
1381         tvi.mask   = TVIF_TEXT | TVIF_PARAM | TVIF_IMAGE | TVIF_SELECTEDIMAGE;
1382         tvs.hParent = TVI_ROOT;
1383         tvi.pszText = lpFolder->m_lptTitle;
1384         tvi.lParam   = (LPARAM)lpFolder;
1385         tvi.iImage   = GetTreeViewIconIndex(lpFolder->m_nIconId);
1386         tvi.iSelectedImage = 0;
1387
1388#if defined(__GNUC__) /* bug in commctrl.h */
1389         tvs.item = tvi;
1390#else
1391         tvs.DUMMYUNIONNAME.item = tvi;
1392#endif
1393
1394         // Add root branch
1395         hti_parent = TreeView_InsertItem(hTreeView, &tvs);
1396
1397         continue;
1398      }
1399
1400      // not a top level branch, so look for parent
1401      if (treeFolders[i]->m_nParent != index_parent)
1402      {
1403         
1404         hti_parent = TreeView_GetRoot(hTreeView);
1405         while (1)
1406         {
1407            if (hti_parent == NULL)
1408            {
1409               // couldn't find parent folder, so it's a built-in but
1410               // not shown folder
1411               break;
1412            }
1413
1414            tvi.hItem = hti_parent;
1415            tvi.mask = TVIF_PARAM;
1416            TreeView_GetItem(hTreeView,&tvi);
1417            if (((LPTREEFOLDER)tvi.lParam) == treeFolders[treeFolders[i]->m_nParent])
1418               break;
1419
1420            hti_parent = TreeView_GetNextSibling(hTreeView,hti_parent);
1421         }
1422
1423         // if parent is not shown, then don't show the child either obviously!
1424         if (hti_parent == NULL)
1425            continue;
1426
1427         index_parent = treeFolders[i]->m_nParent;
1428      }
1429
1430      tvi.mask   = TVIF_TEXT | TVIF_PARAM | TVIF_IMAGE | TVIF_SELECTEDIMAGE;
1431      tvs.hParent = hti_parent;
1432      tvi.iImage   = GetTreeViewIconIndex(treeFolders[i]->m_nIconId);
1433      tvi.iSelectedImage = 0;
1434      tvi.pszText = treeFolders[i]->m_lptTitle;
1435      tvi.lParam   = (LPARAM)treeFolders[i];
1436     
1437#if defined(__GNUC__) /* bug in commctrl.h */
1438      tvs.item = tvi;
1439#else
1440      tvs.DUMMYUNIONNAME.item = tvi;
1441#endif
1442      // Add it to this tree branch
1443      shti = TreeView_InsertItem(hTreeView, &tvs);
1444
1445   }
1446}
1447
1448void SelectTreeViewFolder(int folder_id)
1449{
1450   HWND hTreeView = GetTreeView();
1451   HTREEITEM hti;
1452   TVITEM tvi;
1453
1454   memset(&tvi,0,sizeof(tvi));
1455
1456   hti = TreeView_GetRoot(hTreeView);
1457
1458   while (hti != NULL)
1459   {
1460      HTREEITEM hti_next;
1461
1462      tvi.hItem = hti;
1463      tvi.mask = TVIF_PARAM;
1464      TreeView_GetItem(hTreeView,&tvi);
1465
1466      if (((LPTREEFOLDER)tvi.lParam)->m_nFolderId == folder_id)
1467      {
1468         TreeView_SelectItem(hTreeView,tvi.hItem);
1469         SetCurrentFolder((LPTREEFOLDER)tvi.lParam);
1470         return;
1471      }
1472     
1473      hti_next = TreeView_GetChild(hTreeView,hti);
1474      if (hti_next == NULL)
1475      {
1476         hti_next = TreeView_GetNextSibling(hTreeView,hti);
1477         if (hti_next == NULL)
1478         {
1479            hti_next = TreeView_GetParent(hTreeView,hti);
1480            if (hti_next != NULL)
1481               hti_next = TreeView_GetNextSibling(hTreeView,hti_next);
1482         }
1483      }
1484      hti = hti_next;
1485   }
1486
1487   // could not find folder to select
1488   // make sure we select something
1489   tvi.hItem = TreeView_GetRoot(hTreeView);
1490   tvi.mask = TVIF_PARAM;
1491   TreeView_GetItem(hTreeView,&tvi);
1492
1493   TreeView_SelectItem(hTreeView,tvi.hItem);
1494   SetCurrentFolder((LPTREEFOLDER)tvi.lParam);
1495
1496}
1497
1498/* Add a folder to the list.  Does not allocate */
1499static BOOL AddFolder(LPTREEFOLDER lpFolder)
1500{
1501   if (numFolders + 1 >= folderArrayLength)
1502   {
1503      folderArrayLength += 500;
1504      treeFolders = realloc(treeFolders,sizeof(TREEFOLDER **) * folderArrayLength);
1505   }
1506
1507   treeFolders[numFolders] = lpFolder;
1508   numFolders++;
1509
1510   return TRUE;
1511}
1512
1513/* Allocate and initialize a NEW TREEFOLDER */
1514static LPTREEFOLDER NewFolder(const char *lpTitle,
1515                  UINT nFolderId, int nParent, UINT nIconId, DWORD dwFlags)
1516{
1517   LPTREEFOLDER lpFolder = (LPTREEFOLDER)malloc(sizeof(TREEFOLDER));
1518
1519   memset(lpFolder, '\0', sizeof (TREEFOLDER));
1520   lpFolder->m_lpTitle = (LPSTR)malloc(strlen(lpTitle) + 1);
1521   strcpy((char *)lpFolder->m_lpTitle,lpTitle);
1522   lpFolder->m_lptTitle = tstring_from_utf8(lpFolder->m_lpTitle);
1523   lpFolder->m_lpGameBits = NewBits(driver_list_get_count(drivers));
1524   lpFolder->m_nFolderId = nFolderId;
1525   lpFolder->m_nParent = nParent;
1526   lpFolder->m_nIconId = nIconId;
1527   lpFolder->m_dwFlags = dwFlags;
1528
1529   return lpFolder;
1530}
1531
1532/* Deallocate the passed in LPTREEFOLDER */
1533static void DeleteFolder(LPTREEFOLDER lpFolder)
1534{
1535   if (lpFolder)
1536   {
1537      if (lpFolder->m_lpGameBits)
1538      {
1539         DeleteBits(lpFolder->m_lpGameBits);
1540         lpFolder->m_lpGameBits = 0;
1541      }
1542      free(lpFolder->m_lptTitle);
1543      lpFolder->m_lptTitle = 0;
1544      free(lpFolder->m_lpTitle);
1545      lpFolder->m_lpTitle = 0;
1546      free(lpFolder);
1547      lpFolder = 0;
1548   }
1549}
1550
1551/* Can be called to re-initialize the array of treeFolders */
1552BOOL InitFolders(void)
1553{
1554   int          i = 0;
1555   DWORD         dwFolderFlags;
1556   LPFOLDERDATA   fData = 0;
1557
1558   if (treeFolders != NULL)
1559   {
1560      for (i = numFolders - 1; i >= 0; i--)
1561      {
1562         DeleteFolder(treeFolders[i]);
1563         treeFolders[i] = 0;
1564         numFolders--;
1565      }
1566   }
1567   numFolders = 0;
1568   if (folderArrayLength == 0)
1569   {
1570      folderArrayLength = 200;
1571      treeFolders = (TREEFOLDER **)malloc(sizeof(TREEFOLDER **) * folderArrayLength);
1572      if (!treeFolders)
1573      {
1574         folderArrayLength = 0;
1575         return 0;
1576      }
1577      else
1578      {
1579         memset(treeFolders,'\0', sizeof(TREEFOLDER **) * folderArrayLength);
1580      }
1581   }
1582   // built-in top level folders
1583   for (i = 0; g_lpFolderData[i].m_lpTitle; i++)
1584   {
1585      fData = &g_lpFolderData[i];
1586      /* get the saved folder flags */
1587      dwFolderFlags = GetFolderFlags(numFolders);
1588      /* create the folder */
1589      AddFolder(NewFolder(fData->m_lpTitle, fData->m_nFolderId, -1,
1590                     fData->m_nIconId, dwFolderFlags));
1591   }
1592   
1593   numExtraFolders = InitExtraFolders();
1594
1595   for (i = 0; i < numExtraFolders; i++)
1596   {
1597      LPEXFOLDERDATA  fExData = ExtraFolderData[i];
1598
1599      // OR in the saved folder flags
1600      dwFolderFlags = fExData->m_dwFlags | GetFolderFlags(numFolders);
1601      // create the folder
1602      //dprintf("creating top level custom folder with icon %i",fExData->m_nIconId);
1603      AddFolder(NewFolder(fExData->m_szTitle,fExData->m_nFolderId,fExData->m_nParent,
1604                     fExData->m_nIconId,dwFolderFlags));
1605   }
1606
1607   CreateAllChildFolders();
1608
1609   CreateTreeIcons();
1610
1611   ResetWhichGamesInFolders();
1612
1613   ResetTreeViewFolders();
1614
1615   SelectTreeViewFolder(GetSavedFolderID());
1616
1617   return TRUE;
1618}
1619
1620// create iconlist and Treeview control
1621static BOOL CreateTreeIcons()
1622{
1623   HICON   hIcon;
1624   INT    i;
1625   HINSTANCE hInst = GetModuleHandle(0);
1626
1627   int numIcons = ICON_MAX + numExtraIcons;
1628
1629   hTreeSmall = ImageList_Create (16, 16, ILC_COLORDDB | ILC_MASK, numIcons, numIcons);
1630
1631   //dprintf("Trying to load %i normal icons",ICON_MAX);
1632   for (i = 0; i < ICON_MAX; i++)
1633   {
1634      hIcon = LoadIconFromFile(treeIconNames[i].lpName);
1635      if (!hIcon)
1636         hIcon = LoadIcon(hInst, MAKEINTRESOURCE(treeIconNames[i].nResourceID));
1637
1638      if (ImageList_AddIcon (hTreeSmall, hIcon) == -1)
1639      {
1640         ErrorMsg("Error creating icon on regular folder, %i %i",i,hIcon != NULL);
1641         return FALSE;
1642      }
1643   }
1644
1645   //dprintf("Trying to load %i extra custom-folder icons",numExtraIcons);
1646   for (i = 0; i < numExtraIcons; i++)
1647   {
1648      if ((hIcon = LoadIconFromFile(ExtraFolderIcons[i])) == 0)
1649         hIcon = LoadIcon (hInst, MAKEINTRESOURCE(IDI_FOLDER));
1650
1651      if (ImageList_AddIcon(hTreeSmall, hIcon) == -1)
1652      {
1653         ErrorMsg("Error creating icon on extra folder, %i %i",i,hIcon != NULL);
1654         return FALSE;
1655      }
1656   }
1657
1658   // Be sure that all the small icons were added.
1659   if (ImageList_GetImageCount(hTreeSmall) < numIcons)
1660   {
1661      ErrorMsg("Error with icon list--too few images.  %i %i",
1662            ImageList_GetImageCount(hTreeSmall),numIcons);
1663      return FALSE;
1664   }
1665
1666   // Be sure that all the small icons were added.
1667
1668   if (ImageList_GetImageCount (hTreeSmall) < ICON_MAX)
1669   {
1670      ErrorMsg("Error with icon list--too few images.  %i < %i",
1671             ImageList_GetImageCount(hTreeSmall),ICON_MAX);
1672      return FALSE;
1673   }
1674
1675   // Associate the image lists with the list view control.
1676   (void) TreeView_SetImageList(GetTreeView(), hTreeSmall, TVSIL_NORMAL);
1677
1678   return TRUE;
1679}
1680
1681
1682static void TreeCtrlOnPaint(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
1683{
1684   PAINTSTRUCT ps;
1685   HDC       hDC;
1686   RECT      rcClip, rcClient;
1687   HDC       memDC;
1688   HBITMAP    bitmap;
1689   HBITMAP    hOldBitmap;
1690
1691   HBITMAP hBackground = GetBackgroundBitmap();
1692   MYBITMAPINFO *bmDesc = GetBackgroundInfo();
1693
1694   hDC = BeginPaint(hWnd, &ps);
1695
1696   GetClipBox(hDC, &rcClip);
1697   GetClientRect(hWnd, &rcClient);
1698   
1699   // Create a compatible memory DC
1700   memDC = CreateCompatibleDC(hDC);
1701
1702   // Select a compatible bitmap into the memory DC
1703   bitmap = CreateCompatibleBitmap(hDC, rcClient.right - rcClient.left,
1704                           rcClient.bottom - rcClient.top);
1705   hOldBitmap = SelectObject(memDC, bitmap);
1706   
1707   // First let the control do its default drawing.
1708   CallWindowProc(g_lpTreeWndProc, hWnd, uMsg, (WPARAM)memDC, 0);
1709
1710   // Draw bitmap in the background
1711
1712   {
1713      HPALETTE hPAL;       
1714      HDC maskDC;
1715      HBITMAP maskBitmap;
1716      HDC tempDC;
1717      HDC imageDC;
1718      HBITMAP bmpImage;
1719      HBITMAP hOldBmpImage;
1720      HBITMAP hOldMaskBitmap;
1721      HBITMAP hOldHBitmap;
1722      int i, j;
1723      RECT rcRoot;
1724
1725      // Now create a mask
1726      maskDC = CreateCompatibleDC(hDC);   
1727     
1728      // Create monochrome bitmap for the mask
1729      maskBitmap = CreateBitmap(rcClient.right - rcClient.left,
1730                          rcClient.bottom - rcClient.top,
1731                          1, 1, NULL);
1732
1733      hOldMaskBitmap = SelectObject(maskDC, maskBitmap);
1734      SetBkColor(memDC, GetSysColor(COLOR_WINDOW));
1735
1736      // Create the mask from the memory DC
1737      BitBlt(maskDC, 0, 0, rcClient.right - rcClient.left,
1738            rcClient.bottom - rcClient.top, memDC,
1739            rcClient.left, rcClient.top, SRCCOPY);
1740
1741      tempDC = CreateCompatibleDC(hDC);
1742      hOldHBitmap = SelectObject(tempDC, hBackground);
1743
1744      imageDC = CreateCompatibleDC(hDC);
1745      bmpImage = CreateCompatibleBitmap(hDC,
1746                                rcClient.right - rcClient.left,
1747                                rcClient.bottom - rcClient.top);
1748      hOldBmpImage = SelectObject(imageDC, bmpImage);
1749
1750      hPAL = GetBackgroundPalette();
1751      if (hPAL == NULL)
1752         hPAL = CreateHalftonePalette(hDC);
1753
1754      if (GetDeviceCaps(hDC, RASTERCAPS) & RC_PALETTE && hPAL != NULL)
1755      {
1756         SelectPalette(hDC, hPAL, FALSE);
1757         RealizePalette(hDC);
1758         SelectPalette(imageDC, hPAL, FALSE);
1759      }
1760     
1761      // Get x and y offset
1762      TreeView_GetItemRect(hWnd, TreeView_GetRoot(hWnd), &rcRoot, FALSE);
1763      rcRoot.left = -GetScrollPos(hWnd, SB_HORZ);
1764
1765      // Draw bitmap in tiled manner to imageDC
1766      for (i = rcRoot.left; i < rcClient.right; i += bmDesc->bmWidth)
1767         for (j = rcRoot.top; j < rcClient.bottom; j += bmDesc->bmHeight)
1768            BitBlt(imageDC,  i, j, bmDesc->bmWidth, bmDesc->bmHeight,
1769                  tempDC, 0, 0, SRCCOPY);
1770
1771      // Set the background in memDC to black. Using SRCPAINT with black and any other
1772      // color results in the other color, thus making black the transparent color
1773      SetBkColor(memDC, RGB(0,0,0));
1774      SetTextColor(memDC, RGB(255,255,255));
1775      BitBlt(memDC, rcClip.left, rcClip.top, rcClip.right - rcClip.left,
1776            rcClip.bottom - rcClip.top,
1777            maskDC, rcClip.left, rcClip.top, SRCAND);
1778
1779      // Set the foreground to black. See comment above.
1780      SetBkColor(imageDC, RGB(255,255,255));
1781      SetTextColor(imageDC, RGB(0,0,0));
1782      BitBlt(imageDC, rcClip.left, rcClip.top, rcClip.right - rcClip.left,
1783            rcClip.bottom - rcClip.top,
1784            maskDC, rcClip.left, rcClip.top, SRCAND);
1785
1786      // Combine the foreground with the background
1787      BitBlt(imageDC, rcClip.left, rcClip.top, rcClip.right - rcClip.left,
1788            rcClip.bottom - rcClip.top,
1789            memDC, rcClip.left, rcClip.top, SRCPAINT);
1790
1791      // Draw the final image to the screen
1792      BitBlt(hDC, rcClip.left, rcClip.top, rcClip.right - rcClip.left,
1793            rcClip.bottom - rcClip.top,
1794            imageDC, rcClip.left, rcClip.top, SRCCOPY);
1795     
1796      SelectObject(maskDC, hOldMaskBitmap);
1797      SelectObject(tempDC, hOldHBitmap);
1798      SelectObject(imageDC, hOldBmpImage);
1799
1800      DeleteDC(maskDC);
1801      DeleteDC(imageDC);
1802      DeleteDC(tempDC);
1803      DeleteObject(bmpImage);
1804      DeleteObject(maskBitmap);
1805
1806      if (GetBackgroundPalette() == NULL)
1807      {
1808         DeleteObject(hPAL);
1809         hPAL = 0;
1810      }
1811   }
1812
1813   SelectObject(memDC, hOldBitmap);
1814   DeleteObject(bitmap);
1815   DeleteDC(memDC);
1816   EndPaint(hWnd, &ps);
1817   ReleaseDC(hWnd, hDC);
1818}
1819
1820/* Header code - Directional Arrows */
1821static LRESULT CALLBACK TreeWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
1822{
1823   if (GetBackgroundBitmap() != NULL)
1824   {
1825      switch (uMsg)
1826      {   
1827       case WM_MOUSEMOVE:
1828      {
1829         if (MouseHasBeenMoved())
1830            ShowCursor(TRUE);
1831         break;
1832      }
1833
1834      case WM_KEYDOWN :
1835         if (wParam == VK_F2)
1836         {
1837            if (lpCurrentFolder->m_dwFlags & F_CUSTOM)
1838            {
1839               TreeView_EditLabel(hWnd,TreeView_GetSelection(hWnd));
1840               return TRUE;
1841            }
1842         }
1843         break;
1844
1845      case WM_ERASEBKGND:
1846         return TRUE;
1847         break;
1848
1849      case WM_PAINT:
1850         TreeCtrlOnPaint(hWnd, uMsg, wParam, lParam);
1851         UpdateWindow(hWnd);
1852         break;
1853      }
1854   }
1855
1856   /* message not handled */
1857   return CallWindowProc(g_lpTreeWndProc, hWnd, uMsg, wParam, lParam);
1858}
1859
1860/*
1861 * Filter code - should be moved to filter.c/filter.h
1862 * Added 01/09/99 - MSH <mhaaland@hypertech.com>
1863 */
1864
1865/* find a FOLDERDATA by folderID */
1866LPFOLDERDATA FindFilter(DWORD folderID)
1867{
1868   int i;
1869
1870   for (i = 0; g_lpFolderData[i].m_lpTitle; i++)
1871   {
1872      if (g_lpFolderData[i].m_nFolderId == folderID)
1873         return &g_lpFolderData[i];
1874   }
1875   return (LPFOLDERDATA) 0;
1876}
1877
1878/***************************************************************************
1879    private structures
1880 ***************************************************************************/
1881
1882/***************************************************************************
1883    private functions prototypes
1884 ***************************************************************************/
1885
1886/***************************************************************************
1887    private functions
1888 ***************************************************************************/
1889
1890/**************************************************************************/
1891
1892LPTREEFOLDER GetFolderByName(int nParentId, const char *pszFolderName)
1893{
1894   int i = 0, nParent;
1895
1896   //First Get the Parent TreeviewItem
1897   //Enumerate Children
1898   for(i = 0; i < numFolders/* ||treeFolders[i] != NULL*/; i++)
1899   {
1900      if (!strcmp(treeFolders[i]->m_lpTitle, pszFolderName))
1901      {
1902         nParent = treeFolders[i]->m_nParent;
1903         if ((nParent >= 0) && treeFolders[nParent]->m_nFolderId == nParentId)
1904            return treeFolders[i];
1905      }
1906   }
1907   return NULL;
1908}
1909
1910static int InitExtraFolders(void)
1911{
1912   struct stat     stat_buffer;
1913   struct _finddata_t files;
1914   int             i, count = 0;
1915   long            hLong;
1916   char*           ext;
1917   char            buf[256];
1918   char            curdir[MAX_PATH];
1919   const char*     dir = GetFolderDir();
1920
1921   memset(ExtraFolderData, 0, (MAX_EXTRA_FOLDERS * MAX_EXTRA_SUBFOLDERS)* sizeof(LPEXFOLDERDATA));
1922
1923   /* NPW 9-Feb-2003 - MSVC stat() doesn't like stat() called with an empty
1924    * string
1925    */
1926   if (dir[0] == '\0')
1927      dir = ".";
1928
1929   if (stat(dir, &stat_buffer) != 0)
1930    {
1931      _mkdir(dir);
1932    }
1933
1934   _getcwd(curdir, MAX_PATH);
1935
1936   _chdir(dir);
1937
1938   hLong = _findfirst("*", &files);
1939
1940   for (i = 0; i < MAX_EXTRA_FOLDERS; i++)
1941    {
1942      ExtraFolderIcons[i] = NULL;
1943    }
1944
1945   numExtraIcons = 0;
1946
1947   while (!_findnext(hLong, &files))
1948   {
1949      if ((files.attrib & _A_SUBDIR) == 0)
1950      {
1951         FILE *fp;
1952
1953         fp = fopen(files.name, "r");
1954         if (fp != NULL)
1955         {
1956            int icon[2] = { 0, 0 };
1957            char *p, *name;
1958
1959            while (fgets(buf, 256, fp))
1960            {
1961               if (buf[0] == '[')
1962               {
1963                  p = strchr(buf, ']');
1964                  if (p == NULL)
1965                     continue;
1966
1967                  *p = '\0';
1968                  name = &buf[1];
1969                  if (!strcmp(name, "FOLDER_SETTINGS"))
1970                  {
1971                     while (fgets(buf, 256, fp))
1972                     {
1973                        name = strtok(buf, " =\r\n");
1974                        if (name == NULL)
1975                           break;
1976
1977                        if (!strcmp(name, "RootFolderIcon"))
1978                        {
1979                           name = strtok(NULL, " =\r\n");
1980                           if (name != NULL)
1981                              SetExtraIcons(name, &icon[0]);
1982                        }
1983                        if (!strcmp(name, "SubFolderIcon"))
1984                        {
1985                           name = strtok(NULL, " =\r\n");
1986                           if (name != NULL)
1987                              SetExtraIcons(name, &icon[1]);
1988                        }
1989                     }
1990                     break;
1991                  }
1992               }
1993            }
1994            fclose(fp);
1995
1996            strcpy(buf, files.name);
1997            ext = strrchr(buf, '.');
1998
1999            if (ext && *(ext + 1) && !mame_stricmp(ext + 1, "ini"))
2000            {
2001               ExtraFolderData[count] = malloc(sizeof(EXFOLDERDATA));
2002               if (ExtraFolderData[count])
2003               {
2004                  *ext = '\0';
2005
2006                  memset(ExtraFolderData[count], 0, sizeof(EXFOLDERDATA));
2007
2008                  strncpy(ExtraFolderData[count]->m_szTitle, buf, 63);
2009                  ExtraFolderData[count]->m_nFolderId   = next_folder_id++;
2010                  ExtraFolderData[count]->m_nParent     = -1;
2011                  ExtraFolderData[count]->m_dwFlags     = F_CUSTOM;
2012                  ExtraFolderData[count]->m_nIconId     = icon[0] ? -icon[0] : IDI_FOLDER;
2013                  ExtraFolderData[count]->m_nSubIconId  = icon[1] ? -icon[1] : IDI_FOLDER;
2014                  //dprintf("extra folder with icon %i, subicon %i",
2015                  //ExtraFolderData[count]->m_nIconId,
2016                  //ExtraFolderData[count]->m_nSubIconId);
2017                  count++;
2018               }
2019            }
2020         }
2021      }
2022   }
2023
2024   _chdir(curdir);
2025   return count;
2026}
2027
2028void FreeExtraFolders(void)
2029{
2030   int i;
2031
2032   for (i = 0; i < numExtraFolders; i++)
2033   {
2034      if (ExtraFolderData[i])
2035      {
2036         free(ExtraFolderData[i]);
2037         ExtraFolderData[i] = NULL;
2038      }
2039   }
2040
2041   for (i = 0; i < numExtraIcons; i++)
2042    {
2043      free(ExtraFolderIcons[i]);
2044    }
2045
2046   numExtraIcons = 0;
2047
2048}
2049
2050
2051static void SetExtraIcons(char *name, int *id)
2052{
2053   char *p = strchr(name, '.');
2054
2055   if (p != NULL)
2056      *p = '\0';
2057
2058   ExtraFolderIcons[numExtraIcons] = malloc(strlen(name) + 1);
2059   if (ExtraFolderIcons[numExtraIcons])
2060   {
2061      *id = ICON_MAX + numExtraIcons;
2062      strcpy(ExtraFolderIcons[numExtraIcons], name);
2063      numExtraIcons++;
2064   }
2065}
2066
2067
2068// Called to add child folders of the top level extra folders already created
2069BOOL TryAddExtraFolderAndChildren(int parent_index)
2070{
2071    FILE*   fp = NULL;
2072    char    fname[MAX_PATH];
2073    char    readbuf[256];
2074    char*   p;
2075    char*   name;
2076    int     id, current_id, i;
2077    LPTREEFOLDER lpTemp = NULL;
2078   LPTREEFOLDER lpFolder = treeFolders[parent_index];
2079
2080    current_id = lpFolder->m_nFolderId;
2081   
2082    id = lpFolder->m_nFolderId - MAX_FOLDERS;
2083
2084    /* "folder\title.ini" */
2085
2086    sprintf( fname, "%s\\%s.ini",
2087        GetFolderDir(),
2088        ExtraFolderData[id]->m_szTitle);
2089   
2090    fp = fopen(fname, "r");
2091    if (fp == NULL)
2092        return FALSE;
2093   
2094    while ( fgets(readbuf, 256, fp) )
2095    {
2096        /* do we have [...] ? */
2097
2098        if (readbuf[0] == '[')
2099        {
2100            p = strchr(readbuf, ']');
2101            if (p == NULL)
2102            {
2103                continue;
2104            }
2105           
2106            *p = '\0';
2107            name = &readbuf[1];
2108     
2109            /* is it [FOLDER_SETTINGS]? */
2110
2111            if (strcmp(name, "FOLDER_SETTINGS") == 0)
2112            {
2113                current_id = -1;
2114                continue;
2115            }
2116            else
2117            {
2118                /* it it [ROOT_FOLDER]? */
2119
2120                if (!strcmp(name, "ROOT_FOLDER"))
2121                {
2122                    current_id = lpFolder->m_nFolderId;
2123                    lpTemp = lpFolder;
2124
2125                }
2126                else
2127                {
2128                    /* must be [folder name] */
2129
2130                    current_id = next_folder_id++;
2131               /* create a new folder with this name,
2132                  and the flags for this folder as read from the registry */
2133               lpTemp = NewFolder(name,current_id,parent_index,
2134                               ExtraFolderData[id]->m_nSubIconId,
2135                               GetFolderFlags(numFolders) | F_CUSTOM);
2136               ExtraFolderData[current_id] = malloc(sizeof(EXFOLDERDATA) );
2137               memset(ExtraFolderData[current_id], 0, sizeof(EXFOLDERDATA));
2138
2139               ExtraFolderData[current_id]->m_nFolderId = current_id - MAX_EXTRA_FOLDERS;
2140               ExtraFolderData[current_id]->m_nIconId = ExtraFolderData[id]->m_nSubIconId;
2141               ExtraFolderData[current_id]->m_nParent = ExtraFolderData[id]->m_nFolderId;
2142               ExtraFolderData[current_id]->m_nSubIconId = -1;
2143               strcpy( ExtraFolderData[current_id]->m_szTitle, name );
2144               ExtraFolderData[current_id]->m_dwFlags = ExtraFolderData[id]->m_dwFlags;
2145                    AddFolder(lpTemp);
2146                }
2147            }
2148        }
2149        else if (current_id != -1)
2150        {
2151            /* string on a line by itself -- game name */
2152
2153            name = strtok(readbuf, " \t\r\n");
2154            if (name == NULL)
2155            {
2156                current_id = -1;
2157                continue;
2158            }
2159
2160            /* IMPORTANT: This assumes that all driver names are lowercase! */
2161         for (i = 0; name[i]; i++)
2162            name[i] = tolower(name[i]);
2163
2164         if (lpTemp == NULL)
2165         {
2166            ErrorMsg("Error parsing %s: missing [folder name] or [ROOT_FOLDER]",
2167                   fname);
2168            current_id = lpFolder->m_nFolderId;
2169            lpTemp = lpFolder;
2170         }
2171         AddGame(lpTemp,GetGameNameIndex(name));
2172        }
2173    }
2174
2175    if ( fp )
2176    {
2177        fclose( fp );
2178    }
2179
2180    return TRUE;
2181}
2182
2183
2184void GetFolders(TREEFOLDER ***folders,int *num_folders)
2185{
2186   *folders = treeFolders;
2187   *num_folders = numFolders;
2188}
2189
2190BOOL TryRenameCustomFolderIni(LPTREEFOLDER lpFolder,const char *old_name,const char *new_name)
2191{
2192   char filename[MAX_PATH];
2193   char new_filename[MAX_PATH];
2194   LPTREEFOLDER lpParent = NULL;
2195   if (lpFolder->m_nParent >= 0)
2196   {
2197      //it is a custom SubFolder
2198      lpParent = GetFolder( lpFolder->m_nParent );
2199      if( lpParent )
2200      {
2201         snprintf(filename,ARRAY_LENGTH(filename),"%s\\%s\\%s.ini",GetIniDir(),lpParent->m_lpTitle, old_name );
2202         snprintf(new_filename,ARRAY_LENGTH(new_filename),"%s\\%s\\%s.ini",GetIniDir(),lpParent->m_lpTitle, new_name );
2203         win_move_file_utf8(filename,new_filename);
2204      }
2205   }
2206   else
2207   {
2208      //Rename the File, if it exists
2209      snprintf(filename,ARRAY_LENGTH(filename),"%s\\%s.ini",GetIniDir(),old_name );
2210      snprintf(new_filename,ARRAY_LENGTH(new_filename),"%s\\%s.ini",GetIniDir(), new_name );
2211      win_move_file_utf8(filename,new_filename);
2212      //Rename the Directory, if it exists
2213      snprintf(filename,ARRAY_LENGTH(filename),"%s\\%s",GetIniDir(),old_name );
2214      snprintf(new_filename,ARRAY_LENGTH(new_filename),"%s\\%s",GetIniDir(), new_name );
2215      win_move_file_utf8(filename,new_filename);
2216   }
2217   return TRUE;
2218}
2219
2220BOOL TryRenameCustomFolder(LPTREEFOLDER lpFolder, const char *new_name)
2221{
2222   BOOL retval;
2223   char filename[MAX_PATH];
2224   char new_filename[MAX_PATH];
2225   
2226   if (lpFolder->m_nParent >= 0)
2227   {
2228      // a child extra folder was renamed, so do the rename and save the parent
2229
2230      // save old title
2231      char *old_title = lpFolder->m_lpTitle;
2232
2233      // set new title
2234      lpFolder->m_lpTitle = (char *)malloc(strlen(new_name) + 1);
2235      strcpy(lpFolder->m_lpTitle,new_name);
2236
2237      // try to save
2238      if (TrySaveExtraFolder(lpFolder) == FALSE)
2239      {
2240         // failed, so free newly allocated title and restore old
2241         free(lpFolder->m_lpTitle);
2242         lpFolder->m_lpTitle = old_title;
2243         return FALSE;
2244      }
2245      TryRenameCustomFolderIni(lpFolder, old_title, new_name);
2246      // successful, so free old title
2247      free(old_title);
2248      return TRUE;
2249   }
2250   
2251   // a parent extra folder was renamed, so rename the file
2252
2253   snprintf(new_filename,ARRAY_LENGTH(new_filename),"%s\\%s.ini",GetFolderDir(),new_name);
2254   snprintf(filename,ARRAY_LENGTH(filename),"%s\\%s.ini",GetFolderDir(),lpFolder->m_lpTitle);
2255
2256   retval = win_move_file_utf8(filename,new_filename);
2257
2258   if (retval)
2259   {
2260      TryRenameCustomFolderIni(lpFolder, lpFolder->m_lpTitle, new_name);
2261      free(lpFolder->m_lpTitle);
2262      lpFolder->m_lpTitle = (char *)malloc(strlen(new_name) + 1);
2263      strcpy(lpFolder->m_lpTitle,new_name);
2264   }
2265   else
2266   {
2267      char buf[500];
2268      snprintf(buf,ARRAY_LENGTH(buf),"Error while renaming custom file %s to %s",
2269             filename,new_filename);
2270      win_message_box_utf8(GetMainWindow(), buf, MAME32NAME, MB_OK | MB_ICONERROR);
2271   }
2272   return retval;
2273}
2274
2275void AddToCustomFolder(LPTREEFOLDER lpFolder,int driver_index)
2276{
2277    if ((lpFolder->m_dwFlags & F_CUSTOM) == 0)
2278   {
2279       win_message_box_utf8(GetMainWindow(),"Unable to add game to non-custom folder",
2280               MAME32NAME,MB_OK | MB_ICONERROR);
2281      return;
2282   }
2283
2284   if (TestBit(lpFolder->m_lpGameBits,driver_index) == 0)
2285   {
2286      AddGame(lpFolder,driver_index);
2287      if (TrySaveExtraFolder(lpFolder) == FALSE)
2288         RemoveGame(lpFolder,driver_index); // undo on error
2289   }
2290}
2291
2292void RemoveFromCustomFolder(LPTREEFOLDER lpFolder,int driver_index)
2293{
2294    if ((lpFolder->m_dwFlags & F_CUSTOM) == 0)
2295   {
2296       win_message_box_utf8(GetMainWindow(),"Unable to remove game from non-custom folder",
2297               MAME32NAME,MB_OK | MB_ICONERROR);
2298      return;
2299   }
2300
2301   if (TestBit(lpFolder->m_lpGameBits,driver_index) != 0)
2302   {
2303      RemoveGame(lpFolder,driver_index);
2304      if (TrySaveExtraFolder(lpFolder) == FALSE)
2305         AddGame(lpFolder,driver_index); // undo on error
2306   }
2307}
2308
2309BOOL TrySaveExtraFolder(LPTREEFOLDER lpFolder)
2310{
2311    char fname[MAX_PATH];
2312   FILE *fp;
2313   BOOL error = FALSE;
2314    int i,j;
2315
2316   LPTREEFOLDER root_folder = NULL;
2317   LPEXFOLDERDATA extra_folder = NULL;
2318
2319   for (i=0;i<numExtraFolders;i++)
2320   {
2321       if (ExtraFolderData[i]->m_nFolderId == lpFolder->m_nFolderId)
2322      {
2323          root_folder = lpFolder;
2324          extra_folder = ExtraFolderData[i];
2325         break;
2326      }
2327
2328      if (lpFolder->m_nParent >= 0 &&
2329         ExtraFolderData[i]->m_nFolderId == treeFolders[lpFolder->m_nParent]->m_nFolderId)
2330      {
2331         root_folder = treeFolders[lpFolder->m_nParent];
2332         extra_folder = ExtraFolderData[i];
2333         break;
2334      }
2335   }
2336
2337   if (extra_folder == NULL || root_folder == NULL)
2338   {
2339      MessageBox(GetMainWindow(), TEXT("Error finding custom file name to save"), TEXT(MAME32NAME), MB_OK | MB_ICONERROR);
2340      return FALSE;
2341   }
2342    /* "folder\title.ini" */
2343
2344    snprintf( fname, sizeof(fname), "%s\\%s.ini", GetFolderDir(), extra_folder->m_szTitle);
2345
2346    fp = fopen(fname, "wt");
2347    if (fp == NULL)
2348      error = TRUE;
2349   else
2350   {
2351      TREEFOLDER *folder_data;
2352
2353
2354      fprintf(fp,"[FOLDER_SETTINGS]\n");
2355      // negative values for icons means it's custom, so save 'em
2356      if (extra_folder->m_nIconId < 0)
2357      {
2358         fprintf(fp, "RootFolderIcon %s\n",
2359               ExtraFolderIcons[(-extra_folder->m_nIconId) - ICON_MAX]);
2360      }
2361      if (extra_folder->m_nSubIconId < 0)
2362      {
2363         fprintf(fp,"SubFolderIcon %s\n",
2364               ExtraFolderIcons[(-extra_folder->m_nSubIconId) - ICON_MAX]);
2365      }
2366
2367      /* need to loop over all our TREEFOLDERs--first the root one, then each child.
2368        start with the root */
2369
2370      folder_data = root_folder;
2371
2372      fprintf(fp,"\n[ROOT_FOLDER]\n");
2373
2374      for (i=0;i<driver_list_get_count(drivers);i++)
2375      {
2376         int driver_index = GetIndexFromSortedIndex(i);
2377         if (TestBit(folder_data->m_lpGameBits,driver_index))
2378         {
2379            fprintf(fp,"%s\n",drivers[driver_index]->name);
2380         }
2381      }
2382
2383      /* look through the custom folders for ones with our root as parent */
2384      for (j=0;j<numFolders;j++)
2385      {
2386         folder_data = treeFolders[j];
2387
2388         if (folder_data->m_nParent >= 0 &&
2389            treeFolders[folder_data->m_nParent] == root_folder)
2390         {
2391            fprintf(fp,"\n[%s]\n",folder_data->m_lpTitle);
2392           
2393            for (i=0;i<driver_list_get_count(drivers);i++)
2394            {
2395               int driver_index = GetIndexFromSortedIndex(i);
2396               if (TestBit(folder_data->m_lpGameBits,driver_index))
2397               {
2398                  fprintf(fp,"%s\n",drivers[driver_index]->name);
2399               }
2400            }
2401         }
2402      }
2403      if (fclose(fp) != 0)
2404         error = TRUE;
2405   }
2406
2407   if (error)
2408   {
2409      char buf[500];
2410      snprintf(buf,ARRAY_LENGTH(buf),"Error while saving custom file %s",fname);
2411      win_message_box_utf8(GetMainWindow(), buf, MAME32NAME, MB_OK | MB_ICONERROR);
2412   }
2413   return !error;
2414}
2415
2416HIMAGELIST GetTreeViewIconList(void)
2417{
2418    return hTreeSmall;
2419}
2420
2421int GetTreeViewIconIndex(int icon_id)
2422{
2423   int i;
2424
2425   if (icon_id < 0)
2426      return -icon_id;
2427
2428   for (i = 0; i < sizeof(treeIconNames) / sizeof(treeIconNames[0]); i++)
2429   {
2430      if (icon_id == treeIconNames[i].nResourceID)
2431         return i;
2432   }
2433
2434   return -1;
2435}
2436
2437/* End of source file */
src/osd/windows/ui/properties.c
r995r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11***************************************************************************/
12 
13/***************************************************************************
14
15  Properties.c
16
17    Properties Popup and Misc UI support routines.
18   
19    Created 8/29/98 by Mike Haaland (mhaaland@hypertech.com)
20
21***************************************************************************/
22#define WIN32_LEAN_AND_MEAN
23#define NONAMELESSUNION 1
24#include <windows.h>
25#include <windowsx.h>
26#include <commctrl.h>
27#include <commdlg.h>
28#undef NONAMELESSUNION
29#include <ddraw.h>
30#include <stdio.h>
31#include <string.h>
32#include <sys/stat.h>
33#include <tchar.h>
34
35#include <driver.h>
36#include <info.h>
37#include "audit.h"
38#include "audit32.h"
39#include "bitmask.h"
40#include "m32opts.h"
41#include "file.h"
42#include "resource.h"
43#include "DIJoystick.h"     /* For DIJoystick avalibility. */
44#include "m32util.h"
45#include "directdraw.h"
46#include "properties.h"
47#include "treeview.h"
48#include "win32ui.h"
49#include "screenshot.h"
50#include "Mame32.h"
51#include "DataMap.h"
52#include "help.h"
53#include "resource.hm"
54#include "winmain.h"
55#include "strconv.h"
56#include "winutf8.h"
57#include "ui/m32util.h"
58
59typedef HANDLE HTHEME;
60
61#ifdef _MSC_VER
62#define snprintf _snprintf
63#endif
64
65#ifdef MESS
66// done like this until I figure out a better idea
67#include "messopts.h"
68#include "ui/resourcems.h"
69#include "ui/propertiesms.h"
70#endif
71
72// missing win32 api defines
73#ifndef TBCD_TICS
74#define TBCD_TICS 1
75#endif
76#ifndef TBCD_THUMB
77#define TBCD_THUMB 2
78#endif
79#ifndef TBCD_CHANNEL
80#define TBCD_CHANNEL 3
81#endif
82
83#if defined(__GNUC__)
84/* fix warning: cast does not match function type */
85#undef  PropSheet_GetTabControl
86#define PropSheet_GetTabControl(d) (HWND)(LRESULT)(int)SendMessage((d),PSM_GETTABCONTROL,0,0)
87#endif /* defined(__GNUC__) */
88
89/***************************************************************
90 * Imported function prototypes
91 ***************************************************************/
92
93/**************************************************************
94 * Local function prototypes
95 **************************************************************/
96
97static void SetStereoEnabled(HWND hWnd, int nIndex);
98static void SetYM3812Enabled(HWND hWnd, int nIndex);
99static void SetSamplesEnabled(HWND hWnd, int nIndex, BOOL bSoundEnabled);
100static void InitializeOptions(HWND hDlg);
101static void InitializeMisc(HWND hDlg);
102static void OptOnHScroll(HWND hWnd, HWND hwndCtl, UINT code, int pos);
103static void NumScreensSelectionChange(HWND hwnd);
104static void RefreshSelectionChange(HWND hWnd, HWND hWndCtrl);
105static void InitializeSoundUI(HWND hwnd);
106static void InitializeSkippingUI(HWND hwnd);
107static void InitializeRotateUI(HWND hwnd);
108static void UpdateSelectScreenUI(HWND hwnd);
109static void InitializeSelectScreenUI(HWND hwnd);
110static void InitializeD3DVersionUI(HWND hwnd);
111static void InitializeVideoUI(HWND hwnd);
112static void InitializeEffectUI(HWND hWnd);
113static void InitializeBIOSUI(HWND hwnd);
114static void InitializeControllerMappingUI(HWND hwnd);
115static void PropToOptions(HWND hWnd, core_options *o);
116static void OptionsToProp(HWND hWnd, core_options *o);
117static void SetPropEnabledControls(HWND hWnd);
118static BOOL SelectEffect(HWND hWnd);
119static BOOL ResetEffect(HWND hWnd);
120
121static void BuildDataMap(void);
122static void ResetDataMap(HWND hWnd);
123
124static BOOL IsControlOptionValue(HWND hDlg,HWND hwnd_ctrl, core_options *opts );
125
126static void UpdateBackgroundBrush(HWND hwndTab);
127HBRUSH hBkBrush;
128
129/**************************************************************
130 * Local private variables
131 **************************************************************/
132
133static core_options *origGameOpts;
134static BOOL orig_uses_defaults;
135static core_options *pGameOpts = NULL;
136static datamap *properties_datamap;
137
138static int  g_nGame            = 0;
139static int  g_nFolder          = 0;
140static int  g_nFolderGame      = 0;
141static int  g_nPropertyMode    = 0;
142static BOOL g_bUseDefaults     = FALSE;
143static BOOL g_bReset           = FALSE;
144static BOOL  g_bAutoAspect[MAX_SCREENS] = {FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE};
145static HICON g_hIcon = NULL;
146
147/* Property sheets */
148
149#define HIGHLIGHT_COLOR RGB(0,196,0)
150HBRUSH highlight_brush = NULL;
151HBRUSH background_brush = NULL;
152#define VECTOR_COLOR RGB( 190, 0, 0) //DARK RED
153#define FOLDER_COLOR RGB( 0, 128, 0 ) // DARK GREEN
154#define PARENT_COLOR RGB( 190, 128, 192 ) // PURPLE
155#define GAME_COLOR RGB( 0, 128, 192 ) // DARK BLUE
156
157BOOL PropSheetFilter_Vector(const machine_config *drv, const game_driver *gamedrv)
158{
159   return (drv->video_attributes & VIDEO_TYPE_VECTOR) != 0;
160}
161
162/* Help IDs */
163static DWORD dwHelpIDs[] =
164{
165   
166   IDC_JDZ,            HIDC_JDZ,
167   IDC_ANTIALIAS,          HIDC_ANTIALIAS,
168   IDC_ARTWORK_CROP,      HIDC_ARTWORK_CROP,
169   IDC_ASPECTRATIOD,       HIDC_ASPECTRATIOD,
170   IDC_ASPECTRATION,       HIDC_ASPECTRATION,
171   IDC_AUTOFRAMESKIP,      HIDC_AUTOFRAMESKIP,
172   IDC_BACKDROPS,         HIDC_BACKDROPS,
173   IDC_BEAM,               HIDC_BEAM,
174   IDC_BEZELS,            HIDC_BEZELS,
175   IDC_FSGAMMA,          HIDC_FSGAMMA,
176   IDC_BRIGHTCORRECT,      HIDC_BRIGHTCORRECT,
177   IDC_BROADCAST,         HIDC_BROADCAST,
178   IDC_RANDOM_BG,          HIDC_RANDOM_BG,
179   IDC_CHEAT,              HIDC_CHEAT,
180   IDC_DEFAULT_INPUT,      HIDC_DEFAULT_INPUT,
181   IDC_FILTER_CLONES,      HIDC_FILTER_CLONES,
182   IDC_FILTER_EDIT,        HIDC_FILTER_EDIT,
183   IDC_FILTER_NONWORKING,  HIDC_FILTER_NONWORKING,
184   IDC_FILTER_ORIGINALS,   HIDC_FILTER_ORIGINALS,
185   IDC_FILTER_RASTER,      HIDC_FILTER_RASTER,
186   IDC_FILTER_UNAVAILABLE, HIDC_FILTER_UNAVAILABLE,
187   IDC_FILTER_VECTOR,      HIDC_FILTER_VECTOR,
188   IDC_FILTER_WORKING,     HIDC_FILTER_WORKING,
189   IDC_FLICKER,            HIDC_FLICKER,
190   IDC_FLIPX,              HIDC_FLIPX,
191   IDC_FLIPY,              HIDC_FLIPY,
192   IDC_FRAMESKIP,          HIDC_FRAMESKIP,
193   IDC_GAMMA,              HIDC_GAMMA,
194   IDC_HISTORY,            HIDC_HISTORY,
195   IDC_HWSTRETCH,          HIDC_HWSTRETCH,
196   IDC_JOYSTICK,           HIDC_JOYSTICK,
197   IDC_KEEPASPECT,         HIDC_KEEPASPECT,
198   IDC_LANGUAGECHECK,      HIDC_LANGUAGECHECK,
199   IDC_LANGUAGEEDIT,       HIDC_LANGUAGEEDIT,
200   IDC_LOG,                HIDC_LOG,
201   IDC_SLEEP,            HIDC_SLEEP,
202   IDC_MAXIMIZE,           HIDC_MAXIMIZE,
203   IDC_OVERLAYS,         HIDC_OVERLAYS,
204   IDC_PROP_RESET,         HIDC_PROP_RESET,
205   IDC_REFRESH,            HIDC_REFRESH,
206   IDC_RESET_DEFAULT,      HIDC_RESET_DEFAULT,
207   IDC_RESET_FILTERS,      HIDC_RESET_FILTERS,
208   IDC_RESET_GAMES,        HIDC_RESET_GAMES,
209   IDC_RESET_UI,           HIDC_RESET_UI,
210   IDC_ROTATE,             HIDC_ROTATE,
211   IDC_SAMPLERATE,         HIDC_SAMPLERATE,
212   IDC_SAMPLES,            HIDC_SAMPLES,
213   IDC_SIZES,              HIDC_SIZES,
214   IDC_START_GAME_CHECK,   HIDC_START_GAME_CHECK,
215   IDC_SWITCHRES,          HIDC_SWITCHRES,
216   IDC_SYNCREFRESH,        HIDC_SYNCREFRESH,
217   IDC_THROTTLE,           HIDC_THROTTLE,
218   IDC_TRIPLE_BUFFER,      HIDC_TRIPLE_BUFFER,
219   IDC_USE_DEFAULT,        HIDC_USE_DEFAULT,
220   IDC_USE_MOUSE,          HIDC_USE_MOUSE,
221   IDC_USE_SOUND,          HIDC_USE_SOUND,
222   IDC_VOLUME,             HIDC_VOLUME,
223   IDC_WAITVSYNC,          HIDC_WAITVSYNC,
224   IDC_WINDOWED,           HIDC_WINDOWED,
225   IDC_PAUSEBRIGHT,        HIDC_PAUSEBRIGHT,
226   IDC_LIGHTGUN,           HIDC_LIGHTGUN,
227   IDC_STEADYKEY,          HIDC_STEADYKEY,
228   IDC_JOY_GUI,            HIDC_JOY_GUI,
229   IDC_RANDOM_BG,          HIDC_RANDOM_BG,
230   IDC_SKIP_GAME_INFO,     HIDC_SKIP_GAME_INFO,
231   IDC_HIGH_PRIORITY,      HIDC_HIGH_PRIORITY,
232   IDC_D3D_FILTER,         HIDC_D3D_FILTER,
233   IDC_AUDIO_LATENCY,      HIDC_AUDIO_LATENCY,
234   IDC_BIOS,               HIDC_BIOS,
235   IDC_STRETCH_SCREENSHOT_LARGER, HIDC_STRETCH_SCREENSHOT_LARGER,
236   IDC_SCREEN,             HIDC_SCREEN,
237   IDC_PADDLE,            HIDC_PADDLE,
238   IDC_ADSTICK,         HIDC_ADSTICK,
239   IDC_PEDAL,            HIDC_PEDAL,
240   IDC_DIAL,            HIDC_DIAL,
241   IDC_TRACKBALL,         HIDC_TRACKBALL,
242   IDC_LIGHTGUNDEVICE,      HIDC_LIGHTGUNDEVICE,
243   IDC_ENABLE_AUTOSAVE,    HIDC_ENABLE_AUTOSAVE,
244   IDC_MULTITHREAD_RENDERING,    HIDC_MULTITHREAD_RENDERING,
245   IDC_JSAT,            HIDC_JSAT,
246   0,                      0
247};
248
249static struct ComboBoxVideo
250{
251   const TCHAR*   m_pText;
252   const char*      m_pData;
253} g_ComboBoxVideo[] =
254{
255   { TEXT("GDI"),                  "gdi"    },
256   { TEXT("DirectDraw"),           "ddraw"   },
257   { TEXT("Direct3D"),             "d3d"     },
258};
259#define NUMVIDEO (sizeof(g_ComboBoxVideo) / sizeof(g_ComboBoxVideo[0]))
260
261static struct ComboBoxD3DVersion
262{
263   const TCHAR*   m_pText;
264   const int      m_pData;
265} g_ComboBoxD3DVersion[] =
266{
267   { TEXT("Version 9"),           9   },
268   { TEXT("Version 8"),           8   },
269};
270
271#define NUMD3DVERSIONS (sizeof(g_ComboBoxD3DVersion) / sizeof(g_ComboBoxD3DVersion[0]))
272
273static struct ComboBoxSelectScreen
274{
275   const TCHAR*   m_pText;
276   const int      m_pData;
277} g_ComboBoxSelectScreen[] =
278{
279   { TEXT("Screen 0"),             0    },
280   { TEXT("Screen 1"),             1    },
281   { TEXT("Screen 2"),             2    },
282   { TEXT("Screen 3"),             3    },
283};
284#define NUMSELECTSCREEN (sizeof(g_ComboBoxSelectScreen) / sizeof(g_ComboBoxSelectScreen[0]))
285
286static struct ComboBoxView
287{
288   const TCHAR*   m_pText;
289   const char*      m_pData;
290} g_ComboBoxView[] =
291{
292   { TEXT("Auto"),              "auto"        },
293   { TEXT("Standard"),         "standard"    },
294   { TEXT("Pixel Aspect"),     "pixel"       },
295   { TEXT("Cocktail"),         "cocktail"    },
296};
297#define NUMVIEW (sizeof(g_ComboBoxView) / sizeof(g_ComboBoxView[0]))
298
299
300
301static struct ComboBoxDevices
302{
303   const TCHAR*   m_pText;
304   const char*    m_pData;
305} g_ComboBoxDevice[] =
306{
307   { TEXT("None"),                  "none"      },
308   { TEXT("Keyboard"),              "keyboard"  },
309   { TEXT("Mouse"),               "mouse"     },
310   { TEXT("Joystick"),              "joystick"  },
311   { TEXT("Lightgun"),              "lightgun"  },
312};
313
314#define NUMDEVICES (sizeof(g_ComboBoxDevice) / sizeof(g_ComboBoxDevice[0]))
315
316/***************************************************************
317 * Public functions
318 ***************************************************************/
319
320void PropertiesInit(void)
321{
322}
323
324int PropertiesCurrentGame(HWND hDlg)
325{
326   return g_nGame;
327}
328
329DWORD GetHelpIDs(void)
330{
331   return (DWORD) (LPSTR) dwHelpIDs;
332}
333
334// This function (and the code that use it) is a gross hack - but at least the vile
335// and disgusting global variables are gone, making it less gross than what came before
336static int GetSelectedScreen(HWND hWnd)
337{
338   int nSelectedScreen = 0;
339   HWND hCtrl = GetDlgItem(hWnd, IDC_SCREENSELECT);
340   if (hCtrl)
341      nSelectedScreen = ComboBox_GetCurSel(hCtrl);
342   if ((nSelectedScreen < 0) || (nSelectedScreen >= MAX_SCREENS))
343      nSelectedScreen = 0;
344   return nSelectedScreen;
345
346}
347
348static PROPSHEETPAGE *CreatePropSheetPages(HINSTANCE hInst, BOOL bOnlyDefault,
349   const game_driver *gamedrv, UINT *pnMaxPropSheets, PROP_SOURCE source )
350{
351   PROPSHEETPAGE *pspages;
352   int maxPropSheets;
353   int possiblePropSheets;
354   int i;
355   machine_config drv;
356
357   if (gamedrv)
358       expand_machine_driver(gamedrv->drv, &drv);
359
360   if( source != SRC_GAME )
361   {
362      i = 2;
363   }
364   else
365   {
366      i = 0;
367   }
368   for (; g_propSheets[i].pfnDlgProc; i++)
369      ;
370
371   if( source != SRC_GAME )
372   {
373      possiblePropSheets = i - 1;
374   }
375   else
376   {
377      possiblePropSheets = i + 1;
378   }
379
380   pspages = malloc(sizeof(PROPSHEETPAGE) * possiblePropSheets);
381   if (!pspages)
382      return NULL;
383   memset(pspages, 0, sizeof(PROPSHEETPAGE) * possiblePropSheets);
384
385   maxPropSheets = 0;
386   if( source != SRC_GAME )
387   {
388      i = 2;
389   }
390   else
391   {
392      i = 0;
393   }
394   for (; g_propSheets[i].pfnDlgProc; i++)
395   {
396      if ((gamedrv != NULL) || g_propSheets[i].bOnDefaultPage)
397      {
398         if (!gamedrv || !g_propSheets[i].pfnFilterProc || g_propSheets[i].pfnFilterProc(&drv, gamedrv))
399         {
400            pspages[maxPropSheets].dwSize                     = sizeof(PROPSHEETPAGE);
401            pspages[maxPropSheets].dwFlags                    = 0;
402            pspages[maxPropSheets].hInstance                  = hInst;
403            pspages[maxPropSheets].DUMMYUNIONNAME.pszTemplate = MAKEINTRESOURCE(g_propSheets[i].dwDlgID);
404            pspages[maxPropSheets].pfnCallback                = NULL;
405            pspages[maxPropSheets].lParam                     = 0;
406            pspages[maxPropSheets].pfnDlgProc                 = g_propSheets[i].pfnDlgProc;
407            maxPropSheets++;
408         }
409      }
410   }
411   
412   if (pnMaxPropSheets)
413      *pnMaxPropSheets = maxPropSheets;
414
415   return pspages;
416}
417
418void InitDefaultPropertyPage(HINSTANCE hInst, HWND hWnd)
419{
420   PROPSHEETHEADER pshead;
421   PROPSHEETPAGE   *pspage;
422
423   // clear globals
424   pGameOpts = NULL;
425
426   g_nGame = GLOBAL_OPTIONS;
427
428   /* Get default options to populate property sheets */
429   pGameOpts = GetDefaultOptions(-1, FALSE);
430   g_bUseDefaults = FALSE;
431   /* Stash the result for comparing later */
432   origGameOpts = CreateGameOptions(OPTIONS_TYPE_GLOBAL);
433   options_copy(origGameOpts, pGameOpts);
434   orig_uses_defaults = FALSE;
435   g_bReset = FALSE;
436   BuildDataMap();
437
438   ZeroMemory(&pshead, sizeof(pshead));
439
440   pspage = CreatePropSheetPages(hInst, TRUE, NULL, &pshead.nPages, SRC_GAME);
441   if (!pspage)
442      return;
443
444   /* Fill in the property sheet header */
445   pshead.hwndParent                 = hWnd;
446   pshead.dwSize                     = sizeof(PROPSHEETHEADER);
447   pshead.dwFlags                    = PSH_PROPSHEETPAGE | PSH_USEICONID | PSH_PROPTITLE;
448   pshead.hInstance                  = hInst;
449   pshead.pszCaption                 = TEXT("Default Game");
450   pshead.DUMMYUNIONNAME2.nStartPage = 0;
451   pshead.DUMMYUNIONNAME.pszIcon     = MAKEINTRESOURCE(IDI_MAME32_ICON);
452   pshead.DUMMYUNIONNAME3.ppsp       = pspage;
453
454   /* Create the Property sheet and display it */
455   if (PropertySheet(&pshead) == -1)
456   {
457      char temp[100];
458      DWORD dwError = GetLastError();
459      sprintf(temp, "Propery Sheet Error %d %X", (int)dwError, (int)dwError);
460      win_message_box_utf8(0, temp, "Error", IDOK);
461   }
462
463   free(pspage);
464}
465
466void InitPropertyPage(HINSTANCE hInst, HWND hWnd, int game_num, HICON hIcon, int folder_index, PROP_SOURCE source)
467{
468   InitPropertyPageToPage(hInst, hWnd, game_num, hIcon, PROPERTIES_PAGE, folder_index, source);
469}
470
471void InitPropertyPageToPage(HINSTANCE hInst, HWND hWnd, int game_num, HICON hIcon, int start_page, int folder_index, PROP_SOURCE source )
472{
473   PROPSHEETHEADER pshead;
474   PROPSHEETPAGE   *pspage;
475   TCHAR*          t_description = 0;
476   TCHAR*          t_foldername = 0;
477
478   // clear globals
479   pGameOpts = NULL;
480
481   if (highlight_brush == NULL)
482      highlight_brush = CreateSolidBrush(HIGHLIGHT_COLOR);
483
484   if (background_brush == NULL)
485      background_brush = CreateSolidBrush(GetSysColor(COLOR_3DFACE));
486
487   g_hIcon = CopyIcon(hIcon);
488   InitGameAudit(game_num);
489   g_nGame = game_num;
490   g_nFolder = game_num;
491   if( source == SRC_GAME )
492   {
493      pGameOpts = GetGameOptions(game_num, folder_index);
494      g_bUseDefaults = GetGameUsesDefaults(game_num);
495      /* Stash the result for comparing later */
496      origGameOpts = CreateGameOptions(game_num);
497      options_copy(origGameOpts, pGameOpts);
498      g_nFolderGame = game_num;
499      g_nPropertyMode = SOURCE_GAME;
500   }
501   else
502   {
503      g_nFolderGame = folder_index;
504      //For our new scheme to work, we need the possibility to determine whether a sourcefolder contains vector games
505      //so we take the selected game in the listview of a source file to check if it is a Vector game
506      //this implies that vector games are not mixed up in the source with non-vector games
507      //which I think is the case
508      if (DriverIsVector( folder_index ) && (game_num != FOLDER_VECTOR ) )
509      {
510         GetFolderOptions(game_num, TRUE);
511         pGameOpts = GetSourceOptions( folder_index );
512      }
513      else
514      {
515         pGameOpts = GetFolderOptions( game_num, FALSE );
516      }
517      if( g_nFolder == FOLDER_VECTOR )
518      {
519         g_nPropertyMode = SOURCE_VECTOR;
520         g_bUseDefaults = GetVectorUsesDefaults() ? TRUE : FALSE;
521      }
522      else
523      {
524         g_nPropertyMode = SOURCE_FOLDER;
525         g_bUseDefaults = GetFolderUsesDefaults(g_nFolder, g_nFolderGame) ? TRUE : FALSE;
526      }
527      if( DriverIsVector( folder_index ) && (game_num != FOLDER_VECTOR ) )
528      {
529         pGameOpts =GetFolderOptions(game_num, TRUE);
530         //CopyGameOptions(GetSourceOptions( folder_index ), &folder_options[folder_index] );
531         //pGameOpts = &folder_options[folder_index];
532      }
533      else
534      {
535         pGameOpts = GetFolderOptions( game_num, FALSE );
536      }
537      /* Stash the result for comparing later */
538      g_nGame = FOLDER_OPTIONS;
539      origGameOpts = CreateGameOptions(OPTIONS_TYPE_FOLDER);
540      options_copy(origGameOpts, pGameOpts);
541   }
542   orig_uses_defaults = g_bUseDefaults;
543   g_bReset = FALSE;
544   BuildDataMap();
545
546   ZeroMemory(&pshead, sizeof(PROPSHEETHEADER));
547
548   if( source == SRC_GAME )
549   {
550      pspage = CreatePropSheetPages(hInst, FALSE, drivers[game_num], &pshead.nPages, source);
551   }
552   else
553   {
554      pspage = CreatePropSheetPages(hInst, FALSE, NULL, &pshead.nPages, source);
555   }
556   if (!pspage)
557      return;
558
559   /* Fill in the property sheet header */
560   pshead.hwndParent                 = hWnd;
561   pshead.dwSize                     = sizeof(PROPSHEETHEADER);
562   pshead.dwFlags                    = PSH_PROPSHEETPAGE | PSH_USEICONID | PSH_PROPTITLE;
563   pshead.hInstance                  = hInst;
564   if( source == SRC_GAME )
565   {
566      t_description = tstring_from_utf8(ModifyThe(drivers[g_nGame]->description));
567      if( !t_description )
568         return;
569      pshead.pszCaption = t_description;
570   }
571   else
572   {
573      t_foldername = tstring_from_utf8(GetFolderNameByID(g_nFolder));
574      if( !t_foldername )
575         return;
576      pshead.pszCaption = t_foldername;
577   }
578   pshead.DUMMYUNIONNAME2.nStartPage = start_page;
579   pshead.DUMMYUNIONNAME.pszIcon     = MAKEINTRESOURCE(IDI_MAME32_ICON);
580   pshead.DUMMYUNIONNAME3.ppsp       = pspage;
581
582   /* Create the Property sheet and display it */
583   if (PropertySheet(&pshead) == -1)
584   {
585      char temp[100];
586      DWORD dwError = GetLastError();
587      sprintf(temp, "Propery Sheet Error %d %X", (int)dwError, (int)dwError);
588      win_message_box_utf8(0, temp, "Error", IDOK);
589   }
590   
591   if( t_foldername )
592      free(t_foldername);
593   if( t_description )
594      free(t_description);
595   free(pspage);
596}
597
598/*********************************************************************
599 * Local Functions
600 *********************************************************************/
601
602/* Build CPU info string */
603static char *GameInfoCPU(UINT nIndex)
604{
605   int i;
606   static char buf[1024] = "";
607   machine_config drv;
608   expand_machine_driver(drivers[nIndex]->drv,&drv);
609
610   ZeroMemory(buf, sizeof(buf));
611
612   cpuintrf_init(NULL);
613
614   i = 0;
615   while (i < MAX_CPU && drv.cpu[i].cpu_type)
616   {
617      if (drv.cpu[i].cpu_clock >= 1000000)
618         sprintf(&buf[strlen(buf)], "%s %d.%06d MHz",
619               cputype_name(drv.cpu[i].cpu_type),
620               drv.cpu[i].cpu_clock / 1000000,
621               drv.cpu[i].cpu_clock % 1000000);
622      else
623         sprintf(&buf[strlen(buf)], "%s %d.%03d kHz",
624               cputype_name(drv.cpu[i].cpu_type),
625               drv.cpu[i].cpu_clock / 1000,
626               drv.cpu[i].cpu_clock % 1000);
627
628      strcat(buf, "\n");
629
630      i++;
631    }
632
633   return buf;
634}
635
636/* Build Sound system info string */
637static char *GameInfoSound(UINT nIndex)
638{
639   int i;
640   static char buf[1024];
641   machine_config drv;
642   expand_machine_driver(drivers[nIndex]->drv,&drv);
643
644   buf[0] = 0;
645
646   i = 0;
647   while (i < MAX_SOUND && drv.sound[i].sound_type)
648   {
649      int clock,sound_type,count;
650
651      sound_type = drv.sound[i].sound_type;
652      clock = drv.sound[i].clock;
653
654      count = 1;
655      i++;
656
657      while (i < MAX_SOUND
658            && drv.sound[i].sound_type == sound_type
659            && drv.sound[i].clock == clock)
660      {
661         count++;
662         i++;
663      }
664
665      if (count > 1)
666         sprintf(&buf[strlen(buf)],"%dx",count);
667
668      sprintf(&buf[strlen(buf)],"%s",sndtype_name(sound_type));
669
670      if (clock)
671      {
672         if (clock >= 1000000)
673            sprintf(&buf[strlen(buf)]," %d.%06d MHz",
674                  clock / 1000000,
675                  clock % 1000000);
676         else
677            sprintf(&buf[strlen(buf)]," %d.%03d kHz",
678                  clock / 1000,
679                  clock % 1000);
680      }
681
682      strcat(buf,"\n");
683   }
684
685   return buf;
686}
687
688/* Build Display info string */
689static char *GameInfoScreen(UINT nIndex)
690{
691   static char buf[1024];
692   machine_config drv;
693   expand_machine_driver(drivers[nIndex]->drv,&drv);
694
695   if (drv.video_attributes & VIDEO_TYPE_VECTOR)
696      strcpy(buf, "Vector Game");
697   else
698   {
699      if (drivers[nIndex]->flags & ORIENTATION_SWAP_XY)
700         sprintf(buf,"%d x %d (V) %f Hz",
701         drv.screen[0].defstate.visarea.max_y - drv.screen[0].defstate.visarea.min_y + 1,
702               drv.screen[0].defstate.visarea.max_x - drv.screen[0].defstate.visarea.min_x + 1,
703               SUBSECONDS_TO_HZ(drv.screen[0].defstate.refresh));
704      else
705         sprintf(buf,"%d x %d (H) %f Hz",
706               drv.screen[0].defstate.visarea.max_x - drv.screen[0].defstate.visarea.min_x + 1,
707               drv.screen[0].defstate.visarea.max_y - drv.screen[0].defstate.visarea.min_y + 1,
708               SUBSECONDS_TO_HZ(drv.screen[0].defstate.refresh));
709   }
710   return buf;
711}
712
713/* Build color information string */
714static char *GameInfoColors(UINT nIndex)
715{
716   static char buf[1024];
717   machine_config drv;
718   expand_machine_driver(drivers[nIndex]->drv,&drv);
719
720   ZeroMemory(buf, sizeof(buf));
721   sprintf(buf, "%d colors ", drv.total_colors);
722
723   return buf;
724}
725
726/* Build game status string */
727const char *GameInfoStatus(int driver_index, BOOL bRomStatus)
728{
729   static char buffer[1024];
730   int audit_result = GetRomAuditResults(driver_index);
731   memset(buffer,0,sizeof(char)*1024);
732   if ( bRomStatus )
733    {
734      if (IsAuditResultKnown(audit_result) == FALSE)
735       {
736         strcpy(buffer, "Unknown");
737      }
738      else if (IsAuditResultYes(audit_result))
739      {
740         if (DriverIsBroken(driver_index))
741          {
742            strcpy(buffer, "Not working");
743           
744            if (drivers[driver_index]->flags & GAME_UNEMULATED_PROTECTION)
745            {
746               if (*buffer != '\0')
747                  strcat(buffer, "\r\n");
748               strcat(buffer, "Game protection isn't fully emulated");
749            }
750            if (drivers[driver_index]->flags & GAME_WRONG_COLORS)
751            {
752               if (*buffer != '\0')
753                  strcat(buffer, "\r\n");
754               strcat(buffer, "Colors are completely wrong");
755            }
756            if (drivers[driver_index]->flags & GAME_IMPERFECT_COLORS)
757            {
758               if (*buffer != '\0')
759                  strcat(buffer, "\r\n");
760               strcat(buffer, "Colors aren't 100% accurate");
761            }
762            if (drivers[driver_index]->flags & GAME_IMPERFECT_GRAPHICS)
763            {
764               if (*buffer != '\0')
765                  strcat(buffer, "\r\n");
766               strcat(buffer, "Video emulation isn't 100% accurate");
767            }
768            if (drivers[driver_index]->flags & GAME_NO_SOUND)
769            {
770               if (*buffer != '\0')
771                  strcat(buffer, "\r\n");
772               strcat(buffer, "Game lacks sound");
773            }
774            if (drivers[driver_index]->flags & GAME_IMPERFECT_SOUND)
775            {
776               if (*buffer != '\0')
777                  strcat(buffer, "\r\n");
778               strcat(buffer, "Sound emulation isn't 100% accurate");
779            }
780            if (drivers[driver_index]->flags & GAME_NO_COCKTAIL)
781            {
782               if (*buffer != '\0')
783                  strcat(buffer, "\r\n");
784               strcat(buffer, "Screen flipping is not supported");
785            }
786          }
787         else
788         {
789            strcpy(buffer, "Working");
790           
791            if (drivers[driver_index]->flags & GAME_UNEMULATED_PROTECTION)
792            {
793               if (*buffer != '\0')
794                  strcat(buffer, "\r\n");
795               strcat(buffer, "Game protection isn't fully emulated");
796            }
797            if (drivers[driver_index]->flags & GAME_WRONG_COLORS)
798            {
799               if (*buffer != '\0')
800                  strcat(buffer, "\r\n");
801               strcat(buffer, "Colors are completely wrong");
802            }
803            if (drivers[driver_index]->flags & GAME_IMPERFECT_COLORS)
804            {
805               if (*buffer != '\0')
806                  strcat(buffer, "\r\n");
807               strcat(buffer, "Colors aren't 100% accurate");
808            }
809            if (drivers[driver_index]->flags & GAME_IMPERFECT_GRAPHICS)
810            {
811               if (*buffer != '\0')
812                  strcat(buffer, "\r\n");
813               strcat(buffer, "Video emulation isn't 100% accurate");
814            }
815            if (drivers[driver_index]->flags & GAME_NO_SOUND)
816            {
817               if (*buffer != '\0')
818                  strcat(buffer, "\r\n");
819               strcat(buffer, "Game lacks sound");
820            }
821            if (drivers[driver_index]->flags & GAME_IMPERFECT_SOUND)
822            {
823               if (*buffer != '\0')
824                  strcat(buffer, "\r\n");
825               strcat(buffer, "Sound emulation isn't 100% accurate");
826            }
827            if (drivers[driver_index]->flags & GAME_NO_COCKTAIL)
828            {
829               if (*buffer != '\0')
830                  strcat(buffer, "\r\n");
831               strcat(buffer, "Screen flipping is not supported");
832            }
833         }
834      }
835      else
836      {
837         // audit result is no
838   #ifdef MESS
839         strcpy(buffer, "BIOS missing");
840   #else
841         strcpy(buffer, "ROMs missing");
842   #endif
843      }
844   }
845   else
846   {
847      //Just show the emulation flags
848      if (DriverIsBroken(driver_index))
849      {
850         strcpy(buffer, "Not working");
851      }
852      else
853      {
854         strcpy(buffer, "Working");
855      }   
856      if (drivers[driver_index]->flags & GAME_UNEMULATED_PROTECTION)
857      {
858         if (*buffer != '\0')
859            strcat(buffer, "\r\n");
860         strcat(buffer, "Game protection isn't fully emulated");
861      }
862      if (drivers[driver_index]->flags & GAME_WRONG_COLORS)
863      {
864      if (*buffer != '\0')
865            strcat(buffer, "\r\n");
866         strcat(buffer, "Colors are completely wrong");
867      }
868      if (drivers[driver_index]->flags & GAME_IMPERFECT_COLORS)
869      {
870         if (*buffer != '\0')
871            strcat(buffer, "\r\n");
872         strcat(buffer, "Colors aren't 100% accurate");
873      }
874      if (drivers[driver_index]->flags & GAME_IMPERFECT_GRAPHICS)
875      {
876         if (*buffer != '\0')
877            strcat(buffer, "\r\n");
878         strcat(buffer, "Video emulation isn't 100% accurate");
879      }
880      if (drivers[driver_index]->flags & GAME_NO_SOUND)
881      {
882         if (*buffer != '\0')
883            strcat(buffer, "\r\n");
884         strcat(buffer, "Game lacks sound");
885      }
886      if (drivers[driver_index]->flags & GAME_IMPERFECT_SOUND)
887      {
888         if (*buffer != '\0')
889            strcat(buffer, "\r\n");
890         strcat(buffer, "Sound emulation isn't 100% accurate");
891      }
892      if (drivers[driver_index]->flags & GAME_NO_COCKTAIL)
893      {
894         if (*buffer != '\0')
895            strcat(buffer, "\r\n");
896         strcat(buffer, "Screen flipping is not supported");
897      }
898   }
899   return buffer;
900}
901
902/* Build game manufacturer string */
903static char *GameInfoManufactured(UINT nIndex)
904{
905   static char buffer[1024];
906
907   snprintf(buffer,sizeof(buffer),"%s %s",drivers[nIndex]->year,drivers[nIndex]->manufacturer);
908   return buffer;
909}
910
911/* Build Game title string */
912char *GameInfoTitle(UINT nIndex)
913{
914   static char buf[1024];
915
916   if (nIndex == GLOBAL_OPTIONS)
917      strcpy(buf, "Global game options\nDefault options used by all games");
918   else if (nIndex == FOLDER_OPTIONS)
919      strcpy(buf, "Global folder options\nDefault options used by all games in the folder");
920   else
921      sprintf(buf, "%s\n\"%s\"", ModifyThe(drivers[nIndex]->description), drivers[nIndex]->name);
922   return buf;
923}
924
925/* Build game clone infromation string */
926static char *GameInfoCloneOf(UINT nIndex)
927{
928   static char buf[1024];
929   int nParentIndex= -1;
930
931   buf[0] = '\0';
932
933   if (DriverIsClone(nIndex))
934   {
935      nParentIndex = GetParentIndex(drivers[nIndex]);
936      sprintf(buf, "%s - \"%s\"",
937         ConvertAmpersandString(ModifyThe(drivers[nParentIndex]->description)),
938         drivers[nParentIndex]->name);
939   }
940
941   return buf;
942}
943
944static const char * GameInfoSource(UINT nIndex)
945{
946   return GetDriverFilename(nIndex);
947}
948
949/* Handle the information property page */
950INT_PTR CALLBACK GamePropertiesDialogProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam)
951{
952HWND hWnd;
953   switch (Msg)
954   {
955   case WM_INITDIALOG:
956      if (g_hIcon)
957         SendDlgItemMessage(hDlg, IDC_GAME_ICON, STM_SETICON, (WPARAM) g_hIcon, 0);
958#if defined(USE_SINGLELINE_TABCONTROL)
959      {
960         HWND hWnd = PropSheet_GetTabControl(GetParent(hDlg));
961         DWORD tabStyle = (GetWindowLong(hWnd,GWL_STYLE) & ~TCS_MULTILINE);
962         SetWindowLong(hWnd,GWL_STYLE,tabStyle | TCS_SINGLELINE);
963      }
964#endif
965
966      win_set_window_text_utf8(GetDlgItem(hDlg, IDC_PROP_TITLE),         GameInfoTitle(g_nGame));
967      win_set_window_text_utf8(GetDlgItem(hDlg, IDC_PROP_MANUFACTURED),  GameInfoManufactured(g_nGame));
968      win_set_window_text_utf8(GetDlgItem(hDlg, IDC_PROP_STATUS),        GameInfoStatus(g_nGame, FALSE));
969      win_set_window_text_utf8(GetDlgItem(hDlg, IDC_PROP_CPU),           GameInfoCPU(g_nGame));
970      win_set_window_text_utf8(GetDlgItem(hDlg, IDC_PROP_SOUND),         GameInfoSound(g_nGame));
971      win_set_window_text_utf8(GetDlgItem(hDlg, IDC_PROP_SCREEN),        GameInfoScreen(g_nGame));
972      win_set_window_text_utf8(GetDlgItem(hDlg, IDC_PROP_COLORS),        GameInfoColors(g_nGame));
973      win_set_window_text_utf8(GetDlgItem(hDlg, IDC_PROP_CLONEOF),       GameInfoCloneOf(g_nGame));
974      win_set_window_text_utf8(GetDlgItem(hDlg, IDC_PROP_SOURCE),        GameInfoSource(g_nGame));
975     
976      if (DriverIsClone(g_nGame))
977      {
978         ShowWindow(GetDlgItem(hDlg, IDC_PROP_CLONEOF_TEXT), SW_SHOW);
979      }
980      else
981      {
982         ShowWindow(GetDlgItem(hDlg, IDC_PROP_CLONEOF_TEXT), SW_HIDE);
983      }
984      hWnd = PropSheet_GetTabControl(GetParent(hDlg));
985      UpdateBackgroundBrush(hWnd);
986      ShowWindow(hDlg, SW_SHOW);
987      return 1;
988
989   }
990    return 0;
991}
992
993/* Handle all options property pages */
994INT_PTR CALLBACK GameOptionsProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam)
995{
996   RECT rc;
997   int nParentIndex = -1;
998   switch (Msg)
999   {
1000   case WM_INITDIALOG:
1001      /* Fill in the Game info at the top of the sheet */
1002      win_set_window_text_utf8(GetDlgItem(hDlg, IDC_PROP_TITLE), GameInfoTitle(g_nGame));
1003      InitializeOptions(hDlg);
1004      InitializeMisc(hDlg);
1005
1006      datamap_populate_all_controls(properties_datamap, hDlg, pGameOpts);
1007      OptionsToProp(hDlg, pGameOpts);
1008      if( g_nGame >= 0)
1009      {
1010         g_bUseDefaults = GetGameUsesDefaults(g_nGame);
1011      }
1012      if( g_nGame == FOLDER_OPTIONS)
1013      {
1014         if( g_nFolder == FOLDER_VECTOR )
1015         {
1016            g_bUseDefaults = GetVectorUsesDefaults() ? TRUE : FALSE;
1017         }
1018         else
1019         {
1020            g_bUseDefaults = GetFolderUsesDefaults(g_nFolder, g_nFolderGame) ? TRUE : FALSE;
1021         }
1022      }
1023      SetPropEnabledControls(hDlg);
1024      if (g_nGame == GLOBAL_OPTIONS)
1025         ShowWindow(GetDlgItem(hDlg, IDC_USE_DEFAULT), SW_HIDE);
1026      else
1027         EnableWindow(GetDlgItem(hDlg, IDC_USE_DEFAULT), (g_bUseDefaults) ? FALSE : TRUE);
1028
1029      EnableWindow(GetDlgItem(hDlg, IDC_PROP_RESET), g_bReset);
1030      ShowWindow(hDlg, SW_SHOW);
1031   
1032      return 1;
1033
1034   case WM_HSCROLL:
1035      /* slider changed */
1036      HANDLE_WM_HSCROLL(hDlg, wParam, lParam, OptOnHScroll);
1037      g_bUseDefaults = FALSE;
1038      g_bReset = TRUE;
1039      EnableWindow(GetDlgItem(hDlg, IDC_USE_DEFAULT), TRUE);
1040      PropSheet_Changed(GetParent(hDlg), hDlg);
1041
1042      // make sure everything's copied over, to determine what's changed
1043      PropToOptions(hDlg,pGameOpts);
1044      datamap_read_all_controls(properties_datamap, hDlg, pGameOpts);
1045      // redraw it, it might be a new color now
1046      InvalidateRect((HWND)lParam,NULL,TRUE);
1047
1048      break;
1049
1050   case WM_COMMAND:
1051      {
1052         /* Below, 'changed' is used to signify the 'Apply'
1053          * button should be enabled.
1054          */
1055         WORD wID         = GET_WM_COMMAND_ID(wParam, lParam);
1056         HWND hWndCtrl    = GET_WM_COMMAND_HWND(wParam, lParam);
1057         WORD wNotifyCode = GET_WM_COMMAND_CMD(wParam, lParam);
1058         BOOL changed     = FALSE;
1059         int nCurSelection = 0;
1060         TCHAR szClass[256];
1061
1062         switch (wID)
1063         {
1064         case IDC_REFRESH:
1065            if (wNotifyCode == LBN_SELCHANGE)
1066            {
1067               RefreshSelectionChange(hDlg, hWndCtrl);
1068               changed = TRUE;
1069            }
1070            break;
1071
1072         case IDC_ASPECT:
1073            nCurSelection = Button_GetCheck( GetDlgItem(hDlg, IDC_ASPECT));
1074            if( g_bAutoAspect[GetSelectedScreen(hDlg)] != nCurSelection )
1075            {
1076               changed = TRUE;
1077               g_bAutoAspect[GetSelectedScreen(hDlg)] = nCurSelection;
1078            }
1079            break;
1080
1081         case IDC_SELECT_EFFECT:
1082            changed = SelectEffect(hDlg);
1083            break;
1084
1085         case IDC_RESET_EFFECT:
1086            changed = ResetEffect(hDlg);
1087            break;
1088
1089         case IDC_PROP_RESET:
1090            if (wNotifyCode != BN_CLICKED)
1091               break;
1092
1093            options_copy(pGameOpts, origGameOpts);
1094            if (g_nGame > -1)
1095               SetGameUsesDefaults(g_nGame,orig_uses_defaults);
1096            datamap_populate_all_controls(properties_datamap, hDlg, pGameOpts);
1097            OptionsToProp(hDlg, pGameOpts);
1098            SetPropEnabledControls(hDlg);
1099            g_bReset = FALSE;
1100            PropSheet_UnChanged(GetParent(hDlg), hDlg);
1101            g_bUseDefaults = orig_uses_defaults;
1102            EnableWindow(GetDlgItem(hDlg, IDC_USE_DEFAULT), (g_bUseDefaults) ? FALSE : TRUE);
1103            break;
1104
1105         case IDC_USE_DEFAULT:
1106            if (g_nGame != GLOBAL_OPTIONS)
1107            {
1108               // NPW 20-Apr-2007 - I hate this code.  WTF were people thinking!  This
1109               // code has more spaghetti than the entire nation of Italy
1110               if( g_nGame != FOLDER_OPTIONS )
1111               {
1112                  SetGameUsesDefaults(g_nGame,TRUE);
1113
1114                  SaveGameOptions(g_nGame);
1115                  pGameOpts = GetGameOptions(g_nGame, -1);
1116               }
1117               else
1118               {
1119                  if( g_nFolder == FOLDER_VECTOR)
1120                     options_copy(pGameOpts, GetDefaultOptions(GLOBAL_OPTIONS, TRUE));
1121                  //Not Vector Folder, but Source Folder of Vector Games
1122                  else if ( DriverIsVector(g_nFolderGame) )
1123                     options_copy(pGameOpts, GetVectorOptions());
1124                  // every other folder
1125                  else
1126                     options_copy(pGameOpts, GetDefaultOptions(GLOBAL_OPTIONS, FALSE));
1127
1128                  SaveFolderOptions(g_nFolder, g_nFolderGame);
1129                  pGameOpts = GetFolderOptions(g_nFolder, (g_nFolder == FOLDER_VECTOR));
1130               }
1131               datamap_populate_all_controls(properties_datamap, hDlg, pGameOpts);
1132               OptionsToProp(hDlg, pGameOpts);
1133               SetPropEnabledControls(hDlg);
1134               g_bUseDefaults = TRUE;
1135
1136               if (orig_uses_defaults != g_bUseDefaults)
1137               {
1138                  PropSheet_Changed(GetParent(hDlg), hDlg);
1139                  g_bReset = TRUE;
1140               }
1141               else
1142               {
1143                  PropSheet_UnChanged(GetParent(hDlg), hDlg);
1144                  g_bReset = FALSE;
1145               }
1146               EnableWindow(GetDlgItem(hDlg, IDC_USE_DEFAULT), (g_bUseDefaults) ? FALSE : TRUE);
1147            }
1148            break;
1149
1150         case IDC_SCREENSELECT:
1151            if ((wNotifyCode == CBN_SELCHANGE) || (wNotifyCode == CBN_SELENDOK))
1152            {
1153               changed = datamap_read_control(properties_datamap, hDlg, pGameOpts, wID);
1154               datamap_populate_control(properties_datamap, hDlg, pGameOpts, IDC_SCREEN);
1155            }
1156            break;
1157
1158         case IDC_SCREEN:
1159            // NPW 3-Apr-2007:  Ugh I'm only perpetuating the vile hacks in this code
1160            if ((wNotifyCode == CBN_SELCHANGE) || (wNotifyCode == CBN_SELENDOK))
1161            {
1162               changed = datamap_read_control(properties_datamap, hDlg, pGameOpts, wID);
1163               datamap_populate_control(properties_datamap, hDlg, pGameOpts, IDC_REFRESH);
1164               datamap_populate_control(properties_datamap, hDlg, pGameOpts, IDC_SIZES);
1165
1166               if (strcmp(options_get_string(pGameOpts, "screen0"), options_get_string(origGameOpts, "screen0")) ||
1167                  strcmp(options_get_string(pGameOpts, "screen1"), options_get_string(origGameOpts, "screen1")) ||
1168                  strcmp(options_get_string(pGameOpts, "screen2"), options_get_string(origGameOpts, "screen2")) ||
1169                  strcmp(options_get_string(pGameOpts, "screen3"), options_get_string(origGameOpts, "screen3")))
1170               {
1171                  changed = TRUE;
1172               }
1173            }
1174            break;
1175
1176         default:
1177#ifdef MESS
1178            if (MessPropertiesCommand(hDlg, wNotifyCode, wID, &changed))
1179               break;
1180#endif // MESS
1181
1182            // use default behavior; try to get the result out of the datamap if
1183            // appropriate
1184            GetClassName(hWndCtrl, szClass, ARRAY_LENGTH(szClass));
1185            if (!_tcscmp(szClass, WC_COMBOBOX))
1186            {
1187               // combo box
1188               if ((wNotifyCode == CBN_SELCHANGE) || (wNotifyCode == CBN_SELENDOK))
1189               {
1190                  changed = datamap_read_control(properties_datamap, hDlg, pGameOpts, wID);
1191               }
1192            }
1193            else if (!_tcscmp(szClass, WC_BUTTON) && (GetWindowLong(hWndCtrl, GWL_STYLE) & BS_CHECKBOX))
1194            {
1195               // check box
1196               changed = datamap_read_control(properties_datamap, hDlg, pGameOpts, wID);
1197            }
1198            break;
1199         }
1200
1201         if (changed == TRUE)
1202         {
1203            // enable the apply button   
1204            if (g_nGame > -1)
1205               SetGameUsesDefaults(g_nGame,FALSE);
1206            g_bUseDefaults = FALSE;
1207            PropSheet_Changed(GetParent(hDlg), hDlg);
1208            g_bReset = TRUE;
1209            EnableWindow(GetDlgItem(hDlg, IDC_USE_DEFAULT), (g_bUseDefaults) ? FALSE : TRUE);
1210         }
1211         SetPropEnabledControls(hDlg);
1212
1213         // make sure everything's copied over, to determine what's changed
1214         datamap_read_all_controls(properties_datamap, hDlg, pGameOpts);
1215
1216         // redraw it, it might be a new color now
1217         if (GetDlgItem(hDlg,wID))
1218            InvalidateRect(GetDlgItem(hDlg,wID),NULL,FALSE);
1219
1220      }
1221      break;
1222
1223   case WM_NOTIFY:
1224      {
1225         switch (((NMHDR *) lParam)->code)
1226         {
1227            //We'll need to use a CheckState Table
1228            //Because this one gets called for all kinds of other things too, and not only if a check is set
1229         case PSN_SETACTIVE:
1230            /* Initialize the controls. */
1231            datamap_populate_all_controls(properties_datamap, hDlg, pGameOpts);
1232            OptionsToProp(hDlg, pGameOpts);
1233            SetPropEnabledControls(hDlg);
1234            EnableWindow(GetDlgItem(hDlg, IDC_USE_DEFAULT), (g_bUseDefaults) ? FALSE : TRUE);
1235            break;
1236
1237         case PSN_APPLY:
1238            /* Save and apply the options here */
1239            if (g_nGame == GLOBAL_OPTIONS)
1240            {
1241               pGameOpts = GetDefaultOptions(g_nGame, FALSE);
1242               datamap_read_all_controls(properties_datamap, hDlg, pGameOpts);
1243            }
1244            else if (g_nGame == FOLDER_OPTIONS)
1245            {
1246               pGameOpts = GetFolderOptions(g_nFolder, (g_nFolder == FOLDER_VECTOR));
1247               datamap_read_all_controls(properties_datamap, hDlg, pGameOpts);
1248               SaveFolderOptions(g_nFolder, g_nFolderGame);
1249            }
1250            else
1251            {
1252               //SetGameUsesDefaults(g_nGame,g_bUseDefaults);
1253               //orig_uses_defaults = g_bUseDefaults;
1254               pGameOpts = GetGameOptions(g_nGame, -1);
1255            }
1256
1257            options_copy(origGameOpts, pGameOpts);
1258
1259            datamap_populate_all_controls(properties_datamap, hDlg, pGameOpts);
1260            OptionsToProp(hDlg, pGameOpts);
1261            SetPropEnabledControls(hDlg);
1262            EnableWindow(GetDlgItem(hDlg, IDC_USE_DEFAULT), (g_bUseDefaults) ? FALSE : TRUE);
1263            g_bReset = FALSE;
1264            PropSheet_UnChanged(GetParent(hDlg), hDlg);
1265            SetWindowLong(hDlg, DWL_MSGRESULT, TRUE);
1266            return PSNRET_NOERROR;
1267
1268         case PSN_KILLACTIVE:
1269            /* Save Changes to the options here. */
1270            datamap_read_all_controls(properties_datamap, hDlg, pGameOpts);
1271            ResetDataMap(hDlg);
1272            SetWindowLong(hDlg, DWL_MSGRESULT, FALSE);
1273            return 1; 
1274
1275         case PSN_RESET:
1276            // Reset to the original values. Disregard changes
1277            options_copy(pGameOpts, origGameOpts);
1278            SetWindowLong(hDlg, DWL_MSGRESULT, FALSE);
1279            break;
1280
1281         case PSN_HELP:
1282            // User wants help for this property page
1283            break;
1284         }
1285      }
1286      break;
1287   case WM_CTLCOLORSTATIC :
1288   case WM_CTLCOLOREDIT :
1289      if( g_nGame >= 0 )
1290      {
1291         if( DriverIsClone(g_nGame) )
1292         {
1293            nParentIndex = GetParentIndex( drivers[g_nGame] );
1294         }
1295      }
1296      //Set the Coloring of the elements
1297      if (GetWindowLong((HWND)lParam, GWL_ID) < 0)
1298         break;
1299      if (IsControlOptionValue(hDlg,(HWND)lParam, GetDefaultOptions( -1, FALSE) ) )
1300      {
1301         //Normal Black case
1302         SetTextColor((HDC)wParam,COLOR_WINDOWTEXT);
1303      }
1304      else if (IsControlOptionValue(hDlg,(HWND)lParam, GetVectorOptions() )  && DriverIsVector(g_nFolderGame) )
1305      {
1306         SetTextColor((HDC)wParam,VECTOR_COLOR);
1307      }
1308      else if (IsControlOptionValue(hDlg,(HWND)lParam, GetSourceOptions(g_nFolderGame ) ) )
1309      {
1310         SetTextColor((HDC)wParam,FOLDER_COLOR);
1311      }
1312      else if ((nParentIndex >=0) && (IsControlOptionValue(hDlg,(HWND)lParam, GetGameOptions(nParentIndex, g_nFolder ) ) ) )
1313      {
1314         SetTextColor((HDC)wParam,PARENT_COLOR);
1315      }
1316//      else if ( (g_nGame >= 0) && (IsControlOptionValue(hDlg,(HWND)lParam, GetGameOptions(g_nGame, g_nFolder) ) ) )
1317      else if ( (g_nGame >= 0) && (IsControlOptionValue(hDlg,(HWND)lParam, origGameOpts ) ) )
1318      {
1319         SetTextColor((HDC)wParam,GAME_COLOR);
1320      }
1321      else
1322      {
1323         switch ( g_nPropertyMode )
1324         {
1325            case SOURCE_GAME:
1326               SetTextColor((HDC)wParam,GAME_COLOR);
1327               break;
1328            case SOURCE_FOLDER:
1329               SetTextColor((HDC)wParam,FOLDER_COLOR);
1330               break;
1331            case SOURCE_VECTOR:
1332               SetTextColor((HDC)wParam,VECTOR_COLOR);
1333               break;
1334            default:
1335            case SOURCE_GLOBAL:
1336               SetTextColor((HDC)wParam,COLOR_WINDOWTEXT);
1337               break;
1338         }
1339      }
1340      if( Msg == WM_CTLCOLORSTATIC )
1341      {
1342         if (SafeIsAppThemed())
1343         {
1344            HWND hWnd = PropSheet_GetTabControl(GetParent(hDlg));
1345            // Set the background mode to transparent
1346            SetBkMode((HDC)wParam, TRANSPARENT);
1347
1348            // Get the controls window dimensions
1349            GetWindowRect((HWND)lParam, &rc);
1350
1351            // Map the coordinates to coordinates with the upper left corner of dialog control as base
1352            MapWindowPoints(NULL, hWnd, (LPPOINT)(&rc), 2);
1353
1354            // Adjust the position of the brush for this control (else we see the top left of the brush as background)
1355            SetBrushOrgEx((HDC)wParam, -rc.left, -rc.top, NULL);
1356
1357            // Return the brush
1358            return (INT_PTR)(hBkBrush);
1359         }
1360         else
1361         {
1362            SetBkColor((HDC) wParam,GetSysColor(COLOR_3DFACE) );
1363         }
1364      }
1365      else
1366         SetBkColor((HDC)wParam,RGB(255,255,255) );
1367      UnrealizeObject(background_brush);
1368      return (DWORD)background_brush;
1369      break;
1370   case WM_HELP:
1371      /* User clicked the ? from the upper right on a control */
1372      HelpFunction(((LPHELPINFO)lParam)->hItemHandle, MAME32CONTEXTHELP, HH_TP_HELP_WM_HELP, GetHelpIDs());
1373      break;
1374
1375   case WM_CONTEXTMENU:
1376      HelpFunction((HWND)wParam, MAME32CONTEXTHELP, HH_TP_HELP_CONTEXTMENU, GetHelpIDs());
1377      break;
1378
1379   }
1380   EnableWindow(GetDlgItem(hDlg, IDC_PROP_RESET), g_bReset);
1381
1382   return 0;
1383}
1384
1385/* Read controls that are not handled in the DataMap */
1386static void PropToOptions(HWND hWnd, core_options *o)
1387{
1388   HWND hCtrl;
1389   HWND hCtrl2;
1390   HWND hCtrl3;
1391
1392   if (g_nGame > -1)
1393      SetGameUsesDefaults(g_nGame,g_bUseDefaults);
1394
1395   /* aspect ratio */
1396   hCtrl  = GetDlgItem(hWnd, IDC_ASPECTRATION);
1397   hCtrl2 = GetDlgItem(hWnd, IDC_ASPECTRATIOD);
1398   hCtrl3 = GetDlgItem(hWnd, IDC_ASPECT);
1399   if (hCtrl && hCtrl2 && hCtrl3)
1400   {
1401      char aspect_option[32];
1402      snprintf(aspect_option, ARRAY_LENGTH(aspect_option), "aspect%d", GetSelectedScreen(hWnd));
1403
1404      if (Button_GetCheck(hCtrl3))
1405      {
1406         options_set_string(o, aspect_option, "auto", OPTION_PRIORITY_CMDLINE);
1407      }
1408      else
1409      {
1410         int n = 0;
1411         int d = 0;
1412         TCHAR buffer[200];
1413         char buffer2[200];
1414
1415         Edit_GetText(hCtrl,buffer,sizeof(buffer));
1416         _stscanf(buffer,TEXT("%d"),&n);
1417
1418         Edit_GetText(hCtrl2,buffer,sizeof(buffer));
1419         _stscanf(buffer,TEXT("%d"),&d);
1420
1421         if (n == 0 || d == 0)
1422         {
1423            n = 4;
1424            d = 3;
1425         }
1426
1427         snprintf(buffer2,sizeof(buffer2),"%d:%d",n,d);
1428         options_set_string(o, aspect_option, buffer2, OPTION_PRIORITY_CMDLINE);
1429      }
1430   }
1431}
1432
1433/* Populate controls that are not handled in the DataMap */
1434static void OptionsToProp(HWND hWnd, core_options* o)
1435{
1436   HWND hCtrl;
1437   HWND hCtrl2;
1438   TCHAR buf[100];
1439   int  n = 0;
1440   int  d = 0;
1441
1442   /* video */
1443
1444   /* Setup refresh list based on depth. */
1445   datamap_update_control(properties_datamap, hWnd, pGameOpts, IDC_REFRESH);
1446   /* Setup Select screen*/
1447   UpdateSelectScreenUI(hWnd );
1448
1449   hCtrl = GetDlgItem(hWnd, IDC_ASPECT);
1450   if (hCtrl)
1451   {
1452      Button_SetCheck(hCtrl, g_bAutoAspect[GetSelectedScreen(hWnd)] )   ;
1453   }
1454
1455   /* Bios select list */
1456   hCtrl = GetDlgItem(hWnd, IDC_BIOS);
1457   if (hCtrl)
1458   {
1459      const char* cBuffer;
1460      int i = 0;
1461      int iCount = ComboBox_GetCount( hCtrl );
1462      for( i=0; i< iCount; i++ )
1463      {
1464         cBuffer = (const char*)ComboBox_GetItemData( hCtrl, i );
1465         if (strcmp(cBuffer, options_get_string(pGameOpts, OPTION_BIOS) ) == 0)
1466         {
1467            (void)ComboBox_SetCurSel(hCtrl, i);
1468            break;
1469         }
1470
1471      }
1472   }
1473
1474
1475   hCtrl = GetDlgItem(hWnd, IDC_ASPECT);
1476   if (hCtrl)
1477   {
1478      char aspect_option[32];
1479      snprintf(aspect_option, ARRAY_LENGTH(aspect_option), "aspect%d", GetSelectedScreen(hWnd));
1480      if( strcmp(options_get_string(o, aspect_option), "auto") == 0)
1481      {
1482         Button_SetCheck(hCtrl, TRUE);
1483         g_bAutoAspect[GetSelectedScreen(hWnd)] = TRUE;
1484      }
1485      else
1486      {
1487         Button_SetCheck(hCtrl, FALSE);
1488         g_bAutoAspect[GetSelectedScreen(hWnd)] = FALSE;
1489      }
1490   }
1491
1492   /* aspect ratio */
1493   hCtrl  = GetDlgItem(hWnd, IDC_ASPECTRATION);
1494   hCtrl2 = GetDlgItem(hWnd, IDC_ASPECTRATIOD);
1495   if (hCtrl && hCtrl2)
1496   {
1497      char aspect_option[32];
1498      snprintf(aspect_option, ARRAY_LENGTH(aspect_option), "aspect%d", GetSelectedScreen(hWnd));
1499
1500      n = 0;
1501      d = 0;
1502      if (options_get_string(o, aspect_option))
1503      {
1504         if (sscanf(options_get_string(o, aspect_option), "%d:%d", &n, &d) == 2 && n != 0 && d != 0)
1505         {
1506            _stprintf(buf, TEXT("%d"), n);
1507            Edit_SetText(hCtrl, buf);
1508            _stprintf(buf, TEXT("%d"), d);
1509            Edit_SetText(hCtrl2, buf);
1510         }
1511         else
1512         {
1513            Edit_SetText(hCtrl,  TEXT("4"));
1514            Edit_SetText(hCtrl2, TEXT("3"));
1515         }
1516      }
1517      else
1518      {
1519         Edit_SetText(hCtrl,  TEXT("4"));
1520         Edit_SetText(hCtrl2, TEXT("3"));
1521      }
1522   }
1523}
1524
1525/* Adjust controls - tune them to the currently selected game */
1526static void SetPropEnabledControls(HWND hWnd)
1527{
1528   HWND hCtrl;
1529   int  nIndex;
1530   int  sound;
1531   BOOL ddraw = FALSE;
1532   BOOL d3d = FALSE;
1533   BOOL gdi = FALSE;
1534   BOOL useart = TRUE;
1535   BOOL multimon = (DirectDraw_GetNumDisplays() >= 2);
1536   int joystick_attached = 0;
1537   int in_window = 0;
1538
1539   nIndex = g_nGame;
1540   
1541   d3d = !mame_stricmp(options_get_string(pGameOpts, WINOPTION_VIDEO), "d3d");
1542   ddraw = !mame_stricmp(options_get_string(pGameOpts, WINOPTION_VIDEO), "ddraw");
1543   gdi = !d3d && !ddraw;
1544
1545   in_window = options_get_bool(pGameOpts, WINOPTION_WINDOW);
1546   Button_SetCheck(GetDlgItem(hWnd, IDC_ASPECT), g_bAutoAspect[GetSelectedScreen(hWnd)] );
1547
1548   EnableWindow(GetDlgItem(hWnd, IDC_WAITVSYNC), !gdi);
1549   EnableWindow(GetDlgItem(hWnd, IDC_TRIPLE_BUFFER), !gdi);
1550   EnableWindow(GetDlgItem(hWnd, IDC_PRESCALE), !gdi);
1551   EnableWindow(GetDlgItem(hWnd, IDC_PRESCALEDISP), !gdi);
1552   EnableWindow(GetDlgItem(hWnd, IDC_HWSTRETCH),       ddraw && DirectDraw_HasHWStretch());
1553   EnableWindow(GetDlgItem(hWnd, IDC_SWITCHRES), TRUE);
1554   EnableWindow(GetDlgItem(hWnd, IDC_SYNCREFRESH),     TRUE);
1555   EnableWindow(GetDlgItem(hWnd, IDC_REFRESH),         !in_window );
1556   EnableWindow(GetDlgItem(hWnd, IDC_REFRESHTEXT),     !in_window );
1557   EnableWindow(GetDlgItem(hWnd, IDC_FSGAMMA),      !in_window);
1558   EnableWindow(GetDlgItem(hWnd, IDC_FSGAMMATEXT),  !in_window);
1559   EnableWindow(GetDlgItem(hWnd, IDC_FSGAMMADISP),  !in_window);
1560   EnableWindow(GetDlgItem(hWnd, IDC_FSBRIGHTNESS),      !in_window);
1561   EnableWindow(GetDlgItem(hWnd, IDC_FSBRIGHTNESSTEXT),  !in_window);
1562   EnableWindow(GetDlgItem(hWnd, IDC_FSBRIGHTNESSDISP),  !in_window);
1563   EnableWindow(GetDlgItem(hWnd, IDC_FSCONTRAST),      !in_window);
1564   EnableWindow(GetDlgItem(hWnd, IDC_FSCONTRASTTEXT),  !in_window);
1565   EnableWindow(GetDlgItem(hWnd, IDC_FSCONTRASTDISP),  !in_window);
1566
1567   EnableWindow(GetDlgItem(hWnd, IDC_ASPECTRATIOTEXT), !g_bAutoAspect[GetSelectedScreen(hWnd)]);
1568   EnableWindow(GetDlgItem(hWnd, IDC_ASPECTRATION), !g_bAutoAspect[GetSelectedScreen(hWnd)]);
1569   EnableWindow(GetDlgItem(hWnd, IDC_ASPECTRATIOD), !g_bAutoAspect[GetSelectedScreen(hWnd)]);
1570
1571   EnableWindow(GetDlgItem(hWnd,IDC_D3D_FILTER),d3d);
1572   EnableWindow(GetDlgItem(hWnd,IDC_D3D_VERSION),d3d);
1573   
1574   //Switchres and D3D or ddraw enable the per screen parameters
1575
1576   EnableWindow(GetDlgItem(hWnd, IDC_NUMSCREENS),                 (ddraw || d3d) && multimon);
1577   EnableWindow(GetDlgItem(hWnd, IDC_NUMSCREENSDISP),             (ddraw || d3d) && multimon);
1578   EnableWindow(GetDlgItem(hWnd, IDC_SCREENSELECT),               (ddraw || d3d) && multimon);
1579   EnableWindow(GetDlgItem(hWnd, IDC_SCREENSELECTTEXT),           (ddraw || d3d) && multimon);
1580
1581   EnableWindow(GetDlgItem(hWnd, IDC_ARTWORK_CROP),   useart);
1582   EnableWindow(GetDlgItem(hWnd, IDC_BACKDROPS),      useart);
1583   EnableWindow(GetDlgItem(hWnd, IDC_BEZELS),         useart);
1584   EnableWindow(GetDlgItem(hWnd, IDC_OVERLAYS),      useart);
1585   EnableWindow(GetDlgItem(hWnd, IDC_ARTMISCTEXT),      useart);
1586
1587   /* Joystick options */
1588   joystick_attached = DIJoystick.Available();
1589
1590   Button_Enable(GetDlgItem(hWnd,IDC_JOYSTICK),      joystick_attached);
1591   EnableWindow(GetDlgItem(hWnd, IDC_JDZTEXT),         joystick_attached);
1592   EnableWindow(GetDlgItem(hWnd, IDC_JDZDISP),         joystick_attached);
1593   EnableWindow(GetDlgItem(hWnd, IDC_JDZ),            joystick_attached);
1594   EnableWindow(GetDlgItem(hWnd, IDC_JSATTEXT),         joystick_attached);
1595   EnableWindow(GetDlgItem(hWnd, IDC_JSATDISP),         joystick_attached);
1596   EnableWindow(GetDlgItem(hWnd, IDC_JSAT),            joystick_attached);
1597   /* Trackball / Mouse options */
1598   if (nIndex <= -1 || DriverUsesTrackball(nIndex) || DriverUsesLightGun(nIndex))
1599      Button_Enable(GetDlgItem(hWnd,IDC_USE_MOUSE),TRUE);
1600   else
1601      Button_Enable(GetDlgItem(hWnd,IDC_USE_MOUSE),FALSE);
1602
1603   if (!in_window && (nIndex <= -1 || DriverUsesLightGun(nIndex)))
1604   {
1605      // on WinXP the Lightgun and Dual Lightgun switches are no longer supported use mouse instead
1606      OSVERSIONINFOEX osvi;
1607      BOOL bOsVersionInfoEx;
1608      // Try calling GetVersionEx using the OSVERSIONINFOEX structure.
1609      // If that fails, try using the OSVERSIONINFO structure.
1610
1611      ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
1612      osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
1613
1614      if( !(bOsVersionInfoEx = GetVersionEx ((OSVERSIONINFO *) &osvi)) )
1615      {
1616         osvi.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
1617         bOsVersionInfoEx = GetVersionEx ( (OSVERSIONINFO *) &osvi);
1618      }
1619
1620      if( bOsVersionInfoEx && (osvi.dwPlatformId == VER_PLATFORM_WIN32_NT) && (osvi.dwMajorVersion >= 5) )
1621      {
1622         BOOL use_lightgun;
1623         //XP and above...
1624         Button_Enable(GetDlgItem(hWnd,IDC_LIGHTGUN),FALSE);
1625         use_lightgun = Button_GetCheck(GetDlgItem(hWnd,IDC_USE_MOUSE));
1626         Button_Enable(GetDlgItem(hWnd,IDC_DUAL_LIGHTGUN),FALSE);
1627         Button_Enable(GetDlgItem(hWnd,IDC_RELOAD),use_lightgun);
1628      }
1629      else
1630      {
1631         BOOL use_lightgun;
1632         // Older than XP
1633         Button_Enable(GetDlgItem(hWnd,IDC_LIGHTGUN),TRUE);
1634         use_lightgun = Button_GetCheck(GetDlgItem(hWnd,IDC_LIGHTGUN));
1635         Button_Enable(GetDlgItem(hWnd,IDC_DUAL_LIGHTGUN),use_lightgun);
1636         Button_Enable(GetDlgItem(hWnd,IDC_RELOAD),use_lightgun);
1637      }
1638   }
1639   else
1640   {
1641      Button_Enable(GetDlgItem(hWnd,IDC_LIGHTGUN),FALSE);
1642      Button_Enable(GetDlgItem(hWnd,IDC_DUAL_LIGHTGUN),FALSE);
1643      Button_Enable(GetDlgItem(hWnd,IDC_RELOAD),FALSE);
1644   }
1645
1646
1647   /* Sound options */
1648   hCtrl = GetDlgItem(hWnd, IDC_USE_SOUND);
1649   if (hCtrl)
1650   {
1651      sound = Button_GetCheck(hCtrl);
1652      ComboBox_Enable(GetDlgItem(hWnd, IDC_SAMPLERATE), (sound != 0));
1653
1654      EnableWindow(GetDlgItem(hWnd,IDC_VOLUME),sound);
1655      EnableWindow(GetDlgItem(hWnd,IDC_RATETEXT),sound);
1656      EnableWindow(GetDlgItem(hWnd,IDC_VOLUMEDISP),sound);
1657      EnableWindow(GetDlgItem(hWnd,IDC_VOLUMETEXT),sound);
1658      EnableWindow(GetDlgItem(hWnd,IDC_AUDIO_LATENCY),sound);
1659      EnableWindow(GetDlgItem(hWnd,IDC_AUDIO_LATENCY_DISP),sound);
1660      EnableWindow(GetDlgItem(hWnd,IDC_AUDIO_LATENCY_TEXT),sound);
1661      SetSamplesEnabled(hWnd, nIndex, sound);
1662      SetStereoEnabled(hWnd, nIndex);
1663      SetYM3812Enabled(hWnd, nIndex);
1664   }
1665   
1666   if (Button_GetCheck(GetDlgItem(hWnd, IDC_AUTOFRAMESKIP)))
1667      EnableWindow(GetDlgItem(hWnd, IDC_FRAMESKIP), FALSE);
1668   else
1669      EnableWindow(GetDlgItem(hWnd, IDC_FRAMESKIP), TRUE);
1670
1671   if (nIndex <= -1 || DriverHasOptionalBIOS(nIndex))
1672      EnableWindow(GetDlgItem(hWnd,IDC_BIOS),TRUE);
1673   else
1674      EnableWindow(GetDlgItem(hWnd,IDC_BIOS),FALSE);
1675
1676}
1677
1678//============================================================
1679//  CONTROL HELPER FUNCTIONS FOR DATA EXCHANGE
1680//============================================================
1681
1682static void RotateReadControl(datamap *map, HWND dialog, HWND control, core_options *opts, const char *option_name)
1683{
1684   int selected_index = ComboBox_GetCurSel(control);
1685   options_set_bool(opts, OPTION_ROR,      selected_index == 1, OPTION_PRIORITY_CMDLINE);
1686   options_set_bool(opts, OPTION_ROL,      selected_index == 2, OPTION_PRIORITY_CMDLINE);
1687   options_set_bool(opts, OPTION_ROTATE,   selected_index != 3, OPTION_PRIORITY_CMDLINE);
1688   options_set_bool(opts, OPTION_AUTOROR,   selected_index == 4, OPTION_PRIORITY_CMDLINE);
1689   options_set_bool(opts, OPTION_AUTOROL,   selected_index == 5, OPTION_PRIORITY_CMDLINE);
1690}
1691
1692
1693
1694static void RotatePopulateControl(datamap *map, HWND dialog, HWND control, core_options *opts, const char *option_name)
1695{
1696   int selected_index = 0;
1697   if (options_get_bool(opts, OPTION_ROR) && !options_get_bool(opts, OPTION_ROL))
1698      selected_index = 1;
1699   else if (!options_get_bool(opts, OPTION_ROR) && options_get_bool(opts, OPTION_ROL))
1700      selected_index = 2;
1701   else if (!options_get_bool(opts, OPTION_ROTATE))
1702      selected_index = 3;
1703   else if (options_get_bool(opts, OPTION_AUTOROR))
1704      selected_index = 4;
1705   else if (options_get_bool(opts, OPTION_AUTOROL))
1706      selected_index = 5;
1707
1708   (void)ComboBox_SetCurSel(control, selected_index);
1709}
1710
1711
1712
1713static void ScreenReadControl(datamap *map, HWND dialog, HWND control, core_options *opts, const char *option_name)
1714{
1715   char screen_option_name[32];
1716   const char *screen_option_value;
1717   int selected_screen;
1718   int screen_option_index;
1719
1720   selected_screen = GetSelectedScreen(dialog);
1721   screen_option_index = ComboBox_GetCurSel(control);
1722   screen_option_value = (const char *) ComboBox_GetItemData(control, screen_option_index);
1723   snprintf(screen_option_name, ARRAY_LENGTH(screen_option_name), "screen%d", selected_screen);
1724   options_set_string(opts, screen_option_name, screen_option_value, OPTION_PRIORITY_CMDLINE);
1725}
1726
1727
1728
1729static void ScreenPopulateControl(datamap *map, HWND dialog, HWND control, core_options *opts, const char *option_name)
1730{
1731   int iMonitors;
1732   DISPLAY_DEVICE dd;
1733   int i = 0;
1734   int nSelection = 0;
1735   TCHAR* t_option = 0;
1736
1737   /* Remove all items in the list. */
1738   (void)ComboBox_ResetContent(control);
1739   (void)ComboBox_InsertString(control, 0, TEXT("Auto"));
1740   (void)ComboBox_SetItemData(control, 0, (const char*)mame_strdup("auto"));
1741
1742   //Dynamically populate it, by enumerating the Monitors
1743   iMonitors = GetSystemMetrics(SM_CMONITORS); // this gets the count of monitors attached
1744   ZeroMemory(&dd, sizeof(dd));
1745   dd.cb = sizeof(dd);
1746   for(i=0; EnumDisplayDevices(NULL, i, &dd, 0); i++)
1747   {
1748      if( !(dd.StateFlags & DISPLAY_DEVICE_MIRRORING_DRIVER) )
1749      {
1750         char screen_option[32];
1751
1752         //we have to add 1 to account for the "auto" entry
1753         (void)ComboBox_InsertString(control, i+1, win_tstring_strdup(dd.DeviceName));
1754         (void)ComboBox_SetItemData(control, i+1, (void*)win_tstring_strdup(dd.DeviceName));
1755
1756         snprintf(screen_option, ARRAY_LENGTH(screen_option), "screen%d", GetSelectedScreen(dialog));
1757         t_option = tstring_from_utf8(options_get_string(opts, screen_option));
1758         if( !t_option )
1759            return;
1760         if (_tcscmp(t_option, dd.DeviceName) == 0)
1761            nSelection = i+1;
1762         free(t_option);
1763      }
1764   }
1765   (void)ComboBox_SetCurSel(control, nSelection);
1766}
1767
1768
1769
1770static void ViewSetOptionName(datamap *map, HWND dialog, HWND control, char *buffer, size_t buffer_size)
1771{
1772   snprintf(buffer, buffer_size, "view%d", GetSelectedScreen(dialog));
1773}
1774
1775
1776
1777static void ViewPopulateControl(datamap *map, HWND dialog, HWND control, core_options *opts, const char *option_name)
1778{
1779   int i;
1780   int selected_index = 0;
1781   char view_option[32];
1782   const char *view;
1783
1784   // determine the view option value
1785   snprintf(view_option, ARRAY_LENGTH(view_option), "view%d", GetSelectedScreen(dialog));
1786   view = options_get_string(opts, view_option);
1787
1788   (void)ComboBox_ResetContent(control);
1789   for (i = 0; i < NUMVIEW; i++)
1790   {
1791      (void)ComboBox_InsertString(control, i, g_ComboBoxView[i].m_pText);
1792      (void)ComboBox_SetItemData(control, i, g_ComboBoxView[i].m_pData);
1793
1794      if (!strcmp(view, g_ComboBoxView[i].m_pData))
1795         selected_index = i;
1796   }
1797   (void)ComboBox_SetCurSel(control, selected_index);
1798}
1799
1800
1801
1802static void DefaultInputPopulateControl(datamap *map, HWND dialog, HWND control, core_options *opts, const char *option_name)
1803{
1804   WIN32_FIND_DATA FindFileData;
1805   HANDLE hFind;
1806   TCHAR *ext;
1807   TCHAR root[256];
1808   TCHAR path[256];
1809   int selected = 0;
1810   int index = 0;
1811   LPCTSTR t_ctrlr_option = 0;
1812   LPTSTR buf = 0;
1813   const char *ctrlr_option;
1814   TCHAR* t_ctrldir;
1815
1816   // determine the ctrlr option
1817   ctrlr_option = options_get_string(opts, OPTION_CTRLR);
1818   if( ctrlr_option != NULL ) {
1819      buf = tstring_from_utf8(ctrlr_option);
1820      if( !buf )
1821         return;
1822      t_ctrlr_option = buf;
1823   }
1824   else {
1825      t_ctrlr_option = TEXT("");
1826   }
1827
1828   // reset the controllers dropdown
1829   (void)ComboBox_ResetContent(control);
1830   (void)ComboBox_InsertString(control, index, TEXT("Standard"));
1831   (void)ComboBox_SetItemData(control, index, "");
1832   index++;
1833   
1834   t_ctrldir = tstring_from_utf8(GetCtrlrDir());
1835   if( !t_ctrldir ) {
1836      if( buf )
1837         free(buf);
1838      return;
1839   }
1840
1841   _stprintf (path, TEXT("%s\\*.*"), t_ctrldir);
1842   
1843   free(t_ctrldir);
1844
1845   hFind = FindFirstFile(path, &FindFileData);
1846
1847   if (hFind != INVALID_HANDLE_VALUE)
1848   {
1849      do
1850      {
1851         // copy the filename
1852         _tcscpy (root,FindFileData.cFileName);
1853
1854         // find the extension
1855         ext = _tcsrchr (root,'.');
1856         if (ext)
1857         {
1858            // check if it's a cfg file
1859            if (_tcscmp (ext, TEXT(".cfg")) == 0)
1860            {
1861               // and strip off the extension
1862               *ext = 0;
1863
1864               // set the option?
1865               if (!_tcscmp(root, t_ctrlr_option))
1866                  selected = index;
1867
1868               // add it as an option
1869               (void)ComboBox_InsertString(control, index, root);
1870               (void)ComboBox_SetItemData(control, index, (void*)win_tstring_strdup(root));   // FIXME - leaks memory!
1871               index++;
1872            }
1873         }
1874      }
1875      while (FindNextFile (hFind, &FindFileData) != 0);
1876     
1877      FindClose (hFind);
1878   }
1879
1880   (void)ComboBox_SetCurSel(control, selected);
1881   
1882   if( buf )
1883      free(buf);
1884}
1885
1886
1887
1888static void ResolutionSetOptionName(datamap *map, HWND dialog, HWND control, char *buffer, size_t buffer_size)
1889{
1890   snprintf(buffer, buffer_size, "resolution%d", GetSelectedScreen(dialog));
1891}
1892
1893
1894
1895static void ResolutionReadControl(datamap *map, HWND dialog, HWND control, core_options *opts, const char *option_name)
1896{
1897   HWND refresh_control = GetDlgItem(dialog, IDC_REFRESH);
1898   HWND sizes_control = GetDlgItem(dialog, IDC_SIZES);
1899   int refresh_index, refresh_value, width, height;
1900   char option_value[256];
1901   TCHAR buffer[256];
1902
1903   if (refresh_control && sizes_control)
1904   {
1905      (void)ComboBox_GetText(sizes_control, buffer, ARRAY_LENGTH(buffer) - 1);
1906      if (_stscanf(buffer, TEXT("%d x %d"), &width, &height) == 2)
1907      {
1908         refresh_index = ComboBox_GetCurSel(refresh_control);
1909         refresh_value = ComboBox_GetItemData(refresh_control, refresh_index);
1910         snprintf(option_value, ARRAY_LENGTH(option_value), "%dx%d@%d", width, height, refresh_value);
1911      }
1912      else
1913      {
1914         snprintf(option_value, ARRAY_LENGTH(option_value), "auto");
1915      }
1916      options_set_string(opts, option_name, option_value, OPTION_PRIORITY_CMDLINE);
1917   }
1918}
1919
1920
1921
1922static void ResolutionPopulateControl(datamap *map, HWND dialog, HWND control_, core_options *opts, const char *option_name)
1923{
1924   HWND sizes_control = GetDlgItem(dialog, IDC_SIZES);
1925   HWND refresh_control = GetDlgItem(dialog, IDC_REFRESH);
1926   int width, height, refresh;
1927   const char *option_value;
1928   int sizes_index = 0;
1929   int refresh_index = 0;
1930   int sizes_selection = 0;
1931   int refresh_selection = 0;
1932   char screen_option[32];
1933   const char *screen;
1934   LPTSTR t_screen;
1935   TCHAR buf[16];
1936   int i;
1937   DEVMODE devmode;
1938
1939   if (sizes_control && refresh_control)
1940   {
1941      // determine the resolution
1942      option_value = options_get_string(opts, option_name);
1943      if (sscanf(option_value, "%dx%d@%d", &width, &height, &refresh) != 3)
1944      {
1945         width = 0;
1946         height = 0;
1947         refresh = 0;
1948      }
1949
1950      // reset sizes control
1951      (void)ComboBox_ResetContent(sizes_control);
1952      (void)ComboBox_InsertString(sizes_control, sizes_index, TEXT("Auto"));
1953      (void)ComboBox_SetItemData(sizes_control, sizes_index, 0);
1954      sizes_index++;
1955
1956      // reset refresh control
1957      (void)ComboBox_ResetContent(refresh_control);
1958      (void)ComboBox_InsertString(refresh_control, refresh_index, TEXT("Auto"));
1959      (void)ComboBox_SetItemData(refresh_control, refresh_index, 0);
1960      refresh_index++;
1961
1962      // determine which screen we're using
1963      snprintf(screen_option, ARRAY_LENGTH(screen_option), "screen%d", GetSelectedScreen(dialog));
1964      screen = options_get_string(opts, screen_option);
1965      t_screen = tstring_from_utf8(screen);
1966
1967      // retrieve screen information
1968      devmode.dmSize = sizeof(devmode);
1969      for (i = 0; EnumDisplaySettings(t_screen, i, &devmode); i++)
1970      {
1971         if ((devmode.dmBitsPerPel == 32 ) // Only 32 bit depth supported by core
1972            &&(devmode.dmDisplayFrequency == refresh || refresh == 0))
1973         {
1974            _sntprintf(buf, ARRAY_LENGTH(buf), TEXT("%li x %li"),
1975               devmode.dmPelsWidth, devmode.dmPelsHeight);
1976
1977            if (ComboBox_FindString(sizes_control, 0, buf) == CB_ERR)
1978            {
1979               (void)ComboBox_InsertString(sizes_control, sizes_index, buf);
1980
1981               if ((width == devmode.dmPelsWidth) && (height == devmode.dmPelsHeight))
1982                  sizes_selection = sizes_index;
1983               sizes_index++;
1984
1985            }
1986         }
1987         if (devmode.dmDisplayFrequency >= 10 )
1988         {
1989            // I have some devmode "vga" which specifes 1 Hz, which is probably bogus, so we filter it out
1990
1991            _sntprintf(buf, ARRAY_LENGTH(buf), TEXT("%li Hz"), devmode.dmDisplayFrequency);
1992
1993            if (ComboBox_FindString(refresh_control, 0, buf) == CB_ERR)
1994            {
1995               (void)ComboBox_InsertString(refresh_control, refresh_index, buf);
1996               (void)ComboBox_SetItemData(refresh_control, refresh_index, devmode.dmDisplayFrequency);
1997
1998               if (refresh == devmode.dmDisplayFrequency)
1999                  refresh_selection = refresh_index;
2000
2001               refresh_index++;
2002            }
2003         }
2004      }
2005      free(t_screen);
2006
2007      (void)ComboBox_SetCurSel(sizes_control, sizes_selection);
2008      (void)ComboBox_SetCurSel(refresh_control, refresh_selection);
2009   }
2010}
2011
2012
2013
2014//============================================================
2015
2016/************************************************************
2017 * DataMap initializers
2018 ************************************************************/
2019
2020/* Initialize local helper variables */
2021static void ResetDataMap(HWND hWnd)
2022{
2023   char screen_option[32];
2024
2025   snprintf(screen_option, ARRAY_LENGTH(screen_option), "screen%d", GetSelectedScreen(hWnd));
2026
2027   if (options_get_string(pGameOpts, screen_option) == NULL
2028      || (mame_stricmp(options_get_string(pGameOpts, screen_option), "") == 0 )
2029      || (mame_stricmp(options_get_string(pGameOpts, screen_option), "auto") == 0 ) )
2030   {
2031      options_set_string(pGameOpts, screen_option, "auto", OPTION_PRIORITY_CMDLINE);
2032   }
2033}
2034
2035/* Build the control mapping by adding all needed information to the DataMap */
2036static void BuildDataMap(void)
2037{
2038   properties_datamap = datamap_create();
2039
2040   /* video */
2041   datamap_add(properties_datamap, IDC_D3D_VERSION,         DM_INT,      WINOPTION_D3DVERSION);
2042   datamap_add(properties_datamap, IDC_VIDEO_MODE,            DM_STRING,   WINOPTION_VIDEO);
2043   datamap_add(properties_datamap, IDC_PRESCALE,            DM_INT,      WINOPTION_PRESCALE);
2044   datamap_add(properties_datamap, IDC_PRESCALEDISP,         DM_INT,      WINOPTION_PRESCALE);
2045   datamap_add(properties_datamap, IDC_NUMSCREENS,            DM_INT,      WINOPTION_NUMSCREENS);
2046   datamap_add(properties_datamap, IDC_NUMSCREENSDISP,         DM_INT,      WINOPTION_NUMSCREENS);
2047   datamap_add(properties_datamap, IDC_AUTOFRAMESKIP,         DM_BOOL,   OPTION_AUTOFRAMESKIP);
2048   datamap_add(properties_datamap, IDC_FRAMESKIP,            DM_INT,      OPTION_FRAMESKIP);
2049   datamap_add(properties_datamap, IDC_WAITVSYNC,            DM_BOOL,   WINOPTION_WAITVSYNC);
2050   datamap_add(properties_datamap, IDC_TRIPLE_BUFFER,         DM_BOOL,   WINOPTION_TRIPLEBUFFER);
2051   datamap_add(properties_datamap, IDC_WINDOWED,            DM_BOOL,   WINOPTION_WINDOW);
2052   datamap_add(properties_datamap, IDC_HWSTRETCH,            DM_BOOL,   WINOPTION_HWSTRETCH);
2053   datamap_add(properties_datamap, IDC_SWITCHRES,            DM_BOOL,   WINOPTION_SWITCHRES);
2054   datamap_add(properties_datamap, IDC_MAXIMIZE,            DM_BOOL,   WINOPTION_MAXIMIZE);
2055   datamap_add(properties_datamap, IDC_KEEPASPECT,            DM_BOOL,   WINOPTION_KEEPASPECT);
2056   datamap_add(properties_datamap, IDC_SYNCREFRESH,         DM_BOOL,   WINOPTION_SYNCREFRESH);
2057   datamap_add(properties_datamap, IDC_THROTTLE,            DM_BOOL,   OPTION_THROTTLE);
2058   datamap_add(properties_datamap, IDC_FSGAMMA,            DM_FLOAT,   WINOPTION_FULLSCREENGAMMA);
2059   datamap_add(properties_datamap, IDC_FSGAMMADISP,         DM_FLOAT,   WINOPTION_FULLSCREENGAMMA);
2060   datamap_add(properties_datamap, IDC_FSBRIGHTNESS,         DM_FLOAT,   WINOPTION_FULLSCREENBRIGHTNESS);
2061   datamap_add(properties_datamap, IDC_FSBRIGHTNESSDISP,      DM_FLOAT,   WINOPTION_FULLSCREENBRIGHTNESS);
2062   datamap_add(properties_datamap, IDC_FSCONTRAST,            DM_FLOAT,   WINOPTION_FULLLSCREENCONTRAST);
2063   datamap_add(properties_datamap, IDC_FSCONTRASTDISP,         DM_FLOAT,   WINOPTION_FULLLSCREENCONTRAST);
2064   datamap_add(properties_datamap, IDC_EFFECT,               DM_STRING,   WINOPTION_EFFECT);
2065   datamap_add(properties_datamap, IDC_ASPECTRATIOD,         DM_STRING,  NULL);
2066   datamap_add(properties_datamap, IDC_ASPECTRATION,         DM_STRING,  NULL);
2067   datamap_add(properties_datamap, IDC_REFRESH,            DM_STRING,  NULL);
2068   datamap_add(properties_datamap, IDC_SIZES,               DM_STRING,  NULL);
2069
2070   // direct3d
2071   datamap_add(properties_datamap, IDC_D3D_FILTER,            DM_BOOL,   WINOPTION_FILTER);
2072
2073   // input
2074   datamap_add(properties_datamap, IDC_DEFAULT_INPUT,         DM_STRING,   OPTION_CTRLR);
2075   datamap_add(properties_datamap, IDC_USE_MOUSE,            DM_BOOL,   OPTION_MOUSE);
2076   datamap_add(properties_datamap, IDC_JOYSTICK,            DM_BOOL,   OPTION_JOYSTICK);
2077   datamap_add(properties_datamap, IDC_JDZ,               DM_FLOAT,   OPTION_JOYSTICK_DEADZONE);
2078   datamap_add(properties_datamap, IDC_JDZDISP,            DM_FLOAT,   OPTION_JOYSTICK_DEADZONE);
2079   datamap_add(properties_datamap, IDC_JSAT,               DM_FLOAT,   OPTION_JOYSTICK_SATURATION);
2080   datamap_add(properties_datamap, IDC_JSATDISP,            DM_FLOAT,   OPTION_JOYSTICK_SATURATION);
2081   datamap_add(properties_datamap, IDC_STEADYKEY,            DM_BOOL,   OPTION_STEADYKEY);
2082   datamap_add(properties_datamap, IDC_LIGHTGUN,            DM_BOOL,   OPTION_LIGHTGUN);
2083   datamap_add(properties_datamap, IDC_DUAL_LIGHTGUN,         DM_BOOL,   WINOPTION_DUAL_LIGHTGUN);
2084   datamap_add(properties_datamap, IDC_RELOAD,               DM_BOOL,   OPTION_OFFSCREEN_RELOAD);
2085   datamap_add(properties_datamap, IDC_MULTIKEYBOARD,         DM_BOOL,   OPTION_MULTIKEYBOARD);
2086   datamap_add(properties_datamap, IDC_MULTIMOUSE,            DM_BOOL,   OPTION_MULTIMOUSE);
2087
2088   // controller mapping
2089   datamap_add(properties_datamap, IDC_PADDLE,               DM_STRING,   OPTION_PADDLE_DEVICE);
2090   datamap_add(properties_datamap, IDC_ADSTICK,            DM_STRING,   OPTION_ADSTICK_DEVICE);
2091   datamap_add(properties_datamap, IDC_PEDAL,               DM_STRING,   OPTION_PEDAL_DEVICE);
2092   datamap_add(properties_datamap, IDC_DIAL,               DM_STRING,   OPTION_DIAL_DEVICE);
2093   datamap_add(properties_datamap, IDC_TRACKBALL,            DM_STRING,   OPTION_TRACKBALL_DEVICE);
2094   datamap_add(properties_datamap, IDC_LIGHTGUNDEVICE,         DM_STRING,   OPTION_LIGHTGUN_DEVICE);
2095
2096   // core video
2097   datamap_add(properties_datamap, IDC_BRIGHTCORRECT,         DM_FLOAT,   OPTION_BRIGHTNESS);
2098   datamap_add(properties_datamap, IDC_BRIGHTCORRECTDISP,      DM_FLOAT,   OPTION_BRIGHTNESS);
2099   datamap_add(properties_datamap, IDC_PAUSEBRIGHT,         DM_FLOAT,   OPTION_PAUSE_BRIGHTNESS);
2100   datamap_add(properties_datamap, IDC_PAUSEBRIGHTDISP,      DM_FLOAT,   OPTION_PAUSE_BRIGHTNESS);
2101   datamap_add(properties_datamap, IDC_ROTATE,               DM_INT,      NULL);
2102   datamap_add(properties_datamap, IDC_FLIPX,               DM_BOOL,   OPTION_FLIPX);
2103   datamap_add(properties_datamap, IDC_FLIPY,               DM_BOOL,   OPTION_FLIPY);
2104   datamap_add(properties_datamap, IDC_SCREEN,               DM_STRING,   NULL);
2105   datamap_add(properties_datamap, IDC_SCREENSELECT,         DM_STRING,   NULL);
2106   datamap_add(properties_datamap, IDC_VIEW,               DM_STRING,   NULL);
2107
2108   // debugres
2109   datamap_add(properties_datamap, IDC_GAMMA,               DM_FLOAT,   OPTION_GAMMA);
2110   datamap_add(properties_datamap, IDC_GAMMADISP,            DM_FLOAT,   OPTION_GAMMA);
2111   datamap_add(properties_datamap, IDC_CONTRAST,            DM_FLOAT,   OPTION_CONTRAST);
2112   datamap_add(properties_datamap, IDC_CONTRASTDISP,         DM_FLOAT,   OPTION_CONTRAST);
2113
2114   // vector
2115   datamap_add(properties_datamap, IDC_ANTIALIAS,            DM_BOOL,   OPTION_ANTIALIAS);
2116   datamap_add(properties_datamap, IDC_BEAM,               DM_FLOAT,   OPTION_BEAM);
2117   datamap_add(properties_datamap, IDC_BEAMDISP,            DM_FLOAT,   OPTION_BEAM);
2118   datamap_add(properties_datamap, IDC_FLICKER,            DM_FLOAT,   OPTION_FLICKER);
2119   datamap_add(properties_datamap, IDC_FLICKERDISP,         DM_FLOAT,   OPTION_FLICKER);
2120
2121   // sound
2122   datamap_add(properties_datamap, IDC_SAMPLERATE,            DM_INT,      OPTION_SAMPLERATE);
2123   datamap_add(properties_datamap, IDC_SAMPLES,            DM_BOOL,   OPTION_SAMPLES);
2124   datamap_add(properties_datamap, IDC_USE_SOUND,            DM_BOOL,   OPTION_SOUND);
2125   datamap_add(properties_datamap, IDC_VOLUME,               DM_INT,      OPTION_VOLUME);
2126   datamap_add(properties_datamap, IDC_VOLUMEDISP,            DM_INT,      OPTION_VOLUME);
2127   datamap_add(properties_datamap, IDC_AUDIO_LATENCY,         DM_INT,      WINOPTION_AUDIO_LATENCY);
2128   datamap_add(properties_datamap, IDC_AUDIO_LATENCY_DISP,      DM_INT,      WINOPTION_AUDIO_LATENCY);
2129
2130   // misc artwork options
2131   datamap_add(properties_datamap, IDC_BACKDROPS,            DM_BOOL,   OPTION_USE_BACKDROPS);
2132   datamap_add(properties_datamap, IDC_OVERLAYS,            DM_BOOL,   OPTION_USE_OVERLAYS);
2133   datamap_add(properties_datamap, IDC_BEZELS,               DM_BOOL,   OPTION_USE_BEZELS);
2134   datamap_add(properties_datamap, IDC_ARTWORK_CROP,         DM_BOOL,   OPTION_ARTWORK_CROP);
2135
2136   // misc
2137   datamap_add(properties_datamap, IDC_CHEAT,               DM_BOOL,   OPTION_CHEAT);
2138   datamap_add(properties_datamap, IDC_LOG,               DM_BOOL,   OPTION_LOG);
2139   datamap_add(properties_datamap, IDC_SLEEP,               DM_BOOL,   OPTION_SLEEP);
2140   datamap_add(properties_datamap, IDC_HIGH_PRIORITY,         DM_INT,      WINOPTION_PRIORITY);
2141   datamap_add(properties_datamap, IDC_HIGH_PRIORITYTXT,      DM_INT,      WINOPTION_PRIORITY);
2142   datamap_add(properties_datamap, IDC_SKIP_GAME_INFO,         DM_BOOL,   OPTION_SKIP_GAMEINFO);
2143   datamap_add(properties_datamap, IDC_BIOS,               DM_STRING,   OPTION_BIOS);
2144   datamap_add(properties_datamap, IDC_ENABLE_AUTOSAVE,      DM_BOOL,   OPTION_AUTOSAVE);
2145   datamap_add(properties_datamap, IDC_MULTITHREAD_RENDERING,   DM_BOOL,   WINOPTION_MULTITHREADING);
2146
2147   // set up callbacks
2148   datamap_set_callback(properties_datamap, IDC_ROTATE,      DCT_READ_CONTROL,      RotateReadControl);
2149   datamap_set_callback(properties_datamap, IDC_ROTATE,      DCT_POPULATE_CONTROL,   RotatePopulateControl);
2150   datamap_set_callback(properties_datamap, IDC_SCREEN,      DCT_READ_CONTROL,      ScreenReadControl);
2151   datamap_set_callback(properties_datamap, IDC_SCREEN,      DCT_POPULATE_CONTROL,   ScreenPopulateControl);
2152   datamap_set_callback(properties_datamap, IDC_VIEW,         DCT_POPULATE_CONTROL,   ViewPopulateControl);
2153   datamap_set_callback(properties_datamap, IDC_REFRESH,      DCT_READ_CONTROL,      ResolutionReadControl);
2154   datamap_set_callback(properties_datamap, IDC_REFRESH,      DCT_POPULATE_CONTROL,   ResolutionPopulateControl);
2155   datamap_set_callback(properties_datamap, IDC_SIZES,         DCT_READ_CONTROL,      ResolutionReadControl);
2156   datamap_set_callback(properties_datamap, IDC_SIZES,         DCT_POPULATE_CONTROL,   ResolutionPopulateControl);
2157   datamap_set_callback(properties_datamap, IDC_DEFAULT_INPUT,   DCT_POPULATE_CONTROL,   DefaultInputPopulateControl);
2158   datamap_set_option_name_callback(properties_datamap, IDC_VIEW,      ViewSetOptionName);
2159   datamap_set_option_name_callback(properties_datamap, IDC_REFRESH,   ResolutionSetOptionName);
2160   datamap_set_option_name_callback(properties_datamap, IDC_SIZES,      ResolutionSetOptionName);
2161
2162   // formats
2163   datamap_set_int_format(properties_datamap, IDC_VOLUMEDISP,         "%ddB");
2164   datamap_set_int_format(properties_datamap, IDC_AUDIO_LATENCY_DISP,   "%d/5");
2165   datamap_set_float_format(properties_datamap, IDC_BEAMDISP,         "%03.2f");
2166   datamap_set_float_format(properties_datamap, IDC_FLICKERDISP,      "%03.2f");
2167   datamap_set_float_format(properties_datamap, IDC_GAMMADISP,         "%03.2f");
2168   datamap_set_float_format(properties_datamap, IDC_BRIGHTCORRECTDISP,   "%03.2f");
2169   datamap_set_float_format(properties_datamap, IDC_CONTRASTDISP,      "%03.2f");
2170   datamap_set_float_format(properties_datamap, IDC_PAUSEBRIGHTDISP,   "%03.2f");
2171   datamap_set_float_format(properties_datamap, IDC_FSGAMMADISP,      "%03.2f");
2172   datamap_set_float_format(properties_datamap, IDC_FSBRIGHTNESSDISP,   "%03.2f");
2173   datamap_set_float_format(properties_datamap, IDC_FSCONTRASTDISP,   "%03.2f");
2174   datamap_set_float_format(properties_datamap, IDC_JDZDISP,         "%03.2f");
2175   datamap_set_float_format(properties_datamap, IDC_JSATDISP,         "%03.2f");
2176
2177   // trackbar ranges
2178   datamap_set_trackbar_range(properties_datamap, IDC_PRESCALE,    1, 10, 1);
2179   datamap_set_trackbar_range(properties_datamap, IDC_JDZ,         0.00,  1.00, 0.05);
2180   datamap_set_trackbar_range(properties_datamap, IDC_JSAT,        0.00,  1.00, 0.05);
2181
2182#ifdef MESS
2183   // MESS specific stuff
2184   MessBuildDataMap(properties_datamap);
2185#endif // MESS
2186}
2187
2188BOOL IsControlOptionValue(HWND hDlg,HWND hwnd_ctrl, core_options *opts )
2189{
2190   int control_id = GetWindowLong(hwnd_ctrl, GWL_ID);
2191
2192   // certain controls we need to handle specially
2193   switch (control_id)
2194   {
2195      case IDC_ASPECTRATION :
2196      {
2197         char aspect_option[32];
2198         int n1 = 0, n2 = 0;
2199         int d1 = 0, d2 = 0;
2200
2201         snprintf(aspect_option, ARRAY_LENGTH(aspect_option), "aspect%d", GetSelectedScreen(hDlg));
2202
2203         sscanf(options_get_string(pGameOpts, aspect_option), "%d:%d", &n1, &d1);
2204         sscanf(options_get_string(opts, aspect_option), "%d:%d", &n2, &d2);
2205
2206         return n1 == n2;
2207      }
2208      case IDC_ASPECTRATIOD :
2209      {
2210         char aspect_option[32];
2211         int n1 = 0, n2 = 0;
2212         int d1 = 0, d2 = 0;
2213
2214         snprintf(aspect_option, ARRAY_LENGTH(aspect_option), "aspect%d", GetSelectedScreen(hDlg));
2215
2216         sscanf(options_get_string(pGameOpts, aspect_option), "%d:%d", &n1, &d1);
2217         sscanf(options_get_string(opts, aspect_option), "%d:%d", &n2, &d2);
2218
2219         return d1 == d2;
2220      }
2221      case IDC_SIZES :
2222      {
2223         char resolution_option[32];
2224         int x1=0,y1=0,x2=0,y2=0;
2225
2226         snprintf(resolution_option, ARRAY_LENGTH(resolution_option), "resolution%d", GetSelectedScreen(hDlg));
2227
2228         if ((strcmp(options_get_string(pGameOpts, resolution_option), "auto") == 0) &&
2229            (strcmp(options_get_string(opts, resolution_option), "auto") == 0))
2230            return TRUE;
2231         
2232         sscanf(options_get_string(pGameOpts, resolution_option),"%d x %d",&x1,&y1);
2233         sscanf(options_get_string(opts, resolution_option),"%d x %d",&x2,&y2);
2234
2235         return x1 == x2 && y1 == y2;     
2236      }
2237      case IDC_ROTATE :
2238      {
2239         datamap_read_control(properties_datamap, hDlg, pGameOpts, control_id);
2240
2241         return (options_get_bool(pGameOpts, OPTION_ROR) == options_get_bool(opts, OPTION_ROR))
2242            || (options_get_bool(pGameOpts, OPTION_ROL) == options_get_bool(opts, OPTION_ROL));
2243      }
2244   }
2245
2246   // most options we can compare using data in the data map
2247   //if (IsControlDifferent(hDlg,hwnd_ctrl,pGameOpts,opts))
2248   //   return FALSE;
2249
2250   return TRUE;
2251}
2252
2253
2254static void SetStereoEnabled(HWND hWnd, int nIndex)
2255{
2256   BOOL enabled = FALSE;
2257   HWND hCtrl;
2258   machine_config drv;
2259   int speakernum, num_speakers;
2260
2261   num_speakers = 0;
2262
2263   if ( nIndex > -1)
2264   {
2265      expand_machine_driver(drivers[nIndex]->drv,&drv);
2266      for (speakernum = 0; speakernum < MAX_SPEAKER; speakernum++)
2267         if (drv.speaker[speakernum].tag != NULL)
2268            num_speakers++;
2269   }
2270
2271   hCtrl = GetDlgItem(hWnd, IDC_STEREO);
2272   if (hCtrl)
2273   {
2274      if (nIndex <= -1 || num_speakers == 2)
2275         enabled = TRUE;
2276
2277      EnableWindow(hCtrl, enabled);
2278   }
2279}
2280
2281static void SetYM3812Enabled(HWND hWnd, int nIndex)
2282{
2283   int i;
2284   BOOL enabled;
2285   HWND hCtrl;
2286   machine_config drv;
2287
2288   if (nIndex > -1)
2289      expand_machine_driver(drivers[nIndex]->drv,&drv);
2290
2291   hCtrl = GetDlgItem(hWnd, IDC_USE_FM_YM3812);
2292   if (hCtrl)
2293   {
2294      enabled = FALSE;
2295      for (i = 0; i < MAX_SOUND; i++)
2296      {
2297         if (nIndex <= -1
2298#if HAS_YM3812
2299         ||  drv.sound[i].sound_type == SOUND_YM3812
2300#endif
2301#if HAS_YM3526
2302         ||  drv.sound[i].sound_type == SOUND_YM3526
2303#endif
2304#if HAS_YM2413
2305         ||  drv.sound[i].sound_type == SOUND_YM2413
2306#endif
2307         )
2308            enabled = TRUE;
2309      }
2310   
2311      EnableWindow(hCtrl, enabled);
2312   }
2313}
2314
2315static void SetSamplesEnabled(HWND hWnd, int nIndex, BOOL bSoundEnabled)
2316{
2317#if (HAS_SAMPLES == 1) || (HAS_VLM5030 == 1)
2318   int i;
2319   BOOL enabled = FALSE;
2320   HWND hCtrl;
2321   machine_config drv;
2322
2323   hCtrl = GetDlgItem(hWnd, IDC_SAMPLES);
2324
2325   if ( nIndex > -1 )
2326      expand_machine_driver(drivers[nIndex]->drv,&drv);
2327   
2328   if (hCtrl)
2329   {
2330      for (i = 0; i < MAX_SOUND; i++)
2331      {
2332         if (nIndex <= -1
2333         ||  drv.sound[i].sound_type == SOUND_SAMPLES
2334#if HAS_VLM5030
2335         ||  drv.sound[i].sound_type == SOUND_VLM5030
2336#endif
2337         )
2338            enabled = TRUE;
2339      }
2340      enabled = enabled && bSoundEnabled;
2341      EnableWindow(hCtrl, enabled);
2342   }
2343#endif
2344}
2345
2346/* Moved here cause it's called in a few places */
2347static void InitializeOptions(HWND hDlg)
2348{
2349   InitializeSoundUI(hDlg);
2350   InitializeSkippingUI(hDlg);
2351   InitializeRotateUI(hDlg);
2352   InitializeSelectScreenUI(hDlg);
2353   InitializeEffectUI(hDlg);
2354   InitializeBIOSUI(hDlg);
2355   InitializeControllerMappingUI(hDlg);
2356   InitializeD3DVersionUI(hDlg);
2357   InitializeVideoUI(hDlg);
2358}
2359
2360/* Moved here because it is called in several places */
2361static void InitializeMisc(HWND hDlg)
2362{
2363   Button_Enable(GetDlgItem(hDlg, IDC_JOYSTICK), DIJoystick.Available());
2364}
2365
2366static void OptOnHScroll(HWND hwnd, HWND hwndCtl, UINT code, int pos)
2367{
2368   if (hwndCtl == GetDlgItem(hwnd, IDC_NUMSCREENS))
2369   {
2370      NumScreensSelectionChange(hwnd);
2371   }
2372}
2373
2374/* Handle changes to the Numscreens slider */
2375static void NumScreensSelectionChange(HWND hwnd)
2376{
2377   //Also Update the ScreenSelect Combo with the new number of screens
2378   UpdateSelectScreenUI(hwnd );
2379}
2380
2381/* Handle changes to the Refresh drop down */
2382static void RefreshSelectionChange(HWND hWnd, HWND hWndCtrl)
2383{
2384   int nCurSelection;
2385
2386   nCurSelection = ComboBox_GetCurSel(hWndCtrl);
2387   if (nCurSelection != CB_ERR)
2388   {
2389      datamap_populate_control(properties_datamap, hWnd, pGameOpts, IDC_SIZES);
2390   }
2391}
2392
2393/* Initialize the sound options */
2394static void InitializeSoundUI(HWND hwnd)
2395{
2396   HWND    hCtrl;
2397   int i = 0;
2398
2399   hCtrl = GetDlgItem(hwnd, IDC_SAMPLERATE);
2400   if (hCtrl)
2401   {
2402      (void)ComboBox_AddString(hCtrl, TEXT("11025"));
2403      (void)ComboBox_SetItemData(hCtrl, i++, 11025);
2404      (void)ComboBox_AddString(hCtrl, TEXT("22050"));
2405      (void)ComboBox_SetItemData(hCtrl, i++, 22050);
2406      (void)ComboBox_AddString(hCtrl, TEXT("44100"));
2407      (void)ComboBox_SetItemData(hCtrl, i++, 44100);
2408      (void)ComboBox_AddString(hCtrl, TEXT("48000"));
2409      (void)ComboBox_SetItemData(hCtrl, i++, 48000);
2410      (void)ComboBox_SetCurSel(hCtrl, 1);
2411   }
2412}
2413
2414/* Populate the Frame Skipping drop down */
2415static void InitializeSkippingUI(HWND hwnd)
2416{
2417   HWND hCtrl = GetDlgItem(hwnd, IDC_FRAMESKIP);
2418   int i = 0;
2419
2420   if (hCtrl)
2421   {
2422      (void)ComboBox_AddString(hCtrl, TEXT("Draw every frame"));
2423      (void)ComboBox_SetItemData(hCtrl, i++, 0);
2424      (void)ComboBox_AddString(hCtrl, TEXT("Skip 1 of 12 frames"));
2425      (void)ComboBox_SetItemData(hCtrl, i++, 1);
2426      (void)ComboBox_AddString(hCtrl, TEXT("Skip 2 of 12 frames"));
2427      (void)ComboBox_SetItemData(hCtrl, i++, 2);
2428      (void)ComboBox_AddString(hCtrl, TEXT("Skip 3 of 12 frames"));
2429      (void)ComboBox_SetItemData(hCtrl, i++, 3);
2430      (void)ComboBox_AddString(hCtrl, TEXT("Skip 4 of 12 frames"));
2431      (void)ComboBox_SetItemData(hCtrl, i++, 4);
2432      (void)ComboBox_AddString(hCtrl, TEXT("Skip 5 of 12 frames"));
2433      (void)ComboBox_SetItemData(hCtrl, i++, 5);
2434      (void)ComboBox_AddString(hCtrl, TEXT("Skip 6 of 12 frames"));
2435      (void)ComboBox_SetItemData(hCtrl, i++, 6);
2436      (void)ComboBox_AddString(hCtrl, TEXT("Skip 7 of 12 frames"));
2437      (void)ComboBox_SetItemData(hCtrl, i++, 7);
2438      (void)ComboBox_AddString(hCtrl, TEXT("Skip 8 of 12 frames"));
2439      (void)ComboBox_SetItemData(hCtrl, i++, 8);
2440      (void)ComboBox_AddString(hCtrl, TEXT("Skip 9 of 12 frames"));
2441      (void)ComboBox_SetItemData(hCtrl, i++, 9);
2442      (void)ComboBox_AddString(hCtrl, TEXT("Skip 10 of 12 frames"));
2443      (void)ComboBox_SetItemData(hCtrl, i++, 10);
2444      (void)ComboBox_AddString(hCtrl, TEXT("Skip 11 of 12 frames"));
2445      (void)ComboBox_SetItemData(hCtrl, i++, 11);
2446   }
2447}
2448
2449/* Populate the Rotate drop down */
2450static void InitializeRotateUI(HWND hwnd)
2451{
2452   HWND hCtrl = GetDlgItem(hwnd, IDC_ROTATE);
2453
2454   if (hCtrl)
2455   {
2456      (void)ComboBox_AddString(hCtrl, TEXT("Default"));             // 0
2457      (void)ComboBox_AddString(hCtrl, TEXT("Clockwise"));           // 1
2458      (void)ComboBox_AddString(hCtrl, TEXT("Anti-clockwise"));      // 2
2459      (void)ComboBox_AddString(hCtrl, TEXT("None"));                // 3
2460      (void)ComboBox_AddString(hCtrl, TEXT("Auto clockwise"));      // 4
2461      (void)ComboBox_AddString(hCtrl, TEXT("Auto anti-clockwise")); // 5
2462   }
2463}
2464
2465/* Populate the Video Mode drop down */
2466static void InitializeVideoUI(HWND hwnd)
2467{
2468   HWND    hCtrl;
2469
2470   hCtrl = GetDlgItem(hwnd, IDC_VIDEO_MODE);
2471   if (hCtrl)
2472   {
2473      int i;
2474      for (i = 0; i < NUMVIDEO; i++)
2475      {
2476         (void)ComboBox_InsertString(hCtrl, i, g_ComboBoxVideo[i].m_pText);
2477         (void)ComboBox_SetItemData( hCtrl, i, g_ComboBoxVideo[i].m_pData);
2478      }
2479   }
2480}
2481
2482/* Populate the D3D Version drop down */
2483static void InitializeD3DVersionUI(HWND hwnd)
2484{
2485   HWND hCtrl = GetDlgItem(hwnd, IDC_D3D_VERSION);
2486   if (hCtrl)
2487   {
2488      int i;
2489      for (i = 0; i < NUMD3DVERSIONS; i++)
2490      {
2491         (void)ComboBox_InsertString(hCtrl, i, g_ComboBoxD3DVersion[i].m_pText);
2492         (void)ComboBox_SetItemData( hCtrl, i, g_ComboBoxD3DVersion[i].m_pData);
2493      }
2494   }
2495}
2496
2497static void UpdateSelectScreenUI(HWND hwnd)
2498{
2499   HWND hCtrl = GetDlgItem(hwnd, IDC_SCREENSELECT);
2500   if (hCtrl)
2501   {
2502      int i, curSel;
2503      curSel = ComboBox_GetCurSel(hCtrl);
2504      if ((curSel < 0) || (curSel >= MAX_SCREENS))
2505         curSel = 0;
2506      (void)ComboBox_ResetContent(hCtrl );
2507      for (i = 0; i < NUMSELECTSCREEN && i < options_get_int(pGameOpts, WINOPTION_NUMSCREENS) ; i++)
2508      {
2509         (void)ComboBox_InsertString(hCtrl, i, g_ComboBoxSelectScreen[i].m_pText);
2510         (void)ComboBox_SetItemData( hCtrl, i, g_ComboBoxSelectScreen[i].m_pData);
2511      }
2512      // Smaller Amount of screens was selected, so use 0
2513      if( i< curSel )
2514         (void)ComboBox_SetCurSel(hCtrl, 0 );
2515      else
2516         (void)ComboBox_SetCurSel(hCtrl, curSel );
2517   }
2518}
2519
2520/* Populate the Select Screen drop down */
2521static void InitializeSelectScreenUI(HWND hwnd)
2522{
2523   UpdateSelectScreenUI(hwnd);
2524}
2525
2526static void InitializeEffectUI(HWND hwnd)
2527{
2528}
2529
2530static void InitializeControllerMappingUI(HWND hwnd)
2531{
2532   int i;
2533   HWND hCtrl = GetDlgItem(hwnd,IDC_PADDLE);
2534   HWND hCtrl1 = GetDlgItem(hwnd,IDC_ADSTICK);
2535   HWND hCtrl2 = GetDlgItem(hwnd,IDC_PEDAL);
2536   HWND hCtrl3 = GetDlgItem(hwnd,IDC_DIAL);
2537   HWND hCtrl4 = GetDlgItem(hwnd,IDC_TRACKBALL);
2538   HWND hCtrl5 = GetDlgItem(hwnd,IDC_LIGHTGUNDEVICE);
2539
2540   if (hCtrl)
2541   {
2542      for (i = 0; i < NUMDEVICES; i++)
2543      {
2544         (void)ComboBox_InsertString(hCtrl, i, g_ComboBoxDevice[i].m_pText);
2545         (void)ComboBox_SetItemData( hCtrl, i, g_ComboBoxDevice[i].m_pData);
2546      }
2547   }
2548   if (hCtrl1)
2549   {
2550      for (i = 0; i < NUMDEVICES; i++)
2551      {
2552         (void)ComboBox_InsertString(hCtrl1, i, g_ComboBoxDevice[i].m_pText);
2553         (void)ComboBox_SetItemData( hCtrl1, i, g_ComboBoxDevice[i].m_pData);
2554      }
2555   }
2556   if (hCtrl2)
2557   {
2558      for (i = 0; i < NUMDEVICES; i++)
2559      {
2560         (void)ComboBox_InsertString(hCtrl2, i, g_ComboBoxDevice[i].m_pText);
2561         (void)ComboBox_SetItemData( hCtrl2, i, g_ComboBoxDevice[i].m_pData);
2562      }
2563   }
2564   if (hCtrl3)
2565   {
2566      for (i = 0; i < NUMDEVICES; i++)
2567      {
2568         (void)ComboBox_InsertString(hCtrl3, i, g_ComboBoxDevice[i].m_pText);
2569         (void)ComboBox_SetItemData( hCtrl3, i, g_ComboBoxDevice[i].m_pData);
2570      }
2571   }
2572   if (hCtrl4)
2573   {
2574      for (i = 0; i < NUMDEVICES; i++)
2575      {
2576         (void)ComboBox_InsertString(hCtrl4, i, g_ComboBoxDevice[i].m_pText);
2577         (void)ComboBox_SetItemData( hCtrl4, i, g_ComboBoxDevice[i].m_pData);
2578      }
2579   }
2580   if (hCtrl5)
2581   {
2582      for (i = 0; i < NUMDEVICES; i++)
2583      {
2584         (void)ComboBox_InsertString(hCtrl5, i, g_ComboBoxDevice[i].m_pText);
2585         (void)ComboBox_SetItemData( hCtrl5, i, g_ComboBoxDevice[i].m_pData);
2586      }
2587   }
2588}
2589
2590
2591static void InitializeBIOSUI(HWND hwnd)
2592{
2593   HWND hCtrl = GetDlgItem(hwnd,IDC_BIOS);
2594   int i = 0;
2595   TCHAR* t_s;
2596   if (hCtrl)
2597   {
2598      const game_driver *gamedrv = drivers[g_nGame];
2599      const rom_entry *rom;
2600
2601      if (g_nGame == GLOBAL_OPTIONS)
2602      {
2603         (void)ComboBox_InsertString(hCtrl, i, TEXT("None"));
2604         (void)ComboBox_SetItemData( hCtrl, i++, "none");
2605         return;
2606      }
2607      if (g_nGame == FOLDER_OPTIONS) //Folder Options
2608      {
2609         gamedrv = drivers[g_nFolderGame];
2610         if (DriverHasOptionalBIOS(g_nFolderGame) == FALSE)
2611         {
2612            (void)ComboBox_InsertString(hCtrl, i, TEXT("None"));
2613            (void)ComboBox_SetItemData( hCtrl, i++, "default");
2614            return;
2615         }
2616         (void)ComboBox_InsertString(hCtrl, i, TEXT("Default"));
2617         (void)ComboBox_SetItemData( hCtrl, i++, "default");
2618
2619         if (gamedrv->rom != NULL)
2620         {
2621            for (rom = gamedrv->rom; !ROMENTRY_ISEND(rom); rom++)
2622            {
2623               if (ROMENTRY_ISSYSTEM_BIOS(rom))
2624               {
2625                  const char *name = ROM_GETHASHDATA(rom);
2626                  t_s = tstring_from_utf8(name);
2627                  if( !t_s )
2628                     return;
2629                  (void)ComboBox_InsertString(hCtrl, i, win_tstring_strdup(t_s));
2630                  (void)ComboBox_SetItemData( hCtrl, i++, name);
2631                  free(t_s);
2632               }
2633            }
2634         }
2635         return;
2636      }
2637
2638      if (DriverHasOptionalBIOS(g_nGame) == FALSE)
2639      {
2640         (void)ComboBox_InsertString(hCtrl, i, TEXT("None"));
2641         (void)ComboBox_SetItemData( hCtrl, i++, "none");
2642         return;
2643      }
2644      (void)ComboBox_InsertString(hCtrl, i, TEXT("Default"));
2645      (void)ComboBox_SetItemData( hCtrl, i++, "default");
2646
2647      if (gamedrv->rom != NULL)
2648      {
2649         for (rom = gamedrv->rom; !ROMENTRY_ISEND(rom); rom++)
2650         {
2651            if (ROMENTRY_ISSYSTEM_BIOS(rom))
2652            {
2653               const char *name = ROM_GETHASHDATA(rom);
2654               t_s = tstring_from_utf8(name);
2655               if( !t_s )
2656                  return;
2657               (void)ComboBox_InsertString(hCtrl, i, win_tstring_strdup(t_s));
2658               (void)ComboBox_SetItemData( hCtrl, i++, name);
2659               free(t_s);
2660            }
2661         }
2662      }
2663   }
2664}
2665
2666static BOOL SelectEffect(HWND hWnd)
2667{
2668   char filename[MAX_PATH];
2669   BOOL changed = FALSE;
2670
2671   *filename = 0;
2672   if (CommonFileDialog(GetOpenFileName, filename, FILETYPE_EFFECT_FILES))
2673   {
2674      //strip Path and extension
2675      char buff[MAX_PATH];
2676      int i, j = 0, k = 0, l = 0;
2677      for(i=0; i<strlen(filename); i++ )
2678      {
2679         if( filename[i] == '\\' )
2680            j = i;
2681         if( filename[i] == '.' )
2682            k = i;
2683      }
2684      for(i=j+1;i<k;i++)
2685      {
2686         buff[l++] = filename[i];
2687      }
2688      buff[l] = '\0';
2689
2690      if (strcmp(buff, options_get_string(pGameOpts, WINOPTION_EFFECT)))
2691      {
2692         options_set_string(pGameOpts, WINOPTION_EFFECT, buff, OPTION_PRIORITY_CMDLINE);
2693         datamap_populate_control(properties_datamap, hWnd, pGameOpts, IDC_EFFECT);
2694         changed = TRUE;
2695      }
2696   }
2697   return changed;
2698}
2699
2700static BOOL ResetEffect(HWND hWnd)
2701{
2702   BOOL changed = FALSE;
2703   const char *new_value = "none";
2704
2705   if (strcmp(new_value, options_get_string(pGameOpts, WINOPTION_EFFECT)))
2706   {
2707      options_set_string(pGameOpts, WINOPTION_EFFECT, new_value, OPTION_PRIORITY_CMDLINE);
2708      datamap_populate_control(properties_datamap, hWnd, pGameOpts, IDC_EFFECT);
2709      changed = TRUE;
2710   }
2711   return changed;
2712}
2713
2714
2715void UpdateBackgroundBrush(HWND hwndTab)
2716{
2717    // Destroy old brush
2718    if (hBkBrush)
2719        DeleteObject(hBkBrush);
2720
2721    hBkBrush = NULL;
2722
2723    // Only do this if the theme is active
2724    if (SafeIsAppThemed())
2725    {
2726        RECT rc;
2727        HDC hDC, hDCMem;
2728      HBITMAP hBmp, hBmpOld;
2729        // Get tab control dimensions
2730        GetWindowRect( hwndTab, &rc);
2731
2732        // Get the tab control DC
2733      hDC = GetDC(hwndTab);
2734
2735        // Create a compatible DC
2736        hDCMem = CreateCompatibleDC(hDC);
2737        hBmp = CreateCompatibleBitmap(hDC,
2738               rc.right - rc.left, rc.bottom - rc.top);
2739        hBmpOld = (HBITMAP)(SelectObject(hDCMem, hBmp));
2740
2741        // Tell the tab control to paint in our DC
2742        SendMessage(hwndTab, WM_PRINTCLIENT, (WPARAM)(hDCMem),
2743           (LPARAM)(PRF_ERASEBKGND | PRF_CLIENT | PRF_NONCLIENT));
2744
2745        // Create a pattern brush from the bitmap selected in our DC
2746        hBkBrush = CreatePatternBrush(hBmp);
2747
2748        // Restore the bitmap
2749        SelectObject(hDCMem, hBmpOld);
2750
2751        // Cleanup
2752        DeleteObject(hBmp);
2753        DeleteDC(hDCMem);
2754        ReleaseDC(hwndTab, hDC);
2755    }
2756}
2757
2758
2759/* End of source file */
src/osd/windows/ui/help.h
r995r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11 ***************************************************************************/
12
13#ifndef HELP_H
14#define HELP_H
15
16#if defined(__GNUC__)
17#define HH_DISPLAY_TOPIC      0
18#define HH_TP_HELP_CONTEXTMENU   16
19#define HH_TP_HELP_WM_HELP      17
20#define HH_CLOSE_ALL         18
21#define HH_INITIALIZE         28
22#define HH_UNINITIALIZE         29
23#else
24#include <htmlhelp.h>
25#endif
26
27typedef struct
28{
29   int      nMenuItem;
30   BOOL   bIsHtmlHelp;
31   LPCSTR   lpFile;
32} MAMEHELPINFO;
33
34extern const MAMEHELPINFO g_helpInfo[];
35
36#if !defined(MAME32HELP)
37#define MAME32HELP "mame32.chm"
38#endif
39
40#if !defined(MAME32CONTEXTHELP)
41#define MAME32CONTEXTHELP "mame32.chm::/cntx_help.txt"
42#endif
43
44extern int HelpInit(void);
45extern void HelpExit(void);
46extern HWND HelpFunction(HWND hwndCaller, LPCSTR pszFile, UINT uCommand, DWORD_PTR dwData);
47
48#endif
src/osd/windows/ui/directdraw.h
r995r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11 ***************************************************************************/
12
13#ifndef DIRECTDRAW_H
14#define DIRECTDRAW_H
15
16#include <ddraw.h>
17
18#define MAXMODES    256 /* Maximum number of DirectDraw Display modes. */
19
20/* Display mode node */
21struct tDisplayMode
22{
23   DWORD m_dwWidth;
24   DWORD m_dwHeight;
25   DWORD m_dwBPP;
26   DWORD m_dwRefresh;
27};
28
29/* EnumDisplayMode Context */
30struct tDisplayModes
31{
32   struct tDisplayMode m_Modes[MAXMODES];
33   int                 m_nNumModes;
34};
35
36extern BOOL DirectDraw_Initialize(void);
37extern void DirectDraw_Close(void);
38
39extern struct tDisplayModes* DirectDraw_GetDisplayModes(void);
40extern int            DirectDraw_GetNumDisplays(void);
41extern BOOL           DirectDraw_HasHWStretch(void);
42extern BOOL           DirectDraw_HasRefresh(void);
43extern LPCTSTR        DirectDraw_GetDisplayName(int num_display);
44
45#endif
src/osd/winui/m32util.c
r0r996
1/***************************************************************************
2
3  M.A.M.E.32   -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11 ***************************************************************************/
12
13/***************************************************************************
14
15  M32Util.c
16
17 ***************************************************************************/
18
19#define WIN32_LEAN_AND_MEAN
20#include <windows.h>
21#include <shellapi.h>
22#include <shlwapi.h>
23#include <assert.h>
24#include <stdio.h>
25#include <tchar.h>
26
27#include "unzip.h"
28#include "bitmask.h"
29#include "screenshot.h"
30#include "sound/samples.h"
31#include "mame32.h"
32#include "m32util.h"
33#include "winutf8.h"
34#include "strconv.h"
35
36
37/***************************************************************************
38   function prototypes
39 ***************************************************************************/
40
41/***************************************************************************
42   External variables
43 ***************************************************************************/
44
45/***************************************************************************
46   Internal structures
47 ***************************************************************************/
48static struct DriversInfo
49{
50   BOOL isClone;
51   BOOL isBroken;
52   BOOL isHarddisk;
53   BOOL hasOptionalBIOS;
54   BOOL isStereo;
55   BOOL isMultiMon;
56   BOOL isVector;
57   BOOL usesRoms;
58   BOOL usesSamples;
59   BOOL usesTrackball;
60   BOOL usesLightGun;
61   BOOL supportsSaveState;
62   BOOL isVertical;
63} *drivers_info = NULL;
64
65
66/***************************************************************************
67   External functions
68 ***************************************************************************/
69
70/*
71   ErrorMsg
72*/
73void __cdecl ErrorMsg(const char* fmt, ...)
74{
75   static FILE*   pFile = NULL;
76   DWORD         dwWritten;
77   char         buf[5000];
78   char         buf2[5000];
79   va_list       va;
80
81   va_start(va, fmt);
82
83   vsprintf(buf, fmt, va);
84
85   win_message_box_utf8(GetActiveWindow(), buf, MAME32NAME, MB_OK | MB_ICONERROR);
86
87   strcpy(buf2, MAME32NAME ": ");
88   strcat(buf2,buf);
89   strcat(buf2, "\n");
90
91   WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), buf2, strlen(buf2), &dwWritten, NULL);
92
93   if (pFile == NULL)
94      pFile = fopen("debug.txt", "wt");
95
96   if (pFile != NULL)
97   {
98      fprintf(pFile, "%s", buf2);
99      fflush(pFile);
100   }
101
102   va_end(va);
103}
104
105void __cdecl dprintf(const char* fmt, ...)
106{
107   char    buf[5000];
108   va_list va;
109
110   va_start(va, fmt);
111
112   _vsnprintf(buf,sizeof(buf),fmt,va);
113
114   win_output_debug_string_utf8(buf);
115
116   va_end(va);
117}
118
119UINT GetDepth(HWND hWnd)
120{
121   UINT   nBPP;
122   HDC    hDC;
123
124   hDC = GetDC(hWnd);
125   
126   nBPP = GetDeviceCaps(hDC, BITSPIXEL) * GetDeviceCaps(hDC, PLANES);
127
128   ReleaseDC(hWnd, hDC);
129
130   return nBPP;
131}
132
133/*
134 * Return TRUE if comctl32.dll is version 4.71 or greater
135 * otherwise return FALSE.
136 */
137LONG GetCommonControlVersion()
138{
139   HMODULE hModule = GetModuleHandle(TEXT("comctl32"));
140
141   if (hModule)
142   {
143      FARPROC lpfnICCE = GetProcAddress(hModule, "InitCommonControlsEx");
144
145      if (NULL != lpfnICCE)
146      {
147         FARPROC lpfnDLLI = GetProcAddress(hModule, "DllInstall");
148
149         if (NULL != lpfnDLLI)
150         {
151            /* comctl 4.71 or greater */
152
153            // see if we can find out exactly
154           
155            DLLGETVERSIONPROC pDllGetVersion;
156            pDllGetVersion = (DLLGETVERSIONPROC)GetProcAddress(hModule, "DllGetVersion");
157
158            /* Because some DLLs might not implement this function, you
159               must test for it explicitly. Depending on the particular
160               DLL, the lack of a DllGetVersion function can be a useful
161               indicator of the version. */
162
163            if(pDllGetVersion)
164            {
165               DLLVERSIONINFO dvi;
166               HRESULT hr;
167
168               ZeroMemory(&dvi, sizeof(dvi));
169               dvi.cbSize = sizeof(dvi);
170
171               hr = (*pDllGetVersion)(&dvi);
172
173               if (SUCCEEDED(hr))
174               {
175                  return PACKVERSION(dvi.dwMajorVersion, dvi.dwMinorVersion);
176               }
177            }
178            return PACKVERSION(4,71);
179         }
180         return PACKVERSION(4,7);
181      }
182      return PACKVERSION(4,0);
183   }
184   /* DLL not found */
185   return PACKVERSION(0,0);
186}
187
188void DisplayTextFile(HWND hWnd, const char *cName)
189{
190   HINSTANCE hErr;
191   LPCTSTR     msg = 0;
192   LPTSTR    tName;
193   
194   tName = tstring_from_utf8(cName);
195   if( !tName )
196      return;
197
198   hErr = ShellExecute(hWnd, NULL, tName, NULL, NULL, SW_SHOWNORMAL);
199   if ((FPTR)hErr > 32)
200   {
201      free(tName);
202      return;
203   }
204
205   switch((FPTR)hErr)
206   {
207   case 0:
208      msg = TEXT("The operating system is out of memory or resources.");
209      break;
210
211   case ERROR_FILE_NOT_FOUND:
212      msg = TEXT("The specified file was not found.");
213      break;
214
215   case SE_ERR_NOASSOC :
216      msg = TEXT("There is no application associated with the given filename extension.");
217      break;
218
219   case SE_ERR_OOM :
220      msg = TEXT("There was not enough memory to complete the operation.");
221      break;
222
223   case SE_ERR_PNF :
224      msg = TEXT("The specified path was not found.");
225      break;
226
227   case SE_ERR_SHARE :
228      msg = TEXT("A sharing violation occurred.");
229      break;
230
231   default:
232      msg = TEXT("Unknown error.");
233   }
234 
235   MessageBox(NULL, msg, tName, MB_OK);
236   
237   free(tName);
238}
239
240char* MyStrStrI(const char* pFirst, const char* pSrch)
241{
242   char* cp = (char*)pFirst;
243   char* s1;
244   char* s2;
245   
246   while (*cp)
247   {
248      s1 = cp;
249      s2 = (char*)pSrch;
250     
251      while (*s1 && *s2 && !mame_strnicmp(s1, s2, 1))
252         s1++, s2++;
253     
254      if (!*s2)
255         return cp;
256     
257      cp++;
258   }
259   return NULL;
260}
261
262char * ConvertToWindowsNewlines(const char *source)
263{
264   static char buf[40000];
265   char *dest;
266
267   dest = buf;
268   while (*source != 0)
269   {
270      if (*source == '\n')
271      {
272         *dest++ = '\r';
273         *dest++ = '\n';
274      }
275      else
276         *dest++ = *source;
277      source++;
278   }
279   *dest = 0;
280   return buf;
281}
282
283/* Lop off path and extention from a source file name
284 * This assumes their is a pathname passed to the function
285 * like src\drivers\blah.c
286 */
287const char * GetDriverFilename(int nIndex)
288{
289   static char tmp[40];
290   char *ptmp;
291
292   const char *s = drivers[nIndex]->source_file;
293
294   tmp[0] = '\0';
295
296   ptmp = strrchr(s, '\\');
297   if (ptmp == NULL)
298      ptmp = strrchr(s, '/');
299   if (ptmp == NULL)
300      return s;
301
302   ptmp++;
303   strcpy(tmp,ptmp);
304   return tmp;
305}
306
307static struct DriversInfo* GetDriversInfo(int driver_index)
308{
309   if (drivers_info == NULL)
310   {
311      int ndriver, i;
312      drivers_info = malloc(sizeof(struct DriversInfo) * driver_list_get_count(drivers));
313      for (ndriver = 0; ndriver < driver_list_get_count(drivers); ndriver++)
314      {
315         const game_driver *gamedrv = drivers[ndriver];
316         struct DriversInfo *gameinfo = &drivers_info[ndriver];
317         const rom_entry *region, *rom;
318         machine_config drv;
319         const input_port_entry *input_ports;
320         int speakernum, num_speakers;
321         gameinfo->isClone = (GetParentRomSetIndex(gamedrv) != -1);
322         gameinfo->isBroken = ((gamedrv->flags & GAME_NOT_WORKING) != 0);
323         gameinfo->supportsSaveState = ((gamedrv->flags & GAME_SUPPORTS_SAVE) != 0);
324         gameinfo->isHarddisk = FALSE;
325         gameinfo->isVertical = (gamedrv->flags & ORIENTATION_SWAP_XY) ? TRUE : FALSE;
326         for (region = rom_first_region(gamedrv); region; region = rom_next_region(region))
327         {
328            if (ROMREGION_ISDISKDATA(region))
329               gameinfo->isHarddisk = TRUE;
330         }
331         gameinfo->hasOptionalBIOS = FALSE;
332         if (gamedrv->rom != NULL)
333         {
334            for (rom = gamedrv->rom; !ROMENTRY_ISEND(rom); rom++)
335            {
336               if (ROMENTRY_ISSYSTEM_BIOS(rom))
337               {
338                  gameinfo->hasOptionalBIOS = TRUE;
339                  break;
340               }
341            }
342         }
343         expand_machine_driver(gamedrv->drv, &drv);
344
345         num_speakers = 0;
346         for (speakernum = 0; speakernum < MAX_SPEAKER; speakernum++)
347            if (drv.speaker[speakernum].tag != NULL)
348               num_speakers++;
349
350         gameinfo->isStereo = (num_speakers > 1);
351         //gameinfo->isMultiMon = ((drv.video_attributes & VIDEO_DUAL_MONITOR) != 0);
352         // Was removed from Core
353         gameinfo->isMultiMon = 0;
354         gameinfo->isVector = ((drv.video_attributes & VIDEO_TYPE_VECTOR) != 0);
355         gameinfo->usesRoms = FALSE;
356         for (region = rom_first_region(gamedrv); region; region = rom_next_region(region))
357            for (rom = rom_first_file(region); rom; rom = rom_next_file(rom))
358            {
359               gameinfo->usesRoms = TRUE;
360               break;
361            }
362         gameinfo->usesSamples = FALSE;
363         
364         if (HAS_SAMPLES || HAS_VLM5030)
365         {
366            for (i = 0; drv.sound[i].sound_type && i < MAX_SOUND; i++)
367            {
368               const char **samplenames = NULL;
369               
370#if (HAS_SAMPLES || HAS_VLM5030)
371               for( i = 0; drv.sound[i].sound_type && i < MAX_SOUND; i++ )
372               {
373#if (HAS_SAMPLES)
374                  if( drv.sound[i].sound_type == SOUND_SAMPLES )
375                     samplenames = ((struct Samplesinterface *)drv.sound[i].config)->samplenames;
376#endif
377               }
378#endif
379               if (samplenames != 0 && samplenames[0] != 0)
380               {
381                  gameinfo->usesSamples = TRUE;
382                  break;
383               }
384            }
385         }
386
387         gameinfo->usesTrackball = FALSE;
388         gameinfo->usesLightGun = FALSE;
389         if (gamedrv->ipt != NULL)
390         {
391            begin_resource_tracking();
392            input_ports = input_port_allocate(gamedrv->ipt, NULL);
393            while (1)
394            {
395               UINT32 type;
396               type = input_ports->type;
397               if (type == IPT_END)
398                  break;
399               if (type == IPT_DIAL || type == IPT_PADDLE ||
400                  type == IPT_TRACKBALL_X || type == IPT_TRACKBALL_Y ||
401                  type == IPT_AD_STICK_X || type == IPT_AD_STICK_Y)
402                  gameinfo->usesTrackball = TRUE;
403               if (type == IPT_LIGHTGUN_X || type == IPT_LIGHTGUN_Y)
404                  gameinfo->usesLightGun = TRUE;
405               input_ports++;
406            }
407            end_resource_tracking();
408         }
409      }
410   }
411   return &drivers_info[driver_index];
412}
413
414BOOL DriverIsClone(int driver_index)
415{
416    return GetDriversInfo(driver_index)->isClone;
417}
418
419BOOL DriverIsBroken(int driver_index)
420{
421   return GetDriversInfo(driver_index)->isBroken;
422}
423
424BOOL DriverIsHarddisk(int driver_index)
425{
426   return GetDriversInfo(driver_index)->isHarddisk;
427}
428
429BOOL DriverIsBios(int driver_index)
430{
431   BOOL bBios = FALSE;
432   if( !( (drivers[driver_index]->flags & GAME_IS_BIOS_ROOT ) == 0)   )
433      bBios = TRUE;
434   return bBios;
435}
436
437
438BOOL DriverHasOptionalBIOS(int driver_index)
439{
440   return GetDriversInfo(driver_index)->hasOptionalBIOS;
441}
442
443BOOL DriverIsStereo(int driver_index)
444{
445   return GetDriversInfo(driver_index)->isStereo;
446}
447BOOL DriverIsMultiMon(int driver_index)
448{
449   return GetDriversInfo(driver_index)->isMultiMon;
450}
451
452BOOL DriverIsVector(int driver_index)
453{
454   return GetDriversInfo(driver_index)->isVector;
455}
456
457BOOL DriverUsesRoms(int driver_index)
458{
459   return GetDriversInfo(driver_index)->usesRoms;
460}
461
462BOOL DriverUsesSamples(int driver_index)
463{
464   return GetDriversInfo(driver_index)->usesSamples;
465}
466
467BOOL DriverUsesTrackball(int driver_index)
468{
469   return GetDriversInfo(driver_index)->usesTrackball;
470}
471
472BOOL DriverUsesLightGun(int driver_index)
473{
474   return GetDriversInfo(driver_index)->usesLightGun;
475}
476
477BOOL DriverSupportsSaveState(int driver_index)
478{
479   return GetDriversInfo(driver_index)->supportsSaveState;
480}
481
482BOOL DriverIsVertical(int driver_index) {
483   return GetDriversInfo(driver_index)->isVertical;
484}
485
486void FlushFileCaches(void)
487{
488   zip_file_cache_clear();
489}
490
491void FreeIfAllocated(char **s)
492{
493   if (*s)
494      free(*s);
495   *s = NULL;
496}
497
498BOOL StringIsSuffixedBy(const char *s, const char *suffix)
499{
500   return (strlen(s) > strlen(suffix)) && (strcmp(s + strlen(s) - strlen(suffix), suffix) == 0);
501}
502
503/***************************************************************************
504   Win32 wrappers
505 ***************************************************************************/
506
507BOOL SafeIsAppThemed(void)
508{
509   BOOL bResult = FALSE;
510   HMODULE hThemes;
511   BOOL (WINAPI *pfnIsAppThemed)(void);
512   
513   hThemes = LoadLibrary(TEXT("uxtheme.dll"));
514   if (hThemes != NULL)
515   {
516      pfnIsAppThemed = (BOOL (WINAPI *)(void)) GetProcAddress(hThemes, "IsAppThemed");
517      if (pfnIsAppThemed != NULL)
518         bResult = pfnIsAppThemed();
519      FreeLibrary(hThemes);
520   }
521   return bResult;
522
523}
524
525
526
527//============================================================
528//  win_extract_icon_utf8
529//============================================================
530
531HICON win_extract_icon_utf8(HINSTANCE inst, const char* exefilename, UINT iconindex)
532{
533   HICON icon = 0;
534   TCHAR* t_exefilename = tstring_from_utf8(exefilename);
535   if( !t_exefilename )
536      return icon;
537   
538   icon = ExtractIcon(inst, t_exefilename, iconindex);
539   
540   free(t_exefilename);
541   
542   return icon;
543}
544
545
546
547//============================================================
548//  win_tstring_strdup
549//============================================================
550
551TCHAR* win_tstring_strdup(LPCTSTR str)
552{
553   TCHAR *cpy = NULL;
554   if (str != NULL)
555   {
556      cpy = malloc((_tcslen(str) + 1) * sizeof(TCHAR));
557      if (cpy != NULL)
558         _tcscpy(cpy, str);
559   }
560   return cpy;
561}
562
563//============================================================
564//  win_create_file_utf8
565//============================================================
566
567HANDLE win_create_file_utf8(const char* filename, DWORD desiredmode, DWORD sharemode,
568                        LPSECURITY_ATTRIBUTES securityattributes, DWORD creationdisposition,
569                        DWORD flagsandattributes, HANDLE templatehandle)
570{
571   HANDLE result = 0;
572   TCHAR* t_filename = tstring_from_utf8(filename);
573   if( !t_filename )
574      return result;
575   
576   result = CreateFile(t_filename, desiredmode, sharemode, securityattributes, creationdisposition,
577                  flagsandattributes, templatehandle);
578
579   free(t_filename);
580                 
581   return result;
582}
583
584//============================================================
585//  win_get_current_directory_utf8
586//============================================================
587
588DWORD win_get_current_directory_utf8(DWORD bufferlength, char* buffer)
589{
590   DWORD result = 0;
591   TCHAR* t_buffer = NULL;
592   char* utf8_buffer = NULL;
593   
594   if( bufferlength > 0 ) {
595      t_buffer = malloc((bufferlength * sizeof(TCHAR)) + 1);
596      if( !t_buffer )
597         return result;
598   }
599   
600   result = GetCurrentDirectory(bufferlength, t_buffer);
601   
602   if( bufferlength > 0 ) {
603      utf8_buffer = utf8_from_tstring(t_buffer);
604      if( !utf8_buffer ) {
605         free(t_buffer);
606         return result;
607      }
608   }
609     
610   strncpy(buffer, utf8_buffer, bufferlength);
611   
612   if( utf8_buffer )
613      free(utf8_buffer);
614   
615   if( t_buffer )
616      free(t_buffer);
617   
618   return result;
619}
620
621//============================================================
622//  win_find_first_file_utf8
623//============================================================
624
625HANDLE win_find_first_file_utf8(const char* filename, LPWIN32_FIND_DATA findfiledata)
626{
627   HANDLE result = 0;
628   TCHAR* t_filename = tstring_from_utf8(filename);
629   if( !t_filename )
630      return result;
631   
632   result = FindFirstFile(t_filename, findfiledata);
633   
634   free(t_filename);
635   
636   return result;
637}
src/osd/winui/treeview.h
r0r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11 ***************************************************************************/
12
13#ifndef TREEVIEW_H
14#define TREEVIEW_H
15
16/* corrections for commctrl.h */
17
18#if defined(__GNUC__)
19/* fix warning: cast does not match function type */
20#undef  TreeView_InsertItem
21#define TreeView_InsertItem(w,i) (HTREEITEM)(LRESULT)(int)SendMessage((w),TVM_INSERTITEM,0,(LPARAM)(LPTV_INSERTSTRUCT)(i))
22
23#undef  TreeView_SetImageList
24#define TreeView_SetImageList(w,h,i) (HIMAGELIST)(LRESULT)(int)SendMessage((w),TVM_SETIMAGELIST,i,(LPARAM)(HIMAGELIST)(h))
25
26#undef  TreeView_GetNextItem
27#define TreeView_GetNextItem(w,i,c) (HTREEITEM)(LRESULT)(int)SendMessage((w),TVM_GETNEXTITEM,c,(LPARAM)(HTREEITEM)(i))
28
29#undef TreeView_HitTest
30#define TreeView_HitTest(hwnd, lpht) \
31    (HTREEITEM)(LRESULT)(int)SNDMSG((hwnd), TVM_HITTEST, 0, (LPARAM)(LPTV_HITTESTINFO)(lpht))
32
33/* fix wrong return type */
34#undef  TreeView_Select
35#define TreeView_Select(w,i,c) (BOOL)(int)SendMessage((w),TVM_SELECTITEM,c,(LPARAM)(HTREEITEM)(i))
36
37#undef TreeView_EditLabel
38#define TreeView_EditLabel(w, i) \
39    SNDMSG(w,TVM_EDITLABEL,0,(LPARAM)(i))
40
41#endif /* defined(__GNUC__) */
42
43/***************************************************************************
44    Folder And Filter Definitions
45 ***************************************************************************/
46
47typedef struct
48{
49   const char *m_lpTitle; // Folder Title
50   const char *short_name;  // for saving in the .ini
51   UINT        m_nFolderId; // ID
52   UINT        m_nIconId; // if >= 0, resource id of icon (IDI_xxx), otherwise index in image list
53   DWORD       m_dwUnset; // Excluded filters
54   DWORD       m_dwSet;   // Implied filters
55   void        (*m_pfnCreateFolders)(int parent_index); // Constructor for special folders
56   BOOL        (*m_pfnQuery)(int nDriver);              // Query function
57   BOOL        m_bExpectedResult;                       // Expected query result
58} FOLDERDATA, *LPFOLDERDATA;
59
60typedef struct
61{
62   DWORD m_dwFilterType;            /* Filter value */
63   DWORD m_dwCtrlID;               /* Control ID that represents it */
64   BOOL (*m_pfnQuery)(int nDriver);   /* Query function */
65   BOOL m_bExpectedResult;            /* Expected query result */
66} FILTER_ITEM, *LPFILTER_ITEM;
67
68/***************************************************************************
69    Functions to build builtin folder lists
70 ***************************************************************************/
71
72void CreateManufacturerFolders(int parent_index);
73void CreateYearFolders(int parent_index);
74void CreateSourceFolders(int parent_index);
75void CreateCPUFolders(int parent_index);
76void CreateSoundFolders(int parent_index);
77void CreateOrientationFolders(int parent_index);
78void CreateDeficiencyFolders(int parent_index);
79void CreateDumpingFolders(int parent_index);
80
81/***************************************************************************/
82
83#define MAX_EXTRA_FOLDERS 256
84#define MAX_EXTRA_SUBFOLDERS 256
85
86/* TreeView structures */
87enum
88{
89   FOLDER_NONE = 0,
90   FOLDER_ALLGAMES,
91   FOLDER_AVAILABLE,
92#ifdef SHOW_UNAVAILABLE_FOLDER
93   FOLDER_UNAVAILABLE,
94#endif
95   FOLDER_MANUFACTURER,
96   FOLDER_YEAR,
97   FOLDER_SOURCE,
98   FOLDER_CPU,
99   FOLDER_SND,
100   FOLDER_DEFICIENCY,
101   FOLDER_WORKING,
102   FOLDER_NONWORKING,
103   FOLDER_ORIGINAL,
104   FOLDER_CLONES,
105   FOLDER_RASTER,
106   FOLDER_VECTOR,
107   FOLDER_TRACKBALL,
108   FOLDER_LIGHTGUN,
109   FOLDER_STEREO,
110   FOLDER_HARDDISK,
111   FOLDER_SAMPLES,
112   FOLDER_DUMPING,
113   FOLDER_SAVESTATE,
114   FOLDER_BIOS,
115   FOLDER_HORIZONTAL,
116   FOLDER_VERTICAL,
117#ifdef MESS
118   FOLDER_CONSOLE,
119   FOLDER_COMPUTER,
120   FOLDER_MODIFIED,
121   FOLDER_MOUSE,
122#endif
123   MAX_FOLDERS,
124};
125
126typedef enum
127{
128   F_CLONES        = 0x00000001,
129   F_NONWORKING    = 0x00000002,
130   F_UNAVAILABLE   = 0x00000004,
131   F_VECTOR        = 0x00000008,
132   F_RASTER        = 0x00000010,
133   F_ORIGINALS     = 0x00000020,
134   F_WORKING       = 0x00000040,
135   F_AVAILABLE     = 0x00000080,
136   F_HORIZONTAL    = 0x00001000,
137   F_VERTICAL      = 0x00002000,
138#ifdef MESS
139   F_COMPUTER      = 0x00000200,
140   F_CONSOLE       = 0x00000400,
141   F_MODIFIED      = 0x00000800,
142#endif
143   F_MASK          = 0x0000FFFF,
144   F_INIEDIT       = 0x00010000, // There is an .ini that can be edited. MSH 20070811
145   F_CUSTOM        = 0x01000000  // for current .ini custom folders
146} FOLDERFLAG;
147
148typedef struct
149{
150    LPSTR m_lpTitle;              // String contains the folder name
151    LPTSTR m_lptTitle;            // String contains the folder name as TCHAR*
152    UINT        m_nFolderId;      // Index / Folder ID number
153    int         m_nParent;        // Parent folder index in treeFolders[]
154    int         m_nIconId;        // negative icon index into the ImageList, or IDI_xxx resource id
155    DWORD       m_dwFlags;        // Misc flags
156    LPBITS      m_lpGameBits;     // Game bits, represent game indices
157} TREEFOLDER, *LPTREEFOLDER;
158
159typedef struct
160{
161    char        m_szTitle[64];  // Folder Title
162    UINT        m_nFolderId;    // ID
163    int         m_nParent;      // Parent Folder index in treeFolders[]
164    DWORD       m_dwFlags;      // Flags - Customizable and Filters
165    int         m_nIconId;      // negative icon index into the ImageList, or IDI_xxx resource id
166    int         m_nSubIconId;   // negative icon index into the ImageList, or IDI_xxx resource id
167} EXFOLDERDATA, *LPEXFOLDERDATA;
168
169void FreeFolders(void);
170void ResetFilters(void);
171void InitTree(LPFOLDERDATA lpFolderData, LPFILTER_ITEM lpFilterList);
172void SetCurrentFolder(LPTREEFOLDER lpFolder);
173UINT GetCurrentFolderID(void);
174
175LPTREEFOLDER GetCurrentFolder(void);
176int GetNumFolders(void);
177LPTREEFOLDER GetFolder(UINT nFolder);
178LPTREEFOLDER GetFolderByID(UINT nID);
179LPTREEFOLDER GetFolderByName(int nParentId, const char *pszFolderName);
180
181void AddGame(LPTREEFOLDER lpFolder, UINT nGame);
182void RemoveGame(LPTREEFOLDER lpFolder, UINT nGame);
183int  FindGame(LPTREEFOLDER lpFolder, int nGame);
184
185void ResetWhichGamesInFolders(void);
186
187LPFOLDERDATA FindFilter(DWORD folderID);
188
189BOOL GameFiltered(int nGame, DWORD dwFlags);
190BOOL GetParentFound(int nGame);
191
192LPFILTER_ITEM GetFilterList(void);
193
194void SetTreeIconSize(HWND hWnd, BOOL bLarge);
195BOOL GetTreeIconSize(void);
196
197void GetFolders(TREEFOLDER ***folders,int *num_folders);
198BOOL TryRenameCustomFolder(LPTREEFOLDER lpFolder,const char *new_name);
199void AddToCustomFolder(LPTREEFOLDER lpFolder,int driver_index);
200void RemoveFromCustomFolder(LPTREEFOLDER lpFolder,int driver_index);
201
202HIMAGELIST GetTreeViewIconList(void);
203int GetTreeViewIconIndex(int icon_id);
204
205void ResetTreeViewFolders(void);
206void SelectTreeViewFolder(int folder_id);
207
208#endif /* TREEVIEW_H */
src/osd/winui/win32ui.c
r0r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11 ***************************************************************************/
12
13 /***************************************************************************
14
15  win32ui.c
16
17  Win32 GUI code.
18
19  Created 8/12/97 by Christopher Kirmse (ckirmse@ricochet.net)
20  Additional code November 1997 by Jeff Miller (miller@aa.net)
21  More July 1998 by Mike Haaland (mhaaland@hypertech.com)
22  Added Spitters/Property Sheets/Removed Tabs/Added Tree Control in
23  Nov/Dec 1998 - Mike Haaland
24
25***************************************************************************/
26
27#define WIN32_LEAN_AND_MEAN
28#define _WIN32_IE 0x0500
29#include <windows.h>
30#include <windowsx.h>
31#include <shellapi.h>
32#include <stdio.h>
33#include <ctype.h>
34#include <io.h>
35#include <fcntl.h>
36#include <commctrl.h>
37#include <dlgs.h>
38#include <string.h>
39#include <sys/stat.h>
40#include <wingdi.h>
41#include <time.h>
42#include <tchar.h>
43
44#include <driver.h>
45#include <osdepend.h>
46#include <unzip.h>
47
48#include "resource.h"
49#include "resource.hm"
50
51#include "screenshot.h"
52#include "mame32.h"
53#include "m32util.h"
54#include "file.h"
55#include "audit32.h"
56#include "directories.h"
57#include "m32opts.h"
58#include "properties.h"
59#include "columnedit.h"
60#include "picker.h"
61#include "tabview.h"
62#include "bitmask.h"
63#include "treeview.h"
64#include "splitters.h"
65#include "dirwatch.h"
66#include "help.h"
67#include "history.h"
68#include "dialogs.h"
69#include "state.h"
70#include "winmain.h"
71#include "winutf8.h"
72#include "strconv.h"
73#include "input.h"
74#include "windows/window.h"
75
76#include "directdraw.h"
77#include "directinput.h"
78#include "dijoystick.h"     /* For DIJoystick avalibility. */
79
80#ifdef MESS
81#include "mess32ui.h"
82#include "messopts.h"
83#endif // MESS
84
85#ifdef _MSC_VER
86#define snprintf _snprintf
87#endif
88
89#ifndef LVS_EX_LABELTIP
90#define LVS_EX_LABELTIP         0x00004000 // listview unfolds partly hidden labels if it does not have infotip text
91#endif // LVS_EX_LABELTIP
92
93// fix warning: cast does not match function type
94#if defined(__GNUC__) && defined(ListView_CreateDragImage)
95#undef ListView_CreateDragImage
96#endif
97
98#ifndef ListView_CreateDragImage
99#define ListView_CreateDragImage(hwnd, i, lpptUpLeft) \
100    (HIMAGELIST)(LRESULT)(int)SendMessage((hwnd), LVM_CREATEDRAGIMAGE, (WPARAM)(int)(i), (LPARAM)(LPPOINT)(lpptUpLeft))
101#endif // ListView_CreateDragImage
102
103#ifndef TreeView_EditLabel
104#define TreeView_EditLabel(w, i) \
105    SNDMSG(w,TVM_EDITLABEL,0,(LPARAM)(i))
106#endif // TreeView_EditLabel
107
108#ifndef HDF_SORTUP
109#define HDF_SORTUP 0x400
110#endif // HDF_SORTUP
111
112#ifndef HDF_SORTDOWN
113#define HDF_SORTDOWN 0x200
114#endif // HDF_SORTDOWN
115
116#ifndef LVM_SETBKIMAGEA
117#define LVM_SETBKIMAGEA         (LVM_FIRST + 68)
118#endif // LVM_SETBKIMAGEA
119
120#ifndef LVM_SETBKIMAGEW
121#define LVM_SETBKIMAGEW         (LVM_FIRST + 138)
122#endif // LVM_SETBKIMAGEW
123
124#ifndef LVM_GETBKIMAGEA
125#define LVM_GETBKIMAGEA         (LVM_FIRST + 69)
126#endif // LVM_GETBKIMAGEA
127
128#ifndef LVM_GETBKIMAGEW
129#define LVM_GETBKIMAGEW         (LVM_FIRST + 139)
130#endif // LVM_GETBKIMAGEW
131
132#ifndef LVBKIMAGE
133
134typedef struct tagLVBKIMAGEA
135{
136   ULONG ulFlags;
137   HBITMAP hbm;
138   LPSTR pszImage;
139   UINT cchImageMax;
140   int xOffsetPercent;
141   int yOffsetPercent;
142} LVBKIMAGEA, *LPLVBKIMAGEA;
143
144typedef struct tagLVBKIMAGEW
145{
146   ULONG ulFlags;
147   HBITMAP hbm;
148   LPWSTR pszImage;
149   UINT cchImageMax;
150   int xOffsetPercent;
151   int yOffsetPercent;
152} LVBKIMAGEW, *LPLVBKIMAGEW;
153
154#ifdef UNICODE
155#define LVBKIMAGE               LVBKIMAGEW
156#define LPLVBKIMAGE             LPLVBKIMAGEW
157#define LVM_SETBKIMAGE          LVM_SETBKIMAGEW
158#define LVM_GETBKIMAGE          LVM_GETBKIMAGEW
159#else
160#define LVBKIMAGE               LVBKIMAGEA
161#define LPLVBKIMAGE             LPLVBKIMAGEA
162#define LVM_SETBKIMAGE          LVM_SETBKIMAGEA
163#define LVM_GETBKIMAGE          LVM_GETBKIMAGEA
164#endif
165#endif
166
167#ifndef LVBKIF_SOURCE_NONE
168#define LVBKIF_SOURCE_NONE      0x00000000
169#endif // LVBKIF_SOURCE_NONE
170
171#ifndef LVBKIF_SOURCE_HBITMAP
172#define LVBKIF_SOURCE_HBITMAP   0x00000001
173#endif
174
175#ifndef LVBKIF_SOURCE_URL
176#define LVBKIF_SOURCE_URL       0x00000002
177#endif // LVBKIF_SOURCE_URL
178
179#ifndef LVBKIF_SOURCE_MASK
180#define LVBKIF_SOURCE_MASK      0x00000003
181#endif // LVBKIF_SOURCE_MASK
182
183#ifndef LVBKIF_STYLE_NORMAL
184#define LVBKIF_STYLE_NORMAL     0x00000000
185#endif // LVBKIF_STYLE_NORMAL
186
187#ifndef LVBKIF_STYLE_TILE
188#define LVBKIF_STYLE_TILE       0x00000010
189#endif // LVBKIF_STYLE_TILE
190
191#ifndef LVBKIF_STYLE_MASK
192#define LVBKIF_STYLE_MASK       0x00000010
193#endif // LVBKIF_STYLE_MASK
194
195#ifndef ListView_SetBkImage
196#define ListView_SetBkImage(hwnd, plvbki) \
197    (BOOL)SNDMSG((hwnd), LVM_SETBKIMAGE, 0, (LPARAM)(plvbki))
198#endif // ListView_SetBkImage
199
200#ifndef ListView_GetBkImage
201#define ListView_GetBkImage(hwnd, plvbki) \
202    (BOOL)SNDMSG((hwnd), LVM_GETBKIMAGE, 0, (LPARAM)(plvbki))
203#endif // ListView_GetBkImage
204
205#define MM_PLAY_GAME (WM_APP + 15000)
206
207#define JOYGUI_MS 100
208
209#define JOYGUI_TIMER 1
210#define SCREENSHOT_TIMER 2
211#define GAMEWND_TIMER 3
212
213/* Max size of a sub-menu */
214#define DBU_MIN_WIDTH  292
215#define DBU_MIN_HEIGHT 190
216
217int MIN_WIDTH  = DBU_MIN_WIDTH;
218int MIN_HEIGHT = DBU_MIN_HEIGHT;
219
220/* Max number of bkground picture files */
221#define MAX_BGFILES 100
222
223#ifndef LVS_EX_LABELTIP
224#define LVS_EX_LABELTIP         0x00004000 // listview unfolds partly hidden labels if it does not have infotip text
225#endif
226
227#define NO_FOLDER -1
228#define STATESAVE_VERSION 1
229
230/***************************************************************************
231 externally defined global variables
232 ***************************************************************************/
233extern const ICONDATA g_iconData[];
234extern const TCHAR g_szPlayGameString[];
235extern const char g_szGameCountString[];
236
237typedef struct _play_options play_options;
238struct _play_options
239{
240   const char *record;         // OPTION_RECORD
241   const char *playback;      // OPTION_PLAYBACK
242   const char *state;         // OPTION_STATE
243   const char *wavwrite;      // OPTION_WAVWRITE
244   const char *mngwrite;      // OPTION_MNGWRITE
245};
246
247/***************************************************************************
248    function prototypes
249 ***************************************************************************/
250
251static BOOL             Win32UI_init(HINSTANCE hInstance, LPSTR lpCmdLine, int nCmdShow);
252static void             Win32UI_exit(void);
253
254static BOOL             PumpMessage(void);
255static BOOL             OnIdle(HWND hWnd);
256static void             OnSize(HWND hwnd, UINT state, int width, int height);
257static long WINAPI      MameWindowProc(HWND hwnd,UINT message,UINT wParam,LONG lParam);
258
259static void             SetView(int menu_id);
260static void             ResetListView(void);
261static void             UpdateGameList(BOOL bUpdateRomAudit, BOOL bUpdateSampleAudit);
262static void             DestroyIcons(void);
263static void             ReloadIcons(void);
264static void             PollGUIJoystick(void);
265static void             PressKey(HWND hwnd,UINT vk);
266static BOOL             MameCommand(HWND hwnd,int id, HWND hwndCtl, UINT codeNotify);
267static void             KeyboardKeyDown(int syskey, int vk_code, int special);
268static void             KeyboardKeyUp(int syskey, int vk_code, int special);
269static void             KeyboardStateClear(void);
270
271static void             UpdateStatusBar(void);
272static BOOL             PickerHitTest(HWND hWnd);
273static BOOL             TreeViewNotify(NMHDR *nm);
274
275static void             ResetBackground(char *szFile);
276static void            RandomSelectBackground(void);
277static void             LoadBackgroundBitmap(void);
278static void             PaintBackgroundImage(HWND hWnd, HRGN hRgn, int x, int y);
279
280static int CLIB_DECL    DriverDataCompareFunc(const void *arg1,const void *arg2);
281static int              GamePicker_Compare(HWND hwndPicker, int index1, int index2, int sort_subitem);
282
283static void             DisableSelection(void);
284static void             EnableSelection(int nGame);
285
286static HICON         GetSelectedPickItemIcon(void);
287static void             SetRandomPickItem(void);
288static void            PickColor(COLORREF *cDefault);
289
290static LPTREEFOLDER     GetSelectedFolder(void);
291static HICON         GetSelectedFolderIcon(void);
292
293static LRESULT CALLBACK HistoryWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
294static LRESULT CALLBACK PictureFrameWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
295static LRESULT CALLBACK PictureWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
296static INT_PTR CALLBACK LanguageDialogProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam);
297
298static BOOL             SelectLanguageFile(HWND hWnd, TCHAR* filename);
299static void             MamePlayRecordGame(void);
300static void             MamePlayBackGame(void);
301static void             MamePlayRecordWave(void);
302static void             MamePlayRecordMNG(void);
303static void            MameLoadState(void);
304static void             MamePlayGameWithOptions(int nGame, const play_options *playopts);
305static BOOL             GameCheck(void);
306static BOOL             FolderCheck(void);
307
308static void             ToggleScreenShot(void);
309static void             AdjustMetrics(void);
310static void             EnablePlayOptions(int nIndex, core_options *o);
311
312/* Icon routines */
313static DWORD            GetShellLargeIconSize(void);
314static DWORD            GetShellSmallIconSize(void);
315static void             CreateIcons(void);
316static int              GetIconForDriver(int nItem);
317static void             AddDriverIcon(int nItem,int default_icon_index);
318
319// Context Menu handlers
320static void             UpdateMenu(HMENU hMenu);
321static void             InitTreeContextMenu(HMENU hTreeMenu);
322static void             InitBodyContextMenu(HMENU hBodyContextMenu);
323static void             ToggleShowFolder(int folder);
324static BOOL             HandleTreeContextMenu( HWND hWnd, WPARAM wParam, LPARAM lParam);
325static BOOL             HandleScreenShotContextMenu( HWND hWnd, WPARAM wParam, LPARAM lParam);
326static void            GamePicker_OnHeaderContextMenu(POINT pt, int nColumn);
327static void            GamePicker_OnBodyContextMenu(POINT pt);
328
329static void             InitListView(void);
330/* Re/initialize the ListView header columns */
331static void             ResetColumnDisplay(BOOL first_time);
332
333static void             CopyToolTipText (LPTOOLTIPTEXT lpttt);
334
335static void             ProgressBarShow(void);
336static void             ProgressBarHide(void);
337static void             ResizeProgressBar(void);
338static void             ProgressBarStep(void);
339static void             ProgressBarStepParam(int iGameIndex, int nGameCount);
340
341static HWND             InitProgressBar(HWND hParent);
342static HWND             InitToolbar(HWND hParent);
343static HWND             InitStatusBar(HWND hParent);
344
345static LRESULT          Statusbar_MenuSelect (HWND hwnd, WPARAM wParam, LPARAM lParam);
346
347static void             UpdateHistory(void);
348
349
350void RemoveCurrentGameCustomFolder(void);
351void RemoveGameCustomFolder(int driver_index);
352
353void BeginListViewDrag(NM_LISTVIEW *pnmv);
354void MouseMoveListViewDrag(POINTS pt);
355void ButtonUpListViewDrag(POINTS p);
356
357void CalculateBestScreenShotRect(HWND hWnd, RECT *pRect, BOOL restrict_height);
358
359BOOL MouseHasBeenMoved(void);
360void SwitchFullScreenMode(void);
361
362/***************************************************************************
363    External variables
364 ***************************************************************************/
365
366/***************************************************************************
367    Internal structures
368 ***************************************************************************/
369
370/*
371 * These next two structs represent how the icon information
372 * is stored in an ICO file.
373 */
374typedef struct
375{
376   BYTE    bWidth;               /* Width of the image */
377   BYTE    bHeight;              /* Height of the image (times 2) */
378   BYTE    bColorCount;          /* Number of colors in image (0 if >=8bpp) */
379   BYTE    bReserved;            /* Reserved */
380   WORD    wPlanes;              /* Color Planes */
381   WORD    wBitCount;            /* Bits per pixel */
382   DWORD   dwBytesInRes;         /* how many bytes in this resource? */
383   DWORD   dwImageOffset;        /* where in the file is this image */
384} ICONDIRENTRY, *LPICONDIRENTRY;
385
386typedef struct
387{
388   UINT            Width, Height, Colors; /* Width, Height and bpp */
389   LPBYTE          lpBits;                /* ptr to DIB bits */
390   DWORD           dwNumBytes;            /* how many bytes? */
391   LPBITMAPINFO    lpbi;                  /* ptr to header */
392   LPBYTE          lpXOR;                 /* ptr to XOR image bits */
393   LPBYTE          lpAND;                 /* ptr to AND image bits */
394} ICONIMAGE, *LPICONIMAGE;
395
396/* Which edges of a control are anchored to the corresponding side of the parent window */
397#define RA_LEFT     0x01
398#define RA_RIGHT    0x02
399#define RA_TOP      0x04
400#define RA_BOTTOM   0x08
401#define RA_ALL      0x0F
402
403#define RA_END  0
404#define RA_ID   1
405#define RA_HWND 2
406
407typedef struct
408{
409   int         type;       /* Either RA_ID or RA_HWND, to indicate which member of u is used; or RA_END
410                        to signify last entry */
411   union                   /* Can identify a child window by control id or by handle */
412   {
413      int     id;         /* Window control id */
414      HWND    hwnd;       /* Window handle */
415   } u;
416   BOOL      setfont;   /* Do we set this item's font? */
417   int         action;     /* What to do when control is resized */
418   void        *subwindow; /* Points to a Resize structure for this subwindow; NULL if none */
419} ResizeItem;
420
421typedef struct
422{
423   RECT        rect;       /* Client rect of window; must be initialized before first resize */
424   ResizeItem* items;      /* Array of subitems to be resized */
425} Resize;
426
427static void ResizeWindow(HWND hParent, Resize *r);
428static void SetAllWindowsFont(HWND hParent, const Resize *r, HFONT hFont, BOOL bRedraw);
429
430/* List view Icon defines */
431#define LG_ICONMAP_WIDTH    GetSystemMetrics(SM_CXICON)
432#define LG_ICONMAP_HEIGHT   GetSystemMetrics(SM_CYICON)
433#define ICONMAP_WIDTH       GetSystemMetrics(SM_CXSMICON)
434#define ICONMAP_HEIGHT      GetSystemMetrics(SM_CYSMICON)
435
436typedef struct tagPOPUPSTRING
437{
438   HMENU hMenu;
439   UINT uiString;
440} POPUPSTRING;
441
442#define MAX_MENUS 3
443
444#define SPLITTER_WIDTH   4
445#define MIN_VIEW_WIDTH   10
446
447// Struct needed for Game Window Communication
448
449typedef struct
450{
451   LPPROCESS_INFORMATION ProcessInfo;
452   HWND hwndFound;
453} FINDWINDOWHANDLE;
454
455/***************************************************************************
456    Internal variables
457 ***************************************************************************/
458
459static HWND   hMain  = NULL;
460static HACCEL hAccel = NULL;
461
462static HWND hwndList  = NULL;
463static HWND hTreeView = NULL;
464static HWND hProgWnd  = NULL;
465static HWND hTabCtrl  = NULL;
466
467static HINSTANCE hInst = NULL;
468
469static HFONT hFont = NULL;     /* Font for list view */
470
471static int optionfolder_count = 0;
472
473/* global data--know where to send messages */
474static BOOL in_emulation;
475
476/* idle work at startup */
477static BOOL idle_work;
478
479/* object pool in use */
480static object_pool *mame32_pool;
481
482static int  game_index;
483static int  progBarStep;
484
485static BOOL bDoGameCheck = FALSE;
486
487/* Tree control variables */
488static BOOL bShowTree      = 1;
489static BOOL bShowToolBar   = 1;
490static BOOL bShowStatusBar = 1;
491static BOOL bShowTabCtrl   = 1;
492static BOOL bProgressShown = FALSE;
493static BOOL bListReady     = FALSE;
494
495#define   WM_MAME32_FILECHANGED   (WM_USER + 0)
496#define   WM_MAME32_AUDITGAME      (WM_USER + 1)
497
498static PDIRWATCHER s_pWatcher;
499
500/* use a joystick subsystem in the gui? */
501static struct OSDJoystick* g_pJoyGUI = NULL;
502
503/* store current keyboard state (in internal codes) here */
504static input_code keyboard_state[ 2048 ]; /* __code_max #defines the number of internal key_codes */
505
506/* search */
507static char g_SearchText[256];
508/* table copied from windows/inputs.c */
509// table entry indices
510#define MAME_KEY      0
511#define DI_KEY         1
512#define VIRTUAL_KEY      2
513#define ASCII_KEY      3
514
515// master keyboard translation table
516static const int win_key_trans_table[][4] =
517{
518   // MAME key             dinput key          virtual key     ascii
519   { ITEM_ID_ESC,          DIK_ESCAPE,         VK_ESCAPE,       27 },
520   { ITEM_ID_1,          DIK_1,            '1',         '1' },
521   { ITEM_ID_2,          DIK_2,            '2',         '2' },
522   { ITEM_ID_3,          DIK_3,            '3',         '3' },
523   { ITEM_ID_4,          DIK_4,            '4',         '4' },
524   { ITEM_ID_5,          DIK_5,            '5',         '5' },
525   { ITEM_ID_6,          DIK_6,            '6',         '6' },
526   { ITEM_ID_7,          DIK_7,            '7',         '7' },
527   { ITEM_ID_8,          DIK_8,            '8',         '8' },
528   { ITEM_ID_9,          DIK_9,            '9',         '9' },
529   { ITEM_ID_0,          DIK_0,            '0',         '0' },
530   { ITEM_ID_BACKSPACE,   DIK_BACK,          VK_BACK,       8 },
531   { ITEM_ID_TAB,          DIK_TAB,          VK_TAB,       9 },
532   { ITEM_ID_Q,          DIK_Q,            'Q',         'Q' },
533   { ITEM_ID_W,          DIK_W,            'W',         'W' },
534   { ITEM_ID_E,          DIK_E,            'E',         'E' },
535   { ITEM_ID_R,          DIK_R,            'R',         'R' },
536   { ITEM_ID_T,          DIK_T,            'T',         'T' },
537   { ITEM_ID_Y,          DIK_Y,            'Y',         'Y' },
538   { ITEM_ID_U,          DIK_U,            'U',         'U' },
539   { ITEM_ID_I,          DIK_I,            'I',         'I' },
540   { ITEM_ID_O,          DIK_O,            'O',         'O' },
541   { ITEM_ID_P,          DIK_P,            'P',         'P' },
542   { ITEM_ID_OPENBRACE,   DIK_LBRACKET,       VK_OEM_4,      '[' },
543   { ITEM_ID_CLOSEBRACE,   DIK_RBRACKET,       VK_OEM_6,      ']' },
544   { ITEM_ID_ENTER,       DIK_RETURN,       VK_RETURN,       13 },
545   { ITEM_ID_LCONTROL,    DIK_LCONTROL,       VK_LCONTROL,    0 },
546   { ITEM_ID_A,          DIK_A,            'A',         'A' },
547   { ITEM_ID_S,          DIK_S,            'S',         'S' },
548   { ITEM_ID_D,          DIK_D,            'D',         'D' },
549   { ITEM_ID_F,          DIK_F,            'F',         'F' },
550   { ITEM_ID_G,          DIK_G,            'G',         'G' },
551   { ITEM_ID_H,          DIK_H,            'H',         'H' },
552   { ITEM_ID_J,          DIK_J,            'J',         'J' },
553   { ITEM_ID_K,          DIK_K,            'K',         'K' },
554   { ITEM_ID_L,          DIK_L,            'L',         'L' },
555   { ITEM_ID_COLON,       DIK_SEMICOLON,      VK_OEM_1,      ';' },
556   { ITEM_ID_QUOTE,       DIK_APOSTROPHE,      VK_OEM_7,      '\'' },
557   { ITEM_ID_TILDE,       DIK_GRAVE,          VK_OEM_3,      '`' },
558   { ITEM_ID_LSHIFT,       DIK_LSHIFT,       VK_LSHIFT,       0 },
559   { ITEM_ID_BACKSLASH,   DIK_BACKSLASH,       VK_OEM_5,      '\\' },
560   { ITEM_ID_Z,          DIK_Z,            'Z',         'Z' },
561   { ITEM_ID_X,          DIK_X,            'X',         'X' },
562   { ITEM_ID_C,          DIK_C,            'C',         'C' },
563   { ITEM_ID_V,          DIK_V,            'V',         'V' },
564   { ITEM_ID_B,          DIK_B,            'B',         'B' },
565   { ITEM_ID_N,          DIK_N,            'N',         'N' },
566   { ITEM_ID_M,          DIK_M,            'M',         'M' },
567   { ITEM_ID_SLASH,       DIK_SLASH,          VK_OEM_2,      '/' },
568   { ITEM_ID_RSHIFT,       DIK_RSHIFT,       VK_RSHIFT,       0 },
569   { ITEM_ID_ASTERISK,    DIK_MULTIPLY,       VK_MULTIPLY,   '*' },
570   { ITEM_ID_LALT,       DIK_LMENU,          VK_LMENU,       0 },
571   { ITEM_ID_SPACE,       DIK_SPACE,          VK_SPACE,      ' ' },
572   { ITEM_ID_CAPSLOCK,    DIK_CAPITAL,       VK_CAPITAL,    0 },
573   { ITEM_ID_F1,          DIK_F1,            VK_F1,          0 },
574   { ITEM_ID_F2,          DIK_F2,            VK_F2,          0 },
575   { ITEM_ID_F3,          DIK_F3,            VK_F3,          0 },
576   { ITEM_ID_F4,          DIK_F4,            VK_F4,          0 },
577   { ITEM_ID_F5,          DIK_F5,            VK_F5,          0 },
578   { ITEM_ID_F6,          DIK_F6,            VK_F6,          0 },
579   { ITEM_ID_F7,          DIK_F7,            VK_F7,          0 },
580   { ITEM_ID_F8,          DIK_F8,            VK_F8,          0 },
581   { ITEM_ID_F9,          DIK_F9,            VK_F9,          0 },
582   { ITEM_ID_F10,          DIK_F10,         VK_F10,       0 },
583   { ITEM_ID_NUMLOCK,       DIK_NUMLOCK,      VK_NUMLOCK,    0 },
584   { ITEM_ID_SCRLOCK,       DIK_SCROLL,         VK_SCROLL,       0 },
585   { ITEM_ID_7_PAD,       DIK_NUMPAD7,      VK_NUMPAD7,    0 },
586   { ITEM_ID_8_PAD,       DIK_NUMPAD8,      VK_NUMPAD8,    0 },
587   { ITEM_ID_9_PAD,       DIK_NUMPAD9,      VK_NUMPAD9,    0 },
588   { ITEM_ID_MINUS_PAD,   DIK_SUBTRACT,      VK_SUBTRACT,    0 },
589   { ITEM_ID_4_PAD,       DIK_NUMPAD4,      VK_NUMPAD4,    0 },
590   { ITEM_ID_5_PAD,       DIK_NUMPAD5,      VK_NUMPAD5,    0 },
591   { ITEM_ID_6_PAD,       DIK_NUMPAD6,      VK_NUMPAD6,    0 },
592   { ITEM_ID_PLUS_PAD,    DIK_ADD,         VK_ADD,       0 },
593   { ITEM_ID_1_PAD,       DIK_NUMPAD1,      VK_NUMPAD1,    0 },
594   { ITEM_ID_2_PAD,       DIK_NUMPAD2,      VK_NUMPAD2,    0 },
595   { ITEM_ID_3_PAD,       DIK_NUMPAD3,      VK_NUMPAD3,    0 },
596   { ITEM_ID_0_PAD,       DIK_NUMPAD0,      VK_NUMPAD0,    0 },
597   { ITEM_ID_DEL_PAD,       DIK_DECIMAL,      VK_DECIMAL,    0 },
598   { ITEM_ID_F11,          DIK_F11,         VK_F11,       0 },
599   { ITEM_ID_F12,          DIK_F12,         VK_F12,       0 },
600   { ITEM_ID_F13,          DIK_F13,         VK_F13,       0 },
601   { ITEM_ID_F14,          DIK_F14,         VK_F14,       0 },
602   { ITEM_ID_F15,          DIK_F15,         VK_F15,       0 },
603   { ITEM_ID_ENTER_PAD,   DIK_NUMPADENTER,   VK_RETURN,       0 },
604   { ITEM_ID_RCONTROL,    DIK_RCONTROL,      VK_RCONTROL,    0 },
605   { ITEM_ID_SLASH_PAD,   DIK_DIVIDE,         VK_DIVIDE,       0 },
606   { ITEM_ID_PRTSCR,       DIK_SYSRQ,          0,             0 },
607   { ITEM_ID_RALT,       DIK_RMENU,         VK_RMENU,       0 },
608   { ITEM_ID_HOME,       DIK_HOME,         VK_HOME,       0 },
609   { ITEM_ID_UP,          DIK_UP,            VK_UP,          0 },
610   { ITEM_ID_PGUP,       DIK_PRIOR,         VK_PRIOR,       0 },
611   { ITEM_ID_LEFT,       DIK_LEFT,         VK_LEFT,       0 },
612   { ITEM_ID_RIGHT,       DIK_RIGHT,         VK_RIGHT,       0 },
613   { ITEM_ID_END,          DIK_END,         VK_END,       0 },
614   { ITEM_ID_DOWN,       DIK_DOWN,         VK_DOWN,       0 },
615   { ITEM_ID_PGDN,       DIK_NEXT,         VK_NEXT,       0 },
616   { ITEM_ID_INSERT,       DIK_INSERT,         VK_INSERT,       0 },
617   { ITEM_ID_DEL,          DIK_DELETE,         VK_DELETE,       0 },
618   { ITEM_ID_LWIN,       DIK_LWIN,         VK_LWIN,       0 },
619   { ITEM_ID_RWIN,       DIK_RWIN,         VK_RWIN,       0 },
620   { ITEM_ID_MENU,       DIK_APPS,         VK_APPS,       0 },
621   { ITEM_ID_PAUSE,       DIK_PAUSE,         VK_PAUSE,      0 },
622   { ITEM_ID_CANCEL,      0,               VK_CANCEL,      0 },
623};
624
625
626
627typedef struct
628{
629   char      name[40];       // functionality name (optional)
630   input_seq   is;            // the input sequence (the keys pressed)
631   UINT      func_id;        // the identifier
632   input_seq* (*getiniptr)(void);// pointer to function to get the value from .ini file
633} GUISequence;
634
635static GUISequence GUISequenceControl[]=
636{
637   {"gui_key_up",                SEQ_DEF_0,    ID_UI_UP,           Get_ui_key_up },
638   {"gui_key_down",              SEQ_DEF_0,    ID_UI_DOWN,         Get_ui_key_down },
639   {"gui_key_left",              SEQ_DEF_0,    ID_UI_LEFT,         Get_ui_key_left },
640   {"gui_key_right",             SEQ_DEF_0,    ID_UI_RIGHT,        Get_ui_key_right },
641   {"gui_key_start",             SEQ_DEF_0,    ID_UI_START,        Get_ui_key_start },
642   {"gui_key_pgup",              SEQ_DEF_0,    ID_UI_PGUP,         Get_ui_key_pgup },
643   {"gui_key_pgdwn",             SEQ_DEF_0,    ID_UI_PGDOWN,       Get_ui_key_pgdwn },
644   {"gui_key_home",              SEQ_DEF_0,    ID_UI_HOME,         Get_ui_key_home },
645   {"gui_key_end",               SEQ_DEF_0,    ID_UI_END,          Get_ui_key_end },
646   {"gui_key_ss_change",         SEQ_DEF_0,    IDC_SSFRAME,        Get_ui_key_ss_change },
647   {"gui_key_history_up",        SEQ_DEF_0,    ID_UI_HISTORY_UP,   Get_ui_key_history_up },
648   {"gui_key_history_down",      SEQ_DEF_0,    ID_UI_HISTORY_DOWN, Get_ui_key_history_down },
649   
650   {"gui_key_context_filters",    SEQ_DEF_0,    ID_CONTEXT_FILTERS,       Get_ui_key_context_filters },
651   {"gui_key_select_random",      SEQ_DEF_0,    ID_CONTEXT_SELECT_RANDOM, Get_ui_key_select_random },
652   {"gui_key_game_audit",         SEQ_DEF_0,    ID_GAME_AUDIT,            Get_ui_key_game_audit },
653   {"gui_key_game_properties",    SEQ_DEF_0,    ID_GAME_PROPERTIES,       Get_ui_key_game_properties },
654   {"gui_key_help_contents",      SEQ_DEF_0,    ID_HELP_CONTENTS,         Get_ui_key_help_contents },
655   {"gui_key_update_gamelist",    SEQ_DEF_0,    ID_UPDATE_GAMELIST,       Get_ui_key_update_gamelist },
656   {"gui_key_view_folders",       SEQ_DEF_0,    ID_VIEW_FOLDERS,          Get_ui_key_view_folders },
657   {"gui_key_view_fullscreen",    SEQ_DEF_0,    ID_VIEW_FULLSCREEN,       Get_ui_key_view_fullscreen },
658   {"gui_key_view_pagetab",       SEQ_DEF_0,    ID_VIEW_PAGETAB,          Get_ui_key_view_pagetab },
659   {"gui_key_view_picture_area",  SEQ_DEF_0,    ID_VIEW_PICTURE_AREA,     Get_ui_key_view_picture_area },
660   {"gui_key_view_status",        SEQ_DEF_0,    ID_VIEW_STATUS,           Get_ui_key_view_status },
661   {"gui_key_view_toolbars",      SEQ_DEF_0,    ID_VIEW_TOOLBARS,         Get_ui_key_view_toolbars },
662
663   {"gui_key_view_tab_cabinet",     SEQ_DEF_0,  ID_VIEW_TAB_CABINET,       Get_ui_key_view_tab_cabinet },
664   {"gui_key_view_tab_cpanel",      SEQ_DEF_0,  ID_VIEW_TAB_CONTROL_PANEL, Get_ui_key_view_tab_cpanel },
665   {"gui_key_view_tab_flyer",       SEQ_DEF_0,  ID_VIEW_TAB_FLYER,         Get_ui_key_view_tab_flyer },
666   {"gui_key_view_tab_history",     SEQ_DEF_0,  ID_VIEW_TAB_HISTORY,       Get_ui_key_view_tab_history },
667   {"gui_key_view_tab_marquee",     SEQ_DEF_0,  ID_VIEW_TAB_MARQUEE,       Get_ui_key_view_tab_marquee },
668   {"gui_key_view_tab_screenshot",  SEQ_DEF_0,  ID_VIEW_TAB_SCREENSHOT,    Get_ui_key_view_tab_screenshot },
669   {"gui_key_view_tab_title",       SEQ_DEF_0,  ID_VIEW_TAB_TITLE,         Get_ui_key_view_tab_title },
670   {"gui_key_view_tab_pcb",         SEQ_DEF_0,  ID_VIEW_TAB_PCB,          Get_ui_key_view_tab_pcb },
671   {"gui_key_quit",                 SEQ_DEF_0,  ID_FILE_EXIT,              Get_ui_key_quit },
672};
673
674
675#define NUM_GUI_SEQUENCES (sizeof(GUISequenceControl) / sizeof(GUISequenceControl[0]))
676
677
678static UINT    lastColumnClick   = 0;
679static WNDPROC g_lpHistoryWndProc = NULL;
680static WNDPROC g_lpPictureFrameWndProc = NULL;
681static WNDPROC g_lpPictureWndProc = NULL;
682
683static POPUPSTRING popstr[MAX_MENUS + 1];
684
685/* Tool and Status bar variables */
686static HWND hStatusBar = 0;
687static HWND hToolBar   = 0;
688
689/* Column Order as Displayed */
690static BOOL oldControl = FALSE;
691static BOOL xpControl = FALSE;
692
693/* Used to recalculate the main window layout */
694static int  bottomMargin;
695static int  topMargin;
696static int  have_history = FALSE;
697
698static BOOL have_selection = FALSE;
699
700static HBITMAP hMissing_bitmap;
701
702/* Icon variables */
703static HIMAGELIST   hLarge = NULL;
704static HIMAGELIST   hSmall = NULL;
705static HIMAGELIST   hHeaderImages = NULL;
706static int          *icon_index = NULL; /* for custom per-game icons */
707
708static TBBUTTON tbb[] =
709{
710   {0, ID_VIEW_FOLDERS,    TBSTATE_ENABLED, TBSTYLE_CHECK,      {0, 0}, 0, 0},
711   {1, ID_VIEW_PICTURE_AREA,TBSTATE_ENABLED, TBSTYLE_CHECK,      {0, 0}, 0, 1},
712   {0, 0,                  TBSTATE_ENABLED, TBSTYLE_SEP,        {0, 0}, 0, 0},
713   {2, ID_VIEW_LARGE_ICON, TBSTATE_ENABLED, TBSTYLE_CHECKGROUP, {0, 0}, 0, 2},
714   {3, ID_VIEW_SMALL_ICON, TBSTATE_ENABLED, TBSTYLE_CHECKGROUP, {0, 0}, 0, 3},
715   {4, ID_VIEW_LIST_MENU,  TBSTATE_ENABLED, TBSTYLE_CHECKGROUP, {0, 0}, 0, 4},
716   {5, ID_VIEW_DETAIL,     TBSTATE_ENABLED, TBSTYLE_CHECKGROUP, {0, 0}, 0, 5},
717   {6, ID_VIEW_GROUPED, TBSTATE_ENABLED, TBSTYLE_CHECKGROUP, {0, 0}, 0, 6},
718   {0, 0,                  TBSTATE_ENABLED, TBSTYLE_SEP,        {0, 0}, 0, 0},
719   {7, ID_HELP_ABOUT,      TBSTATE_ENABLED, TBSTYLE_BUTTON,     {0, 0}, 0, 7},
720   {8, ID_HELP_CONTENTS,   TBSTATE_ENABLED, TBSTYLE_BUTTON,     {0, 0}, 0, 8}
721};
722
723#define NUM_TOOLBUTTONS (sizeof(tbb) / sizeof(tbb[0]))
724
725#define NUM_TOOLTIPS 8
726
727static const TCHAR szTbStrings[NUM_TOOLTIPS + 1][30] =
728{
729   TEXT("Toggle Folder List"),
730   TEXT("Toggle Screen Shot"),
731   TEXT("Large Icons"),
732   TEXT("Small Icons"),
733   TEXT("List"),
734   TEXT("Details"),
735   TEXT("Grouped"),
736   TEXT("About"),
737   TEXT("Help")
738};
739
740static const int CommandToString[] =
741{
742   ID_VIEW_FOLDERS,
743   ID_VIEW_PICTURE_AREA,
744   ID_VIEW_LARGE_ICON,
745   ID_VIEW_SMALL_ICON,
746   ID_VIEW_LIST_MENU,
747   ID_VIEW_DETAIL,
748   ID_VIEW_GROUPED,
749   ID_HELP_ABOUT,
750   ID_HELP_CONTENTS,
751   -1
752};
753
754static const int s_nPickers[] =
755{
756   IDC_LIST
757#ifdef MESS
758   ,IDC_SWLIST
759#endif
760};
761
762/* How to resize main window */
763static ResizeItem main_resize_items[] =
764{
765   { RA_HWND, { 0 },            FALSE, RA_LEFT  | RA_RIGHT  | RA_TOP,     NULL },
766   { RA_HWND, { 0 },            FALSE, RA_LEFT  | RA_RIGHT  | RA_BOTTOM,  NULL },
767   { RA_ID,   { IDC_DIVIDER },  FALSE, RA_LEFT  | RA_RIGHT  | RA_TOP,     NULL },
768   { RA_ID,   { IDC_TREE },     TRUE,   RA_LEFT  | RA_BOTTOM | RA_TOP,     NULL },
769   { RA_ID,   { IDC_LIST },     TRUE,   RA_ALL,                            NULL },
770   { RA_ID,   { IDC_SPLITTER }, FALSE,   RA_LEFT  | RA_BOTTOM | RA_TOP,     NULL },
771   { RA_ID,   { IDC_SPLITTER2 },FALSE,   RA_RIGHT | RA_BOTTOM | RA_TOP,     NULL },
772   { RA_ID,   { IDC_SSFRAME },  FALSE,   RA_RIGHT | RA_BOTTOM | RA_TOP,     NULL },
773   { RA_ID,   { IDC_SSPICTURE },FALSE,   RA_RIGHT | RA_BOTTOM | RA_TOP,     NULL },
774   { RA_ID,   { IDC_HISTORY },  TRUE,   RA_RIGHT | RA_BOTTOM | RA_TOP,     NULL },
775   { RA_ID,   { IDC_SSTAB },    FALSE,   RA_RIGHT | RA_TOP,                 NULL },
776#ifdef MESS
777   { RA_ID,   { IDC_SWLIST },    TRUE,   RA_RIGHT | RA_BOTTOM | RA_TOP,     NULL },
778   { RA_ID,   { IDC_SPLITTER3 },FALSE,   RA_RIGHT | RA_BOTTOM | RA_TOP,     NULL },
779#endif /* MESS */
780   { RA_END,  { 0 },            FALSE, 0,                                 NULL }
781};
782
783static Resize main_resize = { {0, 0, 0, 0}, main_resize_items };
784
785/* last directory for common file dialogs */
786TCHAR last_directory[MAX_PATH];
787
788/* system-wide window message sent out with an ATOM of the current game name
789   each time it changes */
790static UINT g_mame32_message = 0;
791static BOOL g_bDoBroadcast   = FALSE;
792
793static BOOL use_gui_romloading = FALSE;
794
795static BOOL g_listview_dragging = FALSE;
796HIMAGELIST himl_drag;
797int game_dragged; /* which game started the drag */
798HTREEITEM prev_drag_drop_target; /* which tree view item we're currently highlighting */
799
800static BOOL g_in_treeview_edit = FALSE;
801
802typedef struct
803{
804    const char *name;
805    int index;
806} driver_data_type;
807static driver_data_type *sorted_drivers;
808
809/***************************************************************************
810    Global variables
811 ***************************************************************************/
812
813/* Background Image handles also accessed from TreeView.c */
814static HPALETTE         hPALbg   = 0;
815static HBITMAP          hBackground  = 0;
816static MYBITMAPINFO     bmDesc;
817
818/* List view Column text */
819LPCTSTR column_names[COLUMN_MAX] =
820{
821#ifdef MESS
822   TEXT("System"),
823#else
824   TEXT("Game"),
825#endif
826   TEXT("Screen"),
827   //TEXT("ROMs"),
828   TEXT("Samples"),
829   TEXT("Directory"),
830   TEXT("Type"),
831   TEXT("Trackball"),
832   TEXT("Played"),
833   TEXT("Manufacturer"),
834   TEXT("Year"),
835   TEXT("Clone Of"),
836   TEXT("Source"),
837   TEXT("Play Time")
838};
839
840/***************************************************************************
841    Message Macros
842 ***************************************************************************/
843
844#ifndef StatusBar_GetItemRect
845#define StatusBar_GetItemRect(hWnd, iPart, lpRect) \
846    SendMessage(hWnd, SB_GETRECT, (WPARAM) iPart, (LPARAM) (LPRECT) lpRect)
847#endif
848
849#ifndef ToolBar_CheckButton
850#define ToolBar_CheckButton(hWnd, idButton, fCheck) \
851    SendMessage(hWnd, TB_CHECKBUTTON, (WPARAM)idButton, (LPARAM)MAKELONG(fCheck, 0))
852#endif
853
854/***************************************************************************
855    External functions
856 ***************************************************************************/
857
858static void CopyOptions(core_options *pDestOpts, core_options *pSourceOpts)
859{
860   options_enumerator *enumerator;
861   const char *option_name;
862   const char *option_value;
863
864   enumerator = options_enumerator_begin(pSourceOpts);
865   if (enumerator != NULL)
866   {
867      while((option_name = options_enumerator_next(enumerator)) != NULL)
868      {
869         option_value = options_get_string(pSourceOpts, option_name);
870         if (option_value != NULL)
871         {
872            dprintf("CopyOptions(): Copying %s = \"%s\"\n", option_name, option_value);
873            options_set_string(pDestOpts, option_name, option_value, OPTION_PRIORITY_CMDLINE);
874         }
875      }
876      options_enumerator_free(enumerator);
877   }
878}
879
880
881
882static BOOL WaitWithMessageLoop(HANDLE hEvent)
883{
884   DWORD dwRet;
885   MSG   msg;
886
887   while (1)
888   {
889      dwRet = MsgWaitForMultipleObjects(1, &hEvent, FALSE, INFINITE, QS_ALLINPUT);
890
891      if (dwRet == WAIT_OBJECT_0)
892         return TRUE;
893
894      if (dwRet != WAIT_OBJECT_0 + 1)
895         break;
896
897      while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
898      {
899         TranslateMessage(&msg);
900         DispatchMessage(&msg);
901         if (WaitForSingleObject(hEvent, 0) == WAIT_OBJECT_0)
902            return TRUE;
903      }
904   }
905   return FALSE;
906}
907
908static DWORD RunMAME(int nGameIndex, const play_options *playopts)
909{
910   time_t start, end;
911   double elapsedtime;
912   DWORD dwExitCode = 0;
913   int i;
914   core_options *mame_opts;
915
916   // set up MAME options
917   mame_opts = mame_options_init(mame_win_options);
918
919#ifdef MESS
920   // add MESS specific device options
921   mess_add_device_options(mame_opts, drivers[nGameIndex]);
922#endif // MESS
923
924   // set any specified play options
925   if (playopts != NULL)
926   {
927      if (playopts->record != NULL)
928         options_set_string(mame_opts, OPTION_RECORD, playopts->record, OPTION_PRIORITY_CMDLINE);
929      if (playopts->playback != NULL)
930         options_set_string(mame_opts, OPTION_PLAYBACK, playopts->playback, OPTION_PRIORITY_CMDLINE);
931      if (playopts->state != NULL)
932         options_set_string(mame_opts, OPTION_STATE, playopts->state, OPTION_PRIORITY_CMDLINE);
933      if (playopts->wavwrite != NULL)
934         options_set_string(mame_opts, OPTION_WAVWRITE, playopts->wavwrite, OPTION_PRIORITY_CMDLINE);
935      if (playopts->mngwrite != NULL)
936         options_set_string(mame_opts, OPTION_MNGWRITE, playopts->mngwrite, OPTION_PRIORITY_CMDLINE);
937   }
938
939   // Mame will parse all the needed .ini files.
940
941   // prepare MAME32 to run the game
942   ShowWindow(hMain, SW_HIDE);
943
944   for (i = 0; i < ARRAY_LENGTH(s_nPickers); i++)
945      Picker_ClearIdle(GetDlgItem(hMain, s_nPickers[i]));
946
947   // run the emulation
948   options_set_string(mame_opts, OPTION_GAMENAME, drivers[nGameIndex]->name, OPTION_PRIORITY_CMDLINE);
949   // Time the game run.
950   time(&start);
951   mame_execute(mame_opts);
952   // Calc the duration
953   time(&end);
954   elapsedtime = end - start;
955   // Increment our playtime.
956   IncrementPlayTime(nGameIndex, elapsedtime);
957   // the emulation is complete; continue
958   for (i = 0; i < ARRAY_LENGTH(s_nPickers); i++)
959      Picker_ResetIdle(GetDlgItem(hMain, s_nPickers[i]));
960   ShowWindow(hMain, SW_SHOW);
961   SetForegroundWindow(hMain);
962
963   return dwExitCode;
964}
965
966int Mame32Main(HINSTANCE    hInstance,
967                   LPSTR        lpCmdLine,
968                   int          nCmdShow)
969{
970   dprintf("MAME32 starting\n");
971
972   use_gui_romloading = TRUE;
973
974   if (__argc != 1)
975   {
976      /* Rename main because gcc will use it instead of WinMain even with -mwindows */
977      extern int DECL_SPEC mame_main(int, char**);
978      exit(mame_main(__argc, __argv));
979   }
980   if (!Win32UI_init(hInstance, lpCmdLine, nCmdShow))
981      return 1;
982
983   // pump message, but quit on WM_QUIT
984   while(PumpMessage())
985      ;
986
987   Win32UI_exit();
988   return 0;
989}
990
991
992HWND GetMainWindow(void)
993{
994   return hMain;
995}
996
997HWND GetTreeView(void)
998{
999   return hTreeView;
1000}
1001
1002HIMAGELIST GetLargeImageList(void)
1003{
1004   return hLarge;
1005}
1006
1007HIMAGELIST GetSmallImageList(void)
1008{
1009   return hSmall;
1010}
1011
1012object_pool *GetMame32MemoryPool(void)
1013{
1014   return mame32_pool;
1015}
1016
1017void GetRealColumnOrder(int order[])
1018{
1019   int tmpOrder[COLUMN_MAX];
1020   int nColumnMax;
1021   int i;
1022
1023   nColumnMax = Picker_GetNumColumns(hwndList);
1024
1025   /* Get the Column Order and save it */
1026   if (!oldControl)
1027   {
1028      ListView_GetColumnOrderArray(hwndList, nColumnMax, tmpOrder);
1029
1030      for (i = 0; i < nColumnMax; i++)
1031      {
1032         order[i] = Picker_GetRealColumnFromViewColumn(hwndList, tmpOrder[i]);
1033      }
1034   }
1035}
1036
1037/*
1038 * PURPOSE: Format raw data read from an ICO file to an HICON
1039 * PARAMS:  PBYTE ptrBuffer  - Raw data from an ICO file
1040 *          UINT nBufferSize - Size of buffer ptrBuffer
1041 * RETURNS: HICON - handle to the icon, NULL for failure
1042 * History: July '95 - Created
1043 *          March '00- Seriously butchered from MSDN for mine own
1044 *          purposes, sayeth H0ek.
1045 */
1046HICON FormatICOInMemoryToHICON(PBYTE ptrBuffer, UINT nBufferSize)
1047{
1048   ICONIMAGE           IconImage;
1049   LPICONDIRENTRY      lpIDE = NULL;
1050   UINT                nNumImages;
1051   UINT                nBufferIndex = 0;
1052   HICON               hIcon = NULL;
1053
1054   /* Is there a WORD? */
1055   if (nBufferSize < sizeof(WORD))
1056   {
1057      return NULL;
1058   }
1059
1060   /* Was it 'reserved' ?    (ie 0) */
1061   if ((WORD)(ptrBuffer[nBufferIndex]) != 0)
1062   {
1063      return NULL;
1064   }
1065
1066   nBufferIndex += sizeof(WORD);
1067
1068   /* Is there a WORD? */
1069   if (nBufferSize - nBufferIndex < sizeof(WORD))
1070   {
1071      return NULL;
1072   }
1073
1074   /* Was it type 1? */
1075   if ((WORD)(ptrBuffer[nBufferIndex]) != 1)
1076   {
1077      return NULL;
1078   }
1079
1080   nBufferIndex += sizeof(WORD);
1081
1082   /* Is there a WORD? */
1083   if (nBufferSize - nBufferIndex < sizeof(WORD))
1084   {
1085      return NULL;
1086   }
1087
1088   /* Then that's the number of images in the ICO file */
1089   nNumImages = (WORD)(ptrBuffer[nBufferIndex]);
1090
1091   /* Is there at least one icon in the file? */
1092   if ( nNumImages < 1 )
1093   {
1094      return NULL;
1095   }
1096
1097   nBufferIndex += sizeof(WORD);
1098
1099   /* Is there enough space for the icon directory entries? */
1100   if ((nBufferIndex + nNumImages * sizeof(ICONDIRENTRY)) > nBufferSize)
1101   {
1102      return NULL;
1103   }
1104
1105   /* Assign icon directory entries from buffer */
1106   lpIDE = (LPICONDIRENTRY)(&ptrBuffer[nBufferIndex]);
1107   nBufferIndex += nNumImages * sizeof (ICONDIRENTRY);
1108
1109   IconImage.dwNumBytes = lpIDE->dwBytesInRes;
1110
1111   /* Seek to beginning of this image */
1112   if ( lpIDE->dwImageOffset > nBufferSize )
1113   {
1114      return NULL;
1115   }
1116
1117   nBufferIndex = lpIDE->dwImageOffset;
1118
1119   /* Read it in */
1120   if ((nBufferIndex + lpIDE->dwBytesInRes) > nBufferSize)
1121   {
1122      return NULL;
1123   }
1124
1125   IconImage.lpBits = &ptrBuffer[nBufferIndex];
1126   nBufferIndex += lpIDE->dwBytesInRes;
1127#if 0  // Not sure we want odd sized icons.
1128   hIcon = CreateIconFromResourceEx(IconImage.lpBits, IconImage.dwNumBytes, TRUE, 0x00030000,
1129         (*(LPBITMAPINFOHEADER)(IconImage.lpBits)).biWidth, (*(LPBITMAPINFOHEADER)(IconImage.lpBits)).biHeight/2, 0 );
1130#endif
1131   /* It failed, odds are good we're on NT so try the non-Ex way */
1132   if (hIcon == NULL)
1133   {
1134      /* We would break on NT if we try with a 16bpp image */
1135      if (((LPBITMAPINFO)IconImage.lpBits)->bmiHeader.biBitCount != 16)
1136      {
1137         hIcon = CreateIconFromResource(IconImage.lpBits, IconImage.dwNumBytes, TRUE, 0x00030000);
1138      }
1139   }
1140   return hIcon;
1141}
1142
1143HICON LoadIconFromFile(const char *iconname)
1144{
1145   HICON hIcon = 0;
1146   struct stat file_stat;
1147   char tmpStr[MAX_PATH];
1148   char tmpIcoName[MAX_PATH];
1149   const char* sDirName = GetImgDir();
1150   PBYTE bufferPtr;
1151   zip_error ziperr;
1152   zip_file *zip;
1153   const zip_file_header *entry;
1154
1155   sprintf(tmpStr, "%s/%s.ico", GetIconsDir(), iconname);
1156   if (stat(tmpStr, &file_stat) != 0
1157   || (hIcon = win_extract_icon_utf8(hInst, tmpStr, 0)) == 0)
1158   {
1159      sprintf(tmpStr, "%s/%s.ico", sDirName, iconname);
1160      if (stat(tmpStr, &file_stat) != 0
1161      || (hIcon = win_extract_icon_utf8(hInst, tmpStr, 0)) == 0)
1162      {
1163         sprintf(tmpStr, "%s/icons.zip", GetIconsDir());
1164         sprintf(tmpIcoName, "%s.ico", iconname);
1165
1166         ziperr = zip_file_open(tmpStr, &zip);
1167         if (ziperr == ZIPERR_NONE)
1168         {
1169            entry = zip_file_first_file(zip);
1170            while(!hIcon && entry)
1171            {
1172               if (!mame_stricmp(entry->filename, tmpIcoName))
1173               {
1174                  bufferPtr = malloc(entry->uncompressed_length);
1175                  if (bufferPtr)
1176                  {
1177                     ziperr = zip_file_decompress(zip, bufferPtr, entry->uncompressed_length);
1178                     if (ziperr == ZIPERR_NONE)
1179                     {
1180                        hIcon = FormatICOInMemoryToHICON(bufferPtr, entry->uncompressed_length);
1181                     }
1182                     free(bufferPtr);
1183                  }
1184               }
1185               entry = zip_file_next_file(zip);
1186            }
1187            zip_file_close(zip);
1188         }
1189      }
1190   }
1191   return hIcon;
1192}
1193
1194/* Return the number of folders with options */
1195int GetNumOptionFolders()
1196{
1197   return optionfolder_count;
1198}
1199
1200/* Return the number of folders with options */
1201void SetNumOptionFolders(int count)
1202{
1203   optionfolder_count = count;
1204}
1205
1206/* search */
1207const char * GetSearchText(void)
1208{
1209   return g_SearchText;
1210}
1211
1212
1213/* Sets the treeview and listviews sizes in accordance with their visibility and the splitters */
1214static void ResizeTreeAndListViews(BOOL bResizeHidden)
1215{
1216   int i;
1217   int nLastWidth = 0;
1218   int nLastWidth2 = 0;
1219   int nLeftWindowWidth = 0;
1220   RECT rect;
1221   BOOL bVisible;
1222
1223   /* Size the List Control in the Picker */
1224   GetClientRect(hMain, &rect);
1225
1226   if (bShowStatusBar)
1227      rect.bottom -= bottomMargin;
1228   if (bShowToolBar)
1229      rect.top += topMargin;
1230
1231   /* Tree control */
1232   ShowWindow(GetDlgItem(hMain, IDC_TREE), bShowTree ? SW_SHOW : SW_HIDE);
1233
1234   for (i = 0; g_splitterInfo[i].nSplitterWindow; i++)
1235   {
1236      bVisible = GetWindowLong(GetDlgItem(hMain, g_splitterInfo[i].nLeftWindow), GWL_STYLE) & WS_VISIBLE ? TRUE : FALSE;
1237      if (bResizeHidden || bVisible)
1238      {
1239         nLeftWindowWidth = nSplitterOffset[i] - SPLITTER_WIDTH/2 - nLastWidth;
1240
1241         /* special case for the rightmost pane when the screenshot is gone */
1242         if (!GetShowScreenShot() && !g_splitterInfo[i+1].nSplitterWindow)
1243            nLeftWindowWidth = rect.right - nLastWidth;
1244
1245         /* woah?  are we overlapping ourselves? */
1246         if (nLeftWindowWidth < MIN_VIEW_WIDTH)
1247         {
1248            nLastWidth = nLastWidth2;
1249            nLeftWindowWidth = nSplitterOffset[i] - MIN_VIEW_WIDTH - (SPLITTER_WIDTH*3/2) - nLastWidth;
1250            i--;
1251         }
1252
1253         MoveWindow(GetDlgItem(hMain, g_splitterInfo[i].nLeftWindow), nLastWidth, rect.top + 2,
1254            nLeftWindowWidth, (rect.bottom - rect.top) - 4 , TRUE);
1255
1256         MoveWindow(GetDlgItem(hMain, g_splitterInfo[i].nSplitterWindow), nSplitterOffset[i], rect.top + 2,
1257            SPLITTER_WIDTH, (rect.bottom - rect.top) - 4, TRUE);
1258      }
1259
1260      if (bVisible)
1261      {
1262         nLastWidth2 = nLastWidth;
1263         nLastWidth += nLeftWindowWidth + SPLITTER_WIDTH;
1264      }
1265   }
1266}
1267
1268/* Adjust the list view and screenshot button based on GetShowScreenShot() */
1269void UpdateScreenShot(void)
1270{
1271   RECT rect;
1272   int  nWidth;
1273   RECT fRect;
1274   POINT p = {0, 0};
1275
1276   /* first time through can't do this stuff */
1277   if (hwndList == NULL)
1278      return;
1279
1280   /* Size the List Control in the Picker */
1281   GetClientRect(hMain, &rect);
1282
1283   if (bShowStatusBar)
1284      rect.bottom -= bottomMargin;
1285   if (bShowToolBar)
1286      rect.top += topMargin;
1287
1288   if (GetShowScreenShot())
1289   {
1290      nWidth = nSplitterOffset[GetSplitterCount() - 1];
1291      CheckMenuItem(GetMenu(hMain),ID_VIEW_PICTURE_AREA, MF_CHECKED);
1292      ToolBar_CheckButton(hToolBar, ID_VIEW_PICTURE_AREA, MF_CHECKED);
1293   }
1294   else
1295   {
1296      nWidth = rect.right;
1297      CheckMenuItem(GetMenu(hMain),ID_VIEW_PICTURE_AREA, MF_UNCHECKED);
1298      ToolBar_CheckButton(hToolBar, ID_VIEW_PICTURE_AREA, MF_UNCHECKED);
1299   }
1300
1301   ResizeTreeAndListViews(FALSE);
1302
1303   FreeScreenShot();
1304
1305   if (have_selection)
1306   {
1307#ifdef MESS
1308      if (!g_szSelectedItem[0] || !LoadScreenShotEx(Picker_GetSelectedItem(hwndList), g_szSelectedItem,
1309         TabView_GetCurrentTab(hTabCtrl)))
1310#endif
1311      {
1312         // load and set image, or empty it if we don't have one
1313         LoadScreenShot(Picker_GetSelectedItem(hwndList), TabView_GetCurrentTab(hTabCtrl));
1314      }
1315   }
1316
1317   // figure out if we have a history or not, to place our other windows properly
1318   UpdateHistory();
1319
1320   // setup the picture area
1321
1322   if (GetShowScreenShot())
1323   {
1324      DWORD dwStyle;
1325      DWORD dwStyleEx;
1326      BOOL showing_history;
1327
1328      ClientToScreen(hMain, &p);
1329      GetWindowRect(GetDlgItem(hMain, IDC_SSFRAME), &fRect);
1330      OffsetRect(&fRect, -p.x, -p.y);
1331
1332      // show history on this tab IFF
1333      // - we have history for the game
1334      // - we're on the first tab
1335      // - we DON'T have a separate history tab
1336      showing_history = (have_history && (TabView_GetCurrentTab(hTabCtrl) == GetHistoryTab() || GetHistoryTab() == TAB_ALL ) &&
1337                     GetShowTab(TAB_HISTORY) == FALSE);
1338      CalculateBestScreenShotRect(GetDlgItem(hMain, IDC_SSFRAME), &rect,showing_history);
1339         
1340      dwStyle   = GetWindowLong(GetDlgItem(hMain, IDC_SSPICTURE), GWL_STYLE);
1341      dwStyleEx = GetWindowLong(GetDlgItem(hMain, IDC_SSPICTURE), GWL_EXSTYLE);
1342         
1343      AdjustWindowRectEx(&rect, dwStyle, FALSE, dwStyleEx);
1344      MoveWindow(GetDlgItem(hMain, IDC_SSPICTURE),
1345               fRect.left  + rect.left,
1346               fRect.top   + rect.top,
1347               rect.right  - rect.left,
1348               rect.bottom - rect.top,
1349               TRUE);
1350     
1351      ShowWindow(GetDlgItem(hMain,IDC_SSPICTURE),
1352               (TabView_GetCurrentTab(hTabCtrl) != TAB_HISTORY) ? SW_SHOW : SW_HIDE);
1353      ShowWindow(GetDlgItem(hMain,IDC_SSFRAME),SW_SHOW);
1354      ShowWindow(GetDlgItem(hMain,IDC_SSTAB),bShowTabCtrl ? SW_SHOW : SW_HIDE);
1355
1356      InvalidateRect(GetDlgItem(hMain,IDC_SSPICTURE),NULL,FALSE);
1357   }
1358   else
1359   {
1360      ShowWindow(GetDlgItem(hMain,IDC_SSPICTURE),SW_HIDE);
1361      ShowWindow(GetDlgItem(hMain,IDC_SSFRAME),SW_HIDE);
1362      ShowWindow(GetDlgItem(hMain,IDC_SSTAB),SW_HIDE);
1363   }
1364
1365}
1366
1367void ResizePickerControls(HWND hWnd)
1368{
1369   RECT frameRect;
1370   RECT rect, sRect;
1371   int  nListWidth, nScreenShotWidth;
1372   static BOOL firstTime = TRUE;
1373   int  doSSControls = TRUE;
1374   int i, nSplitterCount;
1375
1376   nSplitterCount = GetSplitterCount();
1377
1378   /* Size the List Control in the Picker */
1379   GetClientRect(hWnd, &rect);
1380
1381   /* Calc the display sizes based on g_splitterInfo */
1382   if (firstTime)
1383   {
1384      RECT rWindow;
1385
1386      for (i = 0; i < nSplitterCount; i++)
1387         nSplitterOffset[i] = rect.right * g_splitterInfo[i].dPosition;
1388
1389      GetWindowRect(hStatusBar, &rWindow);
1390      bottomMargin = rWindow.bottom - rWindow.top;
1391      GetWindowRect(hToolBar, &rWindow);
1392      topMargin = rWindow.bottom - rWindow.top;
1393      /*buttonMargin = (sRect.bottom + 4); */
1394
1395      firstTime = FALSE;
1396   }
1397   else
1398   {
1399      doSSControls = GetShowScreenShot();
1400   }
1401
1402   if (bShowStatusBar)
1403      rect.bottom -= bottomMargin;
1404
1405   if (bShowToolBar)
1406      rect.top += topMargin;
1407
1408   MoveWindow(GetDlgItem(hWnd, IDC_DIVIDER), rect.left, rect.top - 4, rect.right, 2, TRUE);
1409
1410   ResizeTreeAndListViews(TRUE);
1411
1412   nListWidth = nSplitterOffset[nSplitterCount-1];
1413   nScreenShotWidth = (rect.right - nListWidth) - 4;
1414
1415   /* Screen shot Page tab control */
1416   if (bShowTabCtrl)
1417   {
1418      MoveWindow(GetDlgItem(hWnd, IDC_SSTAB), nListWidth + 4, rect.top + 2,
1419         nScreenShotWidth - 2, rect.top + 20, doSSControls);
1420      rect.top += 20;
1421   }
1422
1423   /* resize the Screen shot frame */
1424   MoveWindow(GetDlgItem(hWnd, IDC_SSFRAME), nListWidth + 4, rect.top + 2,
1425      nScreenShotWidth - 2, (rect.bottom - rect.top) - 4, doSSControls);
1426
1427   /* The screen shot controls */
1428   GetClientRect(GetDlgItem(hWnd, IDC_SSFRAME), &frameRect);
1429
1430   /* Text control - game history */
1431   sRect.left = nListWidth + 14;
1432   sRect.right = sRect.left + (nScreenShotWidth - 22);
1433
1434   
1435   if (GetShowTab(TAB_HISTORY))
1436   {
1437      // We're using the new mode, with the history filling the entire tab (almost)
1438      sRect.top = rect.top + 14;
1439      sRect.bottom = (rect.bottom - rect.top) - 30;   
1440   }
1441   else
1442   {
1443      // We're using the original mode, with the history beneath the SS picture
1444      sRect.top = rect.top + 264;
1445      sRect.bottom = (rect.bottom - rect.top) - 278;
1446   }
1447
1448   MoveWindow(GetDlgItem(hWnd, IDC_HISTORY),
1449      sRect.left, sRect.top,
1450      sRect.right - sRect.left, sRect.bottom, doSSControls);
1451
1452   /* the other screen shot controls will be properly placed in UpdateScreenshot() */
1453
1454}
1455
1456char *ModifyThe(const char *str)
1457{
1458   static int  bufno = 0;
1459   static char buffer[4][255];
1460
1461   if (strncmp(str, "The ", 4) == 0)
1462   {
1463      char *s, *p;
1464      char temp[255];
1465
1466      strcpy(temp, &str[4]);
1467
1468      bufno = (bufno + 1) % 4;
1469
1470      s = buffer[bufno];
1471
1472      /* Check for version notes in parens */
1473      p = strchr(temp, '(');
1474      if (p)
1475      {
1476         p[-1] = '\0';
1477      }
1478
1479      strcpy(s, temp);
1480      strcat(s, ", The");
1481
1482      if (p)
1483      {
1484         strcat(s, " ");
1485         strcat(s, p);
1486      }
1487
1488      return s;
1489   }
1490   return (char *)str;
1491}
1492
1493HBITMAP GetBackgroundBitmap(void)
1494{
1495   return hBackground;
1496}
1497
1498HPALETTE GetBackgroundPalette(void)
1499{
1500   return hPALbg;
1501}
1502
1503MYBITMAPINFO * GetBackgroundInfo(void)
1504{
1505   return &bmDesc;
1506}
1507
1508BOOL GetUseOldControl(void)
1509{
1510   return oldControl;
1511}
1512
1513BOOL GetUseXPControl(void)
1514{
1515   return xpControl;
1516}
1517
1518int GetMinimumScreenShotWindowWidth(void)
1519{
1520   BITMAP bmp;
1521   GetObject(hMissing_bitmap,sizeof(BITMAP),&bmp);
1522
1523   return bmp.bmWidth + 6; // 6 is for a little breathing room
1524}
1525
1526
1527int GetDriverIndex(const game_driver *driver)
1528{
1529   return GetGameNameIndex(driver->name);
1530}
1531
1532int GetParentIndex(const game_driver *driver)
1533{
1534   return GetGameNameIndex(driver->parent);
1535}
1536
1537int GetParentRomSetIndex(const game_driver *driver)
1538{
1539   int nParentIndex = GetGameNameIndex(driver->parent);
1540
1541   if( nParentIndex >= 0)
1542   {
1543      if ((drivers[nParentIndex]->flags & GAME_IS_BIOS_ROOT) == 0)
1544         return nParentIndex;
1545   }
1546
1547   return -1;
1548}
1549
1550int GetGameNameIndex(const char *name)
1551{
1552   driver_data_type *driver_index_info;
1553   driver_data_type key;
1554   key.name = name;
1555
1556   // uses our sorted array of driver names to get the index in log time
1557   driver_index_info = bsearch(&key,sorted_drivers,driver_list_get_count(drivers),sizeof(driver_data_type),
1558                        DriverDataCompareFunc);
1559
1560   if (driver_index_info == NULL)
1561      return -1;
1562
1563   return driver_index_info->index;
1564
1565}
1566
1567int GetIndexFromSortedIndex(int sorted_index)
1568{
1569   return sorted_drivers[sorted_index].index;
1570}
1571
1572/***************************************************************************
1573    Internal functions
1574 ***************************************************************************/
1575
1576// used for our sorted array of game names
1577int CLIB_DECL DriverDataCompareFunc(const void *arg1,const void *arg2)
1578{
1579    return strcmp( ((driver_data_type *)arg1)->name, ((driver_data_type *)arg2)->name );
1580}
1581
1582static void ResetBackground(char *szFile)
1583{
1584   char szDestFile[MAX_PATH];
1585
1586   /* The MAME core load the .png file first, so we only need replace this file */
1587   sprintf(szDestFile, "%s\\bkground.png", GetBgDir());
1588   win_set_file_attributes_utf8(szDestFile, FILE_ATTRIBUTE_NORMAL);
1589   win_copy_file_utf8(szFile, szDestFile, FALSE);
1590}
1591
1592static void RandomSelectBackground(void)
1593{
1594   struct _finddata_t c_file;
1595   long hFile;
1596   char szFile[MAX_PATH];
1597   int count=0;
1598   const char *szDir=GetBgDir();
1599   char *buf=malloc(_MAX_FNAME * MAX_BGFILES);
1600
1601   if (buf == NULL)
1602      return;
1603
1604   sprintf(szFile, "%s\\*.bmp", szDir);
1605   hFile = _findfirst(szFile, &c_file);
1606   if (hFile != -1L)
1607   {
1608      int Done = 0;
1609      while (!Done && count < MAX_BGFILES)
1610      {
1611         memcpy(buf + count * _MAX_FNAME, c_file.name, _MAX_FNAME);
1612         count++;
1613         Done = _findnext(hFile, &c_file);
1614      }
1615      _findclose(hFile);
1616   }
1617   sprintf(szFile, "%s\\*.png", szDir);
1618   hFile = _findfirst(szFile, &c_file);
1619   if (hFile != -1L)
1620   {
1621      int Done = 0;
1622      while (!Done && count < MAX_BGFILES)
1623      {
1624         memcpy(buf + count * _MAX_FNAME, c_file.name, _MAX_FNAME);
1625         count++;
1626         Done = _findnext(hFile, &c_file);
1627      }
1628      _findclose(hFile);
1629   }
1630
1631   if (count)
1632   {
1633#ifdef rand
1634#undef rand
1635#endif
1636
1637      srand( (unsigned)time( NULL ) );
1638      sprintf(szFile, "%s\\%s", szDir, buf + (rand() % count) * _MAX_FNAME);
1639      ResetBackground(szFile);
1640   }
1641
1642   free(buf);
1643}
1644
1645void SetMainTitle(void)
1646{
1647   char version[50];
1648   char buffer[100];
1649
1650   sscanf(build_version,"%s",version);
1651   snprintf(buffer, ARRAY_LENGTH(buffer), "%s %s", MAME32NAME, version);
1652   win_set_window_text_utf8(hMain,buffer);
1653}
1654
1655static void winui_output_error(void *param, const char *format, va_list argptr)
1656{
1657   char buffer[1024];
1658
1659   // if we are in fullscreen mode, go to windowed mode
1660   if ((video_config.windowed == 0) && (win_window_list != NULL))
1661      winwindow_toggle_full_screen();
1662
1663   vsnprintf(buffer, ARRAY_LENGTH(buffer), format, argptr);
1664   win_message_box_utf8(win_window_list ? win_window_list->hwnd : NULL, buffer, APPNAME, MB_OK);
1665}
1666
1667static void memory_error(const char *message)
1668{
1669   win_message_box_utf8(hMain, message, APPNAME, MB_OK);
1670   exit(-1);
1671}
1672
1673static BOOL Win32UI_init(HINSTANCE hInstance, LPSTR lpCmdLine, int nCmdShow)
1674{
1675   extern int mame_validitychecks(int game);
1676   WNDCLASS   wndclass;
1677   RECT      rect;
1678   int i, nSplitterCount;
1679   extern FOLDERDATA g_folderData[];
1680   extern FILTER_ITEM g_filterList[];
1681   extern const char *history_filename;
1682   extern const char *mameinfo_filename;
1683   LONG common_control_version = GetCommonControlVersion();
1684   int validity_failed = 0;
1685   TCHAR* t_inpdir;
1686
1687   dprintf("about to init options\n");
1688   if (!OptionsInit())
1689      return FALSE;
1690   dprintf("options loaded\n");
1691
1692   srand((unsigned)time(NULL));
1693
1694   // output errors to message boxes
1695   mame_set_output_channel(OUTPUT_CHANNEL_ERROR, winui_output_error, NULL, NULL, NULL);
1696
1697   // create the memory pool
1698   mame32_pool = pool_alloc(memory_error);
1699
1700   // custom per-game icons
1701   icon_index = pool_malloc(mame32_pool, sizeof(int) * driver_list_get_count(drivers));
1702   memset(icon_index, '\0', sizeof(int) * driver_list_get_count(drivers));
1703
1704   // sorted list of drivers by name
1705   sorted_drivers = (driver_data_type *) pool_malloc(mame32_pool, sizeof(driver_data_type) * driver_list_get_count(drivers));
1706   memset(sorted_drivers, '\0', sizeof(driver_data_type) * driver_list_get_count(drivers));
1707   for (i = 0; i < driver_list_get_count(drivers); i++)
1708   {
1709      sorted_drivers[i].name = drivers[i]->name;
1710      sorted_drivers[i].index = i;
1711   }
1712   qsort(sorted_drivers, driver_list_get_count(drivers), sizeof(driver_data_type), DriverDataCompareFunc);
1713
1714   // set up window class
1715   wndclass.style         = CS_HREDRAW | CS_VREDRAW;
1716   wndclass.lpfnWndProc   = MameWindowProc;
1717   wndclass.cbClsExtra    = 0;
1718   wndclass.cbWndExtra    = DLGWINDOWEXTRA;
1719   wndclass.hInstance      = hInstance;
1720   wndclass.hIcon         = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_MAME32_ICON));
1721   wndclass.hCursor      = NULL;
1722   wndclass.hbrBackground = (HBRUSH)(COLOR_3DFACE + 1);
1723   wndclass.lpszMenuName  = MAKEINTRESOURCE(IDR_UI_MENU);
1724   wndclass.lpszClassName = TEXT("MainClass");
1725
1726   RegisterClass(&wndclass);
1727
1728#ifdef MESS
1729   DevView_RegisterClass();
1730#endif //MESS
1731
1732   InitCommonControls();
1733
1734   // Are we using an Old comctl32.dll?
1735   dprintf("common controlversion %i %i",common_control_version >> 16,
1736         common_control_version & 0xffff);
1737         
1738   oldControl = (common_control_version < PACKVERSION(4,71));
1739   xpControl = (common_control_version >= PACKVERSION(6,0));
1740   if (oldControl)
1741   {
1742      char buf[] = MAME32NAME " has detected an old version of comctl32.dll\n\n"
1743                "Game Properties, many configuration options and\n"
1744                "features are not available without an updated DLL\n\n"
1745                "Please install the common control update found at:\n\n"
1746                "http://www.microsoft.com/msdownload/ieplatform/ie/comctrlx86.asp\n\n"
1747                "Would you like to continue without using the new features?\n";
1748
1749      if (IDNO == win_message_box_utf8(0, buf, MAME32NAME " Outdated comctl32.dll Warning", MB_YESNO | MB_ICONWARNING))
1750         return FALSE;
1751    }
1752
1753   g_mame32_message = RegisterWindowMessage(TEXT("MAME32"));
1754   g_bDoBroadcast = GetBroadcast();
1755
1756   HelpInit();
1757   
1758   t_inpdir = tstring_from_utf8(GetInpDir());
1759   if( ! t_inpdir )
1760      return FALSE;
1761
1762   _tcscpy(last_directory,t_inpdir);
1763   free(t_inpdir);
1764   hMain = CreateDialog(hInstance, MAKEINTRESOURCE(IDD_MAIN), 0, NULL);
1765   if (hMain == NULL)
1766   {
1767      dprintf("error creating main dialog, aborting");
1768      return FALSE;
1769   }
1770
1771   s_pWatcher = DirWatcher_Init(hMain, WM_MAME32_FILECHANGED);
1772   if (s_pWatcher)
1773   {
1774      DirWatcher_Watch(s_pWatcher, 0, GetRomDirs(), TRUE);
1775      DirWatcher_Watch(s_pWatcher, 1, GetSampleDirs(), TRUE);
1776   }
1777
1778   SetMainTitle();
1779   hTabCtrl = GetDlgItem(hMain, IDC_SSTAB);
1780   
1781   {
1782      struct TabViewOptions opts;
1783
1784      static struct TabViewCallbacks s_tabviewCallbacks =
1785      {
1786         GetShowTabCtrl,         // pfnGetShowTabCtrl
1787         SetCurrentTab,         // pfnSetCurrentTab
1788         GetCurrentTab,         // pfnGetCurrentTab
1789         SetShowTab,            // pfnSetShowTab
1790         GetShowTab,            // pfnGetShowTab
1791
1792         GetImageTabShortName,   // pfnGetTabShortName
1793         GetImageTabLongName,   // pfnGetTabLongName
1794         UpdateScreenShot      // pfnOnSelectionChanged
1795      };
1796
1797      memset(&opts, 0, sizeof(opts));
1798      opts.pCallbacks = &s_tabviewCallbacks;
1799      opts.nTabCount = MAX_TAB_TYPES;
1800
1801      if (!SetupTabView(hTabCtrl, &opts))
1802         return FALSE;
1803   }
1804
1805   /* subclass history window */
1806   g_lpHistoryWndProc = (WNDPROC)(LONG)(int)GetWindowLong(GetDlgItem(hMain, IDC_HISTORY), GWL_WNDPROC);
1807   SetWindowLong(GetDlgItem(hMain, IDC_HISTORY), GWL_WNDPROC, (LONG)HistoryWndProc);
1808
1809   /* subclass picture frame area */
1810   g_lpPictureFrameWndProc = (WNDPROC)(LONG)(int)GetWindowLong(GetDlgItem(hMain, IDC_SSFRAME), GWL_WNDPROC);
1811   SetWindowLong(GetDlgItem(hMain, IDC_SSFRAME), GWL_WNDPROC, (LONG)PictureFrameWndProc);
1812
1813   /* subclass picture area */
1814   g_lpPictureWndProc = (WNDPROC)(LONG)(int)GetWindowLong(GetDlgItem(hMain, IDC_SSPICTURE), GWL_WNDPROC);
1815   SetWindowLong(GetDlgItem(hMain, IDC_SSPICTURE), GWL_WNDPROC, (LONG)PictureWndProc);
1816
1817   /* Load the pic for the default screenshot. */
1818   hMissing_bitmap = LoadBitmap(GetModuleHandle(NULL),MAKEINTRESOURCE(IDB_ABOUT));
1819
1820   /* Stash hInstance for later use */
1821   hInst = hInstance;
1822
1823   hToolBar   = InitToolbar(hMain);
1824   hStatusBar = InitStatusBar(hMain);
1825   hProgWnd   = InitProgressBar(hStatusBar);
1826
1827   main_resize_items[0].u.hwnd = hToolBar;
1828   main_resize_items[1].u.hwnd = hStatusBar;
1829
1830   /* In order to handle 'Large Fonts' as the Windows
1831    * default setting, we need to make the dialogs small
1832    * enough to fit in our smallest window size with
1833    * large fonts, then resize the picker, tab and button
1834    * controls to fill the window, no matter which font
1835    * is currently set.  This will still look like bad
1836    * if the user uses a bigger default font than 125%
1837    * (Large Fonts) on the Windows display setting tab.
1838    *
1839    * NOTE: This has to do with Windows default font size
1840    * settings, NOT our picker font size.
1841    */
1842
1843   GetClientRect(hMain, &rect);
1844
1845   hTreeView = GetDlgItem(hMain, IDC_TREE);
1846   hwndList  = GetDlgItem(hMain, IDC_LIST);
1847
1848   history_filename = mame_strdup(GetHistoryFileName());
1849   mameinfo_filename = mame_strdup(GetMAMEInfoFileName());
1850
1851   if (!InitSplitters())
1852      return FALSE;
1853
1854   nSplitterCount = GetSplitterCount();
1855   for (i = 0; i < nSplitterCount; i++)
1856   {
1857      HWND hWnd;
1858      HWND hWndLeft;
1859      HWND hWndRight;
1860
1861      hWnd = GetDlgItem(hMain, g_splitterInfo[i].nSplitterWindow);
1862      hWndLeft = GetDlgItem(hMain, g_splitterInfo[i].nLeftWindow);
1863      hWndRight = GetDlgItem(hMain, g_splitterInfo[i].nRightWindow);
1864
1865      AddSplitter(hWnd, hWndLeft, hWndRight, g_splitterInfo[i].pfnAdjust);
1866   }
1867
1868   /* Initial adjustment of controls on the Picker window */
1869   ResizePickerControls(hMain);
1870
1871   TabView_UpdateSelection(hTabCtrl);
1872
1873   bDoGameCheck = GetGameCheck();
1874   idle_work    = TRUE;
1875   game_index   = 0;
1876
1877   bShowTree      = GetShowFolderList();
1878   bShowToolBar   = GetShowToolBar();
1879   bShowStatusBar = GetShowStatusBar();
1880   bShowTabCtrl   = GetShowTabCtrl();
1881
1882   CheckMenuItem(GetMenu(hMain), ID_VIEW_FOLDERS, (bShowTree) ? MF_CHECKED : MF_UNCHECKED);
1883   ToolBar_CheckButton(hToolBar, ID_VIEW_FOLDERS, (bShowTree) ? MF_CHECKED : MF_UNCHECKED);
1884   CheckMenuItem(GetMenu(hMain), ID_VIEW_TOOLBARS, (bShowToolBar) ? MF_CHECKED : MF_UNCHECKED);
1885   ShowWindow(hToolBar, (bShowToolBar) ? SW_SHOW : SW_HIDE);
1886   CheckMenuItem(GetMenu(hMain), ID_VIEW_STATUS, (bShowStatusBar) ? MF_CHECKED : MF_UNCHECKED);
1887   ShowWindow(hStatusBar, (bShowStatusBar) ? SW_SHOW : SW_HIDE);
1888   CheckMenuItem(GetMenu(hMain), ID_VIEW_PAGETAB, (bShowTabCtrl) ? MF_CHECKED : MF_UNCHECKED);
1889
1890   if (oldControl)
1891   {
1892      EnableMenuItem(GetMenu(hMain), ID_CUSTOMIZE_FIELDS, MF_GRAYED);
1893      EnableMenuItem(GetMenu(hMain), ID_GAME_PROPERTIES,   MF_GRAYED);
1894      EnableMenuItem(GetMenu(hMain), ID_OPTIONS_DEFAULTS, MF_GRAYED);
1895   }
1896
1897   /* Init DirectDraw */
1898   if (!DirectDraw_Initialize())
1899   {
1900      DialogBox(GetModuleHandle(NULL),MAKEINTRESOURCE(IDD_DIRECTX), NULL, DirectXDialogProc);
1901      return FALSE;
1902   }
1903
1904   if (GetRandomBackground())
1905      RandomSelectBackground();
1906
1907   LoadBackgroundBitmap();
1908
1909   dprintf("about to init tree");
1910   InitTree(g_folderData, g_filterList);
1911   dprintf("did init tree");
1912
1913   /* Initialize listview columns */
1914#ifdef MESS
1915   InitMessPicker();
1916#endif
1917   InitListView();
1918   SetFocus(hwndList);
1919
1920   /* Reset the font */
1921   {
1922      LOGFONT logfont;
1923
1924      GetListFont(&logfont);
1925      hFont = CreateFontIndirect(&logfont);
1926      if (hFont != NULL)
1927         SetAllWindowsFont(hMain, &main_resize, hFont, FALSE);
1928   }
1929
1930   /* Init DirectInput */
1931   if (!DirectInputInitialize())
1932   {
1933      DialogBox(GetModuleHandle(NULL),MAKEINTRESOURCE(IDD_DIRECTX), NULL, DirectXDialogProc);
1934      return FALSE;
1935   }
1936
1937   AdjustMetrics();
1938   UpdateScreenShot();
1939
1940   hAccel = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDA_TAB_KEYS));
1941
1942   /* clear keyboard state */
1943   KeyboardStateClear();
1944
1945   for (i = 0; i < NUM_GUI_SEQUENCES; i++)
1946   {
1947      input_seq *is1;
1948      input_seq *is2;
1949      is1 = &(GUISequenceControl[i].is);
1950      is2 = GUISequenceControl[i].getiniptr();
1951      // FIXME
1952      //input_seq_copy(is1, is2);
1953      //dprintf("seq =%s is: %4i %4i %4i %4i\n",GUISequenceControl[i].name, (*is1)[0], (*is1)[1], (*is1)[2], (*is1)[3]);
1954   }
1955
1956   if (GetJoyGUI() == TRUE)
1957   {
1958      g_pJoyGUI = &DIJoystick;
1959      if (g_pJoyGUI->init() != 0)
1960         g_pJoyGUI = NULL;
1961      else
1962         SetTimer(hMain, JOYGUI_TIMER, JOYGUI_MS, NULL);
1963   }
1964   else
1965      g_pJoyGUI = NULL;
1966
1967   if (GetHideMouseOnStartup())
1968   {   
1969      /*  For some reason the mouse is centered when a game is exited, which of
1970         course causes a WM_MOUSEMOVE event that shows the mouse. So we center
1971         it now, before the startup coords are initilized, and that way the mouse
1972         will still be hidden when exiting from a game (i hope) :)
1973      */     
1974      SetCursorPos(GetSystemMetrics(SM_CXSCREEN)/2,GetSystemMetrics(SM_CYSCREEN)/2);
1975     
1976      // Then hide it
1977      ShowCursor(FALSE);
1978   }
1979
1980   dprintf("about to show window\n");
1981
1982   nCmdShow = GetWindowState();
1983   if (nCmdShow == SW_HIDE || nCmdShow == SW_MINIMIZE || nCmdShow == SW_SHOWMINIMIZED)
1984   {
1985      nCmdShow = SW_RESTORE;
1986   }
1987
1988   if (GetRunFullScreen())
1989   {
1990      LONG lMainStyle;
1991
1992      // Remove menu
1993      SetMenu(hMain,NULL);
1994
1995      // Frameless dialog (fake fullscreen)
1996      lMainStyle = GetWindowLong(hMain, GWL_STYLE);
1997      lMainStyle = lMainStyle & (WS_BORDER ^ 0xffffffff);
1998      SetWindowLong(hMain, GWL_STYLE, lMainStyle);
1999
2000      nCmdShow = SW_MAXIMIZE;
2001   }
2002
2003   ShowWindow(hMain, nCmdShow);
2004
2005   
2006   switch (GetViewMode())
2007   {
2008   case VIEW_LARGE_ICONS :
2009      SetView(ID_VIEW_LARGE_ICON);
2010      break;
2011   case VIEW_SMALL_ICONS :
2012      SetView(ID_VIEW_SMALL_ICON);
2013      break;
2014   case VIEW_INLIST :
2015      SetView(ID_VIEW_LIST_MENU);
2016      break;
2017   case VIEW_REPORT :
2018      SetView(ID_VIEW_DETAIL);
2019      break;
2020   case VIEW_GROUPED :
2021   default :
2022      SetView(ID_VIEW_GROUPED);
2023      break;
2024   }
2025
2026   if (GetCycleScreenshot() > 0)
2027   {
2028      SetTimer(hMain, SCREENSHOT_TIMER, GetCycleScreenshot()*1000, NULL); //scale to Seconds
2029   }
2030
2031   if (validity_failed)
2032   {
2033      win_message_box_utf8(hMain, MAMENAME " has failed its validity checks.  The GUI will "
2034         "still work, but emulations will fail to execute", MAMENAME, MB_OK);
2035   }
2036
2037   return TRUE;
2038}
2039
2040
2041static void Win32UI_exit()
2042{
2043    if (g_bDoBroadcast == TRUE)
2044    {
2045        ATOM a = GlobalAddAtom(TEXT(""));
2046        SendMessage(HWND_BROADCAST, g_mame32_message, a, a);
2047        GlobalDeleteAtom(a);
2048    }
2049
2050   if (g_pJoyGUI != NULL)
2051      g_pJoyGUI->exit();
2052
2053   /* Free GDI resources */
2054
2055   if (hMissing_bitmap)
2056   {
2057      DeleteObject(hMissing_bitmap);
2058      hMissing_bitmap = NULL;
2059   }
2060
2061   if (hBackground)
2062   {
2063      DeleteObject(hBackground);
2064      hBackground = NULL;
2065   }
2066   
2067   if (hPALbg)
2068   {
2069      DeleteObject(hPALbg);
2070      hPALbg = NULL;
2071   }
2072   
2073   if (hFont)
2074   {
2075      DeleteObject(hFont);
2076      hFont = NULL;
2077   }
2078   
2079   DestroyIcons();
2080
2081   DestroyAcceleratorTable(hAccel);
2082
2083   DirectInputClose();
2084   DirectDraw_Close();
2085
2086   SetSavedFolderID(GetCurrentFolderID());
2087
2088   SaveOptions();
2089
2090   FreeFolders();
2091
2092    /* DestroyTree(hTreeView); */
2093
2094   FreeScreenShot();
2095
2096   OptionsExit();
2097
2098   HelpExit();
2099
2100   pool_free(mame32_pool);
2101   mame32_pool = NULL;
2102}
2103
2104static long WINAPI MameWindowProc(HWND hWnd, UINT message, UINT wParam, LONG lParam)
2105{
2106   MINMAXINFO   *mminfo;
2107   int       i;
2108   TCHAR szClass[128];
2109
2110   switch (message)
2111   {
2112   case WM_CTLCOLORSTATIC:
2113      if (hBackground && (HWND)lParam == GetDlgItem(hMain, IDC_HISTORY))
2114      {
2115         static HBRUSH hBrush=0;
2116         HDC hDC=(HDC)wParam;
2117         LOGBRUSH lb;
2118
2119         if (hBrush)
2120            DeleteObject(hBrush);
2121         lb.lbStyle  = BS_HOLLOW;
2122         hBrush = CreateBrushIndirect(&lb);
2123         SetBkMode(hDC, TRANSPARENT);
2124         SetTextColor(hDC, GetListFontColor());
2125         return (LRESULT) hBrush;
2126      }
2127      break;
2128
2129   case WM_INITDIALOG:
2130      /* Initialize info for resizing subitems */
2131      GetClientRect(hWnd, &main_resize.rect);
2132      return TRUE;
2133
2134   case WM_SETFOCUS:
2135      SetFocus(hwndList);
2136      break;
2137
2138   case WM_SETTINGCHANGE:
2139      AdjustMetrics();
2140      return 0;
2141
2142   case WM_SIZE:
2143      OnSize(hWnd, wParam, LOWORD(lParam), HIWORD(wParam));
2144      return TRUE;
2145
2146   case WM_MENUSELECT:
2147      return Statusbar_MenuSelect(hWnd, wParam, lParam);
2148
2149   case MM_PLAY_GAME:
2150      MamePlayGame();
2151      return TRUE;
2152
2153   case WM_INITMENUPOPUP:
2154      UpdateMenu(GetMenu(hWnd));
2155      break;
2156
2157   case WM_CONTEXTMENU:
2158      if (HandleTreeContextMenu(hWnd, wParam, lParam)
2159      ||   HandleScreenShotContextMenu(hWnd, wParam, lParam))
2160         return FALSE;
2161      break;
2162
2163   case WM_COMMAND:
2164      return MameCommand(hWnd,(int)(LOWORD(wParam)),(HWND)(lParam),(UINT)HIWORD(wParam));
2165
2166   case WM_GETMINMAXINFO:
2167      /* Don't let the window get too small; it can break resizing */
2168      mminfo = (MINMAXINFO *) lParam;
2169      mminfo->ptMinTrackSize.x = MIN_WIDTH;
2170      mminfo->ptMinTrackSize.y = MIN_HEIGHT;
2171      return 0;
2172
2173   case WM_TIMER:
2174      switch (wParam)
2175      {
2176      case JOYGUI_TIMER:
2177         PollGUIJoystick();
2178         break;
2179      case SCREENSHOT_TIMER:
2180         TabView_CalculateNextTab(hTabCtrl);
2181         UpdateScreenShot();
2182         TabView_UpdateSelection(hTabCtrl);
2183         break;
2184      default:
2185         break;
2186      }
2187      return TRUE;
2188
2189   case WM_CLOSE:
2190      {
2191         /* save current item */
2192         RECT rect;
2193         AREA area;
2194         int nItem;
2195         WINDOWPLACEMENT wndpl;
2196         UINT state;
2197
2198         wndpl.length = sizeof(WINDOWPLACEMENT);
2199         GetWindowPlacement(hMain, &wndpl);
2200         state = wndpl.showCmd;
2201
2202         /* Restore the window before we attempt to save parameters,
2203          * This fixed the lost window on startup problem, among other problems
2204          */
2205         if (state == SW_MINIMIZE || state == SW_SHOWMINIMIZED || state == SW_MAXIMIZE)
2206         {
2207            if( wndpl.flags & WPF_RESTORETOMAXIMIZED || state == SW_MAXIMIZE)
2208               state = SW_MAXIMIZE;
2209            else
2210            {
2211               state = SW_RESTORE;
2212               ShowWindow(hWnd, SW_RESTORE);
2213            }
2214         }
2215         for (i = 0; i < GetSplitterCount(); i++)
2216            SetSplitterPos(i, nSplitterOffset[i]);
2217         SetWindowState(state);
2218
2219         for (i = 0; i < sizeof(s_nPickers) / sizeof(s_nPickers[0]); i++)
2220            Picker_SaveColumnWidths(GetDlgItem(hMain, s_nPickers[i]));
2221
2222         GetWindowRect(hWnd, &rect);
2223         area.x      = rect.left;
2224         area.y      = rect.top;
2225         area.width   = rect.right  - rect.left;
2226         area.height = rect.bottom - rect.top;
2227         SetWindowArea(&area);
2228
2229         /* Save the users current game options and default game */
2230         nItem = Picker_GetSelectedItem(hwndList);
2231         SetDefaultGame(ModifyThe(drivers[nItem]->name));
2232
2233         /* hide window to prevent orphan empty rectangles on the taskbar */
2234         /* ShowWindow(hWnd,SW_HIDE); */
2235            DestroyWindow( hWnd );
2236
2237         /* PostQuitMessage(0); */
2238         break;
2239      }
2240
2241   case WM_DESTROY:
2242        PostQuitMessage(0);
2243      return 0;
2244
2245   case WM_LBUTTONDOWN:
2246      OnLButtonDown(hWnd, (UINT)wParam, MAKEPOINTS(lParam));
2247      break;
2248
2249      /*
2250        Check to see if the mouse has been moved by the user since
2251        startup. I'd like this checking to be done only in the
2252        main WinProc (here), but somehow the WM_MOUSEDOWN messages
2253        are eaten up before they reach MameWindowProc. That's why
2254        there is one check for each of the subclassed windows too.
2255   
2256        POSSIBLE BUGS:
2257        I've included this check in the subclassed windows, but a
2258        mose move in either the title bar, the menu, or the
2259        toolbar will not generate a WM_MOUSEOVER message. At least
2260        not one that I know how to pick up. A solution could maybe
2261        be to subclass those too, but that's too much work :)
2262      */
2263     
2264   case WM_MOUSEMOVE:
2265   {
2266      if (MouseHasBeenMoved())
2267         ShowCursor(TRUE);
2268     
2269      if (g_listview_dragging)
2270         MouseMoveListViewDrag(MAKEPOINTS(lParam));
2271      else
2272         /* for splitters */
2273         OnMouseMove(hWnd, (UINT)wParam, MAKEPOINTS(lParam));
2274      break;
2275   }
2276
2277   case WM_LBUTTONUP:
2278       if (g_listview_dragging)
2279          ButtonUpListViewDrag(MAKEPOINTS(lParam));
2280      else
2281         /* for splitters */
2282         OnLButtonUp(hWnd, (UINT)wParam, MAKEPOINTS(lParam));
2283      break;
2284
2285   case WM_NOTIFY:
2286      /* Where is this message intended to go */
2287      {
2288         LPNMHDR lpNmHdr = (LPNMHDR)lParam;
2289
2290         /* Fetch tooltip text */
2291         if (lpNmHdr->code == TTN_NEEDTEXT)
2292         {
2293            LPTOOLTIPTEXT lpttt = (LPTOOLTIPTEXT)lParam;
2294            CopyToolTipText(lpttt);
2295         }
2296
2297         if (lpNmHdr->hwndFrom == hTreeView)
2298            return TreeViewNotify(lpNmHdr);
2299
2300         GetClassName(lpNmHdr->hwndFrom, szClass, sizeof(szClass) / sizeof(szClass[0]));
2301         if (!_tcscmp(szClass, TEXT("SysListView32")))
2302            return Picker_HandleNotify(lpNmHdr);   
2303         if (!_tcscmp(szClass, TEXT("SysTabControl32")))
2304            return TabView_HandleNotify(lpNmHdr);
2305      }
2306      break;
2307
2308   case WM_DRAWITEM:
2309      {
2310         LPDRAWITEMSTRUCT lpDis = (LPDRAWITEMSTRUCT)lParam;
2311
2312         GetClassName(lpDis->hwndItem, szClass, sizeof(szClass) / sizeof(szClass[0]));
2313         if (!_tcscmp(szClass, TEXT("SysListView32")))
2314            Picker_HandleDrawItem(GetDlgItem(hMain, lpDis->CtlID), lpDis);
2315      }
2316      break;
2317
2318   case WM_MEASUREITEM :
2319   {
2320      LPMEASUREITEMSTRUCT lpmis = (LPMEASUREITEMSTRUCT) lParam;
2321
2322      // tell the list view that each row (item) should be just taller than our font
2323
2324      //DefWindowProc(hWnd, message, wParam, lParam);
2325      //dprintf("default row height calculation gives %u\n",lpmis->itemHeight);
2326
2327      TEXTMETRIC tm;
2328      HDC hDC = GetDC(NULL);
2329      HFONT hFontOld = (HFONT)SelectObject(hDC,hFont);
2330
2331      GetTextMetrics(hDC,&tm);
2332     
2333      lpmis->itemHeight = tm.tmHeight + tm.tmExternalLeading + 1;
2334      if (lpmis->itemHeight < 17)
2335         lpmis->itemHeight = 17;
2336      //dprintf("we would do %u\n",tm.tmHeight + tm.tmExternalLeading + 1);
2337      SelectObject(hDC,hFontOld);
2338      ReleaseDC(NULL,hDC);
2339
2340      return TRUE;
2341   }
2342
2343   case WM_MAME32_FILECHANGED:
2344      {
2345         char szFileName[32];
2346         char *s;
2347         int nGameIndex;
2348         int (*pfnGetAuditResults)(int driver_index) = NULL;
2349         void (*pfnSetAuditResults)(int driver_index, int audit_results) = NULL;
2350
2351         switch(HIWORD(wParam))
2352         {
2353            case 0:
2354               pfnGetAuditResults = GetRomAuditResults;
2355               pfnSetAuditResults = SetRomAuditResults;
2356               break;
2357
2358            case 1:
2359               pfnGetAuditResults = GetSampleAuditResults;
2360               pfnSetAuditResults = SetSampleAuditResults;
2361               break;
2362         }
2363
2364         if (pfnGetAuditResults && pfnSetAuditResults)
2365         {
2366            int nParentIndex = -1;
2367
2368            snprintf(szFileName, sizeof(szFileName), "%s", (LPCSTR) lParam);
2369            s = strchr(szFileName, '.');
2370            if (s)
2371               *s = '\0';
2372            s = strchr(szFileName, '\\');
2373            if (s)
2374               *s = '\0';
2375
2376            for (nGameIndex = 0; drivers[nGameIndex]; nGameIndex++)
2377            {
2378               for (nParentIndex = nGameIndex; nGameIndex == -1; nParentIndex = GetParentIndex(drivers[nParentIndex]))
2379               {
2380                  if (!mame_stricmp(drivers[nParentIndex]->name, szFileName))
2381                  {
2382                     if (pfnGetAuditResults(nGameIndex) != UNKNOWN)
2383                     {
2384                        pfnSetAuditResults(nGameIndex, UNKNOWN);
2385                        PostMessage(hMain, WM_MAME32_AUDITGAME, wParam, nGameIndex);
2386                     }
2387                     break;
2388                  }
2389               }
2390            }
2391         }
2392      }
2393      break;
2394
2395   case WM_MAME32_AUDITGAME:
2396      {
2397         LV_FINDINFO lvfi;
2398         int nGameIndex;
2399
2400         nGameIndex = lParam;
2401
2402         switch(HIWORD(wParam))
2403         {
2404            case 0:
2405               Mame32VerifyRomSet(nGameIndex);
2406               break;
2407            case 1:
2408               Mame32VerifySampleSet(nGameIndex);
2409               break;
2410         }
2411
2412         memset(&lvfi, 0, sizeof(lvfi));
2413         lvfi.flags   = LVFI_PARAM;
2414         lvfi.lParam = nGameIndex;
2415
2416         i = ListView_FindItem(hwndList, -1, &lvfi);
2417         if (i != -1)
2418         {
2419            ListView_RedrawItems(hwndList, i, i);
2420         }
2421      }
2422      break;
2423
2424   default:
2425
2426      break;
2427   }
2428
2429   return DefWindowProc(hWnd, message, wParam, lParam);
2430}
2431
2432static int HandleKeyboardGUIMessage(HWND hWnd, UINT message, UINT wParam, LONG lParam)
2433{
2434   switch (message)
2435   {
2436      case WM_CHAR: /* List-View controls use this message for searching the items "as user types" */
2437         //MessageBox(NULL,"wm_char message arrived","TitleBox",MB_OK);
2438         return TRUE;
2439
2440      case WM_KEYDOWN:
2441         KeyboardKeyDown(0, wParam, lParam);
2442         return TRUE;
2443
2444      case WM_KEYUP:
2445         KeyboardKeyUp(0, wParam, lParam);
2446         return TRUE;
2447
2448      case WM_SYSKEYDOWN:
2449         KeyboardKeyDown(1, wParam, lParam);
2450         return TRUE;
2451
2452      case WM_SYSKEYUP:
2453         KeyboardKeyUp(1, wParam, lParam);
2454         return TRUE;
2455   }
2456
2457   return FALSE;   /* message not processed */
2458}
2459
2460static BOOL PumpMessage()
2461{
2462   MSG msg;
2463
2464   if (!GetMessage(&msg, NULL, 0, 0))
2465    {
2466      return FALSE;
2467    }
2468
2469   if (IsWindow(hMain))
2470   {
2471      BOOL absorbed_key = FALSE;
2472      if (GetKeyGUI())
2473         absorbed_key = HandleKeyboardGUIMessage(msg.hwnd, msg.message,
2474                                       msg.wParam, msg.lParam);
2475      else
2476         absorbed_key = TranslateAccelerator(hMain, hAccel, &msg);
2477
2478      if (!absorbed_key)
2479      {
2480         if (!IsDialogMessage(hMain, &msg))
2481         {
2482            TranslateMessage(&msg);
2483            DispatchMessage(&msg);
2484         }
2485      }
2486   }
2487
2488   return TRUE;
2489}
2490
2491static BOOL FolderCheck(void)
2492{
2493   
2494   char *pDescription = NULL;
2495   int nGameIndex = 0;
2496   int i=0;
2497   int iStep = 0;
2498   LV_FINDINFO lvfi;
2499   int nCount = ListView_GetItemCount(hwndList);
2500   BOOL changed = FALSE;
2501
2502   MSG msg;
2503   for(i=0; i<nCount;i++)
2504   {
2505      LV_ITEM lvi;
2506
2507      lvi.iItem = i;
2508      lvi.iSubItem = 0;
2509      lvi.mask    = LVIF_PARAM;
2510      ListView_GetItem(hwndList, &lvi);
2511      nGameIndex  = lvi.lParam;
2512      SetRomAuditResults(nGameIndex, UNKNOWN);
2513      SetSampleAuditResults(nGameIndex, UNKNOWN);
2514   }
2515   if( nCount > 0)
2516      ProgressBarShow();
2517   else
2518      return FALSE;
2519   if( nCount < 100 )
2520      iStep = 100 / nCount;
2521   else
2522      iStep = nCount/100;
2523   UpdateListView();
2524   UpdateWindow(hMain);
2525   for(i=0; i<nCount;i++)
2526   {
2527      LV_ITEM lvi;
2528
2529      lvi.iItem = i;
2530      lvi.iSubItem = 0;
2531      lvi.mask    = LVIF_PARAM;
2532      ListView_GetItem(hwndList, &lvi);
2533      nGameIndex  = lvi.lParam;
2534      if (GetRomAuditResults(nGameIndex) == UNKNOWN)
2535      {
2536         Mame32VerifyRomSet(nGameIndex);
2537         changed = TRUE;
2538      }
2539
2540      if (GetSampleAuditResults(nGameIndex) == UNKNOWN)
2541      {
2542         Mame32VerifySampleSet(nGameIndex);
2543         changed = TRUE;
2544      }
2545
2546      lvfi.flags   = LVFI_PARAM;
2547      lvfi.lParam = nGameIndex;
2548
2549      i = ListView_FindItem(hwndList, -1, &lvfi);
2550      if (changed && i != -1);
2551      {
2552         ListView_RedrawItems(hwndList, i, i);
2553         while( PeekMessage( &msg, hwndList, 0, 0, PM_REMOVE ) != 0)
2554         {
2555            TranslateMessage(&msg);
2556            DispatchMessage(&msg);
2557         }
2558      }
2559      changed = FALSE;
2560      if ((i % iStep) == 0)
2561         ProgressBarStepParam(i, nCount);
2562   }
2563   ProgressBarHide();
2564   pDescription = ModifyThe(drivers[Picker_GetSelectedItem(hwndList)]->description);
2565   SetStatusBarText(0, pDescription);
2566   UpdateStatusBar();
2567   return TRUE;
2568}
2569
2570static BOOL GameCheck(void)
2571{
2572   LV_FINDINFO lvfi;
2573   int i;
2574   BOOL changed = FALSE;
2575
2576   if (game_index == 0)
2577      ProgressBarShow();
2578
2579   if (game_index >= driver_list_get_count(drivers))
2580   {
2581      bDoGameCheck = FALSE;
2582      ProgressBarHide();
2583      ResetWhichGamesInFolders();
2584      return FALSE;
2585   }
2586
2587   if (GetRomAuditResults(game_index) == UNKNOWN)
2588   {
2589      Mame32VerifyRomSet(game_index);
2590      changed = TRUE;
2591   }
2592
2593   if (GetSampleAuditResults(game_index) == UNKNOWN)
2594   {
2595      Mame32VerifySampleSet(game_index);
2596      changed = TRUE;
2597   }
2598
2599   lvfi.flags   = LVFI_PARAM;
2600   lvfi.lParam = game_index;
2601
2602   i = ListView_FindItem(hwndList, -1, &lvfi);
2603   if (changed && i != -1);
2604      ListView_RedrawItems(hwndList, i, i);
2605   if ((game_index % progBarStep) == 0)
2606      ProgressBarStep();
2607   game_index++;
2608
2609   return changed;
2610}
2611
2612static BOOL OnIdle(HWND hWnd)
2613{
2614   static int bFirstTime = TRUE;
2615   static int bResetList = TRUE;
2616
2617   char *pDescription;
2618   int driver_index;
2619
2620   if (bFirstTime)
2621   {
2622      bResetList = FALSE;
2623      bFirstTime = FALSE;
2624   }
2625   if (bDoGameCheck)
2626   {
2627      bResetList |= GameCheck();
2628      return idle_work;
2629   }
2630   // NPW 17-Jun-2003 - Commenting this out because it is redundant
2631   // and it causes the game to reset back to the original game after an F5
2632   // refresh
2633   //driver_index = GetGameNameIndex(GetDefaultGame());
2634   //SetSelectedPickItem(driver_index);
2635
2636   // in case it's not found, get it back
2637   driver_index = Picker_GetSelectedItem(hwndList);
2638
2639   pDescription = ModifyThe(drivers[driver_index]->description);
2640   SetStatusBarText(0, pDescription);
2641   idle_work = FALSE;
2642   UpdateStatusBar();
2643   bFirstTime = TRUE;
2644
2645   if (!idle_work)
2646      PostMessage(GetMainWindow(),WM_COMMAND, MAKEWPARAM(ID_VIEW_LINEUPICONS, TRUE),(LPARAM)NULL);
2647   return idle_work;
2648}
2649
2650static void OnSize(HWND hWnd, UINT nState, int nWidth, int nHeight)
2651{
2652   static BOOL firstTime = TRUE;
2653
2654   if (nState != SIZE_MAXIMIZED && nState != SIZE_RESTORED)
2655      return;
2656
2657   ResizeWindow(hWnd, &main_resize);
2658   ResizeProgressBar();
2659   if (firstTime == FALSE)
2660      OnSizeSplitter(hMain);
2661   //firstTime = FALSE;
2662   /* Update the splitters structures as appropriate */
2663   RecalcSplitters();
2664   if (firstTime == FALSE)
2665      ResizePickerControls(hMain);
2666   firstTime = FALSE;
2667   UpdateScreenShot();
2668}
2669
2670
2671
2672static HWND GetResizeItemWindow(HWND hParent, const ResizeItem *ri)
2673{
2674   HWND hControl;
2675   if (ri->type == RA_ID)
2676      hControl = GetDlgItem(hParent, ri->u.id);
2677   else
2678      hControl = ri->u.hwnd;
2679   return hControl;
2680}
2681
2682
2683
2684static void SetAllWindowsFont(HWND hParent, const Resize *r, HFONT hTheFont, BOOL bRedraw)
2685{
2686   int i;
2687   HWND hControl;
2688
2689   for (i = 0; r->items[i].type != RA_END; i++)
2690   {
2691      if (r->items[i].setfont)
2692      {
2693         hControl = GetResizeItemWindow(hParent, &r->items[i]);
2694         SetWindowFont(hControl, hTheFont, bRedraw);
2695      }
2696   }
2697}
2698
2699
2700
2701static void ResizeWindow(HWND hParent, Resize *r)
2702{
2703   int cmkindex = 0, dx, dy, dx1, dtempx;
2704   HWND hControl;
2705   RECT parent_rect, rect;
2706   ResizeItem *ri;
2707   POINT p = {0, 0};
2708
2709   if (hParent == NULL)
2710      return;
2711
2712   /* Calculate change in width and height of parent window */
2713   GetClientRect(hParent, &parent_rect);
2714   //dx = parent_rect.right - r->rect.right;
2715   dtempx = parent_rect.right - r->rect.right;
2716   dy = parent_rect.bottom - r->rect.bottom;
2717   dx = dtempx/2;
2718   dx1 = dtempx - dx;
2719   ClientToScreen(hParent, &p);
2720
2721   while (r->items[cmkindex].type != RA_END)
2722   {
2723      ri = &r->items[cmkindex];
2724      if (ri->type == RA_ID)
2725         hControl = GetDlgItem(hParent, ri->u.id);
2726      else
2727         hControl = ri->u.hwnd;
2728
2729      if (hControl == NULL)
2730      {
2731         cmkindex++;
2732         continue;
2733      }
2734
2735      /* Get control's rectangle relative to parent */
2736      GetWindowRect(hControl, &rect);
2737      OffsetRect(&rect, -p.x, -p.y);
2738
2739      if (!(ri->action & RA_LEFT))
2740         rect.left += dx;
2741
2742      if (!(ri->action & RA_TOP))
2743         rect.top += dy;
2744
2745      if (ri->action & RA_RIGHT)
2746         rect.right += dx;
2747
2748      if (ri->action & RA_BOTTOM)
2749         rect.bottom += dy;
2750
2751      MoveWindow(hControl, rect.left, rect.top,
2752               (rect.right - rect.left),
2753               (rect.bottom - rect.top), TRUE);
2754
2755      /* Take care of subcontrols, if appropriate */
2756      if (ri->subwindow != NULL)
2757         ResizeWindow(hControl, ri->subwindow);
2758
2759      cmkindex++;
2760   }
2761
2762   /* Record parent window's new location */
2763   memcpy(&r->rect, &parent_rect, sizeof(RECT));
2764}
2765
2766static void ProgressBarShow()
2767{
2768   RECT rect;
2769   int  widths[2] = {150, -1};
2770
2771   if (driver_list_get_count(drivers) < 100)
2772      progBarStep = 100 / driver_list_get_count(drivers);
2773   else
2774      progBarStep = (driver_list_get_count(drivers) / 100);
2775
2776   SendMessage(hStatusBar, SB_SETPARTS, (WPARAM)2, (LPARAM)(LPINT)widths);
2777   SendMessage(hProgWnd, PBM_SETRANGE, 0, (LPARAM)MAKELONG(0, driver_list_get_count(drivers)));
2778   SendMessage(hProgWnd, PBM_SETSTEP, (WPARAM)progBarStep, 0);
2779   SendMessage(hProgWnd, PBM_SETPOS, 0, 0);
2780
2781   StatusBar_GetItemRect(hStatusBar, 1, &rect);
2782
2783   MoveWindow(hProgWnd, rect.left, rect.top,
2784            rect.right - rect.left,
2785            rect.bottom - rect.top, TRUE);
2786
2787   bProgressShown = TRUE;
2788}
2789
2790static void ProgressBarHide()
2791{
2792   RECT rect;
2793   int  widths[4];
2794   HDC  hDC;
2795   SIZE size;
2796   int  numParts = 4;
2797
2798   if (hProgWnd == NULL)
2799   {
2800      return;
2801   }
2802
2803   hDC = GetDC(hProgWnd);
2804
2805   ShowWindow(hProgWnd, SW_HIDE);
2806
2807   GetTextExtentPoint32(hDC, TEXT("MMX"), 3, &size);
2808   widths[3] = size.cx;
2809   GetTextExtentPoint32(hDC, TEXT("MMMM games"), 10, &size);
2810   widths[2] = size.cx;
2811   //Just specify 24 instead of 30, gives us sufficient space to display the message, and saves some space
2812   GetTextExtentPoint32(hDC, TEXT("Screen flip support is missing"), 24, &size);
2813   widths[1] = size.cx;
2814
2815   ReleaseDC(hProgWnd, hDC);
2816
2817   widths[0] = -1;
2818   SendMessage(hStatusBar, SB_SETPARTS, (WPARAM)1, (LPARAM)(LPINT)widths);
2819   StatusBar_GetItemRect(hStatusBar, 0, &rect);
2820
2821   widths[0] = (rect.right - rect.left) - (widths[1] + widths[2] + widths[3]);
2822   widths[1] += widths[0];
2823   widths[2] += widths[1];
2824   widths[3] = -1;
2825
2826   SendMessage(hStatusBar, SB_SETPARTS, (WPARAM)numParts, (LPARAM)(LPINT)widths);
2827   UpdateStatusBar();
2828
2829   bProgressShown = FALSE;
2830}
2831
2832static void ResizeProgressBar()
2833{
2834   if (bProgressShown)
2835   {
2836      RECT rect;
2837      int  widths[2] = {150, -1};
2838
2839      SendMessage(hStatusBar, SB_SETPARTS, (WPARAM)2, (LPARAM)(LPINT)widths);
2840      StatusBar_GetItemRect(hStatusBar, 1, &rect);
2841      MoveWindow(hProgWnd, rect.left, rect.top,
2842               rect.right  - rect.left,
2843               rect.bottom - rect.top, TRUE);
2844   }
2845   else
2846   {
2847      ProgressBarHide();
2848   }
2849}
2850
2851static void ProgressBarStepParam(int iGameIndex, int nGameCount)
2852{
2853   SetStatusBarTextF(0, "Game search %d%% complete",
2854         ((iGameIndex + 1) * 100) / nGameCount);
2855   if (iGameIndex == 0)
2856      ShowWindow(hProgWnd, SW_SHOW);
2857   SendMessage(hProgWnd, PBM_STEPIT, 0, 0);
2858}
2859
2860static void ProgressBarStep()
2861{
2862   ProgressBarStepParam(game_index, driver_list_get_count(drivers));
2863}
2864
2865static HWND InitProgressBar(HWND hParent)
2866{
2867   RECT rect;
2868
2869   StatusBar_GetItemRect(hStatusBar, 0, &rect);
2870
2871   rect.left += 150;
2872
2873   return CreateWindowEx(WS_EX_STATICEDGE,
2874         PROGRESS_CLASS,
2875         TEXT("Progress Bar"),
2876         WS_CHILD | PBS_SMOOTH,
2877         rect.left,
2878         rect.top,
2879         rect.right   - rect.left,
2880         rect.bottom - rect.top,
2881         hParent,
2882         NULL,
2883         hInst,
2884         NULL);
2885}
2886
2887static void CopyToolTipText(LPTOOLTIPTEXT lpttt)
2888{
2889   int   i;
2890   int   iButton = lpttt->hdr.idFrom;
2891   static TCHAR String[1024];
2892   BOOL bConverted = FALSE;
2893   TCHAR* t_gameinfostatus;
2894
2895   /* Map command ID to string index */
2896   for (i = 0; CommandToString[i] != -1; i++)
2897   {
2898      if (CommandToString[i] == iButton)
2899      {
2900         iButton = i;
2901         bConverted = TRUE;
2902         break;
2903      }
2904   }
2905   if( bConverted )
2906   {
2907      /* Check for valid parameter */
2908      if(iButton > NUM_TOOLTIPS)
2909      {
2910         _tcscpy(String,TEXT("Invalid Button Index"));
2911      }
2912      else
2913      {
2914         _tcscpy(String,szTbStrings[iButton]);
2915      }
2916   }
2917   else if ( iButton <= 2 )
2918   {
2919      //Statusbar
2920      SendMessage(lpttt->hdr.hwndFrom, TTM_SETMAXTIPWIDTH, 0, 200);
2921      if( iButton != 1)
2922         SendMessage(hStatusBar, SB_GETTEXT, (WPARAM)iButton, (LPARAM)&String );
2923      else {
2924         //for first pane we get the Status directly, to get the line breaks
2925         t_gameinfostatus = tstring_from_utf8( GameInfoStatus(Picker_GetSelectedItem(hwndList), FALSE));
2926         if( !t_gameinfostatus )
2927            return;
2928         _tcscpy(String, t_gameinfostatus);
2929         free(t_gameinfostatus);
2930      }
2931   }
2932   else
2933      _tcscpy(String,TEXT("Invalid Button Index"));
2934
2935   lpttt->lpszText = String;
2936}
2937
2938static HWND InitToolbar(HWND hParent)
2939{
2940   HWND hToolBar = CreateToolbarEx(hParent,
2941                     WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS |
2942                     CCS_TOP | TBSTYLE_FLAT | TBSTYLE_TOOLTIPS,
2943                     1,
2944                     8,
2945                     hInst,
2946                     IDB_TOOLBAR,
2947                     tbb,
2948                     NUM_TOOLBUTTONS,
2949                     16,
2950                     16,
2951                     0,
2952                     0,
2953                     sizeof(TBBUTTON));
2954   RECT rect;
2955   int idx;
2956   int iPosX, iPosY, iHeight;
2957
2958   // get Edit Control position
2959   idx = SendMessage(hToolBar, TB_BUTTONCOUNT, (WPARAM)0, (LPARAM)0) - 1;
2960   SendMessage(hToolBar, TB_GETITEMRECT, (WPARAM)idx, (LPARAM)&rect);
2961   iPosX = rect.right + 10;
2962   iPosY = rect.top + 1;
2963   iHeight = rect.bottom - rect.top - 2;
2964
2965   // create Edit Control
2966   CreateWindowEx( 0L, TEXT("Edit"), SEARCH_PROMPT, WS_CHILD | WS_BORDER | WS_VISIBLE | ES_LEFT,
2967               iPosX, iPosY, 200, iHeight, hToolBar, (HMENU)ID_TOOLBAR_EDIT, hInst, NULL );
2968
2969   return hToolBar;
2970}
2971
2972static HWND InitStatusBar(HWND hParent)
2973{
2974   HMENU hMenu = GetMenu(hParent);
2975
2976   popstr[0].hMenu    = 0;
2977   popstr[0].uiString = 0;
2978   popstr[1].hMenu    = hMenu;
2979   popstr[1].uiString = IDS_UI_FILE;
2980   popstr[2].hMenu    = GetSubMenu(hMenu, 1);
2981   popstr[2].uiString = IDS_VIEW_TOOLBAR;
2982   popstr[3].hMenu    = 0;
2983   popstr[3].uiString = 0;
2984
2985   return CreateStatusWindow(WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS |
2986                       CCS_BOTTOM | SBARS_SIZEGRIP | SBT_TOOLTIPS,
2987                       TEXT("Ready"),
2988                       hParent,
2989                       2);
2990}
2991
2992
2993static LRESULT Statusbar_MenuSelect(HWND hwnd, WPARAM wParam, LPARAM lParam)
2994{
2995   UINT  fuFlags   = (UINT)HIWORD(wParam);
2996   HMENU hMainMenu = NULL;
2997   int   iMenu    = 0;
2998
2999   /* Handle non-system popup menu descriptions. */
3000   if (  (fuFlags & MF_POPUP)
3001   &&   (!(fuFlags & MF_SYSMENU)))
3002   {
3003      for (iMenu = 1; iMenu < MAX_MENUS; iMenu++)
3004      {
3005         if ((HMENU)lParam == popstr[iMenu].hMenu)
3006         {
3007            hMainMenu = (HMENU)lParam;
3008            break ;
3009         }
3010      }
3011   }
3012
3013   if (hMainMenu)
3014   {
3015      /* Display helpful text in status bar */
3016      MenuHelp(WM_MENUSELECT, wParam, lParam, hMainMenu, hInst,
3017             hStatusBar, (UINT *)&popstr[iMenu]);
3018   }
3019   else
3020   {
3021      UINT nZero = 0;
3022      MenuHelp(WM_MENUSELECT, wParam, lParam, NULL, hInst,
3023             hStatusBar, &nZero);
3024   }
3025
3026   return 0;
3027}
3028
3029static void UpdateStatusBar()
3030{
3031   LPTREEFOLDER lpFolder = GetCurrentFolder();
3032   int        games_shown = 0;
3033   int        i = -1;
3034
3035   if (!lpFolder)
3036      return;
3037
3038   while (1)
3039   {
3040      i = FindGame(lpFolder,i+1);
3041      if (i == -1)
3042         break;
3043
3044      if (!GameFiltered(i, lpFolder->m_dwFlags))
3045         games_shown++;
3046   }
3047
3048   /* Show number of games in the current 'View' in the status bar */
3049   SetStatusBarTextF(2, g_szGameCountString, games_shown);
3050
3051   i = Picker_GetSelectedItem(hwndList);
3052
3053   if (games_shown == 0)
3054      DisableSelection();
3055   else
3056   {
3057      const char* pStatus = GameInfoStatus(i, FALSE);
3058      SetStatusBarText(1, pStatus);
3059   }
3060}
3061
3062static void UpdateHistory(void)
3063{
3064   HDC hDC;
3065   RECT rect;
3066   TEXTMETRIC     tm ;
3067   int nLines, nLineHeight;
3068   //DWORD dwStyle = GetWindowLong(GetDlgItem(hMain, IDC_HISTORY), GWL_STYLE);
3069   have_history = FALSE;
3070
3071   if (GetSelectedPick() >= 0)
3072   {
3073      char *histText = GetGameHistory(Picker_GetSelectedItem(hwndList));
3074
3075      have_history = (histText && histText[0]) ? TRUE : FALSE;
3076      win_set_window_text_utf8(GetDlgItem(hMain, IDC_HISTORY), histText);
3077   }
3078
3079   if (have_history && GetShowScreenShot()
3080      && ((TabView_GetCurrentTab(hTabCtrl) == TAB_HISTORY) ||
3081         (TabView_GetCurrentTab(hTabCtrl) == GetHistoryTab() && GetShowTab(TAB_HISTORY) == FALSE) ||
3082         (TAB_ALL == GetHistoryTab() && GetShowTab(TAB_HISTORY) == FALSE) ))
3083   {
3084      Edit_GetRect(GetDlgItem(hMain, IDC_HISTORY),&rect);
3085      nLines = Edit_GetLineCount(GetDlgItem(hMain, IDC_HISTORY) );
3086      hDC = GetDC(GetDlgItem(hMain, IDC_HISTORY));
3087      GetTextMetrics (hDC, &tm);
3088      nLineHeight = tm.tmHeight - tm.tmInternalLeading;
3089      if( ( (rect.bottom - rect.top) / nLineHeight) < (nLines) )
3090      {
3091         //more than one Page, so show Scrollbar
3092         SetScrollRange(GetDlgItem(hMain, IDC_HISTORY), SB_VERT, 0, nLines, TRUE);
3093      }
3094      else
3095      {
3096         //hide Scrollbar
3097         SetScrollRange(GetDlgItem(hMain, IDC_HISTORY),SB_VERT, 0, 0, TRUE);
3098
3099      }
3100       ShowWindow(GetDlgItem(hMain, IDC_HISTORY), SW_SHOW);
3101   }
3102   else
3103      ShowWindow(GetDlgItem(hMain, IDC_HISTORY), SW_HIDE);
3104
3105}
3106
3107
3108static void DisableSelection()
3109{
3110   MENUITEMINFO   mmi;
3111   HMENU         hMenu = GetMenu(hMain);
3112   BOOL         prev_have_selection = have_selection;
3113
3114   mmi.cbSize      = sizeof(mmi);
3115   mmi.fMask      = MIIM_TYPE;
3116   mmi.fType      = MFT_STRING;
3117   mmi.dwTypeData = (TCHAR *) TEXT("&Play");
3118   mmi.cch       = _tcslen(mmi.dwTypeData);
3119   SetMenuItemInfo(hMenu, ID_FILE_PLAY, FALSE, &mmi);
3120
3121   EnableMenuItem(hMenu, ID_FILE_PLAY,          MF_GRAYED);
3122   EnableMenuItem(hMenu, ID_FILE_PLAY_RECORD,      MF_GRAYED);
3123   EnableMenuItem(hMenu, ID_GAME_PROPERTIES,      MF_GRAYED);
3124
3125   SetStatusBarText(0, "No Selection");
3126   SetStatusBarText(1, "");
3127   SetStatusBarText(3, "");
3128
3129   have_selection = FALSE;
3130
3131   if (prev_have_selection != have_selection)
3132      UpdateScreenShot();
3133}
3134
3135static void EnableSelection(int nGame)
3136{
3137   TCHAR         buf[200];
3138   const char *   pText;
3139   MENUITEMINFO   mmi;
3140   HMENU         hMenu = GetMenu(hMain);
3141   TCHAR*          t_description;
3142
3143#ifdef MESS
3144   MyFillSoftwareList(nGame, FALSE);
3145#endif
3146
3147   t_description = tstring_from_utf8(ConvertAmpersandString(ModifyThe(drivers[nGame]->description)));
3148   if( !t_description )
3149      return;
3150
3151   _sntprintf(buf, sizeof(buf) / sizeof(buf[0]), g_szPlayGameString, t_description);
3152   mmi.cbSize      = sizeof(mmi);
3153   mmi.fMask      = MIIM_TYPE;
3154   mmi.fType      = MFT_STRING;
3155   mmi.dwTypeData = buf;
3156   mmi.cch       = _tcslen(mmi.dwTypeData);
3157   SetMenuItemInfo(hMenu, ID_FILE_PLAY, FALSE, &mmi);
3158
3159   pText = ModifyThe(drivers[nGame]->description);
3160   SetStatusBarText(0, pText);
3161   /* Add this game's status to the status bar */
3162   pText = GameInfoStatus(nGame, FALSE);
3163   SetStatusBarText(1, pText);
3164   SetStatusBarText(3, "");
3165
3166   /* If doing updating game status and the game name is NOT pacman.... */
3167
3168   EnableMenuItem(hMenu, ID_FILE_PLAY,          MF_ENABLED);
3169   EnableMenuItem(hMenu, ID_FILE_PLAY_RECORD,      MF_ENABLED);
3170
3171   if (!oldControl)
3172      EnableMenuItem(hMenu, ID_GAME_PROPERTIES, MF_ENABLED);
3173
3174   if (bProgressShown && bListReady == TRUE)
3175   {
3176      SetDefaultGame(ModifyThe(drivers[nGame]->name));
3177   }
3178   have_selection = TRUE;
3179
3180   UpdateScreenShot();
3181
3182   free(t_description);
3183}
3184
3185static void PaintBackgroundImage(HWND hWnd, HRGN hRgn, int x, int y)
3186{
3187   RECT      rcClient;
3188   HRGN      rgnBitmap;
3189   HPALETTE   hPAL;
3190   HDC       hDC = GetDC(hWnd);
3191   int       i, j;
3192   HDC       htempDC;
3193   HBITMAP    oldBitmap;
3194
3195   /* x and y are offsets within the background image that should be at 0,0 in hWnd */
3196
3197   /* So we don't paint over the control's border */
3198   GetClientRect(hWnd, &rcClient);
3199
3200   htempDC = CreateCompatibleDC(hDC);
3201   oldBitmap = SelectObject(htempDC, hBackground);
3202
3203   if (hRgn == NULL)
3204   {
3205      /* create a region of our client area */
3206      rgnBitmap = CreateRectRgnIndirect(&rcClient);
3207      SelectClipRgn(hDC, rgnBitmap);
3208      DeleteObject(rgnBitmap);
3209   }
3210   else
3211   {
3212      /* use the passed in region */
3213      SelectClipRgn(hDC, hRgn);
3214   }
3215
3216   hPAL = GetBackgroundPalette();
3217   if (hPAL == NULL)
3218      hPAL = CreateHalftonePalette(hDC);
3219
3220   if (GetDeviceCaps(htempDC, RASTERCAPS) & RC_PALETTE && hPAL != NULL)
3221   {
3222      SelectPalette(htempDC, hPAL, FALSE);
3223      RealizePalette(htempDC);
3224   }
3225
3226   for (i = rcClient.left-x; i < rcClient.right; i += bmDesc.bmWidth)
3227      for (j = rcClient.top-y; j < rcClient.bottom; j += bmDesc.bmHeight)
3228         BitBlt(hDC, i, j, bmDesc.bmWidth, bmDesc.bmHeight, htempDC, 0, 0, SRCCOPY);
3229   
3230   SelectObject(htempDC, oldBitmap);
3231   DeleteDC(htempDC);
3232   
3233   if (GetBackgroundPalette() == NULL)
3234   {
3235      DeleteObject(hPAL);
3236      hPAL = NULL;
3237   }
3238
3239   ReleaseDC(hWnd, hDC);
3240}
3241
3242static LPCSTR GetCloneParentName(int nItem)
3243{
3244   int nParentIndex = -1;
3245
3246   if (DriverIsClone(nItem) == TRUE)
3247   {
3248      nParentIndex = GetParentIndex(drivers[nItem]);
3249      if( nParentIndex >= 0)
3250         return ModifyThe(drivers[nParentIndex]->description);
3251   }
3252   return "";
3253}
3254
3255static BOOL PickerHitTest(HWND hWnd)
3256{
3257   RECT         rect;
3258   POINTS         p;
3259   DWORD         res = GetMessagePos();
3260   LVHITTESTINFO   htInfo;
3261
3262    ZeroMemory(&htInfo,sizeof(LVHITTESTINFO));
3263   p = MAKEPOINTS(res);
3264   GetWindowRect(hWnd, &rect);
3265   htInfo.pt.x = p.x - rect.left;
3266   htInfo.pt.y = p.y - rect.top;
3267   ListView_HitTest(hWnd, &htInfo);
3268
3269   return (! (htInfo.flags & LVHT_NOWHERE));
3270}
3271
3272static BOOL TreeViewNotify(LPNMHDR nm)
3273{
3274   switch (nm->code)
3275   {
3276   case TVN_SELCHANGED :
3277   {
3278      HTREEITEM hti = TreeView_GetSelection(hTreeView);
3279      TVITEM     tvi;
3280
3281      tvi.mask  = TVIF_PARAM | TVIF_HANDLE;
3282      tvi.hItem = hti;
3283     
3284      if (TreeView_GetItem(hTreeView, &tvi))
3285      {
3286         SetCurrentFolder((LPTREEFOLDER)tvi.lParam);
3287         if (bListReady)
3288         {
3289            ResetListView();
3290            UpdateScreenShot();
3291         }
3292      }
3293      return TRUE;
3294   }
3295   case TVN_BEGINLABELEDIT :
3296   {
3297      TV_DISPINFO *ptvdi = (TV_DISPINFO *)nm;
3298      LPTREEFOLDER folder = (LPTREEFOLDER)ptvdi->item.lParam;
3299
3300      if (folder->m_dwFlags & F_CUSTOM)
3301      {
3302         // user can edit custom folder names
3303         g_in_treeview_edit = TRUE;
3304         return FALSE;
3305      }
3306      // user can't edit built in folder names
3307      return TRUE;
3308   }
3309   case TVN_ENDLABELEDIT :
3310   {
3311      TV_DISPINFO *ptvdi = (TV_DISPINFO *)nm;
3312      LPTREEFOLDER folder = (LPTREEFOLDER)ptvdi->item.lParam;
3313      char* szText;
3314      BOOL result;
3315
3316      g_in_treeview_edit = FALSE;
3317
3318      if (ptvdi->item.pszText == NULL || _tcslen(ptvdi->item.pszText) == 0)
3319         return FALSE;
3320         
3321      szText = utf8_from_tstring(ptvdi->item.pszText);
3322      if( !szText )
3323         return FALSE;
3324
3325      result = TryRenameCustomFolder(folder,szText);
3326     
3327      free(szText);
3328     
3329      return result;
3330   }
3331   }
3332   return FALSE;
3333}
3334
3335
3336
3337static void GamePicker_OnHeaderContextMenu(POINT pt, int nColumn)
3338{
3339   // Right button was clicked on header
3340   HMENU hMenuLoad;
3341   HMENU hMenu;
3342
3343   hMenuLoad = LoadMenu(hInst, MAKEINTRESOURCE(IDR_CONTEXT_HEADER));
3344   hMenu = GetSubMenu(hMenuLoad, 0);
3345   lastColumnClick = nColumn;
3346   TrackPopupMenu(hMenu,TPM_LEFTALIGN | TPM_RIGHTBUTTON,pt.x,pt.y,0,hMain,NULL);
3347
3348   DestroyMenu(hMenuLoad);
3349}
3350
3351
3352
3353char* ConvertAmpersandString(const char *s)
3354{
3355   /* takes a string and changes any ampersands to double ampersands,
3356      for setting text of window controls that don't allow us to disable
3357      the ampersand underlining.
3358    */
3359   /* returns a static buffer--use before calling again */
3360
3361   static char buf[200];
3362   char *ptr;
3363
3364   ptr = buf;
3365   while (*s)
3366   {
3367      if (*s == '&')
3368         *ptr++ = *s;
3369      *ptr++ = *s++;
3370   }
3371   *ptr = 0;
3372
3373   return buf;
3374}
3375
3376static int GUI_seq_pressed(const input_seq *seq)
3377{
3378   int codenum;
3379   int res = 1;
3380   int invert = 0;
3381   int count = 0;
3382
3383   for (codenum = 0; codenum < ARRAY_LENGTH(seq->code); codenum++)
3384   {
3385      input_code code = seq->code[codenum];
3386
3387      switch (code)
3388      {
3389         case SEQCODE_OR :
3390            if (res && count)
3391               return 1;
3392            res = 1;
3393            count = 0;
3394            break;
3395         case SEQCODE_NOT :
3396            invert = !invert;
3397            break;
3398         default:
3399            if (res)
3400            {
3401               int pressed = keyboard_state[code];
3402               if ((pressed != 0) == invert)
3403                  res = 0;
3404            }
3405            invert = 0;
3406            ++count;
3407      }
3408   }
3409   return res && count;
3410}
3411
3412static void check_for_GUI_action(void)
3413{
3414   int i;
3415
3416   for (i = 0; i < NUM_GUI_SEQUENCES; i++)
3417   {
3418      input_seq *is = &(GUISequenceControl[i].is);
3419
3420      if (GUI_seq_pressed(is))
3421      {
3422         dprintf("seq =%s pressed\n", GUISequenceControl[i].name);
3423         switch (GUISequenceControl[i].func_id)
3424         {
3425         case ID_GAME_AUDIT:
3426         case ID_GAME_PROPERTIES:
3427         case ID_CONTEXT_FILTERS:
3428         case ID_UI_START:
3429            KeyboardStateClear(); /* beacuse whe won't receive KeyUp mesage when we loose focus */
3430            break;
3431         default:
3432            break;
3433         }
3434         SendMessage(hMain, WM_COMMAND, GUISequenceControl[i].func_id, 0);
3435      }
3436   }
3437}
3438
3439static void KeyboardStateClear(void)
3440{
3441   memset(keyboard_state, 0, sizeof(keyboard_state));
3442   dprintf("keyboard gui state cleared.\n");
3443}
3444
3445
3446static void KeyboardKeyDown(int syskey, int vk_code, int special)
3447{
3448   int i, found = 0;
3449   input_code icode = 0;
3450   int special_code = (special >> 24) & 1;
3451   int scancode = (special>>16) & 0xff;
3452
3453   if ((vk_code==VK_MENU) || (vk_code==VK_CONTROL) || (vk_code==VK_SHIFT))
3454   {
3455      found = 1;
3456
3457      /* a hack for right shift - it's better to use Direct X for keyboard input it seems......*/
3458      if (vk_code==VK_SHIFT)
3459         if (scancode>0x30) /* on my keyboard left shift scancode is 0x2a, right shift is 0x36 */
3460            special_code = 1;
3461
3462      if (special_code) /* right hand keys */
3463      {
3464         switch(vk_code)
3465         {
3466         case VK_MENU:
3467            icode = KEYCODE_RALT;
3468            break;
3469         case VK_CONTROL:
3470            icode = KEYCODE_RCONTROL;
3471            break;
3472         case VK_SHIFT:
3473            icode = KEYCODE_RSHIFT;
3474            break;
3475         }
3476      }
3477      else /* left hand keys */
3478      {
3479         switch(vk_code)
3480         {
3481         case VK_MENU:
3482            icode = KEYCODE_LALT;
3483            break;
3484         case VK_CONTROL:
3485            icode = KEYCODE_LCONTROL;
3486            break;
3487         case VK_SHIFT:
3488            icode = KEYCODE_LSHIFT;
3489            break;
3490         }
3491      }
3492   }
3493   else
3494   {
3495      for (i = 0; i < ARRAY_LENGTH(win_key_trans_table); i++)
3496      {
3497         if ( vk_code == win_key_trans_table[i][VIRTUAL_KEY])
3498         {
3499            icode = win_key_trans_table[i][MAME_KEY];
3500            found = 1;
3501            break;
3502         }
3503      }
3504   }
3505   if (!found)
3506   {
3507      dprintf("VK_code pressed not found =  %i\n",vk_code);
3508      //MessageBox(NULL,"keydown message arrived not processed","TitleBox",MB_OK);
3509      return;
3510   }
3511   dprintf("VK_code pressed found =  %i, sys=%i, mame_keycode=%i special=%08x\n", vk_code, syskey, icode, special);
3512   keyboard_state[icode] = 1;
3513   check_for_GUI_action();
3514}
3515
3516static void KeyboardKeyUp(int syskey, int vk_code, int special)
3517{
3518   int i, found = 0;
3519   input_code icode = 0;
3520   int special_code = (special >> 24) & 1;
3521   int scancode = (special>>16) & 0xff;
3522
3523   if ((vk_code==VK_MENU) || (vk_code==VK_CONTROL) || (vk_code==VK_SHIFT))
3524   {
3525      found = 1;
3526
3527      /* a hack for right shift - it's better to use Direct X for keyboard input it seems......*/
3528      if (vk_code==VK_SHIFT)
3529         if (scancode>0x30) /* on my keyboard left shift scancode is 0x2a, right shift is 0x36 */
3530            special_code = 1;
3531
3532      if (special_code) /* right hand keys */
3533      {
3534         switch(vk_code)
3535         {
3536         case VK_MENU:
3537            icode = KEYCODE_RALT;
3538            break;
3539         case VK_CONTROL:
3540            icode = KEYCODE_RCONTROL;
3541            break;
3542         case VK_SHIFT:
3543            icode = KEYCODE_RSHIFT;
3544            break;
3545         }
3546      }
3547      else /* left hand keys */
3548      {
3549         switch(vk_code)
3550         {
3551         case VK_MENU:
3552            icode = KEYCODE_LALT;
3553            break;
3554         case VK_CONTROL:
3555            icode = KEYCODE_LCONTROL;
3556            break;
3557         case VK_SHIFT:
3558            icode = KEYCODE_LSHIFT;
3559            break;
3560         }
3561      }
3562   }
3563   else
3564   {
3565      for (i = 0; i < ARRAY_LENGTH(win_key_trans_table); i++)
3566      {
3567         if (vk_code == win_key_trans_table[i][VIRTUAL_KEY])
3568         {
3569            icode = win_key_trans_table[i][MAME_KEY];
3570            found = 1;
3571            break;
3572         }
3573      }
3574   }
3575   if (!found)
3576   {
3577      dprintf("VK_code released not found =  %i",vk_code);
3578      //MessageBox(NULL,"keyup message arrived not processed","TitleBox",MB_OK);
3579      return;
3580   }
3581   keyboard_state[icode] = 0;
3582   dprintf("VK_code released found=  %i, sys=%i, mame_keycode=%i special=%08x\n", vk_code, syskey, icode, special );
3583   check_for_GUI_action();
3584}
3585
3586static void PollGUIJoystick()
3587{
3588   // For the exec timer, will keep track of how long the button has been pressed 
3589   static int exec_counter = 0;
3590   const char* exec_command;
3591   TCHAR* t_exec_command;
3592 
3593   if (in_emulation)
3594      return;
3595
3596   if (g_pJoyGUI == NULL)
3597      return;
3598
3599   g_pJoyGUI->poll_joysticks();
3600
3601
3602   // User pressed UP
3603   if (g_pJoyGUI->is_joy_pressed(JOYCODE(GetUIJoyUp(0), GetUIJoyUp(1), GetUIJoyUp(2),GetUIJoyUp(3))))
3604   {
3605      SendMessage(hMain, WM_COMMAND, ID_UI_UP, 0);
3606   }
3607   
3608   // User pressed DOWN
3609   if (g_pJoyGUI->is_joy_pressed(JOYCODE(GetUIJoyDown(0), GetUIJoyDown(1), GetUIJoyDown(2),GetUIJoyDown(3))))
3610   {
3611      SendMessage(hMain, WM_COMMAND, ID_UI_DOWN, 0);
3612   }
3613   
3614   // User pressed LEFT
3615   if (g_pJoyGUI->is_joy_pressed(JOYCODE(GetUIJoyLeft(0), GetUIJoyLeft(1), GetUIJoyLeft(2),GetUIJoyLeft(3))))
3616   {
3617      SendMessage(hMain, WM_COMMAND, ID_UI_LEFT, 0);
3618   }
3619
3620   // User pressed RIGHT
3621   if (g_pJoyGUI->is_joy_pressed(JOYCODE(GetUIJoyRight(0), GetUIJoyRight(1), GetUIJoyRight(2),GetUIJoyRight(3))))
3622   {
3623      SendMessage(hMain, WM_COMMAND, ID_UI_RIGHT, 0);
3624   }
3625
3626   // User pressed START GAME
3627   if (g_pJoyGUI->is_joy_pressed(JOYCODE(GetUIJoyStart(0), GetUIJoyStart(1), GetUIJoyStart(2),GetUIJoyStart(3))))
3628   {
3629      SendMessage(hMain, WM_COMMAND, ID_UI_START, 0);
3630   }
3631
3632   // User pressed PAGE UP
3633   if (g_pJoyGUI->is_joy_pressed(JOYCODE(GetUIJoyPageUp(0), GetUIJoyPageUp(1), GetUIJoyPageUp(2),GetUIJoyPageUp(3))))
3634   {
3635      SendMessage(hMain, WM_COMMAND, ID_UI_PGUP, 0);
3636   }
3637
3638   // User pressed PAGE DOWN
3639   if (g_pJoyGUI->is_joy_pressed(JOYCODE(GetUIJoyPageDown(0), GetUIJoyPageDown(1), GetUIJoyPageDown(2),GetUIJoyPageDown(3))))
3640   {
3641      SendMessage(hMain, WM_COMMAND, ID_UI_PGDOWN, 0);
3642   }
3643
3644   // User pressed HOME
3645   if (g_pJoyGUI->is_joy_pressed(JOYCODE(GetUIJoyHome(0), GetUIJoyHome(1), GetUIJoyHome(2),GetUIJoyHome(3))))
3646   {
3647      SendMessage(hMain, WM_COMMAND, ID_UI_HOME, 0);
3648   }
3649
3650   // User pressed END
3651   if (g_pJoyGUI->is_joy_pressed(JOYCODE(GetUIJoyEnd(0), GetUIJoyEnd(1), GetUIJoyEnd(2),GetUIJoyEnd(3))))
3652   {
3653      SendMessage(hMain, WM_COMMAND, ID_UI_END, 0);
3654   }
3655
3656   // User pressed CHANGE SCREENSHOT
3657   if (g_pJoyGUI->is_joy_pressed(JOYCODE(GetUIJoySSChange(0), GetUIJoySSChange(1), GetUIJoySSChange(2),GetUIJoySSChange(3))))
3658   {
3659      SendMessage(hMain, WM_COMMAND, IDC_SSFRAME, 0);
3660   }
3661   
3662   // User pressed SCROLL HISTORY UP
3663   if (g_pJoyGUI->is_joy_pressed(JOYCODE(GetUIJoyHistoryUp(0), GetUIJoyHistoryUp(1), GetUIJoyHistoryUp(2),GetUIJoyHistoryUp(3))))
3664   {
3665      SendMessage(hMain, WM_COMMAND, ID_UI_HISTORY_UP, 0);
3666   }
3667   
3668   // User pressed SCROLL HISTORY DOWN
3669   if (g_pJoyGUI->is_joy_pressed(JOYCODE(GetUIJoyHistoryDown(0), GetUIJoyHistoryDown(1), GetUIJoyHistoryDown(2),GetUIJoyHistoryDown(3))))
3670   {
3671      SendMessage(hMain, WM_COMMAND, ID_UI_HISTORY_DOWN, 0);
3672   }
3673 
3674  // User pressed EXECUTE COMMANDLINE
3675   if (g_pJoyGUI->is_joy_pressed(JOYCODE(GetUIJoyExec(0), GetUIJoyExec(1), GetUIJoyExec(2),GetUIJoyExec(3))))
3676   {
3677      if (++exec_counter >= GetExecWait()) // Button has been pressed > exec timeout
3678      {
3679         PROCESS_INFORMATION pi;
3680         STARTUPINFO si;
3681         
3682         // Reset counter
3683         exec_counter = 0;
3684
3685         ZeroMemory( &si, sizeof(si) );
3686         ZeroMemory( &pi, sizeof(pi) );
3687         si.dwFlags = STARTF_FORCEONFEEDBACK;
3688         si.cb = sizeof(si);
3689         
3690         exec_command = GetExecCommand();
3691         t_exec_command = tstring_from_utf8(exec_command);
3692         if( !t_exec_command )
3693            return;
3694         CreateProcess(NULL, t_exec_command, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
3695         
3696         free(t_exec_command);
3697
3698         // We will not wait for the process to finish cause it might be a background task
3699         // The process won't get closed when MAME32 closes either.
3700
3701         // But close the handles cause we won't need them anymore. Will not close process.
3702         CloseHandle(pi.hProcess);
3703         CloseHandle(pi.hThread);
3704      }
3705   }
3706   else
3707   {
3708      // Button has been released within the timeout period, reset the counter
3709      exec_counter = 0;
3710   }
3711}
3712
3713static void PressKey(HWND hwnd, UINT vk)
3714{
3715   SendMessage(hwnd, WM_KEYDOWN, vk, 0);
3716   SendMessage(hwnd, WM_KEYUP,   vk, 0xc0000000);
3717}
3718
3719static void SetView(int menu_id)
3720{
3721   BOOL force_reset = FALSE;
3722   int i;
3723
3724   // first uncheck previous menu item, check new one
3725   CheckMenuRadioItem(GetMenu(hMain), ID_VIEW_LARGE_ICON, ID_VIEW_GROUPED, menu_id, MF_CHECKED);
3726   ToolBar_CheckButton(hToolBar, menu_id, MF_CHECKED);
3727
3728   if (Picker_GetViewID(hwndList) == VIEW_GROUPED || menu_id == ID_VIEW_GROUPED)
3729   {
3730      // this changes the sort order, so redo everything
3731      force_reset = TRUE;
3732   }
3733
3734   for (i = 0; i < sizeof(s_nPickers) / sizeof(s_nPickers[0]); i++)
3735      Picker_SetViewID(GetDlgItem(hMain, s_nPickers[i]), menu_id - ID_VIEW_LARGE_ICON);
3736
3737   if (force_reset)
3738   {
3739      for (i = 0; i < sizeof(s_nPickers) / sizeof(s_nPickers[0]); i++)
3740         Picker_Sort(GetDlgItem(hMain, s_nPickers[i]));
3741   }
3742}
3743
3744static void ResetListView()
3745{
3746   int    i;
3747   int    current_game;
3748   LV_ITEM lvi;
3749   BOOL   no_selection = FALSE;
3750   LPTREEFOLDER lpFolder = GetCurrentFolder();
3751
3752   if (!lpFolder)
3753    {
3754      return;
3755    }
3756
3757   /* If the last folder was empty, no_selection is TRUE */
3758   if (have_selection == FALSE)
3759    {
3760      no_selection = TRUE;
3761    }
3762
3763   current_game = Picker_GetSelectedItem(hwndList);
3764
3765   SetWindowRedraw(hwndList,FALSE);
3766
3767   ListView_DeleteAllItems(hwndList);
3768
3769   // hint to have it allocate it all at once
3770   ListView_SetItemCount(hwndList,driver_list_get_count(drivers));
3771
3772   lvi.mask = LVIF_TEXT | LVIF_IMAGE | LVIF_PARAM;
3773   lvi.stateMask = 0;
3774
3775   i = -1;
3776
3777   do
3778   {
3779      /* Add the games that are in this folder */
3780      if ((i = FindGame(lpFolder, i + 1)) != -1)
3781      {
3782         if (GameFiltered(i, lpFolder->m_dwFlags))
3783            continue;
3784
3785         lvi.iItem    = i;
3786         lvi.iSubItem = 0;
3787         lvi.lParam    = i;
3788         lvi.pszText  = LPSTR_TEXTCALLBACK;
3789         lvi.iImage    = I_IMAGECALLBACK;
3790         ListView_InsertItem(hwndList, &lvi);
3791      }
3792   } while (i != -1);
3793
3794   Picker_Sort(hwndList);
3795
3796   if (bListReady)
3797   {
3798       /* If last folder was empty, select the first item in this folder */
3799       if (no_selection)
3800          Picker_SetSelectedPick(hwndList, 0);
3801      else
3802          Picker_SetSelectedItem(hwndList, current_game);
3803   }
3804
3805   /*RS Instead of the Arrange Call that was here previously on all Views
3806       We now need to set the ViewMode for SmallIcon again,
3807       for an explanation why, see SetView*/
3808   if (GetViewMode() == VIEW_SMALL_ICONS)
3809      SetView(ID_VIEW_SMALL_ICON);
3810
3811   SetWindowRedraw(hwndList, TRUE);
3812
3813   UpdateStatusBar();
3814
3815}
3816
3817static void UpdateGameList(BOOL bUpdateRomAudit, BOOL bUpdateSampleAudit)
3818{
3819   int i;
3820
3821   for (i = 0; i < driver_list_get_count(drivers); i++)
3822   {
3823      if (bUpdateRomAudit && DriverUsesRoms(i))
3824         SetRomAuditResults(i, UNKNOWN);
3825      if (bUpdateSampleAudit && DriverUsesSamples(i))
3826         SetSampleAuditResults(i, UNKNOWN);
3827   }
3828
3829   idle_work    = TRUE;
3830   bDoGameCheck = TRUE;
3831   game_index    = 0;
3832
3833   ReloadIcons();
3834
3835   // Let REFRESH also load new background if found
3836   LoadBackgroundBitmap();
3837   InvalidateRect(hMain,NULL,TRUE);
3838   Picker_ResetIdle(hwndList);
3839}
3840
3841UINT_PTR CALLBACK CFHookProc(
3842  HWND hdlg,      // handle to dialog box
3843  UINT uiMsg,     // message identifier
3844  WPARAM wParam,  // message parameter
3845  LPARAM lParam   // message parameter
3846)
3847{
3848   int iIndex, i;
3849   COLORREF cCombo, cList;
3850   switch (uiMsg)
3851   {
3852      case WM_INITDIALOG:
3853         SendDlgItemMessage(hdlg, cmb4, CB_ADDSTRING, 0, (LPARAM)TEXT("Custom"));
3854         iIndex = SendDlgItemMessage(hdlg, cmb4, CB_GETCOUNT, 0, 0);
3855         cList = GetListFontColor();
3856         SendDlgItemMessage(hdlg, cmb4, CB_SETITEMDATA,(WPARAM)iIndex-1,(LPARAM)cList );
3857         for( i = 0; i< iIndex; i++)
3858         {
3859            cCombo = SendDlgItemMessage(hdlg, cmb4, CB_GETITEMDATA,(WPARAM)i,0 );
3860            if( cList == cCombo)
3861            {
3862               SendDlgItemMessage(hdlg, cmb4, CB_SETCURSEL,(WPARAM)i,0 );
3863               break;
3864            }
3865         }
3866         break;
3867      case WM_COMMAND:
3868         if( LOWORD(wParam) == cmb4)
3869         {
3870            switch (HIWORD(wParam))
3871            {
3872               case CBN_SELCHANGE:  // The color ComboBox changed selection
3873                  iIndex = (int)SendDlgItemMessage(hdlg, cmb4,
3874                                         CB_GETCURSEL, 0, 0L);
3875                  if( iIndex == SendDlgItemMessage(hdlg, cmb4, CB_GETCOUNT, 0, 0)-1)
3876                  {
3877                     //Custom color selected
3878                      cList = GetListFontColor();
3879                      PickColor(&cList);
3880                     SendDlgItemMessage(hdlg, cmb4, CB_DELETESTRING, iIndex, 0);
3881                     SendDlgItemMessage(hdlg, cmb4, CB_ADDSTRING, 0, (LPARAM)TEXT("Custom"));
3882                     SendDlgItemMessage(hdlg, cmb4, CB_SETITEMDATA,(WPARAM)iIndex,(LPARAM)cList);
3883                     SendDlgItemMessage(hdlg, cmb4, CB_SETCURSEL,(WPARAM)iIndex,0 );
3884                     return TRUE;
3885                  }
3886            }
3887         }
3888         break;
3889   }
3890   return FALSE;
3891}
3892
3893static void PickFont(void)
3894{
3895   LOGFONT font;
3896   CHOOSEFONT cf;
3897   TCHAR szClass[128];
3898   HWND hWnd;
3899
3900   GetListFont(&font);
3901   font.lfQuality = DEFAULT_QUALITY;
3902
3903   cf.lStructSize = sizeof(CHOOSEFONT);
3904   cf.hwndOwner   = hMain;
3905   cf.lpLogFont   = &font;
3906   cf.lpfnHook = &CFHookProc;
3907   cf.rgbColors   = GetListFontColor();
3908   cf.Flags      = CF_SCREENFONTS | CF_INITTOLOGFONTSTRUCT | CF_EFFECTS | CF_ENABLEHOOK;
3909   if (!ChooseFont(&cf))
3910      return;
3911
3912   SetListFont(&font);
3913   if (hFont != NULL)
3914      DeleteObject(hFont);
3915   hFont = CreateFontIndirect(&font);
3916   if (hFont != NULL)
3917   {
3918      COLORREF textColor = cf.rgbColors;
3919
3920      if (textColor == RGB(255,255,255))
3921      {
3922         textColor = RGB(240, 240, 240);
3923      }
3924
3925      SetAllWindowsFont(hMain, &main_resize, hFont, TRUE);
3926
3927      hWnd = GetWindow(hMain, GW_CHILD);
3928      while(hWnd)
3929      {
3930         if (GetClassName(hWnd, szClass, sizeof(szClass) / sizeof(szClass[0])))
3931         {
3932            if (!_tcscmp(szClass, TEXT("SysListView32")))
3933            {
3934               ListView_SetTextColor(hWnd, textColor);
3935            }
3936            else if (!_tcscmp(szClass, TEXT("SysTreeView32")))
3937            {
3938               TreeView_SetTextColor(hTreeView, textColor);
3939            }
3940         }
3941         hWnd = GetWindow(hWnd, GW_HWNDNEXT);
3942      }
3943      SetListFontColor(cf.rgbColors);
3944      ResetListView();
3945   }
3946}
3947
3948static void PickColor(COLORREF *cDefault)
3949{
3950    CHOOSECOLOR cc;
3951    COLORREF choice_colors[16];
3952    int i;
3953   
3954    for (i=0;i<16;i++)
3955       choice_colors[i] = GetCustomColor(i);
3956 
3957    cc.lStructSize = sizeof(CHOOSECOLOR);
3958    cc.hwndOwner   = hMain;
3959    cc.rgbResult   = *cDefault;
3960    cc.lpCustColors = choice_colors;
3961    cc.Flags       = CC_ANYCOLOR | CC_RGBINIT | CC_SOLIDCOLOR;
3962    if (!ChooseColor(&cc))
3963       return;
3964    for (i=0;i<16;i++)
3965       SetCustomColor(i,choice_colors[i]);
3966    *cDefault = cc.rgbResult;
3967}
3968 
3969static void PickCloneColor(void)
3970{
3971    COLORREF cClonecolor;
3972    cClonecolor = GetListCloneColor();
3973    PickColor( &cClonecolor);
3974    SetListCloneColor(cClonecolor);
3975    InvalidateRect(hwndList,NULL,FALSE);
3976}
3977 
3978static BOOL MameCommand(HWND hwnd,int id, HWND hwndCtl, UINT codeNotify)
3979{
3980   int i;
3981   LPTREEFOLDER folder;
3982   char* t_szFile;
3983   
3984   switch (id)
3985   {
3986   case ID_FILE_PLAY:
3987      MamePlayGame();
3988      return TRUE;
3989
3990   case ID_FILE_PLAY_RECORD:
3991      MamePlayRecordGame();
3992      return TRUE;
3993
3994   case ID_FILE_PLAY_BACK:
3995      MamePlayBackGame();
3996      return TRUE;
3997
3998   case ID_FILE_PLAY_RECORD_WAVE:
3999      MamePlayRecordWave();
4000      return TRUE;
4001
4002   case ID_FILE_PLAY_RECORD_MNG:
4003      MamePlayRecordMNG();
4004      return TRUE;
4005
4006   case ID_FILE_LOADSTATE :
4007      MameLoadState();
4008      return TRUE;
4009
4010   case ID_FILE_AUDIT:
4011      AuditDialog(hMain);
4012      ResetWhichGamesInFolders();
4013      ResetListView();
4014      SetFocus(hwndList);
4015      return TRUE;
4016
4017   case ID_FILE_EXIT:
4018      PostMessage(hMain, WM_CLOSE, 0, 0);
4019      return TRUE;
4020
4021   case ID_VIEW_LARGE_ICON:
4022      SetView(ID_VIEW_LARGE_ICON);
4023      return TRUE;
4024
4025   case ID_VIEW_SMALL_ICON:
4026      SetView(ID_VIEW_SMALL_ICON);
4027      ResetListView();
4028      return TRUE;
4029
4030   case ID_VIEW_LIST_MENU:
4031      SetView(ID_VIEW_LIST_MENU);
4032      return TRUE;
4033
4034   case ID_VIEW_DETAIL:
4035      SetView(ID_VIEW_DETAIL);
4036      return TRUE;
4037
4038   case ID_VIEW_GROUPED:
4039      SetView(ID_VIEW_GROUPED);
4040      return TRUE;
4041
4042   /* Arrange Icons submenu */
4043   case ID_VIEW_BYGAME:
4044      SetSortReverse(FALSE);
4045      SetSortColumn(COLUMN_GAMES);
4046      Picker_Sort(hwndList);
4047      break;
4048
4049   case ID_VIEW_BYDIRECTORY:
4050      SetSortReverse(FALSE);
4051      SetSortColumn(COLUMN_DIRECTORY);
4052      Picker_Sort(hwndList);
4053      break;
4054
4055   case ID_VIEW_BYMANUFACTURER:
4056      SetSortReverse(FALSE);
4057      SetSortColumn(COLUMN_MANUFACTURER);
4058      Picker_Sort(hwndList);
4059      break;
4060
4061   case ID_VIEW_BYTIMESPLAYED:
4062      SetSortReverse(FALSE);
4063      SetSortColumn(COLUMN_PLAYED);
4064      Picker_Sort(hwndList);
4065      break;
4066
4067   case ID_VIEW_BYTYPE:
4068      SetSortReverse(FALSE);
4069      SetSortColumn(COLUMN_TYPE);
4070      Picker_Sort(hwndList);
4071      break;
4072
4073   case ID_VIEW_BYYEAR:
4074      SetSortReverse(FALSE);
4075      SetSortColumn(COLUMN_YEAR);
4076      Picker_Sort(hwndList);
4077      break;
4078
4079   case ID_VIEW_FOLDERS:
4080      bShowTree = !bShowTree;
4081      SetShowFolderList(bShowTree);
4082      CheckMenuItem(GetMenu(hMain), ID_VIEW_FOLDERS, (bShowTree) ? MF_CHECKED : MF_UNCHECKED);
4083      ToolBar_CheckButton(hToolBar, ID_VIEW_FOLDERS, (bShowTree) ? MF_CHECKED : MF_UNCHECKED);
4084      UpdateScreenShot();
4085      break;
4086
4087   case ID_VIEW_TOOLBARS:
4088      bShowToolBar = !bShowToolBar;
4089      SetShowToolBar(bShowToolBar);
4090      CheckMenuItem(GetMenu(hMain), ID_VIEW_TOOLBARS, (bShowToolBar) ? MF_CHECKED : MF_UNCHECKED);
4091      ToolBar_CheckButton(hToolBar, ID_VIEW_TOOLBARS, (bShowToolBar) ? MF_CHECKED : MF_UNCHECKED);
4092      ShowWindow(hToolBar, (bShowToolBar) ? SW_SHOW : SW_HIDE);
4093      ResizePickerControls(hMain);
4094      UpdateScreenShot();
4095      break;
4096
4097   case ID_VIEW_STATUS:
4098      bShowStatusBar = !bShowStatusBar;
4099      SetShowStatusBar(bShowStatusBar);
4100      CheckMenuItem(GetMenu(hMain), ID_VIEW_STATUS, (bShowStatusBar) ? MF_CHECKED : MF_UNCHECKED);
4101      ToolBar_CheckButton(hToolBar, ID_VIEW_STATUS, (bShowStatusBar) ? MF_CHECKED : MF_UNCHECKED);
4102      ShowWindow(hStatusBar, (bShowStatusBar) ? SW_SHOW : SW_HIDE);
4103      ResizePickerControls(hMain);
4104      UpdateScreenShot();
4105      break;
4106
4107   case ID_VIEW_PAGETAB:
4108      bShowTabCtrl = !bShowTabCtrl;
4109      SetShowTabCtrl(bShowTabCtrl);
4110      ShowWindow(hTabCtrl, (bShowTabCtrl) ? SW_SHOW : SW_HIDE);
4111      ResizePickerControls(hMain);
4112      UpdateScreenShot();
4113      InvalidateRect(hMain,NULL,TRUE);
4114      break;
4115
4116      /*
4117        Switches to fullscreen mode. No check mark handeling
4118        for this item cause in fullscreen mode the menu won't
4119        be visible anyways.
4120      */   
4121   case ID_VIEW_FULLSCREEN:
4122      SwitchFullScreenMode();
4123      break;
4124
4125   case ID_TOOLBAR_EDIT:
4126      {
4127         char buf[256];
4128
4129         Edit_GetText(hwndCtl, buf, sizeof(buf));
4130         switch (codeNotify)
4131         {
4132         case EN_CHANGE:
4133            //put search routine here first, add a 200ms timer later.
4134            if ((!_stricmp(buf, SEARCH_PROMPT) && !_stricmp(g_SearchText, "")) ||
4135                (!_stricmp(g_SearchText, SEARCH_PROMPT) && !_stricmp(buf, "")))
4136            {
4137               strcpy(g_SearchText, buf);
4138            }
4139            else
4140            {
4141               strcpy(g_SearchText, buf);
4142               ResetListView();
4143            }
4144            break;
4145         case EN_SETFOCUS:
4146            if (!_stricmp(buf, SEARCH_PROMPT))
4147               SetWindowText(hwndCtl, "");
4148            break;
4149         case EN_KILLFOCUS:
4150            if (strlen(buf) == 0)
4151               SetWindowText(hwndCtl, SEARCH_PROMPT);
4152            break;
4153         }
4154      }
4155      break;
4156
4157   case ID_GAME_AUDIT:
4158      InitGameAudit(0);
4159      if (!oldControl)
4160      {
4161         InitPropertyPageToPage(hInst, hwnd, GetSelectedPickItemIcon(), OPTIONS_GAME, -1, Picker_GetSelectedItem(hwndList), AUDIT_PAGE);
4162      }
4163      /* Just in case the toggle MMX on/off */
4164      UpdateStatusBar();
4165      break;
4166
4167   /* ListView Context Menu */
4168   case ID_CONTEXT_ADD_CUSTOM:
4169   {
4170       int  nResult;
4171
4172      nResult = DialogBoxParam(GetModuleHandle(NULL),MAKEINTRESOURCE(IDD_CUSTOM_FILE),
4173                         hMain,AddCustomFileDialogProc,Picker_GetSelectedItem(hwndList));
4174      SetFocus(hwndList);
4175      break;
4176   }
4177
4178   case ID_CONTEXT_REMOVE_CUSTOM:
4179   {
4180       RemoveCurrentGameCustomFolder();
4181      break;
4182   }
4183
4184   /* Tree Context Menu */
4185   case ID_CONTEXT_FILTERS:
4186      if (DialogBox(GetModuleHandle(NULL),
4187         MAKEINTRESOURCE(IDD_FILTERS), hMain, FilterDialogProc) == TRUE)
4188         ResetListView();
4189      SetFocus(hwndList);
4190      return TRUE;
4191
4192      // ScreenShot Context Menu
4193      // select current tab
4194   case ID_VIEW_TAB_SCREENSHOT :
4195   case ID_VIEW_TAB_FLYER :
4196   case ID_VIEW_TAB_CABINET :
4197   case ID_VIEW_TAB_MARQUEE :
4198   case ID_VIEW_TAB_TITLE :
4199   case ID_VIEW_TAB_CONTROL_PANEL :
4200   case ID_VIEW_TAB_PCB :
4201   case ID_VIEW_TAB_HISTORY:
4202      if (id == ID_VIEW_TAB_HISTORY && GetShowTab(TAB_HISTORY) == FALSE)
4203         break;
4204
4205      TabView_SetCurrentTab(hTabCtrl, id - ID_VIEW_TAB_SCREENSHOT);
4206      UpdateScreenShot();
4207      TabView_UpdateSelection(hTabCtrl);
4208      break;
4209
4210      // toggle tab's existence
4211   case ID_TOGGLE_TAB_SCREENSHOT :
4212   case ID_TOGGLE_TAB_FLYER :
4213   case ID_TOGGLE_TAB_CABINET :
4214   case ID_TOGGLE_TAB_MARQUEE :
4215   case ID_TOGGLE_TAB_TITLE :
4216   case ID_TOGGLE_TAB_CONTROL_PANEL :
4217   case ID_TOGGLE_TAB_PCB :
4218   case ID_TOGGLE_TAB_HISTORY :
4219   {
4220      int toggle_flag = id - ID_TOGGLE_TAB_SCREENSHOT;
4221
4222      if (AllowedToSetShowTab(toggle_flag,!GetShowTab(toggle_flag)) == FALSE)
4223      {
4224         // attempt to hide the last tab
4225         // should show error dialog? hide picture area? or ignore?
4226         break;
4227      }
4228
4229      SetShowTab(toggle_flag,!GetShowTab(toggle_flag));
4230
4231      TabView_Reset(hTabCtrl);
4232
4233      if (TabView_GetCurrentTab(hTabCtrl) == toggle_flag && GetShowTab(toggle_flag) == FALSE)
4234      {
4235         // we're deleting the tab we're on, so go to the next one
4236         TabView_CalculateNextTab(hTabCtrl);
4237      }
4238
4239
4240      // Resize the controls in case we toggled to another history
4241      // mode (and the history control needs resizing).
4242
4243      ResizePickerControls(hMain);
4244      UpdateScreenShot();
4245   
4246      TabView_UpdateSelection(hTabCtrl);
4247
4248      break;
4249   }
4250
4251   /* Header Context Menu */
4252   case ID_SORT_ASCENDING:
4253      SetSortReverse(FALSE);
4254      SetSortColumn(Picker_GetRealColumnFromViewColumn(hwndList, lastColumnClick));
4255      Picker_Sort(hwndList);
4256      break;
4257
4258   case ID_SORT_DESCENDING:
4259      SetSortReverse(TRUE);
4260      SetSortColumn(Picker_GetRealColumnFromViewColumn(hwndList, lastColumnClick));
4261      Picker_Sort(hwndList);
4262      break;
4263
4264   case ID_CUSTOMIZE_FIELDS:
4265      if (DialogBox(GetModuleHandle(NULL),
4266         MAKEINTRESOURCE(IDD_COLUMNS), hMain, ColumnDialogProc) == TRUE)
4267         ResetColumnDisplay(FALSE);
4268      SetFocus(hwndList);
4269      return TRUE;
4270
4271   /* View Menu */
4272   case ID_VIEW_LINEUPICONS:
4273      if( codeNotify == FALSE)
4274         ResetListView();
4275      else
4276      {
4277         /*it was sent after a refresh (F5) was done, we only reset the View if "available" is the selected folder
4278           as it doesn't affect the others*/
4279         folder = GetSelectedFolder();
4280         if( folder )
4281         {
4282            if (folder->m_nFolderId == FOLDER_AVAILABLE )
4283               ResetListView();
4284
4285         }
4286      }
4287      break;
4288
4289   case ID_GAME_PROPERTIES:
4290      if (!oldControl)
4291      {
4292         folder = GetFolderByName(FOLDER_SOURCE, GetDriverFilename(Picker_GetSelectedItem(hwndList)) );
4293         InitPropertyPage(hInst, hwnd, GetSelectedPickItemIcon(), OPTIONS_GAME, folder->m_nFolderId, Picker_GetSelectedItem(hwndList));
4294#ifdef MESS
4295         {
4296            extern BOOL g_bModifiedSoftwarePaths;
4297            if (g_bModifiedSoftwarePaths) {
4298               g_bModifiedSoftwarePaths = FALSE;
4299               MessUpdateSoftwareList();
4300            }
4301         }
4302#endif
4303      }
4304      /* Just in case the toggle MMX on/off */
4305      UpdateStatusBar();
4306      break;
4307
4308   case ID_FOLDER_PROPERTIES:
4309      if (!oldControl)
4310      {
4311         folder = GetSelectedFolder();
4312         InitPropertyPage(hInst, hwnd, GetSelectedFolderIcon(), (folder->m_nFolderId == FOLDER_VECTOR) ? OPTIONS_VECTOR : OPTIONS_SOURCE, folder->m_nFolderId, Picker_GetSelectedItem(hwndList));
4313         //SaveFolderOptions(folder->m_nFolderId, Picker_GetSelectedItem(hwndList) );
4314      }
4315      /* Just in case the toggle MMX on/off */
4316      UpdateStatusBar();
4317      break;
4318
4319   case ID_FOLDER_SOURCEPROPERTIES:
4320      if (!oldControl)
4321      {
4322         folder = GetFolderByName(FOLDER_SOURCE, GetDriverFilename(Picker_GetSelectedItem(hwndList)) );
4323         InitPropertyPage(hInst, hwnd, GetSelectedFolderIcon(), (folder->m_nFolderId == FOLDER_VECTOR) ? OPTIONS_VECTOR : OPTIONS_SOURCE , folder->m_nFolderId, Picker_GetSelectedItem(hwndList));
4324         //SaveFolderOptions(folder->m_nFolderId, Picker_GetSelectedItem(hwndList) );
4325      }
4326      /* Just in case the toggle MMX on/off */
4327      UpdateStatusBar();
4328      break;
4329
4330   case ID_FOLDER_VECTORPROPERTIES:
4331      if (!oldControl)
4332      {
4333         folder = GetFolderByID( FOLDER_VECTOR );
4334         InitPropertyPage(hInst, hwnd, GetSelectedFolderIcon(), OPTIONS_VECTOR, folder->m_nFolderId, Picker_GetSelectedItem(hwndList));
4335         //SaveFolderOptions(folder->m_nFolderId, Picker_GetSelectedItem(hwndList) );
4336      }
4337      /* Just in case the toggle MMX on/off */
4338      UpdateStatusBar();
4339      break;
4340
4341   case ID_FOLDER_AUDIT:
4342      FolderCheck();
4343      /* Just in case the toggle MMX on/off */
4344      UpdateStatusBar();
4345      break;
4346
4347   case ID_VIEW_PICTURE_AREA :
4348      ToggleScreenShot();
4349      break;
4350
4351   case ID_UPDATE_GAMELIST:
4352      UpdateGameList(TRUE, TRUE);
4353      break;
4354
4355   case ID_OPTIONS_FONT:
4356      PickFont();
4357      return TRUE;
4358
4359   case ID_OPTIONS_CLONE_COLOR:
4360      PickCloneColor();
4361      return TRUE;
4362
4363   case ID_OPTIONS_DEFAULTS:
4364      /* Check the return value to see if changes were applied */
4365      if (!oldControl)
4366      {
4367         InitDefaultPropertyPage(hInst, hwnd);
4368         SaveDefaultOptions();
4369      }
4370      SetFocus(hwndList);
4371      return TRUE;
4372
4373   case ID_OPTIONS_DIR:
4374      {
4375         int  nResult;
4376         BOOL bUpdateRoms;
4377         BOOL bUpdateSamples;
4378#ifdef MESS
4379         BOOL bUpdateSoftware;
4380#endif
4381
4382         nResult = DialogBox(GetModuleHandle(NULL),
4383                        MAKEINTRESOURCE(IDD_DIRECTORIES),
4384                        hMain,
4385                        DirectoriesDialogProc);
4386
4387         SaveDefaultOptions();
4388
4389         bUpdateRoms    = ((nResult & DIRDLG_ROMS)    == DIRDLG_ROMS)   ? TRUE : FALSE;
4390         bUpdateSamples = ((nResult & DIRDLG_SAMPLES) == DIRDLG_SAMPLES) ? TRUE : FALSE;
4391#ifdef MESS
4392         bUpdateSoftware = ((nResult & DIRDLG_SOFTWARE) == DIRDLG_SOFTWARE) ? TRUE : FALSE;
4393
4394         if (bUpdateSoftware)
4395            MessUpdateSoftwareList();
4396#endif /* MESS */
4397
4398         if (s_pWatcher)
4399         {
4400            if (bUpdateRoms)
4401               DirWatcher_Watch(s_pWatcher, 0, GetRomDirs(), TRUE);
4402            if (bUpdateSamples)
4403               DirWatcher_Watch(s_pWatcher, 1, GetSampleDirs(), TRUE);
4404         }
4405
4406         /* update game list */
4407         if (bUpdateRoms == TRUE || bUpdateSamples == TRUE)
4408            UpdateGameList(bUpdateRoms, bUpdateSamples);
4409
4410         SetFocus(hwndList);
4411      }
4412      return TRUE;
4413
4414   case ID_OPTIONS_RESET_DEFAULTS:
4415      if (DialogBox(GetModuleHandle(NULL),
4416                 MAKEINTRESOURCE(IDD_RESET), hMain, ResetDialogProc) == TRUE)
4417        {
4418         // these may have been changed
4419         SaveDefaultOptions();
4420         DestroyWindow(hwnd);
4421         PostQuitMessage(0);
4422      } else {
4423         ResetListView();
4424         SetFocus(hwndList);
4425      }
4426      return TRUE;
4427
4428   case ID_OPTIONS_INTERFACE:
4429      DialogBox(GetModuleHandle(NULL), MAKEINTRESOURCE(IDD_INTERFACE_OPTIONS),
4430              hMain, InterfaceDialogProc);
4431      SaveDefaultOptions();
4432
4433      KillTimer(hMain, SCREENSHOT_TIMER);
4434      if( GetCycleScreenshot() > 0)
4435      {
4436         SetTimer(hMain, SCREENSHOT_TIMER, GetCycleScreenshot()*1000, NULL ); // Scale to seconds
4437      }
4438
4439      return TRUE;
4440
4441   case ID_OPTIONS_BG:
4442      {
4443         OPENFILENAME OpenFileName;
4444         static TCHAR szFile[MAX_PATH] = TEXT("\0");
4445         TCHAR*       t_bgdir = tstring_from_utf8(GetBgDir());
4446         if( !t_bgdir )
4447            return FALSE;
4448
4449         OpenFileName.lStructSize       = sizeof(OPENFILENAME);
4450         OpenFileName.hwndOwner         = hMain;
4451         OpenFileName.hInstance         = 0;
4452         OpenFileName.lpstrFilter       = TEXT("Image Files (*.png, *.bmp)\0*.PNG;*.BMP\0");
4453         OpenFileName.lpstrCustomFilter = NULL;
4454         OpenFileName.nMaxCustFilter    = 0;
4455         OpenFileName.nFilterIndex      = 1;
4456         OpenFileName.lpstrFile         = szFile;
4457         OpenFileName.nMaxFile          = sizeof(szFile);
4458         OpenFileName.lpstrFileTitle    = NULL;
4459         OpenFileName.nMaxFileTitle     = 0;
4460         OpenFileName.lpstrInitialDir   = t_bgdir;
4461         OpenFileName.lpstrTitle        = TEXT("Select a Background Image");
4462         OpenFileName.nFileOffset       = 0;
4463         OpenFileName.nFileExtension    = 0;
4464         OpenFileName.lpstrDefExt       = NULL;
4465         OpenFileName.lCustData         = 0;                                                 
4466         OpenFileName.lpfnHook          = NULL;
4467         OpenFileName.lpTemplateName    = NULL;                                   
4468         OpenFileName.Flags             = OFN_NOCHANGEDIR | OFN_SHOWHELP | OFN_EXPLORER;
4469
4470         if (GetOpenFileName(&OpenFileName))
4471         {
4472            t_szFile = utf8_from_tstring(szFile);
4473            if( !t_szFile )
4474               return FALSE;
4475            ResetBackground(t_szFile);
4476            LoadBackgroundBitmap();
4477            InvalidateRect(hMain, NULL, TRUE);
4478            free(t_bgdir);
4479            free(t_szFile);
4480            return TRUE;
4481         }
4482         free(t_bgdir);
4483      }
4484      break;
4485
4486   case ID_OPTIONS_LANGUAGE:
4487      DialogBox(GetModuleHandle(NULL),
4488              MAKEINTRESOURCE(IDD_LANGUAGE),
4489              hMain,
4490              LanguageDialogProc);
4491      return TRUE;
4492
4493   case ID_HELP_ABOUT:
4494      DialogBox(GetModuleHandle(NULL), MAKEINTRESOURCE(IDD_ABOUT),
4495              hMain, AboutDialogProc);
4496      SetFocus(hwndList);
4497      return TRUE;
4498
4499   case IDOK :
4500      /* cmk -- might need to check more codes here, not sure */
4501      if (codeNotify != EN_CHANGE && codeNotify != EN_UPDATE)
4502      {
4503         /* enter key */
4504         if (g_in_treeview_edit)
4505         {
4506            TreeView_EndEditLabelNow(hTreeView, FALSE);
4507            return TRUE;
4508         }
4509         else
4510            if (have_selection)
4511               MamePlayGame();
4512      }
4513      break;
4514
4515   case IDCANCEL : /* esc key */
4516      if (g_in_treeview_edit)
4517         TreeView_EndEditLabelNow(hTreeView, TRUE);
4518      break;
4519
4520   case IDC_PLAY_GAME :
4521      if (have_selection)
4522         MamePlayGame();
4523      break;
4524
4525   case ID_UI_START:
4526      SetFocus(hwndList);
4527      MamePlayGame();
4528      break;
4529
4530   case ID_UI_UP:
4531      Picker_SetSelectedPick(hwndList, GetSelectedPick() - 1);
4532       break;
4533
4534   case ID_UI_DOWN:
4535      Picker_SetSelectedPick(hwndList, GetSelectedPick() + 1);
4536       break;
4537
4538   case ID_UI_PGUP:
4539      Picker_SetSelectedPick(hwndList, GetSelectedPick() - ListView_GetCountPerPage(hwndList));
4540       break;
4541
4542   case ID_UI_PGDOWN:
4543      if ( (GetSelectedPick() + ListView_GetCountPerPage(hwndList)) < ListView_GetItemCount(hwndList) )
4544         Picker_SetSelectedPick(hwndList,  GetSelectedPick() + ListView_GetCountPerPage(hwndList) );
4545      else
4546         Picker_SetSelectedPick(hwndList,  ListView_GetItemCount(hwndList)-1 );
4547       break;
4548
4549   case ID_UI_HOME:
4550      Picker_SetSelectedPick(hwndList, 0);
4551       break;
4552
4553   case ID_UI_END:
4554      Picker_SetSelectedPick(hwndList,  ListView_GetItemCount(hwndList)-1 );
4555      break;
4556   case ID_UI_LEFT:
4557      /* hmmmmm..... */
4558      SendMessage(hwndList,WM_HSCROLL, SB_LINELEFT, 0);
4559       break;
4560
4561   case ID_UI_RIGHT:
4562      /* hmmmmm..... */
4563      SendMessage(hwndList,WM_HSCROLL, SB_LINERIGHT, 0);
4564       break;
4565   case ID_UI_HISTORY_UP:
4566      /* hmmmmm..... */
4567      {
4568         HWND hHistory = GetDlgItem(hMain, IDC_HISTORY);
4569         SendMessage(hHistory, EM_SCROLL, SB_PAGEUP, 0);
4570      }
4571       break;
4572
4573   case ID_UI_HISTORY_DOWN:
4574      /* hmmmmm..... */
4575      {
4576         HWND hHistory = GetDlgItem(hMain, IDC_HISTORY);
4577         SendMessage(hHistory, EM_SCROLL, SB_PAGEDOWN, 0);
4578      }
4579       break;
4580
4581   case IDC_SSFRAME:
4582      TabView_CalculateNextTab(hTabCtrl);
4583      UpdateScreenShot();
4584      TabView_UpdateSelection(hTabCtrl);
4585      break;
4586
4587   case ID_CONTEXT_SELECT_RANDOM:
4588      SetRandomPickItem();
4589      break;
4590
4591   case ID_CONTEXT_RESET_PLAYTIME:
4592      ResetPlayTime( Picker_GetSelectedItem(hwndList) );
4593      ListView_RedrawItems(hwndList, GetSelectedPick(), GetSelectedPick());
4594      break;
4595
4596   case ID_CONTEXT_RESET_PLAYCOUNT:
4597      ResetPlayCount( Picker_GetSelectedItem(hwndList) );
4598      ListView_RedrawItems(hwndList, GetSelectedPick(), GetSelectedPick());
4599      break;
4600
4601   case ID_CONTEXT_RENAME_CUSTOM :
4602      TreeView_EditLabel(hTreeView,TreeView_GetSelection(hTreeView));
4603      break;
4604
4605   default:
4606      if (id >= ID_CONTEXT_SHOW_FOLDER_START && id < ID_CONTEXT_SHOW_FOLDER_END)
4607      {
4608         ToggleShowFolder(id - ID_CONTEXT_SHOW_FOLDER_START);
4609         break;
4610      }
4611      for (i = 0; g_helpInfo[i].nMenuItem > 0; i++)
4612      {
4613         if (g_helpInfo[i].nMenuItem == id)
4614         {
4615            if (g_helpInfo[i].bIsHtmlHelp)
4616               HelpFunction(hMain, g_helpInfo[i].lpFile, HH_DISPLAY_TOPIC, 0);
4617            else
4618               DisplayTextFile(hMain, g_helpInfo[i].lpFile);
4619            return FALSE;
4620         }
4621      }
4622#ifdef MESS
4623      return MessCommand(hwnd, id, hwndCtl, codeNotify);
4624#else
4625      break;
4626#endif
4627   }
4628
4629   return FALSE;
4630}
4631
4632static void LoadBackgroundBitmap()
4633{
4634   HGLOBAL hDIBbg;
4635   char*   pFileName = 0;
4636
4637   if (hBackground)
4638   {
4639      DeleteObject(hBackground);
4640      hBackground = 0;
4641   }
4642
4643   if (hPALbg)
4644   {
4645      DeleteObject(hPALbg);
4646      hPALbg = 0;
4647   }
4648
4649   /* Pick images based on number of colors avaliable. */
4650   if (GetDepth(hwndList) <= 8)
4651   {
4652      pFileName = (char *)"bkgnd16";
4653      /*nResource = IDB_BKGROUND16;*/
4654   }
4655   else
4656   {
4657      pFileName = (char *)"bkground";
4658      /*nResource = IDB_BKGROUND;*/
4659   }
4660
4661   if (LoadDIB(pFileName, &hDIBbg, &hPALbg, BACKGROUND))
4662   {
4663      HDC hDC = GetDC(hwndList);
4664      hBackground = DIBToDDB(hDC, hDIBbg, &bmDesc);
4665      GlobalFree(hDIBbg);
4666      ReleaseDC(hwndList, hDC);
4667   }
4668}
4669
4670static void ResetColumnDisplay(BOOL first_time)
4671{
4672   int driver_index;
4673
4674   if (!first_time)
4675      Picker_ResetColumnDisplay(hwndList);
4676
4677   ResetListView();
4678
4679   driver_index = GetGameNameIndex(GetDefaultGame());
4680   Picker_SetSelectedItem(hwndList, driver_index);
4681}
4682
4683int GamePicker_GetItemImage(HWND hwndPicker, int nItem)
4684{
4685   return GetIconForDriver(nItem);
4686}
4687
4688const TCHAR *GamePicker_GetItemString(HWND hwndPicker, int nItem, int nColumn,
4689   TCHAR *pszBuffer, UINT nBufferLength)
4690{
4691   const TCHAR *s = NULL;
4692   const char* utf8_s = NULL;
4693   char playtime_buf[256];
4694
4695   switch(nColumn)
4696   {
4697      case COLUMN_GAMES:
4698         /* Driver description */
4699         utf8_s = ModifyThe(drivers[nItem]->description);
4700         break;
4701      case COLUMN_ORIENTATION:
4702         utf8_s = DriverIsVertical(nItem) ? "Vertical" : "Horizontal";
4703         break;
4704#if 0
4705      case COLUMN_ROMS:
4706         /* Has Roms */
4707         utf8_s = GetAuditString(GetRomAuditResults(nItem));
4708         break;
4709#endif
4710      case COLUMN_SAMPLES:
4711         /* Samples */
4712         if (DriverUsesSamples(nItem))
4713            utf8_s = GetAuditString(GetSampleAuditResults(nItem));
4714         break;
4715
4716      case COLUMN_DIRECTORY:
4717         /* Driver name (directory) */
4718         utf8_s = drivers[nItem]->name;
4719         break;
4720
4721      case COLUMN_SRCDRIVERS:
4722         /* Source drivers */
4723         utf8_s = GetDriverFilename(nItem);
4724         break;
4725
4726      case COLUMN_PLAYTIME:
4727         /* Source drivers */
4728         GetTextPlayTime(nItem, playtime_buf);
4729         utf8_s = playtime_buf;
4730         break;
4731
4732      case COLUMN_TYPE:
4733        {
4734            machine_config drv;
4735            expand_machine_driver(drivers[nItem]->drv,&drv);
4736
4737         /* Vector/Raster */
4738         if (drv.video_attributes & VIDEO_TYPE_VECTOR)
4739            s = TEXT("Vector");
4740         else
4741            s = TEXT("Raster");
4742         break;
4743        }
4744      case COLUMN_TRACKBALL:
4745         /* Trackball */
4746         if (DriverUsesTrackball(nItem))
4747            s = TEXT("Yes");
4748         else
4749            s = TEXT("No");
4750         break;
4751
4752      case COLUMN_PLAYED:
4753         /* times played */
4754         _sntprintf(pszBuffer, nBufferLength, TEXT("%i"), GetPlayCount(nItem));
4755         s = pszBuffer;
4756         break;
4757
4758      case COLUMN_MANUFACTURER:
4759         /* Manufacturer */
4760         utf8_s = drivers[nItem]->manufacturer;
4761         break;
4762
4763      case COLUMN_YEAR:
4764         /* Year */
4765         utf8_s = drivers[nItem]->year;
4766         break;
4767
4768      case COLUMN_CLONE:
4769         utf8_s = GetCloneParentName(nItem);
4770         break;
4771   }
4772   
4773   if( utf8_s )
4774   {
4775      TCHAR* t_s = tstring_from_utf8(utf8_s);
4776      if( !t_s )
4777         return s;
4778     
4779      _sntprintf(pszBuffer, nBufferLength, TEXT("%s"), t_s);     
4780      free(t_s);
4781     
4782      s = pszBuffer;
4783   }
4784   
4785   return s;
4786}
4787
4788static void GamePicker_LeavingItem(HWND hwndPicker, int nItem)
4789{
4790   // leaving item
4791   // printf("leaving %s\n",drivers[nItem]->name);
4792}
4793
4794static void GamePicker_EnteringItem(HWND hwndPicker, int nItem)
4795{
4796   TCHAR* t_description;
4797   ATOM a;
4798   // printf("entering %s\n",drivers[nItem]->name);
4799   if (g_bDoBroadcast == TRUE)
4800   {
4801      t_description = tstring_from_utf8(drivers[nItem]->description);
4802      if( !t_description )
4803         return;
4804      a = GlobalAddAtom(t_description);
4805      SendMessage(HWND_BROADCAST, g_mame32_message, a, a);
4806      GlobalDeleteAtom(a);
4807      free(t_description);
4808   }
4809
4810   EnableSelection(nItem);
4811#ifdef MESS
4812   MessReadMountedSoftware(nItem);
4813#endif
4814}
4815
4816static int GamePicker_FindItemParent(HWND hwndPicker, int nItem)
4817{
4818   return GetParentRomSetIndex(drivers[nItem]);
4819}
4820
4821/* Initialize the Picker and List controls */
4822static void InitListView()
4823{
4824   LVBKIMAGE bki;
4825   TCHAR path[MAX_PATH];
4826   TCHAR* t_bgdir;
4827
4828   static const struct PickerCallbacks s_gameListCallbacks =
4829   {
4830      SetSortColumn,            /* pfnSetSortColumn */
4831      GetSortColumn,            /* pfnGetSortColumn */
4832      SetSortReverse,            /* pfnSetSortReverse */
4833      GetSortReverse,            /* pfnGetSortReverse */
4834      SetViewMode,            /* pfnSetViewMode */
4835      GetViewMode,            /* pfnGetViewMode */
4836      SetColumnWidths,         /* pfnSetColumnWidths */
4837      GetColumnWidths,         /* pfnGetColumnWidths */
4838      SetColumnOrder,            /* pfnSetColumnOrder */
4839      GetColumnOrder,            /* pfnGetColumnOrder */
4840      SetColumnShown,            /* pfnSetColumnShown */
4841      GetColumnShown,            /* pfnGetColumnShown */
4842      GetOffsetClones,         /* pfnGetOffsetChildren */
4843
4844      GamePicker_Compare,         /* pfnCompare */
4845      MamePlayGame,            /* pfnDoubleClick */
4846      GamePicker_GetItemString,   /* pfnGetItemString */
4847      GamePicker_GetItemImage,   /* pfnGetItemImage */
4848      GamePicker_LeavingItem,      /* pfnLeavingItem */
4849      GamePicker_EnteringItem,   /* pfnEnteringItem */
4850      BeginListViewDrag,         /* pfnBeginListViewDrag */
4851      GamePicker_FindItemParent,   /* pfnFindItemParent */
4852      OnIdle,                     /* pfnIdle */
4853      GamePicker_OnHeaderContextMenu,   /* pfnOnHeaderContextMenu */
4854      GamePicker_OnBodyContextMenu   /* pfnOnBodyContextMenu */
4855   };
4856
4857   struct PickerOptions opts;
4858
4859   // subclass the list view
4860   memset(&opts, 0, sizeof(opts));
4861   opts.pCallbacks = &s_gameListCallbacks;
4862   opts.nColumnCount = COLUMN_MAX;
4863   opts.ppszColumnNames = column_names;
4864   SetupPicker(hwndList, &opts);
4865
4866   ListView_SetTextBkColor(hwndList, CLR_NONE);
4867   ListView_SetBkColor(hwndList, CLR_NONE);
4868   t_bgdir = tstring_from_utf8(GetBgDir());
4869   if( !t_bgdir )
4870      return;
4871   _stprintf(path, TEXT("%s\\bkground.png"), t_bgdir);
4872   bki.ulFlags = LVBKIF_SOURCE_URL | LVBKIF_STYLE_TILE;
4873   bki.pszImage = path;
4874   if( hBackground )   
4875      ListView_SetBkImage(hwndList, &bki);
4876
4877   CreateIcons();
4878
4879   ResetColumnDisplay(TRUE);
4880
4881   // Allow selection to change the default saved game
4882   bListReady = TRUE;
4883   free(t_bgdir);
4884}
4885
4886static void AddDriverIcon(int nItem,int default_icon_index)
4887{
4888   HICON hIcon = 0;
4889   int nParentIndex = -1;
4890
4891   /* if already set to rom or clone icon, we've been here before */
4892   if (icon_index[nItem] == 1 || icon_index[nItem] == 3)
4893      return;
4894
4895   hIcon = LoadIconFromFile((char *)drivers[nItem]->name);
4896   if (hIcon == NULL)
4897   {
4898      nParentIndex = GetParentIndex(drivers[nItem]);
4899      if( nParentIndex >= 0)
4900      {
4901         hIcon = LoadIconFromFile((char *)drivers[nParentIndex]->name);
4902         nParentIndex = GetParentIndex(drivers[nParentIndex]);
4903         if (hIcon == NULL && nParentIndex >= 0)
4904            hIcon = LoadIconFromFile((char *)drivers[nParentIndex]->name);
4905      }
4906   }
4907
4908   if (hIcon != NULL)
4909   {
4910      int nIconPos = ImageList_AddIcon(hSmall, hIcon);
4911      ImageList_AddIcon(hLarge, hIcon);
4912      if (nIconPos != -1)
4913         icon_index[nItem] = nIconPos;
4914   }
4915   if (icon_index[nItem] == 0)
4916      icon_index[nItem] = default_icon_index;
4917}
4918
4919static void DestroyIcons(void)
4920{
4921   if (hSmall != NULL)
4922   {
4923      ImageList_Destroy(hSmall);
4924      hSmall = NULL;
4925   }
4926
4927   if (icon_index != NULL)
4928   {
4929      int i;
4930      for (i=0;i<driver_list_get_count(drivers);i++)
4931         icon_index[i] = 0; // these are indices into hSmall
4932   }
4933
4934   if (hLarge != NULL)
4935   {
4936      ImageList_Destroy(hLarge);
4937      hLarge = NULL;
4938   }
4939
4940   if (hHeaderImages != NULL)
4941   {
4942      ImageList_Destroy(hHeaderImages);
4943      hHeaderImages = NULL;
4944   }
4945
4946}
4947
4948static void ReloadIcons(void)
4949{
4950   HICON hIcon;
4951   INT i;
4952
4953   // clear out all the images
4954   ImageList_RemoveAll(hSmall);
4955   ImageList_RemoveAll(hLarge);
4956
4957   if (icon_index != NULL)
4958   {
4959      for (i=0;i<driver_list_get_count(drivers);i++)
4960         icon_index[i] = 0; // these are indices into hSmall
4961   }
4962
4963   for (i = 0; g_iconData[i].icon_name; i++)
4964   {
4965      hIcon = LoadIconFromFile((char *) g_iconData[i].icon_name);
4966      if (hIcon == NULL)
4967         hIcon = LoadIcon(hInst, MAKEINTRESOURCE(g_iconData[i].resource));
4968
4969      ImageList_AddIcon(hSmall, hIcon);
4970      ImageList_AddIcon(hLarge, hIcon);
4971   }
4972}
4973
4974static DWORD GetShellLargeIconSize(void)
4975{
4976   DWORD  dwSize, dwLength = 512, dwType = REG_SZ;
4977   TCHAR  szBuffer[512];
4978   HKEY   hKey;
4979
4980   /* Get the Key */
4981   RegOpenKey(HKEY_CURRENT_USER, TEXT("Control Panel\\desktop\\WindowMetrics"), &hKey);
4982   /* Save the last size */
4983   RegQueryValueEx(hKey, TEXT("Shell Icon Size"), NULL, &dwType, (LPBYTE)szBuffer, &dwLength);
4984   dwSize = _ttol(szBuffer);
4985   if (dwSize < 32)
4986      dwSize = 32;
4987
4988   if (dwSize > 48)
4989      dwSize = 48;
4990
4991   /* Clean up */
4992   RegCloseKey(hKey);
4993   return dwSize;
4994}
4995
4996static DWORD GetShellSmallIconSize(void)
4997{
4998   DWORD dwSize = ICONMAP_WIDTH;
4999
5000   if (dwSize < 48)
5001   {
5002      if (dwSize < 32)
5003         dwSize = 16;
5004      else
5005         dwSize = 32;
5006   }
5007   else
5008   {
5009      dwSize = 48;
5010   }
5011   return dwSize;
5012}
5013
5014// create iconlist for Listview control
5015static void CreateIcons(void)
5016{
5017   DWORD dwLargeIconSize = GetShellLargeIconSize();
5018   HICON hIcon;
5019   int icon_count;
5020   DWORD dwStyle;
5021   int i;
5022
5023   icon_count = 0;
5024   while(g_iconData[icon_count].icon_name)
5025      icon_count++;
5026
5027   // the current window style affects the sizing of the rows when changing
5028   // between list views, so put it in small icon mode temporarily while we associate
5029   // our image list
5030   //
5031   // using large icon mode instead kills the horizontal scrollbar when doing
5032   // full refresh, which seems odd (it should recreate the scrollbar when
5033   // set back to report mode, for example, but it doesn't).
5034
5035   dwStyle = GetWindowLong(hwndList,GWL_STYLE);
5036   SetWindowLong(hwndList,GWL_STYLE,(dwStyle & ~LVS_TYPEMASK) | LVS_ICON);
5037
5038   hSmall = ImageList_Create(GetShellSmallIconSize(),GetShellSmallIconSize(),
5039                       ILC_COLORDDB | ILC_MASK, icon_count, icon_count + 5000);
5040   hLarge = ImageList_Create(dwLargeIconSize, dwLargeIconSize,
5041                       ILC_COLORDDB | ILC_MASK, icon_count, icon_count + 5000);
5042
5043   if (NULL == hSmall || NULL == hLarge) {
5044      MessageBox(hwndList, "Cannot allocate Icon lists", TEXT("Allocation error - Exiting"), IDOK);
5045      PostQuitMessage(0);
5046   }
5047
5048   ReloadIcons();
5049
5050   // Associate the image lists with the list view control.
5051   (void)ListView_SetImageList(hwndList, hSmall, LVSIL_SMALL);
5052   (void)ListView_SetImageList(hwndList, hLarge, LVSIL_NORMAL);
5053
5054   // restore our view
5055   SetWindowLong(hwndList,GWL_STYLE,dwStyle);
5056
5057#ifdef MESS
5058   CreateMessIcons();
5059#endif
5060
5061   // Now set up header specific stuff
5062   hHeaderImages = ImageList_Create(8,8,ILC_COLORDDB | ILC_MASK,2,2);
5063   hIcon = LoadIcon(hInst,MAKEINTRESOURCE(IDI_HEADER_UP));
5064   ImageList_AddIcon(hHeaderImages,hIcon);
5065   hIcon = LoadIcon(hInst,MAKEINTRESOURCE(IDI_HEADER_DOWN));
5066   ImageList_AddIcon(hHeaderImages,hIcon);
5067
5068   for (i = 0; i < sizeof(s_nPickers) / sizeof(s_nPickers[0]); i++)
5069      Picker_SetHeaderImageList(GetDlgItem(hMain, s_nPickers[i]), hHeaderImages);
5070}
5071
5072
5073
5074static int GamePicker_Compare(HWND hwndPicker, int index1, int index2, int sort_subitem)
5075{
5076   int value;
5077   const char *name1 = NULL;
5078   const char *name2 = NULL;
5079   int nTemp1, nTemp2;
5080
5081#ifdef DEBUG
5082   if (strcmp(drivers[index1]->name,"1941") == 0 && strcmp(drivers[index2]->name,"1942") == 0)
5083   {
5084      dprintf("comparing 1941, 1942");
5085   }
5086
5087   if (strcmp(drivers[index1]->name,"1942") == 0 && strcmp(drivers[index2]->name,"1941") == 0)
5088   {
5089      dprintf("comparing 1942, 1941");
5090   }
5091#endif
5092
5093   switch (sort_subitem)
5094   {
5095   case COLUMN_GAMES:
5096      value = mame_stricmp(ModifyThe(drivers[index1]->description),
5097                  ModifyThe(drivers[index2]->description));
5098      break;
5099
5100   case COLUMN_ORIENTATION:
5101      nTemp1 = DriverIsVertical(index1) ? 1 : 0;
5102      nTemp2 = DriverIsVertical(index2) ? 1 : 0;
5103      value = nTemp1 - nTemp2;
5104      break;
5105#if 0
5106   case COLUMN_ROMS:
5107      nTemp1 = GetRomAuditResults(index1);
5108      nTemp2 = GetRomAuditResults(index2);
5109
5110      if (IsAuditResultKnown(nTemp1) == FALSE && IsAuditResultKnown(nTemp2) == FALSE)
5111         return GamePicker_Compare(hwndPicker, index1, index2, COLUMN_GAMES);
5112
5113      if (IsAuditResultKnown(nTemp1) == FALSE)
5114      {
5115         value = 1;
5116         break;
5117      }
5118
5119      if (IsAuditResultKnown(nTemp2) == FALSE)
5120      {
5121         value = -1;
5122         break;
5123      }
5124
5125      // ok, both are known
5126
5127      if (IsAuditResultYes(nTemp1) && IsAuditResultYes(nTemp2))
5128         return GamePicker_Compare(hwndPicker, index1, index2, COLUMN_GAMES);
5129     
5130      if (IsAuditResultNo(nTemp1) && IsAuditResultNo(nTemp2))
5131         return GamePicker_Compare(hwndPicker, index1, index2, COLUMN_GAMES);
5132
5133      if (IsAuditResultYes(nTemp1) && IsAuditResultNo(nTemp2))
5134         value = -1;
5135      else
5136         value = 1;
5137      break;
5138#endif
5139   case COLUMN_SAMPLES:
5140      nTemp1 = -1;
5141      if (DriverUsesSamples(index1))
5142      {
5143         int audit_result = GetSampleAuditResults(index1);
5144         if (IsAuditResultKnown(audit_result))
5145         {
5146            if (IsAuditResultYes(audit_result))
5147               nTemp1 = 1;
5148            else
5149               nTemp1 = 0;
5150         }
5151         else
5152            nTemp1 = 2;
5153      }
5154
5155      nTemp2 = -1;
5156      if (DriverUsesSamples(index2))
5157      {
5158         int audit_result = GetSampleAuditResults(index1);
5159         if (IsAuditResultKnown(audit_result))
5160         {
5161            if (IsAuditResultYes(audit_result))
5162               nTemp2 = 1;
5163            else
5164               nTemp2 = 0;
5165         }
5166         else
5167            nTemp2 = 2;
5168      }
5169
5170      if (nTemp1 == nTemp2)
5171         return GamePicker_Compare(hwndPicker, index1, index2, COLUMN_GAMES);
5172
5173      value = nTemp2 - nTemp1;
5174      break;
5175
5176   case COLUMN_DIRECTORY:
5177      value = mame_stricmp(drivers[index1]->name, drivers[index2]->name);
5178      break;
5179
5180      case COLUMN_SRCDRIVERS:
5181      if (mame_stricmp(drivers[index1]->source_file+12, drivers[index2]->source_file+12) == 0)
5182         return GamePicker_Compare(hwndPicker, index1, index2, COLUMN_GAMES);
5183
5184      value = mame_stricmp(drivers[index1]->source_file+12, drivers[index2]->source_file+12);
5185      break;
5186   case COLUMN_PLAYTIME:
5187      value = GetPlayTime(index1) - GetPlayTime(index2);
5188      if (value == 0)
5189        return GamePicker_Compare(hwndPicker, index1, index2, COLUMN_GAMES);
5190
5191      break;
5192
5193   case COLUMN_TYPE:
5194    {
5195        machine_config drv1,drv2;
5196        expand_machine_driver(drivers[index1]->drv,&drv1);
5197        expand_machine_driver(drivers[index2]->drv,&drv2);
5198
5199      if ((drv1.video_attributes & VIDEO_TYPE_VECTOR) ==
5200         (drv2.video_attributes & VIDEO_TYPE_VECTOR))
5201         return GamePicker_Compare(hwndPicker, index1, index2, COLUMN_GAMES);
5202
5203      value = (drv1.video_attributes & VIDEO_TYPE_VECTOR) -
5204            (drv2.video_attributes & VIDEO_TYPE_VECTOR);
5205      break;
5206    }
5207   case COLUMN_TRACKBALL:
5208      if (DriverUsesTrackball(index1) == DriverUsesTrackball(index2))
5209         return GamePicker_Compare(hwndPicker, index1, index2, COLUMN_GAMES);
5210
5211      value = DriverUsesTrackball(index1) - DriverUsesTrackball(index2);
5212      break;
5213
5214   case COLUMN_PLAYED:
5215      value = GetPlayCount(index1) - GetPlayCount(index2);
5216      if (value == 0)
5217        return GamePicker_Compare(hwndPicker, index1, index2, COLUMN_GAMES);
5218
5219      break;
5220
5221   case COLUMN_MANUFACTURER:
5222      if (mame_stricmp(drivers[index1]->manufacturer, drivers[index2]->manufacturer) == 0)
5223         return GamePicker_Compare(hwndPicker, index1, index2, COLUMN_GAMES);
5224
5225      value = mame_stricmp(drivers[index1]->manufacturer, drivers[index2]->manufacturer);
5226      break;
5227
5228   case COLUMN_YEAR:
5229      if (mame_stricmp(drivers[index1]->year, drivers[index2]->year) == 0)
5230         return GamePicker_Compare(hwndPicker, index1, index2, COLUMN_GAMES);
5231
5232      value = mame_stricmp(drivers[index1]->year, drivers[index2]->year);
5233      break;
5234
5235   case COLUMN_CLONE:
5236      name1 = GetCloneParentName(index1);
5237      name2 = GetCloneParentName(index2);
5238
5239      if (*name1 == '\0')
5240         name1 = NULL;
5241      if (*name2 == '\0')
5242         name2 = NULL;
5243
5244      if (name1 == name2)
5245         return GamePicker_Compare(hwndPicker, index1, index2, COLUMN_GAMES);
5246
5247      if (name2 == NULL)
5248         value = -1;
5249      else if (name1 == NULL)
5250         value = 1;
5251      else
5252         value = mame_stricmp(name1, name2);
5253      break;
5254
5255   default :
5256      return GamePicker_Compare(hwndPicker, index1, index2, COLUMN_GAMES);
5257   }
5258
5259#ifdef DEBUG
5260   if ((strcmp(drivers[index1]->name,"1941") == 0 && strcmp(drivers[index2]->name,"1942") == 0) ||
5261      (strcmp(drivers[index1]->name,"1942") == 0 && strcmp(drivers[index2]->name,"1941") == 0))
5262      dprintf("result: %i",value);
5263#endif
5264
5265   return value;
5266}
5267
5268int GetSelectedPick()
5269{
5270   /* returns index of listview selected item */
5271   /* This will return -1 if not found */
5272   return ListView_GetNextItem(hwndList, -1, LVIS_SELECTED | LVIS_FOCUSED);
5273}
5274
5275static HICON GetSelectedPickItemIcon()
5276{
5277   LV_ITEM lvi;
5278
5279   lvi.iItem = GetSelectedPick();
5280   lvi.iSubItem = 0;
5281   lvi.mask = LVIF_IMAGE;
5282   ListView_GetItem(hwndList, &lvi);
5283
5284   return ImageList_GetIcon(hLarge, lvi.iImage, ILD_TRANSPARENT);
5285}
5286
5287static void SetRandomPickItem()
5288{
5289   int nListCount;
5290
5291   nListCount = ListView_GetItemCount(hwndList);
5292
5293   if (nListCount > 0)
5294   {
5295      Picker_SetSelectedPick(hwndList, rand() % nListCount);
5296   }
5297}
5298
5299BOOL CommonFileDialog(common_file_dialog_proc cfd, char *filename, int filetype)
5300{
5301   BOOL success;
5302   OPENFILENAME of;
5303   TCHAR* t_filename;
5304   TCHAR* t_statedir = 0;
5305   TCHAR* t_artdir = 0;
5306   TCHAR t_filename_buffer[MAX_PATH]  = {0, };
5307   char *utf8_filename;
5308
5309   // convert the filename to UTF-8 and copy into buffer
5310   t_filename = tstring_from_utf8(filename);
5311   if (t_filename != NULL)
5312   {
5313      _sntprintf(t_filename_buffer, ARRAY_LENGTH(t_filename_buffer), TEXT("%s"), t_filename);
5314      free(t_filename);
5315   }
5316
5317   of.lStructSize       = sizeof(of);
5318   of.hwndOwner         = hMain;
5319   of.hInstance         = NULL;
5320   switch (filetype)
5321   {
5322   case FILETYPE_INPUT_FILES :
5323      of.lpstrFilter   = TEXT(MAMENAME " input files (*.inp,*.zip)\0*.inp;*.zip\0All files (*.*)\0*.*\0");
5324      break;
5325   case FILETYPE_SAVESTATE_FILES :
5326      of.lpstrFilter   = TEXT(MAMENAME " savestate files (*.sta)\0*.sta;\0All files (*.*)\0*.*\0");
5327      break;
5328   case FILETYPE_WAVE_FILES :
5329      of.lpstrFilter   = TEXT("sounds (*.wav)\0*.wav;\0All files (*.*)\0*.*\0");
5330      break;
5331   case FILETYPE_MNG_FILES :
5332      of.lpstrFilter   = TEXT("videos (*.mng)\0*.mng;\0All files (*.*)\0*.*\0");
5333      break;
5334   case FILETYPE_EFFECT_FILES :
5335      of.lpstrFilter   = TEXT("effects (*.png)\0*.png;\0All files (*.*)\0*.*\0");
5336      break;
5337   }
5338   of.lpstrCustomFilter = NULL;
5339   of.nMaxCustFilter    = 0;
5340   of.nFilterIndex      = 1;
5341   of.lpstrFile         = t_filename_buffer;
5342   of.nMaxFile          = ARRAY_LENGTH(t_filename_buffer);
5343   of.lpstrFileTitle    = NULL;
5344   of.nMaxFileTitle     = 0;
5345   if (filetype == FILETYPE_SAVESTATE_FILES)
5346   {
5347      t_statedir = tstring_from_utf8(GetStateDir());
5348      if( !t_statedir )
5349         return FALSE;
5350
5351      of.lpstrInitialDir = t_statedir;
5352   }
5353   else
5354   {
5355      if (filetype == FILETYPE_EFFECT_FILES)
5356      {
5357         t_artdir = tstring_from_utf8(GetArtDir());
5358         if( !t_artdir )
5359            return FALSE;
5360
5361         of.lpstrInitialDir = t_artdir;
5362      }
5363      else
5364         of.lpstrInitialDir = last_directory;
5365   }
5366   of.lpstrTitle        = NULL;
5367   of.Flags             = OFN_EXPLORER | OFN_NOCHANGEDIR | OFN_PATHMUSTEXIST | OFN_HIDEREADONLY;
5368   of.nFileOffset       = 0;
5369   of.nFileExtension    = 0;
5370   switch (filetype)
5371   {
5372   case FILETYPE_INPUT_FILES :
5373      of.lpstrDefExt       = TEXT("inp");
5374      break;
5375   case FILETYPE_SAVESTATE_FILES :
5376      of.lpstrDefExt       = TEXT("sta");
5377      break;
5378   case FILETYPE_WAVE_FILES :
5379      of.lpstrDefExt       = TEXT("wav");
5380      break;
5381   case FILETYPE_MNG_FILES :
5382      of.lpstrDefExt       = TEXT("mng");
5383      break;
5384   case FILETYPE_EFFECT_FILES :
5385      of.lpstrDefExt       = TEXT("png");
5386      break;
5387   }
5388   of.lCustData         = 0;
5389   of.lpfnHook          = NULL;
5390   of.lpTemplateName    = NULL;
5391
5392   success = cfd(&of);
5393   if (success)
5394   {
5395      //dprintf("got filename %s nFileExtension %u\n",filename,of.nFileExtension);
5396      /*GetDirectory(filename,last_directory,sizeof(last_directory));*/
5397   }
5398   
5399   if( t_artdir )
5400      free(t_artdir);
5401   if( t_statedir )
5402      free(t_statedir);
5403
5404   utf8_filename = utf8_from_tstring(t_filename_buffer);
5405   if (utf8_filename != NULL)
5406   {
5407      snprintf(filename, MAX_PATH, "%s", utf8_filename);
5408   }
5409
5410   return success;
5411}
5412
5413static BOOL SelectLanguageFile(HWND hWnd, TCHAR* filename)
5414{
5415   OPENFILENAME of;
5416
5417   of.lStructSize       = sizeof(of);
5418   of.hwndOwner         = hWnd;
5419   of.hInstance         = NULL;
5420   of.lpstrFilter       = TEXT(MAMENAME " Language files (*.lng)\0*.lng\0");
5421   of.lpstrCustomFilter = NULL;
5422   of.nMaxCustFilter    = 0;
5423   of.nFilterIndex      = 1;
5424   of.lpstrFile         = filename;
5425   of.nMaxFile          = MAX_PATH;
5426   of.lpstrFileTitle    = NULL;
5427   of.nMaxFileTitle     = 0;
5428   of.lpstrInitialDir   = NULL;
5429   of.lpstrTitle        = NULL;
5430   of.Flags             = OFN_EXPLORER | OFN_NOCHANGEDIR | OFN_PATHMUSTEXIST | OFN_HIDEREADONLY | OFN_FILEMUSTEXIST;
5431   of.nFileOffset       = 0;
5432   of.nFileExtension    = 0;
5433   of.lpstrDefExt       = TEXT("lng");
5434   of.lCustData         = 0;
5435   of.lpfnHook          = NULL;
5436   of.lpTemplateName    = NULL;
5437
5438   return GetOpenFileName(&of);
5439}
5440
5441static INT_PTR CALLBACK LanguageDialogProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam)
5442{
5443   TCHAR pLangFile[MAX_PATH];
5444   DWORD dwHelpIDs[] = { IDC_LANGUAGECHECK, HIDC_LANGUAGECHECK,
5445                    IDC_LANGUAGEEDIT,  HIDC_LANGUAGEEDIT,
5446                    0, 0};
5447   char* utf8_LangFile;
5448
5449   switch (Msg)
5450   {
5451   case WM_INITDIALOG:
5452      {
5453         const char* pLang = GetLanguage();
5454         if (pLang == NULL || *pLang == '\0')
5455         {
5456            win_set_window_text_utf8(GetDlgItem(hDlg, IDC_LANGUAGEEDIT), "");
5457            Button_SetCheck(GetDlgItem(hDlg, IDC_LANGUAGECHECK), FALSE);
5458            EnableWindow(GetDlgItem(hDlg, IDC_LANGUAGEEDIT),   FALSE);
5459            EnableWindow(GetDlgItem(hDlg, IDC_LANGUAGEBROWSE), FALSE);
5460         }
5461         else
5462         {
5463            win_set_window_text_utf8(GetDlgItem(hDlg, IDC_LANGUAGEEDIT), pLang);
5464            Button_SetCheck(GetDlgItem(hDlg, IDC_LANGUAGECHECK), TRUE);
5465            EnableWindow(GetDlgItem(hDlg, IDC_LANGUAGEEDIT),   TRUE);
5466            EnableWindow(GetDlgItem(hDlg, IDC_LANGUAGEBROWSE), TRUE);
5467         }
5468
5469         return TRUE;
5470      }
5471
5472   case WM_HELP:
5473      HelpFunction(((LPHELPINFO)lParam)->hItemHandle, MAME32CONTEXTHELP, HH_TP_HELP_WM_HELP, (DWORD)dwHelpIDs);
5474      break;
5475
5476   case WM_CONTEXTMENU:
5477      HelpFunction((HWND)wParam, MAME32CONTEXTHELP, HH_TP_HELP_CONTEXTMENU, (DWORD)dwHelpIDs);
5478      break;
5479
5480   case WM_COMMAND:
5481      switch (GET_WM_COMMAND_ID(wParam, lParam))
5482      {
5483      case IDOK:
5484         Edit_GetText(GetDlgItem(hDlg, IDC_LANGUAGEEDIT), pLangFile, MAX_PATH);
5485         utf8_LangFile = utf8_from_tstring(pLangFile);
5486         if( !utf8_LangFile )
5487            return FALSE;
5488         SetLanguage(utf8_LangFile);
5489         free(utf8_LangFile);
5490
5491      case IDCANCEL:
5492         EndDialog(hDlg, 0);
5493         return TRUE;
5494
5495      case IDC_LANGUAGECHECK:
5496      {
5497         BOOL bCheck = Button_GetCheck(GetDlgItem(hDlg, IDC_LANGUAGECHECK));
5498         EnableWindow(GetDlgItem(hDlg, IDC_LANGUAGEEDIT),   bCheck);
5499         EnableWindow(GetDlgItem(hDlg, IDC_LANGUAGEBROWSE), bCheck);
5500         if (bCheck == FALSE)
5501            Edit_SetText(GetDlgItem(hDlg, IDC_LANGUAGEEDIT), TEXT(""));
5502         return TRUE;
5503      }
5504
5505      case IDC_LANGUAGEBROWSE:
5506         Edit_GetText(GetDlgItem(hDlg, IDC_LANGUAGEEDIT), pLangFile, MAX_PATH);
5507         if (SelectLanguageFile(hDlg, pLangFile) == TRUE)
5508            Edit_SetText(GetDlgItem(hDlg, IDC_LANGUAGEEDIT), pLangFile);
5509         break;
5510      }
5511      break;
5512   }
5513   return 0;
5514}
5515
5516void SetStatusBarText(int part_index, const char *message)
5517{
5518   TCHAR* t_message = tstring_from_utf8(message);
5519   if( !t_message )
5520      return;
5521   SendMessage(hStatusBar, SB_SETTEXT, (WPARAM) part_index, (LPARAM)(LPCTSTR) win_tstring_strdup(t_message));
5522   free(t_message);
5523}
5524
5525void SetStatusBarTextF(int part_index, const char *fmt, ...)
5526{
5527   char buf[256];
5528   va_list va;
5529
5530   va_start(va, fmt);
5531   vsprintf(buf, fmt, va);
5532   va_end(va);
5533
5534   SetStatusBarText(part_index, buf);
5535}
5536
5537static void CLIB_DECL MameMessageBox(const char *fmt, ...)
5538{
5539   char buf[2048];
5540   va_list va;
5541
5542   va_start(va, fmt);
5543   vsprintf(buf, fmt, va);
5544   win_message_box_utf8(GetMainWindow(), buf, MAME32NAME, MB_OK | MB_ICONERROR);
5545   va_end(va);
5546}
5547
5548static void MamePlayBackGame()
5549{
5550   int nGame;
5551   char filename[MAX_PATH];
5552
5553   *filename = 0;
5554
5555   nGame = Picker_GetSelectedItem(hwndList);
5556   if (nGame != -1)
5557      strcpy(filename, drivers[nGame]->name);
5558
5559   if (CommonFileDialog(GetOpenFileName, filename, FILETYPE_INPUT_FILES))
5560   {
5561      file_error fileerr;
5562      mame_file* pPlayBack;
5563      char drive[_MAX_DRIVE];
5564      char dir[_MAX_DIR];
5565      char bare_fname[_MAX_FNAME];
5566      char ext[_MAX_EXT];
5567
5568      char path[MAX_PATH];
5569      char fname[MAX_PATH];
5570      play_options playopts;
5571
5572      _splitpath(filename, drive, dir, bare_fname, ext);
5573
5574      sprintf(path,"%s%s",drive,dir);
5575      sprintf(fname,"%s%s",bare_fname,ext);
5576      if (path[strlen(path)-1] == '\\')
5577         path[strlen(path)-1] = 0; // take off trailing back slash
5578
5579      fileerr = mame_fopen_options(Mame32Global(), SEARCHPATH_INPUTLOG, fname, OPEN_FLAG_READ, &pPlayBack);
5580      if (fileerr != FILERR_NONE)
5581      {
5582         MameMessageBox("Could not open '%s' as a valid input file.", filename);
5583         return;
5584      }
5585
5586      // check for game name embedded in .inp header
5587      if (pPlayBack)
5588      {
5589         inp_header input_header;
5590
5591         // read playback header
5592         mame_fread(pPlayBack, &input_header, sizeof(inp_header));
5593
5594         if (!isalnum(input_header.name[0])) // If first byte is not alpha-numeric
5595            mame_fseek(pPlayBack, 0, SEEK_SET); // old .inp file - no header
5596         else
5597         {
5598            int i;
5599            for (i = 0; drivers[i] != 0; i++) // find game and play it
5600            {
5601               if (strcmp(drivers[i]->name, input_header.name) == 0)
5602               {
5603                  nGame = i;
5604                  break;
5605               }
5606            }
5607         }
5608      }
5609      mame_fclose(pPlayBack);
5610
5611      memset(&playopts, 0, sizeof(playopts));
5612      playopts.playback = fname;
5613      MamePlayGameWithOptions(nGame, &playopts);
5614   }
5615}
5616
5617static void MameLoadState()
5618{
5619   int nGame;
5620   char filename[MAX_PATH];
5621   char selected_filename[MAX_PATH];
5622   play_options playopts;
5623
5624   *filename = 0;
5625
5626   nGame = Picker_GetSelectedItem(hwndList);
5627   if (nGame != -1)
5628   {
5629      strcpy(filename, drivers[nGame]->name);
5630      strcpy(selected_filename, drivers[nGame]->name);
5631   }
5632   if (CommonFileDialog(GetOpenFileName, filename, FILETYPE_SAVESTATE_FILES))
5633   {
5634      mame_file* pSaveState;
5635      char drive[_MAX_DRIVE];
5636      char dir[_MAX_DIR];
5637      char ext[_MAX_EXT];
5638
5639      char path[MAX_PATH];
5640      char fname[MAX_PATH];
5641      char bare_fname[_MAX_FNAME];
5642      char *state_fname;
5643      int rc;
5644
5645      _splitpath(filename, drive, dir, bare_fname, ext);
5646
5647      // parse path
5648      sprintf(path,"%s%s",drive,dir);
5649      sprintf(fname,"%s%s",bare_fname,ext);
5650      if (path[strlen(path)-1] == '\\')
5651         path[strlen(path)-1] = 0; // take off trailing back slash
5652
5653#ifdef MESS
5654      {
5655         state_fname = filename;
5656      }
5657#else // !MESS
5658      {
5659         char *cPos=0;
5660         int  iPos=0;
5661         char romname[MAX_PATH];
5662
5663         cPos = strchr(bare_fname, '-' );
5664         iPos = cPos ? cPos - bare_fname : strlen(bare_fname);
5665         strncpy(romname, bare_fname, iPos );
5666         romname[iPos] = '\0';
5667         if( strcmp(selected_filename,romname) != 0 )
5668         {
5669            MameMessageBox("'%s' is not a valid savestate file for game '%s'.", filename, selected_filename);
5670            return;
5671         }
5672         state_fname = fname;
5673      }
5674#endif // MESS
5675
5676      mame_fopen_options(Mame32Global(), SEARCHPATH_STATE, state_fname, OPEN_FLAG_READ, &pSaveState);
5677      if (pSaveState == NULL)
5678      {
5679         MameMessageBox("Could not open '%s' as a valid savestate file.", filename);
5680         return;
5681      }
5682
5683      // call the MAME core function to check the save state file
5684      rc = state_save_check_file(pSaveState, selected_filename, TRUE, MameMessageBox);
5685      mame_fclose(pSaveState);
5686      if (rc)
5687         return;
5688
5689      memset(&playopts, 0, sizeof(playopts));
5690#ifdef MESS
5691      playopts.state = state_fname;
5692#else
5693      {
5694         char *cPos;
5695         cPos = strrchr(bare_fname, '-' );
5696         cPos = cPos+1;
5697         if( strlen(cPos) >0)
5698         {
5699            playopts.state = cPos;
5700         }
5701      }
5702#endif
5703
5704      MamePlayGameWithOptions(nGame, &playopts);
5705   }
5706}
5707
5708static void MamePlayRecordGame()
5709{
5710   int  nGame;
5711   char filename[MAX_PATH];
5712   *filename = 0;
5713
5714   nGame = Picker_GetSelectedItem(hwndList);
5715   strcpy(filename, drivers[nGame]->name);
5716
5717   if (CommonFileDialog(GetSaveFileName, filename, FILETYPE_INPUT_FILES))
5718   {
5719      char drive[_MAX_DRIVE];
5720      char dir[_MAX_DIR];
5721      char fname[_MAX_FNAME];
5722      char ext[_MAX_EXT];
5723      char path[MAX_PATH];
5724      play_options playopts;
5725
5726      _splitpath(filename, drive, dir, fname, ext);
5727
5728      sprintf(path,"%s%s",drive,dir);
5729      if (path[strlen(path)-1] == '\\')
5730         path[strlen(path)-1] = 0; // take off trailing back slash
5731
5732      memset(&playopts, 0, sizeof(playopts));
5733      playopts.record = fname;
5734      MamePlayGameWithOptions(nGame, &playopts);
5735   }
5736}
5737
5738void MamePlayGame(void)
5739{
5740   int nGame;
5741   play_options playopts;
5742
5743   nGame = Picker_GetSelectedItem(hwndList);
5744
5745   memset(&playopts, 0, sizeof(playopts));
5746   MamePlayGameWithOptions(nGame, &playopts);
5747}
5748
5749static void MamePlayRecordWave()
5750{
5751   int  nGame;
5752   char filename[MAX_PATH];
5753   play_options playopts;
5754
5755   nGame = Picker_GetSelectedItem(hwndList);
5756   strcpy(filename, drivers[nGame]->name);
5757
5758   if (CommonFileDialog(GetSaveFileName, filename, FILETYPE_WAVE_FILES))
5759   {
5760      memset(&playopts, 0, sizeof(playopts));
5761      playopts.wavwrite = filename;
5762      MamePlayGameWithOptions(nGame, &playopts);
5763   }   
5764}
5765
5766static void MamePlayRecordMNG()
5767{
5768   int  nGame;
5769   char filename[MAX_PATH] = { 0, };
5770   play_options playopts;
5771
5772   nGame = Picker_GetSelectedItem(hwndList);
5773   strcpy(filename, drivers[nGame]->name);
5774
5775   if (CommonFileDialog(GetSaveFileName, filename, FILETYPE_MNG_FILES))
5776   {
5777      memset(&playopts, 0, sizeof(playopts));
5778      playopts.mngwrite = filename;
5779      MamePlayGameWithOptions(nGame, &playopts);
5780   }   
5781}
5782
5783static void MamePlayGameWithOptions(int nGame, const play_options *playopts)
5784{
5785   DWORD dwExitCode;
5786
5787#ifdef MESS
5788   if (!MessApproveImageList(hMain, nGame))
5789      return;
5790#endif
5791
5792   if (g_pJoyGUI != NULL)
5793      KillTimer(hMain, JOYGUI_TIMER);
5794   if (GetCycleScreenshot() > 0)
5795      KillTimer(hMain, SCREENSHOT_TIMER);
5796
5797   in_emulation = TRUE;
5798
5799   dwExitCode = RunMAME(nGame, playopts);
5800   if (dwExitCode == 0)
5801   {
5802      IncrementPlayCount(nGame);
5803      ListView_RedrawItems(hwndList, GetSelectedPick(), GetSelectedPick());
5804   }
5805   else
5806   {
5807      ShowWindow(hMain, SW_SHOW);
5808   }
5809
5810   in_emulation = FALSE;
5811
5812   // re-sort if sorting on # of times played
5813   if (GetSortColumn() == COLUMN_PLAYED)
5814      Picker_Sort(hwndList);
5815
5816   UpdateStatusBar();
5817
5818   ShowWindow(hMain, SW_SHOW);
5819   SetFocus(hwndList);
5820
5821   if (g_pJoyGUI != NULL)
5822      SetTimer(hMain, JOYGUI_TIMER, JOYGUI_MS, NULL);
5823   if (GetCycleScreenshot() > 0)
5824      SetTimer(hMain, SCREENSHOT_TIMER, GetCycleScreenshot()*1000, NULL); //scale to seconds
5825}
5826
5827/* Toggle ScreenShot ON/OFF */
5828static void ToggleScreenShot(void)
5829{
5830   BOOL showScreenShot = GetShowScreenShot();
5831
5832   SetShowScreenShot((showScreenShot) ? FALSE : TRUE);
5833   UpdateScreenShot();
5834
5835   /* Redraw list view */
5836   if (hBackground != NULL && showScreenShot)
5837      InvalidateRect(hwndList, NULL, FALSE);
5838}
5839
5840static void AdjustMetrics(void)
5841{
5842   HDC hDC;
5843   TEXTMETRIC tm;
5844   int xtraX, xtraY;
5845   AREA area;
5846   int  offX, offY;
5847   int  maxX, maxY;
5848   COLORREF textColor;
5849   TCHAR szClass[128];
5850   HWND hWnd;
5851
5852   /* WM_SETTINGCHANGE also */
5853   xtraX  = GetSystemMetrics(SM_CXFIXEDFRAME); /* Dialog frame width */
5854   xtraY  = GetSystemMetrics(SM_CYFIXEDFRAME); /* Dialog frame height */
5855   xtraY += GetSystemMetrics(SM_CYMENUSIZE);   /* Menu height */
5856   xtraY += GetSystemMetrics(SM_CYCAPTION);   /* Caption Height */
5857   maxX   = GetSystemMetrics(SM_CXSCREEN);    /* Screen Width */
5858   maxY   = GetSystemMetrics(SM_CYSCREEN);    /* Screen Height */
5859
5860   hDC = GetDC(hMain);
5861   GetTextMetrics (hDC, &tm);
5862
5863   /* Convert MIN Width/Height from Dialog Box Units to pixels. */
5864   MIN_WIDTH  = (int)((tm.tmAveCharWidth / 4.0) * DBU_MIN_WIDTH)  + xtraX;
5865   MIN_HEIGHT = (int)((tm.tmHeight      / 8.0) * DBU_MIN_HEIGHT) + xtraY;
5866   ReleaseDC(hMain, hDC);
5867
5868   if ((textColor = GetListFontColor()) == RGB(255, 255, 255))
5869      textColor = RGB(240, 240, 240);
5870
5871   hWnd = GetWindow(hMain, GW_CHILD);
5872   while(hWnd)
5873   {
5874      if (GetClassName(hWnd, szClass, sizeof(szClass) / sizeof(szClass[0])))
5875      {
5876         if (!_tcscmp(szClass, TEXT("SysListView32")))
5877         {
5878            ListView_SetBkColor(hWnd, GetSysColor(COLOR_WINDOW));
5879            ListView_SetTextColor(hWnd, textColor);
5880         }
5881         else if (!_tcscmp(szClass, TEXT("SysTreeView32")))
5882         {
5883            TreeView_SetBkColor(hTreeView, GetSysColor(COLOR_WINDOW));
5884            TreeView_SetTextColor(hTreeView, textColor);
5885         }
5886      }
5887      hWnd = GetWindow(hWnd, GW_HWNDNEXT);
5888   }
5889
5890   GetWindowArea(&area);
5891
5892   offX = area.x + area.width;
5893   offY = area.y + area.height;
5894
5895   if (offX > maxX)
5896   {
5897      offX = maxX;
5898      area.x = (offX - area.width > 0) ? (offX - area.width) : 0;
5899   }
5900   if (offY > maxY)
5901   {
5902      offY = maxY;
5903      area.y = (offY - area.height > 0) ? (offY - area.height) : 0;
5904   }
5905
5906   SetWindowArea(&area);
5907   SetWindowPos(hMain, 0, area.x, area.y, area.width, area.height, SWP_NOZORDER | SWP_SHOWWINDOW | SWP_NOACTIVATE);
5908}
5909
5910
5911/* Adjust options - tune them to the currently selected game */
5912static void EnablePlayOptions(int nIndex, core_options *o)
5913{
5914}
5915
5916int FindIconIndex(int nIconResource)
5917{
5918   int i;
5919   for(i = 0; g_iconData[i].icon_name; i++)
5920   {
5921      if (g_iconData[i].resource == nIconResource)
5922         return i;
5923   }
5924   return -1;
5925}
5926
5927int FindIconIndexByName(const char *icon_name)
5928{
5929   int i;
5930   for (i = 0; g_iconData[i].icon_name; i++)
5931   {
5932      if (!strcmp(g_iconData[i].icon_name, icon_name))
5933         return i;
5934   }
5935   return -1;
5936}
5937
5938static int GetIconForDriver(int nItem)
5939{
5940   int iconRoms = 1;
5941
5942   if (DriverUsesRoms(nItem))
5943   {
5944      int audit_result = GetRomAuditResults(nItem);
5945      if (IsAuditResultKnown(audit_result) == FALSE)
5946         return 2;
5947#ifdef SHOW_MISSING_ROMS_ICON
5948      if (IsAuditResultYes(audit_result))
5949         iconRoms = 1;
5950      else
5951         iconRoms = 0;
5952#endif
5953   }
5954
5955   // iconRoms is now either 0 (no roms), 1 (roms), or 2 (unknown)
5956
5957   /* these are indices into icon_names, which maps into our image list
5958    * also must match IDI_WIN_NOROMS + iconRoms
5959     */
5960
5961   // Show Red-X if the ROMs are present and flagged as NOT WORKING
5962   if (iconRoms == 1 && DriverIsBroken(nItem))
5963      iconRoms = FindIconIndex(IDI_WIN_REDX);
5964
5965   // show clone icon if we have roms and game is working
5966   if (iconRoms == 1 && DriverIsClone(nItem))
5967      iconRoms = FindIconIndex(IDI_WIN_CLONE);
5968
5969   // if we have the roms, then look for a custom per-game icon to override
5970   if (iconRoms == 1 || iconRoms == 3)
5971   {
5972      if (icon_index[nItem] == 0)
5973         AddDriverIcon(nItem,iconRoms);
5974      iconRoms = icon_index[nItem];
5975   }
5976
5977   return iconRoms;
5978}
5979
5980static BOOL HandleTreeContextMenu(HWND hWnd, WPARAM wParam, LPARAM lParam)
5981{
5982   HMENU hTreeMenu;
5983   HMENU hMenu;
5984   TVHITTESTINFO hti;
5985   POINT pt;
5986
5987   if ((HWND)wParam != GetDlgItem(hWnd, IDC_TREE))
5988      return FALSE;
5989
5990   pt.x = GET_X_LPARAM(lParam);
5991   pt.y = GET_Y_LPARAM(lParam);
5992   if (pt.x < 0 && pt.y < 0)
5993      GetCursorPos(&pt);
5994
5995   /* select the item that was right clicked or shift-F10'ed */
5996   hti.pt = pt;
5997   ScreenToClient(hTreeView,&hti.pt);
5998   (void)TreeView_HitTest(hTreeView,&hti);
5999   if ((hti.flags & TVHT_ONITEM) != 0)
6000      TreeView_SelectItem(hTreeView,hti.hItem);
6001
6002   hTreeMenu = LoadMenu(hInst,MAKEINTRESOURCE(IDR_CONTEXT_TREE));
6003
6004   InitTreeContextMenu(hTreeMenu);
6005
6006   hMenu = GetSubMenu(hTreeMenu, 0);
6007   
6008   UpdateMenu(hMenu);
6009
6010   TrackPopupMenu(hMenu,TPM_LEFTALIGN | TPM_RIGHTBUTTON,pt.x,pt.y,0,hWnd,NULL);
6011
6012   DestroyMenu(hTreeMenu);
6013
6014   return TRUE;
6015}
6016
6017
6018
6019static void GamePicker_OnBodyContextMenu(POINT pt)
6020{
6021   HMENU hMenuLoad;
6022   HMENU hMenu;
6023
6024   hMenuLoad = LoadMenu(hInst, MAKEINTRESOURCE(IDR_CONTEXT_MENU));
6025   hMenu = GetSubMenu(hMenuLoad, 0);
6026   InitBodyContextMenu(hMenu);
6027   
6028   UpdateMenu(hMenu);
6029
6030   TrackPopupMenu(hMenu,TPM_LEFTALIGN | TPM_RIGHTBUTTON,pt.x,pt.y,0,hMain,NULL);
6031
6032   DestroyMenu(hMenuLoad);
6033}
6034
6035
6036
6037static BOOL HandleScreenShotContextMenu(HWND hWnd, WPARAM wParam, LPARAM lParam)
6038{
6039   HMENU hMenuLoad;
6040   HMENU hMenu;
6041   POINT pt;
6042
6043   if ((HWND)wParam != GetDlgItem(hWnd, IDC_SSPICTURE) && (HWND)wParam != GetDlgItem(hWnd, IDC_SSFRAME))
6044      return FALSE;
6045
6046   pt.x = GET_X_LPARAM(lParam);
6047   pt.y = GET_Y_LPARAM(lParam);
6048   if (pt.x < 0 && pt.y < 0)
6049      GetCursorPos(&pt);
6050
6051   hMenuLoad = LoadMenu(hInst, MAKEINTRESOURCE(IDR_CONTEXT_SCREENSHOT));
6052   hMenu = GetSubMenu(hMenuLoad, 0);
6053
6054   UpdateMenu(hMenu);
6055
6056   TrackPopupMenu(hMenu,TPM_LEFTALIGN | TPM_RIGHTBUTTON,pt.x,pt.y,0,hWnd,NULL);
6057
6058   DestroyMenu(hMenuLoad);
6059
6060   return TRUE;
6061}
6062
6063static void UpdateMenu(HMENU hMenu)
6064{
6065   TCHAR         buf[200];
6066   MENUITEMINFO   mItem;
6067   int          nGame = Picker_GetSelectedItem(hwndList);
6068   LPTREEFOLDER lpFolder = GetCurrentFolder();
6069   int i;
6070   const char *pParent;
6071   TCHAR* t_description;
6072
6073   if (have_selection)
6074   {
6075      t_description = tstring_from_utf8(ConvertAmpersandString(ModifyThe(drivers[nGame]->description)));
6076      if( !t_description )
6077         return;
6078     
6079      _sntprintf(buf, ARRAY_LENGTH(buf), g_szPlayGameString, t_description);
6080
6081      mItem.cbSize    = sizeof(mItem);
6082      mItem.fMask     = MIIM_TYPE;
6083      mItem.fType     = MFT_STRING;
6084      mItem.dwTypeData = buf;
6085      mItem.cch       = _tcslen(mItem.dwTypeData);
6086
6087      SetMenuItemInfo(hMenu, ID_FILE_PLAY, FALSE, &mItem);
6088
6089      EnableMenuItem(hMenu, ID_CONTEXT_SELECT_RANDOM, MF_ENABLED);
6090     
6091      free(t_description);
6092   }
6093   else
6094   {
6095      EnableMenuItem(hMenu, ID_FILE_PLAY,          MF_GRAYED);
6096      EnableMenuItem(hMenu, ID_FILE_PLAY_RECORD,      MF_GRAYED);
6097      EnableMenuItem(hMenu, ID_GAME_PROPERTIES,      MF_GRAYED);
6098      EnableMenuItem(hMenu, ID_CONTEXT_SELECT_RANDOM, MF_GRAYED);
6099   }
6100
6101   if (oldControl)
6102   {
6103      EnableMenuItem(hMenu, ID_CUSTOMIZE_FIELDS, MF_GRAYED);
6104      EnableMenuItem(hMenu, ID_GAME_PROPERTIES,  MF_GRAYED);
6105      EnableMenuItem(hMenu, ID_OPTIONS_DEFAULTS, MF_GRAYED);
6106   }
6107
6108   if (lpFolder->m_dwFlags & F_CUSTOM)
6109   {
6110       EnableMenuItem(hMenu,ID_CONTEXT_REMOVE_CUSTOM,MF_ENABLED);
6111      EnableMenuItem(hMenu,ID_CONTEXT_RENAME_CUSTOM,MF_ENABLED);
6112   }
6113   else
6114   {
6115       EnableMenuItem(hMenu,ID_CONTEXT_REMOVE_CUSTOM,MF_GRAYED);
6116      EnableMenuItem(hMenu,ID_CONTEXT_RENAME_CUSTOM,MF_GRAYED);
6117   }
6118   pParent = GetFolderNameByID(lpFolder->m_nParent+1);
6119
6120   if (lpFolder->m_dwFlags & F_INIEDIT)
6121      EnableMenuItem(hMenu,ID_FOLDER_PROPERTIES,MF_ENABLED);
6122   else
6123      EnableMenuItem(hMenu,ID_FOLDER_PROPERTIES,MF_GRAYED);
6124
6125   CheckMenuRadioItem(hMenu, ID_VIEW_TAB_SCREENSHOT, ID_VIEW_TAB_HISTORY,
6126                  ID_VIEW_TAB_SCREENSHOT + TabView_GetCurrentTab(hTabCtrl), MF_BYCOMMAND);
6127
6128   // set whether we're showing the tab control or not
6129   if (bShowTabCtrl)
6130      CheckMenuItem(hMenu,ID_VIEW_PAGETAB,MF_BYCOMMAND | MF_CHECKED);
6131   else
6132      CheckMenuItem(hMenu,ID_VIEW_PAGETAB,MF_BYCOMMAND | MF_UNCHECKED);
6133
6134
6135   for (i=0;i<MAX_TAB_TYPES;i++)
6136   {
6137      // disable menu items for tabs we're not currently showing
6138      if (GetShowTab(i))
6139         EnableMenuItem(hMenu,ID_VIEW_TAB_SCREENSHOT + i,MF_BYCOMMAND | MF_ENABLED);
6140      else
6141         EnableMenuItem(hMenu,ID_VIEW_TAB_SCREENSHOT + i,MF_BYCOMMAND | MF_GRAYED);
6142
6143      // check toggle menu items
6144      if (GetShowTab(i))
6145         CheckMenuItem(hMenu, ID_TOGGLE_TAB_SCREENSHOT + i,MF_BYCOMMAND | MF_CHECKED);
6146      else
6147         CheckMenuItem(hMenu, ID_TOGGLE_TAB_SCREENSHOT + i,MF_BYCOMMAND | MF_UNCHECKED);
6148   }
6149
6150   for (i=0;i<MAX_FOLDERS;i++)
6151   {
6152      if (GetShowFolder(i))
6153         CheckMenuItem(hMenu,ID_CONTEXT_SHOW_FOLDER_START + i,MF_BYCOMMAND | MF_CHECKED);
6154      else
6155         CheckMenuItem(hMenu,ID_CONTEXT_SHOW_FOLDER_START + i,MF_BYCOMMAND | MF_UNCHECKED);
6156   }
6157
6158}
6159
6160void InitTreeContextMenu(HMENU hTreeMenu)
6161{
6162   MENUITEMINFO mii;
6163   HMENU hMenu;
6164   int i;
6165   extern FOLDERDATA g_folderData[];
6166
6167   ZeroMemory(&mii,sizeof(mii));
6168   mii.cbSize = sizeof(mii);
6169
6170   mii.wID = -1;
6171   mii.fMask = MIIM_SUBMENU | MIIM_ID;
6172
6173   hMenu = GetSubMenu(hTreeMenu, 0);
6174
6175   if (GetMenuItemInfo(hMenu,3,TRUE,&mii) == FALSE)
6176   {
6177      dprintf("can't find show folders context menu");
6178      return;
6179   }
6180
6181   if (mii.hSubMenu == NULL)
6182   {
6183      dprintf("can't find submenu for show folders context menu");
6184      return;
6185   }
6186
6187   hMenu = mii.hSubMenu;
6188   
6189   for (i=0;g_folderData[i].m_lpTitle != NULL;i++)
6190   {
6191      TCHAR* t_title = tstring_from_utf8(g_folderData[i].m_lpTitle);
6192      if( !t_title )
6193         return;
6194     
6195      mii.fMask = MIIM_TYPE | MIIM_ID;
6196      mii.fType = MFT_STRING;
6197      mii.dwTypeData = t_title;
6198      mii.cch = _tcslen(mii.dwTypeData);
6199      mii.wID = ID_CONTEXT_SHOW_FOLDER_START + g_folderData[i].m_nFolderId;
6200
6201
6202      // menu in resources has one empty item (needed for the submenu to setup properly)
6203      // so overwrite this one, append after
6204      if (i == 0)
6205         SetMenuItemInfo(hMenu,ID_CONTEXT_SHOW_FOLDER_START,FALSE,&mii);
6206      else
6207         InsertMenuItem(hMenu,i,FALSE,&mii);
6208         
6209      free(t_title);
6210   }
6211
6212}
6213
6214void InitBodyContextMenu(HMENU hBodyContextMenu)
6215{
6216   LPTREEFOLDER lpFolder;
6217   TCHAR tmp[30];
6218   MENUITEMINFO mii;
6219   ZeroMemory(&mii,sizeof(mii));
6220   mii.cbSize = sizeof(mii);
6221
6222   if (GetMenuItemInfo(hBodyContextMenu,ID_FOLDER_SOURCEPROPERTIES,FALSE,&mii) == FALSE)
6223   {
6224      dprintf("can't find show folders context menu");
6225      return;
6226   }
6227   lpFolder = GetFolderByName(FOLDER_SOURCE, GetDriverFilename(Picker_GetSelectedItem(hwndList)) );
6228   _sntprintf(tmp,ARRAY_LENGTH(tmp),TEXT("Properties for %s"),lpFolder->m_lptTitle );
6229   mii.fMask = MIIM_TYPE | MIIM_ID;
6230   mii.fType = MFT_STRING;
6231   mii.dwTypeData = tmp;
6232   mii.cch = _tcslen(mii.dwTypeData);
6233   mii.wID = ID_FOLDER_SOURCEPROPERTIES;
6234
6235
6236   // menu in resources has one default item
6237   // so overwrite this one
6238   SetMenuItemInfo(hBodyContextMenu,ID_FOLDER_SOURCEPROPERTIES,FALSE,&mii);
6239   if( ! DriverIsVector(Picker_GetSelectedItem(hwndList) ) )
6240      EnableMenuItem(hBodyContextMenu, ID_FOLDER_VECTORPROPERTIES, MF_GRAYED);
6241}
6242
6243
6244void ToggleShowFolder(int folder)
6245{
6246   int current_id = GetCurrentFolderID();
6247
6248   SetWindowRedraw(hwndList,FALSE);
6249
6250   SetShowFolder(folder,!GetShowFolder(folder));
6251
6252   ResetTreeViewFolders();
6253   SelectTreeViewFolder(current_id);
6254
6255   SetWindowRedraw(hwndList,TRUE);
6256}
6257
6258static LRESULT CALLBACK HistoryWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
6259{
6260   if (hBackground)
6261   {
6262      switch (uMsg)
6263      {
6264       case WM_MOUSEMOVE:
6265      {
6266         if (MouseHasBeenMoved())
6267            ShowCursor(TRUE);
6268         break;
6269      }
6270   
6271      case WM_ERASEBKGND:
6272         return TRUE;
6273      case WM_PAINT:
6274      {
6275         POINT p = { 0, 0 };
6276           
6277         /* get base point of background bitmap */
6278         MapWindowPoints(hWnd,hTreeView,&p,1);
6279         PaintBackgroundImage(hWnd, NULL, p.x, p.y);
6280         /* to ensure our parent procedure repaints the whole client area */
6281         InvalidateRect(hWnd, NULL, FALSE);
6282         break;
6283      }
6284      }
6285   }
6286   return CallWindowProc(g_lpHistoryWndProc, hWnd, uMsg, wParam, lParam);
6287}
6288
6289static LRESULT CALLBACK PictureFrameWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
6290{
6291   switch (uMsg)
6292   {
6293   case WM_MOUSEMOVE:
6294    {
6295      if (MouseHasBeenMoved())
6296         ShowCursor(TRUE);
6297      break;
6298    }
6299 
6300    case WM_NCHITTEST :
6301   {
6302      POINT pt;
6303      RECT  rect;
6304      HWND hHistory = GetDlgItem(hMain, IDC_HISTORY);
6305
6306      pt.x = LOWORD(lParam);
6307      pt.y = HIWORD(lParam);
6308      GetWindowRect(hHistory, &rect);
6309      // check if they clicked on the picture area (leave 6 pixel no man's land
6310      // by the history window to reduce mistaken clicks)
6311      // no more no man's land, the Cursor changes when Edit control is left, should be enough feedback
6312      if (have_history &&       
6313         ( ( (TabView_GetCurrentTab(hTabCtrl) == TAB_HISTORY) ||
6314          (TabView_GetCurrentTab(hTabCtrl) == GetHistoryTab() && GetShowTab(TAB_HISTORY) == FALSE) ||
6315         (TAB_ALL == GetHistoryTab() && GetShowTab(TAB_HISTORY) == FALSE) ) &&
6316//           (rect.top - 6) < pt.y && pt.y < (rect.bottom + 6) ) )
6317                 PtInRect( &rect, pt ) ) )
6318
6319      {
6320         return HTTRANSPARENT;
6321      }
6322      else
6323      {
6324         return HTCLIENT;
6325      }
6326   }
6327   break;
6328   case WM_CONTEXTMENU:
6329      if ( HandleScreenShotContextMenu(hWnd, wParam, lParam))
6330         return FALSE;
6331      break;
6332   }
6333
6334   if (hBackground)
6335   {
6336      switch (uMsg)
6337      {
6338      case WM_ERASEBKGND :
6339         return TRUE;
6340      case WM_PAINT :
6341      {
6342         RECT rect,nodraw_rect;
6343         HRGN region,nodraw_region;
6344         POINT p = { 0, 0 };
6345
6346         /* get base point of background bitmap */
6347         MapWindowPoints(hWnd,hTreeView,&p,1);
6348
6349         /* get big region */
6350         GetClientRect(hWnd,&rect);
6351         region = CreateRectRgnIndirect(&rect);
6352
6353         if (IsWindowVisible(GetDlgItem(hMain,IDC_HISTORY)))
6354         {
6355            /* don't draw over this window */
6356            GetWindowRect(GetDlgItem(hMain,IDC_HISTORY),&nodraw_rect);
6357            MapWindowPoints(HWND_DESKTOP,hWnd,(LPPOINT)&nodraw_rect,2);
6358            nodraw_region = CreateRectRgnIndirect(&nodraw_rect);
6359            CombineRgn(region,region,nodraw_region,RGN_DIFF);
6360            DeleteObject(nodraw_region);
6361         }
6362         if (IsWindowVisible(GetDlgItem(hMain,IDC_SSPICTURE)))
6363         {
6364            /* don't draw over this window */
6365            GetWindowRect(GetDlgItem(hMain,IDC_SSPICTURE),&nodraw_rect);
6366            MapWindowPoints(HWND_DESKTOP,hWnd,(LPPOINT)&nodraw_rect,2);
6367            nodraw_region = CreateRectRgnIndirect(&nodraw_rect);
6368            CombineRgn(region,region,nodraw_region,RGN_DIFF);
6369            DeleteObject(nodraw_region);
6370         }
6371
6372         PaintBackgroundImage(hWnd,region,p.x,p.y);
6373
6374         DeleteObject(region);
6375
6376         /* to ensure our parent procedure repaints the whole client area */
6377         InvalidateRect(hWnd, NULL, FALSE);
6378
6379         break;
6380      }
6381      }
6382   }
6383   return CallWindowProc(g_lpPictureFrameWndProc, hWnd, uMsg, wParam, lParam);
6384}
6385
6386static LRESULT CALLBACK PictureWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
6387{
6388   switch (uMsg)
6389   {
6390   case WM_ERASEBKGND :
6391      return TRUE;
6392   case WM_PAINT :
6393   {
6394      PAINTSTRUCT ps;
6395      HDC   hdc,hdc_temp;
6396      RECT rect;
6397      HBITMAP old_bitmap;
6398
6399      int width,height;
6400
6401      RECT rect2;
6402      HBRUSH hBrush;
6403      HBRUSH holdBrush;
6404      HRGN region1, region2;
6405      int nBordersize;
6406      nBordersize = GetScreenshotBorderSize();
6407      hBrush = CreateSolidBrush(GetScreenshotBorderColor());
6408
6409      hdc = BeginPaint(hWnd,&ps);
6410
6411      hdc_temp = CreateCompatibleDC(hdc);
6412      if (ScreenShotLoaded())
6413      {
6414         width = GetScreenShotWidth();
6415         height = GetScreenShotHeight();
6416
6417         old_bitmap = SelectObject(hdc_temp,GetScreenShotHandle());
6418      }
6419      else
6420      {
6421         BITMAP bmp;
6422
6423         GetObject(hMissing_bitmap,sizeof(BITMAP),&bmp);
6424         width = bmp.bmWidth;
6425         height = bmp.bmHeight;
6426
6427         old_bitmap = SelectObject(hdc_temp,hMissing_bitmap);
6428      }
6429
6430      GetClientRect(hWnd,&rect);
6431
6432      rect2 = rect;
6433      //Configurable Borders around images
6434      rect.bottom -= nBordersize;
6435      if( rect.bottom < 0)
6436         rect.bottom = rect2.bottom;
6437      rect.right -= nBordersize;
6438      if( rect.right < 0)
6439         rect.right = rect2.right;
6440      rect.top += nBordersize;
6441      if( rect.top > rect.bottom )
6442         rect.top = rect2.top;
6443      rect.left += nBordersize;
6444      if( rect.left > rect.right )
6445         rect.left = rect2.left;
6446      region1 = CreateRectRgnIndirect(&rect);
6447      region2 = CreateRectRgnIndirect(&rect2);
6448      CombineRgn(region2,region2,region1,RGN_DIFF);
6449      holdBrush = SelectObject(hdc, hBrush);
6450
6451      FillRgn(hdc,region2, hBrush );
6452      SelectObject(hdc, holdBrush);
6453      DeleteObject(hBrush);
6454
6455      SetStretchBltMode(hdc,STRETCH_HALFTONE);
6456      StretchBlt(hdc,nBordersize,nBordersize,rect.right-rect.left,rect.bottom-rect.top,
6457               hdc_temp,0,0,width,height,SRCCOPY);
6458      SelectObject(hdc_temp,old_bitmap);
6459      DeleteDC(hdc_temp);
6460
6461      EndPaint(hWnd,&ps);
6462
6463      return TRUE;
6464   }
6465   }
6466
6467   return CallWindowProc(g_lpPictureWndProc, hWnd, uMsg, wParam, lParam);
6468}
6469
6470void RemoveCurrentGameCustomFolder(void)
6471{
6472    RemoveGameCustomFolder(Picker_GetSelectedItem(hwndList));
6473}
6474
6475void RemoveGameCustomFolder(int driver_index)
6476{
6477    int i;
6478   TREEFOLDER **folders;
6479   int num_folders;
6480
6481   GetFolders(&folders,&num_folders);
6482   
6483   for (i=0;i<num_folders;i++)
6484   {
6485       if (folders[i]->m_dwFlags & F_CUSTOM && folders[i]->m_nFolderId == GetCurrentFolderID())
6486      {
6487          int current_pick_index;
6488
6489          RemoveFromCustomFolder(folders[i],driver_index);
6490
6491         if (driver_index == Picker_GetSelectedItem(hwndList))
6492         {
6493            /* if we just removed the current game,
6494              move the current selection so that when we rebuild the listview it
6495              leaves the cursor on next or previous one */
6496         
6497            current_pick_index = GetSelectedPick();
6498            Picker_SetSelectedPick(hwndList, GetSelectedPick() + 1);
6499            if (current_pick_index == GetSelectedPick()) /* we must have deleted the last item */
6500              Picker_SetSelectedPick(hwndList, GetSelectedPick() - 1);
6501         }
6502
6503         ResetListView();
6504         return;
6505      }
6506   }
6507   MessageBox(GetMainWindow(), TEXT("Error searching for custom folder"), TEXT(MAME32NAME), MB_OK | MB_ICONERROR);
6508
6509}
6510
6511
6512void BeginListViewDrag(NM_LISTVIEW *pnmv)
6513{
6514    LV_ITEM lvi;
6515   POINT pt;
6516
6517   lvi.iItem = pnmv->iItem;
6518   lvi.mask    = LVIF_PARAM;
6519   ListView_GetItem(hwndList, &lvi);
6520
6521   game_dragged = lvi.lParam;
6522
6523   pt.x = 0;
6524   pt.y = 0;
6525
6526   /* Tell the list view control to create an image to use
6527      for dragging. */
6528    himl_drag = ListView_CreateDragImage(hwndList,pnmv->iItem,&pt);
6529 
6530    /* Start the drag operation. */
6531    ImageList_BeginDrag(himl_drag, 0, 0, 0);
6532
6533   pt = pnmv->ptAction;
6534   ClientToScreen(hwndList,&pt);
6535   ImageList_DragEnter(GetDesktopWindow(),pt.x,pt.y);
6536
6537    /* Hide the mouse cursor, and direct mouse input to the
6538      parent window. */
6539    SetCapture(hMain);
6540
6541   prev_drag_drop_target = NULL;
6542
6543    g_listview_dragging = TRUE;
6544
6545}
6546
6547void MouseMoveListViewDrag(POINTS p)
6548{
6549   HTREEITEM htiTarget;
6550   TV_HITTESTINFO tvht;
6551
6552   POINT pt;
6553   pt.x = p.x;
6554   pt.y = p.y;
6555
6556   ClientToScreen(hMain,&pt);
6557
6558   ImageList_DragMove(pt.x,pt.y);
6559
6560   MapWindowPoints(GetDesktopWindow(),hTreeView,&pt,1);
6561
6562   tvht.pt = pt;
6563   htiTarget = TreeView_HitTest(hTreeView,&tvht);
6564
6565   if (htiTarget != prev_drag_drop_target)
6566   {
6567      ImageList_DragShowNolock(FALSE);
6568      if (htiTarget != NULL)
6569         TreeView_SelectDropTarget(hTreeView,htiTarget);
6570      else
6571         TreeView_SelectDropTarget(hTreeView,NULL);
6572      ImageList_DragShowNolock(TRUE);
6573     
6574      prev_drag_drop_target = htiTarget;
6575   }
6576}
6577
6578void ButtonUpListViewDrag(POINTS p)
6579{
6580    POINT pt;
6581    HTREEITEM htiTarget;
6582   TV_HITTESTINFO tvht;
6583   TVITEM tvi;
6584   
6585   ReleaseCapture();
6586
6587    ImageList_DragLeave(hwndList);
6588    ImageList_EndDrag();
6589   ImageList_Destroy(himl_drag);
6590
6591   TreeView_SelectDropTarget(hTreeView,NULL);
6592
6593   g_listview_dragging = FALSE;
6594
6595   /* see where the game was dragged */
6596
6597   pt.x = p.x;
6598   pt.y = p.y;
6599
6600   MapWindowPoints(hMain,hTreeView,&pt,1);
6601
6602   tvht.pt = pt;
6603   htiTarget = TreeView_HitTest(hTreeView,&tvht);
6604   if (htiTarget == NULL)
6605   {
6606      LVHITTESTINFO lvhtti;
6607      LPTREEFOLDER folder;
6608      RECT rcList;
6609
6610      /* the user dragged a game onto something other than the treeview */
6611      /* try to remove if we're in a custom folder */
6612
6613      /* see if it was dragged within the list view; if so, ignore */
6614
6615      MapWindowPoints(hTreeView,hwndList,&pt,1);
6616      lvhtti.pt = pt;
6617      GetWindowRect(hwndList, &rcList);
6618      ClientToScreen(hwndList, &pt);
6619      if( PtInRect(&rcList, pt) != 0 )
6620         return;
6621
6622      folder = GetCurrentFolder();
6623      if (folder->m_dwFlags & F_CUSTOM)
6624      {
6625         /* dragged out of a custom folder, so let's remove it */
6626         RemoveCurrentGameCustomFolder();
6627      }
6628      return;
6629   }
6630
6631
6632   tvi.lParam = 0;
6633   tvi.mask  = TVIF_PARAM | TVIF_HANDLE;
6634   tvi.hItem = htiTarget;
6635
6636   if (TreeView_GetItem(hTreeView, &tvi))
6637   {
6638      LPTREEFOLDER folder = (LPTREEFOLDER)tvi.lParam;
6639      AddToCustomFolder(folder,game_dragged);
6640   }
6641
6642}
6643
6644static LPTREEFOLDER GetSelectedFolder(void)
6645{
6646   HTREEITEM htree;
6647   TVITEM tvi;
6648   htree = TreeView_GetSelection(hTreeView);
6649   if(htree != NULL)
6650   {
6651      tvi.hItem = htree;
6652      tvi.mask = TVIF_PARAM;
6653      TreeView_GetItem(hTreeView,&tvi);
6654      return (LPTREEFOLDER)tvi.lParam;
6655   }
6656   return NULL;
6657}
6658
6659static HICON GetSelectedFolderIcon(void)
6660{
6661   HTREEITEM htree;
6662   TVITEM tvi;
6663   HIMAGELIST hSmall_icon;
6664   LPTREEFOLDER folder;
6665   htree = TreeView_GetSelection(hTreeView);
6666
6667   if (htree != NULL)
6668   {
6669      tvi.hItem = htree;
6670      tvi.mask = TVIF_PARAM;
6671      TreeView_GetItem(hTreeView,&tvi);
6672     
6673      folder = (LPTREEFOLDER)tvi.lParam;
6674      //hSmall_icon = TreeView_GetImageList(hTreeView,(int)tvi.iImage);
6675      hSmall_icon = NULL;
6676      return ImageList_GetIcon(hSmall_icon, tvi.iImage, ILD_TRANSPARENT);
6677   }
6678   return NULL;
6679}
6680
6681/* Updates all currently displayed Items in the List with the latest Data*/
6682void UpdateListView(void)
6683{
6684   if( (GetViewMode() == VIEW_GROUPED) || (GetViewMode() == VIEW_DETAILS ) )
6685      ListView_RedrawItems(hwndList,ListView_GetTopIndex(hwndList),
6686                      ListView_GetTopIndex(hwndList)+ ListView_GetCountPerPage(hwndList) );
6687}
6688
6689void CalculateBestScreenShotRect(HWND hWnd, RECT *pRect, BOOL restrict_height)
6690{
6691   int    destX, destY;
6692   int    destW, destH;
6693   int      nBorder;
6694   RECT   rect;
6695   /* for scaling */       
6696   int x, y;
6697   int rWidth, rHeight;
6698   double scale;
6699   BOOL bReduce = FALSE;
6700
6701   GetClientRect(hWnd, &rect);
6702
6703   // Scale the bitmap to the frame specified by the passed in hwnd
6704   if (ScreenShotLoaded())
6705   {
6706      x = GetScreenShotWidth();
6707      y = GetScreenShotHeight();
6708   }
6709   else
6710   {
6711      BITMAP bmp;
6712      GetObject(hMissing_bitmap,sizeof(BITMAP),&bmp);
6713
6714      x = bmp.bmWidth;
6715      y = bmp.bmHeight;
6716   }
6717   rWidth   = (rect.right  - rect.left);
6718   rHeight = (rect.bottom - rect.top);
6719
6720   /* Limit the screen shot to max height of 264 */
6721   if (restrict_height == TRUE && rHeight > 264)
6722   {
6723      rect.bottom = rect.top + 264;
6724      rHeight = 264;
6725   }
6726
6727   /* If the bitmap does NOT fit in the screenshot area */
6728   if (x > rWidth - 10 || y > rHeight - 10)
6729   {
6730      rect.right   -= 10;
6731      rect.bottom -= 10;
6732      rWidth   -= 10;
6733      rHeight -= 10;
6734      bReduce = TRUE;
6735      /* Try to scale it properly */
6736      /*   assumes square pixels, doesn't consider aspect ratio */
6737      if (x > y)
6738         scale = (double)rWidth / x;
6739      else
6740         scale = (double)rHeight / y;
6741
6742      destW = (int)(x * scale);
6743      destH = (int)(y * scale);
6744
6745      /* If it's still too big, scale again */
6746      if (destW > rWidth || destH > rHeight)
6747      {
6748         if (destW > rWidth)
6749            scale = (double)rWidth   / destW;
6750         else
6751            scale = (double)rHeight / destH;
6752
6753         destW = (int)(destW * scale);
6754         destH = (int)(destH * scale);
6755      }
6756   }
6757   else
6758   {
6759      if (GetStretchScreenShotLarger())
6760      {
6761         rect.right   -= 10;
6762         rect.bottom -= 10;
6763         rWidth   -= 10;
6764         rHeight -= 10;
6765         bReduce = TRUE;
6766         // Try to scale it properly
6767         // assumes square pixels, doesn't consider aspect ratio
6768         if (x < y)
6769            scale = (double)rWidth / x;
6770         else
6771            scale = (double)rHeight / y;
6772         
6773         destW = (int)(x * scale);
6774         destH = (int)(y * scale);
6775         
6776         // If it's too big, scale again
6777         if (destW > rWidth || destH > rHeight)
6778         {
6779            if (destW > rWidth)
6780               scale = (double)rWidth   / destW;
6781            else
6782               scale = (double)rHeight / destH;
6783           
6784            destW = (int)(destW * scale);
6785            destH = (int)(destH * scale);
6786         }
6787      }
6788      else
6789      {
6790         // Use the bitmaps size if it fits
6791         destW = x;
6792         destH = y;
6793      }
6794
6795   }
6796
6797
6798   destX = ((rWidth  - destW) / 2);
6799   destY = ((rHeight - destH) / 2);
6800
6801   if (bReduce)
6802   {
6803      destX += 5;
6804      destY += 5;
6805   }
6806   nBorder = GetScreenshotBorderSize();
6807   if( destX > nBorder+1)
6808      pRect->left   = destX - nBorder;
6809   else
6810      pRect->left   = 2;
6811   if( destY > nBorder+1)
6812      pRect->top     = destY - nBorder;
6813   else
6814      pRect->top     = 2;
6815   if( rWidth >= destX + destW + nBorder)
6816      pRect->right  = destX + destW + nBorder;
6817   else
6818      pRect->right  = rWidth - pRect->left;
6819   if( rHeight >= destY + destH + nBorder)
6820      pRect->bottom = destY + destH + nBorder;
6821   else
6822      pRect->bottom = rHeight - pRect->top;
6823}
6824
6825/*
6826  Switches to either fullscreen or normal mode, based on the
6827  current mode.
6828
6829  POSSIBLE BUGS:
6830  Removing the menu might cause problems later if some
6831  function tries to poll info stored in the menu. Don't
6832  know if you've done that, but this was the only way I
6833  knew to remove the menu dynamically.
6834*/
6835
6836void SwitchFullScreenMode(void)
6837{
6838   LONG lMainStyle;
6839   
6840   if (GetRunFullScreen())
6841   {
6842      // Return to normal
6843
6844      // Restore the menu
6845      SetMenu(hMain, LoadMenu(hInst,MAKEINTRESOURCE(IDR_UI_MENU)));
6846     
6847      // Refresh the checkmarks
6848      CheckMenuItem(GetMenu(hMain), ID_VIEW_FOLDERS, GetShowFolderList() ? MF_CHECKED : MF_UNCHECKED);
6849      CheckMenuItem(GetMenu(hMain), ID_VIEW_TOOLBARS, GetShowToolBar() ? MF_CHECKED : MF_UNCHECKED);   
6850      CheckMenuItem(GetMenu(hMain), ID_VIEW_STATUS, GetShowStatusBar() ? MF_CHECKED : MF_UNCHECKED);
6851      CheckMenuItem(GetMenu(hMain), ID_VIEW_PAGETAB, GetShowTabCtrl() ? MF_CHECKED : MF_UNCHECKED);
6852     
6853      // Add frame to dialog again
6854      lMainStyle = GetWindowLong(hMain, GWL_STYLE);
6855      lMainStyle = lMainStyle | WS_BORDER;
6856      SetWindowLong(hMain, GWL_STYLE, lMainStyle);
6857     
6858      // Show the window maximized
6859      if( GetWindowState() == SW_MAXIMIZE )
6860      {
6861         ShowWindow(hMain, SW_NORMAL);
6862         ShowWindow(hMain, SW_MAXIMIZE);
6863      }
6864      else
6865         ShowWindow(hMain, SW_RESTORE);
6866
6867      SetRunFullScreen(FALSE);
6868   }
6869   else
6870   {
6871      // Set to fullscreen
6872     
6873      // Remove menu
6874      SetMenu(hMain,NULL);
6875
6876      // Frameless dialog (fake fullscreen)
6877      lMainStyle = GetWindowLong(hMain, GWL_STYLE);
6878      lMainStyle = lMainStyle & (WS_BORDER ^ 0xffffffff);
6879      SetWindowLong(hMain, GWL_STYLE, lMainStyle);
6880      if( IsMaximized(hMain) )
6881      {
6882         ShowWindow(hMain, SW_NORMAL);
6883         SetWindowState( SW_MAXIMIZE );
6884      }
6885      ShowWindow(hMain, SW_MAXIMIZE);
6886     
6887      SetRunFullScreen(TRUE);
6888   }
6889}
6890
6891/*
6892  Checks to see if the mouse has been moved since this func
6893  was first called (which is at startup). The reason for
6894  storing the startup coordinates of the mouse is that when
6895  a window is created it generates WM_MOUSEOVER events, even
6896  though the user didn't actually move the mouse. So we need
6897  to know when the WM_MOUSEOVER event is user-triggered.
6898
6899  POSSIBLE BUGS:
6900  Gets polled at every WM_MOUSEMOVE so it might cause lag,
6901  but there's probably another way to code this that's
6902  way better?
6903 
6904*/
6905
6906BOOL MouseHasBeenMoved(void)
6907{
6908    static int mouse_x = -1;
6909    static int mouse_y = -1;
6910   POINT p;
6911
6912   GetCursorPos(&p);
6913
6914    if (mouse_x == -1) // First time
6915    {
6916      mouse_x = p.x;
6917      mouse_y = p.y;
6918    }
6919   
6920   return (p.x != mouse_x || p.y != mouse_y);       
6921}
6922
6923/* End of source file */
src/osd/winui/history.c
r0r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11***************************************************************************/
12 
13/***************************************************************************
14
15  history.c
16
17    history functions.
18
19***************************************************************************/
20
21#define WIN32_LEAN_AND_MEAN
22#include <windows.h>
23#include <stdio.h>
24
25#include <driver.h>
26#include "m32util.h"
27
28#include "datafile.h"
29#include "history.h"
30
31
32/**************************************************************
33 * functions
34 **************************************************************/
35
36// Load indexes from history.dat if found
37char * GetGameHistory(int driver_index)
38{
39   static char buffer[32768];
40   buffer[0] = '\0';
41
42   if (load_driver_history(drivers[driver_index],buffer,sizeof(buffer)) != 0)
43      return buffer;
44
45   return ConvertToWindowsNewlines(buffer);
46}
src/osd/winui/properties.h
r0r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11 ***************************************************************************/
12
13#ifndef PROPERTIES_H
14#define PROPERTIES_H
15
16/* Get title string to display in the top of the property page,
17 * Called also in Audit32.c
18 */
19char * GameInfoTitle(OPTIONS_TYPE opt_type, UINT nIndex);
20
21/* Called in win32ui.c to create the property page */
22void   InitPropertyPage(HINSTANCE hInst, HWND hWnd, HICON hIcon, OPTIONS_TYPE opt_type, int folder_id, int game_num);
23
24#define PROPERTIES_PAGE 0
25#define AUDIT_PAGE      1   
26
27void   InitPropertyPageToPage(HINSTANCE hInst, HWND hWnd, HICON hIcon, OPTIONS_TYPE opt_type, int folder_id, int game_num, int start_page);
28void    InitDefaultPropertyPage(HINSTANCE hInst, HWND hWnd);
29
30/* Get Help ID array for WM_HELP and WM_CONTEXTMENU */
31DWORD   GetHelpIDs(void);
32
33/* Get Game status text string */
34const char *GameInfoStatus(int driver_index, BOOL bRomStatus);
35
36/* Property sheet info for layout.c */
37typedef struct
38{
39   BOOL bOnDefaultPage;
40   BOOL (*pfnFilterProc)(const machine_config *drv, const game_driver *gamedrv);
41   DWORD dwDlgID;
42   DLGPROC pfnDlgProc;
43} PROPERTYSHEETINFO;
44
45extern const PROPERTYSHEETINFO g_propSheets[];
46
47BOOL PropSheetFilter_Vector(const machine_config *drv, const game_driver *gamedrv);
48
49INT_PTR CALLBACK GamePropertiesDialogProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam);
50INT_PTR CALLBACK GameOptionsProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam);
51
52int PropertiesCurrentGame(HWND hDlg);
53
54#endif
src/osd/winui/tabview.c
r0r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11 ***************************************************************************/
12
13#define WIN32_LEAN_AND_MEAN
14#include <windows.h>
15#include <windowsx.h>
16#include <shellapi.h>
17#include <stdio.h>
18#include <ctype.h>
19#include <io.h>
20#include <fcntl.h>
21#include <commctrl.h>
22#include <commdlg.h>
23#include <string.h>
24#include <sys/stat.h>
25#include <wingdi.h>
26#include <time.h>
27#include <assert.h>
28#include <tchar.h>
29#include <stdlib.h>
30
31#include "tabview.h"
32#include "m32util.h"
33#include "strconv.h"
34
35
36struct TabViewInfo
37{
38   const struct TabViewCallbacks *pCallbacks;
39   int nTabCount;
40   WNDPROC pfnParentWndProc;
41};
42
43
44
45static struct TabViewInfo *GetTabViewInfo(HWND hWnd)
46{
47   LONG_PTR l;
48   l = GetWindowLongPtr(hWnd, GWLP_USERDATA);
49   return (struct TabViewInfo *) l;
50}
51
52
53
54static LRESULT CallParentWndProc(WNDPROC pfnParentWndProc,
55   HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
56{
57   LRESULT rc;
58
59   if (!pfnParentWndProc)
60      pfnParentWndProc = GetTabViewInfo(hWnd)->pfnParentWndProc;
61
62   if (IsWindowUnicode(hWnd))
63      rc = CallWindowProcW(pfnParentWndProc, hWnd, message, wParam, lParam);
64   else
65      rc = CallWindowProcA(pfnParentWndProc, hWnd, message, wParam, lParam);
66   return rc;
67}
68
69
70
71static LRESULT CALLBACK TabViewWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
72{
73   struct TabViewInfo *pTabViewInfo;
74   WNDPROC pfnParentWndProc;
75   BOOL bHandled = FALSE;
76   LRESULT rc = 0;
77
78   pTabViewInfo = GetTabViewInfo(hWnd);
79   pfnParentWndProc = pTabViewInfo->pfnParentWndProc;
80
81   switch(message)
82   {
83      case WM_DESTROY:
84         free(pTabViewInfo);
85         SetWindowLongPtr(hWnd, GWLP_WNDPROC, (LONG_PTR) pfnParentWndProc);
86         SetWindowLongPtr(hWnd, GWLP_USERDATA, (LONG_PTR) NULL);
87         break;
88   }
89
90   if (!bHandled)
91      rc = CallParentWndProc(pfnParentWndProc, hWnd, message, wParam, lParam);
92
93   switch(message)
94   {
95      case WM_MOVE:
96      case WM_SIZE:
97         if (pTabViewInfo->pCallbacks->pfnOnMoveSize)
98            pTabViewInfo->pCallbacks->pfnOnMoveSize();
99         break;
100   }
101
102   return rc;
103}
104
105
106
107static int TabView_GetTabFromTabIndex(HWND hwndTabView, int tab_index)
108{
109   int shown_tabs = -1;
110   int i;
111   struct TabViewInfo *pTabViewInfo;
112
113   pTabViewInfo = GetTabViewInfo(hwndTabView);
114
115   for (i = 0; i < pTabViewInfo->nTabCount; i++)
116   {
117      if (!pTabViewInfo->pCallbacks->pfnGetShowTab || pTabViewInfo->pCallbacks->pfnGetShowTab(i))
118      {
119         shown_tabs++;
120         if (shown_tabs == tab_index)
121            return i;
122      }
123   }
124   dprintf("invalid tab index %i", tab_index);
125   return 0;
126}
127
128
129
130int TabView_GetCurrentTab(HWND hwndTabView)
131{
132   struct TabViewInfo *pTabViewInfo;
133   LPCSTR pszTab = NULL;
134   LPCSTR pszThatTab;
135   int i, nTab = -1;
136
137   pTabViewInfo = GetTabViewInfo(hwndTabView);
138
139   if (pTabViewInfo->pCallbacks->pfnGetCurrentTab)
140      pszTab = pTabViewInfo->pCallbacks->pfnGetCurrentTab();
141
142   if (pszTab)
143   {
144      if (pTabViewInfo->pCallbacks->pfnGetTabShortName)
145      {
146         for (i = 0; i < pTabViewInfo->nTabCount; i++)
147         {
148            pszThatTab = pTabViewInfo->pCallbacks->pfnGetTabShortName(i);
149            if (pszThatTab && !mame_stricmp(pszTab, pszThatTab))
150            {
151               nTab = i;
152               break;
153            }
154         }
155      }
156      if (nTab < 0)
157      {
158         nTab = 0;
159         sscanf(pszTab, "%d", &nTab);
160      }
161   }
162   else
163   {
164      nTab = 0;
165   }
166   return nTab;
167}
168
169
170
171void TabView_SetCurrentTab(HWND hwndTabView, int nTab)
172{
173   struct TabViewInfo *pTabViewInfo;
174   LPCSTR pszName;
175   char szBuffer[16];
176
177   pTabViewInfo = GetTabViewInfo(hwndTabView);
178
179   if (pTabViewInfo->pCallbacks->pfnGetTabShortName)
180   {
181      pszName = pTabViewInfo->pCallbacks->pfnGetTabShortName(nTab);
182   }
183   else
184   {
185      snprintf(szBuffer, sizeof(szBuffer) / sizeof(szBuffer[0]),
186         "%d", nTab);
187      pszName = szBuffer;
188   }
189
190   if (pTabViewInfo->pCallbacks->pfnSetCurrentTab)
191      pTabViewInfo->pCallbacks->pfnSetCurrentTab(pszName);
192}
193
194
195
196static int TabView_GetCurrentTabIndex(HWND hwndTabView)
197{
198   int shown_tabs = 0;
199   int i;
200   int nCurrentTab;
201   struct TabViewInfo *pTabViewInfo;
202
203   pTabViewInfo = GetTabViewInfo(hwndTabView);
204   nCurrentTab = TabView_GetCurrentTab(hwndTabView);
205
206   for (i = 0; i < pTabViewInfo->nTabCount; i++)
207   {
208      if (i == nCurrentTab)
209         break;
210
211      if (!pTabViewInfo->pCallbacks->pfnGetShowTab || pTabViewInfo->pCallbacks->pfnGetShowTab(i))
212         shown_tabs++;
213   }
214   return shown_tabs;
215}
216
217
218
219void TabView_UpdateSelection(HWND hwndTabView)
220{
221   TabCtrl_SetCurSel(hwndTabView, TabView_GetCurrentTabIndex(hwndTabView));
222}
223
224
225
226BOOL TabView_HandleNotify(LPNMHDR lpNmHdr)
227{
228   HWND hwndTabView;
229   struct TabViewInfo *pTabViewInfo;
230   BOOL bResult = FALSE;
231   int nTabIndex, nTab;
232
233   hwndTabView = lpNmHdr->hwndFrom;
234   pTabViewInfo = GetTabViewInfo(hwndTabView);
235
236   switch (lpNmHdr->code)
237   {
238      case TCN_SELCHANGE:
239         nTabIndex = TabCtrl_GetCurSel(hwndTabView);
240         nTab = TabView_GetTabFromTabIndex(hwndTabView, nTabIndex);
241         TabView_SetCurrentTab(hwndTabView, nTab);
242         if (pTabViewInfo->pCallbacks->pfnOnSelectionChanged)
243            pTabViewInfo->pCallbacks->pfnOnSelectionChanged();
244         bResult = TRUE;
245         break;
246   }
247   return bResult;
248}
249
250
251
252void TabView_CalculateNextTab(HWND hwndTabView)
253{
254   struct TabViewInfo *pTabViewInfo;
255   int i;
256   int nCurrentTab;
257
258   pTabViewInfo = GetTabViewInfo(hwndTabView);
259
260   // at most loop once through all options
261   for (i = 0; i < pTabViewInfo->nTabCount; i++)
262   {
263      nCurrentTab = TabView_GetCurrentTab(hwndTabView);
264      TabView_SetCurrentTab(hwndTabView, (nCurrentTab + 1) % pTabViewInfo->nTabCount);
265      nCurrentTab = TabView_GetCurrentTab(hwndTabView);
266
267      if (!pTabViewInfo->pCallbacks->pfnGetShowTab || pTabViewInfo->pCallbacks->pfnGetShowTab(nCurrentTab))
268      {
269         // this tab is being shown, so we're all set
270         return;
271      }
272   }
273}
274
275
276
277void TabView_Reset(HWND hwndTabView)
278{
279   struct TabViewInfo *pTabViewInfo;
280   TC_ITEM tci;
281   int i;
282   TCHAR* t_text;
283
284   pTabViewInfo = GetTabViewInfo(hwndTabView);
285
286   TabCtrl_DeleteAllItems(hwndTabView);
287
288   memset(&tci, 0, sizeof(tci));
289   tci.mask = TCIF_TEXT;
290   tci.cchTextMax = 20;
291
292   for (i = 0; i < pTabViewInfo->nTabCount; i++)
293   {
294      if (!pTabViewInfo->pCallbacks->pfnGetShowTab || pTabViewInfo->pCallbacks->pfnGetShowTab(i))
295      {
296         t_text = tstring_from_utf8(pTabViewInfo->pCallbacks->pfnGetTabLongName(i));
297         if( !t_text )
298            return;
299         tci.pszText = t_text;
300         TabCtrl_InsertItem(hwndTabView, i, &tci);
301         free(t_text);
302      }
303   }
304   TabView_UpdateSelection(hwndTabView);
305}
306
307
308
309BOOL SetupTabView(HWND hwndTabView, const struct TabViewOptions *pOptions)
310{
311   struct TabViewInfo *pTabViewInfo;
312   LONG_PTR l;
313   BOOL bShowTabView;
314
315   assert(hwndTabView);
316
317   // Allocate the list view struct
318   pTabViewInfo = (struct TabViewInfo *) malloc(sizeof(struct TabViewInfo));
319   if (!pTabViewInfo)
320      return FALSE;
321
322   // And fill it out
323   memset(pTabViewInfo, 0, sizeof(*pTabViewInfo));
324   pTabViewInfo->pCallbacks = pOptions->pCallbacks;
325   pTabViewInfo->nTabCount = pOptions->nTabCount;
326
327   // Hook in our wndproc and userdata pointer
328   l = GetWindowLongPtr(hwndTabView, GWLP_WNDPROC);
329   pTabViewInfo->pfnParentWndProc = (WNDPROC) l;
330   SetWindowLongPtr(hwndTabView, GWLP_USERDATA, (LONG_PTR) pTabViewInfo);
331   SetWindowLongPtr(hwndTabView, GWLP_WNDPROC, (LONG_PTR) TabViewWndProc);
332
333   bShowTabView = pTabViewInfo->pCallbacks->pfnGetShowTabCtrl ?
334      pTabViewInfo->pCallbacks->pfnGetShowTabCtrl() : TRUE;
335   ShowWindow(hwndTabView, bShowTabView ? SW_SHOW : SW_HIDE);
336
337   TabView_Reset(hwndTabView);
338   if (pTabViewInfo->pCallbacks->pfnOnSelectionChanged)
339      pTabViewInfo->pCallbacks->pfnOnSelectionChanged();
340   return TRUE;
341}
342
343
src/osd/winui/columnedit.c
r0r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11***************************************************************************/
12 
13/***************************************************************************
14
15  ColumnEdit.c
16
17  Column Edit dialog
18
19***************************************************************************/
20
21#define WIN32_LEAN_AND_MEAN
22#include <windows.h>
23#include <windowsx.h>
24#include <shellapi.h>
25#include <commctrl.h>
26#include <commdlg.h>
27
28#include "resource.h"
29#include "bitmask.h"
30#include "m32opts.h"
31#include "screenshot.h"
32#include "win32ui.h"
33
34// Returns TRUE if successful
35int DoExchangeItem(HWND hFrom, HWND hTo, int nMinItem)
36{
37   LV_ITEM lvi;
38   TCHAR   buf[80];
39   int    nFrom, nTo;
40
41   nFrom = ListView_GetItemCount(hFrom);
42   nTo   = ListView_GetItemCount(hTo);
43
44   lvi.iItem = ListView_GetNextItem(hFrom, -1, LVIS_SELECTED | LVIS_FOCUSED);
45   if (lvi.iItem < nMinItem)
46   {
47      if (lvi.iItem != -1) // Can't remove the first column
48         MessageBox(0, TEXT("Cannot Move Selected Item"), TEXT("Move Item"), IDOK);
49      SetFocus(hFrom);
50      return FALSE;
51   }
52   lvi.iSubItem   = 0;
53   lvi.mask      = LVIF_PARAM | LVIF_TEXT;
54   lvi.pszText    = buf;
55   lvi.cchTextMax = sizeof(buf);
56   if (ListView_GetItem(hFrom, &lvi))
57   {
58      // Add this item to the Show and delete it from Available
59      ListView_DeleteItem(hFrom, lvi.iItem);
60      lvi.iItem = ListView_GetItemCount(hTo);
61      ListView_InsertItem(hTo, &lvi);
62      ListView_SetItemState(hTo, lvi.iItem,
63                       LVIS_FOCUSED | LVIS_SELECTED,
64                       LVIS_FOCUSED | LVIS_SELECTED);
65      SetFocus(hTo);
66      return lvi.iItem;
67   }
68   return FALSE;
69}
70
71void DoMoveItem( HWND hWnd, BOOL bDown)
72{
73   LV_ITEM lvi;
74   TCHAR   buf[80];
75   int    nMaxpos;
76   
77   lvi.iItem = ListView_GetNextItem(hWnd, -1, LVIS_SELECTED | LVIS_FOCUSED);
78   nMaxpos = ListView_GetItemCount(hWnd);
79   if (lvi.iItem == -1 ||
80      (lvi.iItem <  2 && bDown == FALSE) || // Disallow moving First column
81      (lvi.iItem == 0 && bDown == TRUE)  || // ""
82      (lvi.iItem == nMaxpos - 1 && bDown == TRUE))
83   {
84      SetFocus(hWnd);
85      return;
86   }
87   lvi.iSubItem   = 0;
88   lvi.mask      = LVIF_PARAM | LVIF_TEXT;
89   lvi.pszText    = buf;
90   lvi.cchTextMax = sizeof(buf);
91   if (ListView_GetItem(hWnd, &lvi))
92   {
93      // Add this item to the Show and delete it from Available
94      ListView_DeleteItem(hWnd, lvi.iItem);
95      lvi.iItem += (bDown) ? 1 : -1;
96      ListView_InsertItem(hWnd,&lvi);
97      ListView_SetItemState(hWnd, lvi.iItem,
98                       LVIS_FOCUSED | LVIS_SELECTED,
99                       LVIS_FOCUSED | LVIS_SELECTED);
100      if (lvi.iItem == nMaxpos - 1)
101         EnableWindow(GetDlgItem(GetParent(hWnd), IDC_BUTTONMOVEDOWN), FALSE);
102      else
103         EnableWindow(GetDlgItem(GetParent(hWnd), IDC_BUTTONMOVEDOWN), TRUE);
104
105      if (lvi.iItem < 2)
106         EnableWindow(GetDlgItem(GetParent(hWnd), IDC_BUTTONMOVEUP),   FALSE);
107      else
108         EnableWindow(GetDlgItem(GetParent(hWnd), IDC_BUTTONMOVEUP),   TRUE);
109
110      SetFocus(hWnd);
111   }
112}
113
114INT_PTR InternalColumnDialogProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam,
115   int nColumnMax, int *shown, int *order,
116   LPCTSTR *names, void (*pfnGetRealColumnOrder)(int *),
117   void (*pfnGetColumnInfo)(int *pnOrder, int *pnShown),
118   void (*pfnSetColumnInfo)(int *pnOrder, int *pnShown))
119{
120   static HWND hShown;
121   static HWND hAvailable;
122   static BOOL showMsg = FALSE;
123   int         nShown;
124   int         nAvail;
125   int         i, nCount = 0;
126   LV_ITEM     lvi;
127   DWORD dwShowStyle, dwAvailableStyle, dwView;
128
129   switch (Msg)
130   {
131   case WM_INITDIALOG:
132      hShown      = GetDlgItem(hDlg, IDC_LISTSHOWCOLUMNS);
133      hAvailable = GetDlgItem(hDlg, IDC_LISTAVAILABLECOLUMNS);
134      /*Change Style to Always Show Selection */
135      dwShowStyle = GetWindowLong(hShown, GWL_STYLE);
136      dwAvailableStyle = GetWindowLong(hAvailable, GWL_STYLE);
137      dwView = LVS_SHOWSELALWAYS | LVS_LIST;
138
139      /* Only set the window style if the view bits have changed. */
140      if ((dwShowStyle & LVS_TYPEMASK) != dwView)
141      SetWindowLong(hShown, GWL_STYLE,
142         (dwShowStyle & ~LVS_TYPEMASK) | dwView);
143      if ((dwAvailableStyle & LVS_TYPEMASK) != dwView)
144      SetWindowLong(hAvailable, GWL_STYLE,
145         (dwAvailableStyle & ~LVS_TYPEMASK) | dwView);
146
147      pfnGetColumnInfo(order, shown);
148
149      showMsg = TRUE;
150      nShown   = 0;
151      nAvail   = 0;
152                 
153      lvi.mask     = LVIF_TEXT | LVIF_PARAM;
154      lvi.stateMask = 0;               
155      lvi.iSubItem  = 0;
156      lvi.iImage     = -1;
157
158      /* Get the Column Order and save it */
159      pfnGetRealColumnOrder(order);
160
161#if 0
162        {
163            char tmp[80];
164           
165            sprintf(tmp,"ColumnOrder: %d,%d,%d,%d,%d,%d,%d,%d,%d,%d, %d",
166                order[0], order[1], order[2], order[3], order[4],
167                order[5], order[6], order[7], order[8], order[9], order[10]);
168            MessageBox(0, tmp, "Column Order", IDOK);
169        }
170#endif
171      for (i = 0 ; i < nColumnMax; i++)
172      {       
173         lvi.pszText = (TCHAR *) names[order[i]];
174         lvi.lParam   = order[i];
175
176         if (shown[order[i]])
177         {
178            lvi.iItem = nShown;
179            ListView_InsertItem(hShown, &lvi);
180            nShown++;
181         }
182         else
183         {
184            lvi.iItem = nAvail;
185            ListView_InsertItem(hAvailable, &lvi);
186            nAvail++;
187         }
188      }
189      if( nShown > 0)
190      {
191         /*Set to Second, because first is not allowed*/
192         ListView_SetItemState(hShown, 1,
193            LVIS_FOCUSED | LVIS_SELECTED, LVIS_FOCUSED | LVIS_SELECTED);
194      }
195      if( nAvail > 0)
196      {
197         ListView_SetItemState(hAvailable, 0,
198            LVIS_FOCUSED | LVIS_SELECTED, LVIS_FOCUSED | LVIS_SELECTED);
199      }
200      EnableWindow(GetDlgItem(hDlg, IDC_BUTTONADD)  ,    TRUE);
201      return TRUE;
202
203   case WM_NOTIFY:
204      {
205         NMHDR *nm = (NMHDR *)lParam;
206         NM_LISTVIEW *pnmv;
207         int       nPos;
208         
209         switch (nm->code)
210         {
211         case NM_DBLCLK:
212            // Do Data Exchange here, which ListView was double clicked?
213            switch (nm->idFrom)
214            {
215            case IDC_LISTAVAILABLECOLUMNS:
216               // Move selected Item from Available to Shown column
217               nPos = DoExchangeItem(hAvailable, hShown, 0);
218               if (nPos)
219               {
220                  EnableWindow(GetDlgItem(hDlg, IDC_BUTTONADD),      FALSE);
221                  EnableWindow(GetDlgItem(hDlg, IDC_BUTTONREMOVE),   TRUE);
222                  EnableWindow(GetDlgItem(hDlg, IDC_BUTTONMOVEUP),   TRUE);
223                  EnableWindow(GetDlgItem(hDlg, IDC_BUTTONMOVEDOWN), FALSE);
224               }
225               break;
226
227            case IDC_LISTSHOWCOLUMNS:
228               // Move selected Item from Show to Available column
229               if (DoExchangeItem(hShown, hAvailable, 1))
230               {
231                  EnableWindow(GetDlgItem(hDlg, IDC_BUTTONADD)  ,    TRUE);
232                  EnableWindow(GetDlgItem(hDlg, IDC_BUTTONREMOVE),   FALSE);
233                  EnableWindow(GetDlgItem(hDlg, IDC_BUTTONMOVEUP),   FALSE);
234                  EnableWindow(GetDlgItem(hDlg, IDC_BUTTONMOVEDOWN), FALSE);
235               }
236               break;
237            }
238            return TRUE;
239           
240         case LVN_ITEMCHANGED:
241            // Don't handle this message for now
242            pnmv = (NM_LISTVIEW *)nm;
243            if (//!(pnmv->uOldState & LVIS_SELECTED) &&
244               (pnmv->uNewState  & LVIS_SELECTED))
245            {
246               if (pnmv->iItem == 0 && pnmv->hdr.idFrom == IDC_LISTSHOWCOLUMNS)
247               {
248                  // Don't allow selecting the first item
249                  ListView_SetItemState(hShown, pnmv->iItem,
250                     LVIS_FOCUSED | LVIS_SELECTED, LVIS_FOCUSED | LVIS_SELECTED);
251                  if (showMsg)
252                  {
253                     MessageBox(0, TEXT("Changing this item is not permitted"), TEXT("Select Item"), IDOK);
254                     showMsg = FALSE;
255                  }
256                  EnableWindow(GetDlgItem(hDlg, IDC_BUTTONREMOVE),   FALSE);
257                  EnableWindow(GetDlgItem(hDlg, IDC_BUTTONMOVEUP),   FALSE);
258                  EnableWindow(GetDlgItem(hDlg, IDC_BUTTONMOVEDOWN), FALSE);
259                  /*Leave Focus on Control*/
260                  //SetFocus(GetDlgItem(hDlg,IDOK));
261                  return TRUE;
262               }
263               else
264                  showMsg = TRUE;
265            }
266            if( pnmv->uOldState & LVIS_SELECTED && pnmv->iItem == 0 && pnmv->hdr.idFrom == IDC_LISTSHOWCOLUMNS )
267            {
268               /*we enable the buttons again, if the first Entry loses selection*/
269               EnableWindow(GetDlgItem(hDlg, IDC_BUTTONREMOVE),   TRUE);
270               EnableWindow(GetDlgItem(hDlg, IDC_BUTTONMOVEUP),   TRUE);
271               EnableWindow(GetDlgItem(hDlg, IDC_BUTTONMOVEDOWN), TRUE);
272               //SetFocus(GetDlgItem(hDlg,IDOK));
273            }
274            break;
275         case NM_SETFOCUS:
276            {
277               switch (nm->idFrom)
278               {
279               case IDC_LISTAVAILABLECOLUMNS:
280                  if (ListView_GetItemCount(nm->hwndFrom) != 0)
281                  {
282                     EnableWindow(GetDlgItem(hDlg, IDC_BUTTONADD),      TRUE);
283                     EnableWindow(GetDlgItem(hDlg, IDC_BUTTONREMOVE),   FALSE);
284                     EnableWindow(GetDlgItem(hDlg, IDC_BUTTONMOVEDOWN), FALSE);
285                     EnableWindow(GetDlgItem(hDlg, IDC_BUTTONMOVEUP),   FALSE);
286                  }
287                  break;
288               case IDC_LISTSHOWCOLUMNS:
289                  if (ListView_GetItemCount(nm->hwndFrom) != 0)
290                  {
291                     EnableWindow(GetDlgItem(hDlg, IDC_BUTTONADD),      FALSE);
292                     
293                     if (ListView_GetNextItem(hShown, -1, LVIS_SELECTED | LVIS_FOCUSED) == 0 )
294                     {
295                        EnableWindow(GetDlgItem(hDlg, IDC_BUTTONREMOVE),   FALSE);
296                        EnableWindow(GetDlgItem(hDlg, IDC_BUTTONMOVEDOWN), FALSE);
297                        EnableWindow(GetDlgItem(hDlg, IDC_BUTTONMOVEUP),   FALSE);
298                     }
299                     else
300                     {
301                        EnableWindow(GetDlgItem(hDlg, IDC_BUTTONREMOVE),   TRUE);
302                        EnableWindow(GetDlgItem(hDlg, IDC_BUTTONMOVEDOWN), TRUE);
303                        EnableWindow(GetDlgItem(hDlg, IDC_BUTTONMOVEUP),   TRUE);
304                     }
305                  }
306                  break;
307               }
308            }
309            break;
310         case LVN_KEYDOWN:
311         case NM_CLICK:
312            pnmv = (NM_LISTVIEW *)nm;
313            if (//!(pnmv->uOldState & LVIS_SELECTED) &&
314               (pnmv->uNewState  & LVIS_SELECTED))
315            {
316               if (pnmv->iItem == 0 && pnmv->hdr.idFrom == IDC_LISTSHOWCOLUMNS)
317               {
318               }
319            }
320            switch (nm->idFrom)
321            {
322            case IDC_LISTAVAILABLECOLUMNS:
323               if (ListView_GetItemCount(nm->hwndFrom) != 0)
324               {
325                  EnableWindow(GetDlgItem(hDlg, IDC_BUTTONADD),      TRUE);
326                  EnableWindow(GetDlgItem(hDlg, IDC_BUTTONREMOVE),   FALSE);
327                  EnableWindow(GetDlgItem(hDlg, IDC_BUTTONMOVEDOWN), FALSE);
328                  EnableWindow(GetDlgItem(hDlg, IDC_BUTTONMOVEUP),   FALSE);
329               }
330               break;
331
332            case IDC_LISTSHOWCOLUMNS:
333               if (ListView_GetItemCount(nm->hwndFrom) != 0)
334               {
335                  EnableWindow(GetDlgItem(hDlg, IDC_BUTTONADD),      FALSE);
336                  if (ListView_GetNextItem(hShown, -1, LVIS_SELECTED | LVIS_FOCUSED) == 0 )
337                  {
338                     EnableWindow(GetDlgItem(hDlg, IDC_BUTTONREMOVE),   FALSE);
339                     EnableWindow(GetDlgItem(hDlg, IDC_BUTTONMOVEDOWN), FALSE);
340                     EnableWindow(GetDlgItem(hDlg, IDC_BUTTONMOVEUP),   FALSE);
341                  }
342                  else
343                  {
344                     EnableWindow(GetDlgItem(hDlg, IDC_BUTTONREMOVE),   TRUE);
345                     EnableWindow(GetDlgItem(hDlg, IDC_BUTTONMOVEDOWN), TRUE);
346                     EnableWindow(GetDlgItem(hDlg, IDC_BUTTONMOVEUP),   TRUE);
347                  }
348               }
349               break;
350            }
351            //SetFocus( nm->hwndFrom );
352            return TRUE;
353         }
354      }
355      return FALSE;
356   case WM_COMMAND:
357      {
358         WORD wID     = GET_WM_COMMAND_ID(wParam, lParam);
359         HWND hWndCtrl = GET_WM_COMMAND_HWND(wParam, lParam);
360         int  nPos = 0;
361
362         switch (wID)
363         {
364            case IDC_LISTSHOWCOLUMNS:
365               break;
366            case IDC_BUTTONADD:
367               // Move selected Item in Available to Shown
368               nPos = DoExchangeItem(hAvailable, hShown, 0);
369               if (nPos)
370               {
371                  EnableWindow(hWndCtrl,FALSE);
372                  EnableWindow(GetDlgItem(hDlg, IDC_BUTTONREMOVE),   TRUE);
373                  EnableWindow(GetDlgItem(hDlg, IDC_BUTTONMOVEUP),   TRUE);
374                  EnableWindow(GetDlgItem(hDlg, IDC_BUTTONMOVEDOWN), FALSE);
375               }
376               break;
377
378            case IDC_BUTTONREMOVE:
379               // Move selected Item in Show to Available
380               if (DoExchangeItem( hShown, hAvailable, 1))
381               {
382                  EnableWindow(hWndCtrl,FALSE);
383                  EnableWindow(GetDlgItem(hDlg, IDC_BUTTONADD),      TRUE);
384                  EnableWindow(GetDlgItem(hDlg, IDC_BUTTONMOVEUP),   FALSE);
385                  EnableWindow(GetDlgItem(hDlg, IDC_BUTTONMOVEDOWN), FALSE);
386               }
387               break;
388
389            case IDC_BUTTONMOVEDOWN:
390               // Move selected item in the Show window up 1 item
391               DoMoveItem(hShown, TRUE);
392               break;
393
394            case IDC_BUTTONMOVEUP:
395               // Move selected item in the Show window down 1 item
396               DoMoveItem(hShown, FALSE);
397               break;
398
399            case IDOK:
400               // Save users choices
401               nShown = ListView_GetItemCount(hShown);
402               nAvail = ListView_GetItemCount(hAvailable);
403               nCount = 0;
404               for (i = 0; i < nShown; i++)
405               {
406                  lvi.iSubItem = 0;
407                  lvi.mask     = LVIF_PARAM;
408                  lvi.pszText  = 0;
409                  lvi.iItem    = i;
410                  ListView_GetItem(hShown, &lvi);
411                  order[nCount++]   = lvi.lParam;
412                  shown[lvi.lParam] = TRUE;
413               }
414               for (i = 0; i < nAvail; i++)
415               {
416                  lvi.iSubItem = 0;
417                  lvi.mask     = LVIF_PARAM;
418                  lvi.pszText  = 0;
419                  lvi.iItem    = i;
420                  ListView_GetItem(hAvailable, &lvi);
421                  order[nCount++]   = lvi.lParam;
422                  shown[lvi.lParam] = FALSE;
423               }
424#if 0
425               {
426                  char tmp[80];
427                  sprintf(tmp,"Shown (%d) - Hidden (%d)",nShown,nAvail);
428                  MessageBox(0,tmp,"List Counts",IDOK);
429                  sprintf(tmp,"ColumnOrder: %d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d",
430                     order[0], order[1], order[2], order[3], order[4],
431                     order[5], order[6], order[7], order[8], order[9], shown[10]);
432                  MessageBox(0,tmp,"Column Order", IDOK);
433                  sprintf(tmp,"ColumnShown: %d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d",
434                     shown[0], shown[1], shown[2], shown[3], shown[4],
435                     shown[5], shown[6], shown[7], shown[8], shown[9], shown[10]);
436                  MessageBox(0,tmp,"Column Shown", IDOK);
437               }
438#endif
439               pfnSetColumnInfo(order, shown);
440               EndDialog(hDlg, 1);
441               return TRUE;
442
443            case IDCANCEL:
444               EndDialog(hDlg, 0);
445               return TRUE;
446         }
447      }
448      break;
449   }
450   return 0;
451}
452
453static void GetColumnInfo(int *order, int *shown)
454{
455   GetColumnOrder(order);
456   GetColumnShown(shown);
457}
458
459static void SetColumnInfo(int *order, int *shown)
460{
461   SetColumnOrder(order);
462   SetColumnShown(shown);
463}
464
465INT_PTR CALLBACK ColumnDialogProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam)
466{
467   static int shown[COLUMN_MAX];
468   static int order[COLUMN_MAX];
469   extern LPCTSTR column_names[COLUMN_MAX]; // from win32ui.c, should improve
470
471
472   return InternalColumnDialogProc(hDlg, Msg, wParam, lParam, COLUMN_MAX,
473      shown, order, column_names, GetRealColumnOrder, GetColumnInfo, SetColumnInfo);
474}
475
476
477
src/osd/winui/ui.mak
r0r996
1#####################################################################
2# make SUFFIX=32
3#####################################################################
4
5#-------------------------------------------------
6# object and source roots
7#-------------------------------------------------
8
9WINUISRC = $(SRC)/osd/winui
10WINUIOBJ = $(OBJ)/osd/winui
11
12OBJDIRS += $(WINUIOBJ)
13   
14ifdef MESS
15MESS_WINUISRC = $(SRC)/mess/osd/winui
16MESS_WINUIOBJ = $(OBJ)/mess/osd/winui
17OBJDIRS += $(MESS_WINUIOBJ)
18CFLAGS += -I$(WINUISRC) -I$(MESS_WINUISRC)
19endif
20
21
22
23#-------------------------------------------------
24# Windows UI object files
25#-------------------------------------------------
26
27WINUIOBJS += \
28   $(WINUIOBJ)/m32util.o \
29   $(WINUIOBJ)/directinput.o \
30   $(WINUIOBJ)/dijoystick.o \
31   $(WINUIOBJ)/directdraw.o \
32   $(WINUIOBJ)/directories.o \
33   $(WINUIOBJ)/audit32.o \
34   $(WINUIOBJ)/columnedit.o \
35   $(WINUIOBJ)/screenshot.o \
36   $(WINUIOBJ)/treeview.o \
37   $(WINUIOBJ)/splitters.o \
38   $(WINUIOBJ)/bitmask.o \
39   $(WINUIOBJ)/datamap.o \
40   $(WINUIOBJ)/dxdecode.o \
41   $(WINUIOBJ)/picker.o \
42   $(WINUIOBJ)/properties.o \
43   $(WINUIOBJ)/tabview.o \
44   $(WINUIOBJ)/help.o \
45   $(WINUIOBJ)/history.o \
46   $(WINUIOBJ)/dialogs.o \
47   $(WINUIOBJ)/dirwatch.o   \
48   $(WINUIOBJ)/datafile.o   \
49   $(WINUIOBJ)/m32opts.o \
50   $(WINUIOBJ)/win32ui.o \
51   $(WINUIOBJ)/helpids.o \
52
53ifdef MESS
54WINUIOBJS += \
55   $(MESS_WINUIOBJ)/mess32ui.o \
56   $(MESS_WINUIOBJ)/optionsms.o \
57    $(MESS_WINUIOBJ)/layoutms.o \
58   $(MESS_WINUIOBJ)/ms32util.o \
59   $(MESS_WINUIOBJ)/propertiesms.o \
60   $(MESS_WINUIOBJ)/softwarepicker.o \
61   $(MESS_WINUIOBJ)/devview.o
62else
63WINUIOBJS += \
64    $(WINUIOBJ)/layout.o \
65   $(WINUIOBJ)/m32main.o \
66   $(WINUIOBJ)/mame32.res
67endif
68
69ifdef MESS
70# extra dependencies
71# $(MESS_WINUIOBJ)/mess32ui.o:   $(WINUISRC)/win32ui.c $(MESS_WINUISRC)/mess32ui.c
72# $(MESS_WINUIOBJ)/optionsms.o:   $(WINUISRC)/options.c $(MESS_WINUISRC)/optionsms.c
73endif
74   
75# add resource file
76ifdef MESS
77GUIRESFILE = $(MESS_WINUIOBJ)/mess32.res
78endif
79
80$(LIBOSD): $(WINUIOBJS)
81
82
83#-------------------------------------------------
84# rules for creating helpids.c
85#-------------------------------------------------
86
87$(WINUISRC)/helpids.c : $(WINUIOBJ)/mkhelp$(EXE) $(WINUISRC)/resource.h $(WINUISRC)/resource.hm $(WINUISRC)/mame32.rc
88   $(WINUIOBJ)/mkhelp$(EXE) $(WINUISRC)/mame32.rc >$@
89
90# rule to build the generator
91$(WINUIOBJ)/mkhelp$(EXE): $(WINUIOBJ)/mkhelp.o
92   @echo Linking $@...
93   $(LD) $(LDFLAGS) $^ $(LIBS) -o $@
94
95
96#####################################################################
97# compiler
98
99#
100# Preprocessor Definitions
101#
102
103ifdef MSVC_BUILD
104DEFS += -DWINVER=0x0500 -D_CRT_NON_CONFORMING_SWPRINTFS
105else
106DEFS += -DWINVER=0x0400
107endif
108
109DEFS += \
110   -D_WIN32_IE=0x0500 \
111   -DDECL_SPEC= \
112   -DZEXTERN=extern \
113
114#   -DSHOW_UNAVAILABLE_FOLDER
115
116
117#####################################################################
118# Resources
119
120ifndef MESS
121UI_RC = @windres --use-temp-file
122
123UI_RCDEFS = -DNDEBUG -D_WIN32_IE=0x0400
124
125UI_RCFLAGS = -O coff --include-dir $(WINUISRC)
126
127$(WINUIOBJ)/%.res: $(WINUISRC)/%.rc
128   @echo Compiling mame32 resources $<...
129   $(UI_RC) $(UI_RCDEFS) $(UI_RCFLAGS) -o $@ -i $<
130endif
131
132#####################################################################
133# Linker
134
135ifndef MSVC
136LIBS += -lkernel32 \
137        -lshell32 \
138        -lcomctl32 \
139        -lcomdlg32 \
140        -ladvapi32 \
141
142endif
143
144ifndef MESS
145LDFLAGS += -mwindows
146endif
147
148#####################################################################
149
150ifdef MESS
151
152$(MESS_WINUIOBJ)/mess32.res:   $(WINUISRC)/mame32.rc $(MESS_WINUISRC)/mess32.rc $(WINUISRC)/resource.h $(MESS_WINUISRC)/resourcems.h $(WINUIOBJ)/mamevers.rc
153   @echo Compiling resources $<...
154   $(RC) $(RCDEFS) $(RCFLAGS) --include-dir $(WINUISRC) --include-dir $(MESS_WINUISRC) --include-dir $(WINUIOBJ) -o $@ -i $(MESS_WINUISRC)/mess32.rc
155
156$(WINUIOBJ)/mamevers.rc: $(VERINFO) $(SRC)/version.c
157   @echo Emitting $@...
158   @$(VERINFO) $(SRC)/version.c > $@
159
160endif
src/osd/winui/m32util.h
r0r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5 
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11 ***************************************************************************/
12
13#ifndef M32UTIL_H
14#define M32UTIL_H
15
16extern void __cdecl ErrorMsg(const char* fmt, ...);
17extern void __cdecl dprintf(const char* fmt, ...);
18
19extern UINT GetDepth(HWND hWnd);
20
21/* Open a text file */
22extern void DisplayTextFile(HWND hWnd, const char *cName);
23
24#define PACKVERSION(major,minor) MAKELONG(minor,major)
25
26/* Check for old version of comctl32.dll */
27extern LONG GetCommonControlVersion(void);
28
29extern char * MyStrStrI(const char* pFirst, const char* pSrch);
30extern char * ConvertToWindowsNewlines(const char *source);
31
32extern const char * GetDriverFilename(int nIndex);
33
34BOOL DriverIsClone(int driver_index);
35BOOL DriverIsBroken(int driver_index);
36BOOL DriverIsHarddisk(int driver_index);
37BOOL DriverHasOptionalBIOS(int driver_index);
38BOOL DriverIsStereo(int driver_index);
39BOOL DriverIsMultiMon(int driver_index);
40BOOL DriverIsVector(int driver_index);
41BOOL DriverIsBios(int driver_index);
42BOOL DriverUsesRoms(int driver_index);
43BOOL DriverUsesSamples(int driver_index);
44BOOL DriverUsesTrackball(int driver_index);
45BOOL DriverUsesLightGun(int driver_index);
46BOOL DriverSupportsSaveState(int driver_index);
47BOOL DriverIsVertical(int driver_index);
48
49void FlushFileCaches(void);
50
51void FreeIfAllocated(char **s);
52
53BOOL StringIsSuffixedBy(const char *s, const char *suffix);
54
55BOOL SafeIsAppThemed(void);
56
57HICON win_extract_icon_utf8(HINSTANCE inst, const char* exefilename, UINT iconindex);
58TCHAR* win_tstring_strdup(LPCTSTR str);
59HANDLE win_create_file_utf8(const char* filename, DWORD desiredmode, DWORD sharemode,
60                        LPSECURITY_ATTRIBUTES securityattributes, DWORD creationdisposition,
61                        DWORD flagsandattributes, HANDLE templatehandle);
62DWORD win_get_current_directory_utf8(DWORD bufferlength, char* buffer);
63HANDLE win_find_first_file_utf8(const char* filename, LPWIN32_FIND_DATA findfiledata);
64
65#endif /* MAME32UTIL_H */
src/osd/winui/win32ui.h
r0r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5   
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11 ***************************************************************************/
12
13#ifndef WIN32UI_H
14#define WIN32UI_H
15
16#define WIN32_LEAN_AND_MEAN
17#include <commctrl.h>
18#include <commdlg.h>
19#include <driver.h>
20#include "screenshot.h"
21#include "pool.h"
22#define SEARCH_PROMPT ""
23
24enum
25{
26   TAB_PICKER = 0,
27   TAB_DISPLAY,
28   TAB_MISC,
29   NUM_TABS
30};
31
32enum
33{
34   FILETYPE_INPUT_FILES = 1,
35   FILETYPE_SAVESTATE_FILES = 2,
36   FILETYPE_WAVE_FILES = 3,
37   FILETYPE_MNG_FILES = 5,
38   FILETYPE_EFFECT_FILES = 6
39};
40
41
42typedef struct
43{
44   INT resource;
45   const char *icon_name;
46} ICONDATA;
47
48extern TCHAR last_directory[MAX_PATH];
49
50typedef BOOL (WINAPI *common_file_dialog_proc)(LPOPENFILENAME lpofn);
51BOOL CommonFileDialog(common_file_dialog_proc cfd,char *filename, int filetype);
52
53HWND GetMainWindow(void);
54HWND GetTreeView(void);
55HIMAGELIST GetLargeImageList(void);
56HIMAGELIST GetSmallImageList(void);
57int GetNumOptionFolders(void);
58void SetNumOptionFolders(int count);
59void GetRealColumnOrder(int order[]);
60HICON LoadIconFromFile(const char *iconname);
61void UpdateScreenShot(void);
62void ResizePickerControls(HWND hWnd);
63void MamePlayGame(void);
64int FindIconIndex(int nIconResource);
65int FindIconIndexByName(const char *icon_name);
66int GetSelectedPick(void);
67object_pool *GetMame32MemoryPool(void);
68
69void UpdateListView(void);
70
71// Move The in "The Title (notes)" to "Title, The (notes)"
72char * ModifyThe(const char *str);
73
74// Convert Ampersand so it can display in a static control
75char * ConvertAmpersandString(const char *s);
76
77// globalized for painting tree control
78HBITMAP GetBackgroundBitmap(void);
79HPALETTE GetBackgroundPalette(void);
80MYBITMAPINFO* GetBackgroundInfo(void);
81BOOL GetUseOldControl(void);
82BOOL GetUseXPControl(void);
83
84int GetMinimumScreenShotWindowWidth(void);
85
86// we maintain an array of drivers sorted by name, useful all around
87int GetDriverIndex(const game_driver *driver);
88int GetParentIndex(const game_driver *driver);
89int GetParentRomSetIndex(const game_driver *driver);
90int GetGameNameIndex(const char *name);
91int GetIndexFromSortedIndex(int sorted_index);
92
93// sets text in part of the status bar on the main window
94void SetStatusBarText(int part_index, const char *message);
95void SetStatusBarTextF(int part_index, const char *fmt, ...);
96
97int Mame32Main(HINSTANCE    hInstance,
98                   LPSTR        lpCmdLine,
99                   int          nCmdShow);
100
101BOOL MouseHasBeenMoved(void);
102
103const char * GetSearchText(void);
104#endif
src/osd/winui/history.h
r0r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11 ***************************************************************************/
12
13#ifndef HISTORY_H
14#define HISTORY_H
15
16char * GetGameHistory(int driver_index);
17
18#endif
19
src/osd/winui/mame32.rc
r0r996
1// Microsoft Visual C++ generated resource script.
2//
3#include "resource.h"
4
5#ifdef MESS
6#include "resourcems.h"
7#endif
8
9// Generated Help ID header file
10#define APSTUDIO_HIDDEN_SYMBOLS
11#include "resource.hm"
12#undef APSTUDIO_HIDDEN_SYMBOLS
13
14#define APSTUDIO_READONLY_SYMBOLS
15/////////////////////////////////////////////////////////////////////////////
16//
17// Generated from the TEXTINCLUDE 2 resource.
18//
19#define NOWINRES
20#include "windows.h"
21#include "commctrl.h"
22
23/////////////////////////////////////////////////////////////////////////////
24#undef APSTUDIO_READONLY_SYMBOLS
25
26/////////////////////////////////////////////////////////////////////////////
27// English (U.S.) resources
28
29#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
30#ifdef _WIN32
31LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
32#pragma code_page(1252)
33#endif //_WIN32
34
35/////////////////////////////////////////////////////////////////////////////
36//
37// Menu
38//
39
40IDR_MAIN_MENU MENU
41BEGIN
42    POPUP "&File"
43    BEGIN
44        MENUITEM "&Exit",                       ID_FILE_EXIT
45    END
46    POPUP "&Help"
47    BEGIN
48#ifdef MESS
49        MENUITEM "&About MESS",               ID_ABOUT
50#else
51        MENUITEM "&About MAME32",               ID_ABOUT
52#endif
53    END
54END
55
56IDR_UI_MENU MENU
57BEGIN
58    POPUP "&File"
59    BEGIN
60        MENUITEM "&Play",                       ID_FILE_PLAY
61        MENUITEM SEPARATOR
62        MENUITEM "Play and &Record Input...",   ID_FILE_PLAY_RECORD
63        MENUITEM "P&layback Input...",          ID_FILE_PLAY_BACK
64        MENUITEM SEPARATOR
65        MENUITEM "Play and Record &Wave Output...", ID_FILE_PLAY_RECORD_WAVE
66        MENUITEM SEPARATOR
67        MENUITEM "Play and Record &MNG Output...", ID_FILE_PLAY_RECORD_MNG
68        MENUITEM SEPARATOR
69        MENUITEM "Loa&d Savestate...",          ID_FILE_LOADSTATE
70        MENUITEM SEPARATOR
71#ifdef MESS
72        MENUITEM "&Select Random System",       ID_CONTEXT_SELECT_RANDOM
73        MENUITEM SEPARATOR
74        MENUITEM "Op&en Other Software...",     ID_MESS_OPEN_SOFTWARE
75        MENUITEM "&Create Image...",         ID_MESS_CREATE_SOFTWARE
76#ifdef MAME_DEBUG
77        MENUITEM SEPARATOR
78        MENUITEM "Run Tests",               ID_MESS_RUN_TESTS
79#endif
80#else /* !MESS */
81        MENUITEM "&Select Random Game",         ID_CONTEXT_SELECT_RANDOM
82#endif /* MESS */
83        MENUITEM SEPARATOR
84        MENUITEM "Pr&operties",                 ID_GAME_PROPERTIES
85        MENUITEM SEPARATOR
86#ifdef MESS
87        MENUITEM "&Audit all systems",          ID_FILE_AUDIT
88#else
89        MENUITEM "&Audit all games",            ID_FILE_AUDIT
90#endif /* MESS */
91        MENUITEM SEPARATOR
92        MENUITEM "E&xit",                       ID_FILE_EXIT
93    END
94    POPUP "&View"
95    BEGIN
96        MENUITEM "&Toolbar\tAlt+T",             ID_VIEW_TOOLBARS
97        MENUITEM "&Status bar\tAlt+S",          ID_VIEW_STATUS
98        MENUITEM "Fold&er List\tAlt+D",         ID_VIEW_FOLDERS
99        MENUITEM "&Picture Area\tAlt+P",        ID_VIEW_PICTURE_AREA
100        MENUITEM "Screenshot Ta&b\tAlt+B",      ID_VIEW_PAGETAB
101        MENUITEM SEPARATOR
102        MENUITEM "&Fullscreen\tF11",            ID_VIEW_FULLSCREEN
103        MENUITEM SEPARATOR
104        POPUP "S&how Pictures"
105        BEGIN
106            MENUITEM "&Snapshot",                   ID_TOGGLE_TAB_SCREENSHOT
107            MENUITEM "&Flyer",                      ID_TOGGLE_TAB_FLYER
108            MENUITEM "&Cabinet",                    ID_TOGGLE_TAB_CABINET
109            MENUITEM "&Marquee",                    ID_TOGGLE_TAB_MARQUEE
110            MENUITEM "&Title",                      ID_TOGGLE_TAB_TITLE
111            MENUITEM "Control &Panel",              ID_TOGGLE_TAB_CONTROL_PANEL
112            MENUITEM "PC&B",                        ID_TOGGLE_TAB_PCB
113
114            MENUITEM "&History",                    ID_TOGGLE_TAB_HISTORY
115        END
116        MENUITEM SEPARATOR
117        MENUITEM "L&arge Icons",                ID_VIEW_LARGE_ICON
118        MENUITEM "S&mall Icons",                ID_VIEW_SMALL_ICON
119        MENUITEM "&List",                       ID_VIEW_LIST_MENU
120        MENUITEM "&Details",                    ID_VIEW_DETAIL
121        MENUITEM "&Grouped",                    ID_VIEW_GROUPED
122        MENUITEM SEPARATOR
123        POPUP "Arrange &Icons"
124        BEGIN
125            MENUITEM "by &Name",                    ID_VIEW_BYGAME
126            MENUITEM "by D&irectory",               ID_VIEW_BYDIRECTORY
127            MENUITEM "by &Manufacturer",            ID_VIEW_BYMANUFACTURER
128            MENUITEM "by Times &Played",            ID_VIEW_BYTIMESPLAYED
129            MENUITEM "by &Type",                    ID_VIEW_BYTYPE
130            MENUITEM "by &Date",                    ID_VIEW_BYYEAR
131        END
132        MENUITEM "Line &Up Icons",              ID_VIEW_LINEUPICONS
133        MENUITEM SEPARATOR
134        MENUITEM "&Refresh\tF5",                ID_UPDATE_GAMELIST
135        MENUITEM "&Custom Filters...\tCtrl+F",  ID_CONTEXT_FILTERS
136        MENUITEM "Customi&ze Fields...",        ID_CUSTOMIZE_FIELDS
137    END
138    POPUP "&Options"
139    BEGIN
140#ifdef MESS
141        MENUITEM "System List &Font...",          ID_OPTIONS_FONT
142        MENUITEM "System List &Clone Color...",   ID_OPTIONS_CLONE_COLOR
143        MENUITEM "&Directories...",             ID_OPTIONS_DIR
144        MENUITEM "Default System &Options...",    ID_OPTIONS_DEFAULTS
145#else
146        MENUITEM "Game List &Font...",          ID_OPTIONS_FONT
147        MENUITEM "Game List &Clone Color...",   ID_OPTIONS_CLONE_COLOR
148        MENUITEM "&Directories...",             ID_OPTIONS_DIR
149        MENUITEM "Default Game &Options...",    ID_OPTIONS_DEFAULTS
150#endif
151        MENUITEM "&Reset to Default...",        ID_OPTIONS_RESET_DEFAULTS
152        MENUITEM "&Interface Options...",       ID_OPTIONS_INTERFACE
153        MENUITEM "&Background Image...",        ID_OPTIONS_BG
154    END
155    POPUP "&Help"
156    BEGIN
157#ifdef MESS
158        MENUITEM "&Mess Release Notes",         ID_HELP_RELEASE
159        MENUITEM "&New Mess Features",          ID_HELP_WHATS_NEW
160#else
161        MENUITEM "&Contents\tF1",               ID_HELP_CONTENTS
162        MENUITEM "&Troubleshooting",            ID_HELP_TROUBLE
163        MENUITEM SEPARATOR
164        MENUITEM "&New Game Changes",           ID_HELP_WHATS_NEW32
165        MENUITEM "&Mame Release Notes",         ID_HELP_WHATS_NEW
166#endif
167        MENUITEM SEPARATOR
168        MENUITEM "&About",                      ID_HELP_ABOUT
169    END
170END
171
172IDR_CONTEXT_MENU MENU
173BEGIN
174    POPUP "Context Menu"
175    BEGIN
176        MENUITEM "&Play",                       ID_FILE_PLAY
177        MENUITEM SEPARATOR
178        MENUITEM "Play and &Record Input...",   ID_FILE_PLAY_RECORD
179        MENUITEM SEPARATOR
180        MENUITEM "&Add to Custom Folder...",    ID_CONTEXT_ADD_CUSTOM
181        MENUITEM "R&emove From This Folder",    ID_CONTEXT_REMOVE_CUSTOM
182        MENUITEM "&Custom Filters...",          ID_CONTEXT_FILTERS
183        MENUITEM SEPARATOR
184#ifdef MESS
185        MENUITEM "&Select Random System",         ID_CONTEXT_SELECT_RANDOM
186#else
187        MENUITEM "&Select Random Game",         ID_CONTEXT_SELECT_RANDOM
188#endif
189        MENUITEM SEPARATOR
190        MENUITEM "Rese&t Playcount",            ID_CONTEXT_RESET_PLAYCOUNT
191        MENUITEM "Reset Pla&y Time",            ID_CONTEXT_RESET_PLAYTIME
192        MENUITEM SEPARATOR
193        MENUITEM "A&udit",                      ID_GAME_AUDIT
194        MENUITEM SEPARATOR
195        MENUITEM "Pr&operties",                 ID_GAME_PROPERTIES
196        MENUITEM "Source propert&ies",          ID_FOLDER_SOURCEPROPERTIES
197        MENUITEM "&Vector properties",          ID_FOLDER_VECTORPROPERTIES
198    END
199END
200
201IDR_CONTEXT_HEADER MENU
202BEGIN
203    POPUP "Header Context Menu"
204    BEGIN
205        MENUITEM "Sort &Ascending",             ID_SORT_ASCENDING
206        MENUITEM "Sort &Descending",            ID_SORT_DESCENDING
207        MENUITEM SEPARATOR
208        MENUITEM "Customi&ze Fields...",        ID_CUSTOMIZE_FIELDS
209    END
210END
211
212IDR_CONTEXT_TREE MENU
213BEGIN
214    POPUP "Context Menu Tree"
215    BEGIN
216        MENUITEM "&Rename",                     ID_CONTEXT_RENAME_CUSTOM
217        MENUITEM "&Custom Filters...",          ID_CONTEXT_FILTERS
218        MENUITEM SEPARATOR
219        POPUP "&Show Folders"
220        BEGIN
221            MENUITEM "overridden by code",          ID_CONTEXT_SHOW_FOLDER_START
222
223        END
224        MENUITEM SEPARATOR
225        MENUITEM "&Audit",                      ID_FOLDER_AUDIT
226        MENUITEM SEPARATOR
227        MENUITEM "&Properties",                 ID_FOLDER_PROPERTIES
228    END
229END
230
231IDR_CONTEXT_SCREENSHOT MENU
232BEGIN
233    POPUP "Context Screen Shot"
234    BEGIN
235        MENUITEM "Show Tab &Control",           ID_VIEW_PAGETAB
236        MENUITEM SEPARATOR
237        POPUP "S&how Pictures"
238        BEGIN
239            MENUITEM "&Snapshot",                   ID_TOGGLE_TAB_SCREENSHOT
240            MENUITEM "&Flyer",                      ID_TOGGLE_TAB_FLYER
241            MENUITEM "&Cabinet",                    ID_TOGGLE_TAB_CABINET
242            MENUITEM "&Marquee",                    ID_TOGGLE_TAB_MARQUEE
243            MENUITEM "&Title",                      ID_TOGGLE_TAB_TITLE
244            MENUITEM "Control &Panel",              ID_TOGGLE_TAB_CONTROL_PANEL
245            MENUITEM "PC&B",                        ID_TOGGLE_TAB_PCB
246
247            MENUITEM "&History",                    ID_TOGGLE_TAB_HISTORY
248        END
249        MENUITEM SEPARATOR
250        MENUITEM "&Snapshot",                   ID_VIEW_TAB_SCREENSHOT
251        MENUITEM "&Flyer",                      ID_VIEW_TAB_FLYER
252        MENUITEM "&Cabinet",                    ID_VIEW_TAB_CABINET
253        MENUITEM "&Marquee",                    ID_VIEW_TAB_MARQUEE
254        MENUITEM "&Title",                      ID_VIEW_TAB_TITLE
255        MENUITEM "Control &Panel",              ID_VIEW_TAB_CONTROL_PANEL
256        MENUITEM "PC&B",                        ID_VIEW_TAB_PCB
257        MENUITEM "&History",                    ID_VIEW_TAB_HISTORY
258    END
259END
260
261
262#ifdef APSTUDIO_INVOKED
263/////////////////////////////////////////////////////////////////////////////
264//
265// TEXTINCLUDE
266//
267
2681 TEXTINCLUDE
269BEGIN
270    "resource.h\0"
271END
272
2732 TEXTINCLUDE
274BEGIN
275    "#define NOWINRES\r\n"
276    "#include ""windows.h""\r\n"
277    "#include ""commctrl.h""\r\n"
278    "\0"
279END
280
2813 TEXTINCLUDE
282BEGIN
283    "#include ""mamevers.rc"" // Version block\r\n"
284    "\r\n"
285    "\0"
286END
287
288#endif    // APSTUDIO_INVOKED
289
290
291/////////////////////////////////////////////////////////////////////////////
292//
293// Icon
294//
295
296// Icon with lowest ID value placed first to ensure application icon
297// remains consistent on all systems.
298#ifdef MESS
299IDI_MAME32_ICON         ICON                    "res/mess.ico"
300#else
301IDI_MAME32_ICON         ICON                    "res\\mame32.ico"
302#endif
303IDI_WIN_ROMS            ICON                    "res\\win_roms.ico"
304IDI_WIN_NOROMS          ICON                    "res\\win_noro.ico"
305IDI_WIN_UNKNOWN         ICON                    "res\\win_unkn.ico"
306IDI_WIN_CLONE           ICON                    "res\\win_clone.ico"
307IDI_WIN_REDX            ICON                    "res\\win_redx.ico"
308IDI_FOLDER_AVAILABLE    ICON                    "res\\foldavail.ico"
309IDI_FOLDER              ICON                    "res\\folder.ico"
310IDI_FOLDER_MANUFACTURER ICON                    "res\\foldmanu.ico"
311IDI_FOLDER_OPEN         ICON                    "res\\foldopen.ico"
312IDI_FOLDER_UNAVAILABLE  ICON                    "res\\foldunav.ico"
313IDI_FOLDER_HORIZONTAL   ICON                    "res\\horz.ico"
314IDI_FOLDER_VERTICAL     ICON                    "res\\vert.ico"
315IDI_MANUFACTURER        ICON                    "res\\manufact.ico"
316IDI_FOLDER_YEAR         ICON                    "res\\foldyear.ico"
317IDI_FOLDER_SOURCE       ICON                    "res\\foldsrc.ico"
318IDI_WORKING             ICON                    "res\\working.ico"
319IDI_NONWORKING          ICON                    "res\\nonwork.ico"
320IDI_YEAR                ICON                    "res\\year.ico"
321IDI_KEYBOARD            ICON                    "res\\keyboard.ico"
322IDI_JOYSTICK            ICON                    "res\\joystick.ico"
323IDI_CPU                 ICON                    "res\\cpu.ico"
324IDI_SOUND               ICON                    "res\\samples.ico"
325IDI_SOUNDTAB            ICON                    "res\\sound.ico"
326IDI_SOURCE              ICON                    "res\\source.ico"
327IDI_HARDDISK            ICON                    "res\\harddisk.ico"
328IDI_DISPLAY             ICON                    "res\\display.ico"
329IDI_CHECKMARK           ICON                    "res\\checkmark.ico"
330IDI_HEADER_UP           ICON                    "res\\header_up.ico"
331IDI_HEADER_DOWN         ICON                    "res\\header_down.ico"
332
333#ifdef MESS
334IDI_WIN_NOROMSNEEDED    ICON                    "res/win_nrnd.ico"
335IDI_WIN_MISSINGOPTROM   ICON                  "res/win_noor.ico"
336IDI_WIN_FLOP            ICON        "res/win_flop.ico"
337IDI_WIN_CASS            ICON        "res/win_cass.ico"
338IDI_WIN_SERL            ICON        "res/win_serl.ico"
339IDI_WIN_SNAP            ICON        "res/win_snap.ico"
340IDI_WIN_PRIN            ICON        "res/win_prin.ico"
341IDI_WIN_HARD            ICON        "res/win_hard.ico"
342IDI_WIN_CYLN            ICON        "res/win_cyln.ico"
343IDI_WIN_PTAP            ICON        "res/win_ptap.ico"
344IDI_WIN_PCRD            ICON        "res/win_pcrd.ico"
345
346#endif
347
348/////////////////////////////////////////////////////////////////////////////
349//
350// Dialog
351//
352
353IDD_ABOUT DIALOG  0, 0, 296, 129
354STYLE DS_SETFONT | DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU
355#ifdef MESS
356CAPTION "About MESS"
357#else
358CAPTION "About MAME32"
359#endif
360FONT 8, "MS Shell Dlg"
361BEGIN
362    DEFPUSHBUTTON   "&OK",IDOK,200,109,50,14,WS_GROUP
363#ifdef MESS
364    CTEXT           "Multi Emulator Super System",IDC_STATIC,147,7,142,
365                    11,NOT WS_GROUP
366    CTEXT           "Version 0",IDC_VERSION,147,18,142,11,NOT WS_GROUP
367    CTEXT           "Copyright (C) 1998-2005 The MESS Team",IDC_STATIC,147,
368                    29,142,10,NOT WS_GROUP
369    CTEXT           "MESS GUI based on MAME32 version by",IDC_STATIC,147,51,142,10,NOT
370                    WS_GROUP
371    CONTROL         "",IDC_STATIC,"Static",SS_ETCHEDHORZ,147,44,142,1
372    CTEXT           "Additional MAME32 code by",IDC_STATIC,147,74,142,9
373    CTEXT           "Robert Schlabbach, Dan Miller (Help file)",IDC_STATIC,
374                    147,96,142,9
375    CTEXT           "Michael Soderstrom and Christopher Kirmse",IDC_STATIC,
376                    147,62,142,9,NOT WS_GROUP
377    CTEXT           "Mike Haaland, Andrew Kirmse, Jeff Miller",IDC_STATIC,
378                    147,85,142,9
379#else
380    CTEXT           "Multiple Arcade Machine Emulator",IDC_STATIC,147,7,142,
381                    11,NOT WS_GROUP
382    CTEXT           "Version 0",IDC_VERSION,147,18,142,11,NOT WS_GROUP
383    CTEXT           "Copyright (C) 1997-2007 The MAME Team",IDC_STATIC,147,
384                    29,142,10,NOT WS_GROUP
385    CTEXT           "MAME32 version by",IDC_STATIC,147,51,142,10,NOT
386                    WS_GROUP
387    CONTROL         "",IDC_STATIC,"Static",SS_ETCHEDHORZ,147,44,142,1
388    CTEXT           "Additional MAME32 code by",IDC_STATIC,147,74,142,9
389    CTEXT           "Christopher Kirmse and Michael Soderstrom",IDC_STATIC,
390                    147,62,142,9,NOT WS_GROUP
391    CTEXT           "Mike Haaland, Andrew Kirmse, Jeff Miller",IDC_STATIC,
392                    147,85,142,9
393    CTEXT           "and John Hardy IV",IDC_STATIC,147,96,142,9
394#endif
395    CONTROL         "",IDC_ABOUT,"Static",SS_BITMAP | SS_SUNKEN,7,7,16,14
396END
397
398IDD_DIRECTX DIALOG  0, 0, 236, 69
399STYLE DS_SETFONT | DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU
400#ifdef MESS
401CAPTION "MESS"
402#else
403CAPTION "MAME32"
404#endif
405FONT 8, "MS Shell Dlg"
406BEGIN
407    DEFPUSHBUTTON   "Go to Microsoft's DirectX Web Page",IDB_WEB_PAGE,48,52,
408                    140,14
409    EDITTEXT        IDC_DIRECTX_HELP,7,0,222,48,ES_MULTILINE |
410                    ES_AUTOHSCROLL | ES_READONLY
411END
412
413IDD_AUDIT DIALOG  0, 0, 283, 188
414STYLE DS_SETFONT | DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU
415CAPTION "File Audit"
416FONT 8, "MS Shell Dlg"
417BEGIN
418    PUSHBUTTON      "&Pause",IDPAUSE,98,168,40,14
419    PUSHBUTTON      "&Cancel",IDCANCEL,144,168,40,14
420    GROUPBOX        "ROMs",IDC_STATIC,6,4,132,65
421    LTEXT           "Correct:",IDC_STATIC,51,28,32,8
422    CONTROL         "Progress1",IDC_ROMS_PROGRESS,"msctls_progress32",
423                    WS_BORDER | 0x1,14,16,116,8
424    LTEXT           "Incorrect:",IDC_STATIC,51,42,32,8
425    LTEXT           "Total:",IDC_STATIC,51,56,32,8
426    LTEXT           "0",IDC_ROMS_CORRECT,87,28,20,8
427    LTEXT           "0",IDC_ROMS_INCORRECT,87,42,20,8
428    LTEXT           "0",IDC_ROMS_TOTAL,87,56,20,8
429    GROUPBOX        "Samples",IDC_STATIC,145,4,132,65
430    CONTROL         "Progress1",IDC_SAMPLES_PROGRESS,"msctls_progress32",
431                    WS_BORDER | 0x1,153,16,116,8
432    LTEXT           "Correct:",IDC_STATIC,191,28,33,8
433    LTEXT           "Incorrect:",IDC_STATIC,191,42,33,8
434    LTEXT           "Total:",IDC_STATIC,191,56,33,8
435    LTEXT           "0",IDC_SAMPLES_CORRECT,227,28,20,8
436    LTEXT           "0",IDC_SAMPLES_INCORRECT,227,42,20,8
437    LTEXT           "0",IDC_SAMPLES_TOTAL,227,56,20,8
438    GROUPBOX        "Details",IDC_STATIC,6,72,271,90
439    EDITTEXT        IDC_AUDIT_DETAILS,12,82,259,74,ES_MULTILINE |
440                    ES_AUTOVSCROLL | ES_READONLY | WS_VSCROLL | WS_HSCROLL |
441                    NOT WS_TABSTOP
442END
443
444IDD_DIRECTORIES DIALOG  0, 0, 230, 107
445STYLE DS_SETFONT | DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU
446CAPTION "Directories"
447FONT 8, "MS Shell Dlg"
448BEGIN
449    LTEXT           "Show directories for:",IDC_STATIC,6,6,67,10
450    COMBOBOX        IDC_DIR_COMBO,6,18,160,79,CBS_DROPDOWNLIST | CBS_SORT |
451                    WS_VSCROLL | WS_TABSTOP
452    LTEXT           "Directories:",IDC_STATIC,6,38,38,10
453    CONTROL         "List1",IDC_DIR_LIST,"SysListView32",LVS_REPORT |
454                    LVS_SINGLESEL | LVS_SHOWSELALWAYS | LVS_EDITLABELS |
455                    LVS_ALIGNLEFT | LVS_NOCOLUMNHEADER | WS_BORDER |
456                    WS_TABSTOP,6,50,160,51
457    DEFPUSHBUTTON   "OK",IDOK,173,8,50,14
458    PUSHBUTTON      "Cancel",IDCANCEL,173,26,50,14
459    PUSHBUTTON      "Browse...",IDC_DIR_BROWSE,173,50,50,14
460    PUSHBUTTON      "Insert",IDC_DIR_INSERT,173,68,50,14
461    PUSHBUTTON      "Delete",IDC_DIR_DELETE,173,87,50,14
462END
463
464IDD_COLUMNS DIALOG  0, 0, 302, 145
465STYLE DS_SETFONT | DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU
466CAPTION "Customize Fields"
467FONT 8, "MS Shell Dlg"
468BEGIN
469    LTEXT           "Available fields:",IDC_STATIC,6,6,80,10,SS_CENTERIMAGE
470    CONTROL         "List1",IDC_LISTAVAILABLECOLUMNS,"SysListView32",
471                    LVS_LIST | LVS_SINGLESEL | LVS_NOCOLUMNHEADER |
472                    LVS_NOSORTHEADER | WS_BORDER | WS_HSCROLL | WS_TABSTOP,6,
473                    18,90,100
474    PUSHBUTTON      "Add ->",IDC_BUTTONADD,102,18,46,14,WS_DISABLED
475    PUSHBUTTON      "<- Remove",IDC_BUTTONREMOVE,102,36,46,14,WS_DISABLED
476    LTEXT           "Show these fields in this order:",IDC_STATIC,154,6,96,
477                    10,SS_CENTERIMAGE
478    CONTROL         "List1",IDC_LISTSHOWCOLUMNS,"SysListView32",LVS_LIST |
479                    LVS_SINGLESEL | LVS_NOCOLUMNHEADER | LVS_NOSORTHEADER |
480                    WS_BORDER | WS_HSCROLL | WS_TABSTOP,154,18,90,100
481    PUSHBUTTON      "Move Up",IDC_BUTTONMOVEUP,250,18,46,14,WS_DISABLED
482    PUSHBUTTON      "Move Down",IDC_BUTTONMOVEDOWN,250,36,46,14,WS_DISABLED
483    DEFPUSHBUTTON   "OK",IDOK,105,124,44,14
484    PUSHBUTTON      "Cancel",IDCANCEL,155,124,44,14
485END
486
487IDD_PROP_CONTROLLER DIALOGEX 0, 0, 220, 240
488STYLE DS_SETFONT | DS_FIXEDSYS | WS_CHILD | WS_DISABLED | WS_CAPTION
489CAPTION "Controller Mapping"
490FONT 8, "MS Shell Dlg", 0, 0, 0x1
491BEGIN
492    ICON            IDI_JOYSTICK,IDC_STATIC,20,10,20,20
493    LTEXT           "Title\nDirectory\nExtra",IDC_PROP_TITLE,52,9,161,25,
494                    SS_NOPREFIX
495    GROUPBOX        "Paddle device",IDC_STATIC,4,40,102,28
496    COMBOBOX        IDC_PADDLE,10,50,91,62,CBS_DROPDOWNLIST | WS_VSCROLL |
497                    WS_TABSTOP,0,HIDC_PADDLE
498    GROUPBOX        "ADStick device",IDC_STATIC,4,71,102,28
499    COMBOBOX        IDC_ADSTICK,10,80,91,62,CBS_DROPDOWNLIST | WS_VSCROLL |
500                    WS_TABSTOP,0,HIDC_ADSTICK
501    GROUPBOX        "Pedal device",IDC_STATIC,4,102,102,28
502    COMBOBOX        IDC_PEDAL,10,112,91,62,CBS_DROPDOWNLIST | WS_VSCROLL |
503                    WS_TABSTOP,0,HIDC_PEDAL
504    GROUPBOX        "Mouse device",IDC_STATIC,4,133,102,28
505    COMBOBOX        IDC_MOUSE,10,142,90,62,CBS_DROPDOWNLIST | WS_VSCROLL |
506                    WS_TABSTOP,0,HIDC_MOUSE
507    GROUPBOX        "Dial device",IDC_STATIC,113,40,102,28
508    COMBOBOX        IDC_DIAL,119,50,90,62,CBS_DROPDOWNLIST | WS_VSCROLL |
509                    WS_TABSTOP,0,HIDC_DIAL
510    GROUPBOX        "Trackball device",IDC_STATIC,113,71,102,28
511    COMBOBOX        IDC_TRACKBALL,119,80,90,62,CBS_DROPDOWNLIST | WS_VSCROLL |
512                    WS_TABSTOP,0,HIDC_TRACKBALL
513    GROUPBOX        "Lightgun device",IDC_STATIC,113,102,102,28
514    COMBOBOX        IDC_LIGHTGUNDEVICE,119,112,90,62,CBS_DROPDOWNLIST |
515                    WS_VSCROLL | WS_TABSTOP,0,HIDC_LIGHTGUNDEVICE
516    GROUPBOX        "Positional device",IDC_STATIC,113,133,102,28
517    COMBOBOX        IDC_POSITIONAL,119,142,90,62,CBS_DROPDOWNLIST |
518                    WS_VSCROLL | WS_TABSTOP,0,HIDC_POSITIONAL
519    PUSHBUTTON      "Reset",IDC_PROP_RESET,4,222,97,14,0,0,HIDC_PROP_RESET
520    PUSHBUTTON      "Restore Default Settings",IDC_USE_DEFAULT,118,222,97,14,
521                    0,0,HIDC_USE_DEFAULT
522END
523
524IDD_PROP_SCREEN DIALOGEX 0, 0, 220, 240
525STYLE DS_SETFONT | WS_CHILD | WS_CAPTION
526CAPTION "Screen"
527FONT 8, "MS Shell Dlg", 0, 0, 0x1
528BEGIN
529    ICON            IDI_DISPLAY,IDC_STATIC,20,10,21,20
530    LTEXT           "Title\nDirectory\nExtra",IDC_PROP_TITLE,52,9,161,25,
531                    SS_NOPREFIX
532    GROUPBOX        "Number of screens",IDC_STATIC,4,40,103,24
533    CONTROL         "GammaSlider",IDC_NUMSCREENS,"msctls_trackbar32",
534                    TBS_BOTH | TBS_NOTICKS | WS_TABSTOP,10,50,75,10,0,
535                    HIDC_NUMSCREENS
536    RTEXT           "1",IDC_NUMSCREENSDISP,84,49,14,10,SS_CENTERIMAGE | NOT
537                    WS_GROUP
538    GROUPBOX        "Screen",IDC_STATIC,4,66,103,29
539    COMBOBOX        IDC_SCREEN,10,76,91,64,CBS_DROPDOWNLIST | WS_VSCROLL |
540                    WS_TABSTOP,0,HIDC_SCREEN
541    GROUPBOX        "",IDC_STATIC,4,97,103,28
542    CONTROL         "Autoselect aspect",IDC_ASPECT,"Button",BS_AUTOCHECKBOX |
543                    WS_TABSTOP,10,97,73,10,0,HIDC_ASPECT
544    LTEXT           "Aspect ratio",IDC_ASPECTRATIOTEXT,17,108,40,11,
545                    SS_CENTERIMAGE | NOT WS_GROUP
546    EDITTEXT        IDC_ASPECTRATION,60,108,14,12,ES_RIGHT | ES_AUTOHSCROLL |
547                    ES_NUMBER,0,HIDC_ASPECTRATION
548    LTEXT           ":",IDC_STATIC,76,108,8,10,SS_CENTERIMAGE | NOT WS_GROUP
549    EDITTEXT        IDC_ASPECTRATIOD,80,108,14,12,ES_RIGHT | ES_AUTOHSCROLL |
550                    ES_NUMBER,0,HIDC_ASPECTRATIOD
551    GROUPBOX        "View",IDC_STATIC,4,128,103,28
552    COMBOBOX        IDC_VIEW,10,137,91,64,CBS_DROPDOWNLIST | WS_VSCROLL |
553                    WS_TABSTOP,0,HIDC_VIEW
554    GROUPBOX        "Screennumber",IDC_SCREENSELECTTEXT,113,40,102,28
555    COMBOBOX        IDC_SCREENSELECT,119,50,90,64,CBS_DROPDOWNLIST |
556                    WS_VSCROLL | WS_TABSTOP,0,HIDC_SCREENSELECT
557    GROUPBOX        "Resolution",IDC_STATIC,113,71,102,76,WS_GROUP
558    GROUPBOX        "Size",IDC_STATIC,119,81,90,28,WS_GROUP
559    COMBOBOX        IDC_SIZES,126,91,77,70,CBS_DROPDOWNLIST | WS_VSCROLL |
560                    WS_TABSTOP,0,HIDC_SIZES
561    GROUPBOX        "Refresh",IDC_REFRESHTEXT,119,112,90,28,WS_GROUP
562    COMBOBOX        IDC_REFRESH,126,121,77,76,CBS_DROPDOWNLIST | WS_VSCROLL |
563                    WS_TABSTOP,0,HIDC_REFRESH
564    CONTROL         "Switch resolutions to fit",IDC_SWITCHRES,"Button",
565                    BS_AUTOCHECKBOX | WS_TABSTOP,119,151,93,10,0,
566                    HIDC_SWITCHRES
567    PUSHBUTTON      "Reset",IDC_PROP_RESET,4,222,97,14,0,0,HIDC_PROP_RESET
568    PUSHBUTTON      "Restore Default Settings",IDC_USE_DEFAULT,118,222,97,14,
569                    0,0,HIDC_USE_DEFAULT
570END
571
572IDD_PROP_GAME DIALOG  0, 0, 220, 240
573STYLE DS_SETFONT | WS_CHILD | WS_CAPTION
574CAPTION "General"
575FONT 8, "MS Shell Dlg"
576BEGIN
577    ICON            IDI_MAME32_ICON,IDC_GAME_ICON,20,10,20,20
578    LTEXT           "Title\nDirectory\nExtra",IDC_PROP_TITLE,52,9,161,25,
579                    SS_NOPREFIX
580    CONTROL         "",IDC_STATIC,"Static",SS_ETCHEDHORZ,20,38,178,1
581    LTEXT           "Manufactured:",IDC_STATIC,18,45,47,8
582    LTEXT           "Static",IDC_PROP_MANUFACTURED,75,45,139,9,SS_NOPREFIX
583    LTEXT           "Status:",IDC_STATIC,18,55,47,8
584    LTEXT           "Static",IDC_PROP_STATUS,75,55,139,30
585    CONTROL         "",IDC_STATIC,"Static",SS_ETCHEDHORZ,18,85,178,1
586    LTEXT           "CPU:",IDC_STATIC,18,90,47,8
587    LTEXT           "Static\nStatic\nStatic\nStatic\nStatic",IDC_PROP_CPU,75,
588                    90,139,40
589    CONTROL         "",IDC_STATIC,"Static",SS_ETCHEDHORZ,18,130,178,1
590    LTEXT           "Sound:",IDC_STATIC,18,135,47,8
591    LTEXT           "Static\nStatic\nStatic\nStatic\nStatic",IDC_PROP_SOUND,
592                    75,135,139,45
593    CONTROL         "",IDC_STATIC,"Static",SS_ETCHEDHORZ,18,181,178,1
594    LTEXT           "Screen:",IDC_STATIC,18,188,47,8
595    LTEXT           "Static",IDC_PROP_SCREEN,75,188,139,8
596    LTEXT           "Colors:",IDC_STATIC,18,198,47,8
597    LTEXT           "Static",IDC_PROP_COLORS,75,198,139,8
598    LTEXT           "Clone of:",IDC_PROP_CLONEOF_TEXT,18,218,50,8
599    LTEXT           "Static",IDC_PROP_CLONEOF,75,218,130,18
600    LTEXT           "Source:",IDC_STATIC,18,208,47,8
601    LTEXT           "Static",IDC_PROP_SOURCE,75,208,139,8
602END
603
604IDD_PROP_AUDIT DIALOG  0, 0, 220, 240
605STYLE DS_SETFONT | WS_CHILD | WS_CAPTION
606CAPTION "Audit"
607FONT 8, "MS Shell Dlg"
608BEGIN
609    ICON            IDI_CHECKMARK,IDC_STATIC,20,10,20,20
610    LTEXT           "Title\nDirectory\nExtra",IDC_PROP_TITLE,52,9,161,25,
611                    SS_NOPREFIX
612    LTEXT           "ROM check:",IDC_STATIC,10,40,50,8
613    LTEXT           "Checking...",IDC_PROP_ROMS,66,40,139,8
614    LTEXT           "Sample check:",IDC_STATIC,10,52,50,8
615    LTEXT           "Checking...",IDC_PROP_SAMPLES,66,52,139,8
616    GROUPBOX        "Details",IDC_STATIC,4,64,211,171
617    EDITTEXT        IDC_AUDIT_DETAILS_PROP,10,74,199,155,ES_MULTILINE |
618                    ES_AUTOVSCROLL | ES_READONLY | WS_VSCROLL | WS_HSCROLL |
619                    NOT WS_TABSTOP
620END
621
622IDD_PROP_DISPLAY DIALOGEX 0, 0, 220, 240
623STYLE DS_SETFONT | WS_CHILD | WS_CAPTION
624CAPTION "Display"
625FONT 8, "MS Shell Dlg", 0, 0, 0x1
626BEGIN
627    ICON            IDI_DISPLAY,IDC_STATIC,20,10,20,20
628    LTEXT           "Title\nDirectory\nExtra",IDC_PROP_TITLE,52,9,169,25,
629                    SS_NOPREFIX
630    CONTROL         "Run in a window",IDC_WINDOWED,"Button",BS_AUTOCHECKBOX |
631                    WS_TABSTOP,10,40,69,10,0,HIDC_WINDOWED
632    CONTROL         "Start out maximized",IDC_MAXIMIZE,"Button",
633                    BS_AUTOCHECKBOX | WS_TABSTOP,10,52,74,10,0,HIDC_MAXIMIZE
634    CONTROL         "Enforce aspect ratio",IDC_KEEPASPECT,"Button",
635                    BS_AUTOCHECKBOX | WS_TABSTOP,10,64,77,10,0,
636                    HIDC_KEEPASPECT
637    CONTROL         "Throttle",IDC_THROTTLE,"Button",BS_AUTOCHECKBOX |
638                    WS_TABSTOP,10,76,39,10,0,HIDC_THROTTLE
639    GROUPBOX        "Bitmap prescaling",IDC_STATIC,4,89,103,24
640    CONTROL         "GammaSlider",IDC_PRESCALE,"msctls_trackbar32",TBS_BOTH |
641                    TBS_NOTICKS | WS_TABSTOP,10,99,71,10,0,HIDC_PRESCALE
642    RTEXT           "1.00",IDC_PRESCALEDISP,84,98,14,11,SS_CENTERIMAGE | NOT
643                    WS_GROUP
644    GROUPBOX        "Gamma Correction",IDC_STATIC,4,115,103,24
645    CONTROL         "GammaSlider",IDC_GAMMA,"msctls_trackbar32",TBS_BOTH |
646                    TBS_NOTICKS | WS_TABSTOP,10,125,71,10,0,HIDC_GAMMA
647    RTEXT           "2.00",IDC_GAMMADISP,84,124,14,10,SS_CENTERIMAGE | NOT
648                    WS_GROUP
649    GROUPBOX        "Brightness Correction",IDC_STATIC,4,141,103,24
650    CONTROL         "GammaSlider",IDC_BRIGHTCORRECT,"msctls_trackbar32",
651                    TBS_BOTH | TBS_NOTICKS | WS_TABSTOP,10,151,71,10,0,
652                    HIDC_BRIGHTCORRECT
653    RTEXT           "1.00",IDC_BRIGHTCORRECTDISP,84,150,14,10,SS_CENTERIMAGE |
654                    NOT WS_GROUP
655    GROUPBOX        "Contrast Correction",IDC_STATIC,4,167,103,24
656    CONTROL         "GammaSlider",IDC_CONTRAST,"msctls_trackbar32",TBS_BOTH |
657                    TBS_NOTICKS | WS_TABSTOP,10,176,71,10,0,HIDC_CONTRAST
658    RTEXT           "1.00",IDC_CONTRASTDISP,84,175,14,11,SS_CENTERIMAGE |
659                    NOT WS_GROUP
660    GROUPBOX        "Pause Brightness",IDC_STATIC,4,193,103,24
661    CONTROL         "Slider1",IDC_PAUSEBRIGHT,"msctls_trackbar32",TBS_BOTH |
662                    TBS_NOTICKS | WS_TABSTOP,10,203,71,10,0,HIDC_PAUSEBRIGHT
663    RTEXT           "0.65",IDC_PAUSEBRIGHTDISP,84,202,14,11,SS_CENTERIMAGE |
664                    NOT WS_GROUP
665    GROUPBOX        "Videomode",IDC_STATIC,113,40,102,28
666    COMBOBOX        IDC_VIDEO_MODE,119,50,90,50,CBS_DROPDOWNLIST | CBS_SORT |
667                    WS_VSCROLL | WS_TABSTOP,0,HIDC_VIDEO_MODE
668    GROUPBOX        "Rotation",IDC_STATIC,113,71,102,55
669    COMBOBOX        IDC_ROTATE,119,81,90,57,CBS_DROPDOWNLIST | WS_VSCROLL |
670                    WS_TABSTOP,0,HIDC_ROTATE
671    CONTROL         "Flip screen upside-down",IDC_FLIPY,"Button",
672                    BS_AUTOCHECKBOX | WS_TABSTOP,119,98,91,10,0,HIDC_FLIPY
673    CONTROL         "Flip screen left-right",IDC_FLIPX,"Button",
674                    BS_AUTOCHECKBOX | WS_TABSTOP,119,110,77,10,0,HIDC_FLIPX
675    GROUPBOX        "Direct3D",IDC_STATIC,113,128,102,57
676    CONTROL         "Use Bilinear filtering",IDC_D3D_FILTER,"Button",
677                    BS_AUTOCHECKBOX | WS_TABSTOP,119,138,85,10,0,
678                    HIDC_D3D_FILTER
679    GROUPBOX        "Version",IDC_STATIC,119,150,90,28
680    COMBOBOX        IDC_D3D_VERSION,125,160,78,95,CBS_DROPDOWNLIST |
681                    WS_VSCROLL | WS_TABSTOP,0,HIDC_D3D_VERSION
682    GROUPBOX        "DirectDraw",IDC_STATIC,113,187,102,26
683    CONTROL         "Stretch using hardware",IDC_HWSTRETCH,"Button",
684                    BS_AUTOCHECKBOX | WS_TABSTOP,119,197,85,10,0,
685                    HIDC_HWSTRETCH
686    PUSHBUTTON      "Reset",IDC_PROP_RESET,4,222,97,14,0,0,HIDC_PROP_RESET
687    PUSHBUTTON      "Restore Default Settings",IDC_USE_DEFAULT,118,222,97,14,
688                    0,0,HIDC_USE_DEFAULT
689END
690
691IDD_PROP_SOUND DIALOGEX 0, 0, 220, 240
692STYLE DS_SETFONT | WS_CHILD | WS_CAPTION
693CAPTION "Sound"
694FONT 8, "MS Shell Dlg", 0, 0, 0x1
695BEGIN
696    ICON            IDI_SOUNDTAB,IDC_STATIC,20,10,20,20
697    LTEXT           "Title\nDirectory\nExtra",IDC_PROP_TITLE,52,9,161,25,
698                    SS_NOPREFIX
699    GROUPBOX        "",IDC_STATIC,4,40,211,122
700    CONTROL         "Enable sound and sound CPUs",IDC_USE_SOUND,"Button",
701                    BS_AUTOCHECKBOX | WS_TABSTOP,10,40,112,10,0,
702                    HIDC_USE_SOUND
703    CONTROL         "Use samples",IDC_SAMPLES,"Button",BS_AUTOCHECKBOX |
704                    WS_TABSTOP,10,52,55,10,0,HIDC_SAMPLES
705    GROUPBOX        "Sample rate",IDC_RATETEXT,60,65,100,28
706    COMBOBOX        IDC_SAMPLERATE,66,75,88,60,CBS_DROPDOWNLIST | WS_VSCROLL |
707                    WS_TABSTOP,0,HIDC_SAMPLERATE
708    GROUPBOX        "Volume attenuation",IDC_STATIC,60,96,100,28
709    CONTROL         "Slider1",IDC_VOLUME,"msctls_trackbar32",TBS_BOTH |
710                    TBS_NOTICKS | WS_TABSTOP,66,108,68,10,0,HIDC_VOLUME
711    RTEXT           "0dB",IDC_VOLUMEDISP,132,107,20,11,SS_CENTERIMAGE
712    GROUPBOX        "Audio latency",IDC_AUDIO_LATENCY_TEXT,60,127,100,28
713    CONTROL         "Slider1",IDC_AUDIO_LATENCY,"msctls_trackbar32",TBS_BOTH |
714                    TBS_NOTICKS | WS_TABSTOP,66,139,68,10,0,
715                    HIDC_AUDIO_LATENCY
716    RTEXT           "1/5",IDC_AUDIO_LATENCY_DISP,132,138,20,11,
717                    SS_CENTERIMAGE
718    PUSHBUTTON      "Reset",IDC_PROP_RESET,4,222,97,14,0,0,HIDC_PROP_RESET
719    PUSHBUTTON      "Restore Default Settings",IDC_USE_DEFAULT,118,222,97,14,
720                    0,0,HIDC_USE_DEFAULT
721END
722
723IDD_PROP_ADVANCED DIALOGEX 0, 0, 220, 240
724STYLE DS_SETFONT | DS_FIXEDSYS | WS_CHILD | WS_CAPTION
725CAPTION "Advanced"
726FONT 8, "MS Shell Dlg", 0, 0, 0x1
727BEGIN
728    ICON            IDI_DISPLAY,IDC_STATIC,20,10,20,20
729    LTEXT           "Title\nDirectory\nExtra",IDC_PROP_TITLE,52,9,161,25,
730                    SS_NOPREFIX
731    CONTROL         "Triple buffering",IDC_TRIPLE_BUFFER,"Button",
732                    BS_AUTOCHECKBOX | WS_TABSTOP,10,40,93,10,0,
733                    HIDC_TRIPLE_BUFFER
734    CONTROL         "Sync to monitor refresh",IDC_SYNCREFRESH,"Button",
735                    BS_AUTOCHECKBOX | WS_TABSTOP,10,52,93,10,0,
736                    HIDC_SYNCREFRESH
737    CONTROL         "Wait for vertical sync",IDC_WAITVSYNC,"Button",
738                    BS_AUTOCHECKBOX | WS_TABSTOP,10,64,93,10,0,
739                    HIDC_WAITVSYNC
740    CONTROL         "Refresh speed",IDC_REFRESHSPEED,"Button",
741                    BS_AUTOCHECKBOX | WS_TABSTOP,10,76,93,10,0,
742                    HIDC_REFRESHSPEED
743    GROUPBOX        "Frame skipping",IDC_STATIC,4,88,103,42
744    CONTROL         "Automatic",IDC_AUTOFRAMESKIP,"Button",BS_AUTOCHECKBOX |
745                    WS_TABSTOP,10,98,77,10,0,HIDC_AUTOFRAMESKIP
746    COMBOBOX        IDC_FRAMESKIP,10,111,91,88,CBS_DROPDOWNLIST | WS_VSCROLL |
747                    WS_TABSTOP,0,HIDC_FRAMESKIP
748    GROUPBOX        "Full screen gamma",IDC_FSGAMMATEXT,113,40,102,24
749    CONTROL         "Slider1",IDC_FSGAMMA,"msctls_trackbar32",TBS_BOTH |
750                    TBS_NOTICKS | WS_TABSTOP,119,50,71,10,0,HIDC_FSGAMMA
751    RTEXT           "2.00",IDC_FSGAMMADISP,193,49,16,10,SS_CENTERIMAGE | NOT
752                    WS_GROUP
753    GROUPBOX        "Full screen brightness",IDC_FSBRIGHTNESSTEXT,113,67,102,
754                    24
755    CONTROL         "Slider1",IDC_FSBRIGHTNESS,"msctls_trackbar32",TBS_BOTH |
756                    TBS_NOTICKS | WS_TABSTOP,119,77,71,10,0,
757                    HIDC_FSBRIGHTNESS
758    RTEXT           "2.00",IDC_FSBRIGHTNESSDISP,193,76,16,10,SS_CENTERIMAGE |
759                    NOT WS_GROUP
760    GROUPBOX        "Full screen contrast",IDC_FSCONTRASTTEXT,113,94,102,24
761    CONTROL         "Slider1",IDC_FSCONTRAST,"msctls_trackbar32",TBS_BOTH |
762                    TBS_NOTICKS | WS_TABSTOP,119,104,71,10,0,HIDC_FSCONTRAST
763    RTEXT           "2.00",IDC_FSCONTRASTDISP,193,103,16,11,SS_CENTERIMAGE |
764                    NOT WS_GROUP
765    GROUPBOX        "Emulation speed",IDC_SPEEDTEXT,4,133,211,24
766    CONTROL         "Slider1",IDC_SPEED,"msctls_trackbar32",TBS_BOTH |
767                    TBS_NOTICKS | WS_TABSTOP,10,143,180,10,0,HIDC_SPEED
768    RTEXT           "1.00",IDC_SPEEDDISP,189,142,20,11,SS_CENTERIMAGE | NOT
769                    WS_GROUP
770    GROUPBOX        "Effect",IDC_STATIC,4,160,211,50
771    EDITTEXT        IDC_EFFECT,10,170,200,14,ES_AUTOHSCROLL | WS_DISABLED
772    PUSHBUTTON      "Select Effect",IDC_SELECT_EFFECT,10,189,60,14,0,0,
773                    HIDC_SELECT_EFFECT
774    PUSHBUTTON      "Reset Effect",IDC_RESET_EFFECT,150,189,60,14,0,0,
775                    HIDC_RESET_EFFECT
776    PUSHBUTTON      "Reset",IDC_PROP_RESET,4,222,97,14,0,0,HIDC_PROP_RESET
777    PUSHBUTTON      "Restore Default Settings",IDC_USE_DEFAULT,118,222,97,14,
778                    0,0,HIDC_USE_DEFAULT
779END
780
781IDD_PROP_INPUT DIALOGEX 0, 0, 220, 240
782STYLE DS_SETFONT | DS_FIXEDSYS | WS_CHILD | WS_CAPTION
783CAPTION "Controllers"
784FONT 8, "MS Shell Dlg", 0, 0, 0x1
785BEGIN
786    ICON            IDI_JOYSTICK,IDC_STATIC,20,10,20,20
787    LTEXT           "Title\nDirectory\nExtra",IDC_PROP_TITLE,52,9,161,25,
788                    SS_NOPREFIX
789    CONTROL         "Enable mouse input",IDC_USE_MOUSE,"Button",
790                    BS_AUTOCHECKBOX | WS_TABSTOP,10,40,86,10,0,
791                    HIDC_USE_MOUSE
792    CONTROL         "Enable steadykey support",IDC_STEADYKEY,"Button",
793                    BS_AUTOCHECKBOX | WS_TABSTOP,10,52,95,10,0,
794                    HIDC_STEADYKEY
795    GROUPBOX        "",IDC_STATIC,4,64,103,74
796    CONTROL         "Enable joystick input",IDC_JOYSTICK,"Button",
797                    BS_AUTOCHECKBOX | WS_GROUP | WS_TABSTOP,10,64,78,10,0,
798                    HIDC_JOYSTICK
799    GROUPBOX        "Joystick deadzone",IDC_JDZTEXT,10,76,91,28
800    CONTROL         "IntensitySlider",IDC_JDZ,"msctls_trackbar32",TBS_BOTH |
801                    TBS_NOTICKS | WS_TABSTOP,15,88,60,10,0,HIDC_JDZ
802    RTEXT           "0.3",IDC_JDZDISP,76,87,16,11,SS_CENTERIMAGE | NOT
803                    WS_GROUP
804    GROUPBOX        "Default input layout",IDC_STATIC,113,40,102,28
805    COMBOBOX        IDC_DEFAULT_INPUT,119,50,90,53,CBS_DROPDOWNLIST |
806                    WS_VSCROLL | WS_TABSTOP,0,HIDC_DEFAULT_INPUT
807    GROUPBOX        "",IDC_STATIC,113,71,102,66
808    CONTROL         "Enable lightgun input",IDC_LIGHTGUN,"Button",
809                    BS_AUTOCHECKBOX | WS_TABSTOP,119,71,80,10,0,
810                    HIDC_LIGHTGUN
811    CONTROL         "Offscreen shots reload",IDC_RELOAD,"Button",
812                    BS_AUTOCHECKBOX | WS_TABSTOP,119,83,86,10,0,HIDC_RELOAD
813    CONTROL         "Dual lightguns",IDC_DUAL_LIGHTGUN,"Button",
814                    BS_AUTOCHECKBOX | WS_TABSTOP,119,96,86,10,0,
815                    HIDC_DUAL_LIGHTGUN
816    CONTROL         "Multiple keyboards",IDC_MULTIKEYBOARD,"Button",
817                    BS_AUTOCHECKBOX | WS_TABSTOP,119,109,75,10,0,
818                    HIDC_MULTIKEYBOARD
819    CONTROL         "Multiple mice",IDC_MULTIMOUSE,"Button",BS_AUTOCHECKBOX |
820                    WS_TABSTOP,119,122,56,10,0,HIDC_MULTIMOUSE
821    GROUPBOX        "Joystick saturation",IDC_JSATTEXT,10,106,91,28
822    CONTROL         "IntensitySlider",IDC_JSAT,"msctls_trackbar32",TBS_BOTH |
823                    TBS_NOTICKS | WS_TABSTOP,16,118,60,10,0,HIDC_JSAT
824    RTEXT           "0.85",IDC_JSATDISP,76,116,16,11,SS_CENTERIMAGE | NOT
825                    WS_GROUP
826    PUSHBUTTON      "Reset",IDC_PROP_RESET,4,222,97,14,0,0,HIDC_PROP_RESET
827    PUSHBUTTON      "Restore Default Settings",IDC_USE_DEFAULT,118,222,97,14,
828                    0,0,HIDC_USE_DEFAULT
829END
830
831IDD_PROP_MISC DIALOGEX 0, 0, 220, 240
832STYLE DS_SETFONT | DS_FIXEDSYS | WS_CHILD | WS_CAPTION
833CAPTION "Miscellaneous"
834FONT 8, "MS Shell Dlg", 0, 0, 0x1
835BEGIN
836    ICON            IDI_MAME32_ICON,IDC_STATIC,20,10,20,20
837    LTEXT           "Title\nDirectory\nExtra",IDC_PROP_TITLE,52,9,161,25,
838                    SS_NOPREFIX
839#ifdef MESS
840    CONTROL         "Enable system cheats",IDC_CHEAT,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,10,40,86,10,0,HIDC_CHEAT
841#else
842    CONTROL         "Enable game cheats",IDC_CHEAT,"Button",BS_AUTOCHECKBOX |
843                    WS_TABSTOP,10,40,86,10,0,HIDC_CHEAT
844#endif
845    CONTROL         "Error log (for developers)",IDC_LOG,"Button",
846                    BS_AUTOCHECKBOX | WS_TABSTOP,10,52,96,10,0,HIDC_LOG
847    CONTROL         "Sleep when possible",IDC_SLEEP,"Button",BS_AUTOCHECKBOX |
848                    WS_TABSTOP,10,64,86,10,0,HIDC_SLEEP
849    CONTROL         "Enable game debugger",IDC_DEBUG,"Button",
850                    BS_AUTOCHECKBOX | WS_TABSTOP,10,76,86,10,0,HIDC_DEBUG
851#ifdef MESS
852    CONTROL         "Skip system info",IDC_SKIP_GAME_INFO,"Button",
853                    BS_AUTOCHECKBOX | WS_TABSTOP,10,88,96,10,0,
854                    HIDC_SKIP_GAME_INFO
855#else
856    CONTROL         "Skip game info",IDC_SKIP_GAME_INFO,"Button",
857                    BS_AUTOCHECKBOX | WS_TABSTOP,10,88,96,10,0,
858                    HIDC_SKIP_GAME_INFO
859#endif
860    CONTROL         "Save game state on exit",IDC_ENABLE_AUTOSAVE,"Button",
861                    BS_AUTOCHECKBOX | WS_TABSTOP,10,100,96,10,0,
862                    HIDC_ENABLE_AUTOSAVE
863    CONTROL         "Multi-threaded rendering",IDC_MULTITHREAD_RENDERING,
864                    "Button",BS_AUTOCHECKBOX | WS_TABSTOP,10,112,96,10,0,
865                    HIDC_MULTITHREAD_RENDERING
866    GROUPBOX        "Thread Priority",IDC_HIGH_PRIORITY_TEXT,4,124,103,34
867    CONTROL         "Slider1",IDC_HIGH_PRIORITY,"msctls_trackbar32",TBS_BOTH |
868                    TBS_NOTICKS | WS_TABSTOP,10,135,75,10,0,
869                    HIDC_HIGH_PRIORITY
870    LTEXT           "idle",IDC_STATIC,13,144,12,8
871    RTEXT           "-15",IDC_HIGH_PRIORITYTXT,84,134,14,10,SS_CENTERIMAGE
872    RTEXT           "real-time",IDC_STATIC,53,144,28,8
873    GROUPBOX        "Artwork options",IDC_STATIC,113,40,102,61
874    CONTROL         "Backdrops",IDC_BACKDROPS,"Button",BS_AUTOCHECKBOX |
875                    WS_TABSTOP,119,50,86,10,0,HIDC_BACKDROPS
876    CONTROL         "Bezels",IDC_BEZELS,"Button",BS_AUTOCHECKBOX |
877                    WS_TABSTOP,119,62,86,10,0,HIDC_BEZELS
878    CONTROL         "Overlays",IDC_OVERLAYS,"Button",BS_AUTOCHECKBOX |
879                    WS_TABSTOP,119,74,84,10,0,HIDC_OVERLAYS
880    CONTROL         "Crop artwork",IDC_ARTWORK_CROP,"Button",BS_AUTOCHECKBOX |
881                    WS_TABSTOP,119,86,53,10,0,HIDC_ARTWORK_CROP
882    GROUPBOX        "BIOS",IDC_STATIC,113,104,102,28
883    COMBOBOX        IDC_BIOS,119,114,90,60,CBS_DROPDOWNLIST | WS_VSCROLL |
884                    WS_TABSTOP,0,HIDC_BIOS
885    PUSHBUTTON      "Reset",IDC_PROP_RESET,4,222,97,14,0,0,HIDC_PROP_RESET
886    PUSHBUTTON      "Restore Default Settings",IDC_USE_DEFAULT,118,222,97,14,
887                    0,0,HIDC_USE_DEFAULT
888#ifdef MESS
889    CONTROL         "Skip warnings",IDC_SKIP_WARNINGS,"Button",
890                    BS_AUTOCHECKBOX | WS_TABSTOP,10,180,86,10,0
891    CONTROL         "Use New UI",IDC_USE_NEW_UI,"Button",
892                    BS_AUTOCHECKBOX | WS_TABSTOP,10,192,86,10,0
893#endif
894END
895
896IDD_PROP_VECTOR DIALOGEX 0, 0, 220, 240
897STYLE DS_SETFONT | WS_CHILD | WS_CAPTION
898CAPTION "Vector"
899FONT 8, "MS Shell Dlg", 0, 0, 0x1
900BEGIN
901    ICON            IDI_MAME32_ICON,IDC_STATIC,20,10,20,20
902    LTEXT           "Title\nDirectory\nExtra",IDC_PROP_TITLE,52,9,161,25,
903                    SS_NOPREFIX
904    CONTROL         "Draw antialiased vectors",IDC_ANTIALIAS,"Button",
905                    BS_AUTOCHECKBOX | WS_TABSTOP,10,40,92,10,0,
906                    HIDC_ANTIALIAS
907    GROUPBOX        "Beam width",IDC_BEAMTEXT,60,53,100,28
908    CONTROL         "BeamSlider",IDC_BEAM,"msctls_trackbar32",TBS_BOTH |
909                    TBS_NOTICKS | WS_TABSTOP,66,65,64,10,0,HIDC_BEAM
910    RTEXT           "16.00",IDC_BEAMDISP,132,64,20,11,SS_CENTERIMAGE
911    GROUPBOX        "Flicker",IDC_FLICKERTEXT,60,84,100,28
912    CONTROL         "FlickerSlider",IDC_FLICKER,"msctls_trackbar32",TBS_BOTH |
913                    TBS_NOTICKS | WS_TABSTOP,66,96,64,10,0,HIDC_FLICKER
914    RTEXT           "100.00",IDC_FLICKERDISP,128,95,24,11,SS_CENTERIMAGE |
915                    NOT WS_GROUP
916    PUSHBUTTON      "Reset",IDC_PROP_RESET,4,222,97,14,0,0,HIDC_PROP_RESET
917    PUSHBUTTON      "Restore Default Settings",IDC_USE_DEFAULT,118,222,97,14,
918                    0,0,HIDC_USE_DEFAULT
919END
920
921
922#ifdef MESS
923IDD_MAIN DIALOGEX 0, 0, 364, 206
924#else
925IDD_MAIN DIALOGEX 0, 0, 304, 206
926#endif
927STYLE DS_SETFONT | DS_3DLOOK | DS_NOFAILCREATE | WS_MINIMIZEBOX |
928    WS_MAXIMIZEBOX | WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME
929EXSTYLE WS_EX_CONTROLPARENT
930CAPTION "MAME32 - overwritten at runtime"
931CLASS "MainClass"
932FONT 8, "MS Shell Dlg", 0, 0, 0x1
933BEGIN
934    CONTROL         "",IDC_DIVIDER,"Static",SS_ETCHEDHORZ,0,5,304,1
935    CONTROL         "Tree1",IDC_TREE,"SysTreeView32",TVS_HASBUTTONS |
936                    TVS_HASLINES | TVS_LINESATROOT | TVS_EDITLABELS |
937                    TVS_SHOWSELALWAYS | TVS_FULLROWSELECT | WS_BORDER |
938                    WS_TABSTOP,5,28,48,172
939    CONTROL         "List1",IDC_LIST,"SysListView32",LVS_REPORT |
940                    LVS_SINGLESEL | LVS_SHOWSELALWAYS | LVS_AUTOARRANGE |
941                    LVS_OWNERDRAWFIXED | WS_BORDER | WS_TABSTOP,65,28,42,172
942    GROUPBOX        "",IDC_SPLITTER,55,28,8,172,BS_NOTIFY | NOT WS_VISIBLE
943    GROUPBOX        "",IDC_SPLITTER2,109,28,8,172,BS_NOTIFY | NOT WS_VISIBLE
944#ifdef MESS
945    CONTROL         "",IDC_SSTAB,"SysTabControl32",TCS_HOTTRACK,121,0,181,18
946    CONTROL         "",IDC_SWTAB,"SysTabControl32",TCS_HOTTRACK,119,0,200,100
947    CONTROL         "List2",IDC_SWLIST,"SysListView32",LVS_REPORT |
948                    LVS_SHOWSELALWAYS | LVS_OWNERDRAWFIXED | WS_BORDER |
949               WS_TABSTOP,119,60,42,140
950   CONTROL         "",IDC_SWDEVVIEW,"MessSoftwareDevView",WS_VISIBLE,119,0,200,100
951    GROUPBOX        "",IDC_SPLITTER3,163,28,8,172,BS_NOTIFY | NOT WS_VISIBLE
952    CONTROL         "",IDC_SSFRAME,"Static",SS_ETCHEDFRAME,175,11,181,194
953    CONTROL         "",IDC_SSPICTURE,"Static",SS_BITMAP | SS_NOTIFY |
954                    SS_CENTERIMAGE | NOT WS_VISIBLE,195,18,141,127
955    EDITTEXT        IDC_HISTORY,183,150,167,49,ES_MULTILINE | ES_READONLY |
956                    WS_VSCROLL,WS_EX_STATICEDGE,HIDC_HISTORY
957#else
958    CONTROL         "",IDC_SSFRAME,"Static",SS_ETCHEDFRAME | SS_NOTIFY,121,
959                    11,181,194
960    CONTROL         "",IDC_SSTAB,"SysTabControl32",TCS_HOTTRACK,121,0,181,18
961    CONTROL         "",IDC_SSPICTURE,"Static",SS_BITMAP | NOT WS_VISIBLE,141,
962                    18,141,127
963    EDITTEXT        IDC_HISTORY,129,150,167,49,ES_MULTILINE | ES_READONLY |
964                    NOT WS_BORDER | WS_VSCROLL | NOT WS_TABSTOP,0,
965                    HIDC_HISTORY
966#endif
967END
968
969IDD_FILTERS DIALOGEX 0, 0, 190, 182
970STYLE DS_SETFONT | DS_MODALFRAME | DS_3DLOOK | WS_POPUP | WS_CAPTION |
971    WS_SYSMENU
972EXSTYLE WS_EX_CONTEXTHELP
973#ifdef MESS
974CAPTION "System Filters"
975#else
976CAPTION "Game Filters"
977#endif
978FONT 8, "MS Shell Dlg", 0, 0, 0x1
979BEGIN
980#ifdef MESS
981    GROUPBOX        "System filters",IDC_STATIC,6,4,178,85
982#else
983    GROUPBOX        "Game filters",IDC_STATIC,6,4,178,85
984#endif
985    CONTROL         "&Vector Graphics",IDC_FILTER_VECTOR,"Button",
986                    BS_AUTOCHECKBOX | WS_TABSTOP,14,16,70,10,0,
987                    HIDC_FILTER_VECTOR
988    CONTROL         "C&lones",IDC_FILTER_CLONES,"Button",BS_AUTOCHECKBOX |
989                    WS_TABSTOP,14,30,41,10,0,HIDC_FILTER_CLONES
990    CONTROL         "Non-Wor&king",IDC_FILTER_NONWORKING,"Button",
991                    BS_AUTOCHECKBOX | WS_TABSTOP,14,44,61,10,0,
992                    HIDC_FILTER_NONWORKING
993    CONTROL         "&Horizontal",IDC_FILTER_HORIZONTAL,"Button",
994                    BS_AUTOCHECKBOX | WS_TABSTOP,14,58,57,10,0,
995                    HIDC_FILTER_HORIZONTAL
996    CONTROL         "&Unavailable",IDC_FILTER_UNAVAILABLE,"Button",
997                    BS_AUTOCHECKBOX | WS_TABSTOP,14,72,57,10,0,
998                    HIDC_FILTER_UNAVAILABLE
999#ifdef MESS
1000    CONTROL         "&Computers",IDC_FILTER_COMPUTER,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,14,72,57,10,0,HIDC_FILTER_UNAVAILABLE
1001    CONTROL         "C&onsoles",IDC_FILTER_CONSOLE,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,100,58,57,10,0,HIDC_FILTER_UNAVAILABLE
1002#endif
1003    CONTROL         "&Raster Graphics",IDC_FILTER_RASTER,"Button",
1004                    BS_AUTOCHECKBOX | WS_TABSTOP,100,16,70,10,0,
1005                    HIDC_FILTER_RASTER
1006    CONTROL         "Ori&ginals",IDC_FILTER_ORIGINALS,"Button",
1007                    BS_AUTOCHECKBOX | WS_TABSTOP,100,30,47,10,0,
1008                    HIDC_FILTER_ORIGINALS
1009    CONTROL         "&Working",IDC_FILTER_WORKING,"Button",BS_AUTOCHECKBOX |
1010                    WS_TABSTOP,100,44,47,10,0,HIDC_FILTER_WORKING
1011    CONTROL         "&Vertical",IDC_FILTER_VERTICAL,"Button",BS_AUTOCHECKBOX |
1012                    WS_TABSTOP,100,58,47,10,0,HIDC_FILTER_VERTICAL
1013    LTEXT           "(*) = inherited from parent folder",IDC_INHERITED,14,72,
1014                    99,10
1015#ifdef MESS
1016    CTEXT           "System filters allow customizing the systems that are displayed in each folder by hiding games that match the filters applied.",IDC_STATIC,6,94,178,27
1017#else
1018    CTEXT           "Game filters allow customizing the games that are displayed in each folder by hiding games that match the filters applied.",
1019                    IDC_STATIC,6,94,178,27
1020#endif
1021    GROUPBOX        "&Description filter",IDC_STATIC,6,122,178,33
1022    EDITTEXT        IDC_FILTER_EDIT,14,134,162,13,ES_AUTOHSCROLL,0,
1023                    HIDC_FILTER_EDIT
1024    DEFPUSHBUTTON   "&OK",IDOK,42,161,50,14
1025    PUSHBUTTON      "&Cancel",IDCANCEL,98,161,50,14
1026END
1027
1028IDD_RESET DIALOGEX 0, 0, 190, 122
1029STYLE DS_SETFONT | DS_MODALFRAME | DS_3DLOOK | WS_POPUP | WS_CAPTION |
1030    WS_SYSMENU
1031EXSTYLE WS_EX_CONTEXTHELP
1032CAPTION "Reset Options"
1033FONT 8, "MS Shell Dlg", 0, 0, 0x1
1034BEGIN
1035    GROUPBOX        "Categories",IDC_STATIC,6,4,178,70
1036    CONTROL         "&User Interface (Fonts, Colors, Sizes)",IDC_RESET_UI,
1037                    "Button",BS_AUTOCHECKBOX | WS_TABSTOP,14,16,146,10,0,
1038                    HIDC_RESET_UI
1039#ifdef MESS
1040    CONTROL         "&Default system options",IDC_RESET_DEFAULT,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,14,30,146,10,0,HIDC_RESET_DEFAULT
1041    CONTROL         "&All systems to use default options",IDC_RESET_GAMES,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,14,44,146,10,0,HIDC_RESET_GAMES
1042#else
1043    CONTROL         "&Default game options",IDC_RESET_DEFAULT,"Button",
1044                    BS_AUTOCHECKBOX | WS_TABSTOP,14,30,146,10,0,
1045                    HIDC_RESET_DEFAULT
1046    CONTROL         "&All games to use default options",IDC_RESET_GAMES,
1047                    "Button",BS_AUTOCHECKBOX | WS_TABSTOP,14,44,146,10,0,
1048                    HIDC_RESET_GAMES
1049#endif
1050    CONTROL         "&Folder 'filters'",IDC_RESET_FILTERS,"Button",
1051                    BS_AUTOCHECKBOX | WS_TABSTOP,14,58,146,10,0,
1052                    HIDC_RESET_FILTERS
1053    CTEXT           "Select the options to be restored to the default settings.",
1054                    IDC_STATIC,6,79,178,20
1055    DEFPUSHBUTTON   "&OK",IDOK,42,101,50,14
1056    PUSHBUTTON      "&Cancel",IDCANCEL,98,101,50,14
1057END
1058
1059IDD_LOAD_PROGRESS DIALOGEX 0, 0, 260, 187
1060STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION |
1061    WS_SYSMENU
1062EXSTYLE WS_EX_CONTROLPARENT
1063FONT 8, "MS Shell Dlg", 0, 0, 0x1
1064BEGIN
1065    CONTROL         "Progress1",IDC_LOAD_PROGRESS,"msctls_progress32",
1066                    WS_BORDER | 0x1,6,7,248,12
1067    CTEXT           "",IDC_LOAD_ROMNAME,6,21,248,10,SS_CENTERIMAGE | NOT
1068                    WS_GROUP
1069    EDITTEXT        IDC_LOAD_STATUS,6,32,248,116,ES_MULTILINE | ES_READONLY |
1070                    WS_VSCROLL
1071    CTEXT           "",IDC_ERROR_TEXT,6,150,248,13,SS_NOPREFIX |
1072                    SS_CENTERIMAGE
1073    PUSHBUTTON      "&OK",IDOK,77,166,50,14,WS_DISABLED
1074    PUSHBUTTON      "&Cancel",IDCANCEL,133,166,50,14
1075END
1076
1077IDD_INTERFACE_OPTIONS DIALOGEX 0, 0, 378, 225
1078STYLE DS_SETFONT | DS_MODALFRAME | DS_3DLOOK | WS_POPUP | WS_CAPTION |
1079    WS_SYSMENU
1080EXSTYLE WS_EX_CONTEXTHELP
1081CAPTION "Interface Options"
1082FONT 8, "MS Shell Dlg", 0, 0, 0x1
1083BEGIN
1084#ifdef MESS
1085    GROUPBOX        "System Selection",IDC_STATIC,6,4,189,194
1086    CONTROL         "&Search for new systems on start",IDC_START_GAME_CHECK,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,14,16,112,10,0,HIDC_START_GAME_CHECK
1087    CONTROL         "Allow system selection by a &joystick (requires restart)",IDC_JOY_GUI,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,14,30,178,10,0,HIDC_JOY_GUI
1088    CONTROL         "Allow system selection by custom &key sequences",IDC_KEY_GUI,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,14,44,166,10
1089#else
1090    GROUPBOX        "Game Selection",IDC_STATIC,6,4,189,194
1091    CONTROL         "&Search for new games on start",IDC_START_GAME_CHECK,
1092                    "Button",BS_AUTOCHECKBOX | WS_TABSTOP,14,16,111,10,0,
1093                    HIDC_START_GAME_CHECK
1094    CONTROL         "Allow game selection by a &joystick (requires restart)",
1095                    IDC_JOY_GUI,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,14,30,
1096                    174,10,0,HIDC_JOY_GUI
1097    CONTROL         "Allow game selection by custom &key sequences",
1098                    IDC_KEY_GUI,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,14,44,
1099                    166,10
1100#endif
1101    CONTROL         "Select &random background image",IDC_RANDOM_BG,"Button",
1102                    BS_AUTOCHECKBOX | WS_TABSTOP,14,58,122,10,0,
1103                    HIDC_RANDOM_BG
1104    CONTROL         "&Broadcast selected game to all windows",IDC_BROADCAST,
1105                    "Button",BS_AUTOCHECKBOX | WS_TABSTOP,14,72,141,10,0,
1106                    HIDC_BROADCAST
1107    CONTROL         "Hide &mouse cursor (requires restart)",IDC_HIDE_MOUSE,
1108                    "Button",BS_AUTOCHECKBOX | WS_TABSTOP,14,86,126,10,0,
1109                    HIDC_HIDE_MOUSE
1110    CONTROL         "Inheritable Filters",IDC_FILTER_INHERIT,"Button",
1111                    BS_AUTOCHECKBOX | WS_TABSTOP,14,100,68,10
1112    CONTROL         "No offset for clones missing parent in view",
1113                    IDC_NOOFFSET_CLONES,"Button",BS_AUTOCHECKBOX |
1114                    WS_TABSTOP,14,114,148,10
1115    GROUPBOX        "Show History on Tab",IDC_STATIC,14,128,173,28
1116    COMBOBOX        IDC_HISTORY_TAB,57,138,88,50,CBS_DROPDOWNLIST |
1117                    WS_VSCROLL | WS_TABSTOP
1118    GROUPBOX        "Emulation",IDC_STATIC,202,4,170,28
1119#ifdef MESS
1120    CONTROL         "Show System Ca&ption",IDC_GAME_CAPTION,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,210,16,81,10
1121#else
1122    CONTROL         "Show Game Ca&ption",IDC_GAME_CAPTION,"Button",
1123                    BS_AUTOCHECKBOX | WS_TABSTOP,210,16,80,10,0,
1124                    HIDC_GAME_CAPTION
1125#endif
1126    GROUPBOX        "Bookkeeping",IDC_STATIC,202,36,170,43
1127    CONTROL         "Reset all Playcounts",IDC_RESET_PLAYCOUNT,"Button",
1128                    BS_AUTOCHECKBOX | WS_TABSTOP,210,48,80,10
1129    CONTROL         "Reset all Play Times",IDC_RESET_PLAYTIME,"Button",
1130                    BS_AUTOCHECKBOX | WS_TABSTOP,210,62,79,10
1131    GROUPBOX        "Screenshot Area",IDC_STATIC,202,83,170,115
1132    CONTROL         "S&tretch screenshot larger than natural size",
1133                    IDC_STRETCH_SCREENSHOT_LARGER,"Button",BS_AUTOCHECKBOX |
1134                    WS_TABSTOP,210,95,148,10,0,
1135                    HIDC_STRETCH_SCREENSHOT_LARGER
1136    GROUPBOX        "Screenshot Cycletime in Seconds",IDC_STATIC,210,109,154,
1137                    28
1138    CONTROL         "Slider1",IDC_CYCLETIMESEC,"msctls_trackbar32",TBS_BOTH |
1139                    TBS_NOTICKS | WS_TABSTOP,218,121,120,10,0,
1140                    HIDC_CYCLETIMESEC
1141    RTEXT           "60",IDC_CYCLETIMESECTXT,340,120,13,10,SS_CENTERIMAGE
1142    GROUPBOX        "Screenshot Bordersize",IDC_STATIC,210,141,154,28
1143    CONTROL         "Slider1",IDC_SCREENSHOT_BORDERSIZE,"msctls_trackbar32",
1144                    TBS_BOTH | TBS_NOTICKS | WS_TABSTOP,218,153,120,10
1145    RTEXT           "100",IDC_SCREENSHOT_BORDERSIZETXT,340,152,13,10,
1146                    SS_CENTERIMAGE
1147    PUSHBUTTON      "Set Screenshot Border Color",IDC_SCREENSHOT_BORDERCOLOR,
1148                    210,176,154,14
1149    DEFPUSHBUTTON   "&OK",IDOK,136,204,50,14
1150    PUSHBUTTON      "&Cancel",IDCANCEL,192,204,50,14
1151END
1152
1153IDD_LANGUAGE DIALOGEX 0, 0, 190, 66
1154STYLE DS_SETFONT | DS_MODALFRAME | DS_CONTEXTHELP | WS_POPUP | WS_CAPTION |
1155    WS_SYSMENU
1156EXSTYLE WS_EX_CONTEXTHELP
1157CAPTION "Language"
1158FONT 8, "MS Shell Dlg", 0, 0, 0x1
1159BEGIN
1160    GROUPBOX        "",IDC_STATIC,6,4,178,34
1161    CONTROL         "Use language file",IDC_LANGUAGECHECK,"Button",
1162                    BS_AUTOCHECKBOX | WS_TABSTOP,12,4,66,10,0,
1163                    HIDC_LANGUAGECHECK
1164    EDITTEXT        IDC_LANGUAGEEDIT,14,17,142,13,ES_AUTOHSCROLL,0,
1165                    HIDC_LANGUAGEEDIT
1166    PUSHBUTTON      "...",IDC_LANGUAGEBROWSE,162,17,14,13
1167    DEFPUSHBUTTON   "OK",IDOK,42,45,50,14
1168    PUSHBUTTON      "Cancel",IDCANCEL,98,45,50,14
1169END
1170
1171IDD_CUSTOM_FILE DIALOG  0, 0, 190, 135
1172STYLE DS_SETFONT | DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU
1173CAPTION "Add Game To Custom Folder"
1174FONT 8, "MS Shell Dlg"
1175BEGIN
1176    LTEXT           "",IDC_CUSTOMFILE_GAME,6,6,175,10,SS_NOPREFIX |
1177                    SS_CENTERIMAGE
1178    CONTROL         "CustomTree",IDC_CUSTOM_TREE,"SysTreeView32",
1179                    TVS_HASBUTTONS | TVS_HASLINES | TVS_LINESATROOT |
1180                    TVS_DISABLEDRAGDROP | TVS_SHOWSELALWAYS |
1181                    TVS_FULLROWSELECT | WS_BORDER | WS_TABSTOP,6,18,178,90
1182    DEFPUSHBUTTON   "OK",IDOK,42,114,50,14
1183    PUSHBUTTON      "Cancel",IDCANCEL,98,114,50,14
1184END
1185
1186
1187/////////////////////////////////////////////////////////////////////////////
1188//
1189// Accelerator
1190//
1191
1192IDA_TAB_KEYS ACCELERATORS
1193BEGIN
1194    "1",            ID_VIEW_TAB_SCREENSHOT, VIRTKEY, ALT, NOINVERT
1195    "2",            ID_VIEW_TAB_FLYER,      VIRTKEY, ALT, NOINVERT
1196    "3",            ID_VIEW_TAB_CABINET,    VIRTKEY, ALT, NOINVERT
1197    "4",            ID_VIEW_TAB_MARQUEE,    VIRTKEY, ALT, NOINVERT
1198    "5",            ID_VIEW_TAB_TITLE,      VIRTKEY, ALT, NOINVERT
1199    "6",            ID_VIEW_TAB_CONTROL_PANEL, VIRTKEY, ALT, NOINVERT
1200    "7",            ID_VIEW_TAB_PCB,        VIRTKEY, ALT, NOINVERT
1201    "8",            ID_VIEW_TAB_HISTORY,    VIRTKEY, ALT, NOINVERT
1202    "A",            ID_GAME_AUDIT,          VIRTKEY, ALT, NOINVERT
1203    "B",            ID_VIEW_PAGETAB,        VIRTKEY, ALT, NOINVERT
1204    "D",            ID_VIEW_FOLDERS,        VIRTKEY, ALT, NOINVERT
1205    "F",            ID_CONTEXT_FILTERS,     VIRTKEY, CONTROL, NOINVERT
1206    "U",            ID_FOLDER_AUDIT,        VIRTKEY, ALT, NOINVERT
1207    "P",            ID_VIEW_PICTURE_AREA,   VIRTKEY, ALT, NOINVERT
1208    "R",            ID_CONTEXT_SELECT_RANDOM, VIRTKEY, CONTROL, NOINVERT
1209    "S",            ID_VIEW_STATUS,         VIRTKEY, ALT, NOINVERT
1210    "T",            ID_VIEW_TOOLBARS,       VIRTKEY, ALT, NOINVERT
1211    VK_F1,          ID_HELP_CONTENTS,       VIRTKEY, NOINVERT
1212    VK_F11,         ID_VIEW_FULLSCREEN,     VIRTKEY, NOINVERT
1213    VK_F5,          ID_UPDATE_GAMELIST,     VIRTKEY, NOINVERT
1214    VK_NEXT,        ID_UI_HISTORY_DOWN,     VIRTKEY, CONTROL, NOINVERT
1215    VK_PRIOR,       ID_UI_HISTORY_UP,       VIRTKEY, CONTROL, NOINVERT
1216    VK_RETURN,      ID_GAME_PROPERTIES,     VIRTKEY, ALT, NOINVERT
1217END
1218
1219
1220/////////////////////////////////////////////////////////////////////////////
1221//
1222// DESIGNINFO
1223//
1224
1225#ifdef APSTUDIO_INVOKED
1226GUIDELINES DESIGNINFO
1227BEGIN
1228    IDD_ABOUT, DIALOG
1229    BEGIN
1230        LEFTMARGIN, 7
1231        RIGHTMARGIN, 289
1232        TOPMARGIN, 7
1233        BOTTOMMARGIN, 123
1234    END
1235
1236    IDD_DIRECTX, DIALOG
1237    BEGIN
1238        LEFTMARGIN, 7
1239        RIGHTMARGIN, 229
1240        TOPMARGIN, 7
1241        BOTTOMMARGIN, 62
1242    END
1243
1244    IDD_AUDIT, DIALOG
1245    BEGIN
1246        LEFTMARGIN, 7
1247        RIGHTMARGIN, 280
1248        TOPMARGIN, 7
1249        BOTTOMMARGIN, 187
1250        HORZGUIDE, 19
1251    END
1252
1253    IDD_DIRECTORIES, DIALOG
1254    BEGIN
1255        LEFTMARGIN, 7
1256        RIGHTMARGIN, 224
1257        TOPMARGIN, 7
1258        BOTTOMMARGIN, 98
1259    END
1260
1261    IDD_COLUMNS, DIALOG
1262    BEGIN
1263        LEFTMARGIN, 7
1264        RIGHTMARGIN, 301
1265        TOPMARGIN, 7
1266        BOTTOMMARGIN, 143
1267    END
1268
1269    IDD_PROP_CONTROLLER, DIALOG
1270    BEGIN
1271        RIGHTMARGIN, 210
1272        BOTTOMMARGIN, 154
1273    END
1274
1275    IDD_PROP_SCREEN, DIALOG
1276    BEGIN
1277        LEFTMARGIN, 4
1278        VERTGUIDE, 7
1279        VERTGUIDE, 123
1280        BOTTOMMARGIN, 199
1281        HORZGUIDE, 179
1282    END
1283
1284    IDD_PROP_GAME, DIALOG
1285    BEGIN
1286        LEFTMARGIN, 7
1287        RIGHTMARGIN, 213
1288        VERTGUIDE, 19
1289        VERTGUIDE, 66
1290        VERTGUIDE, 74
1291        VERTGUIDE, 201
1292        BOTTOMMARGIN, 232
1293    END
1294
1295    IDD_PROP_AUDIT, DIALOG
1296    BEGIN
1297        LEFTMARGIN, 7
1298        RIGHTMARGIN, 213
1299        VERTGUIDE, 12
1300        VERTGUIDE, 208
1301        BOTTOMMARGIN, 198
1302        HORZGUIDE, 38
1303    END
1304
1305    IDD_PROP_DISPLAY, DIALOG
1306    BEGIN
1307        LEFTMARGIN, 4
1308        VERTGUIDE, 7
1309        VERTGUIDE, 123
1310        HORZGUIDE, 179
1311    END
1312
1313    IDD_PROP_SOUND, DIALOG
1314    BEGIN
1315        LEFTMARGIN, 7
1316        RIGHTMARGIN, 213
1317        VERTGUIDE, 50
1318        BOTTOMMARGIN, 198
1319    END
1320
1321    IDD_PROP_ADVANCED, DIALOG
1322    BEGIN
1323        LEFTMARGIN, 10
1324        BOTTOMMARGIN, 211
1325    END
1326
1327    IDD_PROP_INPUT, DIALOG
1328    BEGIN
1329        LEFTMARGIN, 4
1330        RIGHTMARGIN, 215
1331        VERTGUIDE, 50
1332        VERTGUIDE, 170
1333    END
1334
1335    IDD_PROP_MISC, DIALOG
1336    BEGIN
1337        LEFTMARGIN, 7
1338        RIGHTMARGIN, 213
1339        VERTGUIDE, 25
1340        VERTGUIDE, 40
1341        VERTGUIDE, 104
1342        VERTGUIDE, 114
1343        VERTGUIDE, 204
1344        BOTTOMMARGIN, 183
1345    END
1346
1347    IDD_PROP_VECTOR, DIALOG
1348    BEGIN
1349        LEFTMARGIN, 7
1350        RIGHTMARGIN, 213
1351        VERTGUIDE, 50
1352        BOTTOMMARGIN, 198
1353    END
1354
1355    IDD_FILTERS, DIALOG
1356    BEGIN
1357        LEFTMARGIN, 7
1358        TOPMARGIN, 7
1359        BOTTOMMARGIN, 178
1360    END
1361
1362    IDD_RESET, DIALOG
1363    BEGIN
1364        LEFTMARGIN, 7
1365        RIGHTMARGIN, 175
1366        VERTGUIDE, 18
1367        VERTGUIDE, 164
1368        TOPMARGIN, 7
1369    END
1370
1371    IDD_LANGUAGE, DIALOG
1372    BEGIN
1373        LEFTMARGIN, 7
1374        RIGHTMARGIN, 179
1375        TOPMARGIN, 7
1376        BOTTOMMARGIN, 59
1377    END
1378END
1379#endif    // APSTUDIO_INVOKED
1380
1381
1382/////////////////////////////////////////////////////////////////////////////
1383//
1384// Bitmap
1385//
1386
1387#ifdef MESS
1388IDB_ABOUT               BITMAP      "res\\about_mess.bmp"
1389#else
1390IDB_ABOUT               BITMAP                  "res\\about.bmp"
1391#endif
1392IDB_TOOLBAR             BITMAP                  "res\\toolbar.bmp"
1393
1394/////////////////////////////////////////////////////////////////////////////
1395//
1396// Cursor
1397//
1398
1399IDC_CURSOR_HSPLIT       CURSOR                  "Res\\Splith.cur"
1400
1401/////////////////////////////////////////////////////////////////////////////
1402//
1403// RT_MANIFEST
1404//
1405
14061                       RT_MANIFEST             "res\\mame32.manifest"
1407
1408/////////////////////////////////////////////////////////////////////////////
1409//
1410// String Table
1411//
1412
1413STRINGTABLE
1414BEGIN
1415    IDS_UI_FILE             "Contains commands for working with the selected items"
1416    IDS_UI_VIEW             "Contains commands for manupulating the view"
1417    IDS_UI_OPTIONS          "Contains commands for user interface options"
1418END
1419
1420STRINGTABLE
1421BEGIN
1422    IDS_UI_HELP             "Contains commands for displaying help"
1423    IDS_VIEW_TOOLBAR        "Show or hide the toolbar"
1424    IDS_VIEW_STATUSBAR      "Show or hide the status bar"
1425    IDS_VIEW_FOLDERLIST     "Show or hide the folder list"
1426    IDS_VIEW_SCREENSHOT     "Show or hide the screen shot"
1427    IDS_VIEW_PICTURETABS    "Show or hide tabs in the picture area"
1428    IDS_VIEW_SPACER1        "Spacer"
1429    IDS_VIEW_FULLSCREEN     "Toggle full screen mode"
1430    IDS_VIEW_SPACER2        "Spacer"
1431    IDS_VIEW_SHOWPICTURES   "Contains commands to select tabs shown in the picture area"
1432    IDS_VIEW_SPACER3        "Spacer"
1433END
1434
1435STRINGTABLE
1436BEGIN
1437    IDS_VIEW_LARGEICONS     "Display items by using large icons."
1438    IDS_VIEW_SMALLICONS     "Display items by using small icons."
1439    IDS_VIEW_LIST           "Displays items in a list."
1440    IDS_VIEW_DETAILS        "Displays detailed information about each item in the window."
1441    IDS_VIEW_GROUPED        "Displays items grouped by parent game"
1442    IDS_VIEW_SPACER4        "Spacer"
1443    IDS_VIEW_ARRANGE        "Contains commands for sorting by various columns"
1444    IDS_VIEW_LINEUPICONS    "Arranges icons in a grid"
1445    IDS_VIEW_SPACER5        "Spacer"
1446    IDS_VIEW_REFRESH        "Refresh game list"
1447    IDS_VIEW_CONTEXTFILTERS "Allows filtering out games from a folder"
1448    IDS_VIEW_CUSTOMIZEFIELDS
1449                            "Customize which columns are used in the game list"
1450END
1451
1452STRINGTABLE
1453BEGIN
1454    ID_FILE_EXIT            "Exit the application"
1455#ifdef MESS
1456    ID_FILE_PLAY            "Play currently selected system"
1457#else
1458    ID_FILE_PLAY            "Play currently selected game"
1459#endif
1460    ID_HELP_ABOUT           "Displays program and copyright information"
1461    ID_VIEW_LARGE_ICON      "Display items by using large icons."
1462    ID_VIEW_SMALL_ICON      "Display items by using small icons."
1463    ID_VIEW_LIST_MENU       "Displays items in a list."
1464    ID_VIEW_DETAIL          "Displays detailed information about each item in the window."
1465#ifdef MESS
1466    ID_OPTIONS_FONT         "Set system list and folder list font"
1467    ID_OPTIONS_DIR          "Set directory configuration"
1468    ID_OPTIONS_DEFAULTS     "Set default system options"
1469#else
1470    ID_VIEW_GROUPED         "Show items grouped by parent game"
1471    ID_OPTIONS_FONT         "Set game list and folder list font"
1472    ID_OPTIONS_CLONE_COLOR  "Set the clone font color"
1473    ID_OPTIONS_DIR          "Set directory configuration"
1474    ID_OPTIONS_DEFAULTS     "Set default game options"
1475#endif
1476END
1477
1478STRINGTABLE
1479BEGIN
1480    ID_OPTIONS_RESET_DEFAULTS "Allow restoring options to 'sane' values."
1481    ID_OPTIONS_INTERFACE    "Customize interface options."
1482    ID_FILE_AUDIT           "Audit ROM and samples sets"
1483#ifdef MESS
1484    ID_FILE_PLAY_RECORD     "Record a system for later playback"
1485    ID_FILE_PLAY_BACK       "Playback a recorded system"
1486    ID_FILE_PLAY_RECORD_WAVE "Record the sound output of a system"
1487#else
1488    ID_FILE_PLAY_RECORD     "Record a game for later playback"
1489    ID_FILE_PLAY_BACK       "Playback a recorded game"
1490    ID_FILE_PLAY_RECORD_WAVE "Record the audio output of a game"
1491    ID_FILE_PLAY_RECORD_MNG "Record the video output of a game"
1492#endif
1493    ID_VIEW_PICTURE_AREA    "Show or hide the picture area"
1494    ID_HELP_CONTENTS        "Display help contents"
1495#ifdef MESS
1496    ID_HELP_WHATS_NEW32     "Recent changes"
1497    ID_HELP_TROUBLE         "Troubleshooting Documentation"
1498    ID_HELP_RELEASE         "MESS release notes"
1499    ID_HELP_WHATS_NEW       "What's new in MESS"
1500    ID_HELP_CHEATS          "How cheats work"
1501#else
1502    ID_HELP_WHATS_NEW32     "New game changes"
1503    ID_HELP_TROUBLE         "Troubleshooting Documentation"
1504    ID_HELP_RELEASE         "MAME release notes"
1505    ID_HELP_WHATS_NEW       "What's new in MAME"
1506    ID_HELP_CHEATS          "How cheats work"
1507#endif
1508END
1509
1510STRINGTABLE
1511BEGIN
1512    ID_CONTEXT_RESET_PLAYTIME "Reset time played for selected item"
1513    ID_CONTEXT_RESET_PLAYCOUNT "Reset number of plays for selected item"
1514    ID_FOLDER_PROPERTIES    "Display folder properties"
1515    ID_FOLDER_AUDIT         "Audit itmes in this folder"
1516#ifdef MESS
1517    ID_FILE_LOADSTATE       "Run a system starting with the given savestate"
1518#else
1519    ID_FILE_LOADSTATE       "Play a game starting with the given savestate"
1520#endif
1521END
1522
1523STRINGTABLE
1524BEGIN
1525    ID_VIEW_TAB_CABINET     "Select Cabinet tab"
1526    ID_VIEW_TAB_MARQUEE     "Select Marquee tab"
1527    ID_VIEW_TAB_TITLE       "Select Title tab"
1528    ID_VIEW_TAB_CONTROL_PANEL "Select Control panel tab"
1529    ID_VIEW_TAB_HISTORY     "Select History tab"
1530    ID_OPTIONS_BG           "Set the bacground image"
1531    ID_TOGGLE_TAB_SCREENSHOT "Enable the screenshot tab"
1532    ID_TOGGLE_TAB_FLYER     "Enable the flyer tab"
1533    ID_TOGGLE_TAB_CABINET   "Enable the cabinet tab"
1534    ID_TOGGLE_TAB_MARQUEE   "Enable the marquee tab"
1535    ID_TOGGLE_TAB_TITLE     "Enable the title tab"
1536    ID_TOGGLE_TAB_CONTROL_PANEL "Enable the control panel tab"
1537    ID_TOGGLE_TAB_PCB       "Enable the PCB tab"
1538    ID_TOGGLE_TAB_HISTORY   "Enable the history tab"
1539    ID_VIEW_FULLSCREEN      "Toggle Fullscreen mode"
1540END
1541
1542STRINGTABLE
1543BEGIN
1544#ifdef MESS
1545    ID_CUSTOMIZE_FIELDS     "Customize which columns are used in the system list"
1546#else
1547    ID_CUSTOMIZE_FIELDS     "Customize which columns are used in the game list"
1548#endif
1549    ID_GAME_PROPERTIES      "Display the properties of the selected item"
1550    ID_VIEW_PAGETAB         "Show or hide the tabs in the picture area"
1551    ID_VIEW_FOLDERS         "Show or hide the folder list"
1552    ID_VIEW_TOOLBARS        "Show or hide the toolbar"
1553    ID_VIEW_STATUS          "Show or hide the status bar"
1554#ifdef MESS
1555    ID_CONTEXT_FILTERS      "Allows filtering out systems from a folder"
1556    ID_CONTEXT_RENAME_CUSTOM "Rename this folder"
1557    ID_CONTEXT_ADD_CUSTOM   "Add selected item to custom folder"
1558    ID_CONTEXT_REMOVE_CUSTOM "Remove selected item from this folder"
1559    ID_GAME_AUDIT           "Audit the selected item"
1560    ID_CONTEXT_SELECT_RANDOM "Randomly select a system."
1561#else
1562    ID_CONTEXT_FILTERS      "Allows filtering out games from a folder"
1563    ID_CONTEXT_RENAME_CUSTOM "Rename this folder"
1564    ID_CONTEXT_ADD_CUSTOM   "Add selected item to custom folder"
1565    ID_CONTEXT_REMOVE_CUSTOM "Remove selected item from this folder"
1566    ID_GAME_AUDIT           "Audit the selected item"
1567    ID_CONTEXT_SELECT_RANDOM "Randomly select a game."
1568#endif
1569    ID_VIEW_TAB_SCREENSHOT  "Select Screenshot tab"
1570    ID_VIEW_TAB_FLYER       "Select Flyer tab"
1571END
1572
1573STRINGTABLE
1574BEGIN
1575#ifdef MESS
1576    ID_VIEW_BYGAME          "Sort items by system"
1577#else
1578    ID_VIEW_BYGAME          "Sort items by game"
1579#endif
1580    ID_VIEW_BYDIRECTORY     "Sort items by directories"
1581    ID_VIEW_BYMANUFACTURER  "Sort items by manufacturer"
1582    ID_VIEW_BYYEAR          "Sort items by year"
1583    ID_VIEW_BYTYPE          "Sort items by type"
1584    ID_VIEW_BYTIMESPLAYED   "Sort by number of plays"
1585    ID_VIEW_LINEUPICONS     "Arranges icons in a grid"
1586#ifdef MESS
1587    ID_UPDATE_GAMELIST      "Refresh system list"
1588#else
1589    ID_UPDATE_GAMELIST      "Refresh game list"
1590#endif
1591    ID_SORT_ASCENDING       "Sort column in ascending (A-Z) order"
1592    ID_SORT_DESCENDING      "Sort column in descending (Z-A) order"
1593END
1594
1595STRINGTABLE
1596BEGIN
1597    ID_FOLDER_SOURCEPROPERTIES
1598                            "Display properties for all games in this source file"
1599    ID_FOLDER_VECTORPROPERTIES "Display properties for all vector based games"
1600END
1601
1602#endif    // English (U.S.) resources
1603/////////////////////////////////////////////////////////////////////////////
1604
1605
1606
1607#ifndef APSTUDIO_INVOKED
1608/////////////////////////////////////////////////////////////////////////////
1609//
1610// Generated from the TEXTINCLUDE 3 resource.
1611//
1612#include "mamevers.rc" // Version block
1613
1614
1615/////////////////////////////////////////////////////////////////////////////
1616#endif    // not APSTUDIO_INVOKED
1617
src/osd/winui/tabview.h
r0r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11 ***************************************************************************/
12
13#ifndef TABVIEW_H
14#define TABVIEW_H
15
16struct TabViewCallbacks
17{
18   // Options retrieval
19   BOOL (*pfnGetShowTabCtrl)(void);
20   void (*pfnSetCurrentTab)(LPCSTR pszShortName);
21   LPCSTR (*pfnGetCurrentTab)(void);
22   void (*pfnSetShowTab)(int nTab, BOOL show);
23   int (*pfnGetShowTab)(int nTab);
24
25   // Accessors
26   LPCSTR (*pfnGetTabShortName)(int nTab);
27   LPCSTR (*pfnGetTabLongName)(int nTab);
28
29   // Callbacks
30   void (*pfnOnSelectionChanged)(void);
31   void (*pfnOnMoveSize)(void);
32};
33
34struct TabViewOptions
35{
36   const struct TabViewCallbacks *pCallbacks;
37   int nTabCount;
38};
39
40
41BOOL SetupTabView(HWND hwndTabView, const struct TabViewOptions *pOptions);
42
43void TabView_Reset(HWND hwndTabView);
44void TabView_CalculateNextTab(HWND hwndTabView);
45int TabView_GetCurrentTab(HWND hwndTabView);
46void TabView_SetCurrentTab(HWND hwndTabView, int nTab);
47void TabView_UpdateSelection(HWND hwndTabView);
48
49// These are used to handle events received by the parent regarding
50// tabview controls
51BOOL TabView_HandleNotify(LPNMHDR lpNmHdr);
52
53#endif // TABVIEW_H
src/osd/winui/datamap.c
r0r996
1//============================================================
2//
3//  datamap.c - Win32 dialog and options bridge code
4//
5//============================================================
6
7// standard windows headers
8#define WIN32_LEAN_AND_MEAN
9#include <windows.h>
10#include <windowsx.h>
11#include <commctrl.h>
12#include <tchar.h>
13
14// standard C headers
15#include <stdarg.h>
16#include <ctype.h>
17#include <assert.h>
18#include <math.h>
19
20// MAME/MAME32 headers
21#include "corestr.h"
22#include "strconv.h"
23#include "datamap.h"
24#include "winutf8.h"
25#include "emuopts.h"
26
27#ifdef _MSC_VER
28#define snprintf _snprintf
29#endif
30
31//============================================================
32//  TYPE DEFINITIONS
33//============================================================
34
35typedef enum _control_type control_type;
36enum _control_type
37{
38   CT_UNKNOWN,
39   CT_BUTTON,
40   CT_STATIC,
41   CT_EDIT,
42   CT_COMBOBOX,
43   CT_TRACKBAR,
44   CT_LISTVIEW
45};
46
47
48
49typedef struct _datamap_entry datamap_entry;
50struct _datamap_entry
51{
52   // the basics about the entry
53   int dlgitem;
54   datamap_entry_type type;
55   const char *option_name;
56
57   // callbacks
58   datamap_callback callbacks[DCT_COUNT];
59   get_option_name_callback get_option_name;
60
61   // formats
62   const char *int_format;
63   const char *float_format;
64
65   // trackbar options
66   BOOL use_trackbar_options;
67   float trackbar_min;
68   float trackbar_max;
69   float trackbar_increments;
70};
71
72
73struct _datamap
74{
75   int entry_count;
76   datamap_entry entries[256];
77};
78
79typedef void (*datamap_default_callback)(datamap *map, HWND control, core_options *opts, datamap_entry *entry, const char *option_name);
80
81
82
83//============================================================
84//  PROTOTYPES
85//============================================================
86
87static datamap_entry *find_entry(datamap *map, int dlgitem);
88static control_type get_control_type(HWND control);
89static int control_operation(datamap *map, HWND dialog, core_options *opts,
90   datamap_entry *entry, datamap_callback_type callback_type);
91static void read_control(datamap *map, HWND control, core_options *opts, datamap_entry *entry, const char *option_name);
92static void populate_control(datamap *map, HWND control, core_options *opts, datamap_entry *entry, const char *option_name);
93static   char *tztrim(float float_value);
94
95
96//============================================================
97//  datamap_create
98//============================================================
99
100datamap *datamap_create(void)
101{
102   datamap *map = malloc(sizeof(*map));
103   if (!map)
104      return NULL;
105
106   map->entry_count = 0;
107   return map;
108}
109
110
111
112//============================================================
113//  datamap_free
114//============================================================
115
116void datamap_free(datamap *map)
117{
118   free(map);
119}
120
121
122
123//============================================================
124//  datamap_add
125//============================================================
126
127void datamap_add(datamap *map, int dlgitem, datamap_entry_type type, const char *option_name)
128{
129   // sanity check for too many entries
130   assert(map->entry_count < ARRAY_LENGTH(map->entries));
131
132   // add entry to the datamap
133   memset(&map->entries[map->entry_count], 0, sizeof(map->entries[map->entry_count]));
134   map->entries[map->entry_count].dlgitem = dlgitem;
135   map->entries[map->entry_count].type = type;
136   map->entries[map->entry_count].option_name = option_name;
137   map->entry_count++;
138}
139
140
141
142//============================================================
143//  datamap_set_callback
144//============================================================
145
146void datamap_set_callback(datamap *map, int dlgitem, datamap_callback_type callback_type, datamap_callback callback)
147{
148   datamap_entry *entry;
149
150   assert(0 <= callback_type < DCT_COUNT);
151
152   entry = find_entry(map, dlgitem);
153   entry->callbacks[callback_type] = callback;
154}
155
156
157
158//============================================================
159//  datamap_set_option_name_callback
160//============================================================
161
162void datamap_set_option_name_callback(datamap *map, int dlgitem, get_option_name_callback get_option_name)
163{
164   datamap_entry *entry;
165   entry = find_entry(map, dlgitem);
166   entry->get_option_name = get_option_name;
167}
168
169
170
171//============================================================
172//  datamap_set_trackbar_range
173//============================================================
174
175void datamap_set_trackbar_range(datamap *map, int dlgitem, float min, float max, float increments)
176{
177   datamap_entry *entry = find_entry(map, dlgitem);
178   entry->use_trackbar_options = TRUE;
179   entry->trackbar_min = min;
180   entry->trackbar_max = max;
181   entry->trackbar_increments = increments;
182}
183
184
185
186//============================================================
187//  datamap_set_int_format
188//============================================================
189
190void datamap_set_int_format(datamap *map, int dlgitem, const char *format)
191{
192   datamap_entry *entry = find_entry(map, dlgitem);
193   entry->int_format = format;
194}
195
196
197
198//============================================================
199//  datamap_set_float_format
200//============================================================
201
202void datamap_set_float_format(datamap *map, int dlgitem, const char *format)
203{
204   datamap_entry *entry = find_entry(map, dlgitem);
205   entry->float_format = format;
206}
207
208
209
210//============================================================
211//  datamap_read_control
212//============================================================
213
214BOOL datamap_read_control(datamap *map, HWND dialog, core_options *opts, int dlgitem)
215{
216   datamap_entry *entry = find_entry(map, dlgitem);
217   return control_operation(map, dialog, opts, entry, DCT_READ_CONTROL);
218}
219
220
221
222//============================================================
223//  datamap_read_all_controls
224//============================================================
225
226void datamap_read_all_controls(datamap *map, HWND dialog, core_options *opts)
227{
228   int i;
229   for (i = 0; i < map->entry_count; i++)
230      control_operation(map, dialog, opts, &map->entries[i], DCT_READ_CONTROL);
231}
232
233
234
235//============================================================
236//  datamap_populate_control
237//============================================================
238
239void datamap_populate_control(datamap *map, HWND dialog, core_options *opts, int dlgitem)
240{
241   datamap_entry *entry = find_entry(map, dlgitem);
242   control_operation(map, dialog, opts, entry, DCT_POPULATE_CONTROL);
243}
244
245
246
247//============================================================
248//  datamap_populate_all_controls
249//============================================================
250
251void datamap_populate_all_controls(datamap *map, HWND dialog, core_options *opts)
252{
253   int i;
254   for (i = 0; i < map->entry_count; i++)
255      control_operation(map, dialog, opts, &map->entries[i], DCT_POPULATE_CONTROL);
256}
257
258
259
260//============================================================
261//  datamap_update_control
262//============================================================
263
264void datamap_update_control(datamap *map, HWND dialog, core_options *opts, int dlgitem)
265{
266   datamap_entry *entry = find_entry(map, dlgitem);
267   control_operation(map, dialog, opts, entry, DCT_UPDATE_STATUS);
268}
269
270
271
272//============================================================
273//  datamap_update_all_controls
274//============================================================
275
276void datamap_update_all_controls(datamap *map, HWND dialog, core_options *opts)
277{
278   int i;
279   for (i = 0; i < map->entry_count; i++)
280      control_operation(map, dialog, opts, &map->entries[i], DCT_UPDATE_STATUS);
281}
282
283
284
285//============================================================
286//  find_entry
287//============================================================
288
289static datamap_entry *find_entry(datamap *map, int dlgitem)
290{
291   int i;
292   for (i = 0; i < map->entry_count; i++)
293   {
294      if (map->entries[i].dlgitem == dlgitem)
295         return &map->entries[i];
296   }
297   
298   // should not reach here
299   assert(FALSE);
300   return NULL;
301}
302
303
304
305//============================================================
306//  get_control_type
307//============================================================
308
309static control_type get_control_type(HWND control)
310{
311   control_type type;
312   TCHAR class_name[256];
313
314   GetClassName(control, class_name, ARRAY_LENGTH(class_name));
315   if (!_tcscmp(class_name, WC_BUTTON))
316      type = CT_BUTTON;
317   else if (!_tcscmp(class_name, WC_STATIC))
318      type = CT_STATIC;
319   else if (!_tcscmp(class_name, WC_EDIT))
320      type = CT_EDIT;
321   else if (!_tcscmp(class_name, WC_COMBOBOX))
322      type = CT_COMBOBOX;
323   else if (!_tcscmp(class_name, TRACKBAR_CLASS))
324      type = CT_TRACKBAR;
325   else if (!_tcscmp(class_name, WC_LISTVIEW))
326      type = CT_LISTVIEW;
327   else
328      type = CT_UNKNOWN;
329
330   assert(type != CT_UNKNOWN);
331   return type;
332}
333
334
335
336//============================================================
337//  is_control_displayonly
338//============================================================
339
340static BOOL is_control_displayonly(HWND control)
341{
342   BOOL displayonly;
343   switch(get_control_type(control))
344   {
345      case CT_STATIC:
346         displayonly = TRUE;
347         break;
348
349      case CT_EDIT:
350         displayonly = (GetWindowLong(control, GWL_STYLE) & ES_READONLY) ? TRUE : FALSE;
351         break;
352
353      default:
354         displayonly = FALSE;
355         break;
356   }
357
358   if (!IsWindowEnabled(control))
359      displayonly = TRUE;
360   return displayonly;
361}
362
363
364
365//============================================================
366//  broadcast_changes
367//============================================================
368
369static void broadcast_changes(datamap *map, HWND dialog, core_options *opts, datamap_entry *entry, const char *option_name)
370{
371   HWND other_control;
372   const char *that_option_name;
373   int i;
374
375   for (i = 0; i < map->entry_count; i++)
376   {
377      // search for an entry with the same option_name, but is not the exact
378      // same entry
379      that_option_name = map->entries[i].option_name;
380      if (map->entries[i].option_name && (&map->entries[i] != entry) && !strcmp(that_option_name, option_name))
381      {
382         // we've found a control sharing the same option; populate it
383         other_control = GetDlgItem(dialog, map->entries[i].dlgitem);
384         if (other_control != NULL)
385            populate_control(map, other_control, opts, &map->entries[i], that_option_name);
386      }
387   }
388}
389
390
391
392//============================================================
393//  control_operation
394//============================================================
395
396static int control_operation(datamap *map, HWND dialog, core_options *opts,
397   datamap_entry *entry, datamap_callback_type callback_type)
398{
399   static const datamap_default_callback default_callbacks[DCT_COUNT] =
400   {
401      read_control,
402      populate_control,
403      NULL
404   };
405   HWND control;
406   int result = 0;
407   const char *option_name;
408   char option_name_buffer[64];
409   char option_value[1024] = {0, };
410
411   control = GetDlgItem(dialog, entry->dlgitem);
412   if (control != NULL)
413   {
414      // don't do anything if we're reading from a display-only control
415      if ((callback_type != DCT_READ_CONTROL) || !is_control_displayonly(control))
416      {
417         // figure out the option_name
418         if (entry->get_option_name != NULL)
419         {
420            option_name_buffer[0] = '\0';
421            entry->get_option_name(map, dialog, control, option_name_buffer, ARRAY_LENGTH(option_name_buffer));
422            option_name = option_name_buffer;
423         }
424         else
425         {
426            option_name = entry->option_name;
427         }
428
429         // if reading, get the option value, solely for the purposes of comparison
430         if ((callback_type == DCT_READ_CONTROL) && (option_name != NULL))
431            snprintf(option_value, ARRAY_LENGTH(option_value), "%s", options_get_string(opts, option_name));
432
433         if (entry->callbacks[callback_type] != NULL)
434         {
435            // use custom callback
436            result = entry->callbacks[callback_type](map, dialog, control, opts, option_name);
437         }
438         else if (default_callbacks[callback_type] && (option_name != NULL))
439         {
440            // use default callback
441            default_callbacks[callback_type](map, control, opts, entry, option_name);
442         }
443
444         // the result is dependent on the type of control
445         switch(callback_type)
446         {
447            case DCT_READ_CONTROL:
448               // For callbacks that returned TRUE, do not broadcast_changes.
449               if (!result) {
450                  // do a check to see if the control changed
451                  result = (option_name != NULL) && (strcmp(option_value, options_get_string(opts, option_name)) != 0);
452                  if (result)
453                  {
454                     // the value has changed; we may need to broadcast the change
455                     broadcast_changes(map, dialog, opts, entry, option_name);
456                  }
457               }
458               break;
459
460            default:
461               // do nothing
462               break;
463         }
464      }
465   }
466   return result;
467}
468
469
470
471//============================================================
472//  trackbar_value_from_position
473//============================================================
474
475static float trackbar_value_from_position(datamap_entry *entry, int position)
476{
477   float position_f = position;
478
479   if (entry->use_trackbar_options)
480   {
481      position_f = (position_f * entry->trackbar_increments) + entry->trackbar_min;
482   }
483   return position_f;
484}
485
486
487
488//============================================================
489//  trackbar_position_from_value
490//============================================================
491
492static int trackbar_position_from_value(datamap_entry *entry, float value)
493{
494   if (entry->use_trackbar_options)
495   {
496      value = floor((value - entry->trackbar_min) / entry->trackbar_increments + 0.5);
497   }
498   return (int) value;
499}
500
501
502
503//============================================================
504//  read_control
505//============================================================
506
507static void read_control(datamap *map, HWND control, core_options *opts, datamap_entry *entry, const char *option_name)
508{
509   BOOL bool_value;
510   int int_value;
511   float float_value;
512   const char *string_value;
513   int selected_index;
514   int trackbar_pos;
515   
516   // use default read value behavior
517   switch(get_control_type(control))
518   {
519      case CT_BUTTON:
520         assert(entry->type == DM_BOOL);
521         bool_value = Button_GetCheck(control);
522         options_set_bool(opts, option_name, bool_value, OPTION_PRIORITY_CMDLINE);
523         break;
524
525      case CT_COMBOBOX:
526         selected_index = ComboBox_GetCurSel(control);
527         if (selected_index >= 0)
528         {
529            switch(entry->type)
530            {
531               case DM_INT:
532                  int_value = (int) ComboBox_GetItemData(control, selected_index);
533                  options_set_int(opts, option_name, int_value, OPTION_PRIORITY_CMDLINE);
534                  break;
535
536               case DM_STRING:
537                  string_value = (const char *) ComboBox_GetItemData(control, selected_index);
538                  options_set_string(opts, option_name, string_value ? string_value : "", OPTION_PRIORITY_CMDLINE);
539                  break;
540
541               default:
542                  assert(FALSE);
543                  break;
544            }
545         }
546         break;
547
548      case CT_TRACKBAR:
549         trackbar_pos = SendMessage(control, TBM_GETPOS, 0, 0);
550         float_value = trackbar_value_from_position(entry, trackbar_pos);
551         switch(entry->type)
552         {
553            case DM_INT:
554               int_value = (int) float_value;
555               if (int_value != options_get_int(opts, option_name))
556                  options_set_int(opts, option_name, int_value, OPTION_PRIORITY_CMDLINE);
557               break;
558
559            case DM_FLOAT:
560               // Use tztrim(float_value) or we get trailing zero's that break options_equal().
561               if (float_value != options_get_float(opts, option_name))
562                  options_set_string(opts, option_name, tztrim(float_value), OPTION_PRIORITY_CMDLINE);
563               break;
564
565            default:
566               assert(FALSE);
567               break;
568         }
569         break;
570
571      case CT_EDIT:
572         // NYI
573         break;
574
575      case CT_STATIC:
576      case CT_LISTVIEW:
577      case CT_UNKNOWN:
578         // non applicable
579         break;
580   }
581}
582
583
584
585//============================================================
586//  populate_control
587//============================================================
588
589static void populate_control(datamap *map, HWND control, core_options *opts, datamap_entry *entry, const char *option_name)
590{
591   int i;
592   BOOL bool_value;
593   int int_value;
594   float float_value;
595   const char *string_value;
596   const char *item_string;
597   int selected_index;
598   char buffer[128];
599   int trackbar_range;
600   int trackbar_pos;
601   double trackbar_range_d;
602   int minval_int, maxval_int;
603   float minval_float, maxval_float;
604
605   // use default populate control value
606   switch(get_control_type(control))
607   {
608      case CT_BUTTON:
609         assert(entry->type == DM_BOOL);
610         bool_value = options_get_bool(opts, option_name);
611         Button_SetCheck(control, bool_value);
612         break;
613
614      case CT_EDIT:
615      case CT_STATIC:
616         switch(entry->type)
617         {
618            case DM_STRING:
619               string_value = options_get_string(opts, option_name);
620               break;
621
622            case DM_INT:
623               int_value = options_get_int(opts, option_name);
624               if (entry->int_format != NULL)
625                  snprintf(buffer, ARRAY_LENGTH(buffer), entry->int_format, int_value);
626               else
627                  snprintf(buffer, ARRAY_LENGTH(buffer), "%d", int_value);
628               string_value = buffer;
629               break;
630
631            case DM_FLOAT:
632               float_value = options_get_float(opts, option_name);
633               if (entry->float_format != NULL)
634                  snprintf(buffer, ARRAY_LENGTH(buffer), entry->float_format, float_value);
635               else
636                  snprintf(buffer, ARRAY_LENGTH(buffer), "%f", float_value);
637               string_value = buffer;
638               break;
639
640            default:
641               string_value = "";
642               break;
643         }
644         if (string_value == NULL)
645            string_value = "";
646         win_set_window_text_utf8(control, string_value);
647         break;
648
649      case CT_COMBOBOX:
650         selected_index = 0;
651         switch(entry->type)
652         {
653            case DM_INT:
654               int_value = options_get_int(opts, option_name);
655               for (i = 0; i < ComboBox_GetCount(control); i++)
656               {
657                  if (int_value == (int) ComboBox_GetItemData(control, i))
658                  {
659                     selected_index = i;
660                     break;
661                  }
662               }
663               break;
664
665            case DM_STRING:
666               string_value = options_get_string(opts, option_name);
667               for (i = 0; i < ComboBox_GetCount(control); i++)
668               {
669                  item_string = (const char *) ComboBox_GetItemData(control, i);
670                  if (!core_stricmp(string_value, item_string ? item_string : ""))
671                  {
672                     selected_index = i;
673                     break;
674                  }
675               }
676               break;
677
678            default:
679               assert(FALSE);
680               break;
681         }
682         (void)ComboBox_SetCurSel(control, selected_index);
683         break;
684
685      case CT_TRACKBAR:
686         // do we need to set the trackbar options?
687         if (!entry->use_trackbar_options)
688         {
689            switch(options_get_range_type(opts, option_name))
690            {
691               case OPTION_RANGE_NONE:
692                  // do nothing
693                  break;
694
695               case OPTION_RANGE_INT:
696                  options_get_range_int(opts, option_name, &minval_int, &maxval_int);
697                  entry->use_trackbar_options = TRUE;
698                  entry->trackbar_min = minval_int;
699                  entry->trackbar_max = maxval_int;
700                  entry->trackbar_increments = 1;
701                  break;
702
703               case OPTION_RANGE_FLOAT:
704                  options_get_range_float(opts, option_name, &minval_float, &maxval_float);
705                  entry->use_trackbar_options = TRUE;
706                  entry->trackbar_min = minval_float;
707                  entry->trackbar_max = maxval_float;
708                  entry->trackbar_increments = 0.05;
709                  break;
710            }
711         }
712
713         // do we specify default options for this control?  if so, we need to specify
714         // the range
715         if (entry->use_trackbar_options)
716         {
717            trackbar_range_d = floor(((entry->trackbar_max - entry->trackbar_min)
718               / entry->trackbar_increments) + 0.5);
719            trackbar_range = (int) trackbar_range_d;
720            SendMessage(control, TBM_SETRANGEMIN, (WPARAM) FALSE, (LPARAM) 0);
721            SendMessage(control, TBM_SETRANGEMAX, (WPARAM) FALSE, (LPARAM) trackbar_range);
722         }
723
724         switch(entry->type)
725         {
726            case DM_INT:
727               int_value = options_get_int(opts, option_name);
728               trackbar_pos = trackbar_position_from_value(entry, int_value);
729               break;
730
731            case DM_FLOAT:
732               float_value = options_get_float(opts, option_name);
733               trackbar_pos = trackbar_position_from_value(entry, float_value);
734               break;
735
736            default:
737               trackbar_pos = 0;
738               assert(FALSE);
739               break;
740         }
741         SendMessage(control, TBM_SETPOS, (WPARAM) TRUE, (LPARAM) trackbar_pos);
742         break;
743
744      case CT_LISTVIEW:
745      case CT_UNKNOWN:
746         // non applicable
747         break;
748   }
749}
750
751// Return a string from a float value with trailing zeros removed.
752static   char *tztrim(float float_value) {
753   static char tz_string[20];
754   char float_string[20];
755   char *ptr;
756   int i = 0;
757
758   sprintf(float_string, "%f", float_value);
759
760   ptr = float_string;
761
762   // Copy before the '.'
763   while (*ptr && *ptr != '.') {
764      tz_string[i++] = *ptr++;
765   }
766   // add the '.' and the next digit
767   if (*ptr == '.') {
768      tz_string[i++] = *ptr++;
769      tz_string[i++] = *ptr++;
770   }
771   // Keep copying until we hit a '0'
772   while (*ptr && *ptr != '0') {
773      tz_string[i++] = *ptr++;
774   }
775   // Null terminate
776   tz_string[i] = '\0';
777   return tz_string;
778}
779
src/osd/winui/columnedit.h
r0r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11 ***************************************************************************/
12
13#ifndef COLUMNEDIT_H
14#define COLUMNEDIT_H
15
16INT_PTR InternalColumnDialogProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam,
17   int nColumnMax, int *shown, int *order,
18   LPCTSTR *names, void (*pfnGetRealColumnOrder)(int *),
19   void (*pfnGetColumnInfo)(int *pnOrder, int *pnShown),
20   void (*pfnSetColumnInfo)(int *pnOrder, int *pnShown));
21
22INT_PTR CALLBACK ColumnDialogProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam);
23
24#endif
src/osd/winui/verinfo.c
r0r996
1#include <stdio.h>
2#include <ctype.h>
3
4static int read_version_integer(const char *s, int *position)
5{
6   int value = 0;
7
8   if (isdigit(s[*position]))
9   {
10      while(isdigit(s[*position]))
11      {
12         value *= 10;
13         value += s[(*position)++] - '0';
14      }
15
16      if ((s[*position] == '.') || (s[*position] == 'u'))
17         (*position)++;
18   }
19   return value;
20}
21
22
23
24int main(int argc, char *argv[])
25{
26   extern char build_version[];
27   int version_major;
28   int version_minor;
29   int version_build;
30   int version_subbuild;
31   int year = 2006;
32   const char *author;
33   const char *comments;
34   const char *company_name;
35   const char *file_description;
36   const char *internal_name;
37   const char *product_name;
38   const char *legal_trademarks;
39   const char *original_filename;
40   char legal_copyright[256];
41   int position = 0;
42
43   version_major      = read_version_integer(build_version, &position);
44   version_minor      = read_version_integer(build_version, &position);
45   version_build      = read_version_integer(build_version, &position);
46   version_subbuild   = read_version_integer(build_version, &position);
47
48#ifdef MESS
49   file_description = "Multiple Emulation Super System for Win32";
50   company_name = "MESS Team";
51   product_name = "MESS";
52   sprintf(legal_copyright, "Copyright 1997-%d Nicola Salmoria and the MAME team", year);
53   original_filename = "MESS.exe";
54#else
55   file_description = "Multiple Arcade Machine Emulator for Win32";
56   company_name = "MAME Team";
57   product_name = "MAME32";
58   sprintf(legal_copyright, "Copyright 1997-%d Nicola Salmoria and the MAME team", year);
59   original_filename = "MAME32.exe";
60#endif
61   author = "Christopher Kirmse and Michael Soderstrom";
62   comments = file_description;
63   internal_name = product_name;
64   legal_trademarks = "";
65   
66   printf("VS_VERSION_INFO VERSIONINFO\n");
67   printf(" FILEVERSION %d,%d,%d,%d\n", version_major, version_minor, version_build, version_subbuild);
68   printf(" PRODUCTVERSION %d,%d,%d,%d\n", version_major, version_minor, version_build, version_subbuild);
69   printf(" FILEFLAGSMASK 0x3fL\n");
70   printf("#ifdef _DEBUG\n");
71   printf(" FILEFLAGS 0x1L\n");
72   printf("#else\n");
73   printf(" FILEFLAGS 0x0L\n");
74   printf("#endif\n");
75   printf(" FILEOS 0x40004L\n");
76   printf(" FILETYPE 0x1L\n");
77   printf(" FILESUBTYPE 0x0L\n");
78   printf("BEGIN\n");
79   printf("    BLOCK \"StringFileInfo\"\n");
80   printf("    BEGIN\n");
81   printf("        BLOCK \"040904b0\"\n");
82   printf("        BEGIN\n");
83   printf("            VALUE \"Author\", \"%s\\0\"\n", author);
84   printf("            VALUE \"Comments\", \"%s\\0\"\n", comments);
85   printf("            VALUE \"CompanyName\", \"%s\\0\"\n", company_name);
86   printf("            VALUE \"FileDescription\", \"%s\\0\"\n", file_description);
87   printf("            VALUE \"FileVersion\", \"%d, %d, %d, %d\\0\"\n", version_major, version_minor, version_build, version_subbuild);
88   printf("            VALUE \"InternalName\", \"%s\\0\"\n", internal_name);
89   printf("            VALUE \"LegalCopyright\", \"%s\\0\"\n", legal_copyright);
90   printf("            VALUE \"LegalTrademarks\", \"%s\\0\"\n", legal_trademarks);
91   printf("            VALUE \"OriginalFilename\", \"%s\\0\"\n", original_filename);
92   printf("            VALUE \"ProductName\", \"%s\\0\"\n", product_name);
93   printf("            VALUE \"ProductVersion\", \"%d, %d, %d, %d\\0\"\n", version_major, version_minor, version_build, version_subbuild);
94   printf("        END\n");
95   printf("    END\n");
96   printf("    BLOCK \"VarFileInfo\"\n");
97   printf("    BEGIN\n");
98   printf("        VALUE \"Translation\", 0x409, 1200\n");
99   printf("    END\n");
100   printf("END\n");
101
102   return 0;
103}
src/osd/winui/datafile.c
r0r996
1/****************************************************************************
2 *      datafile.c
3 *      History database engine
4 *
5 *      Token parsing by Neil Bradley
6 *      Modifications and higher-level functions by John Butler
7 ****************************************************************************/
8
9#include <assert.h>
10#include <ctype.h>
11#include <windows.h>
12#include "osdcomm.h"
13#include "osd_cpu.h"
14#include "driver.h"
15#include "datafile.h"
16#include "m32opts.h"
17
18/****************************************************************************
19 *      token parsing constants
20 ****************************************************************************/
21
22#define CR      0x0d    /* '\n' and '\r' meanings are swapped in some */
23#define LF      0x0a    /*     compilers (e.g., Mac compilers) */
24
25enum
26{
27        TOKEN_COMMA,
28        TOKEN_EQUALS,
29        TOKEN_SYMBOL,
30        TOKEN_LINEBREAK,
31        TOKEN_INVALID=-1
32};
33
34#define MAX_TOKEN_LENGTH        256
35
36
37/****************************************************************************
38 *      datafile constants
39 ****************************************************************************/
40#define DATAFILE_TAG '$'
41
42const char *DATAFILE_TAG_KEY = "$info";
43const char *DATAFILE_TAG_BIO = "$bio";
44const char *DATAFILE_TAG_MAME = "$mame";
45
46const char *history_filename = NULL;
47const char *mameinfo_filename = NULL;
48
49
50/****************************************************************************
51 *      private data for parsing functions
52 ****************************************************************************/
53static mame_file *fp;                                       /* Our file pointer */
54static long dwFilePos;                                          /* file position */
55static UINT8 bToken[MAX_TOKEN_LENGTH];          /* Our current token */
56
57/* an array of driver name/drivers array index sorted by driver name
58   for fast look up by name */
59typedef struct
60{
61    const char *name;
62    int index;
63} driver_data_type;
64static driver_data_type *sorted_drivers = NULL;
65static int num_games;
66
67
68/**************************************************************************
69 **************************************************************************
70 *
71 *              Parsing functions
72 *
73 **************************************************************************
74 **************************************************************************/
75
76/*
77 * DriverDataCompareFunc -- compare function for GetGameNameIndex
78 */
79static int CLIB_DECL DriverDataCompareFunc(const void *arg1,const void *arg2)
80{
81    return strcmp( ((driver_data_type *)arg1)->name, ((driver_data_type *)arg2)->name );
82}
83
84/*
85 * GetGameNameIndex -- given a driver name (in lowercase), return
86 * its index in the main drivers[] array, or -1 if it's not found.
87 */
88static int GetGameNameIndex(const char *name)
89{
90    driver_data_type *driver_index_info;
91   driver_data_type key;
92   key.name = name;
93
94   if (sorted_drivers == NULL)
95   {
96      /* initialize array of game names/indices */
97      int i;
98
99      sorted_drivers = (driver_data_type *)malloc(sizeof(driver_data_type) * num_games);
100      for (i=0;i<num_games;i++)
101      {
102         sorted_drivers[i].name = drivers[i]->name;
103         sorted_drivers[i].index = i;
104      }
105      qsort(sorted_drivers,num_games,sizeof(driver_data_type),DriverDataCompareFunc);
106   }
107
108   /* uses our sorted array of driver names to get the index in log time */
109   driver_index_info = bsearch(&key,sorted_drivers,num_games,sizeof(driver_data_type),
110                        DriverDataCompareFunc);
111
112   if (driver_index_info == NULL)
113      return -1;
114
115   return driver_index_info->index;
116
117}
118
119/****************************************************************************
120 *      GetNextToken - Pointer to the token string pointer
121 *                                 Pointer to position within file
122 *
123 *      Returns token, or TOKEN_INVALID if at end of file
124 ****************************************************************************/
125static UINT32 GetNextToken(UINT8 **ppszTokenText, long *pdwPosition)
126{
127        UINT32 dwLength;                                                /* Length of symbol */
128        long dwPos;                                                             /* Temporary position */
129        UINT8 *pbTokenPtr = bToken;                             /* Point to the beginning */
130        UINT8 bData;                                                    /* Temporary data byte */
131
132        while (1)
133        {
134                bData = mame_fgetc(fp);                                  /* Get next character */
135
136                /* If we're at the end of the file, bail out */
137
138                if (mame_feof(fp))
139                        return(TOKEN_INVALID);
140
141                /* If it's not whitespace, then let's start eating characters */
142
143                if (' ' != bData && '\t' != bData)
144                {
145                        /* Store away our file position (if given on input) */
146
147                        if (pdwPosition)
148                                *pdwPosition = dwFilePos;
149
150                        /* If it's a separator, special case it */
151
152                        if (',' == bData || '=' == bData)
153                        {
154                                *pbTokenPtr++ = bData;
155                                *pbTokenPtr = '\0';
156                                ++dwFilePos;
157
158                                if (',' == bData)
159                                        return(TOKEN_COMMA);
160                                else
161                                        return(TOKEN_EQUALS);
162                        }
163
164                        /* Otherwise, let's try for a symbol */
165
166                        if (bData > ' ')
167                        {
168                                dwLength = 0;                   /* Assume we're 0 length to start with */
169
170                                /* Loop until we've hit something we don't understand */
171
172                                while (bData != ',' &&
173                                                 bData != '=' &&
174                                                 bData != ' ' &&
175                                                 bData != '\t' &&
176                                                 bData != '\n' &&
177                                                 bData != '\r' &&
178                                                 mame_feof(fp) == 0)
179                                {
180                                        ++dwFilePos;
181                                        *pbTokenPtr++ = bData;  /* Store our byte */
182                                        ++dwLength;
183                                        assert(dwLength < MAX_TOKEN_LENGTH);
184                                        bData = mame_fgetc(fp);
185                                }
186
187                                /* If it's not the end of the file, put the last received byte */
188                                /* back. We don't want to touch the file position, though if */
189                                /* we're past the end of the file. Otherwise, adjust it. */
190
191                                if (0 == mame_feof(fp))
192                                {
193                                        mame_ungetc(bData, fp);
194                                }
195
196                                /* Null terminate the token */
197
198                                *pbTokenPtr = '\0';
199
200                                /* Connect up the */
201
202                                if (ppszTokenText)
203                                        *ppszTokenText = bToken;
204
205                                return(TOKEN_SYMBOL);
206                        }
207
208                        /* Not a symbol. Let's see if it's a cr/cr, lf/lf, or cr/lf/cr/lf */
209                        /* sequence */
210
211                        if (LF == bData)
212                        {
213                                /* Unix style perhaps? */
214
215                                bData = mame_fgetc(fp);          /* Peek ahead */
216                                mame_ungetc(bData, fp);          /* Force a retrigger if subsequent LF's */
217
218                                if (LF == bData)                /* Two LF's in a row - it's a UNIX hard CR */
219                                {
220                                        ++dwFilePos;
221                                        *pbTokenPtr++ = bData;  /* A real linefeed */
222                                        *pbTokenPtr = '\0';
223                                        return(TOKEN_LINEBREAK);
224                                }
225
226                                /* Otherwise, fall through and keep parsing. */
227
228                        }
229                        else
230                        if (CR == bData)                /* Carriage return? */
231                        {
232                                /* Figure out if it's Mac or MSDOS format */
233
234                                ++dwFilePos;
235                                bData = mame_fgetc(fp);          /* Peek ahead */
236
237                                /* We don't need to bother with EOF checking. It will be 0xff if */
238                                /* it's the end of the file and will be caught by the outer loop. */
239
240                                if (CR == bData)                /* Mac style hard return! */
241                                {
242                                        /* Do not advance the file pointer in case there are successive */
243                                        /* CR/CR sequences */
244
245                                        /* Stuff our character back upstream for successive CR's */
246
247                                        mame_ungetc(bData, fp);
248
249                                        *pbTokenPtr++ = bData;  /* A real carriage return (hard) */
250                                        *pbTokenPtr = '\0';
251                                        return(TOKEN_LINEBREAK);
252                                }
253                                else
254                                if (LF == bData)        /* MSDOS format! */
255                                {
256                                        ++dwFilePos;                    /* Our file position to reset to */
257                                        dwPos = dwFilePos;              /* Here so we can reposition things */
258
259                                        /* Look for a followup CR/LF */
260
261                                        bData = mame_fgetc(fp);  /* Get the next byte */
262
263                                        if (CR == bData)        /* CR! Good! */
264                                        {
265                                                bData = mame_fgetc(fp);  /* Get the next byte */
266
267                                                /* We need to do this to pick up subsequent CR/LF sequences */
268
269                                                mame_fseek(fp, dwPos, SEEK_SET);
270
271                                                if (pdwPosition)
272                                                        *pdwPosition = dwPos;
273
274                                                if (LF == bData)        /* LF? Good! */
275                                                {
276                                                        *pbTokenPtr++ = '\r';
277                                                        *pbTokenPtr++ = '\n';
278                                                        *pbTokenPtr = '\0';
279
280                                                        return(TOKEN_LINEBREAK);
281                                                }
282                                        }
283                                        else
284                                        {
285                                                --dwFilePos;
286                                                mame_ungetc(bData, fp);  /* Put the character back. No good */
287                                        }
288                                }
289                                else
290                                {
291                                        --dwFilePos;
292                                        mame_ungetc(bData, fp);  /* Put the character back. No good */
293                                }
294
295                                /* Otherwise, fall through and keep parsing */
296                        }
297                }
298
299                ++dwFilePos;
300        }
301}
302
303
304/****************************************************************************
305 *      ParseClose - Closes the existing opened file (if any)
306 ****************************************************************************/
307static void ParseClose(void)
308{
309        /* If the file is open, time for fclose. */
310
311        if (fp)
312        {
313                mame_fclose(fp);
314        }
315
316        fp = NULL;
317}
318
319
320/****************************************************************************
321 *      ParseOpen - Open up file for reading
322 ****************************************************************************/
323static UINT8 ParseOpen(const char *pszFilename)
324{
325        /* Open file up in binary mode */
326
327        mame_fopen_options(Mame32Global(), NULL, pszFilename, OPEN_FLAG_READ, &fp);
328
329        /* If this is NULL, return FALSE. We can't open it */
330
331        if (NULL == fp)
332        {
333                return(FALSE);
334        }
335
336        /* Otherwise, prepare! */
337
338        dwFilePos = 0;
339        return(TRUE);
340}
341
342
343/****************************************************************************
344 *      ParseSeek - Move the file position indicator
345 ****************************************************************************/
346static UINT8 ParseSeek(long offset, int whence)
347{
348        int result = mame_fseek(fp, offset, whence);
349
350        if (0 == result)
351        {
352                dwFilePos = mame_ftell(fp);
353        }
354        return (UINT8)result;
355}
356
357
358
359/**************************************************************************
360 **************************************************************************
361 *
362 *              Datafile functions
363 *
364 **************************************************************************
365 **************************************************************************/
366
367
368/**************************************************************************
369 *      ci_strncmp - case insensitive character array compare
370 *
371 *      Returns zero if the first n characters of s1 and s2 are equal,
372 *      ignoring case.
373 **************************************************************************/
374static int ci_strncmp (const char *s1, const char *s2, int n)
375{
376        int c1, c2;
377
378        while (n)
379        {
380                if ((c1 = tolower (*s1)) != (c2 = tolower (*s2)))
381                        return (c1 - c2);
382                else if (!c1)
383                        break;
384                --n;
385
386                s1++;
387                s2++;
388        }
389        return 0;
390}
391
392
393/**************************************************************************
394 *      index_datafile
395 *      Create an index for the records in the currently open datafile.
396 *
397 *      Returns 0 on error, or the number of index entries created.
398 **************************************************************************/
399static int index_datafile (struct tDatafileIndex **_index)
400{
401        struct tDatafileIndex *idx;
402        int count = 0;
403        UINT32 token = TOKEN_SYMBOL;
404      num_games = 0;
405      while (drivers[num_games] != NULL)
406         num_games++;
407        /* rewind file */
408        if (ParseSeek (0L, SEEK_SET)) return 0;
409
410        /* allocate index */
411        idx = *_index = malloc (num_games * sizeof (struct tDatafileIndex));
412        if (NULL == idx) return 0;
413
414        /* loop through datafile */
415        while ((count < (num_games - 1)) && TOKEN_INVALID != token)
416        {
417                long tell;
418                UINT8 *s;
419
420                token = GetNextToken (&s, &tell);
421                if (TOKEN_SYMBOL != token) continue;
422
423                /* DATAFILE_TAG_KEY identifies the driver */
424                if (!ci_strncmp (DATAFILE_TAG_KEY, (char *)s, strlen (DATAFILE_TAG_KEY)))
425                {
426                        token = GetNextToken (&s, &tell);
427                        if (TOKEN_EQUALS == token)
428                        {
429                                int done = 0;
430
431                                token = GetNextToken (&s, &tell);
432                                while (!done && TOKEN_SYMBOL == token)
433                                {
434                           int game_index;
435                           UINT8 *p;
436                           for (p = s; *p; p++)
437                              *p = tolower(*p);
438
439                           game_index = GetGameNameIndex((char *)s);
440                           if (game_index >= 0)
441                           {
442                              idx->driver = drivers[game_index];
443                              idx->offset = tell;
444                              idx++;
445                              count++;
446                              /* done = 1;  Not done, as we must process other clones in list */
447
448                           }
449                           if (!done)
450                           {
451                              token = GetNextToken (&s, &tell);
452
453                              if (TOKEN_COMMA == token)
454                                 token = GetNextToken (&s, &tell);
455                              else
456                                 done = 1; /* end of key field */
457                           }
458                                }
459                        }
460                }
461        }
462
463        /* mark end of index */
464        idx->offset = 0L;
465        idx->driver = 0;
466        return count;
467}
468
469
470/**************************************************************************
471 *      load_datafile_text
472 *
473 *      Loads text field for a driver into the buffer specified. Specify the
474 *      driver, a pointer to the buffer, the buffer size, the index created by
475 *      index_datafile(), and the desired text field (e.g., DATAFILE_TAG_BIO).
476 *
477 *      Returns 0 if successful.
478 **************************************************************************/
479static int load_datafile_text (const game_driver *drv, char *buffer, int bufsize,
480        struct tDatafileIndex *idx, const char *tag)
481{
482        int     offset = 0;
483        int found = 0;
484        UINT32  token = TOKEN_SYMBOL;
485        UINT32  prev_token = TOKEN_SYMBOL;
486
487        *buffer = '\0';
488
489        /* find driver in datafile index */
490        while (idx->driver)
491        {
492
493                if (idx->driver == drv) break;
494
495                idx++;
496        }
497        if (idx->driver == 0) return 1; /* driver not found in index */
498
499        /* seek to correct point in datafile */
500        if (ParseSeek (idx->offset, SEEK_SET)) return 1;
501
502        /* read text until buffer is full or end of entry is encountered */
503        while (TOKEN_INVALID != token)
504        {
505                UINT8 *s;
506                int len;
507                long tell;
508
509                token = GetNextToken (&s, &tell);
510                if (TOKEN_INVALID == token) continue;
511
512                if (found)
513                {
514                        /* end entry when a tag is encountered */
515                        if (TOKEN_SYMBOL == token && DATAFILE_TAG == s[0] && TOKEN_LINEBREAK == prev_token) break;
516
517                        prev_token = token;
518
519                        /* translate platform-specific linebreaks to '\n' */
520                        if (TOKEN_LINEBREAK == token)
521                     strcpy ((char *)s, "\n");
522
523                        /* append a space to words */
524                        if (TOKEN_LINEBREAK != token)
525                     strcat ((char *)s, " ");
526
527                        /* remove extraneous space before commas */
528                        if (TOKEN_COMMA == token)
529                        {
530                                --buffer;
531                                --offset;
532                                *buffer = '\0';
533                        }
534
535                        /* Get length of text to add to the buffer */
536                        len = strlen ((char *)s);
537
538                        /* Check for buffer overflow */
539                        /* For some reason we can get a crash if we try */
540                        /* to use the last 30 characters of the buffer  */
541                        if ((bufsize - offset) - len <= 45)
542                        {
543                            strcpy ((char *)s, " ...[TRUNCATED]");
544                            len = strlen((char *)s);
545                            strcpy (buffer, (char *)s);
546                            buffer += len;
547                            offset += len;
548                            break;
549                        }
550
551                        /* add this word to the buffer */
552                        strcpy (buffer, (char *)s);
553                        buffer += len;
554                        offset += len;
555                }
556                else
557                {
558                        if (TOKEN_SYMBOL == token)
559                        {
560                                /* looking for requested tag */
561                                if (!ci_strncmp (tag, (char *)s, strlen (tag)))
562                                        found = 1;
563                                else if (!ci_strncmp (DATAFILE_TAG_KEY, (char *)s, strlen (DATAFILE_TAG_KEY)))
564                                        break; /* error: tag missing */
565                        }
566                }
567        }
568        return (!found);
569}
570
571
572/**************************************************************************
573 *      load_driver_history
574 *      Load history text for the specified driver into the specified buffer.
575 *      Combines $bio field of HISTORY.DAT with $mame field of MAMEINFO.DAT.
576 *
577 *      Returns 0 if successful.
578 *
579 *      NOTE: For efficiency the indices are never freed (intentional leak).
580 **************************************************************************/
581int load_driver_history (const game_driver *drv, char *buffer, int bufsize)
582{
583        static struct tDatafileIndex *hist_idx = 0;
584        static struct tDatafileIndex *mame_idx = 0;
585//   const game_driver *clone_of = NULL;
586        int history = 0, mameinfo = 0;
587        int err = 0;
588
589        *buffer = 0;
590
591
592        if (!history_filename || !*history_filename)
593                history_filename = "history.dat";
594
595        /* try to open history datafile */
596        if (ParseOpen (history_filename))
597        {
598                /* create index if necessary */
599                if (hist_idx)
600                        history = 1;
601                else
602                        history = (index_datafile (&hist_idx) != 0);
603
604                /* load history text */
605                if (hist_idx)
606                {
607                        const game_driver *gdrv;
608
609                        gdrv = drv;
610                        do
611                        {
612                                if ( ( gdrv->flags & GAME_IS_BIOS_ROOT) == 1 )
613               break;
614                                err = load_datafile_text (gdrv, buffer, bufsize,
615                                                                                  hist_idx, DATAFILE_TAG_BIO);
616            gdrv = driver_get_clone(gdrv);
617                        } while (err && gdrv);
618
619                        if (err) history = 0;
620                }
621                ParseClose ();
622        }
623
624        if (!mameinfo_filename || !*mameinfo_filename)
625                mameinfo_filename = "mameinfo.dat";
626
627        /* try to open mameinfo datafile */
628        if (ParseOpen (mameinfo_filename))
629        {
630                /* create index if necessary */
631                if (mame_idx)
632                        mameinfo = 1;
633                else
634                        mameinfo = (index_datafile (&mame_idx) != 0);
635
636                /* load informational text (append) */
637                if (mame_idx)
638                {
639         int len = strlen (buffer);
640                        const game_driver *gdrv;
641
642                        gdrv = drv;
643                        do
644                        {
645                                if ( (gdrv->flags & GAME_IS_BIOS_ROOT) == 1 )
646               break;
647            err = load_datafile_text (gdrv, buffer+len, bufsize-len,
648                                                                                  mame_idx, DATAFILE_TAG_MAME);
649           
650            gdrv = driver_get_clone(gdrv);
651                        } while (err && gdrv);
652
653                        if (err) mameinfo = 0;
654                }
655                ParseClose ();
656        }
657
658        return (history == 0 && mameinfo == 0);
659}
src/osd/winui/resource.hm
r0r996
1// Microsoft Visual C++ generated Help ID include file.
2// Used by mame32.rc
3//
4#define HIDC_ADSTICK                    0x80b904b9    // IDD_PROP_CONTROLLER
5#define HIDC_ANTIALIAS                  0x809f0405    // IDD_PROP_VECTOR
6#define HIDC_ARTWORK_CROP               0x809e03fa    // IDD_PROP_MISC
7#define HIDC_ASPECT                     0x80bb04c4    // IDD_PROP_SCREEN
8#define HIDC_ASPECTRATIOD               0x80bb0483    // IDD_PROP_SCREEN
9#define HIDC_ASPECTRATION               0x80bb0482    // IDD_PROP_SCREEN
10#define HIDC_AUDIO_LATENCY              0x809b04a2    // IDD_PROP_SOUND
11#define HIDC_AUTOFRAMESKIP              0x809c0449    // IDD_PROP_ADVANCED
12#define HIDC_BACKDROPS                  0x809e040a    // IDD_PROP_MISC
13#define HIDC_BEAM                       0x809f0406    // IDD_PROP_VECTOR
14#define HIDC_BEZELS                     0x809e03fd    // IDD_PROP_MISC
15#define HIDC_BIOS                       0x809e04b1    // IDD_PROP_MISC
16#define HIDC_BRIGHTCORRECT              0x809a0400    // IDD_PROP_DISPLAY
17#define HIDC_BROADCAST                  0x80ad0486    // IDD_INTERFACE_OPTIONS
18#define HIDC_CHEAT                      0x809e03f8    // IDD_PROP_MISC
19#define HIDC_CONTRAST                   0x809a0402    // IDD_PROP_DISPLAY
20#define HIDC_CYCLETIMESEC               0x80ad04bb    // IDD_INTERFACE_OPTIONS
21#define HIDC_D3D_FILTER                 0x809a04a0    // IDD_PROP_DISPLAY
22#define HIDC_D3D_VERSION                0x809a04a3    // IDD_PROP_DISPLAY
23#define HIDC_DEBUG                      0x809e04cf    // IDD_PROP_MISC
24#define HIDC_DEFAULT_INPUT              0x809d0469    // IDD_PROP_INPUT
25#define HIDC_DIAL                       0x80b904bb    // IDD_PROP_CONTROLLER
26#define HIDC_DUAL_LIGHTGUN              0x809d04af    // IDD_PROP_INPUT
27#define HIDC_ENABLE_AUTOSAVE            0x809e0499    // IDD_PROP_MISC
28#define HIDC_FILTER_CLONES              0x80a90455    // IDD_FILTERS
29#define HIDC_FILTER_EDIT                0x80a9046d    // IDD_FILTERS
30#define HIDC_FILTER_HORIZONTAL          0x80a9049c    // IDD_FILTERS
31#define HIDC_FILTER_NONWORKING          0x80a90454    // IDD_FILTERS
32#define HIDC_FILTER_ORIGINALS           0x80a9045b    // IDD_FILTERS
33#define HIDC_FILTER_RASTER              0x80a90452    // IDD_FILTERS
34#define HIDC_FILTER_UNAVAILABLE         0x80a90453    // IDD_FILTERS
35#define HIDC_FILTER_VECTOR              0x80a90451    // IDD_FILTERS
36#define HIDC_FILTER_VERTICAL            0x80a90460    // IDD_FILTERS
37#define HIDC_FILTER_WORKING             0x80a9045c    // IDD_FILTERS
38#define HIDC_FLICKER                    0x809f0407    // IDD_PROP_VECTOR
39#define HIDC_FLIPX                      0x809a0408    // IDD_PROP_DISPLAY
40#define HIDC_FLIPY                      0x809a0409    // IDD_PROP_DISPLAY
41#define HIDC_FRAMESKIP                  0x809c03f1    // IDD_PROP_ADVANCED
42#define HIDC_FSBRIGHTNESS               0x809c0444    // IDD_PROP_ADVANCED
43#define HIDC_FSCONTRAST                 0x809c040e    // IDD_PROP_ADVANCED
44#define HIDC_FSGAMMA                    0x809c0442    // IDD_PROP_ADVANCED
45#define HIDC_GAME_CAPTION               0x80ad04c8    // IDD_INTERFACE_OPTIONS
46#define HIDC_GAMMA                      0x809a03ff    // IDD_PROP_DISPLAY
47#define HIDC_HIDE_MOUSE                 0x80ad04b5    // IDD_INTERFACE_OPTIONS
48#define HIDC_HIGH_PRIORITY              0x809e049f    // IDD_PROP_MISC
49#define HIDC_HISTORY                    0x806504cb    // IDD_MAIN
50#define HIDC_HWSTRETCH                  0x809a046c    // IDD_PROP_DISPLAY
51#define HIDC_JDZ                        0x809d0487    // IDD_PROP_INPUT
52#define HIDC_JOYSTICK                   0x809d03eb    // IDD_PROP_INPUT
53#define HIDC_JOY_GUI                    0x80ad0485    // IDD_INTERFACE_OPTIONS
54#define HIDC_JSAT                       0x809d048b    // IDD_PROP_INPUT
55#define HIDC_KEEPASPECT                 0x809a0474    // IDD_PROP_DISPLAY
56#define HIDC_LANGUAGECHECK              0x80b204d1    // IDD_LANGUAGE
57#define HIDC_LANGUAGEEDIT               0x80b204d4    // IDD_LANGUAGE
58#define HIDC_LIGHTGUN                   0x809d048f    // IDD_PROP_INPUT
59#define HIDC_LIGHTGUNDEVICE             0x80b904bd    // IDD_PROP_CONTROLLER
60#define HIDC_LOG                        0x809e03f9    // IDD_PROP_MISC
61#define HIDC_MAXIMIZE                   0x809a046e    // IDD_PROP_DISPLAY
62#define HIDC_MOUSE                      0x80b904be    // IDD_PROP_CONTROLLER
63#define HIDC_MULTIKEYBOARD              0x809d0429    // IDD_PROP_INPUT
64#define HIDC_MULTIMOUSE                 0x809d04ce    // IDD_PROP_INPUT
65#define HIDC_MULTITHREAD_RENDERING      0x809e04c3    // IDD_PROP_MISC
66#define HIDC_NUMSCREENS                 0x80bb0404    // IDD_PROP_SCREEN
67#define HIDC_OVERLAYS                   0x809e03fb    // IDD_PROP_MISC
68#define HIDC_PADDLE                     0x80b904b8    // IDD_PROP_CONTROLLER
69#define HIDC_PAUSEBRIGHT                0x809a049c    // IDD_PROP_DISPLAY
70#define HIDC_PEDAL                      0x80b904ba    // IDD_PROP_CONTROLLER
71#define HIDC_POSITIONAL                 0x80b904bf    // IDD_PROP_CONTROLLER
72#define HIDC_PRESCALE                   0x809a041f    // IDD_PROP_DISPLAY
73#define HIDC_PROP_RESET                 0x809c044d    // IDD_PROP_ADVANCED
74#define HIDC_RANDOM_BG                  0x80ad0491    // IDD_INTERFACE_OPTIONS
75#define HIDC_REFRESH                    0x80bb047c    // IDD_PROP_SCREEN
76#define HIDC_REFRESHSPEED               0x809c04d0    // IDD_PROP_ADVANCED
77#define HIDC_RELOAD                     0x809d04ae    // IDD_PROP_INPUT
78#define HIDC_RESET_DEFAULT              0x80aa04a2    // IDD_RESET
79#define HIDC_RESET_EFFECT               0x809c0459    // IDD_PROP_ADVANCED
80#define HIDC_RESET_FILTERS              0x80aa049f    // IDD_RESET
81#define HIDC_RESET_GAMES                0x80aa049d    // IDD_RESET
82#define HIDC_RESET_UI                   0x80aa049e    // IDD_RESET
83#define HIDC_ROTATE                     0x809a03f2    // IDD_PROP_DISPLAY
84#define HIDC_SAMPLERATE                 0x809b0403    // IDD_PROP_SOUND
85#define HIDC_SAMPLES                    0x809b0461    // IDD_PROP_SOUND
86#define HIDC_SCREEN                     0x80bb03f4    // IDD_PROP_SCREEN
87#define HIDC_SCREENSELECT               0x80bb03f7    // IDD_PROP_SCREEN
88#define HIDC_SELECT_EFFECT              0x809c04c2    // IDD_PROP_ADVANCED
89#define HIDC_SIZES                      0x80bb03ed    // IDD_PROP_SCREEN
90#define HIDC_SKIP_GAME_INFO             0x809e049a    // IDD_PROP_MISC
91#define HIDC_SLEEP                      0x809e03fe    // IDD_PROP_MISC
92#define HIDC_SPEED                      0x809c04d2    // IDD_PROP_ADVANCED
93#define HIDC_START_GAME_CHECK           0x80ad045b    // IDD_INTERFACE_OPTIONS
94#define HIDC_STEADYKEY                  0x809d0480    // IDD_PROP_INPUT
95#define HIDC_STRETCH_SCREENSHOT_LARGER  0x80ad04bd    // IDD_INTERFACE_OPTIONS
96#define HIDC_SWITCHRES                  0x80bb046d    // IDD_PROP_SCREEN
97#define HIDC_SYNCREFRESH                0x809c0476    // IDD_PROP_ADVANCED
98#define HIDC_THROTTLE                   0x809a0478    // IDD_PROP_DISPLAY
99#define HIDC_TRACKBALL                  0x80b904bc    // IDD_PROP_CONTROLLER
100#define HIDC_TRIPLE_BUFFER              0x809c0467    // IDD_PROP_ADVANCED
101#define HIDC_USE_DEFAULT                0x809c0401    // IDD_PROP_ADVANCED
102#define HIDC_USE_MOUSE                  0x809d0477    // IDD_PROP_INPUT
103#define HIDC_USE_SOUND                  0x809b046d    // IDD_PROP_SOUND
104#define HIDC_VIDEO_MODE                 0x809a04ca    // IDD_PROP_DISPLAY
105#define HIDC_VIEW                       0x80bb03f6    // IDD_PROP_SCREEN
106#define HIDC_VOLUME                     0x809b045d    // IDD_PROP_SOUND
107#define HIDC_WAITVSYNC                  0x809c0471    // IDD_PROP_ADVANCED
108#define HIDC_WINDOWED                   0x809a0497    // IDD_PROP_DISPLAY
src/osd/winui/directories.c
r0r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11 ***************************************************************************/
12
13/***************************************************************************
14
15  Directories.c
16
17***************************************************************************/
18
19#define COBJMACROS
20#define WIN32_LEAN_AND_MEAN
21#include <windows.h>
22#include <windowsx.h>
23#include <shlobj.h>
24#include <sys/stat.h>
25#include <assert.h>
26#include <tchar.h>
27
28#include "screenshot.h"
29#include "mame32.h"
30#include "directories.h"
31#include "resource.h"
32#include "strconv.h"
33#include "m32util.h"
34
35#define MAX_DIRS 20
36
37/***************************************************************************
38    Internal structures
39 ***************************************************************************/
40
41typedef struct
42{
43   TCHAR   m_Directories[MAX_DIRS][MAX_PATH];
44   int     m_NumDirectories;
45   BOOL    m_bModified;
46} tPath;
47
48typedef struct
49{
50   tPath   *m_Path;
51   TCHAR   *m_Directory;
52} tDirInfo;
53
54/***************************************************************************
55    Function prototypes
56 ***************************************************************************/
57
58static int CALLBACK BrowseCallbackProc(HWND hwnd, UINT uMsg, LPARAM lParam, LPARAM lpData);
59#ifdef MESS
60BOOL            BrowseForDirectory(HWND hwnd, LPCTSTR pStartDir, TCHAR* pResult);
61#else
62static BOOL     BrowseForDirectory(HWND hwnd, LPCTSTR pStartDir, TCHAR* pResult);
63#endif
64
65static void     DirInfo_SetDir(tDirInfo *pInfo, int nType, int nItem, LPCTSTR pText);
66static TCHAR*   DirInfo_Dir(tDirInfo *pInfo, int nType);
67static TCHAR*   DirInfo_Path(tDirInfo *pInfo, int nType, int nItem);
68static void     DirInfo_SetModified(tDirInfo *pInfo, int nType, BOOL bModified);
69static BOOL     DirInfo_Modified(tDirInfo *pInfo, int nType);
70static TCHAR*   FixSlash(TCHAR *s);
71
72static void     UpdateDirectoryList(HWND hDlg);
73
74static void     Directories_OnSelChange(HWND hDlg);
75static BOOL     Directories_OnInitDialog(HWND hDlg, HWND hwndFocus, LPARAM lParam);
76static void     Directories_OnDestroy(HWND hDlg);
77static void     Directories_OnClose(HWND hDlg);
78static void     Directories_OnOk(HWND hDlg);
79static void     Directories_OnCancel(HWND hDlg);
80static void     Directories_OnInsert(HWND hDlg);
81static void     Directories_OnBrowse(HWND hDlg);
82static void     Directories_OnDelete(HWND hDlg);
83static BOOL     Directories_OnBeginLabelEdit(HWND hDlg, NMHDR* pNMHDR);
84static BOOL     Directories_OnEndLabelEdit(HWND hDlg, NMHDR* pNMHDR);
85static void     Directories_OnCommand(HWND hDlg, int id, HWND hwndCtl, UINT codeNotify);
86static BOOL     Directories_OnNotify(HWND hDlg, int id, NMHDR* pNMHDR);
87
88/***************************************************************************
89    External variables
90 ***************************************************************************/
91
92/***************************************************************************
93    Internal variables
94 ***************************************************************************/
95
96static tDirInfo *g_pDirInfo;
97
98/***************************************************************************
99    External function definitions
100 ***************************************************************************/
101
102INT_PTR CALLBACK DirectoriesDialogProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam)
103{
104   BOOL bReturn = FALSE;
105
106   switch (Msg)
107   {
108   case WM_INITDIALOG:
109      return (BOOL)HANDLE_WM_INITDIALOG(hDlg, wParam, lParam, Directories_OnInitDialog);
110
111   case WM_COMMAND:
112      HANDLE_WM_COMMAND(hDlg, wParam, lParam, Directories_OnCommand);
113      bReturn = TRUE;
114      break;
115
116   case WM_NOTIFY:
117      return (BOOL)HANDLE_WM_NOTIFY(hDlg, wParam, lParam, Directories_OnNotify);
118      break;
119
120   case WM_CLOSE:
121      HANDLE_WM_CLOSE(hDlg, wParam, lParam, Directories_OnClose);
122      break;
123
124   case WM_DESTROY:
125      HANDLE_WM_DESTROY(hDlg, wParam, lParam, Directories_OnDestroy);
126      break;
127
128   default:
129      bReturn = FALSE;
130   }
131   return bReturn;
132}
133
134/***************************************************************************
135   Internal function definitions
136 ***************************************************************************/
137
138static BOOL IsMultiDir(int nType)
139{
140   return g_directoryInfo[nType].bMulti;
141}
142
143static void DirInfo_SetDir(tDirInfo *pInfo, int nType, int nItem, LPCTSTR pText)
144{
145   TCHAR *s;
146   TCHAR *pOldText;
147
148   if (IsMultiDir(nType))
149   {
150      assert(nItem >= 0);
151      _tcscpy(DirInfo_Path(pInfo, nType, nItem), pText);
152      DirInfo_SetModified(pInfo, nType, TRUE);
153   }
154   else
155   {
156      s = win_tstring_strdup(pText);
157      if (!s)
158         return;
159      pOldText = pInfo[nType].m_Directory;
160      if (pOldText)
161         free(pOldText);
162      pInfo[nType].m_Directory = s;
163   }
164}
165
166static TCHAR* DirInfo_Dir(tDirInfo *pInfo, int nType)
167{
168   assert(!IsMultiDir(nType));
169   return pInfo[nType].m_Directory;
170}
171
172static TCHAR* DirInfo_Path(tDirInfo *pInfo, int nType, int nItem)
173{
174   return pInfo[nType].m_Path->m_Directories[nItem];
175}
176
177static void DirInfo_SetModified(tDirInfo *pInfo, int nType, BOOL bModified)
178{
179   assert(IsMultiDir(nType));
180   pInfo[nType].m_Path->m_bModified = bModified;
181}
182
183static BOOL DirInfo_Modified(tDirInfo *pInfo, int nType)
184{
185   assert(IsMultiDir(nType));
186   return pInfo[nType].m_Path->m_bModified;
187}
188
189#define DirInfo_NumDir(pInfo, path) \
190   ((pInfo)[(path)].m_Path->m_NumDirectories)
191
192/* lop off trailing backslash if it exists */
193static TCHAR * FixSlash(TCHAR *s)
194{
195   int len = 0;
196   
197   if (s)
198      len = _tcslen(s);
199
200   if (len && s[len - 1] == '\\')
201      s[len - 1] = '\0';
202
203   return s;
204}
205
206static void UpdateDirectoryList(HWND hDlg)
207{
208   int    i;
209   int    nType;
210   LV_ITEM Item;
211   HWND   hList  = GetDlgItem(hDlg, IDC_DIR_LIST);
212   HWND   hCombo = GetDlgItem(hDlg, IDC_DIR_COMBO);
213
214   /* Remove previous */
215
216   ListView_DeleteAllItems(hList);
217
218   /* Update list */
219
220   memset(&Item, 0, sizeof(LV_ITEM));
221   Item.mask = LVIF_TEXT;
222
223   nType = ComboBox_GetCurSel(hCombo);
224   if (IsMultiDir(nType))
225   {
226      Item.pszText = (TCHAR*) TEXT(DIRLIST_NEWENTRYTEXT);
227      ListView_InsertItem(hList, &Item);
228      for (i = DirInfo_NumDir(g_pDirInfo, nType) - 1; 0 <= i; i--)
229      {
230         Item.pszText = DirInfo_Path(g_pDirInfo, nType, i);
231         ListView_InsertItem(hList, &Item);
232      }
233   }
234   else
235   {
236      Item.pszText = DirInfo_Dir(g_pDirInfo, nType);
237      ListView_InsertItem(hList, &Item);
238   }
239
240   /* select first one */
241
242   ListView_SetItemState(hList, 0, LVIS_SELECTED, LVIS_SELECTED);
243}
244
245static void Directories_OnSelChange(HWND hDlg)
246{
247   UpdateDirectoryList(hDlg);
248   
249   if (ComboBox_GetCurSel(GetDlgItem(hDlg, IDC_DIR_COMBO)) == 0
250   ||   ComboBox_GetCurSel(GetDlgItem(hDlg, IDC_DIR_COMBO)) == 1)
251   {
252      EnableWindow(GetDlgItem(hDlg, IDC_DIR_DELETE), TRUE);
253      EnableWindow(GetDlgItem(hDlg, IDC_DIR_INSERT), TRUE);
254   }
255   else
256   {
257      EnableWindow(GetDlgItem(hDlg, IDC_DIR_DELETE), FALSE);
258      EnableWindow(GetDlgItem(hDlg, IDC_DIR_INSERT), FALSE);
259   }
260}
261
262static BOOL Directories_OnInitDialog(HWND hDlg, HWND hwndFocus, LPARAM lParam)
263{
264   RECT      rectClient;
265   LVCOLUMN   LVCol;
266   int       i;
267   int         nDirInfoCount;
268   LPCSTR      s;
269   TCHAR       *token;
270   TCHAR       buf[MAX_PATH * MAX_DIRS];
271   TCHAR*      t_s = NULL;
272
273   /* count how many dirinfos there are */
274   nDirInfoCount = 0;
275   while(g_directoryInfo[nDirInfoCount].lpName)
276      nDirInfoCount++;
277
278   g_pDirInfo = (tDirInfo *) malloc(sizeof(tDirInfo) * nDirInfoCount);
279   if (!g_pDirInfo) /* bummer */
280      goto error;
281   memset(g_pDirInfo, 0, sizeof(tDirInfo) * nDirInfoCount);
282
283   for (i = nDirInfoCount - 1; i >= 0; i--)
284   {
285      t_s = tstring_from_utf8(g_directoryInfo[i].lpName);
286      if( !t_s )
287         return FALSE;
288      (void)ComboBox_InsertString(GetDlgItem(hDlg, IDC_DIR_COMBO), 0, win_tstring_strdup(t_s));
289      free(t_s);
290      t_s = NULL;
291   }
292
293   (void)ComboBox_SetCurSel(GetDlgItem(hDlg, IDC_DIR_COMBO), 0);
294
295   GetClientRect(GetDlgItem(hDlg, IDC_DIR_LIST), &rectClient);
296
297   memset(&LVCol, 0, sizeof(LVCOLUMN));
298   LVCol.mask     = LVCF_WIDTH;
299   LVCol.cx     = rectClient.right - rectClient.left - GetSystemMetrics(SM_CXHSCROLL);
300   
301   ListView_InsertColumn(GetDlgItem(hDlg, IDC_DIR_LIST), 0, &LVCol);
302
303   /* Keep a temporary copy of the directory strings in g_pDirInfo. */
304   for (i = 0; i < nDirInfoCount; i++)
305   {
306      s = g_directoryInfo[i].pfnGetTheseDirs();
307      t_s = tstring_from_utf8(s);
308      if( !t_s )
309         return FALSE;
310      if (g_directoryInfo[i].bMulti)
311      {
312         /* Copy the string to our own buffer so that we can mutilate it */
313         _tcscpy(buf, t_s);
314
315         g_pDirInfo[i].m_Path = malloc(sizeof(tPath));
316         if (!g_pDirInfo[i].m_Path)
317            goto error;
318
319         g_pDirInfo[i].m_Path->m_NumDirectories = 0;
320         token = _tcstok(buf, TEXT(";"));
321         while ((DirInfo_NumDir(g_pDirInfo, i) < MAX_DIRS) && token)
322         {
323            _tcscpy(DirInfo_Path(g_pDirInfo, i, DirInfo_NumDir(g_pDirInfo, i)), token);
324            DirInfo_NumDir(g_pDirInfo, i)++;
325            token = _tcstok(NULL, TEXT(";"));
326         }
327         DirInfo_SetModified(g_pDirInfo, i, FALSE);
328      }
329      else
330      {
331         DirInfo_SetDir(g_pDirInfo, i, -1, t_s);
332      }
333      free(t_s);
334      t_s = NULL;
335   }
336
337   UpdateDirectoryList(hDlg);
338   return TRUE;
339
340error:
341   if( t_s )
342      free(t_s);
343   Directories_OnDestroy(hDlg);
344   EndDialog(hDlg, -1);
345   return FALSE;
346}
347
348static void Directories_OnDestroy(HWND hDlg)
349{
350   int nDirInfoCount, i;
351
352   if (g_pDirInfo)
353   {
354      /* count how many dirinfos there are */
355      nDirInfoCount = 0;
356      while(g_directoryInfo[nDirInfoCount].lpName)
357         nDirInfoCount++;
358
359      for (i = 0; i < nDirInfoCount; i++)
360      {
361         if (g_pDirInfo[i].m_Path)
362            free(g_pDirInfo[i].m_Path);
363         if (g_pDirInfo[i].m_Directory)
364            free(g_pDirInfo[i].m_Directory);         
365      }
366      free(g_pDirInfo);
367      g_pDirInfo = NULL;
368   }
369}
370
371static void Directories_OnClose(HWND hDlg)
372{
373   EndDialog(hDlg, IDCANCEL);
374}
375
376static int RetrieveDirList(int nDir, int nFlagResult, void (*SetTheseDirs)(const char *s))
377{
378   int i;
379   int nResult = 0;
380   int nPaths;
381   TCHAR buf[MAX_PATH * MAX_DIRS];
382   char* utf8_buf;
383
384   if (DirInfo_Modified(g_pDirInfo, nDir))
385   {
386      memset(buf, 0, sizeof(buf));
387      nPaths = DirInfo_NumDir(g_pDirInfo, nDir);
388      for (i = 0; i < nPaths; i++)
389      {
390         _tcscat(buf, FixSlash(DirInfo_Path(g_pDirInfo, nDir, i)));
391
392         if (i < nPaths - 1)
393            _tcscat(buf, TEXT(";"));
394      }
395      utf8_buf = utf8_from_tstring(buf);
396      SetTheseDirs(utf8_buf);
397      free(utf8_buf);
398
399      nResult |= nFlagResult;
400    }
401   return nResult;
402}
403
404static void Directories_OnOk(HWND hDlg)
405{
406   int i;
407   int nResult = 0;
408   LPTSTR s;
409   char* utf8_s;
410
411   for (i = 0; g_directoryInfo[i].lpName; i++)
412   {
413      if (g_directoryInfo[i].bMulti)
414      {
415         nResult |= RetrieveDirList(i, g_directoryInfo[i].nDirDlgFlags, g_directoryInfo[i].pfnSetTheseDirs);
416      }
417      else
418      {
419         s = FixSlash(DirInfo_Dir(g_pDirInfo, i));
420         utf8_s = utf8_from_tstring(s);
421         g_directoryInfo[i].pfnSetTheseDirs(utf8_s);
422         free(utf8_s);
423      }
424   }
425   EndDialog(hDlg, nResult);
426}
427
428static void Directories_OnCancel(HWND hDlg)
429{
430   EndDialog(hDlg, IDCANCEL);
431}
432
433static void Directories_OnInsert(HWND hDlg)
434{
435   int    nItem;
436   TCHAR   buf[MAX_PATH];
437   HWND   hList;
438
439   hList = GetDlgItem(hDlg, IDC_DIR_LIST);
440   nItem = ListView_GetNextItem(hList, -1, LVNI_SELECTED);
441
442   if (BrowseForDirectory(hDlg, NULL, buf) == TRUE)
443   {
444      int    i;
445      int    nType;
446
447      /* list was empty */
448      if (nItem == -1)
449         nItem = 0;
450
451      nType = ComboBox_GetCurSel(GetDlgItem(hDlg, IDC_DIR_COMBO));
452      if (IsMultiDir(nType))
453      {
454         if (MAX_DIRS <= DirInfo_NumDir(g_pDirInfo, nType))
455            return;
456
457         for (i = DirInfo_NumDir(g_pDirInfo, nType); nItem < i; i--)
458            _tcscpy(DirInfo_Path(g_pDirInfo, nType, i),
459                  DirInfo_Path(g_pDirInfo, nType, i - 1));
460
461         _tcscpy(DirInfo_Path(g_pDirInfo, nType, nItem), buf);
462         DirInfo_NumDir(g_pDirInfo, nType)++;
463         DirInfo_SetModified(g_pDirInfo, nType, TRUE);
464      }
465
466      UpdateDirectoryList(hDlg);
467
468      ListView_SetItemState(hList, nItem, LVIS_FOCUSED | LVIS_SELECTED, LVIS_FOCUSED | LVIS_SELECTED);
469   }
470}
471
472static void Directories_OnBrowse(HWND hDlg)
473{
474   int    nType;
475   int    nItem;
476   TCHAR   inbuf[MAX_PATH];
477   TCHAR   outbuf[MAX_PATH];
478   HWND   hList;
479
480   hList = GetDlgItem(hDlg, IDC_DIR_LIST);
481   nItem = ListView_GetNextItem(hList, -1, LVNI_SELECTED);
482
483   if (nItem == -1)
484      return;
485
486   nType = ComboBox_GetCurSel(GetDlgItem(hDlg, IDC_DIR_COMBO));
487   if (IsMultiDir(nType))
488   {
489      /* Last item is placeholder for append */
490      if (nItem == ListView_GetItemCount(hList) - 1)
491      {
492         Directories_OnInsert(hDlg);
493         return;
494      }
495   }
496
497   ListView_GetItemText(hList, nItem, 0, inbuf, MAX_PATH);
498
499   if (BrowseForDirectory(hDlg, inbuf, outbuf) == TRUE)
500   {
501      nType = ComboBox_GetCurSel(GetDlgItem(hDlg, IDC_DIR_COMBO));
502      DirInfo_SetDir(g_pDirInfo, nType, nItem, outbuf);
503      UpdateDirectoryList(hDlg);
504   }
505}
506
507static void Directories_OnDelete(HWND hDlg)
508{
509   int    nType;
510   int    nCount;
511   int    nSelect;
512   int    i;
513   int    nItem;
514   HWND   hList = GetDlgItem(hDlg, IDC_DIR_LIST);
515
516   nItem = ListView_GetNextItem(hList, -1, LVNI_SELECTED | LVNI_ALL);
517
518   if (nItem == -1)
519      return;
520
521   /* Don't delete "Append" placeholder. */
522   if (nItem == ListView_GetItemCount(hList) - 1)
523      return;
524
525   nType = ComboBox_GetCurSel(GetDlgItem(hDlg, IDC_DIR_COMBO));
526   if (IsMultiDir(nType))
527   {
528      for (i = nItem; i < DirInfo_NumDir(g_pDirInfo, nType) - 1; i++)
529         _tcscpy(DirInfo_Path(g_pDirInfo, nType, i),
530               DirInfo_Path(g_pDirInfo, nType, i + 1));
531
532      _tcscpy(DirInfo_Path(g_pDirInfo, nType, DirInfo_NumDir(g_pDirInfo, nType) - 1), TEXT(""));
533      DirInfo_NumDir(g_pDirInfo, nType)--;
534
535      DirInfo_SetModified(g_pDirInfo, nType, TRUE);
536   }
537
538   UpdateDirectoryList(hDlg);
539   
540
541   nCount = ListView_GetItemCount(hList);
542   if (nCount <= 1)
543      return;
544
545   /* If the last item was removed, select the item above. */
546   if (nItem == nCount - 1)
547      nSelect = nCount - 2;
548   else
549      nSelect = nItem;
550
551   ListView_SetItemState(hList, nSelect, LVIS_FOCUSED | LVIS_SELECTED, LVIS_FOCUSED | LVIS_SELECTED);
552}
553
554static BOOL Directories_OnBeginLabelEdit(HWND hDlg, NMHDR* pNMHDR)
555{
556   int         nType;
557   BOOL        bResult = FALSE;
558   NMLVDISPINFO* pDispInfo = (NMLVDISPINFO*)pNMHDR;
559   LVITEM*      pItem = &pDispInfo->item;
560
561   nType = ComboBox_GetCurSel(GetDlgItem(hDlg, IDC_DIR_COMBO));
562   if (IsMultiDir(nType))
563   {
564      /* Last item is placeholder for append */
565      if (pItem->iItem == ListView_GetItemCount(GetDlgItem(hDlg, IDC_DIR_LIST)) - 1)
566      {
567         HWND hEdit;
568
569         if (MAX_DIRS <= DirInfo_NumDir(g_pDirInfo, nType))
570            return TRUE; /* don't edit */
571
572         hEdit = (HWND)(LRESULT)(int)SendDlgItemMessage(hDlg, IDC_DIR_LIST, LVM_GETEDITCONTROL, 0, 0);
573         Edit_SetText(hEdit, TEXT(""));
574      }
575   }
576
577   return bResult;
578}
579
580static BOOL Directories_OnEndLabelEdit(HWND hDlg, NMHDR* pNMHDR)
581{
582   BOOL        bResult = FALSE;
583   NMLVDISPINFO* pDispInfo = (NMLVDISPINFO*)pNMHDR;
584   LVITEM*      pItem = &pDispInfo->item;
585
586   if (pItem->pszText != NULL)
587   {
588      struct _stat file_stat;
589
590      /* Don't allow empty entries. */
591      if (!_tcscmp(pItem->pszText, TEXT("")))
592      {
593         return FALSE;
594      }
595
596      /* Check validity of edited directory. */
597      if (_tstat(pItem->pszText, &file_stat) == 0
598      &&   (file_stat.st_mode & S_IFDIR))
599      {
600         bResult = TRUE;
601      }
602      else
603      {
604         if (MessageBox(NULL, TEXT("Directory does not exist, continue anyway?"), TEXT(MAME32NAME), MB_OKCANCEL) == IDOK)
605            bResult = TRUE;
606      }
607   }
608
609   if (bResult == TRUE)
610   {
611      int nType;
612      int i;
613
614      nType = ComboBox_GetCurSel(GetDlgItem(hDlg, IDC_DIR_COMBO));
615      if (IsMultiDir(nType))
616      {
617         /* Last item is placeholder for append */
618         if (pItem->iItem == ListView_GetItemCount(GetDlgItem(hDlg, IDC_DIR_LIST)) - 1)
619         {
620            if (MAX_DIRS <= DirInfo_NumDir(g_pDirInfo, nType))
621               return FALSE;
622
623            for (i = DirInfo_NumDir(g_pDirInfo, nType); pItem->iItem < i; i--)
624               _tcscpy(DirInfo_Path(g_pDirInfo, nType, i),
625                     DirInfo_Path(g_pDirInfo, nType, i - 1));
626
627            _tcscpy(DirInfo_Path(g_pDirInfo, nType, pItem->iItem), pItem->pszText);
628
629            DirInfo_SetModified(g_pDirInfo, nType, TRUE);
630            DirInfo_NumDir(g_pDirInfo, nType)++;
631         }
632         else
633            DirInfo_SetDir(g_pDirInfo, nType, pItem->iItem, pItem->pszText);
634      }
635      else
636      {
637         DirInfo_SetDir(g_pDirInfo, nType, pItem->iItem, pItem->pszText);
638      }
639
640      UpdateDirectoryList(hDlg);
641      ListView_SetItemState(GetDlgItem(hDlg, IDC_DIR_LIST), pItem->iItem,
642                       LVIS_FOCUSED | LVIS_SELECTED, LVIS_FOCUSED | LVIS_SELECTED);
643
644   }
645
646   return bResult;
647}
648
649static void Directories_OnCommand(HWND hDlg, int id, HWND hwndCtl, UINT codeNotify)
650{
651   switch (id)
652   {
653   case IDOK:
654      if (codeNotify == BN_CLICKED)
655         Directories_OnOk(hDlg);
656      break;
657
658   case IDCANCEL:
659      if (codeNotify == BN_CLICKED)
660         Directories_OnCancel(hDlg);
661      break;
662
663   case IDC_DIR_BROWSE:
664      if (codeNotify == BN_CLICKED)
665         Directories_OnBrowse(hDlg);
666      break;
667
668   case IDC_DIR_INSERT:
669      if (codeNotify == BN_CLICKED)
670         Directories_OnInsert(hDlg);
671      break;
672
673   case IDC_DIR_DELETE:
674      if (codeNotify == BN_CLICKED)
675         Directories_OnDelete(hDlg);
676      break;
677
678   case IDC_DIR_COMBO:
679      switch (codeNotify)
680      {
681      case CBN_SELCHANGE:
682         Directories_OnSelChange(hDlg);
683         break;
684      }
685      break;
686   }
687}
688
689static BOOL Directories_OnNotify(HWND hDlg, int id, NMHDR* pNMHDR)
690{
691   switch (id)
692   {
693   case IDC_DIR_LIST:
694      switch (pNMHDR->code)
695      {
696      case LVN_ENDLABELEDIT:
697         return Directories_OnEndLabelEdit(hDlg, pNMHDR);
698
699      case LVN_BEGINLABELEDIT:
700         return Directories_OnBeginLabelEdit(hDlg, pNMHDR);
701      }
702   }
703   return FALSE;
704}
705
706/**************************************************************************
707
708   Use the shell to select a Directory.
709
710 **************************************************************************/
711
712static int CALLBACK BrowseCallbackProc(HWND hwnd, UINT uMsg, LPARAM lParam, LPARAM lpData)
713{
714   /*
715      Called just after the dialog is initialized
716      Select the dir passed in BROWSEINFO.lParam
717   */
718   if (uMsg == BFFM_INITIALIZED)
719   {
720      if ((const char*)lpData != NULL)
721         SendMessage(hwnd, BFFM_SETSELECTION, TRUE, lpData);
722   }
723
724   return 0;
725}
726
727BOOL BrowseForDirectory(HWND hwnd, LPCTSTR pStartDir, TCHAR* pResult)
728{
729   BOOL      bResult = FALSE;
730   IMalloc*   piMalloc = 0;
731   BROWSEINFO   Info;
732   ITEMIDLIST* pItemIDList = NULL;
733   TCHAR      buf[MAX_PATH];
734   
735   if (!SUCCEEDED(SHGetMalloc(&piMalloc)))
736      return FALSE;
737
738   Info.hwndOwner      = hwnd;
739   Info.pidlRoot      = NULL;
740   Info.pszDisplayName = buf;
741   Info.lpszTitle      = TEXT("Directory name:");
742   Info.ulFlags      = BIF_RETURNONLYFSDIRS;
743   Info.lpfn         = BrowseCallbackProc;
744   Info.lParam       = (LPARAM)pStartDir;
745
746   pItemIDList = SHBrowseForFolder(&Info);
747
748   if (pItemIDList != NULL)
749   {
750      if (SHGetPathFromIDList(pItemIDList, buf) == TRUE)
751      {
752         _sntprintf(pResult, MAX_PATH, TEXT("%s"), buf);
753         bResult = TRUE;
754      }
755      IMalloc_Free(piMalloc, pItemIDList);
756   }
757   else
758   {
759      bResult = FALSE;
760   }
761
762   IMalloc_Release(piMalloc);
763   return bResult;
764}
765
766/**************************************************************************/
767
src/osd/winui/datamap.h
r0r996
1//============================================================
2//
3//  datamap.c - Win32 dialog and options bridge code
4//
5//============================================================
6
7#ifndef _DATAMAP_H_
8#define _DATAMAP_H_
9
10#include "options.h"
11
12
13//============================================================
14//  TYPE DEFINITIONS
15//============================================================
16
17typedef enum _datamap_entry_type datamap_entry_type;
18enum _datamap_entry_type
19{
20   DM_NONE = 0,
21   DM_BOOL,
22   DM_INT,
23   DM_FLOAT,
24   DM_STRING
25};
26
27
28typedef enum _datamap_callback_type datamap_callback_type;
29enum _datamap_callback_type
30{
31   DCT_READ_CONTROL,
32   DCT_POPULATE_CONTROL,
33   DCT_UPDATE_STATUS,
34
35   DCT_COUNT
36};
37
38
39typedef struct _datamap datamap;
40// MSH - Callback can now return TRUE, signifying that changes have been made, but should NOT be broadcast.
41typedef BOOL (*datamap_callback)(datamap *map, HWND dialog, HWND control, core_options *opts, const char *option_name);
42typedef void (*get_option_name_callback)(datamap *map, HWND dialog, HWND control, char *buffer, size_t buffer_size);
43
44
45//============================================================
46//  PROTOTYPES
47//============================================================
48
49// datamap creation and disposal
50datamap *datamap_create(void);
51void datamap_free(datamap *map);
52
53// datamap setup
54void datamap_add(datamap *map, int dlgitem, datamap_entry_type type, const char *option_name);
55void datamap_set_callback(datamap *map, int dlgitem, datamap_callback_type callback_type, datamap_callback callback);
56void datamap_set_option_name_callback(datamap *map, int dlgitem, get_option_name_callback get_option_name);
57void datamap_set_trackbar_range(datamap *map, int dlgitem, float min, float max, float increments);
58void datamap_set_int_format(datamap *map, int dlgitem, const char *format);
59void datamap_set_float_format(datamap *map, int dlgitem, const char *format);
60
61// datamap operations
62BOOL datamap_read_control(datamap *map, HWND dialog, core_options *opts, int dlgitem);
63void datamap_read_all_controls(datamap *map, HWND dialog, core_options *opts);
64void datamap_populate_control(datamap *map, HWND dialog, core_options *opts, int dlgitem);
65void datamap_populate_all_controls(datamap *map, HWND dialog, core_options *opts);
66void datamap_update_control(datamap *map, HWND dialog, core_options *opts, int dlgitem);
67void datamap_update_all_controls(datamap *map, HWND dialog, core_options *opts);
68
69#endif // _DATAMAP_H_
src/osd/winui/dijoystick.c
r0r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11 ***************************************************************************/
12
13/***************************************************************************
14
15  DIJoystick.c
16
17 ***************************************************************************/
18
19#define WIN32_LEAN_AND_MEAN
20#include <windows.h>
21#include <assert.h>
22#include <stdio.h>
23#include <math.h>
24#include <tchar.h>
25#include "screenshot.h"
26#include "mame32.h"
27#include "directinput.h"
28#include "dijoystick.h"
29#include "m32util.h"
30#include "dxdecode.h"
31
32/***************************************************************************
33    function prototypes
34 ***************************************************************************/
35
36static int  DIJoystick_init(void);
37static void DIJoystick_exit(void);
38static void DIJoystick_poll_joysticks(void);
39static int  DIJoystick_is_joy_pressed(int joycode);
40static BOOL DIJoystick_Available(void);
41
42static BOOL CALLBACK DIJoystick_EnumDeviceProc(LPDIDEVICEINSTANCE pdidi, LPVOID pv);
43
44/***************************************************************************
45    External variables
46 ***************************************************************************/
47
48struct OSDJoystick  DIJoystick =
49{
50   DIJoystick_init,                /* init              */
51   DIJoystick_exit,                /* exit              */
52   DIJoystick_is_joy_pressed,      /* joy_pressed       */
53   DIJoystick_poll_joysticks,      /* poll_joysticks    */
54   DIJoystick_Available,           /* Available         */
55};
56
57/***************************************************************************
58    Internal structures
59 ***************************************************************************/
60
61#define MAX_PHYSICAL_JOYSTICKS 20
62#define MAX_AXES               20
63
64typedef struct
65{
66   GUID guid;
67   TCHAR *name;
68
69   int offset; /* offset in dijoystate */
70} axis_type;
71
72typedef struct
73{
74   BOOL use_joystick;
75
76   GUID guidDevice;
77   TCHAR *name;
78
79   BOOL is_light_gun;
80
81   LPDIRECTINPUTDEVICE2 did;
82
83   DWORD num_axes;
84   axis_type axes[MAX_AXES];
85
86   DWORD num_pov;
87   DWORD num_buttons;
88
89   DIJOYSTATE dijs;
90
91} joystick_type;
92
93struct tDIJoystick_private
94{
95   int   use_count; /* the gui and game can both init/exit us, so keep track */
96   BOOL  m_bCoinSlot;
97
98   DWORD num_joysticks;
99   joystick_type joysticks[MAX_PHYSICAL_JOYSTICKS]; /* actual joystick data! */
100};
101
102/* internal functions needing our declarations */
103static BOOL CALLBACK DIJoystick_EnumAxisObjectsProc(LPCDIDEVICEOBJECTINSTANCE lpddoi, LPVOID pvRef);
104static BOOL CALLBACK DIJoystick_EnumPOVObjectsProc(LPCDIDEVICEOBJECTINSTANCE lpddoi, LPVOID pvRef);
105static BOOL CALLBACK DIJoystick_EnumButtonObjectsProc(LPCDIDEVICEOBJECTINSTANCE lpddoi, LPVOID pvRef);
106static void ClearJoyState(DIJOYSTATE *pdijs);
107
108static void InitJoystick(joystick_type *joystick);
109static void ExitJoystick(joystick_type *joystick);
110
111/***************************************************************************
112    Internal variables
113 ***************************************************************************/
114
115static struct tDIJoystick_private   This;
116
117static const GUID guidNULL = {0, 0, 0, {0, 0, 0, 0, 0, 0, 0, 0}};
118
119/***************************************************************************
120    External OSD functions 
121 ***************************************************************************/
122/*
123    put here anything you need to do when the program is started. Return 0 if
124    initialization was successful, nonzero otherwise.
125*/
126static int DIJoystick_init(void)
127{
128   DWORD i;
129   HRESULT hr;
130   LPDIRECTINPUT di = GetDirectInput();
131
132   This.use_count++;
133
134   This.num_joysticks = 0;
135
136   if (di == NULL)
137   {
138      ErrorMsg("DirectInput not initialized");
139      return 0;
140   }
141
142   /* enumerate for joystick devices */
143   hr = IDirectInput_EnumDevices(di, DIDEVTYPE_JOYSTICK,
144             (LPDIENUMDEVICESCALLBACK)DIJoystick_EnumDeviceProc,
145             NULL,
146             DIEDFL_ATTACHEDONLY  );
147   if (FAILED(hr))
148   {
149      ErrorMsg("DirectInput EnumDevices() failed: %s", DirectXDecodeError(hr));
150      return 0;
151   }
152
153   /* create each joystick device, enumerate each joystick for axes, etc */
154   for (i = 0; i < This.num_joysticks; i++)
155   {
156      InitJoystick(&This.joysticks[i]);
157   }
158
159   /* Are there any joysticks attached? */
160   if (This.num_joysticks < 1)
161   {
162      /*ErrorMsg("DirectInput EnumDevices didn't find any joysticks");*/
163      return 0;
164   }
165   
166   return 0;
167}
168
169/*
170   put here cleanup routines to be executed when the program is terminated.
171*/
172static void DIJoystick_exit(void)
173{
174   DWORD i;
175
176   This.use_count--;
177
178   if (This.use_count > 0)
179      return;
180
181   for (i = 0; i < This.num_joysticks; i++)
182      ExitJoystick(&This.joysticks[i]);
183   
184   This.num_joysticks = 0;
185}
186
187static void DIJoystick_poll_joysticks(void)
188{
189   HRESULT hr;
190   DWORD   i;
191   
192   This.m_bCoinSlot = 0;
193
194   for (i = 0; i < This.num_joysticks; i++)
195   {
196      /* start by clearing the structure, then fill it in if possible */
197
198      ClearJoyState(&This.joysticks[i].dijs);
199
200      if (This.joysticks[i].did == NULL)
201         continue;
202
203      if (This.joysticks[i].use_joystick == FALSE)
204         continue;
205
206      hr = IDirectInputDevice2_Poll(This.joysticks[i].did);
207
208      hr = IDirectInputDevice2_GetDeviceState(This.joysticks[i].did,sizeof(DIJOYSTATE),
209                                    &This.joysticks[i].dijs);
210      if (FAILED(hr))
211      {
212         if (hr == DIERR_INPUTLOST || hr == DIERR_NOTACQUIRED)
213         {
214            hr = IDirectInputDevice2_Acquire(This.joysticks[i].did);
215         }
216         continue;
217      }
218   }
219}
220
221/*
222   check if the DIJoystick is moved in the specified direction, defined in
223   osdepend.h. Return 0 if it is not pressed, nonzero otherwise.
224*/
225
226static int DIJoystick_is_joy_pressed(int joycode)
227{
228   int joy_num;
229   int stick;
230   int axis;
231   int dir;
232
233   DIJOYSTATE dijs;
234
235   int value;
236   int dz = 60;
237
238   joy_num = GET_JOYCODE_JOY(joycode);
239
240   /* do we have as many sticks? */
241   if (joy_num == 0 || This.num_joysticks < joy_num)
242      return 0;
243   joy_num--;
244   
245   if (This.joysticks[joy_num].use_joystick == FALSE)
246      return 0;
247
248   dijs = This.joysticks[joy_num].dijs;
249
250   stick = GET_JOYCODE_STICK(joycode);
251
252   if (stick == JOYCODE_STICK_BTN)
253   {
254      /* buttons */
255      int button;
256
257      button = GET_JOYCODE_BUTTON(joycode);
258      button--;
259
260      if (button >= This.joysticks[joy_num].num_buttons
261      ||   GET_JOYCODE_DIR(joycode) != JOYCODE_DIR_BTN)
262         return 0;
263
264      return dijs.rgbButtons[button] != 0;
265   }
266
267   if (stick == JOYCODE_STICK_POV)
268   {
269      /* POV */
270      int pov_value;
271      int angle;
272      int axis_value;
273
274      int num_pov = GET_JOYCODE_BUTTON(joycode) / 4;
275      int code   = GET_JOYCODE_BUTTON(joycode) % 4;
276      axis = code / 2;
277      dir  = code % 2;
278
279      if (num_pov >= This.joysticks[joy_num].num_pov)
280         return 0;
281
282      pov_value = dijs.rgdwPOV[num_pov];
283      if (LOWORD(pov_value) == 0xffff)
284         return 0;
285
286      angle = (pov_value + 27000) % 36000;
287      angle = (36000 - angle) % 36000;
288      angle /= 100;
289
290      /* angle is now in degrees counterclockwise from x axis*/
291      if (axis == 1)
292         axis_value = 128 + (int)(127 * cos(2 * M_PI * angle / 360.0)); /* x */
293      else
294         axis_value = 128 + (int)(127 * sin(2 * M_PI * angle / 360.0)); /* y */
295
296      if (dir == 1)
297         return axis_value <= (128 - 128 * dz / 100);
298      else
299         return axis_value >= (128 + 128 * dz / 100);
300   }
301
302   /* sticks */
303   
304   axis = GET_JOYCODE_AXIS(joycode);
305   dir  = GET_JOYCODE_DIR(joycode);
306   
307   if (axis == 0 || This.joysticks[joy_num].num_axes < axis)
308      return 0;
309   axis--;
310
311   value = *(int *)(((byte *)&dijs) + This.joysticks[joy_num].axes[axis].offset);
312
313   if (dir == JOYCODE_DIR_NEG)
314      return value <= (128 - 128 * dz / 100);
315   else
316      return value >= (128 + 128 * dz / 100);
317}
318
319static BOOL DIJoystick_Available(void)
320{
321   static BOOL bBeenHere = FALSE;
322   static BOOL bAvailable = FALSE;
323   HRESULT    hr;
324   GUID      guidDevice = guidNULL;
325   LPDIRECTINPUTDEVICE didTemp;
326   LPDIRECTINPUTDEVICE didJoystick;
327   LPDIRECTINPUT di = GetDirectInput();
328
329   if (di == NULL)
330   {
331      return FALSE;
332   }
333
334   if (bBeenHere == FALSE)
335      bBeenHere = TRUE;
336   else
337      return bAvailable;
338
339   /* enumerate for joystick devices */
340   hr = IDirectInput_EnumDevices(di, DIDEVTYPE_JOYSTICK,
341                          inputEnumDeviceProc,
342                          &guidDevice,
343                          DIEDFL_ATTACHEDONLY);
344   if (FAILED(hr))
345   {
346      return FALSE;
347   }
348
349   /* Are there any joysticks attached? */
350   if (IsEqualGUID(&guidDevice, &guidNULL))
351   {
352      return FALSE;
353   }
354
355   hr = IDirectInput_CreateDevice(di, &guidDevice, &didTemp, NULL);
356   if (FAILED(hr))
357   {
358      return FALSE;
359   }
360
361   /* Determine if DX5 is available by a QI for a DX5 interface. */
362   hr = IDirectInputDevice_QueryInterface(didTemp,
363                                 &IID_IDirectInputDevice2,
364                                 (void**)&didJoystick);
365   if (FAILED(hr))
366   {
367      bAvailable = FALSE;
368   }
369   else
370   {
371      bAvailable = TRUE;
372      IDirectInputDevice_Release(didJoystick);
373   }
374
375   /* dispose of the temp interface */
376   IDirectInputDevice_Release(didTemp);
377
378   return bAvailable;
379}
380
381int DIJoystick_GetNumPhysicalJoysticks()
382{
383   return This.num_joysticks;
384}
385
386TCHAR* DIJoystick_GetPhysicalJoystickName(int num_joystick)
387{
388   return This.joysticks[num_joystick].name;
389}
390
391int DIJoystick_GetNumPhysicalJoystickAxes(int num_joystick)
392{
393   return This.joysticks[num_joystick].num_axes;
394}
395
396TCHAR* DIJoystick_GetPhysicalJoystickAxisName(int num_joystick, int num_axis)
397{
398   return This.joysticks[num_joystick].axes[num_axis].name;
399}
400
401/***************************************************************************
402   Internal functions
403 ***************************************************************************/
404
405BOOL CALLBACK DIJoystick_EnumDeviceProc(LPDIDEVICEINSTANCE pdidi, LPVOID pv)
406{
407   TCHAR buffer[5000];
408
409   This.joysticks[This.num_joysticks].guidDevice = pdidi->guidInstance;
410
411   _stprintf(buffer, TEXT("%s (%s)"), pdidi->tszProductName, pdidi->tszInstanceName);
412   This.joysticks[This.num_joysticks].name = (TCHAR *)malloc((_tcslen(buffer) + 1) * sizeof(TCHAR));
413   _tcscpy(This.joysticks[This.num_joysticks].name, buffer);
414
415   This.num_joysticks++;
416
417   return DIENUM_CONTINUE;
418   }
419
420static BOOL CALLBACK DIJoystick_EnumAxisObjectsProc(LPCDIDEVICEOBJECTINSTANCE lpddoi,
421                                       LPVOID pvRef)
422{
423   joystick_type* joystick = (joystick_type*)pvRef;
424   DIPROPRANGE diprg;
425   HRESULT hr;
426
427   joystick->axes[joystick->num_axes].guid = lpddoi->guidType;
428
429   joystick->axes[joystick->num_axes].name = (TCHAR *)malloc((_tcslen(lpddoi->tszName) + 1) * sizeof(TCHAR));
430   _tcscpy(joystick->axes[joystick->num_axes].name, lpddoi->tszName);
431
432   joystick->axes[joystick->num_axes].offset = lpddoi->dwOfs;
433
434   /*ErrorMsg("got axis %s, offset %i",lpddoi->tszName, lpddoi->dwOfs);*/
435
436   diprg.diph.dwSize      = sizeof(diprg);
437   diprg.diph.dwHeaderSize = sizeof(diprg.diph);
438   diprg.diph.dwObj      = lpddoi->dwOfs;
439   diprg.diph.dwHow      = DIPH_BYOFFSET;
440   diprg.lMin            = 0;
441   diprg.lMax            = 255;
442
443   hr = IDirectInputDevice2_SetProperty(joystick->did, DIPROP_RANGE, &diprg.diph);
444   if (FAILED(hr)) /* if this fails, don't use this axis */
445   {
446      free(joystick->axes[joystick->num_axes].name);
447      joystick->axes[joystick->num_axes].name = NULL;
448      return DIENUM_CONTINUE;
449   }
450
451#ifdef JOY_DEBUG
452   if (FAILED(hr))
453   {
454      ErrorMsg("DirectInput SetProperty() joystick axis %s failed - %s\n",
455             joystick->axes[joystick->num_axes].name,
456             DirectXDecodeError(hr));
457   }
458#endif
459   
460   /* Set axis dead zone to 0; we need accurate #'s for analog joystick reading. */
461
462   hr = SetDIDwordProperty(joystick->did, DIPROP_DEADZONE, lpddoi->dwOfs, DIPH_BYOFFSET, 0);
463
464#ifdef JOY_DEBUG
465   if (FAILED(hr))
466   {
467      ErrorMsg("DirectInput SetProperty() joystick axis %s dead zone failed - %s\n",
468             joystick->axes[joystick->num_axes].name,
469             DirectXDecodeError(hr));
470   }
471#endif
472
473   joystick->num_axes++;
474
475   return DIENUM_CONTINUE;
476}
477
478static BOOL CALLBACK DIJoystick_EnumPOVObjectsProc(LPCDIDEVICEOBJECTINSTANCE lpddoi, LPVOID pvRef)
479{
480   joystick_type* joystick = (joystick_type*)pvRef;
481   joystick->num_pov++;
482
483   return DIENUM_CONTINUE;
484}
485
486static BOOL CALLBACK DIJoystick_EnumButtonObjectsProc(LPCDIDEVICEOBJECTINSTANCE lpddoi, LPVOID pvRef)
487{
488   joystick_type* joystick = (joystick_type*)pvRef;
489   joystick->num_buttons++;
490
491   return DIENUM_CONTINUE;
492}
493
494static void ClearJoyState(DIJOYSTATE *pdijs)
495{
496   memset(pdijs, 0, sizeof(DIJOYSTATE));
497   pdijs->lX         = 128;
498   pdijs->lY         = 128;
499   pdijs->lZ         = 128;
500   pdijs->lRx         = 128;
501   pdijs->lRy         = 128;
502   pdijs->lRz         = 128;
503   pdijs->rglSlider[0] = 128;
504   pdijs->rglSlider[1] = 128;
505   pdijs->rgdwPOV[0]   = -1;
506   pdijs->rgdwPOV[1]   = -1;
507   pdijs->rgdwPOV[2]   = -1;
508   pdijs->rgdwPOV[3]   = -1;
509}
510
511static void InitJoystick(joystick_type *joystick)
512{
513   LPDIRECTINPUTDEVICE didTemp;
514   HRESULT hr;
515   LPDIRECTINPUT di = GetDirectInput();
516
517   joystick->use_joystick = FALSE;
518
519   joystick->did      = NULL;
520   joystick->num_axes = 0;
521
522   joystick->is_light_gun = (_tcscmp(joystick->name, TEXT("ACT LABS GS (ACT LABS GS)")) == 0);
523
524   /* get a did1 interface first... */
525   hr = IDirectInput_CreateDevice(di, &joystick->guidDevice, &didTemp, NULL);
526   if (FAILED(hr))
527   {
528      ErrorMsg("DirectInput CreateDevice() joystick failed: %s\n", DirectXDecodeError(hr));
529      return;
530   }
531   
532   /* get a did2 interface to work with polling (most) joysticks */
533   hr = IDirectInputDevice_QueryInterface(didTemp,
534                                 &IID_IDirectInputDevice2,
535                                 (void**)&joystick->did);
536
537   /* dispose of the temp interface */
538   IDirectInputDevice_Release(didTemp);
539
540   /* check result of getting the did2 */
541   if (FAILED(hr))
542   {
543      /* no error message because this happens in dx3 */
544      /* ErrorMsg("DirectInput QueryInterface joystick failed\n"); */
545      joystick->did = NULL;
546      return;
547   }
548
549   
550   hr = IDirectInputDevice2_SetCooperativeLevel(joystick->did, GetMainWindow(),
551                                     DISCL_NONEXCLUSIVE | DISCL_BACKGROUND);
552   if (FAILED(hr))
553   {
554      ErrorMsg("DirectInput SetCooperativeLevel() joystick failed: %s\n", DirectXDecodeError(hr));
555      return;
556   }
557
558
559   hr = IDirectInputDevice2_SetDataFormat(joystick->did, &c_dfDIJoystick);
560   if (FAILED(hr))
561   {
562      ErrorMsg("DirectInput SetDataFormat() joystick failed: %s\n", DirectXDecodeError(hr));
563      return;
564   }
565
566   if (joystick->is_light_gun)
567   {
568      /* setup light gun to report raw screen pixel data */
569
570      DIPROPDWORD diprop;
571      memset(&diprop, 0, sizeof(diprop));
572      diprop.diph.dwSize       = sizeof(DIPROPDWORD);
573      diprop.diph.dwHeaderSize = sizeof(DIPROPHEADER);
574      diprop.diph.dwObj       = 0;
575      diprop.diph.dwHow       = DIPH_DEVICE;
576      diprop.dwData          = DIPROPCALIBRATIONMODE_RAW;
577
578      IDirectInputDevice2_SetProperty(joystick->did, DIPROP_CALIBRATIONMODE, &diprop.diph);
579   }
580   else
581   {
582      /* enumerate our axes */
583      hr = IDirectInputDevice_EnumObjects(joystick->did,
584                                 DIJoystick_EnumAxisObjectsProc,
585                                 joystick,
586                                 DIDFT_AXIS);
587      if (FAILED(hr))
588      {
589         ErrorMsg("DirectInput EnumObjects() Axes failed: %s\n", DirectXDecodeError(hr));
590         return;
591      }
592
593      /* enumerate our POV hats */
594      joystick->num_pov = 0;
595      hr = IDirectInputDevice_EnumObjects(joystick->did,
596                                 DIJoystick_EnumPOVObjectsProc,
597                                 joystick,
598                                 DIDFT_POV);
599      if (FAILED(hr))
600      {
601         ErrorMsg("DirectInput EnumObjects() POVs failed: %s\n", DirectXDecodeError(hr));
602         return;
603      }
604   }
605
606   /* enumerate our buttons */
607
608   joystick->num_buttons = 0;
609   hr = IDirectInputDevice_EnumObjects(joystick->did,
610                              DIJoystick_EnumButtonObjectsProc,
611                              joystick,
612                              DIDFT_BUTTON);
613   if (FAILED(hr))
614   {
615      ErrorMsg("DirectInput EnumObjects() Buttons failed: %s\n", DirectXDecodeError(hr));
616      return;
617   }
618
619   hr = IDirectInputDevice2_Acquire(joystick->did);
620   if (FAILED(hr))
621   {
622      ErrorMsg("DirectInputDevice Acquire joystick failed!\n");
623      return;
624   }
625
626   /* start by clearing the structures */
627
628   ClearJoyState(&joystick->dijs);
629
630   joystick->use_joystick = TRUE;
631}
632
633static void ExitJoystick(joystick_type *joystick)
634{
635   DWORD i;
636   
637   if (joystick->did != NULL)
638   {
639      IDirectInputDevice_Unacquire(joystick->did);
640      IDirectInputDevice_Release(joystick->did);
641      joystick->did = NULL;
642   }
643   
644   for (i = 0; i < joystick->num_axes; i++)
645   {
646      if (joystick->axes[i].name)
647         free(joystick->axes[i].name);
648      joystick->axes[i].name = NULL;
649   }
650   
651   if (joystick->name != NULL)
652   {
653      free(joystick->name);
654      joystick->name = NULL;
655   }
656}
657
src/osd/winui/picker.c
r0r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11 ***************************************************************************/
12
13#define WIN32_LEAN_AND_MEAN
14#define _WIN32_IE 0x0500
15#include <windows.h>
16#include <windowsx.h>
17#include <shellapi.h>
18#include <stdio.h>
19#include <ctype.h>
20#include <commctrl.h>
21#include <commdlg.h>
22#include <string.h>
23#include <sys/stat.h>
24#include <wingdi.h>
25#include <time.h>
26#include <tchar.h>
27
28#include "picker.h"
29#include "resource.h"
30#include "screenshot.h"
31#include "win32ui.h"
32#include "bitmask.h"
33#include "m32util.h"
34#include "m32opts.h"
35
36
37// fix warning: cast does not match function type
38#if defined(__GNUC__) && defined(ListView_GetHeader)
39#undef ListView_GetHeader
40#endif
41#if defined(__GNUC__) && defined(ListView_GetImageList)
42#undef ListView_GetImageList
43#undef ListView_GetItemRect
44#endif
45
46#ifndef ListView_GetItemRect
47#define ListView_GetItemRect(w,i,p,c) \
48   (BOOL)SNDMSG((w),LVM_GETITEMRECT,i,((p != NULL)?(((LPRECT)(p))->left=(c),(LPARAM)(LPRECT)(p)):0))
49#endif
50
51#ifndef ListView_GetImageList
52#define ListView_GetImageList(w,i) (HIMAGELIST)(LRESULT)(int)SendMessage((w),LVM_GETIMAGELIST,(i),0)
53#endif // ListView_GetImageList
54
55#ifndef ListView_GetHeader
56#define ListView_GetHeader(w) (HWND)(LRESULT)(int)SNDMSG((w),LVM_GETHEADER,0,0)
57#endif // ListView_GetHeader
58
59#ifndef HDM_SETIMAGELIST
60#define HDM_SETIMAGELIST        (HDM_FIRST + 8)
61#endif // HDM_SETIMAGELIST
62
63#ifndef Header_SetImageList
64#define Header_SetImageList(h,i) (HIMAGELIST)(LRESULT)(int)SNDMSG((h), HDM_SETIMAGELIST, 0, (LPARAM)i)
65#endif // Header_SetImageList
66
67#ifndef HDF_SORTUP
68#define HDF_SORTUP 0x400
69#endif
70
71#ifndef HDF_SORTDOWN
72#define HDF_SORTDOWN 0x200
73#endif
74
75
76
77struct PickerInfo
78{
79   const struct PickerCallbacks *pCallbacks;
80   WNDPROC pfnParentWndProc;
81   int nCurrentViewID;
82   int nLastItem;
83   int nColumnCount;
84   int *pnColumnsShown;
85   int *pnColumnsOrder;
86   UINT_PTR nTimer;
87   LPCTSTR *ppszColumnNames;
88};
89
90
91static struct PickerInfo *GetPickerInfo(HWND hWnd)
92{
93   LONG_PTR l;
94   l = GetWindowLongPtr(hWnd, GWLP_USERDATA);
95   return (struct PickerInfo *) l;
96}
97
98
99
100static LRESULT CallParentWndProc(WNDPROC pfnParentWndProc,
101   HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
102{
103   LRESULT rc;
104
105   if (!pfnParentWndProc)
106      pfnParentWndProc = GetPickerInfo(hWnd)->pfnParentWndProc;
107
108   if (IsWindowUnicode(hWnd))
109      rc = CallWindowProcW(pfnParentWndProc, hWnd, message, wParam, lParam);
110   else
111      rc = CallWindowProcA(pfnParentWndProc, hWnd, message, wParam, lParam);
112   return rc;
113}
114
115static BOOL ListViewOnErase(HWND hWnd, HDC hDC)
116{
117   RECT      rcClient;
118   HRGN      rgnBitmap;
119   HPALETTE   hPAL;
120
121   int       i, j;
122   HDC       htempDC;
123   POINT      ptOrigin;
124   POINT      pt = {0,0};
125   HBITMAP    hOldBitmap;
126   MYBITMAPINFO *pbmDesc = GetBackgroundInfo();
127   HBITMAP      hBackground = GetBackgroundBitmap();
128   HPALETTE   hPALbg = GetBackgroundPalette();
129
130   // this does not draw the background properly in report view
131
132   GetClientRect(hWnd, &rcClient);
133
134   htempDC = CreateCompatibleDC(hDC);
135   hOldBitmap = SelectObject(htempDC, hBackground);
136
137   rgnBitmap = CreateRectRgnIndirect(&rcClient);
138   SelectClipRgn(hDC, rgnBitmap);
139   DeleteObject(rgnBitmap);
140
141   hPAL = (!hPALbg) ? CreateHalftonePalette(hDC) : hPALbg;
142
143   if (GetDeviceCaps(htempDC, RASTERCAPS) & RC_PALETTE && hPAL != NULL)
144   {
145      SelectPalette(htempDC, hPAL, FALSE);
146      RealizePalette(htempDC);
147   }
148
149   // Get x and y offset
150   MapWindowPoints(hWnd, GetTreeView(), &pt, 1);
151   GetDCOrgEx(hDC, &ptOrigin);
152   ptOrigin.x -= pt.x;
153   ptOrigin.y -= pt.y;
154   ptOrigin.x = -GetScrollPos(hWnd, SB_HORZ);
155   ptOrigin.y = -GetScrollPos(hWnd, SB_VERT);
156
157   if (pbmDesc->bmWidth && pbmDesc->bmHeight)
158   {
159      for (i = ptOrigin.x; i < rcClient.right; i += pbmDesc->bmWidth)
160         for (j = ptOrigin.y; j < rcClient.bottom; j += pbmDesc->bmHeight)
161            BitBlt(hDC, i, j, pbmDesc->bmWidth, pbmDesc->bmHeight, htempDC, 0, 0, SRCCOPY);
162   }
163
164   SelectObject(htempDC, hOldBitmap);
165   DeleteDC(htempDC);
166
167   if (!pbmDesc->bmColors)
168   {
169      DeleteObject(hPAL);
170      hPAL = 0;
171   }
172
173   return TRUE;
174}
175
176
177
178static BOOL ListViewNotify(HWND hWnd, LPNMHDR lpNmHdr)
179{
180   RECT rcClient;
181   DWORD dwPos;
182   POINT pt;
183
184   // This code is for using bitmap in the background
185   // Invalidate the right side of the control when a column is resized         
186   if (lpNmHdr->code == HDN_ITEMCHANGINGA || lpNmHdr->code == HDN_ITEMCHANGINGW)
187   {
188      dwPos = GetMessagePos();
189      pt.x = LOWORD(dwPos);
190      pt.y = HIWORD(dwPos);
191
192      GetClientRect(hWnd, &rcClient);
193      ScreenToClient(hWnd, &pt);
194      rcClient.left = pt.x;
195      InvalidateRect(hWnd, &rcClient, FALSE);
196   }
197   return FALSE;
198}
199
200
201
202static BOOL ListViewContextMenu(HWND hwndPicker, LPARAM lParam)
203{
204   struct PickerInfo *pPickerInfo;
205   POINT pt, headerPt;
206   int i, nViewID, nColumn = -1;
207   HWND hwndHeader;
208   RECT rcCol;
209
210   pPickerInfo = GetPickerInfo(hwndPicker);
211
212   // Extract the point out of the lparam
213   pt.x = GET_X_LPARAM(lParam);
214   pt.y = GET_Y_LPARAM(lParam);
215   if (pt.x < 0 && pt.y < 0)
216      GetCursorPos(&pt);
217
218   // Figure out which header column was clicked, if at all
219   nViewID = Picker_GetViewID(hwndPicker);
220   if ((nViewID == VIEW_REPORT) || (nViewID == VIEW_GROUPED))
221   {
222      hwndHeader = ListView_GetHeader(hwndPicker);
223      headerPt = pt;
224      ScreenToClient(hwndHeader, &headerPt);
225
226      for (i = 0; Header_GetItemRect(hwndHeader, i, &rcCol); i++)
227      {
228         if (PtInRect(&rcCol, headerPt))
229         {
230            nColumn = i;
231            break;
232         }
233      }
234   }
235
236   if (nColumn >= 0)
237   {
238      // A column header was clicked
239      if (pPickerInfo->pCallbacks->pfnOnHeaderContextMenu)
240         pPickerInfo->pCallbacks->pfnOnHeaderContextMenu(pt, nColumn);
241   }
242   else
243   {
244      // The body was clicked
245      if (pPickerInfo->pCallbacks->pfnOnBodyContextMenu)
246         pPickerInfo->pCallbacks->pfnOnBodyContextMenu(pt);
247   }
248   return TRUE;
249}
250
251
252
253static void Picker_Free(struct PickerInfo *pPickerInfo)
254{
255   // Free up all resources associated with this picker structure
256   if (pPickerInfo->pnColumnsShown)
257      free(pPickerInfo->pnColumnsShown);
258   if (pPickerInfo->pnColumnsOrder)
259      free(pPickerInfo->pnColumnsOrder);
260   free(pPickerInfo);
261}
262
263
264
265static LRESULT CALLBACK ListViewWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
266{
267   struct PickerInfo *pPickerInfo;
268   LRESULT rc = 0;
269   BOOL bHandled = FALSE;
270   WNDPROC pfnParentWndProc;
271   HWND hwndHeaderCtrl  = NULL;
272   HFONT hHeaderCtrlFont = NULL;
273
274   pPickerInfo = GetPickerInfo(hWnd);
275   pfnParentWndProc = pPickerInfo->pfnParentWndProc;
276
277   switch(message)
278   {
279       case WM_MOUSEMOVE:
280         if (MouseHasBeenMoved())
281            ShowCursor(TRUE);
282         break;
283
284      case WM_ERASEBKGND:
285         if (GetBackgroundBitmap())
286         {
287            rc = ListViewOnErase(hWnd, (HDC) wParam);
288            bHandled = TRUE;
289         }
290         break;
291
292      case WM_NOTIFY:
293         bHandled = ListViewNotify(hWnd, (LPNMHDR) lParam);
294         break;
295
296      case WM_SETFONT:
297         hwndHeaderCtrl = ListView_GetHeader(hWnd);
298         if (hwndHeaderCtrl)
299            hHeaderCtrlFont = GetWindowFont(hwndHeaderCtrl);
300         break;
301
302      case WM_CONTEXTMENU:
303         bHandled = ListViewContextMenu(hWnd, lParam);
304         break;
305
306      case WM_DESTROY:
307         // Received WM_DESTROY; time to clean up
308         if (pPickerInfo->pCallbacks->pfnSetViewMode)
309            pPickerInfo->pCallbacks->pfnSetViewMode(pPickerInfo->nCurrentViewID);
310         Picker_Free(pPickerInfo);
311         SetWindowLongPtr(hWnd, GWLP_WNDPROC, (LONG_PTR) pfnParentWndProc);
312         SetWindowLongPtr(hWnd, GWLP_USERDATA, (LONG_PTR) NULL);
313         break;
314   }
315
316   if (!bHandled)
317      rc = CallParentWndProc(pfnParentWndProc, hWnd, message, wParam, lParam);
318
319    // If we received WM_SETFONT, reset header ctrl font back to original font
320   if (hwndHeaderCtrl)
321      SetWindowFont(hwndHeaderCtrl, hHeaderCtrlFont, TRUE);
322
323   return rc;
324}
325
326
327
328// Re/initialize the ListControl Columns
329static void Picker_InternalResetColumnDisplay(HWND hWnd, BOOL bFirstTime)
330{
331   LV_COLUMN   lvc;
332   int         i;
333   int         nColumn;
334   int         *widths;
335   int         *order;
336   int         *shown;
337   int shown_columns;
338   LVCOLUMN col;
339   struct PickerInfo *pPickerInfo;
340
341   pPickerInfo = GetPickerInfo(hWnd);
342
343   widths = malloc(pPickerInfo->nColumnCount * sizeof(*widths));
344   order = malloc(pPickerInfo->nColumnCount * sizeof(*order));
345   shown = malloc(pPickerInfo->nColumnCount * sizeof(*shown));
346   if (!widths || !order || !shown)
347      goto done;
348
349   memset(widths, 0, pPickerInfo->nColumnCount * sizeof(*widths));
350   memset(order, 0, pPickerInfo->nColumnCount * sizeof(*order));
351   memset(shown, 0, pPickerInfo->nColumnCount * sizeof(*shown));
352   pPickerInfo->pCallbacks->pfnGetColumnWidths(widths);
353   pPickerInfo->pCallbacks->pfnGetColumnOrder(order);
354   pPickerInfo->pCallbacks->pfnGetColumnShown(shown);
355
356   if (!bFirstTime)
357   {
358      DWORD style = GetWindowLong(hWnd, GWL_STYLE);
359
360      // switch the list view to LVS_REPORT style so column widths reported correctly
361      SetWindowLong(hWnd, GWL_STYLE,
362                 (GetWindowLong(hWnd, GWL_STYLE) & ~LVS_TYPEMASK) | LVS_REPORT);
363
364      // Retrieve each of the column widths
365      i = 0;
366      memset(&col, 0, sizeof(col));
367      col.mask = LVCF_WIDTH;
368      while(ListView_GetColumn(hWnd, 0, &col))
369      {
370         nColumn = Picker_GetRealColumnFromViewColumn(hWnd, i++);
371         widths[nColumn] = col.cx;
372         ListView_DeleteColumn(hWnd, 0);
373      }
374
375      pPickerInfo->pCallbacks->pfnSetColumnWidths(widths);
376
377      // restore old style
378      SetWindowLong(hWnd, GWL_STYLE, style);
379   }
380
381   nColumn = 0;
382   for (i = 0; i < pPickerInfo->nColumnCount; i++)
383   {
384      if (shown[order[i]])
385      {
386         lvc.mask = LVCF_FMT | LVCF_WIDTH | LVCF_SUBITEM | LVCF_TEXT;
387         lvc.pszText = (LPTSTR) pPickerInfo->ppszColumnNames[order[i]];
388         lvc.iSubItem = nColumn;
389         lvc.cx = widths[order[i]];
390         lvc.fmt = LVCFMT_LEFT;
391         ListView_InsertColumn(hWnd, nColumn, &lvc);
392         pPickerInfo->pnColumnsOrder[nColumn] = order[i];
393
394         dprintf("Visible column %d: Logical column %d; Width=%d\n", nColumn, order[i], widths[order[i]]);
395
396         nColumn++;
397      }
398   }
399
400   shown_columns = nColumn;
401
402   /* Fill this in so we can still sort on columns NOT shown */
403   for (i = 0; i < pPickerInfo->nColumnCount && nColumn < pPickerInfo->nColumnCount; i++)
404   {
405      if (!shown[order[i]])
406      {
407         pPickerInfo->pnColumnsOrder[nColumn] = order[i];
408         nColumn++;
409      }
410   }
411
412   if (GetListFontColor() == RGB(255, 255, 255))
413      ListView_SetTextColor(hWnd, RGB(240, 240, 240));
414   else
415      ListView_SetTextColor(hWnd, GetListFontColor());
416
417done:     
418   if (widths)
419      free(widths);
420   if (order)
421      free(order);
422   if (shown)
423      free(shown);
424}
425
426
427
428void Picker_ResetColumnDisplay(HWND hWnd)
429{
430   Picker_InternalResetColumnDisplay(hWnd, FALSE);
431}
432
433
434
435void Picker_ClearIdle(HWND hwndPicker)
436{
437   struct PickerInfo *pPickerInfo;
438
439   pPickerInfo = GetPickerInfo(hwndPicker);
440   if (pPickerInfo->nTimer)
441   {
442      KillTimer(hwndPicker, 0);
443      pPickerInfo->nTimer = 0;
444   }
445}
446
447
448
449static void CALLBACK Picker_TimerProc(HWND hwndPicker, UINT uMsg,
450  UINT_PTR idEvent, DWORD dwTime)
451{
452   struct PickerInfo *pPickerInfo;
453   BOOL bContinueIdle;
454   DWORD nTickCount, nBaseTickCount;
455   DWORD nMaxIdleTicks = 50;
456
457   pPickerInfo = GetPickerInfo(hwndPicker);
458   bContinueIdle = FALSE;
459   nBaseTickCount = GetTickCount();
460
461   // This idle procedure will loop until either idling is over, or until
462   // a specified amount of time elapses (in this case, 50ms).  This frees
463   // idle callbacks of any responsibility for balancing their workloads; the
464   // picker code will
465   do
466   {
467      if (pPickerInfo->pCallbacks->pfnOnIdle)
468         bContinueIdle = pPickerInfo->pCallbacks->pfnOnIdle(hwndPicker);
469      nTickCount = GetTickCount();
470   }
471   while(bContinueIdle && ((nTickCount - nBaseTickCount) < nMaxIdleTicks));
472
473   if (!bContinueIdle)
474      Picker_ClearIdle(hwndPicker);
475}
476
477
478
479// Instructs this picker to reset idling; idling will continue until the
480// idle function returns FALSE
481void Picker_ResetIdle(HWND hwndPicker)
482{
483   struct PickerInfo *pPickerInfo;
484
485   pPickerInfo = GetPickerInfo(hwndPicker);
486
487   Picker_ClearIdle(hwndPicker);
488   if (pPickerInfo->pCallbacks->pfnOnIdle)
489      pPickerInfo->nTimer = SetTimer(hwndPicker, 0, 0, Picker_TimerProc);
490}
491
492
493
494BOOL Picker_IsIdling(HWND hwndPicker)
495{
496   struct PickerInfo *pPickerInfo;
497   pPickerInfo = GetPickerInfo(hwndPicker);
498   return pPickerInfo->nTimer != 0;
499}
500
501
502
503BOOL SetupPicker(HWND hwndPicker, const struct PickerOptions *pOptions)
504{
505   struct PickerInfo *pPickerInfo;
506   int i;
507   LONG_PTR l;
508
509   assert(hwndPicker);
510
511   // Allocate the list view struct
512   pPickerInfo = (struct PickerInfo *) malloc(sizeof(struct PickerInfo));
513   if (!pPickerInfo)
514      return FALSE;
515
516   // And fill it out
517   memset(pPickerInfo, 0, sizeof(*pPickerInfo));
518   pPickerInfo->pCallbacks = pOptions->pCallbacks;
519   pPickerInfo->nColumnCount = pOptions->nColumnCount;
520   pPickerInfo->ppszColumnNames = pOptions->ppszColumnNames;
521   pPickerInfo->nLastItem = -1;
522
523   if (pPickerInfo->nColumnCount)
524   {
525      // Allocate space for the column order and columns shown array
526      pPickerInfo->pnColumnsOrder = malloc(pPickerInfo->nColumnCount *
527         sizeof(*pPickerInfo->pnColumnsOrder));
528      pPickerInfo->pnColumnsShown = malloc(pPickerInfo->nColumnCount *
529         sizeof(*pPickerInfo->pnColumnsShown));
530      if (!pPickerInfo->pnColumnsOrder || !pPickerInfo->pnColumnsShown)
531         goto error;
532
533      // set up initial values
534      for (i = 0; i < pPickerInfo->nColumnCount; i++)
535      {
536         pPickerInfo->pnColumnsOrder[i] = i;
537         pPickerInfo->pnColumnsShown[i] = TRUE;
538      }
539
540      if (GetUseOldControl())
541      {
542         if (pPickerInfo->pCallbacks->pfnSetColumnOrder)
543            pPickerInfo->pCallbacks->pfnSetColumnOrder(pPickerInfo->pnColumnsOrder);
544         if (pPickerInfo->pCallbacks->pfnSetColumnShown)
545            pPickerInfo->pCallbacks->pfnSetColumnShown(pPickerInfo->pnColumnsShown);
546      }
547      else
548      {
549         if (pPickerInfo->pCallbacks->pfnGetColumnOrder)
550            pPickerInfo->pCallbacks->pfnGetColumnOrder(pPickerInfo->pnColumnsOrder);
551         if (pPickerInfo->pCallbacks->pfnGetColumnShown)
552            pPickerInfo->pCallbacks->pfnGetColumnShown(pPickerInfo->pnColumnsShown);
553      }
554   }
555
556   // Hook in our wndproc and userdata pointer
557   l = GetWindowLongPtr(hwndPicker, GWLP_WNDPROC);
558   pPickerInfo->pfnParentWndProc = (WNDPROC) l;
559   SetWindowLongPtr(hwndPicker, GWLP_USERDATA, (LONG_PTR) pPickerInfo);
560   SetWindowLongPtr(hwndPicker, GWLP_WNDPROC, (LONG_PTR) ListViewWndProc);
561
562   ListView_SetExtendedListViewStyle(hwndPicker, LVS_EX_FULLROWSELECT | LVS_EX_HEADERDRAGDROP |
563      LVS_EX_UNDERLINEHOT | LVS_EX_UNDERLINECOLD | LVS_EX_LABELTIP);
564
565   Picker_InternalResetColumnDisplay(hwndPicker, TRUE);
566   Picker_ResetIdle(hwndPicker);
567   return TRUE;
568
569error:
570   if (pPickerInfo)
571      Picker_Free(pPickerInfo);
572   return FALSE;
573}
574
575
576
577int Picker_GetViewID(HWND hwndPicker)
578{
579   struct PickerInfo *pPickerInfo;
580   pPickerInfo = GetPickerInfo(hwndPicker);
581   return pPickerInfo->nCurrentViewID;
582}
583
584
585
586void Picker_SetViewID(HWND hwndPicker, int nViewID)
587{
588   struct PickerInfo *pPickerInfo;
589   LONG_PTR nListViewStyle;
590   DWORD dwStyle;
591
592   pPickerInfo = GetPickerInfo(hwndPicker);
593
594   // Change the nCurrentViewID member
595   pPickerInfo->nCurrentViewID = nViewID;
596   if (pPickerInfo->pCallbacks->pfnSetViewMode)
597      pPickerInfo->pCallbacks->pfnSetViewMode(pPickerInfo->nCurrentViewID);
598
599   // Change the ListView flags in accordance
600   switch(nViewID)
601   {
602      case VIEW_LARGE_ICONS:
603         nListViewStyle = LVS_ICON;
604         break;
605      case VIEW_SMALL_ICONS:
606         nListViewStyle = LVS_SMALLICON;
607         break;
608      case VIEW_INLIST:
609         nListViewStyle = LVS_LIST;
610         break;
611      case VIEW_GROUPED:
612      case VIEW_REPORT:
613      default:
614         nListViewStyle = LVS_REPORT;
615         break;
616   }
617
618   dwStyle = GetWindowLong(hwndPicker, GWL_STYLE);
619   if (GetUseXPControl())
620   {
621      // RS Microsoft must have changed something in the Ownerdraw handling with Version 6 of the Common Controls
622      // as on all other OSes it works without this...
623      if (nViewID == VIEW_LARGE_ICONS || nViewID == VIEW_SMALL_ICONS)
624      {
625         // remove Ownerdraw style for Icon views
626         dwStyle &= ~LVS_OWNERDRAWFIXED;
627         if( nViewID == VIEW_SMALL_ICONS )
628         {
629            // to properly get them to arrange, otherwise the entries might overlap
630            // we have to call SetWindowLong to get it into effect !!
631            // It's no use just setting the Style, as it's changed again further down...
632            SetWindowLong(hwndPicker, GWL_STYLE, (GetWindowLong(hwndPicker, GWL_STYLE)
633               & ~LVS_TYPEMASK) | LVS_ICON);
634         }
635      }
636      else
637      {
638         // add again..
639         dwStyle |= LVS_OWNERDRAWFIXED;
640      }
641   }
642
643   dwStyle &= ~LVS_TYPEMASK;
644   dwStyle |= nListViewStyle;
645   SetWindowLong(hwndPicker, GWL_STYLE, dwStyle);
646   RedrawWindow(hwndPicker, NULL, NULL, RDW_ERASE | RDW_INVALIDATE | RDW_FRAME);
647}
648
649
650
651static BOOL PickerHitTest(HWND hWnd)
652{
653   RECT         rect;
654   POINTS         p;
655   DWORD         res = GetMessagePos();
656   LVHITTESTINFO   htInfo;
657
658    memset(&htInfo, 0, sizeof(htInfo));
659   p = MAKEPOINTS(res);
660   GetWindowRect(hWnd, &rect);
661   htInfo.pt.x = p.x - rect.left;
662   htInfo.pt.y = p.y - rect.top;
663   ListView_HitTest(hWnd, &htInfo);
664
665   return (! (htInfo.flags & LVHT_NOWHERE));
666}
667
668
669
670int Picker_GetSelectedItem(HWND hWnd)
671{
672   int nItem;
673   LV_ITEM lvi;
674
675   nItem = ListView_GetNextItem(hWnd, -1, LVIS_SELECTED | LVIS_FOCUSED);
676   if (nItem < 0)
677      return 0;
678
679   memset(&lvi, 0, sizeof(lvi));
680   lvi.iItem = nItem;
681   lvi.mask = LVIF_PARAM;
682   ListView_GetItem(hWnd, &lvi);
683   return lvi.lParam;
684}
685
686
687
688void Picker_SetSelectedPick(HWND hWnd, int nIndex)
689{
690   if (nIndex < 0)
691      nIndex = 0;
692
693   ListView_SetItemState(hWnd, nIndex, LVIS_FOCUSED | LVIS_SELECTED,
694      LVIS_FOCUSED | LVIS_SELECTED);
695   ListView_EnsureVisible(hWnd, nIndex, FALSE);
696}
697
698
699
700void Picker_SetSelectedItem(HWND hWnd, int nItem)
701{
702   int i;
703   LV_FINDINFO lvfi;
704
705   if (nItem < 0)
706      return;
707
708   lvfi.flags = LVFI_PARAM;
709   lvfi.lParam = nItem;
710   i = ListView_FindItem(hWnd, -1, &lvfi);
711   if (i == -1)
712   {
713      POINT p = {0,0};
714      lvfi.flags = LVFI_NEARESTXY;
715      lvfi.pt = p;
716      i = ListView_FindItem(hWnd, -1, &lvfi);
717   }
718   Picker_SetSelectedPick(hWnd, (i == -1) ? 0 : i);
719}
720
721
722
723static const TCHAR *Picker_CallGetItemString(HWND hwndPicker,
724   int nItem, int nColumn, TCHAR *pszBuffer, UINT nBufferLength)
725{
726   // this call wraps the pfnGetItemString callback to properly set up the
727   // buffers, and normalize the results
728   struct PickerInfo *pPickerInfo;
729   const TCHAR *s;
730
731   pPickerInfo = GetPickerInfo(hwndPicker);
732   pszBuffer[0] = '\0';
733   s = NULL;
734
735   if (pPickerInfo->pCallbacks->pfnGetItemString)
736   {
737      s = pPickerInfo->pCallbacks->pfnGetItemString(hwndPicker,
738         nItem, nColumn, pszBuffer, nBufferLength);
739   }
740   if (!s)
741      s = pszBuffer;
742   return s;
743}
744
745
746
747// put the arrow on the new sort column
748static void Picker_ResetHeaderSortIcon(HWND hwndPicker)
749{
750   struct PickerInfo *pPickerInfo;
751   HWND hwndHeader;
752   HD_ITEM hdi;
753   int i, nViewColumn;
754
755   pPickerInfo = GetPickerInfo(hwndPicker);
756
757   hwndHeader = ListView_GetHeader(hwndPicker);
758
759   // take arrow off non-current columns
760   hdi.mask = HDI_FORMAT;
761   hdi.fmt = HDF_STRING;
762   for (i = 0; i < pPickerInfo->nColumnCount; i++)
763   {
764      if (i != pPickerInfo->pCallbacks->pfnGetSortColumn())
765         Header_SetItem(hwndHeader, Picker_GetViewColumnFromRealColumn(hwndPicker, i), &hdi);
766   }
767
768   if (GetUseXPControl())
769   {
770      // use built in sort arrows
771      hdi.mask = HDI_FORMAT;
772      hdi.fmt = HDF_STRING | (pPickerInfo->pCallbacks->pfnGetSortReverse() ? HDF_SORTDOWN : HDF_SORTUP);
773   }
774   else
775   {
776      // put our arrow icon next to the text
777      hdi.mask = HDI_FORMAT | HDI_IMAGE;
778      hdi.fmt = HDF_STRING | HDF_IMAGE | HDF_BITMAP_ON_RIGHT;
779      hdi.iImage = pPickerInfo->pCallbacks->pfnGetSortReverse() ? 1 : 0;
780   }
781
782   nViewColumn = Picker_GetViewColumnFromRealColumn(hwndPicker, pPickerInfo->pCallbacks->pfnGetSortColumn());
783   Header_SetItem(hwndHeader, nViewColumn, &hdi);
784}
785
786
787
788struct CompareProcParams
789{
790   HWND hwndPicker;
791   struct PickerInfo *pPickerInfo;
792   int nSortColumn;
793   int nViewMode;
794   BOOL bReverse;
795};
796
797
798
799static void Picker_PopulateCompareProcParams(HWND hwndPicker,
800   struct CompareProcParams *pParams)
801{
802   struct PickerInfo *pPickerInfo;
803
804   pPickerInfo = GetPickerInfo(hwndPicker);
805
806   // populate the CompareProcParams structure
807   memset(pParams, 0, sizeof(*pParams));
808   pParams->hwndPicker = hwndPicker;
809   pParams->pPickerInfo = pPickerInfo;
810   pParams->nViewMode = pPickerInfo->pCallbacks->pfnGetViewMode();
811   if (pPickerInfo->pCallbacks->pfnGetSortColumn)
812      pParams->nSortColumn = pPickerInfo->pCallbacks->pfnGetSortColumn();
813   if (pPickerInfo->pCallbacks->pfnGetSortReverse)
814      pParams->bReverse = pPickerInfo->pCallbacks->pfnGetSortReverse();
815}
816
817
818
819static int CALLBACK Picker_CompareProc(LPARAM index1, LPARAM index2, LPARAM nParamSort)
820{
821   struct CompareProcParams *pcpp = (struct CompareProcParams *) nParamSort;
822   struct PickerInfo *pPickerInfo = pcpp->pPickerInfo;
823   BOOL bCallCompare = TRUE;
824   int nResult = 0, nParent1, nParent2;
825   TCHAR szBuffer1[256], szBuffer2[256];
826   const TCHAR *s1, *s2;
827
828   if (pcpp->nViewMode == VIEW_GROUPED)
829   {
830      // do our fancy compare, with clones grouped under parents
831      // first thing we need to do is identify both item's parents
832      if (pPickerInfo->pCallbacks->pfnFindItemParent)
833      {
834         nParent1 = pPickerInfo->pCallbacks->pfnFindItemParent(pcpp->hwndPicker, index1);
835         nParent2 = pPickerInfo->pCallbacks->pfnFindItemParent(pcpp->hwndPicker, index2);
836      }
837      else
838      {
839         nParent1 = nParent2 = -1;
840      }
841
842      if ((nParent1 < 0) && (nParent2 < 0))
843      {
844         // if both entries are both parents, we just do a basic sort
845      }
846      else if ((nParent1 >= 0) && (nParent2 >= 0))
847      {
848         // if both entries are children and the parents are different,
849         // sort on their parents
850         if (nParent1 != nParent2)
851         {
852            index1 = nParent1;
853            index2 = nParent2;
854         }
855      }
856      else
857      {
858         // one parent, one child
859         if (nParent1 >= 0)
860         {
861            // first one is a child
862            if (nParent1 == index2)
863            {
864               // if this is a child and its parent, put child after
865               nResult = 1;
866               bCallCompare = FALSE;
867            }
868            else
869            {
870               // sort on parent
871               index1 = nParent1;
872            }
873         }
874         else
875         {
876            // second one is a child
877            if (nParent2 == index1)
878            {
879               // if this is a child and its parent, put child after
880               nResult = -1;
881               bCallCompare = FALSE;
882            }
883            else
884            {
885               // sort on parent
886               index2 = nParent2;
887            }
888         }
889      }
890   }
891
892   if (bCallCompare)
893   {
894      if (pPickerInfo->pCallbacks->pfnCompare)
895      {
896         nResult = pPickerInfo->pCallbacks->pfnCompare(pcpp->hwndPicker,
897            index1, index2, pcpp->nSortColumn);
898      }
899      else
900      {
901         // no default sort proc, just get the string and compare them
902         s1 = Picker_CallGetItemString(pcpp->hwndPicker, index1, pcpp->nSortColumn,
903            szBuffer1, sizeof(szBuffer1) / sizeof(szBuffer1[0]));
904         s2 = Picker_CallGetItemString(pcpp->hwndPicker, index2, pcpp->nSortColumn,
905            szBuffer2, sizeof(szBuffer2) / sizeof(szBuffer2[0]));
906         nResult = _tcsicmp(s1, s2);
907      }
908
909      if (pcpp->bReverse)
910         nResult = -nResult;
911   }
912   return nResult;
913}
914
915
916
917void Picker_Sort(HWND hwndPicker)
918{
919   LV_FINDINFO lvfi;
920   struct PickerInfo *pPickerInfo;
921   struct CompareProcParams params;
922   int nItem;
923
924   pPickerInfo = GetPickerInfo(hwndPicker);
925
926   // populate the CompareProcParams structure
927   Picker_PopulateCompareProcParams(hwndPicker, &params);
928
929   ListView_SortItems(hwndPicker, Picker_CompareProc, (LPARAM) &params);
930
931   Picker_ResetHeaderSortIcon(hwndPicker);
932
933   memset(&lvfi, 0, sizeof(lvfi));
934   lvfi.flags = LVFI_PARAM;
935   lvfi.lParam = Picker_GetSelectedItem(hwndPicker);
936   nItem = ListView_FindItem(hwndPicker, -1, &lvfi);
937
938   ListView_EnsureVisible(hwndPicker, nItem, FALSE);
939}
940
941
942
943int Picker_InsertItemSorted(HWND hwndPicker, int nParam)
944{
945   struct PickerInfo *pPickerInfo;
946   int nHigh, nLow, nMid;
947   struct CompareProcParams params;
948   int nCompareResult;
949   LVITEM lvi;
950
951   pPickerInfo = GetPickerInfo(hwndPicker);
952
953   nLow = 0;
954   nHigh = ListView_GetItemCount(hwndPicker);
955
956   // populate the CompareProcParams structure
957   Picker_PopulateCompareProcParams(hwndPicker, &params);
958
959   while(nLow < nHigh)
960   {
961      nMid = (nHigh + nLow) / 2;
962
963      memset(&lvi, 0, sizeof(lvi));
964      lvi.mask = LVIF_PARAM;
965      lvi.iItem = nMid;
966      ListView_GetItem(hwndPicker, &lvi);
967
968      nCompareResult = Picker_CompareProc(nParam, lvi.lParam, (LPARAM) &params);
969
970      if (nCompareResult > 0)
971         nLow  = nMid + 1;
972      else if (nCompareResult < 0)
973         nHigh = nMid;
974      else
975      {
976         nLow = nMid;
977         break;
978      }
979   }
980
981   memset(&lvi, 0, sizeof(lvi));
982   lvi.mask     = LVIF_IMAGE | LVIF_TEXT | LVIF_PARAM;
983   lvi.iItem    = nLow;
984   lvi.iSubItem = 0;
985   lvi.lParam    = nParam;
986   lvi.pszText  = LPSTR_TEXTCALLBACK;
987   lvi.iImage    = I_IMAGECALLBACK;
988
989   return ListView_InsertItem(hwndPicker, &lvi);
990}
991
992
993
994int Picker_GetRealColumnFromViewColumn(HWND hWnd, int nViewColumn)
995{
996   struct PickerInfo *pPickerInfo;
997   int nRealColumn = 0;
998
999   pPickerInfo = GetPickerInfo(hWnd);
1000   if (nViewColumn >= 0 && nViewColumn < pPickerInfo->nColumnCount)
1001      nRealColumn = pPickerInfo->pnColumnsOrder[nViewColumn];
1002   return nRealColumn;
1003}
1004
1005
1006
1007int Picker_GetViewColumnFromRealColumn(HWND hWnd, int nRealColumn)
1008{
1009   struct PickerInfo *pPickerInfo;
1010   int i;
1011
1012   pPickerInfo = GetPickerInfo(hWnd);
1013   for (i = 0; i < pPickerInfo->nColumnCount; i++)
1014   {
1015      if (pPickerInfo->pnColumnsOrder[i] == nRealColumn)
1016         return i;
1017   }
1018
1019   // major error, shouldn't be possible, but no good way to warn
1020   return 0;
1021}
1022
1023
1024
1025BOOL Picker_HandleNotify(LPNMHDR lpNmHdr)
1026{
1027   struct PickerInfo *pPickerInfo;
1028   HWND hWnd;
1029   BOOL bResult = FALSE;
1030   NM_LISTVIEW *pnmv;
1031   LV_DISPINFO *pDispInfo;
1032   int nItem, nColumn;
1033   const TCHAR *s;
1034   BOOL bReverse;
1035
1036   hWnd = lpNmHdr->hwndFrom;
1037   pPickerInfo = GetPickerInfo(hWnd);
1038   pnmv = (NM_LISTVIEW *) lpNmHdr;
1039
1040   switch(lpNmHdr->code)
1041   {
1042      case NM_RCLICK:
1043      case NM_CLICK:
1044      case NM_DBLCLK:
1045         // don't allow selection of blank spaces in the listview
1046         if (!PickerHitTest(hWnd))
1047         {
1048            // we have no current item selected
1049            if (pPickerInfo->nLastItem != -1)
1050            {
1051               Picker_SetSelectedItem(hWnd, pPickerInfo->nLastItem);
1052            }
1053            bResult = TRUE;
1054         }
1055         else if ((lpNmHdr->code == NM_DBLCLK) && (pPickerInfo->pCallbacks->pfnDoubleClick))
1056         {
1057            // double click!
1058            pPickerInfo->pCallbacks->pfnDoubleClick();
1059            bResult = TRUE;
1060         }
1061         break;
1062
1063      case LVN_GETDISPINFO:
1064         pDispInfo = (LV_DISPINFO *) lpNmHdr;
1065         nItem = (int) pDispInfo->item.lParam;
1066
1067         if (pDispInfo->item.mask & LVIF_IMAGE)
1068         {
1069            // retrieve item image
1070            if (pPickerInfo->pCallbacks->pfnGetItemImage)
1071               pDispInfo->item.iImage = pPickerInfo->pCallbacks->pfnGetItemImage(hWnd, nItem);
1072            else
1073               pDispInfo->item.iImage = 0;
1074            bResult = TRUE;
1075         }
1076
1077         if (pDispInfo->item.mask & LVIF_STATE)
1078         {
1079            pDispInfo->item.state = 0;
1080            bResult = TRUE;
1081         }
1082
1083         if (pDispInfo->item.mask & LVIF_TEXT)
1084         {
1085            // retrieve item text
1086            nColumn = Picker_GetRealColumnFromViewColumn(hWnd, pDispInfo->item.iSubItem);
1087           
1088            s = Picker_CallGetItemString(hWnd, nItem, nColumn,
1089               pDispInfo->item.pszText, pDispInfo->item.cchTextMax);
1090
1091            pDispInfo->item.pszText = (TCHAR *) s;
1092            bResult = TRUE;
1093         }
1094         break;
1095
1096      case LVN_ITEMCHANGED:
1097         if ((pnmv->uOldState & LVIS_SELECTED)
1098            && !(pnmv->uNewState & LVIS_SELECTED))
1099         {
1100            if (pnmv->lParam != -1)
1101               pPickerInfo->nLastItem = pnmv->lParam;
1102            if (pPickerInfo->pCallbacks->pfnLeavingItem)
1103               pPickerInfo->pCallbacks->pfnLeavingItem(hWnd, pnmv->lParam);
1104         }
1105         if (!(pnmv->uOldState & LVIS_SELECTED)
1106            && (pnmv->uNewState & LVIS_SELECTED))
1107         {
1108            if (pPickerInfo->pCallbacks->pfnEnteringItem)
1109               pPickerInfo->pCallbacks->pfnEnteringItem(hWnd, pnmv->lParam);
1110         }
1111         bResult = TRUE;
1112         break;
1113
1114      case LVN_COLUMNCLICK:
1115         // if clicked on the same column we're sorting by, reverse it
1116         if (pPickerInfo->pCallbacks->pfnGetSortColumn() == Picker_GetRealColumnFromViewColumn(hWnd, pnmv->iSubItem))
1117            bReverse = !pPickerInfo->pCallbacks->pfnGetSortReverse();
1118         else
1119            bReverse = FALSE;
1120         pPickerInfo->pCallbacks->pfnSetSortReverse(bReverse);
1121         pPickerInfo->pCallbacks->pfnSetSortColumn(Picker_GetRealColumnFromViewColumn(hWnd, pnmv->iSubItem));
1122         Picker_Sort(hWnd);
1123         bResult = TRUE;
1124         break;
1125
1126      case LVN_BEGINDRAG:
1127         if (pPickerInfo->pCallbacks->pfnBeginListViewDrag)
1128            pPickerInfo->pCallbacks->pfnBeginListViewDrag(pnmv);
1129         break;
1130   }
1131   return bResult;
1132}
1133
1134
1135
1136int Picker_GetNumColumns(HWND hWnd)
1137{
1138   int  nColumnCount = 0;
1139   int  i;
1140   HWND hwndHeader;
1141   int  *shown;
1142   struct PickerInfo *pPickerInfo;
1143
1144   pPickerInfo = GetPickerInfo(hWnd);
1145
1146   shown = malloc(pPickerInfo->nColumnCount * sizeof(*shown));
1147   if (!shown)
1148      return -1;
1149
1150   pPickerInfo->pCallbacks->pfnGetColumnShown(shown);
1151   hwndHeader = ListView_GetHeader(hWnd);
1152
1153   if (GetUseOldControl() || (nColumnCount = Header_GetItemCount(hWnd)) < 1)
1154   {
1155      nColumnCount = 0;
1156      for (i = 0; i < pPickerInfo->nColumnCount ; i++ )
1157      {
1158         if (shown[i])
1159            nColumnCount++;
1160      }
1161   }
1162   
1163   free(shown);
1164   return nColumnCount;
1165}
1166
1167
1168
1169/* Add ... to Items in ListView if needed */
1170static LPCTSTR MakeShortString(HDC hDC, LPCTSTR lpszLong, int nColumnLen, int nOffset)
1171{
1172   static const TCHAR szThreeDots[] = TEXT("...");
1173   static TCHAR szShort[MAX_PATH];
1174   int nStringLen = lstrlen(lpszLong);
1175   int nAddLen;
1176   SIZE size;
1177   int i;
1178
1179   GetTextExtentPoint32(hDC, lpszLong, nStringLen, &size);
1180   if (nStringLen == 0 || size.cx + nOffset <= nColumnLen)
1181      return lpszLong;
1182
1183   lstrcpy(szShort, lpszLong);
1184   GetTextExtentPoint32(hDC, szThreeDots, sizeof(szThreeDots), &size);
1185   nAddLen = size.cx;
1186
1187   for (i = nStringLen - 1; i > 0; i--)
1188   {
1189      szShort[i] = 0;
1190      GetTextExtentPoint32(hDC, szShort, i, &size);
1191      if (size.cx + nOffset + nAddLen <= nColumnLen)
1192         break;
1193   }
1194
1195   lstrcat(szShort, szThreeDots);
1196
1197   return szShort;
1198}
1199
1200
1201
1202void Picker_HandleDrawItem(HWND hWnd, LPDRAWITEMSTRUCT lpDrawItemStruct)
1203{
1204   struct PickerInfo *pPickerInfo;
1205   HDC         hDC = lpDrawItemStruct->hDC;
1206   RECT        rcItem = lpDrawItemStruct->rcItem;
1207   UINT        uiFlags = ILD_TRANSPARENT;
1208   HIMAGELIST  hImageList;
1209   int         nItem = lpDrawItemStruct->itemID;
1210   COLORREF    clrTextSave = 0;
1211   COLORREF    clrBkSave = 0;
1212   COLORREF    clrImage = GetSysColor(COLOR_WINDOW);
1213   static TCHAR szBuff[MAX_PATH];
1214   BOOL        bFocus = (GetFocus() == hWnd);
1215   LPCTSTR     pszText;
1216   UINT        nStateImageMask;
1217   BOOL        bSelected;
1218   LV_COLUMN   lvc;
1219   LV_ITEM     lvi;
1220   RECT        rcAllLabels;
1221   RECT        rcLabel;
1222   RECT        rcIcon;
1223   int         offset;
1224   SIZE        size;
1225   int         i, j;
1226   int         nColumn;
1227   int         nColumnMax = 0;
1228   int         *order;
1229   BOOL        bDrawAsChild;
1230   int         indent_space;
1231   BOOL      bColorChild = FALSE;
1232   BOOL      bParentFound = FALSE;
1233   int         nParent;
1234   HBITMAP      hBackground = GetBackgroundBitmap();
1235   MYBITMAPINFO *pbmDesc = GetBackgroundInfo();
1236
1237   pPickerInfo = GetPickerInfo(hWnd);
1238
1239   order = malloc(pPickerInfo->nColumnCount * sizeof(*order));
1240   if (!order)
1241      return;
1242   nColumnMax = Picker_GetNumColumns(hWnd);
1243
1244   if (GetUseOldControl())
1245   {
1246      pPickerInfo->pCallbacks->pfnGetColumnOrder(order);
1247   }
1248   else
1249   {
1250      /* Get the Column Order and save it */
1251      ListView_GetColumnOrderArray(hWnd, nColumnMax, order);
1252
1253      /* Disallow moving column 0 */
1254      if (order[0] != 0)
1255      {
1256         for (i = 0; i < nColumnMax; i++)
1257         {
1258            if (order[i] == 0)
1259            {
1260               order[i] = order[0];
1261               order[0] = 0;
1262            }
1263         }
1264         ListView_SetColumnOrderArray(hWnd, nColumnMax, order);
1265      }
1266   }
1267
1268   /* Labels are offset by a certain amount */
1269   /* This offset is related to the width of a space character */
1270   GetTextExtentPoint32(hDC, TEXT(" "), 1 , &size);
1271   offset = size.cx;
1272
1273   lvi.mask      = LVIF_TEXT | LVIF_IMAGE | LVIF_STATE | LVIF_PARAM;
1274   lvi.iItem      = nItem;
1275   lvi.iSubItem   = order[0];
1276   lvi.pszText      = szBuff;
1277   lvi.cchTextMax = sizeof(szBuff) / sizeof(szBuff[0]);
1278   lvi.stateMask  = 0xFFFF;      /* get all state flags */
1279   ListView_GetItem(hWnd, &lvi);
1280
1281   bSelected = ((lvi.state & LVIS_DROPHILITED) || ( (lvi.state & LVIS_SELECTED)
1282      && ((bFocus) || (GetWindowLong(hWnd, GWL_STYLE) & LVS_SHOWSELALWAYS))));
1283
1284   /* figure out if we indent and draw grayed */
1285   if (pPickerInfo->pCallbacks->pfnFindItemParent)
1286      nParent = pPickerInfo->pCallbacks->pfnFindItemParent(hWnd, lvi.lParam);
1287   else
1288      nParent = -1;
1289   bDrawAsChild = (pPickerInfo->pCallbacks->pfnGetViewMode() == VIEW_GROUPED && (nParent >= 0));
1290
1291   /* only indent if parent is also in this view */
1292   if ((nParent >= 0) && bDrawAsChild)
1293   {
1294      for (i = 0; i < ListView_GetItemCount(hWnd); i++)
1295      {
1296         lvi.mask = LVIF_PARAM;
1297         lvi.iItem = i;
1298         ListView_GetItem(hWnd, &lvi);
1299
1300         if (lvi.lParam == nParent)
1301         {
1302            bParentFound = TRUE;
1303            break;
1304         }
1305      }
1306   }
1307
1308   if (pPickerInfo->pCallbacks->pfnGetOffsetChildren && pPickerInfo->pCallbacks->pfnGetOffsetChildren())
1309   {
1310      if (!bParentFound && bDrawAsChild)
1311      {
1312         /*Reset it, as no Parent is there*/
1313         bDrawAsChild = FALSE;
1314         bColorChild = TRUE;
1315      }
1316      else
1317      {
1318         nParent = -1;
1319         bParentFound = FALSE;
1320      }
1321   }
1322
1323   ListView_GetItemRect(hWnd, nItem, &rcAllLabels, LVIR_BOUNDS);
1324   ListView_GetItemRect(hWnd, nItem, &rcLabel, LVIR_LABEL);
1325
1326   rcAllLabels.left = rcLabel.left;
1327
1328   if (hBackground != NULL)
1329   {
1330      RECT      rcClient;
1331      HRGN      rgnBitmap;
1332      RECT      rcTmpBmp = rcItem;
1333      RECT      rcFirstItem;
1334      HPALETTE   hPAL;
1335      HDC       htempDC;
1336      HBITMAP    oldBitmap;
1337
1338      htempDC = CreateCompatibleDC(hDC);
1339
1340      oldBitmap = SelectObject(htempDC, hBackground);
1341
1342      GetClientRect(hWnd, &rcClient);
1343      rcTmpBmp.right = rcClient.right;
1344      /* We also need to check whether it is the last item
1345         The update region has to be extended to the bottom if it is */
1346      if (nItem == ListView_GetItemCount(hWnd) - 1)
1347         rcTmpBmp.bottom = rcClient.bottom;
1348
1349      rgnBitmap = CreateRectRgnIndirect(&rcTmpBmp);
1350      SelectClipRgn(hDC, rgnBitmap);
1351      DeleteObject(rgnBitmap);
1352
1353      hPAL = GetBackgroundPalette();
1354      if (hPAL == NULL)
1355         hPAL = CreateHalftonePalette(hDC);
1356
1357      if (GetDeviceCaps(htempDC, RASTERCAPS) & RC_PALETTE && hPAL != NULL)
1358      {
1359         SelectPalette(htempDC, hPAL, FALSE);
1360         RealizePalette(htempDC);
1361      }
1362
1363      ListView_GetItemRect(hWnd, 0, &rcFirstItem, LVIR_BOUNDS);
1364
1365      for (i = rcFirstItem.left; i < rcClient.right; i += pbmDesc->bmWidth)
1366         for (j = rcFirstItem.top; j < rcClient.bottom; j +=  pbmDesc->bmHeight)
1367            BitBlt(hDC, i, j, pbmDesc->bmWidth, pbmDesc->bmHeight, htempDC, 0, 0, SRCCOPY);
1368
1369      SelectObject(htempDC, oldBitmap);
1370      DeleteDC(htempDC);
1371
1372      if (GetBackgroundPalette() == NULL)
1373      {
1374         DeleteObject(hPAL);
1375         hPAL = NULL;
1376      }
1377   }
1378
1379   indent_space = 0;
1380
1381   if (bDrawAsChild)
1382   {
1383      RECT rect;
1384     
1385      ListView_GetItemRect(hWnd, nItem, &rect, LVIR_ICON);
1386
1387      /* indent width of icon + the space between the icon and text
1388       * so left of clone icon starts at text of parent
1389         */
1390      indent_space = rect.right - rect.left + offset;
1391   }
1392
1393   rcAllLabels.left += indent_space;
1394
1395   if (bSelected)
1396   {
1397      HBRUSH hBrush;
1398      HBRUSH hOldBrush;
1399
1400      if (bFocus)
1401      {
1402         clrTextSave = SetTextColor(hDC, GetSysColor(COLOR_HIGHLIGHTTEXT));
1403         clrBkSave   = SetBkColor(hDC, GetSysColor(COLOR_HIGHLIGHT));
1404         hBrush      = CreateSolidBrush(GetSysColor(COLOR_HIGHLIGHT));
1405      }
1406      else
1407      {
1408         clrTextSave = SetTextColor(hDC, GetSysColor(COLOR_BTNTEXT));
1409         clrBkSave   = SetBkColor(hDC, GetSysColor(COLOR_BTNFACE));
1410         hBrush      = CreateSolidBrush(GetSysColor(COLOR_BTNFACE));
1411      }
1412
1413      hOldBrush = SelectObject(hDC, hBrush);
1414      FillRect(hDC, &rcAllLabels, hBrush);
1415      SelectObject(hDC, hOldBrush);
1416      DeleteObject(hBrush);
1417   }
1418   else
1419   {
1420      if (hBackground == NULL)
1421      {
1422         HBRUSH hBrush;
1423         
1424         hBrush = CreateSolidBrush(GetSysColor(COLOR_WINDOW));
1425         FillRect(hDC, &rcAllLabels, hBrush);
1426         DeleteObject(hBrush);
1427      }
1428     
1429      if (pPickerInfo->pCallbacks->pfnGetOffsetChildren && pPickerInfo->pCallbacks->pfnGetOffsetChildren())
1430      {
1431         if (bDrawAsChild || bColorChild)
1432            clrTextSave = SetTextColor(hDC, GetListCloneColor());
1433         else
1434            clrTextSave = SetTextColor(hDC, GetListFontColor());
1435      }
1436      else
1437      {
1438         if (bDrawAsChild)
1439            clrTextSave = SetTextColor(hDC, GetListCloneColor());
1440         else
1441            clrTextSave = SetTextColor(hDC, GetListFontColor());
1442      }
1443
1444      clrBkSave = SetBkColor(hDC, GetSysColor(COLOR_WINDOW));
1445   }
1446
1447
1448   if (lvi.state & LVIS_CUT)
1449   {
1450      clrImage = GetSysColor(COLOR_WINDOW);
1451      uiFlags |= ILD_BLEND50;
1452   }
1453   else if (bSelected)
1454   {
1455      if (bFocus)
1456         clrImage = GetSysColor(COLOR_HIGHLIGHT);
1457      else
1458         clrImage = GetSysColor(COLOR_BTNFACE);
1459
1460      uiFlags |= ILD_BLEND50;
1461   }
1462
1463   nStateImageMask = lvi.state & LVIS_STATEIMAGEMASK;
1464
1465   if (nStateImageMask)
1466   {
1467      int nImage = (nStateImageMask >> 12) - 1;
1468      hImageList = ListView_GetImageList(hWnd, LVSIL_STATE);
1469      if (hImageList)
1470         ImageList_Draw(hImageList, nImage, hDC, rcItem.left, rcItem.top, ILD_TRANSPARENT);
1471   }
1472
1473   ListView_GetItemRect(hWnd, nItem, &rcIcon, LVIR_ICON);
1474
1475   rcIcon.left += indent_space;
1476
1477   ListView_GetItemRect(hWnd, nItem, &rcItem, LVIR_LABEL);
1478
1479   hImageList = ListView_GetImageList(hWnd, LVSIL_SMALL);
1480   if (hImageList)
1481   {
1482      UINT nOvlImageMask = lvi.state & LVIS_OVERLAYMASK;
1483      if (rcIcon.left + 16 + indent_space < rcItem.right)
1484      {
1485         ImageList_DrawEx(hImageList, lvi.iImage, hDC, rcIcon.left, rcIcon.top, 16, 16,
1486                      GetSysColor(COLOR_WINDOW), clrImage, uiFlags | nOvlImageMask);
1487      }
1488   }
1489
1490   ListView_GetItemRect(hWnd, nItem, &rcItem, LVIR_LABEL);
1491
1492   pszText = MakeShortString(hDC, szBuff, rcItem.right - rcItem.left, 2*offset + indent_space);
1493
1494   rcLabel = rcItem;
1495   rcLabel.left  += offset + indent_space;
1496   rcLabel.right -= offset;
1497
1498   DrawText(hDC, pszText, -1, &rcLabel,
1499          DT_LEFT | DT_SINGLELINE | DT_NOPREFIX | DT_VCENTER);
1500
1501   for (nColumn = 1; nColumn < nColumnMax; nColumn++)
1502   {
1503      int    nRetLen;
1504      UINT   nJustify;
1505      LV_ITEM lvItem;
1506
1507      lvc.mask = LVCF_FMT | LVCF_WIDTH;
1508      ListView_GetColumn(hWnd, order[nColumn], &lvc);
1509
1510      lvItem.mask      = LVIF_TEXT;
1511      lvItem.iItem     = nItem;
1512      lvItem.iSubItem   = order[nColumn];
1513      lvItem.pszText     = szBuff;
1514      lvItem.cchTextMax = sizeof(szBuff) / sizeof(szBuff[0]);
1515
1516      if (ListView_GetItem(hWnd, &lvItem) == FALSE)
1517         continue;
1518
1519      rcItem.left   = rcItem.right;
1520      rcItem.right += lvc.cx;
1521
1522      nRetLen = _tcslen(szBuff);
1523      if (nRetLen == 0)
1524         continue;
1525
1526      pszText = MakeShortString(hDC, szBuff, rcItem.right - rcItem.left, 2 * offset);
1527
1528      nJustify = DT_LEFT;
1529
1530      if (pszText == szBuff)
1531      {
1532         switch (lvc.fmt & LVCFMT_JUSTIFYMASK)
1533         {
1534         case LVCFMT_RIGHT:
1535            nJustify = DT_RIGHT;
1536            break;
1537
1538         case LVCFMT_CENTER:
1539            nJustify = DT_CENTER;
1540            break;
1541
1542         default:
1543            break;
1544         }
1545      }
1546
1547      rcLabel = rcItem;
1548      rcLabel.left  += offset;
1549      rcLabel.right -= offset;
1550      DrawText(hDC, pszText, -1, &rcLabel,
1551             nJustify | DT_SINGLELINE | DT_NOPREFIX | DT_VCENTER);
1552   }
1553
1554   if (lvi.state & LVIS_FOCUSED && bFocus)
1555      DrawFocusRect(hDC, &rcAllLabels);
1556
1557   SetTextColor(hDC, clrTextSave);
1558   SetBkColor(hDC, clrBkSave);
1559   free(order);
1560}
1561
1562
1563
1564const struct PickerCallbacks *Picker_GetCallbacks(HWND hwndPicker)
1565{
1566   struct PickerInfo *pPickerInfo;
1567   pPickerInfo = GetPickerInfo(hwndPicker);
1568   return pPickerInfo->pCallbacks;
1569}
1570
1571
1572
1573int Picker_GetColumnCount(HWND hwndPicker)
1574{
1575   struct PickerInfo *pPickerInfo;
1576   pPickerInfo = GetPickerInfo(hwndPicker);
1577   return pPickerInfo->nColumnCount;
1578}
1579
1580
1581
1582LPCTSTR *Picker_GetColumnNames(HWND hwndPicker)
1583{
1584   struct PickerInfo *pPickerInfo;
1585   pPickerInfo = GetPickerInfo(hwndPicker);
1586   return pPickerInfo->ppszColumnNames;
1587}
1588
1589
1590
1591void Picker_SetHeaderImageList(HWND hwndPicker, HIMAGELIST hHeaderImages)
1592{
1593   HWND hwndHeader;
1594   hwndHeader = ListView_GetHeader(hwndPicker);
1595   SendMessage(hwndHeader, HDM_SETIMAGELIST, 0, (LPARAM) (void *) hHeaderImages);
1596}
1597
1598
1599
1600BOOL Picker_SaveColumnWidths(HWND hwndPicker)
1601{
1602   struct PickerInfo *pPickerInfo;
1603   int *widths;
1604   int *order;
1605   int *tmpOrder;
1606   int nColumnMax, i;
1607   BOOL bSuccess = FALSE;
1608
1609   pPickerInfo = GetPickerInfo(hwndPicker);
1610
1611   /* allocate space for the column info */
1612   widths = malloc(pPickerInfo->nColumnCount * sizeof(*widths));
1613   order = malloc(pPickerInfo->nColumnCount * sizeof(*order));
1614   tmpOrder = malloc(pPickerInfo->nColumnCount * sizeof(*tmpOrder));
1615   if (!widths || !order || !tmpOrder)
1616      goto done;
1617
1618   /* retrieve the values */
1619   memset(widths, 0, pPickerInfo->nColumnCount * sizeof(*widths));
1620   memset(order, 0, pPickerInfo->nColumnCount * sizeof(*order));
1621   pPickerInfo->pCallbacks->pfnGetColumnWidths(widths);
1622   pPickerInfo->pCallbacks->pfnGetColumnOrder(order);
1623
1624   /* switch the list view to LVS_REPORT style so column widths reported correctly */
1625   SetWindowLong(hwndPicker, GWL_STYLE,
1626               (GetWindowLong(hwndPicker, GWL_STYLE) & ~LVS_TYPEMASK) | LVS_REPORT);
1627
1628   nColumnMax = Picker_GetNumColumns(hwndPicker);
1629
1630   if (GetUseOldControl())
1631   {
1632      for (i = 0; i < nColumnMax; i++)
1633      {
1634         widths[Picker_GetRealColumnFromViewColumn(hwndPicker, i)] =
1635            ListView_GetColumnWidth(hwndPicker, i);
1636      }
1637   }
1638   else
1639   {
1640      /* Get the Column Order and save it */
1641      ListView_GetColumnOrderArray(hwndPicker, nColumnMax, tmpOrder);
1642
1643      for (i = 0; i < nColumnMax; i++)
1644      {
1645         widths[Picker_GetRealColumnFromViewColumn(hwndPicker, i)]
1646            = ListView_GetColumnWidth(hwndPicker, i);
1647         order[i] = Picker_GetRealColumnFromViewColumn(hwndPicker, tmpOrder[i]);
1648      }
1649   }
1650
1651   pPickerInfo->pCallbacks->pfnSetColumnWidths(widths);
1652   pPickerInfo->pCallbacks->pfnSetColumnOrder(order);
1653   bSuccess = TRUE;
1654
1655done:
1656   if (widths)
1657      free(widths);
1658   if (order)
1659      free(order);
1660   if (tmpOrder)
1661      free(tmpOrder);
1662   return bSuccess;
1663}
src/osd/winui/screenshot.c
r0r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10   
11***************************************************************************/
12
13/***************************************************************************
14
15  Screenshot.c
16 
17    Win32 DIB handling.
18   
19      Created 7/1/98 by Mike Haaland (mhaaland@hypertech.com)
20     
21***************************************************************************/
22
23#define WIN32_LEAN_AND_MEAN
24#include <windows.h>
25#include <stdlib.h>
26#include <io.h>
27#include <fcntl.h>
28#include <driver.h>
29#include <png.h>
30#include <osdepend.h>
31#include <tchar.h>
32
33#include "screenshot.h"
34#include "file.h"
35#include "bitmask.h"
36#include "m32opts.h"
37#include "m32util.h"
38#include "win32ui.h"
39#include "unzip.h"
40#include "strconv.h"
41
42/***************************************************************************
43    function prototypes
44***************************************************************************/
45
46static BOOL     AllocatePNG(png_info *p, HGLOBAL *phDIB, HPALETTE* pPal);
47
48static int png_read_bitmap_gui(LPVOID mfile, HGLOBAL *phDIB, HPALETTE *pPAL);
49/***************************************************************************
50    Static global variables
51***************************************************************************/
52
53/* these refer to the single image currently loaded by the ScreenShot functions */
54static HGLOBAL   m_hDIB = NULL;
55static HPALETTE  m_hPal = NULL;
56static HANDLE m_hDDB = NULL;
57static int current_image_game = -1;
58static int current_image_type = -1;
59
60#define WIDTHBYTES(width) ((width) / 8)
61
62/* PNG variables */
63
64static int   copy_size = 0;
65static char* pixel_ptr = 0;
66static int   row = 0;
67static int   effWidth;
68
69/***************************************************************************
70    Functions
71***************************************************************************/
72
73BOOL ScreenShotLoaded(void)
74{
75   return m_hDDB != NULL;
76}
77
78#ifdef MESS
79static BOOL LoadSoftwareScreenShot(const game_driver *drv, LPCSTR lpSoftwareName, int nType)
80{
81   BOOL result;
82   char *s = alloca(strlen(drv->name) + 1 + strlen(lpSoftwareName) + 5);
83   sprintf(s, "%s/%s.png", drv->name, lpSoftwareName);
84   result = LoadDIB(s, &m_hDIB, &m_hPal, nType);
85   return result;
86}
87#endif /* MESS */
88
89/* Allow us to pre-load the DIB once for future draws */
90#ifdef MESS
91BOOL LoadScreenShotEx(int nGame, LPCSTR lpSoftwareName, int nType)
92#else /* !MESS */
93BOOL LoadScreenShot(int nGame, int nType)
94#endif /* MESS */
95{
96   BOOL loaded = FALSE;
97   /* No need to reload the same one again */
98#ifndef MESS
99   if (nGame == current_image_game && nType == current_image_type)
100      return TRUE;
101#endif
102
103   /* Delete the last ones */
104   FreeScreenShot();
105
106   /* Load the DIB */
107#ifdef MESS
108   if (lpSoftwareName)
109   {
110      int nParentIndex = -1;
111      loaded = LoadSoftwareScreenShot(drivers[nGame], lpSoftwareName, nType);
112      if (!loaded && DriverIsClone(nGame) == TRUE)
113      {
114         nParentIndex = GetParentIndex(drivers[nGame]);
115         loaded = LoadSoftwareScreenShot(drivers[nParentIndex], lpSoftwareName, nType);
116      }
117   }
118   if (!loaded)
119#endif /* MESS */
120   {
121      loaded = LoadDIB(drivers[nGame]->name, &m_hDIB, &m_hPal, nType);
122   }
123
124   /* If not loaded, see if there is a clone and try that */
125   if (!loaded)
126   {
127      int nParentIndex = GetParentIndex(drivers[nGame]);
128      if( nParentIndex >= 0)
129      {
130         loaded = LoadDIB(drivers[nParentIndex]->name, &m_hDIB, &m_hPal, nType);
131         nParentIndex = GetParentIndex(drivers[nParentIndex]);
132         if (!loaded && nParentIndex >= 0)
133            loaded = LoadDIB(drivers[nParentIndex]->name, &m_hDIB, &m_hPal, nType);
134      }
135   }
136
137   if (loaded)
138   {
139      HDC hdc = GetDC(GetMainWindow());
140      m_hDDB = DIBToDDB(hdc, m_hDIB, NULL);
141      ReleaseDC(GetMainWindow(),hdc);
142     
143      current_image_game = nGame;
144      current_image_type = nType;
145
146   }
147
148   return (loaded) ? TRUE : FALSE;
149}
150
151HANDLE GetScreenShotHandle()
152{
153   return m_hDDB;
154}
155
156int GetScreenShotWidth(void)
157{
158   return ((LPBITMAPINFO)m_hDIB)->bmiHeader.biWidth;
159}
160
161int GetScreenShotHeight(void)
162{
163   return ((LPBITMAPINFO)m_hDIB)->bmiHeader.biHeight;
164}
165
166/* Delete the HPALETTE and Free the HDIB memory */
167void FreeScreenShot(void)
168{
169   if (m_hDIB != NULL)
170      GlobalFree(m_hDIB);
171   m_hDIB = NULL;
172
173   if (m_hPal != NULL)
174      DeleteObject(m_hPal);
175   m_hPal = NULL;
176
177   if (m_hDDB != NULL)
178      DeleteObject(m_hDDB);
179   m_hDDB = NULL;
180
181   current_image_game = -1;
182   current_image_type = -1;
183}
184
185static const zip_file_header *zip_file_seek_file(zip_file *zip, const char *filename)
186{
187   const zip_file_header *header;
188   char *new_filename;
189   int i;
190
191   // we need to change filename; allocate a copy
192   new_filename = malloc(strlen(filename) + 1);
193   if (!new_filename)
194      return NULL;
195   
196   // change all backslashes to forward slashes
197   for (i = 0; filename[i]; i++)
198      new_filename[i] = (filename[i] != '\\') ? filename[i] : '/';
199   new_filename[i] = '\0';
200
201   // find the entry
202   header = zip_file_first_file(zip);
203   while(header && mame_stricmp(header->filename, new_filename))
204   {
205      header = zip_file_next_file(zip);
206   }
207
208   free(new_filename);
209   return header;
210}
211
212static file_error OpenDIBFile(const char *dir_name, const char *zip_name, const char *filename,
213   core_file **file, void **buffer)
214{
215   file_error filerr;
216   zip_error ziperr;
217   zip_file *zip;
218   const zip_file_header *zip_header;
219   astring *fname;
220
221   // clear out result
222   *file = NULL;
223
224   // look for the raw file
225   fname = astring_assemble_3(astring_alloc(), dir_name, PATH_SEPARATOR, filename);
226   filerr = core_fopen(astring_c(fname), OPEN_FLAG_READ, file);
227   astring_free(fname);
228
229   // did the raw file not exist?
230   if (filerr != FILERR_NONE)
231   {
232      // look into zip file
233      fname = astring_assemble_4(astring_alloc(), dir_name, PATH_SEPARATOR, zip_name, ".zip");
234      ziperr = zip_file_open(astring_c(fname), &zip);
235      astring_free(fname);
236      if (ziperr == ZIPERR_NONE)
237      {
238         zip_header = zip_file_seek_file(zip, filename);
239         if (zip_header != NULL)
240         {
241            *buffer = malloc(zip_header->uncompressed_length);
242            ziperr = zip_file_decompress(zip, *buffer, zip_header->uncompressed_length);
243            if (ziperr == ZIPERR_NONE)
244            {
245               filerr = core_fopen_ram(*buffer, zip_header->uncompressed_length, OPEN_FLAG_READ, file);
246            }
247         }
248         zip_file_close(zip);
249      }
250   }
251   return filerr;
252}
253
254BOOL LoadDIB(const char *filename, HGLOBAL *phDIB, HPALETTE *pPal, int pic_type)
255{
256   file_error filerr;
257   core_file *file = NULL;
258   BOOL success = FALSE;
259   const char *dir_name;
260   const char *zip_name;
261   astring *fname;
262   void *buffer = NULL;
263
264   switch (pic_type)
265   {
266      case TAB_SCREENSHOT:
267         dir_name = GetImgDir();
268         zip_name = "snap";
269         break;
270      case TAB_FLYER:
271         dir_name = GetFlyerDir();
272         zip_name = "flyers";
273         break;
274      case TAB_CABINET:
275         dir_name = GetCabinetDir();
276         zip_name = "cabinets";
277         break;
278      case TAB_MARQUEE:
279         dir_name = GetMarqueeDir();
280         zip_name = "marquees";
281         break;
282      case TAB_TITLE:
283         dir_name = GetTitlesDir();
284         zip_name = "titles";
285         break;
286      case TAB_CONTROL_PANEL:
287         dir_name = GetControlPanelDir();
288         zip_name = "cpanel";
289         break;
290        case TAB_PCB :
291         dir_name = GetPcbDir();
292          zip_name = "pcb";
293         break;
294      case BACKGROUND:
295         dir_name = GetBgDir();
296         zip_name = "bkground";
297         break;
298      default :
299         // in case a non-image tab gets here, which can happen
300         return FALSE;
301   }
302
303   fname = astring_assemble_2(astring_alloc(), filename, ".png");
304   filerr = OpenDIBFile(dir_name, zip_name, astring_c(fname), &file, &buffer);
305   astring_free(fname);
306
307   if (filerr != FILERR_NONE)
308   {
309      fname = astring_assemble_3(astring_alloc(), filename, PATH_SEPARATOR, "0000.png");
310      filerr = OpenDIBFile(dir_name, zip_name, astring_c(fname), &file, &buffer);
311      astring_free(fname);
312   }
313
314   if (filerr == FILERR_NONE)
315   {
316      success = png_read_bitmap_gui(file, phDIB, pPal);
317      core_fclose(file);
318   }
319
320   // free the buffer if we have to
321   if (buffer != NULL)
322      free(buffer);
323
324   return success;
325}
326
327HBITMAP DIBToDDB(HDC hDC, HANDLE hDIB, LPMYBITMAPINFO desc)
328{
329   LPBITMAPINFOHEADER   lpbi;
330   HBITMAP          hBM;
331   int             nColors;
332   BITMAPINFO *      bmInfo = (LPBITMAPINFO)hDIB;
333   LPVOID            lpDIBBits;
334
335   if (hDIB == NULL)
336      return NULL;
337
338   lpbi = (LPBITMAPINFOHEADER)hDIB;
339   nColors = lpbi->biClrUsed ? lpbi->biClrUsed : 1 << lpbi->biBitCount;
340
341   if (bmInfo->bmiHeader.biBitCount > 8)
342      lpDIBBits = (LPVOID)((LPDWORD)(bmInfo->bmiColors +
343         bmInfo->bmiHeader.biClrUsed) +
344         ((bmInfo->bmiHeader.biCompression == BI_BITFIELDS) ? 3 : 0));
345   else
346      lpDIBBits = (LPVOID)(bmInfo->bmiColors + nColors);
347
348   if (desc != 0)
349   {
350      /* Store for easy retrieval later */
351      desc->bmWidth  = bmInfo->bmiHeader.biWidth;
352      desc->bmHeight = bmInfo->bmiHeader.biHeight;
353      desc->bmColors = (nColors <= 256) ? nColors : 0;
354   }
355
356   hBM = CreateDIBitmap(hDC,                 /* handle to device context */
357                  (LPBITMAPINFOHEADER)lpbi, /* pointer to bitmap info header   */
358                  (LONG)CBM_INIT,         /* initialization flag */
359                  lpDIBBits,              /* pointer to initialization data  */
360                  (LPBITMAPINFO)lpbi,      /* pointer to bitmap info */
361                  DIB_RGB_COLORS);        /* color-data usage  */
362
363   return hBM;
364}
365
366
367/***************************************************************************
368    PNG graphics handling functions
369***************************************************************************/
370
371static void store_pixels(UINT8 *buf, int len)
372{
373   if (pixel_ptr && copy_size)
374   {
375      memcpy(&pixel_ptr[row * effWidth], buf, len);
376      row--;
377      copy_size -= len;
378   }
379}
380
381BOOL AllocatePNG(png_info *p, HGLOBAL *phDIB, HPALETTE *pPal)
382{
383   int             dibSize;
384   HGLOBAL          hDIB;
385   BITMAPINFOHEADER   bi;
386   LPBITMAPINFOHEADER   lpbi;
387   LPBITMAPINFO      bmInfo;
388   LPVOID            lpDIBBits = 0;
389   int             lineWidth = 0;
390   int             nColors = 0;
391   RGBQUAD*         pRgb;
392   copy_size = 0;
393   pixel_ptr = 0;
394   row      = p->height - 1;
395   lineWidth = p->width;
396   
397   if (p->color_type != 2 && p->num_palette <= 256)
398      nColors =  p->num_palette;
399
400   bi.biSize         = sizeof(BITMAPINFOHEADER);
401   bi.biWidth         = p->width;
402   bi.biHeight       = p->height;
403   bi.biPlanes       = 1;
404   bi.biBitCount      = (p->color_type == 3) ? 8 : 24; /* bit_depth; */
405   
406   bi.biCompression   = BI_RGB;
407   bi.biSizeImage      = 0;
408   bi.biXPelsPerMeter   = 0;
409   bi.biYPelsPerMeter   = 0;
410   bi.biClrUsed      = nColors;
411   bi.biClrImportant   = nColors;
412   
413   effWidth = (long)(((long)lineWidth*bi.biBitCount + 31) / 32) * 4;
414   
415   dibSize = (effWidth * bi.biHeight);
416   hDIB = GlobalAlloc(GMEM_FIXED, bi.biSize + (nColors * sizeof(RGBQUAD)) + dibSize);
417   
418   if (!hDIB)
419   {
420      return FALSE;
421   }
422
423   lpbi = (LPVOID)hDIB;
424   memcpy(lpbi, &bi, sizeof(BITMAPINFOHEADER));
425   pRgb = (RGBQUAD*)((LPSTR)lpbi + bi.biSize);
426   lpDIBBits = (LPVOID)((LPSTR)lpbi + bi.biSize + (nColors * sizeof(RGBQUAD)));
427   if (nColors)
428   {
429      int i;
430      /*
431        Convert a PNG palette (3 byte RGBTRIPLEs) to a new
432        color table (4 byte RGBQUADs)
433      */
434      for (i = 0; i < nColors; i++)
435      {
436         RGBQUAD rgb;
437         
438         rgb.rgbRed      = p->palette[i * 3 + 0];
439         rgb.rgbGreen   = p->palette[i * 3 + 1];
440         rgb.rgbBlue    = p->palette[i * 3 + 2];
441         rgb.rgbReserved = (BYTE)0;
442         
443         pRgb[i] = rgb;
444      }
445   }
446   
447   bmInfo = (LPBITMAPINFO)hDIB;
448   
449   /* Create a halftone palette if colors > 256. */
450   if (0 == nColors || nColors > 256)
451   {
452      HDC hDC = CreateCompatibleDC(0); /* Desktop DC */
453      *pPal = CreateHalftonePalette(hDC);
454      DeleteDC(hDC);
455   }
456   else
457   {
458      UINT nSize = sizeof(LOGPALETTE) + (sizeof(PALETTEENTRY) * nColors);
459      LOGPALETTE *pLP = (LOGPALETTE *)malloc(nSize);
460      int  i;
461     
462      pLP->palVersion    = 0x300;
463      pLP->palNumEntries   = nColors;
464     
465      for (i = 0; i < nColors; i++)
466      {
467         pLP->palPalEntry[i].peRed   = bmInfo->bmiColors[i].rgbRed;
468         pLP->palPalEntry[i].peGreen = bmInfo->bmiColors[i].rgbGreen;
469         pLP->palPalEntry[i].peBlue   = bmInfo->bmiColors[i].rgbBlue;
470         pLP->palPalEntry[i].peFlags = 0;
471      }
472     
473      *pPal = CreatePalette(pLP);
474     
475      free (pLP);
476   }
477   
478   copy_size = dibSize;
479   pixel_ptr = lpDIBBits;
480   *phDIB = hDIB;
481   return TRUE;
482}
483
484/* Copied and modified from png.c */
485static int png_read_bitmap_gui(LPVOID mfile, HGLOBAL *phDIB, HPALETTE *pPAL)
486{
487   png_info p;
488   UINT32 i;
489   int bytespp;
490   
491   if (png_read_file(mfile, &p) != PNGERR_NONE)
492      return 0;
493
494   if (p.color_type != 3 && p.color_type != 2)
495   {
496      logerror("Unsupported color type %i (has to be 3)\n", p.color_type);
497      free(p.image);
498      return 0;
499   }
500   if (p.interlace_method != 0)
501   {
502      logerror("Interlace unsupported\n");
503      free (p.image);
504      return 0;
505   }
506 
507   /* Convert < 8 bit to 8 bit */
508   png_expand_buffer_8bit(&p);
509   
510   if (!AllocatePNG(&p, phDIB, pPAL))
511   {
512      logerror("Unable to allocate memory for artwork\n");
513      free(p.image);
514      return 0;
515   }
516
517   bytespp = (p.color_type == 2) ? 3 : 1;
518
519   for (i = 0; i < p.height; i++)
520   {
521      UINT8 *ptr = p.image + i * (p.width * bytespp);
522
523      if (p.color_type == 2) /*(p->bit_depth > 8) */
524      {
525         int j;
526         UINT8 bTmp;
527
528         for (j = 0; j < p.width; j++)
529         {
530            bTmp = ptr[0];
531            ptr[0] = ptr[2];
532            ptr[2] = bTmp;
533            ptr += 3;
534         }
535      }   
536      store_pixels(p.image + i * (p.width * bytespp), p.width * bytespp);
537   }
538
539   free(p.image);
540
541   return 1;
542}
543
544#ifdef MESS
545BOOL LoadScreenShot(int nGame, int nType)
546{
547   return LoadScreenShotEx(nGame, NULL, nType);
548}
549#endif
550
551/* End of source */
src/osd/winui/datafile.h
r0r996
1#ifndef DATAFILE_H
2#define DATAFILE_H
3
4struct tDatafileIndex
5{
6   long offset;
7   const game_driver *driver;
8};
9
10extern int load_driver_history (const game_driver *drv, char *buffer, int bufsize);
11
12#endif
src/osd/winui/directories.h
r0r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11 ***************************************************************************/
12
13#ifndef DIRECTORIES_H
14#define DIRECTORIES_H
15
16/* Dialog return codes */
17#define DIRDLG_ROMS         0x0010
18#define DIRDLG_SAMPLES      0x0020
19#define DIRDLG_INI          0x0040
20#define DIRDLG_CFG          0x0100
21#define DIRDLG_IMG          0x0400
22#define DIRDLG_INP          0x0800
23#define DIRDLG_CTRLR        0x1000
24#define DIRDLG_SOFTWARE      0x2000
25#define DIRDLG_COMMENT      0x4000
26
27#define DIRLIST_NEWENTRYTEXT "<               >"
28
29typedef struct
30{
31   LPCSTR   lpName;
32   LPCSTR   (*pfnGetTheseDirs)(void);
33   void     (*pfnSetTheseDirs)(LPCSTR lpDirs);
34   BOOL     bMulti;
35   int      nDirDlgFlags;
36}
37DIRECTORYINFO;
38
39/* in layout[ms].c */
40extern DIRECTORYINFO g_directoryInfo[];
41
42INT_PTR CALLBACK DirectoriesDialogProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam);
43
44#endif /* DIRECTORIES_H */
45
46
src/osd/winui/dijoystick.h
r0r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11 ***************************************************************************/
12
13#ifndef DIJOYSTICK_H
14#define DIJOYSTICK_H
15
16/*
17  limits:
18  - 7 joysticks
19  - 15 sticks on each joystick (15?)
20  - 63 buttons on each joystick
21
22  - 256 total inputs
23
24
25   1 1 1 1 1 1
26   5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
27  +---+-----------+---------+-----+
28  |Dir|Axis/Button|   Stick | Joy |
29  +---+-----------+---------+-----+
30
31    Stick:  0 for buttons 1 for axis
32    Joy:    1 for Mouse/track buttons
33
34*/
35#define JOYCODE(joy, stick, axis_or_button, dir) \
36        ((((dir)            & 0x03) << 14) |     \
37         (((axis_or_button) & 0x3f) <<  8) |     \
38         (((stick)          & 0x1f) <<  3) |     \
39         (((joy)            & 0x07) <<  0))
40
41#define GET_JOYCODE_JOY(code)    (((code) >> 0) & 0x07)
42#define GET_JOYCODE_STICK(code)  (((code) >> 3) & 0x1f)
43#define GET_JOYCODE_AXIS(code)   (((code) >> 8) & 0x3f)
44#define GET_JOYCODE_BUTTON(code) GET_JOYCODE_AXIS(code)
45#define GET_JOYCODE_DIR(code)    (((code) >>14) & 0x03)
46
47#define JOYCODE_STICK_BTN    0
48#define JOYCODE_STICK_AXIS   1
49#define JOYCODE_STICK_POV    2
50
51#define JOYCODE_DIR_BTN      0
52#define JOYCODE_DIR_NEG      1
53#define JOYCODE_DIR_POS      2
54
55struct OSDJoystick
56{
57   int  (*init)(void);
58   void (*exit)(void);
59   int  (*is_joy_pressed)(int joycode);
60   void (*poll_joysticks)(void);
61   BOOL (*Available)(void);
62};
63
64extern struct OSDJoystick DIJoystick;
65
66extern int    DIJoystick_GetNumPhysicalJoysticks(void);
67extern TCHAR* DIJoystick_GetPhysicalJoystickName(int num_joystick);
68
69extern int    DIJoystick_GetNumPhysicalJoystickAxes(int num_joystick);
70extern TCHAR* DIJoystick_GetPhysicalJoystickAxisName(int num_joystick, int num_axis);
71
72#endif
src/osd/winui/picker.h
r0r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11 ***************************************************************************/
12
13#ifndef PICKER_H
14#define PICKER_H
15
16struct PickerCallbacks
17{
18   // Options retrieval
19   void (*pfnSetSortColumn)(int column);
20   int (*pfnGetSortColumn)(void);
21   void (*pfnSetSortReverse)(BOOL reverse);
22   BOOL (*pfnGetSortReverse)(void);
23   void (*pfnSetViewMode)(int val);
24   int (*pfnGetViewMode)(void);
25   void (*pfnSetColumnWidths)(int widths[]);
26   void (*pfnGetColumnWidths)(int widths[]);
27   void (*pfnSetColumnOrder)(int order[]);
28   void (*pfnGetColumnOrder)(int order[]);
29   void (*pfnSetColumnShown)(int shown[]);
30   void (*pfnGetColumnShown)(int shown[]);
31   BOOL (*pfnGetOffsetChildren)(void);
32
33   int (*pfnCompare)(HWND hwndPicker, int nIndex1, int nIndex2, int nSortSubItem);
34   void (*pfnDoubleClick)(void);
35   const TCHAR *(*pfnGetItemString)(HWND hwndPicker, int nItem, int nColumn,
36      TCHAR *pszBuffer, UINT nBufferLength);
37   int (*pfnGetItemImage)(HWND hwndPicker, int nItem);
38   void (*pfnLeavingItem)(HWND hwndPicker, int nItem);
39   void (*pfnEnteringItem)(HWND hwndPicker, int nItem);
40   void (*pfnBeginListViewDrag)(NM_LISTVIEW *pnlv);
41   int (*pfnFindItemParent)(HWND hwndPicker, int nItem);
42   BOOL (*pfnOnIdle)(HWND hwndPicker);
43   void (*pfnOnHeaderContextMenu)(POINT pt, int nColumn);
44   void (*pfnOnBodyContextMenu)(POINT pt);
45};
46
47struct PickerOptions
48{
49   const struct PickerCallbacks *pCallbacks;
50   BOOL bOldControl;
51   BOOL bXPControl;
52   int nColumnCount;
53   LPCTSTR *ppszColumnNames;
54};
55
56enum
57{
58   VIEW_LARGE_ICONS = 0,
59   VIEW_SMALL_ICONS,
60   VIEW_INLIST,
61   VIEW_REPORT,
62   VIEW_GROUPED,
63   VIEW_MAX
64};
65
66
67
68BOOL SetupPicker(HWND hwndPicker, const struct PickerOptions *pOptions);
69
70int Picker_GetViewID(HWND hwndPicker);
71void Picker_SetViewID(HWND hwndPicker, int nViewID);
72int Picker_GetRealColumnFromViewColumn(HWND hwndPicker, int nViewColumn);
73int Picker_GetViewColumnFromRealColumn(HWND hwndPicker, int nRealColumn);
74void Picker_Sort(HWND hwndPicker);
75void Picker_ResetColumnDisplay(HWND hwndPicker);
76int Picker_GetSelectedItem(HWND hwndPicker);
77void Picker_SetSelectedItem(HWND hwndPicker, int nItem);
78void Picker_SetSelectedPick(HWND hwndPicker, int nIndex);
79int Picker_GetNumColumns(HWND hWnd);
80void Picker_ClearIdle(HWND hwndPicker);
81void Picker_ResetIdle(HWND hwndPicker);
82BOOL Picker_IsIdling(HWND hwndPicker);
83void Picker_SetHeaderImageList(HWND hwndPicker, HIMAGELIST hHeaderImages);
84int Picker_InsertItemSorted(HWND hwndPicker, int nParam);
85BOOL Picker_SaveColumnWidths(HWND hwndPicker);
86
87// These are used to handle events received by the parent regarding
88// picker controls
89BOOL Picker_HandleNotify(LPNMHDR lpNmHdr);
90void Picker_HandleDrawItem(HWND hwndPicker, LPDRAWITEMSTRUCT lpDrawItemStruct);
91
92// Accessors
93const struct PickerCallbacks *Picker_GetCallbacks(HWND hwndPicker);
94int Picker_GetColumnCount(HWND hwndPicker);
95LPCTSTR *Picker_GetColumnNames(HWND hwndPicker);
96
97#endif // PICKER_H
src/osd/winui/screenshot.h
r0r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11 ***************************************************************************/
12
13#ifndef SCREENSHOT_H
14#define SCREENSHOT_H
15
16typedef struct _mybitmapinfo
17{
18   int bmWidth;
19   int bmHeight;
20   int bmColors;
21} MYBITMAPINFO, *LPMYBITMAPINFO;
22
23#ifdef MESS
24extern BOOL LoadScreenShotEx(int nGame, LPCSTR lpSoftwareName, int nType);
25#endif /* MESS */
26
27extern BOOL LoadScreenShot(int nGame, int nType);
28extern HANDLE GetScreenShotHandle(void);
29extern int GetScreenShotWidth(void);
30extern int GetScreenShotHeight(void);
31
32extern void FreeScreenShot(void);
33extern BOOL ScreenShotLoaded(void);
34
35extern BOOL LoadDIB(const char *filename, HGLOBAL *phDIB, HPALETTE *pPal, BOOL flyer);
36extern HBITMAP DIBToDDB(HDC hDC, HANDLE hDIB, LPMYBITMAPINFO desc);
37
38#endif
src/osd/winui/splitters.c
r0r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Splitter code Copyright (C) 1997-98 Mike Haaland
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11 ***************************************************************************/
12 
13 /***************************************************************************
14
15  Splitters.c
16
17  Splitter GUI code.
18
19  Created 12/03/98 (C) by Mike Haaland (mhaaland@hypertech.com)
20
21***************************************************************************/
22
23/*
24
25  Tree, spliiter, list, splitter, pict
26
27*/
28 
29
30#define WIN32_LEAN_AND_MEAN
31#include <windows.h>
32#include <windowsx.h>
33#include <commctrl.h>
34
35#include "splitters.h"
36#include "bitmask.h"
37#include "m32opts.h"
38#include "resource.h"
39#include "screenshot.h"
40#include "win32ui.h"
41
42/* Local Variables */
43static BOOL         bTracking = 0;
44static int          numSplitters = 0;
45static int          currentSplitter = 0;
46static HZSPLITTER   *splitter;
47static LPHZSPLITTER lpCurSpltr = 0;
48static HCURSOR      hSplitterCursor = 0;
49
50int *nSplitterOffset;
51
52BOOL InitSplitters(void)
53{
54   int nSplitterCount;
55
56   /* load the cursor for the splitter */
57   hSplitterCursor = LoadCursor(GetModuleHandle(0), MAKEINTRESOURCE(IDC_CURSOR_HSPLIT));
58
59   nSplitterCount = GetSplitterCount();
60
61   splitter = malloc(sizeof(HZSPLITTER) * nSplitterCount);
62   if (!splitter)
63      goto error;     
64   memset(splitter, 0, sizeof(HZSPLITTER) * nSplitterCount);
65
66   nSplitterOffset = malloc(sizeof(int) * nSplitterCount);
67   if (!nSplitterOffset)
68      goto error;     
69   memset(nSplitterOffset, 0, sizeof(int) * nSplitterCount);   
70
71   return TRUE;
72
73error:
74   SplittersExit();
75   return FALSE;
76}
77
78void SplittersExit(void)
79{
80   if (splitter)
81   {
82      free(splitter);
83      splitter = NULL;
84   }
85   if (nSplitterOffset)
86   {
87      free(nSplitterOffset);
88      nSplitterOffset = NULL;
89   }
90}
91
92
93/* Called with hWnd = Parent Window */
94void CalcSplitter(HWND hWnd, LPHZSPLITTER lpSplitter)
95{
96   POINT   p = {0,0};
97   RECT   leftRect, rightRect;
98   int    dragWidth;
99
100   ClientToScreen(hWnd, &p);
101
102   GetWindowRect(lpSplitter->m_hWnd,      &lpSplitter->m_dragRect);
103   GetWindowRect(lpSplitter->m_hWndLeft,   &leftRect);
104   GetWindowRect(lpSplitter->m_hWndRight,   &rightRect);
105
106   OffsetRect(&lpSplitter->m_dragRect, -p.x, -p.y);
107   OffsetRect(&leftRect, -p.x, -p.y);
108   OffsetRect(&rightRect, -p.x, -p.y);
109
110   dragWidth = lpSplitter->m_dragRect.right - lpSplitter->m_dragRect.left;
111
112   lpSplitter->m_limitRect.left   = leftRect.left + 20;
113   lpSplitter->m_limitRect.right   = rightRect.right - 20;
114   lpSplitter->m_limitRect.top    = lpSplitter->m_dragRect.top;
115   lpSplitter->m_limitRect.bottom   = lpSplitter->m_dragRect.bottom;
116   if (lpSplitter->m_func)
117      lpSplitter->m_func(hWnd, &lpSplitter->m_limitRect);
118
119   if (lpSplitter->m_dragRect.left < lpSplitter->m_limitRect.left)
120      lpSplitter->m_dragRect.left = lpSplitter->m_limitRect.left;
121
122   if (lpSplitter->m_dragRect.right > lpSplitter->m_limitRect.right)
123      lpSplitter->m_dragRect.left = lpSplitter->m_limitRect.right - dragWidth;
124
125   lpSplitter->m_dragRect.right = lpSplitter->m_dragRect.left + dragWidth;
126}
127
128void AdjustSplitter2Rect(HWND hWnd, LPRECT lpRect)
129{
130   RECT pRect;
131
132   GetClientRect(hWnd, &pRect);
133
134   if (lpRect->right > pRect.right)
135      lpRect->right = pRect.right;
136
137   lpRect->right = MIN(lpRect->right - GetMinimumScreenShotWindowWidth(), lpRect->right);
138
139   lpRect->left = MAX((pRect.right - (pRect.right - pRect.left)) / 2, lpRect->left);
140}
141
142void AdjustSplitter1Rect(HWND hWnd, LPRECT lpRect)
143{
144}
145
146void RecalcSplitters(void)
147{
148   int    i;
149   
150   for (i = 0; i < numSplitters; i++)
151   {
152      CalcSplitter(GetParent(splitter[i].m_hWnd), &splitter[i]);
153      nSplitterOffset[i] = splitter[i].m_dragRect.left;
154   }
155   
156   for (i = numSplitters - 1; i >= 0; i--)
157   {
158      CalcSplitter(GetParent(splitter[i].m_hWnd), &splitter[i]);
159      nSplitterOffset[i] = splitter[i].m_dragRect.left;
160   }
161
162}
163
164void OnSizeSplitter(HWND hWnd)
165{
166   static int firstTime = TRUE;
167   int changed = FALSE;
168   RECT rWindowRect;
169   POINT p = {0,0};
170   int i;
171   int nSplitterCount;
172   BOOL bMustChange;
173
174   nSplitterCount = GetSplitterCount();
175
176   if (firstTime)
177   {
178      for (i = 0; i < nSplitterCount; i++)
179         nSplitterOffset[i] = GetSplitterPos(i);
180      changed = TRUE;
181      firstTime = FALSE;
182   }
183
184   GetWindowRect(hWnd, &rWindowRect);
185
186   for (i = 0; i < nSplitterCount; i++)
187   {
188      p.x = 0;
189      p.y = 0;
190      ClientToScreen(splitter[i].m_hWnd, &p);
191
192      /* We must change if our window is not in the window rect */
193      bMustChange = !PtInRect(&rWindowRect, p);
194
195      /* We should also change if we are ahead the next splitter */
196      if ((i < nSplitterCount-1) && (nSplitterOffset[i] >= nSplitterOffset[i+1]))
197         bMustChange = TRUE;
198
199      /* ...or if we are behind the previous splitter */
200      if ((i > 0) && (nSplitterOffset[i] <= nSplitterOffset[i-1]))
201         bMustChange = TRUE;
202
203      if (bMustChange)
204      {
205         nSplitterOffset[i] = (rWindowRect.right - rWindowRect.left) * g_splitterInfo[i].dPosition;
206         changed = TRUE;
207      }
208   }
209
210   if (changed)
211   {
212      ResizePickerControls(hWnd);
213      RecalcSplitters();
214      //UpdateScreenShot();
215   }
216}
217
218void AddSplitter(HWND hWnd, HWND hWndLeft, HWND hWndRight, void (*func)(HWND hWnd,LPRECT lpRect))
219{
220   LPHZSPLITTER lpSpltr = &splitter[numSplitters];
221
222   if (numSplitters >= GetSplitterCount())
223      return;
224
225   lpSpltr->m_hWnd = hWnd;
226   lpSpltr->m_hWndLeft = hWndLeft;
227   lpSpltr->m_hWndRight = hWndRight;
228   lpSpltr->m_func = func;
229   CalcSplitter(GetParent(hWnd), lpSpltr);
230
231   numSplitters++;
232}
233
234void OnInvertTracker(HWND hWnd, const RECT *rect)
235{
236   HDC    hDC = GetDC(hWnd);
237   HBRUSH   hBrush = CreateSolidBrush(RGB(0xFF, 0xFF, 0xFF));
238   HBRUSH   hOldBrush = 0;
239
240   if (hBrush != 0)
241      hOldBrush = (HBRUSH)SelectObject(hDC, hBrush);
242   PatBlt(hDC, rect->left, rect->top, rect->right - rect->left, rect->bottom - rect->top, DSTINVERT);
243   if (hOldBrush != 0)
244      SelectObject(hDC, hOldBrush);
245   ReleaseDC(hWnd, hDC);
246   DeleteObject(hBrush);
247}
248
249void StartTracking(HWND hWnd, UINT hitArea)
250{
251   if (!bTracking && lpCurSpltr != 0 && hitArea == SPLITTER_HITITEM)
252   {
253      // Ensure we have and updated cursor structure
254      CalcSplitter(hWnd, lpCurSpltr);
255      // Draw the first splitter shadow
256      OnInvertTracker(hWnd, &lpCurSpltr->m_dragRect);
257      // Capture the mouse
258      SetCapture(hWnd);
259      // Set tracking to TRUE
260      bTracking = TRUE;
261      SetCursor(hSplitterCursor);
262   }
263}
264
265void StopTracking(HWND hWnd)
266{
267   if (bTracking)
268   {
269      // erase the tracking image
270      OnInvertTracker(hWnd, &lpCurSpltr->m_dragRect);
271      // Release the mouse
272      ReleaseCapture();
273      // set tracking to false
274      bTracking = FALSE;
275      SetCursor(LoadCursor(0, IDC_ARROW));
276      // set the new splitter position
277      nSplitterOffset[currentSplitter] = lpCurSpltr->m_dragRect.left;
278      // Redraw the screen area
279      ResizePickerControls(hWnd);
280      UpdateScreenShot();
281      InvalidateRect(GetMainWindow(),NULL,TRUE);
282   }
283}
284
285UINT SplitterHitTest(HWND hWnd, POINTS p)
286{
287   RECT  rect;
288   POINT pt;
289   int   i;
290
291   pt.x = p.x;
292   pt.y = p.y;
293
294   // Check which area we hit
295   ClientToScreen(hWnd, &pt);
296
297   for (i = 0; i < numSplitters; i++)
298   {
299      GetWindowRect(splitter[i].m_hWnd, &rect);
300      if (PtInRect(&rect, pt))
301      {
302         lpCurSpltr = &splitter[i];
303         currentSplitter = i;
304         // We hit the splitter
305         return SPLITTER_HITITEM;
306      }
307   }
308   lpCurSpltr = 0;
309   // We missed the splitter
310   return SPLITTER_HITNOTHING;
311}
312
313void OnMouseMove(HWND hWnd, UINT nFlags, POINTS p)
314{
315   if (bTracking)   // move the tracking image
316   {
317      int    nWidth;
318      RECT   rect;
319      POINT   pt;
320
321      pt.x = (int)p.x;
322      pt.y = (int)p.y;
323
324      ClientToScreen(hWnd, &pt);
325      GetWindowRect(hWnd, &rect);
326      if (! PtInRect(&rect, pt))
327      {
328         if ((short)pt.x < (short)rect.left)
329            pt.x = rect.left;
330         if ((short)pt.x > (short)rect.right)
331            pt.x = rect.right;
332         pt.y = rect.top + 1;
333      }
334
335      ScreenToClient(hWnd, &pt);
336
337      // Erase the old tracking image
338      OnInvertTracker(hWnd, &lpCurSpltr->m_dragRect);
339     
340      // calc the new one based on p.x draw it
341      nWidth = lpCurSpltr->m_dragRect.right - lpCurSpltr->m_dragRect.left;
342      lpCurSpltr->m_dragRect.right = pt.x + nWidth / 2;
343      lpCurSpltr->m_dragRect.left  = pt.x - nWidth / 2;
344
345      if (pt.x - nWidth / 2 > lpCurSpltr->m_limitRect.right)
346      {
347         lpCurSpltr->m_dragRect.right = lpCurSpltr->m_limitRect.right;
348         lpCurSpltr->m_dragRect.left  = lpCurSpltr->m_dragRect.right - nWidth;
349      }
350      if (pt.x + nWidth / 2 < lpCurSpltr->m_limitRect.left)
351      {
352         lpCurSpltr->m_dragRect.left  = lpCurSpltr->m_limitRect.left;
353         lpCurSpltr->m_dragRect.right = lpCurSpltr->m_dragRect.left + nWidth;
354      }
355      OnInvertTracker(hWnd, &lpCurSpltr->m_dragRect);
356   }
357   else
358   {
359      switch(SplitterHitTest(hWnd, p))
360      {
361      case SPLITTER_HITNOTHING:
362         SetCursor(LoadCursor(0, IDC_ARROW));
363         break;
364      case SPLITTER_HITITEM:
365         SetCursor(hSplitterCursor);
366         break;
367      }
368   }
369}
370
371void OnLButtonDown(HWND hWnd, UINT nFlags, POINTS p)
372{
373   if (!bTracking) // See if we need to start a splitter drag
374   {
375      StartTracking(hWnd, SplitterHitTest(hWnd, p));
376   }
377}
378
379void OnLButtonUp(HWND hWnd, UINT nFlags, POINTS p)
380{
381   if (bTracking)
382   {
383      StopTracking(hWnd);
384   }
385}
386
387int GetSplitterCount(void)
388{
389   int nSplitterCount = 0;
390   while(g_splitterInfo[nSplitterCount].dPosition > 0)
391      nSplitterCount++;
392   return nSplitterCount;
393}
394
395/* End of file */
src/osd/winui/directinput.c
r0r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11 ***************************************************************************/
12
13/***************************************************************************
14   
15  directinput.c
16
17  Direct Input routines.
18 
19 ***************************************************************************/
20
21#define WIN32_LEAN_AND_MEAN
22#include <windows.h>
23#include "directinput.h"
24#include "m32util.h"
25
26/***************************************************************************
27   function prototypes
28 ***************************************************************************/
29
30/***************************************************************************
31   External variables
32 ***************************************************************************/
33
34/***************************************************************************
35   Internal structures
36 ***************************************************************************/
37
38/***************************************************************************
39   Internal variables
40 ***************************************************************************/
41
42static LPDIRECTINPUT di = NULL;
43
44static HANDLE hDLL = NULL;
45
46/***************************************************************************
47   External functions   
48 ***************************************************************************/
49
50/****************************************************************************
51 *      DirectInputInitialize
52 *
53 *      Initialize the DirectInput variables.
54 *
55 *      This entails the following functions:
56 *
57 *         DirectInputCreate
58 *
59 ****************************************************************************/
60
61typedef HRESULT (WINAPI *dic_proc)(HINSTANCE hinst, DWORD dwVersion, LPDIRECTINPUT *ppDI,
62                           LPUNKNOWN punkOuter);
63
64BOOL DirectInputInitialize()
65{
66   HRESULT   hr;
67   UINT     error_mode;
68   dic_proc  dic;
69
70   if (hDLL != NULL)
71      return TRUE;
72
73   hDLL = NULL;
74
75   /* Turn off error dialog for this call */
76   error_mode = SetErrorMode(0);
77   hDLL = LoadLibrary(TEXT("dinput.dll"));
78   SetErrorMode(error_mode);
79
80   if (hDLL == NULL)
81      return FALSE;
82
83#ifdef UNICODE
84   dic = (dic_proc)GetProcAddress(hDLL, "DirectInputCreateW");
85#else
86   dic = (dic_proc)GetProcAddress(hDLL, "DirectInputCreateA");
87#endif
88   if (dic == NULL)
89      return FALSE;
90
91   hr = dic(GetModuleHandle(NULL), DIRECTINPUT_VERSION, &di, NULL);
92
93   if (FAILED(hr))
94   {
95      hr = dic(GetModuleHandle(NULL), 0x0300, &di, NULL);
96
97      if (FAILED(hr))
98      {
99         ErrorMsg("DirectInputCreate failed! error=%x\n", hr);
100         di = NULL;
101         return FALSE;
102      }
103   }
104   return TRUE;
105}
106
107/****************************************************************************
108 *
109 *      DirectInputClose
110 *
111 *      Terminate our usage of DirectInput.
112 *
113 ****************************************************************************/
114
115void DirectInputClose()
116{
117   /*
118      Release any lingering IDirectInput object.
119   */
120   if (di)
121   {
122      IDirectInput_Release(di);
123      di = NULL;
124   }
125}
126
127BOOL CALLBACK inputEnumDeviceProc(LPCDIDEVICEINSTANCE pdidi, LPVOID pv)
128{
129   GUID *pguidDevice;
130
131   /* report back the instance guid of the device we enumerated */
132   if (pv)
133   {
134      pguidDevice  = (GUID *)pv;
135      *pguidDevice = pdidi->guidInstance;
136   }
137
138   /* BUGBUG for now, stop after the first device has been found */
139   return DIENUM_STOP;
140}
141
142HRESULT SetDIDwordProperty(LPDIRECTINPUTDEVICE2 pdev, REFGUID guidProperty,
143                     DWORD dwObject, DWORD dwHow, DWORD dwValue)
144{
145   DIPROPDWORD dipdw;
146
147   dipdw.diph.dwSize      = sizeof(dipdw);
148   dipdw.diph.dwHeaderSize = sizeof(dipdw.diph);
149   dipdw.diph.dwObj      = dwObject;
150   dipdw.diph.dwHow      = dwHow;
151   dipdw.dwData         = dwValue;
152
153   return IDirectInputDevice2_SetProperty(pdev, guidProperty, &dipdw.diph);
154}
155
156LPDIRECTINPUT GetDirectInput(void)
157{
158   return di;
159}
160/***************************************************************************
161   Internal functions
162 ***************************************************************************/
src/osd/winui/bitmask.c
r0r996
1/* Bitmask.c - Bitmask support routines - MSH 11/19/1998 */
2
3#define WIN32_LEAN_AND_MEAN
4#include <windows.h>
5
6#include "bitmask.h"
7#include <stdlib.h> /* For malloc and free */
8
9/* Bit routines */
10static UCHAR maskTable[8] = {
11   0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01
12};
13
14/* Create a new LPBITS struct and return the new structure
15 * initialized to 'all bits cleared'
16 *
17 * nLength is the number of desired bits
18 */
19LPBITS NewBits(UINT nLength)
20{
21   LPBITS lpBits = 0;
22   UINT   nSize = (nLength+7) / 8;
23
24   lpBits = (LPBITS)malloc(sizeof(BITS));
25   if (lpBits)
26   {
27      lpBits->m_lpBits = (UCHAR *)malloc(nSize);
28      if (lpBits->m_lpBits)
29      {
30         memset(lpBits->m_lpBits, '\0', nSize);
31         lpBits->m_nSize = nSize;
32      }
33      else
34      {
35         free(lpBits);
36         lpBits = 0;
37      }
38   }
39
40   return lpBits;
41}
42
43void DeleteBits(LPBITS lpBits)
44{
45   if (!lpBits)
46      return;
47
48   if (lpBits->m_nSize && lpBits->m_lpBits)
49      free(lpBits->m_lpBits);
50
51   free(lpBits);
52}
53
54/* Test the 'nBit'th bit */
55BOOL TestBit(LPBITS lpBits, UINT nBit)
56{
57   UINT   offset;
58   UCHAR   mask;
59
60   if (nBit < 0 || !lpBits || !lpBits->m_lpBits)
61      return FALSE;
62
63   offset = nBit >> 3;
64
65   if (offset >= lpBits->m_nSize)
66   {
67      return FALSE;
68   }
69
70   mask = maskTable[nBit & 7];
71   return   (lpBits->m_lpBits[offset] & mask) ? TRUE : FALSE;
72}
73
74/* Set the 'nBit'th bit */
75void SetBit(LPBITS lpBits, UINT nBit)
76{
77   UINT   offset;
78   UCHAR   mask;
79
80   if (nBit < 0 || !lpBits || !lpBits->m_lpBits)
81      return;
82
83   offset = nBit >> 3;
84
85   if (offset >= lpBits->m_nSize)
86   {
87      return;
88   }
89
90   mask = maskTable[nBit & 7];
91   lpBits->m_lpBits[offset] |= mask;
92}
93
94/* Clear the 'nBit'th bit */
95void ClearBit(LPBITS lpBits, UINT nBit)
96{
97   UINT   offset;
98   UCHAR   mask;
99
100   if (nBit < 0 || !lpBits || !lpBits->m_lpBits)
101      return;
102
103   offset = nBit >> 3;
104
105   if (offset >= lpBits->m_nSize)
106   {
107      return;
108   }
109
110   mask = maskTable[nBit & 7];
111   lpBits->m_lpBits[offset] &= ~mask;
112}
113
114/* Set or Clear all bits as specified by 'bSet' */
115void SetAllBits(LPBITS lpBits, BOOL bSet)
116{
117   if (lpBits && lpBits->m_nSize != 0 && lpBits->m_lpBits)
118      memset(lpBits->m_lpBits, (!bSet) ? '\0' : '\xFF', lpBits->m_nSize);
119}
120
121/* Find next bit that matches 'bSet'
122 *
123 * 'nStartPos' specifies the bit to start search after
124 * 'bSet' specifies to search for a set or unset bit
125 *
126 * Returns -1 if no bits are found
127 */
128int FindBit(LPBITS lpBits, int nStartPos, BOOL bSet)
129{
130   UINT   end;
131   UINT   i;
132   BOOL   res;
133
134   if (!lpBits || !lpBits->m_nSize || !lpBits->m_lpBits)
135      return -1;
136
137   end = lpBits->m_nSize << 3;
138
139   if (nStartPos < 0)
140      nStartPos = 0;
141
142   for (i = nStartPos; i < end; i++)
143   {
144      res = (TestBit(lpBits, i)) ? TRUE : FALSE;
145      if ((res && bSet) || (!res && !bSet))
146         return i;
147   }
148
149   return -1;
150}
151
152/* End of source file */
src/osd/winui/resource.h
r0r996
1//{{NO_DEPENDENCIES}}
2// Microsoft Visual C++ generated include file.
3// Used by mame32.rc
4//
5#define IDPAUSE                         3
6#define IDAPPLY                         4
7#define IDS_UI_FILE                     61
8#define IDS_UI_VIEW                     62
9#define IDS_UI_OPTIONS                  63
10#define IDS_UI_HELP                     64
11#define IDS_VIEW_TOOLBAR                70
12#define IDS_VIEW_STATUSBAR              71
13#define IDS_VIEW_FOLDERLIST             72
14#define IDS_VIEW_SCREENSHOT             73
15#define IDS_VIEW_PICTURETABS            74
16#define IDS_VIEW_SPACER1                75
17#define IDS_VIEW_FULLSCREEN             76
18#define IDS_VIEW_SPACER2                77
19#define IDS_VIEW_SHOWPICTURES           78
20#define IDS_VIEW_SPACER3                79
21#define IDS_VIEW_LARGEICONS             80
22#define IDS_VIEW_SMALLICONS             81
23#define IDS_VIEW_LIST                   82
24#define IDS_VIEW_DETAILS                83
25#define IDS_VIEW_GROUPED                84
26#define IDS_VIEW_SPACER4                85
27#define IDS_VIEW_ARRANGE                86
28#define IDS_VIEW_LINEUPICONS            87
29#define IDS_VIEW_SPACER5                88
30#define IDS_VIEW_REFRESH                89
31#define IDS_VIEW_CONTEXTFILTERS         90
32#define IDS_VIEW_CUSTOMIZEFIELDS        91
33#define ID_TOOLBAR_EDIT                 92
34#define IDD_MAIN                        101
35#define IDA_TAB_KEYS                    106
36#define IDI_MAME32_ICON                 107
37#define IDD_ABOUT                       108
38#define IDR_MAIN_MENU                   109
39#define IDR_UI_MENU                     110
40#define IDW_STATUS                      112
41#define IDB_ABOUT                       113
42#define IDD_DIRECTX                     114
43#define IDD_AUDIT                       115
44#define IDD_DIRECTORIES                 116
45#define IDD_CUSTOM_FILE                 117
46#define IDR_CONTEXT_MENU                118
47#define IDI_WIN_NOROMS                  119
48#define IDI_WIN_ROMS                    120
49#define IDI_WIN_UNKNOWN                 121
50#define IDI_WIN_CLONE                   122
51#define IDI_WIN_REDX                    123
52#define IDI_FOLDER_OPEN                 124
53#define IDI_FOLDER                      125
54#define IDI_FOLDER_AVAILABLE            126
55#define IDI_FOLDER_MANUFACTURER         127
56#define IDI_FOLDER_UNAVAILABLE          128
57#define IDI_FOLDER_YEAR                 129
58#define IDI_FOLDER_SOURCE               130
59#define IDI_MANUFACTURER                131
60#define IDI_WORKING                     132
61#define IDI_NONWORKING                  133
62#define IDI_YEAR                        134
63#define IDI_SOUND                       135
64#define IDI_CPU                         136
65#define IDI_HARDDISK                    137
66#define IDI_SOURCE                      138
67#define IDI_FOLDER_HORIZONTAL           139
68#define IDI_FOLDER_VERTICAL             140
69#define IDR_CONTEXT_HEADER              151
70#define IDD_PROP_GAME                   152
71#define IDD_PROP_AUDIT                  153
72#define IDD_PROP_DISPLAY                154
73#define IDD_PROP_SOUND                  155
74#define IDD_PROP_ADVANCED               156
75#define IDD_PROP_INPUT                  157
76#define IDD_PROP_MISC                   158
77#define IDD_PROP_VECTOR                 159
78#define IDD_COLUMNS                     160
79#define IDI_KEYBOARD                    161
80#define IDI_JOYSTICK                    162
81#define IDI_DISPLAY                     163
82#define IDI_CHECKMARK                   164
83#define IDC_CURSOR_HSPLIT               165
84#define IDB_TOOLBAR                     166
85#define IDB_PROP_DISPLAY                167
86#define IDR_CONTEXT_TREE                168
87#define IDD_FILTERS                     169
88#define IDD_RESET                       170
89#define IDD_LOAD_PROGRESS               171
90#define IDD_INTERFACE_OPTIONS           173
91#define IDD_PROP_HISTORY                176
92#define IDD_ROM_ERROR                   177
93#define IDD_LANGUAGE                    178
94#define IDD_ERROR                       179
95#define IDR_CONTEXT_SCREENSHOT          181
96#define IDI_HEADER_UP                   182
97#define IDI_HEADER_DOWN                 183
98#define IDD_PROP_DIRECT3D               184
99#define IDD_PROP_CONTROLLER             185
100#define IDD_PROP_SCREEN                 187
101#define IDI_SOUNDTAB                    666
102#define IDC_LIST                        1000
103#define IDC_PLAY                        1001
104#define IDC_DISPLAYS                    1002
105#define IDC_JOYSTICK                    1003
106#define IDC_VECTORTEXT                  1004
107#define IDC_SIZES                       1005
108#define IDC_USE_TRAK                    1006
109#define IDC_DISPLAYTYPE                 1007
110#define IDC_TRAK_SENSITIVITY            1008
111#define IDC_FRAMESKIP                   1009
112#define IDC_ROTATE                      1010
113#define IDC_HELP_TEXT                   1011
114#define IDC_SCREEN                      1012
115#define IDC_TAB                         1013
116#define IDC_VIEW                        1014
117#define IDC_SCREEN2                     1015
118#define IDC_SCREENSELECT                1015
119#define IDC_CHEAT                       1016
120#define IDC_LOG                         1017
121#define IDC_ARTWORK_CROP                1018
122#define IDC_OVERLAYS                    1019
123#define IDC_BEZELS                      1021
124#define IDC_SLEEP                       1022
125#define IDC_GAMMA                       1023
126#define IDC_BRIGHTCORRECT               1024
127#define IDC_USE_DEFAULT                 1025
128#define IDC_CONTRAST                    1026
129#define IDC_SAMPLERATE                  1027
130#define IDC_NUMSCREENS                  1028
131#define IDC_ANTIALIAS                   1029
132#define IDC_BEAM                        1030
133#define IDC_FLICKER                     1031
134#define IDC_FLIPX                       1032
135#define IDC_FLIPY                       1033
136#define IDC_BACKDROPS                   1034
137#define IDC_DIRECTX_HELP                1035
138#define IDC_FLICKERDISP                 1036
139#define IDB_WEB_PAGE                    1037
140#define IDC_FSCONTRAST                  1038
141#define IDC_ROMS_PROGRESS               1039
142#define IDC_CONTRASTDISP                1040
143#define IDC_ROMS_CORRECT                1041
144#define IDC_FSCONTRASTDISP              1042
145#define IDC_ROMS_INCORRECT              1043
146#define IDC_NUMSCREENSDISP              1044
147#define IDC_ROMS_TOTAL                  1045
148#define IDC_SAMPLES_PROGRESS            1046
149#define IDC_SAMPLES_CORRECT             1047
150#define IDC_BEAMDISP                    1048
151#define IDC_SAMPLES_INCORRECT           1049
152#define IDC_SAMPLES_TOTAL               1050
153#define IDC_AUDIT_DETAILS               1051
154#define IDC_USE_FM_YM3812               1052
155#define IDC_DIR_COMBO                   1053
156#define IDC_DIR_LIST                    1054
157#define IDC_DIR_BROWSE                  1055
158#define IDC_DIR_INSERT                  1056
159#define IDC_DIR_DELETE                  1057
160#define IDC_FLICKERTEXT                 1058
161#define IDC_SSFRAME                     1059
162#define IDC_PRESCALE                    1060
163#define IDC_SSNONE                      1061
164#define IDC_SSPICTURE                   1062
165#define IDC_BEAMTEXT                    1063
166#define IDC_COLORSTEXT                  1064
167#define IDC_MULTIKEYBOARD               1065
168#define IDC_SIZETEXT                    1066
169#define IDC_TRACKSPINTEXT               1067
170#define IDC_INPUTDEVTEXT                1068
171#define IDC_RATETEXT                    1069
172#define IDC_LISTAVAILABLECOLUMNS        1070
173#define IDC_LISTSHOWCOLUMNS             1071
174#define IDC_BUTTONADD                   1072
175#define IDC_BUTTONREMOVE                1073
176#define IDC_BUTTONMOVEDOWN              1074
177#define IDC_BUTTONMOVEUP                1075
178#define IDC_PROP_SOUND                  1076
179#define IDC_PROP_CPU                    1077
180#define IDC_PROP_TITLE                  1078
181#define IDC_PROP_MANUFACTURED           1079
182#define IDC_PROP_STATUS                 1080
183#define IDC_PROP_SCREEN                 1081
184#define IDC_PROP_COLORS                 1082
185#define IDC_PROP_ROMS                   1083
186#define IDC_PROP_SAMPLES                1084
187#define IDC_PROP_CLONEOF_TEXT           1085
188#define IDC_PROP_CLONEOF                1086
189#define IDC_DEPTH                       1087
190#define IDC_VERSION                     1088
191#define IDC_ARTWORK                     1089
192#define IDC_FSGAMMA                     1090
193#define IDC_GAMMADISP                   1091
194#define IDC_FSBRIGHTNESS                1092
195#define IDC_FSGAMMADISP                 1093
196#define IDC_PRESCALEDISP                1094
197#define IDC_BRIGHTCORRECTDISP           1095
198#define IDC_FSBRIGHTNESSDISP            1096
199#define IDC_AUTOFRAMESKIP               1097
200#define IDC_TREE                        1098
201#define IDC_WINDOWED                    1099
202#define IDC_STEREO                      1100
203#define IDC_PROP_RESET                  1101
204#define IDC_SPLITTER                    1102
205#define IDC_SPLITTER2                   1103
206#define IDC_DIVIDER                     1104
207#define IDC_FILTER_VECTOR               1105
208#define IDC_FILTER_RASTER               1106
209#define IDC_FILTER_UNAVAILABLE          1107
210#define IDC_FILTER_NONWORKING           1108
211#define IDC_FILTER_CLONES               1109
212#define IDC_RESET_GAMES                 1110
213#define IDC_RESET_UI                    1111
214#define IDC_RESET_FILTERS               1112
215#define IDC_RESET_EFFECT                1113
216#define IDC_RESET_DEFAULT               1114
217#define IDC_FILTER_ORIGINALS            1115
218#define IDC_FILTER_WORKING              1116
219#define IDC_FILTER_AVAILABLE            1117
220#define IDC_CONFIGURETEXT               1118
221#define IDC_JOYMAPTEXT                  1119
222#define IDC_START_GAME_CHECK            1120
223#define IDC_VOLUME                      1121
224#define IDC_VOLUMEDISP                  1122
225#define IDC_PROP_HISTORY                1123
226#define IDC_HISTORY                     1124
227#define IDC_SAMPLES                     1125
228#define IDC_ERROR_DETAILS               1126
229#define IDC_TRIPLE_BUFFER               1127
230#define IDC_LOAD_ROMNAME                1128
231#define IDC_DEFAULT_INPUT               1129
232#define IDC_LANGUAGECHECK               1130
233#define IDC_LANGUAGEBROWSE              1131
234#define IDC_LANGUAGEEDIT                1132
235#define IDC_FILTER_EDIT                 1133
236#define IDC_ABOUT                       1134
237#define IDC_PROP_DISPLAY                1135
238#define IDC_USE_SOUND                   1136
239#define IDC_WAITVSYNC                   1137
240#define IDC_HWSTRETCH                   1138
241#define IDC_SWITCHRES                   1139
242#define IDC_MAXIMIZE                    1140
243#define IDC_KEEPASPECT                  1141
244#define IDC_SYNCREFRESH                 1142
245#define IDC_USE_MOUSE                   1143
246#define IDC_THROTTLE                    1144
247#define IDC_VOLUMETEXT                  1146
248#define IDC_REFRESH                     1148
249#define IDC_REFRESHTEXT                 1149
250#define IDC_EFFECT                      1150
251#define IDC_FSGAMMATEXT                 1151
252#define IDC_STEADYKEY                   1152
253#define IDC_ASPECTRATIO                 1153
254#define IDC_ASPECTRATION                1154
255#define IDC_ASPECTRATIOD                1155
256#define IDC_ASPECTRATIOTEXT             1156
257#define IDC_JOY_GUI                     1157
258#define IDC_BROADCAST                   1158
259#define IDC_JDZ                         1159
260#define IDC_JDZDISP                     1160
261#define IDC_JDZTEXT                     1161
262#define IDC_JSATTEXT                    1162
263#define IDC_JSAT                        1163
264#define IDC_JSATDISP                    1164
265#define IDC_AUDIO_LATENCY_DISP          1165
266#define IDC_PLAY_GAME                   1166
267#define IDC_LIGHTGUN                    1167
268#define IDC_SSTAB                       1168
269#define IDC_GAME_ICON                   1169
270#define IDC_RANDOM_BG                   1170
271#define IDC_CUSTOM_TREE                 1171
272#define IDC_CUSTOMFILEBROWSE            1172
273#define IDC_CUSTOMFILE_GAME             1173
274#define IDC_LOAD_STATUS                 1174
275#define IDC_ERROR_TEXT                  1175
276#define IDC_ARTMISCTEXT                 1176
277#define IDC_ENABLE_AUTOSAVE             1177
278#define IDC_SKIP_GAME_INFO              1178
279#define IDC_PROP_SOURCE                 1179
280#define IDC_FILTER_HORIZONTAL           1180
281#define IDC_PAUSEBRIGHT                 1181
282#define IDC_PAUSEBRIGHTDISP             1182
283#define IDC_HIGH_PRIORITY               1183
284#define IDC_D3D_FILTER                  1184
285#define IDC_HIDE_MOUSE                  1185
286#define IDC_AUDIO_LATENCY               1186
287#define IDC_D3D_VERSION                 1187
288#define IDC_AUDIT_DETAILS_PROP          1188
289#define IDC_CYCLETIME                   1189
290#define IDC_CYCLETIMESEC                1190
291#define IDC_AUDIO_LATENCY_TEXT          1191
292#define IDC_STRETCH_SCREENSHOT_LARGER   1192
293#define IDC_FILTER_INHERIT              1193
294#define IDC_RESET_PLAYTIME              1194
295#define IDC_RESET_PLAYCOUNT             1195
296#define IDC_INHERITED                   1196
297#define IDC_KEY_GUI                     1197
298#define IDC_RELOAD                      1198
299#define IDC_DUAL_LIGHTGUN               1199
300#define IDC_NOOFFSET_CLONES             1200
301#define IDC_BIOS                        1201
302#define IDC_HISTORY_TAB                 1202
303#define IDC_GAME_CAPTION                1203
304#define IDC_SCREENSHOT_BORDERSIZE       1204
305#define IDC_SCREENSHOT_BORDERCOLOR      1205
306#define IDC_CYCLETIMESECTXT             1206
307#define IDC_SCREENSHOT_BORDERSIZETXT    1207
308#define IDC_PADDLE                      1208
309#define IDC_ADSTICK                     1209
310#define IDC_PEDAL                       1210
311#define IDC_DIAL                        1211
312#define IDC_TRACKBALL                   1212
313#define IDC_LIGHTGUNDEVICE              1213
314#define IDC_MOUSE                       1214
315#define IDC_POSITIONAL                  1215
316#define IDC_POSITIONALDEVICE            1215
317#define IDC_HIGH_PRIORITY_TEXT          1216
318#define IDC_HIGH_PRIORITYTXT            1217
319#define IDC_SELECT_EFFECT               1218
320#define IDC_MULTITHREAD_RENDERING       1219
321#define IDC_ASPECT                      1220
322#define IDC_RESOLUTION                  1221
323#define IDC_LOAD_PROGRESS               1223
324#define IDC_FSBRIGHTNESSTEXT            1224
325#define IDC_FSCONTRASTTEXT              1225
326#define IDC_VIDEO_MODE                  1226
327#define IDC_SCREENSELECTTEXT            1227
328#define IDC_CHECK2                      1229
329#define IDC_MULTIMOUSE                  1230
330#define IDC_DEBUG                       1231
331#define IDC_REFRESHSPEED                1232
332#define IDC_SPEEDTEXT                   1233
333#define IDC_SPEED                       1234
334#define IDC_SPEEDDISP                   1235
335#define IDC_FILTER_VERTICAL             1236
336#define ID_CONTEXT_SHOW_FOLDER_START    39000
337#define ID_CONTEXT_SHOW_FOLDER_END      39200
338#define ID_FILE_EXIT                    40001
339#define ID_ABOUT                        40003
340#define ID_FILE_PLAY                    40004
341#define ID_HELP_ABOUT                   40006
342#define ID_VIEW_LARGE_ICON              40007
343#define ID_VIEW_SMALL_ICON              40008
344#define ID_VIEW_LIST_MENU               40009
345#define ID_VIEW_DETAIL                  40010
346#define ID_VIEW_GROUPED                 40011
347#define ID_OPTIONS_FONT                 40012
348#define ID_OPTIONS_CLONE_COLOR          40013
349#define ID_OPTIONS_DIR                  40014
350#define ID_OPTIONS_DEFAULTS             40015
351#define ID_OPTIONS_RESET_DEFAULTS       40016
352#define ID_OPTIONS_INTERFACE            40017
353#define ID_FILE_AUDIT                   40018
354#define ID_FILE_PLAY_RECORD             40019
355#define ID_FILE_PLAY_BACK               40020
356#define ID_FILE_PLAY_RECORD_WAVE        40021
357#define ID_FILE_PLAY_RECORD_MNG         40022
358#define ID_VIEW_PICTURE_AREA            40023
359#define ID_HELP_CONTENTS                40025
360#define ID_HELP_WHATS_NEW32             40026
361#define ID_HELP_TROUBLE                 40027
362#define ID_HELP_RELEASE                 40028
363#define ID_HELP_WHATS_NEW               40029
364#define ID_HELP_CHEATS                  40030
365#define ID_VIEW_BYGAME                  40034
366#define ID_VIEW_BYDIRECTORY             40035
367#define ID_VIEW_BYMANUFACTURER          40036
368#define ID_VIEW_BYYEAR                  40037
369#define ID_VIEW_BYTYPE                  40038
370#define ID_VIEW_BYTIMESPLAYED           40039
371#define ID_VIEW_LINEUPICONS             40040
372#define ID_UPDATE_GAMELIST              40042
373#define ID_SORT_ASCENDING               40045
374#define ID_SORT_DESCENDING              40046
375#define ID_CUSTOMIZE_FIELDS             40048
376#define ID_GAME_PROPERTIES              40049
377#define ID_VIEW_PAGETAB                 40050
378#define ID_VIEW_FOLDERS                 40051
379#define ID_VIEW_TOOLBARS                40052
380#define ID_VIEW_STATUS                  40053
381#define ID_CONTEXT_FILTERS              40054
382#define ID_CONTEXT_RENAME_CUSTOM        40055
383#define ID_CONTEXT_ADD_CUSTOM           40057
384#define ID_CONTEXT_REMOVE_CUSTOM        40058
385#define ID_GAME_AUDIT                   40059
386#define ID_CONTEXT_SELECT_RANDOM        40060
387#define ID_OPTIONS_LANGUAGE             40061
388#define ID_VIEW_TAB_SCREENSHOT          40062
389#define ID_VIEW_TAB_FLYER               40063
390#define ID_VIEW_TAB_CABINET             40064
391#define ID_VIEW_TAB_MARQUEE             40065
392#define ID_VIEW_TAB_TITLE               40066
393#define ID_VIEW_TAB_CONTROL_PANEL       40067
394#define ID_VIEW_TAB_PCB                 40068
395#define ID_VIEW_TAB_HISTORY             40069
396#define ID_OPTIONS_BG                   40070
397#define ID_TOGGLE_TAB_SCREENSHOT        40071
398#define ID_TOGGLE_TAB_FLYER             40072
399#define ID_TOGGLE_TAB_CABINET           40073
400#define ID_TOGGLE_TAB_MARQUEE           40074
401#define ID_TOGGLE_TAB_TITLE             40075
402#define ID_TOGGLE_TAB_CONTROL_PANEL     40076
403#define ID_TOGGLE_TAB_PCB               40077
404#define ID_TOGGLE_TAB_HISTORY           40078
405#define ID_VIEW_FULLSCREEN              40079
406#define ID_CONTEXT_RESET_PLAYTIME       40080
407#define ID_CONTEXT_RESET_PLAYCOUNT      40081
408#define ID_FOLDER_PROPERTIES            40082
409#define ID_FOLDER_AUDIT                 40083
410#define ID_UI_UP                        40084
411#define ID_UI_DOWN                      40085
412#define ID_UI_LEFT                      40086
413#define ID_UI_RIGHT                     40087
414#define ID_UI_START                     40088
415#define ID_UI_PGUP                      40089
416#define ID_UI_PGDOWN                    40090
417#define ID_UI_HOME                      40091
418#define ID_UI_END                       40092
419#define ID_UI_HISTORY_UP                40093
420#define ID_UI_HISTORY_DOWN              40094
421#define ID_FILE_LOADSTATE               40095
422#define ID_FOLDER_SOURCEPROPERTIES      40096
423#define ID_FOLDER_VECTORPROPERTIES      40097
424#define ID_ARRANGE_ICONS                40098
425#define IDC_STATIC                      -1
426
427// Next default values for new objects
428//
429#ifdef APSTUDIO_INVOKED
430#ifndef APSTUDIO_READONLY_SYMBOLS
431#define _APS_NO_MFC                     1
432#define _APS_3D_CONTROLS                     1
433#define _APS_NEXT_RESOURCE_VALUE        188
434#define _APS_NEXT_COMMAND_VALUE         40099
435#define _APS_NEXT_CONTROL_VALUE         1237
436#define _APS_NEXT_SYMED_VALUE           93
437#endif
438#endif
src/osd/winui/splitters.h
r0r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Splitter Code (C) 1998 Mike Haaland <mhaaland@hypertech.com>
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11 ***************************************************************************/
12
13/* Written by Mike Haaland <mhaaland@hypertech.com> */
14
15#ifndef SPLITTER_H
16#define SPLITTER_H
17
18#if !defined(MAX)
19#define MIN(a, b) ((a) < (b) ? (a) : (b))
20#define MAX(a, b) ((a) > (b) ? (a) : (b))
21#endif
22
23enum eSplitterHits
24{
25   SPLITTER_HITNOTHING = 0,
26   SPLITTER_HITITEM
27};
28
29typedef struct horzSplitter
30{
31   HWND m_hWnd;
32   HWND m_hWndLeft;
33   HWND m_hWndRight;
34   RECT m_limitRect;
35   RECT m_dragRect;
36   void (*m_func)(HWND hWnd, LPRECT lpRect);
37} HZSPLITTER, *LPHZSPLITTER;
38
39/* Splitter routines */
40void    OnMouseMove(HWND hWnd, UINT nFlags, POINTS p);
41void    OnLButtonDown(HWND hWnd, UINT nFlags, POINTS p);
42void    OnLButtonUp(HWND hWnd, UINT nFlags, POINTS p);
43void    OnSizeSplitter(HWND hWnd);
44void    AddSplitter(HWND hWnd, HWND hWndLeft, HWND hWndRight,
45                    void (*func)(HWND hWnd,LPRECT lpRect));
46void    RecalcSplitters(void);
47void    AdjustSplitter2Rect(HWND hWnd, LPRECT lpRect);
48void    AdjustSplitter1Rect(HWND hWnd, LPRECT lpRect);
49BOOL    InitSplitters(void);
50void    SplittersExit(void);
51int     GetSplitterCount(void);
52
53extern int *nSplitterOffset;
54
55typedef struct
56{
57   double dPosition;
58   int nSplitterWindow;
59   int nLeftWindow;
60   int nRightWindow;
61   void (*pfnAdjust)(HWND hWnd,LPRECT lpRect);
62} SPLITTERINFO;
63
64extern const SPLITTERINFO g_splitterInfo[];
65
66
67#endif /* SPLITTER_H */
src/osd/winui/directinput.h
r0r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5 
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11 ***************************************************************************/
12
13#ifndef DIRECTINPUT_H
14#define DIRECTINPUT_H
15
16#ifndef DIRECTINPUT_VERSION
17#define DIRECTINPUT_VERSION 0x0700
18#endif
19
20#include <dinput.h>
21
22extern BOOL DirectInputInitialize(void);
23extern void DirectInputClose(void);
24
25extern BOOL CALLBACK inputEnumDeviceProc(LPCDIDEVICEINSTANCE pdidi, LPVOID pv);
26
27extern HRESULT SetDIDwordProperty(LPDIRECTINPUTDEVICE2 pdev, REFGUID guidProperty,
28                          DWORD dwObject, DWORD dwHow, DWORD dwValue);
29
30LPDIRECTINPUT GetDirectInput(void);
31
32#endif
src/osd/winui/bitmask.h
r0r996
1#ifndef BITMASK_H
2#define BITMASK_H
3
4/* Bit array type */
5typedef struct
6{
7   UINT   m_nSize;
8   UCHAR*   m_lpBits;
9} BITS, * LPBITS;
10
11/* Bit functions */
12LPBITS   NewBits(UINT nLength /* in bits */);
13void   DeleteBits(LPBITS lpBits);
14BOOL   TestBit(LPBITS lpBits, UINT nBit);
15void   SetBit(LPBITS lpBits, UINT nBit);
16void   ClearBit(LPBITS lpBits, UINT nBit);
17void   SetAllBits(LPBITS lpBits, BOOL bSet);
18int    FindBit(LPBITS lpBits, int nStartPos, BOOL bSet);
19
20/* Linked list type */
21typedef struct
22{
23   LPVOID  data;
24   LPVOID  next;
25   LPVOID  prev;
26} NODE, * LPNODE;
27
28/* Linked list functions */
29
30#endif /* BITMASK_H */
src/osd/winui/dirwatch.c
r0r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11 ***************************************************************************/
12
13#include <windows.h>
14#include <string.h>
15#include <tchar.h>
16#include "dirwatch.h"
17#include "m32util.h"
18#include "strconv.h"
19
20typedef BOOL (WINAPI *READDIRECTORYCHANGESFUNC)(HANDLE hDirectory, LPVOID lpBuffer,
21      DWORD nBufferLength, BOOL bWatchSubtree, DWORD dwNotifyFilter,
22      LPDWORD lpBytesReturned, LPOVERLAPPED lpOverlapped,
23      LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine);
24
25
26struct DirWatcherEntry
27{
28   struct DirWatcherEntry *pNext;
29   HANDLE hDir;
30   WORD nIndex;
31   WORD nSubIndex;
32   BOOL bWatchSubtree;
33   OVERLAPPED overlapped;
34
35   union
36   {
37      FILE_NOTIFY_INFORMATION notify;
38      BYTE buffer[1024];
39   } u;
40
41   char szDirPath[1];
42};
43
44
45
46struct DirWatcher
47{
48   HMODULE hKernelModule;
49   READDIRECTORYCHANGESFUNC pfnReadDirectoryChanges;
50   
51   HWND hwndTarget;
52   UINT nMessage;
53
54   HANDLE hRequestEvent;
55   HANDLE hResponseEvent;
56   HANDLE hThread;
57   CRITICAL_SECTION crit;
58   struct DirWatcherEntry *pEntries;
59
60   // These are posted externally
61   BOOL bQuit;
62   BOOL bWatchSubtree;
63   WORD nIndex;
64   LPCSTR pszPathList;
65};
66
67
68
69static void DirWatcher_SetupWatch(PDIRWATCHER pWatcher, struct DirWatcherEntry *pEntry)
70{
71   DWORD nDummy;
72
73   memset(&pEntry->u, 0, sizeof(pEntry->u));
74
75   pWatcher->pfnReadDirectoryChanges(pEntry->hDir,
76      &pEntry->u,
77      sizeof(pEntry->u),
78      pEntry->bWatchSubtree,
79      FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_LAST_WRITE | FILE_NOTIFY_CHANGE_SIZE,
80      &nDummy,
81      &pEntry->overlapped,
82      NULL);
83}
84
85
86
87static void DirWatcher_FreeEntry(struct DirWatcherEntry *pEntry)
88{
89   if (pEntry->hDir)
90      CloseHandle(pEntry->hDir);
91   free(pEntry);
92}
93
94
95
96static BOOL DirWatcher_WatchDirectory(PDIRWATCHER pWatcher, int nIndex, int nSubIndex,
97   LPCSTR pszPath, BOOL bWatchSubtree)
98{
99   struct DirWatcherEntry *pEntry;
100   HANDLE hDir;
101
102   pEntry = malloc(sizeof(*pEntry) + strlen(pszPath));
103   if (!pEntry)
104      goto error;
105   memset(pEntry, 0, sizeof(*pEntry));
106   strcpy(pEntry->szDirPath, pszPath);
107   pEntry->overlapped.hEvent = pWatcher->hRequestEvent;
108
109   hDir = win_create_file_utf8(pszPath, FILE_LIST_DIRECTORY,
110      FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
111      NULL, OPEN_EXISTING,
112      FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED, NULL);
113   if (!hDir || (hDir == INVALID_HANDLE_VALUE))
114      goto error;
115
116   // Populate the entry
117   pEntry->hDir = hDir;
118   pEntry->bWatchSubtree = bWatchSubtree;
119   pEntry->nIndex = nIndex;
120   pEntry->nSubIndex = nSubIndex;
121
122   // Link in the entry
123   pEntry->pNext = pWatcher->pEntries;
124   pWatcher->pEntries = pEntry;
125
126   DirWatcher_SetupWatch(pWatcher, pEntry);
127   return TRUE;
128
129error:
130   if (pEntry)
131      DirWatcher_FreeEntry(pEntry);
132   return FALSE;
133}
134
135
136
137static void DirWatcher_Signal(PDIRWATCHER pWatcher, struct DirWatcherEntry *pEntry)
138{
139   LPSTR pszFileName;
140   LPSTR pszFullFileName;
141   BOOL bPause;
142   HANDLE hFile;
143   int nTries;
144   TCHAR* t_filename;
145
146   {
147      int nLength;
148      nLength = WideCharToMultiByte(CP_ACP, 0, pEntry->u.notify.FileName, -1, NULL, 0, NULL, NULL);
149      pszFileName = (LPSTR) alloca(nLength * sizeof(*pszFileName));
150      WideCharToMultiByte(CP_ACP, 0, pEntry->u.notify.FileName, -1, pszFileName, nLength, NULL, NULL);
151   }
152
153   // get the full path to this new file
154   pszFullFileName = (LPSTR) alloca(strlen(pEntry->szDirPath) + strlen(pszFileName) + 2);
155   strcpy(pszFullFileName, pEntry->szDirPath);
156   strcat(pszFullFileName, "\\");
157   strcat(pszFullFileName, pszFileName);
158
159   // attempt to busy wait until any result other than ERROR_SHARING_VIOLATION
160   // is generated
161   nTries = 100;
162   do
163   {
164      hFile = win_create_file_utf8(pszFullFileName, GENERIC_READ,
165         FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
166      if (hFile != INVALID_HANDLE_VALUE)
167         CloseHandle(hFile);
168
169      bPause = (nTries--) && (hFile == INVALID_HANDLE_VALUE)
170         && (GetLastError() == ERROR_SHARING_VIOLATION);
171      if (bPause)
172         Sleep(10);
173   }
174   while(bPause);
175
176   // send the message (assuming that we have a target)
177   if (pWatcher->hwndTarget)
178   {
179      t_filename = tstring_from_utf8(pszFileName);
180      if( !t_filename )
181         return;
182      SendMessage(pWatcher->hwndTarget,
183         pWatcher->nMessage,
184         (pEntry->nIndex << 16) | (pEntry->nSubIndex << 0),
185         (LPARAM)(LPCTSTR) win_tstring_strdup(t_filename));
186      free(t_filename);
187   }
188
189   DirWatcher_SetupWatch(pWatcher, pEntry);
190}
191
192
193
194static DWORD WINAPI DirWatcher_ThreadProc(LPVOID lpParameter)
195{
196   LPSTR pszPathList;
197   LPSTR s;
198   int nSubIndex;
199   PDIRWATCHER pWatcher = (PDIRWATCHER) lpParameter;
200   struct DirWatcherEntry *pEntry;
201   struct DirWatcherEntry **ppEntry;
202
203   do
204   {
205      WaitForSingleObject(pWatcher->hRequestEvent, INFINITE);
206
207      if (pWatcher->pszPathList)
208      {
209         // remove any entries with the same nIndex
210         ppEntry = &pWatcher->pEntries;
211         while(*ppEntry)
212         {
213            if ((*ppEntry)->nIndex == pWatcher->nIndex)
214            {
215               pEntry = *ppEntry;
216               *ppEntry = pEntry->pNext;
217               DirWatcher_FreeEntry(pEntry);
218            }
219            else
220            {
221               ppEntry = &(*ppEntry)->pNext;
222            }
223         }
224
225         // allocate our own copy of the path list
226         pszPathList = (LPSTR) alloca(strlen(pWatcher->pszPathList) + 1);
227         strcpy(pszPathList, pWatcher->pszPathList);
228         
229         nSubIndex = 0;
230         do
231         {
232            s = strchr(pszPathList, ';');
233            if (s)
234               *s = '\0';
235
236            if (*pszPathList)
237            {
238               DirWatcher_WatchDirectory(pWatcher, pWatcher->nIndex,
239                  nSubIndex++, pszPathList, pWatcher->bWatchSubtree);
240            }
241
242            pszPathList = s ? s + 1 : NULL;
243         }
244         while(pszPathList);
245
246         pWatcher->pszPathList = NULL;
247         pWatcher->bWatchSubtree = FALSE;
248      }
249      else
250      {
251         // we have to go through the list and find what has been hit
252         for (pEntry = pWatcher->pEntries; pEntry; pEntry = pEntry->pNext)
253         {
254            if (pEntry->u.notify.Action != 0)
255            {
256               DirWatcher_Signal(pWatcher, pEntry);
257            }
258         }
259      }
260
261      SetEvent(pWatcher->hResponseEvent);
262   }
263   while(!pWatcher->bQuit);
264   return 0;
265}
266
267
268
269PDIRWATCHER DirWatcher_Init(HWND hwndTarget, UINT nMessage)
270{
271   struct DirWatcher *pWatcher = NULL;
272   DWORD nThreadID;
273
274   // This feature does not exist on Win9x
275   if (GetVersion() >= 0x80000000)
276      goto error;
277
278   pWatcher = malloc(sizeof(struct DirWatcher));
279   if (!pWatcher)
280      goto error;
281   memset(pWatcher, 0, sizeof(*pWatcher));
282   InitializeCriticalSection(&pWatcher->crit);
283
284   pWatcher->hKernelModule = LoadLibrary(TEXT("kernel32.dll"));
285   if (!pWatcher->hKernelModule)
286      goto error;
287
288   pWatcher->pfnReadDirectoryChanges = (READDIRECTORYCHANGESFUNC)
289      GetProcAddress(pWatcher->hKernelModule, "ReadDirectoryChangesW");
290   if (!pWatcher->pfnReadDirectoryChanges)
291      goto error;
292
293   pWatcher->hRequestEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
294   if (!pWatcher->hRequestEvent)
295      goto error;
296
297   pWatcher->hResponseEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
298   if (!pWatcher->hRequestEvent)
299      goto error;
300
301   pWatcher->hThread = CreateThread(NULL, 0, DirWatcher_ThreadProc,
302      (LPVOID) pWatcher, 0, &nThreadID);
303
304   pWatcher->hwndTarget = hwndTarget;
305   pWatcher->nMessage = nMessage;
306   return pWatcher;
307
308error:
309   if (pWatcher)
310      DirWatcher_Free(pWatcher);
311   return NULL;
312}
313
314
315
316BOOL DirWatcher_Watch(PDIRWATCHER pWatcher, WORD nIndex, LPCSTR pszPathList, BOOL bWatchSubtrees)
317{
318   EnterCriticalSection(&pWatcher->crit);
319
320   pWatcher->nIndex = nIndex;
321   pWatcher->pszPathList = pszPathList;
322   pWatcher->bWatchSubtree = bWatchSubtrees;
323   SetEvent(pWatcher->hRequestEvent);
324
325   WaitForSingleObject(pWatcher->hResponseEvent, INFINITE);
326   LeaveCriticalSection(&pWatcher->crit);
327   return TRUE;
328}
329
330
331
332void DirWatcher_Free(PDIRWATCHER pWatcher)
333{
334   struct DirWatcherEntry *pEntry;
335   struct DirWatcherEntry *pNextEntry;
336
337   if (pWatcher->hThread)
338   {
339      EnterCriticalSection(&pWatcher->crit);
340      pWatcher->bQuit = TRUE;
341      SetEvent(pWatcher->hRequestEvent);
342      WaitForSingleObject(pWatcher->hThread, 1000);
343      LeaveCriticalSection(&pWatcher->crit);
344      CloseHandle(pWatcher->hThread);
345   }
346
347   DeleteCriticalSection(&pWatcher->crit);
348
349   pEntry = pWatcher->pEntries;
350   while(pEntry)
351   {
352      pNextEntry = pEntry->pNext;
353      DirWatcher_FreeEntry(pEntry);
354      pEntry = pNextEntry;
355   }
356
357   if (pWatcher->hKernelModule)
358      FreeLibrary(pWatcher->hKernelModule);
359   if (pWatcher->hRequestEvent)
360      CloseHandle(pWatcher->hRequestEvent);
361   if (pWatcher->hResponseEvent)
362      CloseHandle(pWatcher->hResponseEvent);
363   free(pWatcher);
364}
365
366
367
src/osd/winui/m32main.c
r0r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11***************************************************************************/
12
13#define WINUI
14
15// import the main() from MAME, but rename it so we can call it indirectly
16#undef main
17#define main mame_main
18#include "windows/main.c"
19#undef main
20
21#include "screenshot.h"
22#include "win32ui.h"
23
24
25int WINAPI WinMain(HINSTANCE    hInstance,
26                   HINSTANCE    hPrevInstance,
27                   LPSTR        lpCmdLine,
28                   int          nCmdShow)
29{
30   return Mame32Main(hInstance, lpCmdLine, nCmdShow);
31}
src/osd/winui/m32opts.c
r0r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11 ***************************************************************************/
12 
13 /***************************************************************************
14
15  m32opts.c
16
17  Stores global options and per-game options;
18
19***************************************************************************/
20
21#define WIN32_LEAN_AND_MEAN
22
23#include <windows.h>
24#include <windowsx.h>
25#include <winreg.h>
26#include <commctrl.h>
27#include <assert.h>
28#include <stdio.h>
29#include <sys/stat.h>
30#include <math.h>
31#include <direct.h>
32#include <driver.h>
33#include <stddef.h>
34#include <tchar.h>
35
36#include "screenshot.h"
37#include "bitmask.h"
38#include "mame32.h"
39#include "m32util.h"
40#include "resource.h"
41#include "treeview.h"
42#include "file.h"
43#include "splitters.h"
44#include "dijoystick.h"
45#include "audit.h"
46#include "m32opts.h"
47#include "picker.h"
48#include "winmain.h"
49#include "windows/winutf8.h"
50#include "windows/strconv.h"
51#include "astring.h"
52
53#ifdef MESS
54#include "optionsms.h"
55#endif // MESS
56
57#ifdef _MSC_VER
58#define snprintf _snprintf
59#endif
60
61/***************************************************************************
62    Internal function prototypes
63 ***************************************************************************/
64
65// static void LoadFolderFilter(int folder_index,int filters);
66
67static file_error LoadSettingsFile(core_options *opts, const char *filename);
68static file_error SaveSettingsFile(core_options *opts, const char *filename);
69
70static void LoadOptionsAndSettings(void);
71
72static void  CusColorEncodeString(const COLORREF *value, char* str);
73static void  CusColorDecodeString(const char* str, COLORREF *value);
74
75static void  SplitterEncodeString(const int *value, char* str);
76static void  SplitterDecodeString(const char *str, int *value);
77
78static void  FontEncodeString(const LOGFONT *f, char *str);
79static void  FontDecodeString(const char* str, LOGFONT *f);
80
81static void TabFlagsEncodeString(int data, char *str);
82static void TabFlagsDecodeString(const char *str, int *data);
83
84static DWORD DecodeFolderFlags(const char *buf);
85static const char * EncodeFolderFlags(DWORD value);
86
87static void ResetToDefaults(core_options *opts, int priority);
88
89static void ui_parse_ini_file(core_options *opts, const char *name);
90static BOOL add_options_entry(core_options *opts, const options_entry *entry);
91static core_options * options_prune(core_options *opts1, core_options *opts2);
92static void remove_all_source_options(void);
93
94
95#ifdef _MSC_VER
96#define snprintf _snprintf
97#endif
98
99/***************************************************************************
100    Internal defines
101 ***************************************************************************/
102
103#define UI_INI_FILENAME MAME32NAME "ui.ini"
104#define DEFAULT_OPTIONS_INI_FILENAME CONFIGNAME ".ini"
105
106#define M32OPTION_LIST_MODE                  "list_mode"
107#define M32OPTION_CHECK_GAME               "check_game"
108#define M32OPTION_JOYSTICK_IN_INTERFACE         "joystick_in_interface"
109#define M32OPTION_KEYBOARD_IN_INTERFACE         "keyboard_in_interface"
110#define M32OPTION_CYCLE_SCREENSHOT            "cycle_screenshot"
111#define M32OPTION_STRETCH_SCREENSHOT_LARGER      "stretch_screenshot_larger"
112#define M32OPTION_SCREENSHOT_BORDER_SIZE      "screenshot_bordersize"
113#define M32OPTION_SCREENSHOT_BORDER_COLOR      "screenshot_bordercolor"
114#define M32OPTION_INHERIT_FILTER            "inherit_filter"
115#define M32OPTION_OFFSET_CLONES               "offset_clones"
116#define M32OPTION_GAME_CAPTION               "game_caption"
117#define M32OPTION_BROADCAST_GAME_NAME         "broadcast_game_name"
118#define M32OPTION_RANDOM_BACKGROUND            "random_background"
119#define M32OPTION_DEFAULT_FOLDER_ID            "default_folder_id"
120#define M32OPTION_SHOW_IMAGE_SECTION         "show_image_section"
121#define M32OPTION_SHOW_FOLDER_SECTION         "show_folder_section"
122#define M32OPTION_HIDE_FOLDERS               "hide_folders"
123#define M32OPTION_SHOW_STATUS_BAR            "show_status_bar"
124#define M32OPTION_SHOW_TABS                  "show_tabs"
125#define M32OPTION_SHOW_TOOLBAR               "show_tool_bar"
126#define M32OPTION_CURRENT_TAB               "current_tab"
127#define M32OPTION_WINDOW_X                  "window_x"
128#define M32OPTION_WINDOW_Y                  "window_y"
129#define M32OPTION_WINDOW_WIDTH               "window_width"
130#define M32OPTION_WINDOW_HEIGHT               "window_height"
131#define M32OPTION_WINDOW_STATE               "window_state"
132#define M32OPTION_CUSTOM_COLOR               "custom_color"
133#define M32OPTION_LIST_FONT                  "list_font"
134#define M32OPTION_TEXT_COLOR               "text_color"
135#define M32OPTION_CLONE_COLOR               "clone_color"
136#define M32OPTION_HIDE_TABS                  "hide_tabs"
137#define M32OPTION_HISTORY_TAB               "history_tab"
138#define M32OPTION_COLUMN_WIDTHS               "column_widths"
139#define M32OPTION_COLUMN_ORDER               "column_order"
140#define M32OPTION_COLUMN_SHOWN               "column_shown"
141#define M32OPTION_SPLITTERS                  "splitters"
142#define M32OPTION_SORT_COLUMN               "sort_column"
143#define M32OPTION_SORT_REVERSED               "sort_reversed"
144#define M32OPTION_LANGUAGE                  "language"
145#define M32OPTION_FLYER_DIRECTORY            "flyer_directory"
146#define M32OPTION_CABINET_DIRECTORY            "cabinet_directory"
147#define M32OPTION_MARQUEE_DIRECTORY            "marquee_directory"
148#define M32OPTION_TITLE_DIRECTORY            "title_directory"
149#define M32OPTION_CPANEL_DIRECTORY            "cpanel_directory"
150#define M32OPTION_PCB_DIRECTORY                "pcb_directory"
151#define M32OPTION_ICONS_DIRECTORY            "icons_directory"
152#define M32OPTION_BACKGROUND_DIRECTORY         "background_directory"
153#define M32OPTION_FOLDER_DIRECTORY            "folder_directory"
154#define M32OPTION_UI_KEY_UP                  "ui_key_up"
155#define M32OPTION_UI_KEY_DOWN               "ui_key_down"
156#define M32OPTION_UI_KEY_LEFT               "ui_key_left"
157#define M32OPTION_UI_KEY_RIGHT               "ui_key_right"
158#define M32OPTION_UI_KEY_START               "ui_key_start"
159#define M32OPTION_UI_KEY_PGUP               "ui_key_pgup"
160#define M32OPTION_UI_KEY_PGDWN               "ui_key_pgdwn"
161#define M32OPTION_UI_KEY_HOME               "ui_key_home"
162#define M32OPTION_UI_KEY_END               "ui_key_end"
163#define M32OPTION_UI_KEY_SS_CHANGE            "ui_key_ss_change"
164#define M32OPTION_UI_KEY_HISTORY_UP            "ui_key_history_up"
165#define M32OPTION_UI_KEY_HISTORY_DOWN         "ui_key_history_down"
166#define M32OPTION_UI_KEY_CONTEXT_FILTERS      "ui_key_context_filters"
167#define M32OPTION_UI_KEY_SELECT_RANDOM         "ui_key_select_random"
168#define M32OPTION_UI_KEY_GAME_AUDIT            "ui_key_game_audit"
169#define M32OPTION_UI_KEY_GAME_PROPERTIES      "ui_key_game_properties"
170#define M32OPTION_UI_KEY_HELP_CONTENTS         "ui_key_help_contents"
171#define M32OPTION_UI_KEY_UPDATE_GAMELIST      "ui_key_update_gamelist"
172#define M32OPTION_UI_KEY_VIEW_FOLDERS         "ui_key_view_folders"
173#define M32OPTION_UI_KEY_VIEW_FULLSCREEN      "ui_key_view_fullscreen"
174#define M32OPTION_UI_KEY_VIEW_PAGETAB         "ui_key_view_pagetab"
175#define M32OPTION_UI_KEY_VIEW_PICTURE_AREA      "ui_key_view_picture_area"
176#define M32OPTION_UI_KEY_VIEW_STATUS         "ui_key_view_status"
177#define M32OPTION_UI_KEY_VIEW_TOOLBARS         "ui_key_view_toolbars"
178#define M32OPTION_UI_KEY_VIEW_TAB_CABINET      "ui_key_view_tab_cabinet"
179#define M32OPTION_UI_KEY_VIEW_TAB_CPANEL      "ui_key_view_tab_cpanel"
180#define M32OPTION_UI_KEY_VIEW_TAB_FLYER         "ui_key_view_tab_flyer"
181#define M32OPTION_UI_KEY_VIEW_TAB_HISTORY      "ui_key_view_tab_history"
182#define M32OPTION_UI_KEY_VIEW_TAB_MARQUEE      "ui_key_view_tab_marquee"
183#define M32OPTION_UI_KEY_VIEW_TAB_SCREENSHOT   "ui_key_view_tab_screenshot"
184#define M32OPTION_UI_KEY_VIEW_TAB_TITLE         "ui_key_view_tab_title"
185#define M32OPTION_UI_KEY_VIEW_TAB_PCB         "ui_key_view_tab_pcb"
186#define M32OPTION_UI_KEY_QUIT               "ui_key_quit"
187#define M32OPTION_UI_JOY_UP                  "ui_joy_up"
188#define M32OPTION_UI_JOY_DOWN               "ui_joy_down"
189#define M32OPTION_UI_JOY_LEFT               "ui_joy_left"
190#define M32OPTION_UI_JOY_RIGHT               "ui_joy_right"
191#define M32OPTION_UI_JOY_START               "ui_joy_start"
192#define M32OPTION_UI_JOY_PGUP               "ui_joy_pgup"
193#define M32OPTION_UI_JOY_PGDWN               "ui_joy_pgdwn"
194#define M32OPTION_UI_JOY_HOME               "ui_joy_home"
195#define M32OPTION_UI_JOY_END               "ui_joy_end"
196#define M32OPTION_UI_JOY_SS_CHANGE            "ui_joy_ss_change"
197#define M32OPTION_UI_JOY_HISTORY_UP            "ui_joy_history_up"
198#define M32OPTION_UI_JOY_HISTORY_DOWN         "ui_joy_history_down"
199#define M32OPTION_UI_JOY_EXEC               "ui_joy_exec"
200#define M32OPTION_EXEC_COMMAND               "exec_command"
201#define M32OPTION_EXEC_WAIT                  "exec_wait"
202#define M32OPTION_HIDE_MOUSE               "hide_mouse"
203#define M32OPTION_FULL_SCREEN               "full_screen"
204
205#ifdef MESS
206// Options names
207#define M32OPTION_DEFAULT_GAME               "default_system"
208#define M32OPTION_HISTORY_FILE               "sysinfo_file"
209#define M32OPTION_MAMEINFO_FILE               "messinfo_file"
210// Option values
211#define M32DEFAULT_SELECTION               "nes"
212#define M32DEFAULT_SPLITTERS               "152,310,468"
213#define M32HISTORY_FILE                     "sysinfo.dat"
214#define M32MAMEINFO_FILE                  "messinfo.dat"
215#else
216// Options names
217#define M32OPTION_DEFAULT_GAME               "default_game"
218#define M32OPTION_HISTORY_FILE               "history_file"
219#define M32OPTION_MAMEINFO_FILE               "mameinfo_file"
220// Options values
221#define M32DEFAULT_SELECTION               "puckman"
222#define M32DEFAULT_SPLITTERS               "152,362"
223#define M32HISTORY_FILE                     "history.dat"
224#define M32MAMEINFO_FILE                  "mameinfo.dat"
225#endif
226
227
228
229/***************************************************************************
230    Internal structures
231 ***************************************************************************/
232
233#if 0
234typedef struct
235{
236   int folder_index;
237   int filters;
238} folder_filter_type;
239#endif
240
241/***************************************************************************
242    Internal variables
243 ***************************************************************************/
244
245static object_pool *options_memory_pool;
246
247static core_options *settings;
248
249static core_options *global = NULL;         // Global 'default' options
250
251// UI options in mame32ui.ini
252static const options_entry regSettings[] =
253{
254   // UI options
255   { NULL,                           NULL,       OPTION_HEADER,     "DISPLAY STATE OPTIONS" },
256   { M32OPTION_DEFAULT_GAME,            M32DEFAULT_SELECTION, 0,       NULL },
257   { M32OPTION_DEFAULT_GAME,            "puckman",  0,                 NULL },
258   { M32OPTION_DEFAULT_FOLDER_ID,         "0",        0,                 NULL },
259   { M32OPTION_SHOW_IMAGE_SECTION,         "1",        OPTION_BOOLEAN,    NULL },
260   { M32OPTION_FULL_SCREEN,            "0",        OPTION_BOOLEAN,    NULL },
261   { M32OPTION_CURRENT_TAB,            "0",        0,                 NULL },
262   { M32OPTION_SHOW_TOOLBAR,            "1",        OPTION_BOOLEAN,    NULL },
263   { M32OPTION_SHOW_STATUS_BAR,         "1",        OPTION_BOOLEAN,    NULL },
264   { M32OPTION_HIDE_FOLDERS,            "",         0,                 NULL },
265#ifdef MESS
266   { M32OPTION_SHOW_FOLDER_SECTION,      "0",        OPTION_BOOLEAN,    NULL },
267   { M32OPTION_SHOW_TABS,               "0",        OPTION_BOOLEAN,    NULL },
268   { M32OPTION_HIDE_TABS,               "flyer, cabinet, marquee, title, cpanel, pcb", 0, NULL },
269   { M32OPTION_HISTORY_TAB,            "1",        0,                 NULL },
270#else
271   { M32OPTION_SHOW_FOLDER_SECTION,      "1",        OPTION_BOOLEAN,    NULL },
272   { M32OPTION_SHOW_TABS,               "1",        OPTION_BOOLEAN,    NULL },
273   { M32OPTION_HIDE_TABS,               "marquee, title, cpanel, pcb, history", 0, NULL },
274   { M32OPTION_HISTORY_TAB,            "0",        0,                 NULL },
275#endif
276
277   { M32OPTION_SORT_COLUMN,            "0",        0,                 NULL },
278   { M32OPTION_SORT_REVERSED,            "0",        OPTION_BOOLEAN,    NULL },
279   { M32OPTION_WINDOW_X,               "0",        0,                 NULL },
280   { M32OPTION_WINDOW_Y,               "0",        0,                 NULL },
281   { M32OPTION_WINDOW_WIDTH,            "640",      0,                 NULL },
282   { M32OPTION_WINDOW_HEIGHT,            "400",      0,                 NULL },
283   { M32OPTION_WINDOW_STATE,            "1",        0,                 NULL },
284
285   { M32OPTION_TEXT_COLOR,               "-1",       0,                 NULL },
286   { M32OPTION_CLONE_COLOR,            "-1",       0,                 NULL },
287   { M32OPTION_CUSTOM_COLOR,            "0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0", 0, NULL },
288   /* ListMode needs to be before ColumnWidths settings */
289   { M32OPTION_LIST_MODE,               "5",        0,                 NULL },
290   { M32OPTION_SPLITTERS,               M32DEFAULT_SPLITTERS, 0,       NULL },
291   { M32OPTION_LIST_FONT,               "-8,0,0,0,400,0,0,0,0,0,0,0,0,MS Sans Serif", 0, NULL },
292   { M32OPTION_COLUMN_WIDTHS,            "185,78,84,84,64,88,74,108,60,144,84,60", 0, NULL },
293   { M32OPTION_COLUMN_ORDER,            "0,2,3,4,5,6,7,8,9,1,10,11", 0, NULL },
294   { M32OPTION_COLUMN_SHOWN,            "1,0,1,1,1,1,1,1,1,1,0,0", 0,  NULL },
295
296   { NULL,                           NULL,       OPTION_HEADER,     "INTERFACE OPTIONS" },
297   { M32OPTION_LANGUAGE,               "english",  0,                 NULL },
298   { M32OPTION_CHECK_GAME,               "1",        OPTION_BOOLEAN,    NULL },
299   { M32OPTION_JOYSTICK_IN_INTERFACE,      "0",        OPTION_BOOLEAN,    NULL },
300   { M32OPTION_KEYBOARD_IN_INTERFACE,      "0",        OPTION_BOOLEAN,    NULL },
301   { M32OPTION_RANDOM_BACKGROUND,         "0",        OPTION_BOOLEAN,    NULL },
302   { M32OPTION_BROADCAST_GAME_NAME,      "0",        OPTION_BOOLEAN,    NULL },
303   { M32OPTION_HIDE_MOUSE,               "0",        OPTION_BOOLEAN,    NULL },
304   { M32OPTION_INHERIT_FILTER,            "0",        OPTION_BOOLEAN,    NULL },
305   { M32OPTION_OFFSET_CLONES,            "0",        OPTION_BOOLEAN,    NULL },
306   { M32OPTION_GAME_CAPTION,            "1",        OPTION_BOOLEAN,    NULL },
307   { M32OPTION_STRETCH_SCREENSHOT_LARGER,   "0",        OPTION_BOOLEAN,    NULL },
308   { M32OPTION_CYCLE_SCREENSHOT,         "0",        0,                 NULL },
309    { M32OPTION_SCREENSHOT_BORDER_SIZE,      "11",       0,                 NULL },
310    { M32OPTION_SCREENSHOT_BORDER_COLOR,   "-1",       0,                 NULL },
311   { M32OPTION_EXEC_COMMAND,            "",         0,                 NULL },
312   { M32OPTION_EXEC_WAIT,               "0",        0,                 NULL },
313
314   { NULL,                           NULL,       OPTION_HEADER,     "SEARCH PATH OPTIONS" },
315   { M32OPTION_FLYER_DIRECTORY,         "flyers",   0,                 NULL },
316   { M32OPTION_CABINET_DIRECTORY,         "cabinets", 0,                 NULL },
317   { M32OPTION_MARQUEE_DIRECTORY,         "marquees", 0,                 NULL },
318   { M32OPTION_TITLE_DIRECTORY,         "titles",   0,                 NULL },
319   { M32OPTION_CPANEL_DIRECTORY,         "cpanel",   0,                 NULL },
320   { M32OPTION_PCB_DIRECTORY,             "pcb",      0,                 NULL },
321   { M32OPTION_BACKGROUND_DIRECTORY,      "bkground", 0,                 NULL },
322   { M32OPTION_FOLDER_DIRECTORY,         "folders",  0,                 NULL },
323   { M32OPTION_ICONS_DIRECTORY,         "icons",    0,                 NULL },
324
325
326   { NULL,                           NULL,       OPTION_HEADER,     "FILENAME OPTIONS" },
327   { M32OPTION_HISTORY_FILE,            M32HISTORY_FILE, 0,              NULL },
328   { M32OPTION_MAMEINFO_FILE,            M32MAMEINFO_FILE, 0,             NULL },
329
330   { NULL,                           NULL,       OPTION_HEADER,     "NAVIGATION KEY CODES" },
331   { M32OPTION_UI_KEY_UP,               "KEYCODE_UP", 0,               NULL },
332   { M32OPTION_UI_KEY_DOWN,            "KEYCODE_DOWN", 0,             NULL },
333   { M32OPTION_UI_KEY_LEFT,            "KEYCODE_LEFT", 0,             NULL },
334   { M32OPTION_UI_KEY_RIGHT,            "KEYCODE_RIGHT", 0,            NULL },
335   { M32OPTION_UI_KEY_START,            "KEYCODE_ENTER NOT KEYCODE_LALT", 0, NULL },
336   { M32OPTION_UI_KEY_PGUP,            "KEYCODE_PGUP", 0,             NULL },
337   { M32OPTION_UI_KEY_PGDWN,            "KEYCODE_PGDN", 0,             NULL },
338   { M32OPTION_UI_KEY_HOME,            "KEYCODE_HOME", 0,             NULL },
339   { M32OPTION_UI_KEY_END,               "KEYCODE_END", 0,              NULL },
340   { M32OPTION_UI_KEY_SS_CHANGE,         "KEYCODE_INSERT", 0,           NULL },
341   { M32OPTION_UI_KEY_HISTORY_UP,         "KEYCODE_DEL", 0,              NULL },
342   { M32OPTION_UI_KEY_HISTORY_DOWN,      "KEYCODE_LALT KEYCODE_0", 0,   NULL },
343
344   { M32OPTION_UI_KEY_CONTEXT_FILTERS,      "KEYCODE_LCONTROL KEYCODE_F", 0, NULL },
345   { M32OPTION_UI_KEY_SELECT_RANDOM,      "KEYCODE_LCONTROL KEYCODE_R", 0, NULL },
346   { M32OPTION_UI_KEY_GAME_AUDIT,         "KEYCODE_LALT KEYCODE_A",     0, NULL },
347   { M32OPTION_UI_KEY_GAME_PROPERTIES,      "KEYCODE_LALT KEYCODE_ENTER", 0, NULL },
348   { M32OPTION_UI_KEY_HELP_CONTENTS,      "KEYCODE_F1",                 0, NULL },
349   { M32OPTION_UI_KEY_UPDATE_GAMELIST,      "KEYCODE_F5",                 0, NULL },
350   { M32OPTION_UI_KEY_VIEW_FOLDERS,      "KEYCODE_LALT KEYCODE_D",     0, NULL },
351   { M32OPTION_UI_KEY_VIEW_FULLSCREEN,      "KEYCODE_F11",                0, NULL },
352   { M32OPTION_UI_KEY_VIEW_PAGETAB,      "KEYCODE_LALT KEYCODE_B",     0, NULL },
353   { M32OPTION_UI_KEY_VIEW_PICTURE_AREA,   "KEYCODE_LALT KEYCODE_P",     0, NULL },
354   { M32OPTION_UI_KEY_VIEW_STATUS,         "KEYCODE_LALT KEYCODE_S",     0, NULL },
355    { M32OPTION_UI_KEY_VIEW_TOOLBARS,      "KEYCODE_LALT KEYCODE_T",     0, NULL },
356
357   { M32OPTION_UI_KEY_VIEW_TAB_CABINET,   "KEYCODE_LALT KEYCODE_3",     0, NULL },
358    { M32OPTION_UI_KEY_VIEW_TAB_CPANEL,      "KEYCODE_LALT KEYCODE_6",     0, NULL },
359    { M32OPTION_UI_KEY_VIEW_TAB_FLYER,      "KEYCODE_LALT KEYCODE_2",     0, NULL },
360    { M32OPTION_UI_KEY_VIEW_TAB_HISTORY,   "KEYCODE_LALT KEYCODE_8",     0, NULL },
361    { M32OPTION_UI_KEY_VIEW_TAB_MARQUEE,   "KEYCODE_LALT KEYCODE_4",     0, NULL },
362    { M32OPTION_UI_KEY_VIEW_TAB_SCREENSHOT,   "KEYCODE_LALT KEYCODE_1",     0, NULL },
363    { M32OPTION_UI_KEY_VIEW_TAB_TITLE,      "KEYCODE_LALT KEYCODE_5",     0, NULL },
364    { M32OPTION_UI_KEY_VIEW_TAB_PCB,      "KEYCODE_LALT KEYCODE_7",     0, NULL },
365    { M32OPTION_UI_KEY_QUIT,            "KEYCODE_LALT KEYCODE_Q",     0, NULL },
366
367   { NULL,                           NULL,       OPTION_HEADER,     "NAVIGATION JOYSTICK CODES" },
368   { M32OPTION_UI_JOY_UP,               "",         0,                 NULL },
369   { M32OPTION_UI_JOY_DOWN,            "",         0,                 NULL },
370   { M32OPTION_UI_JOY_LEFT,            "",         0,                 NULL },
371   { M32OPTION_UI_JOY_RIGHT,            "",         0,                 NULL },
372   { M32OPTION_UI_JOY_START,            "",         0,                 NULL },
373   { M32OPTION_UI_JOY_PGUP,            "",         0,                 NULL },
374   { M32OPTION_UI_JOY_PGDWN,            "",         0,                 NULL },
375   { M32OPTION_UI_JOY_HOME,            "0,0,0,0",  0,                 NULL },
376   { M32OPTION_UI_JOY_END,               "0,0,0,0",  0,                 NULL },
377   { M32OPTION_UI_JOY_SS_CHANGE,         "",         0,                 NULL },
378   { M32OPTION_UI_JOY_HISTORY_UP,         "",         0,                 NULL },
379   { M32OPTION_UI_JOY_HISTORY_DOWN,      "",         0,                 NULL },
380   { M32OPTION_UI_JOY_EXEC,            "0,0,0,0",  0,                 NULL },
381
382#ifndef MESS
383   { NULL,                           NULL,       OPTION_HEADER,     "GAME STATISTICS" },
384#endif
385   { NULL }
386};
387
388static const options_entry perGameOptions[] =
389{
390   // per game options
391   { "_play_count",             "0",        0,                 NULL },
392   { "_play_time",              "0",        0,                 NULL },
393   { "_rom_audit",              "-1",       0,                 NULL },
394   { "_samples_audit",          "-1",       0,                 NULL },
395#ifdef MESS
396   { "_extra_software",         "",         0,                 NULL },
397#endif
398   { NULL }
399};
400
401static const options_entry filterOptions[] =
402{
403   // filters
404   { "_filters",                "0",        0,                 NULL },
405   { NULL }
406};
407
408
409
410// Screen shot Page tab control text
411// these must match the order of the options flags in options.h
412// (TAB_...)
413const char* image_tabs_long_name[MAX_TAB_TYPES] =
414{
415   "Snapshot ",
416   "Flyer ",
417   "Cabinet ",
418   "Marquee",
419   "Title",
420   "Control Panel",
421   "PCB",
422   "History ",
423};
424
425const char* image_tabs_short_name[MAX_TAB_TYPES] =
426{
427   "snapshot",
428   "flyer",
429   "cabinet",
430   "marquee",
431   "title",
432   "cpanel",
433   "pcb",
434   "history"
435};
436
437
438static BOOL save_gui_settings = TRUE;
439static BOOL save_default_options = TRUE;
440
441#if 0
442folder_filter_type *folder_filters;
443int size_folder_filters;
444int num_folder_filters;
445#endif
446
447/***************************************************************************
448    External functions 
449 ***************************************************************************/
450
451static void memory_error(const char *message)
452{
453   win_message_box_utf8(NULL, message, NULL, MB_OK);
454   exit(-1);
455}
456
457
458
459void AddOptions(core_options *opts, const options_entry *entrylist, BOOL is_global)
460{
461   static const char *blacklist[] =
462   {
463      WINOPTION_SCREEN,
464      WINOPTION_ASPECT,
465      WINOPTION_RESOLUTION,
466      WINOPTION_VIEW
467   };
468   options_entry entries[2];
469   BOOL good_option;
470   int i;
471
472   for ( ; entrylist->name != NULL || (entrylist->flags & OPTION_HEADER); entrylist++)
473   {
474      good_option = TRUE;
475
476      // check blacklist
477      if (entrylist->name != NULL)
478      {
479         for (i = 0; i < ARRAY_LENGTH(blacklist); i++)
480         {
481            if (!strcmp(entrylist->name, blacklist[i]))
482            {
483               good_option = FALSE;
484               break;
485            }
486         }
487      }
488
489      // if is_global is FALSE, blacklist global options
490      if (entrylist->name && !is_global && IsGlobalOption(entrylist->name))
491         good_option = FALSE;
492
493      if (good_option)
494      {
495         memcpy(entries, entrylist, sizeof(options_entry));
496         memset(&entries[1], 0, sizeof(entries[1]));
497         options_add_entries(opts, entries);
498      }
499   }
500}
501
502
503
504core_options *CreateGameOptions(int driver_index)
505{
506   core_options *opts;
507   BOOL is_global = (driver_index == OPTIONS_TYPE_GLOBAL);
508   extern const options_entry mame_win_options[];
509
510   // create the options
511   opts = options_create(memory_error);
512
513   // add the options
514   AddOptions(opts, mame_core_options, is_global);
515   AddOptions(opts, mame_win_options, is_global);
516
517   // customize certain options
518   if (is_global)
519      options_set_option_default_value(opts, OPTION_INIPATH, "ini");
520
521#ifdef MESS
522   MessSetupGameOptions(opts, driver_index);
523#endif // MESS
524
525   return opts;
526}
527
528
529
530BOOL OptionsInit()
531{
532   // create a memory pool for our data
533   options_memory_pool = pool_alloc(memory_error);
534   if (!options_memory_pool)
535      return FALSE;
536
537   // set up the MAME32 settings (these get placed in MAME32ui.ini
538   settings = options_create(memory_error);
539   options_add_entries(settings, regSettings);
540#ifdef MESS
541   MessSetupSettings(settings);
542#endif
543
544   // set up per game options
545   {
546      char buffer[128];
547      int i, j;
548      int game_option_count = 0;
549      options_entry *driver_per_game_options;
550      options_entry *ent;
551
552      while(perGameOptions[game_option_count].name)
553         game_option_count++;
554
555      driver_per_game_options = (options_entry *) pool_malloc(options_memory_pool,
556         (game_option_count * driver_list_get_count(drivers) + 1) * sizeof(*driver_per_game_options));
557
558      for (i = 0; i < driver_list_get_count(drivers); i++)
559      {
560         for (j = 0; j < game_option_count; j++)
561         {
562            ent = &driver_per_game_options[i * game_option_count + j];
563
564            snprintf(buffer, ARRAY_LENGTH(buffer), "%s%s", drivers[i]->name, perGameOptions[j].name);
565
566            memset(ent, 0, sizeof(*ent));
567            ent->name = pool_strdup(options_memory_pool, buffer);
568            ent->defvalue = perGameOptions[j].defvalue;
569            ent->flags = perGameOptions[j].flags;
570            ent->description = perGameOptions[j].description;
571         }
572      }
573      ent = &driver_per_game_options[driver_list_get_count(drivers) * game_option_count];
574      memset(ent, 0, sizeof(*ent));
575      options_add_entries(settings, driver_per_game_options);
576   }
577
578   // set up global options
579   global = CreateGameOptions(OPTIONS_TYPE_GLOBAL);
580#if 0
581   // set up folders
582   size_folder_filters = 1;
583   num_folder_filters = 0;
584   folder_filters = (folder_filter_type *) pool_malloc(options_memory_pool, size_folder_filters * sizeof(*folder_filters));
585#endif
586   // now load the options and settings
587   LoadOptionsAndSettings();
588
589   return TRUE;
590
591}
592
593void OptionsExit(void)
594{
595   // free global options
596   options_free(global);
597   global = NULL;
598
599   // free settings
600   options_free(settings);
601   settings = NULL;
602
603   // free the memory pool
604   pool_free(options_memory_pool);
605   options_memory_pool = NULL;
606}
607
608core_options * Mame32Settings(void)
609{
610   return settings;
611}
612
613core_options * Mame32Global(void)
614{
615   return global;
616}
617
618#if 0
619static void LoadFolderFilter(int folder_index,int filters)
620{
621   //dprintf("loaded folder filter %i %i",folder_index,filters);
622
623   if (num_folder_filters == size_folder_filters)
624   {
625      size_folder_filters *= 2;
626      folder_filters = (folder_filter_type *)realloc(
627         folder_filters,size_folder_filters * sizeof(folder_filter_type));
628   }
629   folder_filters[num_folder_filters].folder_index = folder_index;
630   folder_filters[num_folder_filters].filters = filters;
631
632   num_folder_filters++;
633}
634#endif
635
636// Restore ui settings to factory
637void ResetGUI(void)
638{
639   ResetToDefaults(settings, OPTION_PRIORITY_NORMAL);
640   // Save the new MAME32ui.ini
641   SaveOptions();
642   save_gui_settings = FALSE;
643}
644
645const char * GetImageTabLongName(int tab_index)
646{
647   assert(0 <= tab_index < ARRAY_LENGTH(image_tabs_long_name));
648   return image_tabs_long_name[tab_index];
649}
650
651const char * GetImageTabShortName(int tab_index)
652{
653   assert(0 <= tab_index < ARRAY_LENGTH(image_tabs_short_name));
654   return image_tabs_short_name[tab_index];
655}
656
657//============================================================
658//  OPTIONS WRAPPERS
659//============================================================
660
661static COLORREF options_get_color(core_options *opts, const char *name)
662{
663   const char *value_str;
664   unsigned int r, g, b;
665   COLORREF value;
666
667   value_str = options_get_string(opts, name);
668
669   if (sscanf(value_str, "%u,%u,%u", &r, &g, &b) == 3)
670      value = RGB(r,g,b);
671   else
672      value = (COLORREF) - 1;
673   return value;
674}
675
676static void options_set_color(core_options *opts, const char *name, COLORREF value)
677{
678   char value_str[32];
679
680   if (value == (COLORREF) -1)
681   {
682      snprintf(value_str, ARRAY_LENGTH(value_str), "%d", (int) value);
683   }
684   else
685   {
686      snprintf(value_str, ARRAY_LENGTH(value_str), "%d,%d,%d",
687         (((int) value) >>  0) & 0xFF,
688         (((int) value) >>  8) & 0xFF,
689         (((int) value) >> 16) & 0xFF);
690   }
691   options_set_string(opts, name, value_str, OPTION_PRIORITY_CMDLINE);
692}
693
694static COLORREF options_get_color_default(core_options *opts, const char *name, int default_color)
695{
696   COLORREF value = options_get_color(opts, name);
697   if (value == (COLORREF) -1)
698      value = GetSysColor(default_color);
699   return value;
700}
701
702static void options_set_color_default(core_options *opts, const char *name, COLORREF value, int default_color)
703{
704   if (value == GetSysColor(default_color))
705      options_set_color(settings, name, (COLORREF) -1);
706   else
707      options_set_color(settings, name, value);
708}
709
710static input_seq *options_get_input_seq(core_options *opts, const char *name)
711{
712   static input_seq seq;
713   const char *seq_string;
714
715   seq_string = options_get_string(opts, name);
716   input_seq_from_tokens(seq_string, &seq);
717   return &seq;
718}
719
720
721
722//============================================================
723//  OPTIONS CALLS
724//============================================================
725
726void SetViewMode(int val)
727{
728   options_set_int(settings, M32OPTION_LIST_MODE, val, OPTION_PRIORITY_CMDLINE);
729}
730
731int GetViewMode(void)
732{
733   return options_get_int(settings, M32OPTION_LIST_MODE);
734}
735
736void SetGameCheck(BOOL game_check)
737{
738   options_set_bool(settings, M32OPTION_CHECK_GAME, game_check, OPTION_PRIORITY_CMDLINE);
739}
740
741BOOL GetGameCheck(void)
742{
743   return options_get_bool(settings,M32OPTION_CHECK_GAME);
744}
745
746void SetJoyGUI(BOOL use_joygui)
747{
748   options_set_bool(settings, M32OPTION_JOYSTICK_IN_INTERFACE, use_joygui, OPTION_PRIORITY_CMDLINE);
749}
750
751BOOL GetJoyGUI(void)
752{
753   return options_get_bool(settings, M32OPTION_JOYSTICK_IN_INTERFACE);
754}
755
756void SetKeyGUI(BOOL use_keygui)
757{
758   options_set_bool(settings, M32OPTION_KEYBOARD_IN_INTERFACE, use_keygui, OPTION_PRIORITY_CMDLINE);
759}
760
761BOOL GetKeyGUI(void)
762{
763   return options_get_bool(settings, M32OPTION_KEYBOARD_IN_INTERFACE);
764}
765
766void SetCycleScreenshot(int cycle_screenshot)
767{
768   options_set_int(settings, M32OPTION_CYCLE_SCREENSHOT, cycle_screenshot, OPTION_PRIORITY_CMDLINE);
769}
770
771int GetCycleScreenshot(void)
772{
773   return options_get_int(settings, M32OPTION_CYCLE_SCREENSHOT);
774}
775
776void SetStretchScreenShotLarger(BOOL stretch)
777{
778   options_set_bool(settings, M32OPTION_STRETCH_SCREENSHOT_LARGER, stretch, OPTION_PRIORITY_CMDLINE);
779}
780
781BOOL GetStretchScreenShotLarger(void)
782{
783   return options_get_bool(settings, M32OPTION_STRETCH_SCREENSHOT_LARGER);
784}
785
786void SetScreenshotBorderSize(int size)
787{
788   options_set_int(settings, M32OPTION_SCREENSHOT_BORDER_SIZE, size, OPTION_PRIORITY_CMDLINE);
789}
790
791int GetScreenshotBorderSize(void)
792{
793   return options_get_int(settings, M32OPTION_SCREENSHOT_BORDER_SIZE);
794}
795
796void SetScreenshotBorderColor(COLORREF uColor)
797{
798   options_set_color_default(settings, M32OPTION_SCREENSHOT_BORDER_COLOR, uColor, COLOR_3DFACE);
799}
800
801COLORREF GetScreenshotBorderColor(void)
802{
803   return options_get_color_default(settings, M32OPTION_SCREENSHOT_BORDER_COLOR, COLOR_3DFACE);
804}
805
806void SetFilterInherit(BOOL inherit)
807{
808   options_set_bool(settings, M32OPTION_INHERIT_FILTER, inherit, OPTION_PRIORITY_CMDLINE);
809}
810
811BOOL GetFilterInherit(void)
812{
813   return options_get_bool(settings, M32OPTION_INHERIT_FILTER);
814}
815
816void SetOffsetClones(BOOL offset)
817{
818   options_set_bool(settings, M32OPTION_OFFSET_CLONES, offset, OPTION_PRIORITY_CMDLINE);
819}
820
821BOOL GetOffsetClones(void)
822{
823   return options_get_bool(settings, M32OPTION_OFFSET_CLONES);
824}
825
826void SetGameCaption(BOOL caption)
827{
828   options_set_bool(settings, M32OPTION_GAME_CAPTION, caption, OPTION_PRIORITY_CMDLINE);
829}
830
831BOOL GetGameCaption(void)
832{
833   return options_get_bool(settings, M32OPTION_GAME_CAPTION);
834}
835
836void SetBroadcast(BOOL broadcast)
837{
838   options_set_bool(settings, M32OPTION_BROADCAST_GAME_NAME, broadcast, OPTION_PRIORITY_CMDLINE);
839}
840
841BOOL GetBroadcast(void)
842{
843   return options_get_bool(settings, M32OPTION_BROADCAST_GAME_NAME);
844}
845
846void SetRandomBackground(BOOL random_bg)
847{
848   options_set_bool(settings, M32OPTION_RANDOM_BACKGROUND, random_bg, OPTION_PRIORITY_CMDLINE);
849}
850
851BOOL GetRandomBackground(void)
852{
853   return options_get_bool(settings, M32OPTION_RANDOM_BACKGROUND);
854}
855
856void SetSavedFolderID(UINT val)
857{
858   options_set_int(settings, M32OPTION_DEFAULT_FOLDER_ID, (int) val, OPTION_PRIORITY_CMDLINE);
859}
860
861UINT GetSavedFolderID(void)
862{
863   return (UINT) options_get_int(settings, M32OPTION_DEFAULT_FOLDER_ID);
864}
865
866void SetShowScreenShot(BOOL val)
867{
868   options_set_bool(settings, M32OPTION_SHOW_IMAGE_SECTION, val, OPTION_PRIORITY_CMDLINE);
869}
870
871BOOL GetShowScreenShot(void)
872{
873   return options_get_bool(settings, M32OPTION_SHOW_IMAGE_SECTION);
874}
875
876void SetShowFolderList(BOOL val)
877{
878   options_set_bool(settings, M32OPTION_SHOW_FOLDER_SECTION, val, OPTION_PRIORITY_CMDLINE);
879}
880
881BOOL GetShowFolderList(void)
882{
883   return options_get_bool(settings, M32OPTION_SHOW_FOLDER_SECTION);
884}
885
886static void GetsShowFolderFlags(LPBITS bits)
887{
888   char s[2000];
889   extern FOLDERDATA g_folderData[];
890   char *token;
891
892   snprintf(s, ARRAY_LENGTH(s), "%s", options_get_string(settings, M32OPTION_HIDE_FOLDERS));
893
894   SetAllBits(bits, TRUE);
895
896   token = strtok(s,", \t");
897   while (token != NULL)
898   {
899      int j;
900
901      for (j=0;g_folderData[j].m_lpTitle != NULL;j++)
902      {
903         if (strcmp(g_folderData[j].short_name,token) == 0)
904         {
905            ClearBit(bits, g_folderData[j].m_nFolderId);
906            break;
907         }
908      }
909      token = strtok(NULL,", \t");
910   }
911}
912
913BOOL GetShowFolder(int folder)
914{
915   BOOL result;
916   LPBITS show_folder_flags = NewBits(MAX_FOLDERS);
917   GetsShowFolderFlags(show_folder_flags);
918   result = TestBit(show_folder_flags, folder);
919   DeleteBits(show_folder_flags);
920   return result;
921}
922
923void SetShowFolder(int folder,BOOL show)
924{
925   LPBITS show_folder_flags = NewBits(MAX_FOLDERS);
926   int i;
927   int num_saved = 0;
928   char str[10000];
929   extern FOLDERDATA g_folderData[];
930
931   GetsShowFolderFlags(show_folder_flags);
932
933   if (show)
934      SetBit(show_folder_flags, folder);
935   else
936      ClearBit(show_folder_flags, folder);
937
938   strcpy(str, "");
939
940   // we save the ones that are NOT displayed, so we can add new ones
941   // and upgraders will see them
942   for (i=0;i<MAX_FOLDERS;i++)
943   {
944      if (TestBit(show_folder_flags, i) == FALSE)
945      {
946         int j;
947
948         if (num_saved != 0)
949            strcat(str,", ");
950
951         for (j=0;g_folderData[j].m_lpTitle != NULL;j++)
952         {
953            if (g_folderData[j].m_nFolderId == i)
954            {
955               strcat(str,g_folderData[j].short_name);
956               num_saved++;
957               break;
958            }
959         }
960      }
961   }
962   options_set_string(settings, M32OPTION_HIDE_FOLDERS, str, OPTION_PRIORITY_CMDLINE);
963   DeleteBits(show_folder_flags);
964}
965
966void SetShowStatusBar(BOOL val)
967{
968   options_set_bool(settings, M32OPTION_SHOW_STATUS_BAR, val, OPTION_PRIORITY_CMDLINE);
969}
970
971BOOL GetShowStatusBar(void)
972{
973   return options_get_bool(settings, M32OPTION_SHOW_STATUS_BAR);
974}
975
976void SetShowTabCtrl (BOOL val)
977{
978   options_set_bool(settings, M32OPTION_SHOW_TABS, val, OPTION_PRIORITY_CMDLINE);
979}
980
981BOOL GetShowTabCtrl (void)
982{
983   return options_get_bool(settings, M32OPTION_SHOW_TABS);
984}
985
986void SetShowToolBar(BOOL val)
987{
988   options_set_bool(settings, M32OPTION_SHOW_TOOLBAR, val, OPTION_PRIORITY_CMDLINE);
989}
990
991BOOL GetShowToolBar(void)
992{
993   return options_get_bool(settings, M32OPTION_SHOW_TOOLBAR);
994}
995
996void SetCurrentTab(const char *shortname)
997{
998   options_set_string(settings, M32OPTION_CURRENT_TAB, shortname, OPTION_PRIORITY_CMDLINE);
999}
1000
1001const char *GetCurrentTab(void)
1002{
1003   return options_get_string(settings, M32OPTION_CURRENT_TAB);
1004}
1005
1006void SetDefaultGame(const char *name)
1007{
1008   options_set_string(settings, M32OPTION_DEFAULT_GAME, name, OPTION_PRIORITY_CMDLINE);
1009}
1010
1011const char *GetDefaultGame(void)
1012{
1013   return options_get_string(settings, M32OPTION_DEFAULT_GAME);
1014}
1015
1016void SetWindowArea(const AREA *area)
1017{
1018   options_set_int(settings, M32OPTION_WINDOW_X,      area->x, OPTION_PRIORITY_CMDLINE);
1019   options_set_int(settings, M32OPTION_WINDOW_Y,      area->y, OPTION_PRIORITY_CMDLINE);
1020   options_set_int(settings, M32OPTION_WINDOW_WIDTH,   area->width, OPTION_PRIORITY_CMDLINE);
1021   options_set_int(settings, M32OPTION_WINDOW_HEIGHT,   area->height, OPTION_PRIORITY_CMDLINE);
1022}
1023
1024void GetWindowArea(AREA *area)
1025{
1026   area->x      = options_get_int(settings, M32OPTION_WINDOW_X);
1027   area->y      = options_get_int(settings, M32OPTION_WINDOW_Y);
1028   area->width  = options_get_int(settings, M32OPTION_WINDOW_WIDTH);
1029   area->height = options_get_int(settings, M32OPTION_WINDOW_HEIGHT);
1030}
1031
1032void SetWindowState(UINT state)
1033{
1034   options_set_int(settings, M32OPTION_WINDOW_STATE, state, OPTION_PRIORITY_CMDLINE);
1035}
1036
1037UINT GetWindowState(void)
1038{
1039   return options_get_int(settings, M32OPTION_WINDOW_STATE);
1040}
1041
1042void SetCustomColor(int iIndex, COLORREF uColor)
1043{
1044   const char *custom_color_string;
1045   COLORREF custom_color[256];
1046   char buffer[10000];
1047
1048   custom_color_string = options_get_string(settings, M32OPTION_CUSTOM_COLOR);
1049   CusColorDecodeString(custom_color_string, custom_color);
1050
1051   custom_color[iIndex] = uColor;
1052
1053   CusColorEncodeString(custom_color, buffer);
1054   options_set_string(settings, M32OPTION_CUSTOM_COLOR, buffer, OPTION_PRIORITY_CMDLINE);
1055}
1056
1057COLORREF GetCustomColor(int iIndex)
1058{
1059   const char *custom_color_string;
1060   COLORREF custom_color[256];
1061
1062   custom_color_string = options_get_string(settings, M32OPTION_CUSTOM_COLOR);
1063   CusColorDecodeString(custom_color_string, custom_color);
1064
1065   if (custom_color[iIndex] == (COLORREF)-1)
1066      return (COLORREF)RGB(0,0,0);
1067
1068   return custom_color[iIndex];
1069}
1070
1071void SetListFont(const LOGFONT *font)
1072{
1073   char font_string[10000];
1074   FontEncodeString(font, font_string);
1075   options_set_string(settings, M32OPTION_LIST_FONT, font_string, OPTION_PRIORITY_CMDLINE);
1076}
1077
1078void GetListFont(LOGFONT *font)
1079{
1080   const char *font_string = options_get_string(settings, M32OPTION_LIST_FONT);
1081   FontDecodeString(font_string, font);
1082}
1083
1084void SetListFontColor(COLORREF uColor)
1085{
1086   options_set_color_default(settings, M32OPTION_TEXT_COLOR, uColor, COLOR_WINDOWTEXT);
1087}
1088
1089COLORREF GetListFontColor(void)
1090{
1091   return options_get_color_default(settings, M32OPTION_TEXT_COLOR, COLOR_WINDOWTEXT);
1092}
1093
1094void SetListCloneColor(COLORREF uColor)
1095{
1096   options_set_color_default(settings, M32OPTION_CLONE_COLOR, uColor, COLOR_WINDOWTEXT);
1097}
1098
1099COLORREF GetListCloneColor(void)
1100{
1101   return options_get_color_default(settings, M32OPTION_CLONE_COLOR, COLOR_WINDOWTEXT);
1102}
1103
1104int GetShowTab(int tab)
1105{
1106   const char *show_tabs_string;
1107   int show_tab_flags;
1108   
1109   show_tabs_string = options_get_string(settings, M32OPTION_HIDE_TABS);
1110   TabFlagsDecodeString(show_tabs_string, &show_tab_flags);
1111   return (show_tab_flags & (1 << tab)) != 0;
1112}
1113
1114void SetShowTab(int tab,BOOL show)
1115{
1116   const char *show_tabs_string;
1117   int show_tab_flags;
1118   char buffer[10000];
1119   
1120   show_tabs_string = options_get_string(settings, M32OPTION_HIDE_TABS);
1121   TabFlagsDecodeString(show_tabs_string, &show_tab_flags);
1122
1123   if (show)
1124      show_tab_flags |= 1 << tab;
1125   else
1126      show_tab_flags &= ~(1 << tab);
1127
1128   TabFlagsEncodeString(show_tab_flags, buffer);
1129   options_set_string(settings, M32OPTION_HIDE_TABS, buffer, OPTION_PRIORITY_CMDLINE);
1130}
1131
1132// don't delete the last one
1133BOOL AllowedToSetShowTab(int tab,BOOL show)
1134{
1135   const char *show_tabs_string;
1136   int show_tab_flags;
1137
1138   if (show == TRUE)
1139      return TRUE;
1140
1141   show_tabs_string = options_get_string(settings, M32OPTION_HIDE_TABS);
1142   TabFlagsDecodeString(show_tabs_string, &show_tab_flags);
1143
1144   show_tab_flags &= ~(1 << tab);
1145   return show_tab_flags != 0;
1146}
1147
1148int GetHistoryTab(void)
1149{
1150   return options_get_int(settings, M32OPTION_HISTORY_TAB);
1151}
1152
1153void SetHistoryTab(int tab, BOOL show)
1154{
1155   if (show)
1156      options_set_int(settings, M32OPTION_HISTORY_TAB, tab, OPTION_PRIORITY_CMDLINE);
1157   else
1158      options_set_int(settings, M32OPTION_HISTORY_TAB, TAB_NONE, OPTION_PRIORITY_CMDLINE);
1159}
1160
1161void SetColumnWidths(int width[])
1162{
1163   char column_width_string[10000];
1164   ColumnEncodeStringWithCount(width, column_width_string, COLUMN_MAX);
1165   options_set_string(settings, M32OPTION_COLUMN_WIDTHS, column_width_string, OPTION_PRIORITY_CMDLINE);
1166}
1167
1168void GetColumnWidths(int width[])
1169{
1170   const char *column_width_string;
1171   column_width_string = options_get_string(settings, M32OPTION_COLUMN_WIDTHS);
1172   ColumnDecodeStringWithCount(column_width_string, width, COLUMN_MAX);
1173}
1174
1175void SetSplitterPos(int splitterId, int pos)
1176{
1177   const char *splitter_string;
1178   int *splitter;
1179   char buffer[10000];
1180
1181   if (splitterId < GetSplitterCount())
1182   {
1183      splitter_string = options_get_string(settings, M32OPTION_SPLITTERS);
1184      splitter = (int *) alloca(GetSplitterCount() * sizeof(*splitter));
1185      SplitterDecodeString(splitter_string, splitter);
1186
1187      splitter[splitterId] = pos;
1188
1189      SplitterEncodeString(splitter, buffer);
1190      options_set_string(settings, M32OPTION_SPLITTERS, buffer, OPTION_PRIORITY_CMDLINE);
1191   }
1192}
1193
1194int  GetSplitterPos(int splitterId)
1195{
1196   const char *splitter_string;
1197   int *splitter;
1198
1199   splitter_string = options_get_string(settings, M32OPTION_SPLITTERS);
1200   splitter = (int *) alloca(GetSplitterCount() * sizeof(*splitter));
1201   SplitterDecodeString(splitter_string, splitter);
1202
1203   if (splitterId < GetSplitterCount())
1204      return splitter[splitterId];
1205
1206   return -1; /* Error */
1207}
1208
1209void SetColumnOrder(int order[])
1210{
1211   char column_order_string[10000];
1212   ColumnEncodeStringWithCount(order, column_order_string, COLUMN_MAX);
1213   options_set_string(settings, M32OPTION_COLUMN_ORDER, column_order_string, OPTION_PRIORITY_CMDLINE);
1214}
1215
1216void GetColumnOrder(int order[])
1217{
1218   const char *column_order_string;
1219   column_order_string = options_get_string(settings, M32OPTION_COLUMN_ORDER);
1220   ColumnDecodeStringWithCount(column_order_string, order, COLUMN_MAX);
1221}
1222
1223void SetColumnShown(int shown[])
1224{
1225   char column_shown_string[10000];
1226   ColumnEncodeStringWithCount(shown, column_shown_string, COLUMN_MAX);
1227   options_set_string(settings, M32OPTION_COLUMN_SHOWN, column_shown_string, OPTION_PRIORITY_CMDLINE);
1228}
1229
1230void GetColumnShown(int shown[])
1231{
1232   const char *column_shown_string;
1233   column_shown_string = options_get_string(settings, M32OPTION_COLUMN_SHOWN);
1234   ColumnDecodeStringWithCount(column_shown_string, shown, COLUMN_MAX);
1235}
1236
1237void SetSortColumn(int column)
1238{
1239   options_set_int(settings, M32OPTION_SORT_COLUMN, column, OPTION_PRIORITY_CMDLINE);
1240}
1241
1242int GetSortColumn(void)
1243{
1244   return options_get_int(settings, M32OPTION_SORT_COLUMN);
1245}
1246
1247void SetSortReverse(BOOL reverse)
1248{
1249   options_set_bool(settings, M32OPTION_SORT_REVERSED, reverse, OPTION_PRIORITY_CMDLINE);
1250}
1251
1252BOOL GetSortReverse(void)
1253{
1254   return options_get_bool(settings, M32OPTION_SORT_REVERSED);
1255}
1256
1257const char* GetLanguage(void)
1258{
1259   return options_get_string(settings, M32OPTION_LANGUAGE);
1260}
1261
1262void SetLanguage(const char* lang)
1263{
1264   options_set_string(settings, M32OPTION_LANGUAGE, lang, OPTION_PRIORITY_CMDLINE);
1265}
1266
1267const char* GetRomDirs(void)
1268{
1269   return options_get_string(global, OPTION_ROMPATH);
1270}
1271
1272void SetRomDirs(const char* paths)
1273{
1274   options_set_string(global, OPTION_ROMPATH, paths, OPTION_PRIORITY_CMDLINE);
1275}
1276
1277const char* GetSampleDirs(void)
1278{
1279   return options_get_string(global, OPTION_SAMPLEPATH);
1280}
1281
1282void SetSampleDirs(const char* paths)
1283{
1284   options_set_string(global, OPTION_SAMPLEPATH, paths, OPTION_PRIORITY_CMDLINE);
1285}
1286
1287const char * GetIniDir(void)
1288{
1289   const char *ini_dir;
1290   const char *s;
1291   
1292   ini_dir = options_get_string(global, OPTION_INIPATH);
1293   while((s = strchr(ini_dir, ';')) != NULL)
1294   {
1295      ini_dir = s + 1;
1296   }
1297   return ini_dir;
1298
1299}
1300
1301void SetIniDir(const char *path)
1302{
1303   options_set_string(global, OPTION_INIPATH, path, OPTION_PRIORITY_CMDLINE);
1304}
1305
1306const char* GetCtrlrDir(void)
1307{
1308   return options_get_string(global, OPTION_CTRLRPATH);
1309}
1310
1311void SetCtrlrDir(const char* path)
1312{
1313   options_set_string(global, OPTION_CTRLRPATH, path, OPTION_PRIORITY_CMDLINE);
1314}
1315
1316const char* GetCommentDir(void)
1317{
1318   return options_get_string(global, OPTION_COMMENT_DIRECTORY);
1319}
1320
1321void SetCommentDir(const char* path)
1322{
1323   options_set_string(global, OPTION_COMMENT_DIRECTORY, path, OPTION_PRIORITY_CMDLINE);
1324}
1325
1326const char* GetCfgDir(void)
1327{
1328   return options_get_string(global, OPTION_CFG_DIRECTORY);
1329}
1330
1331void SetCfgDir(const char* path)
1332{
1333   options_set_string(global, OPTION_CFG_DIRECTORY, path, OPTION_PRIORITY_CMDLINE);
1334}
1335
1336const char* GetNvramDir(void)
1337{
1338   return options_get_string(global, OPTION_NVRAM_DIRECTORY);
1339}
1340
1341void SetNvramDir(const char* path)
1342{
1343   options_set_string(global, OPTION_NVRAM_DIRECTORY, path, OPTION_PRIORITY_CMDLINE);
1344}
1345
1346const char* GetInpDir(void)
1347{
1348   return options_get_string(global, OPTION_INPUT_DIRECTORY);
1349}
1350
1351void SetInpDir(const char* path)
1352{
1353   options_set_string(global, OPTION_INPUT_DIRECTORY, path, OPTION_PRIORITY_CMDLINE);
1354}
1355
1356const char* GetImgDir(void)
1357{
1358   return options_get_string(global, OPTION_SNAPSHOT_DIRECTORY);
1359}
1360
1361void SetImgDir(const char* path)
1362{
1363   options_set_string(global, OPTION_SNAPSHOT_DIRECTORY, path, OPTION_PRIORITY_CMDLINE);
1364}
1365
1366const char* GetStateDir(void)
1367{
1368   return options_get_string(global, OPTION_STATE_DIRECTORY);
1369}
1370
1371void SetStateDir(const char* path)
1372{
1373   options_set_string(global, OPTION_STATE_DIRECTORY, path, OPTION_PRIORITY_CMDLINE);
1374}
1375
1376const char* GetArtDir(void)
1377{
1378   return options_get_string(global, OPTION_ARTPATH);
1379}
1380
1381void SetArtDir(const char* path)
1382{
1383   options_set_string(global, OPTION_ARTPATH, path, OPTION_PRIORITY_CMDLINE);
1384}
1385
1386const char* GetMemcardDir(void)
1387{
1388   return options_get_string(global, OPTION_MEMCARD_DIRECTORY);
1389}
1390
1391void SetMemcardDir(const char* path)
1392{
1393   options_set_string(global, OPTION_MEMCARD_DIRECTORY, path, OPTION_PRIORITY_CMDLINE);
1394}
1395
1396const char* GetFlyerDir(void)
1397{
1398   return options_get_string(settings, M32OPTION_FLYER_DIRECTORY);
1399}
1400
1401void SetFlyerDir(const char* path)
1402{
1403   options_set_string(settings, M32OPTION_FLYER_DIRECTORY, path, OPTION_PRIORITY_CMDLINE);
1404}
1405
1406const char* GetCabinetDir(void)
1407{
1408   return options_get_string(settings, M32OPTION_CABINET_DIRECTORY);
1409}
1410
1411void SetCabinetDir(const char* path)
1412{
1413   options_set_string(settings, M32OPTION_CABINET_DIRECTORY, path, OPTION_PRIORITY_CMDLINE);
1414}
1415
1416const char* GetMarqueeDir(void)
1417{
1418   return options_get_string(settings, M32OPTION_MARQUEE_DIRECTORY);
1419}
1420
1421void SetMarqueeDir(const char* path)
1422{
1423   options_set_string(settings, M32OPTION_MARQUEE_DIRECTORY, path, OPTION_PRIORITY_CMDLINE);
1424}
1425
1426const char* GetTitlesDir(void)
1427{
1428   return options_get_string(settings, M32OPTION_TITLE_DIRECTORY);
1429}
1430
1431void SetTitlesDir(const char* path)
1432{
1433   options_set_string(settings, M32OPTION_TITLE_DIRECTORY, path, OPTION_PRIORITY_CMDLINE);
1434}
1435
1436const char * GetControlPanelDir(void)
1437{
1438   return options_get_string(settings, M32OPTION_CPANEL_DIRECTORY);
1439}
1440
1441void SetControlPanelDir(const char *path)
1442{
1443   options_set_string(settings, M32OPTION_CPANEL_DIRECTORY, path, OPTION_PRIORITY_CMDLINE);
1444}
1445
1446const char * GetPcbDir(void)
1447{
1448   return options_get_string(settings, M32OPTION_PCB_DIRECTORY);
1449}
1450
1451void SetPcbDir(const char *path)
1452{
1453   options_set_string(settings, M32OPTION_PCB_DIRECTORY, path, OPTION_PRIORITY_CMDLINE);
1454}
1455
1456const char * GetDiffDir(void)
1457{
1458   return options_get_string(global, OPTION_DIFF_DIRECTORY);
1459}
1460
1461void SetDiffDir(const char* path)
1462{
1463   options_set_string(global, OPTION_DIFF_DIRECTORY, path, OPTION_PRIORITY_CMDLINE);
1464}
1465
1466const char* GetIconsDir(void)
1467{
1468   return options_get_string(settings, M32OPTION_ICONS_DIRECTORY);
1469}
1470
1471void SetIconsDir(const char* path)
1472{
1473   options_set_string(settings, M32OPTION_ICONS_DIRECTORY, path, OPTION_PRIORITY_CMDLINE);
1474}
1475
1476const char* GetBgDir (void)
1477{
1478   return options_get_string(settings, M32OPTION_BACKGROUND_DIRECTORY);
1479}
1480
1481void SetBgDir (const char* path)
1482{
1483   options_set_string(settings, M32OPTION_BACKGROUND_DIRECTORY, path, OPTION_PRIORITY_CMDLINE);
1484}
1485
1486const char* GetFolderDir(void)
1487{
1488   return options_get_string(settings, M32OPTION_FOLDER_DIRECTORY);
1489}
1490
1491void SetFolderDir(const char* path)
1492{
1493   options_set_string(settings, M32OPTION_FOLDER_DIRECTORY, path, OPTION_PRIORITY_CMDLINE);
1494}
1495
1496const char* GetCheatFileName(void)
1497{
1498   return options_get_string(global, OPTION_CHEAT_FILE);
1499}
1500
1501void SetCheatFileName(const char* path)
1502{
1503   options_set_string(global, OPTION_CHEAT_FILE, path, OPTION_PRIORITY_CMDLINE);
1504}
1505
1506const char* GetHistoryFileName(void)
1507{
1508   return options_get_string(settings, M32OPTION_HISTORY_FILE);
1509}
1510
1511void SetHistoryFileName(const char* path)
1512{
1513   options_set_string(settings, M32OPTION_HISTORY_FILE, path, OPTION_PRIORITY_CMDLINE);
1514}
1515
1516
1517const char* GetMAMEInfoFileName(void)
1518{
1519   return options_get_string(settings, M32OPTION_MAMEINFO_FILE);
1520}
1521
1522void SetMAMEInfoFileName(const char* path)
1523{
1524   options_set_string(settings, M32OPTION_MAMEINFO_FILE, path, OPTION_PRIORITY_CMDLINE);
1525}
1526
1527void ResetGameOptions(int driver_index)
1528{
1529   assert(0 <= driver_index && driver_index < driver_list_get_count(drivers));
1530
1531   save_options(OPTIONS_GAME, NULL, driver_index);
1532}
1533
1534void ResetGameDefaults(void)
1535{
1536   // Walk the global settings and reset everything to defaults;
1537   ResetToDefaults(global, OPTION_PRIORITY_CMDLINE);
1538   save_options(OPTIONS_GLOBAL, global, 1);
1539   save_default_options = FALSE;
1540}
1541
1542/*
1543 * Reset all game, vector and source options to defaults.
1544 * No reason to reboot if this is done.
1545 */
1546void ResetAllGameOptions(void)
1547{
1548   int i;
1549
1550   for (i = 0; i < driver_list_get_count(drivers); i++)
1551   {
1552      ResetGameOptions(i);
1553   }
1554
1555   /* Walk the ini/source folder deleting all ini's. */
1556   remove_all_source_options();
1557   
1558   /* finally vector.ini */
1559   save_options(OPTIONS_VECTOR, NULL, 0);
1560}
1561
1562static void GetDriverOptionName(int driver_index, const char *option_name, char *buffer, size_t buffer_len)
1563{
1564   assert(0 <= driver_index && driver_index < driver_list_get_count(drivers));
1565   snprintf(buffer, buffer_len, "%s_%s", drivers[driver_index]->name, option_name);
1566}
1567
1568int GetRomAuditResults(int driver_index)
1569{
1570   char buffer[128];
1571   GetDriverOptionName(driver_index, "rom_audit", buffer, ARRAY_LENGTH(buffer));
1572   return options_get_int(settings, buffer);
1573}
1574
1575void SetRomAuditResults(int driver_index, int audit_results)
1576{
1577   char buffer[128];
1578   GetDriverOptionName(driver_index, "rom_audit", buffer, ARRAY_LENGTH(buffer));
1579   options_set_int(settings, buffer, audit_results, OPTION_PRIORITY_CMDLINE);
1580}
1581
1582int  GetSampleAuditResults(int driver_index)
1583{
1584   char buffer[128];
1585   GetDriverOptionName(driver_index, "samples_audit", buffer, ARRAY_LENGTH(buffer));
1586   return options_get_int(settings, buffer);
1587}
1588
1589void SetSampleAuditResults(int driver_index, int audit_results)
1590{
1591   char buffer[128];
1592   GetDriverOptionName(driver_index, "samples_audit", buffer, ARRAY_LENGTH(buffer));
1593   options_set_int(settings, buffer, audit_results, OPTION_PRIORITY_CMDLINE);
1594}
1595
1596static void IncrementPlayVariable(int driver_index, const char *play_variable, int increment)
1597{
1598   char buffer[128];
1599   int count;
1600
1601   GetDriverOptionName(driver_index, play_variable, buffer, ARRAY_LENGTH(buffer));
1602   count = options_get_int(settings, buffer);
1603   options_set_int(settings, buffer, count + increment, OPTION_PRIORITY_CMDLINE);
1604}
1605
1606void IncrementPlayCount(int driver_index)
1607{
1608   IncrementPlayVariable(driver_index, "play_count", 1);
1609}
1610
1611int GetPlayCount(int driver_index)
1612{
1613   char buffer[128];
1614   GetDriverOptionName(driver_index, "play_count", buffer, ARRAY_LENGTH(buffer));
1615   return options_get_int(settings, buffer);
1616}
1617
1618static void ResetPlayVariable(int driver_index, const char *play_variable)
1619{
1620   int i;
1621   if (driver_index < 0)
1622   {
1623      /* all games */
1624      for (i = 0; i< driver_list_get_count(drivers); i++)
1625      {
1626         /* 20070808 MSH - Was passing in driver_index instead of i. Doh! */
1627         ResetPlayVariable(i, play_variable);
1628      }
1629   }
1630   else
1631   {
1632      char buffer[128];
1633      GetDriverOptionName(driver_index, play_variable, buffer, ARRAY_LENGTH(buffer));
1634      options_set_int(settings, buffer, 0, OPTION_PRIORITY_CMDLINE);
1635   }
1636}
1637
1638void ResetPlayCount(int driver_index)
1639{
1640   ResetPlayVariable(driver_index, "play_count");
1641}
1642
1643void ResetPlayTime(int driver_index)
1644{
1645   ResetPlayVariable(driver_index, "play_time");
1646}
1647
1648int GetPlayTime(int driver_index)
1649{
1650   char buffer[128];
1651   GetDriverOptionName(driver_index, "play_time", buffer, ARRAY_LENGTH(buffer));
1652   return options_get_int(settings, buffer);
1653}
1654
1655void IncrementPlayTime(int driver_index,int playtime)
1656{
1657   IncrementPlayVariable(driver_index, "play_time", playtime);
1658}
1659
1660void GetTextPlayTime(int driver_index,char *buf)
1661{
1662   int hour, minute, second;
1663   int temp = GetPlayTime(driver_index);
1664
1665   assert(0 <= driver_index && driver_index < driver_list_get_count(drivers));
1666
1667   hour = temp / 3600;
1668   temp = temp - 3600*hour;
1669   minute = temp / 60; //Calc Minutes
1670   second = temp - 60*minute;
1671
1672   if (hour == 0)
1673      sprintf(buf, "%d:%02d", minute, second );
1674   else
1675      sprintf(buf, "%d:%02d:%02d", hour, minute, second );
1676}
1677
1678input_seq* Get_ui_key_up(void)
1679{
1680   return options_get_input_seq(settings, M32OPTION_UI_KEY_UP);
1681}
1682input_seq* Get_ui_key_down(void)
1683{
1684   return options_get_input_seq(settings, M32OPTION_UI_KEY_DOWN);
1685}
1686input_seq* Get_ui_key_left(void)
1687{
1688   return options_get_input_seq(settings, M32OPTION_UI_KEY_LEFT);
1689}
1690input_seq* Get_ui_key_right(void)
1691{
1692   return options_get_input_seq(settings, M32OPTION_UI_KEY_RIGHT);
1693}
1694input_seq* Get_ui_key_start(void)
1695{
1696   return options_get_input_seq(settings, M32OPTION_UI_KEY_START);
1697}
1698input_seq* Get_ui_key_pgup(void)
1699{
1700   return options_get_input_seq(settings, M32OPTION_UI_KEY_PGUP);
1701}
1702input_seq* Get_ui_key_pgdwn(void)
1703{
1704   return options_get_input_seq(settings, M32OPTION_UI_KEY_PGDWN);
1705}
1706input_seq* Get_ui_key_home(void)
1707{
1708   return options_get_input_seq(settings, M32OPTION_UI_KEY_HOME);
1709}
1710input_seq* Get_ui_key_end(void)
1711{
1712   return options_get_input_seq(settings, M32OPTION_UI_KEY_END);
1713}
1714input_seq* Get_ui_key_ss_change(void)
1715{
1716   return options_get_input_seq(settings, M32OPTION_UI_KEY_SS_CHANGE);
1717}
1718input_seq* Get_ui_key_history_up(void)
1719{
1720   return options_get_input_seq(settings, M32OPTION_UI_KEY_HISTORY_UP);
1721}
1722input_seq* Get_ui_key_history_down(void)
1723{
1724   return options_get_input_seq(settings, M32OPTION_UI_KEY_HISTORY_DOWN);
1725}
1726
1727
1728input_seq* Get_ui_key_context_filters(void)
1729{
1730   return options_get_input_seq(settings, M32OPTION_UI_KEY_CONTEXT_FILTERS);
1731}
1732input_seq* Get_ui_key_select_random(void)
1733{
1734   return options_get_input_seq(settings, M32OPTION_UI_KEY_SELECT_RANDOM);
1735}
1736input_seq* Get_ui_key_game_audit(void)
1737{
1738   return options_get_input_seq(settings, M32OPTION_UI_KEY_GAME_AUDIT);
1739}
1740input_seq* Get_ui_key_game_properties(void)
1741{
1742   return options_get_input_seq(settings, M32OPTION_UI_KEY_GAME_PROPERTIES);
1743}
1744input_seq* Get_ui_key_help_contents(void)
1745{
1746   return options_get_input_seq(settings, M32OPTION_UI_KEY_HELP_CONTENTS);
1747}
1748input_seq* Get_ui_key_update_gamelist(void)
1749{
1750   return options_get_input_seq(settings, M32OPTION_UI_KEY_UPDATE_GAMELIST);
1751}
1752input_seq* Get_ui_key_view_folders(void)
1753{
1754   return options_get_input_seq(settings, M32OPTION_UI_KEY_VIEW_FOLDERS);
1755}
1756input_seq* Get_ui_key_view_fullscreen(void)
1757{
1758   return options_get_input_seq(settings, M32OPTION_UI_KEY_VIEW_FULLSCREEN);
1759}
1760input_seq* Get_ui_key_view_pagetab(void)
1761{
1762   return options_get_input_seq(settings, M32OPTION_UI_KEY_VIEW_PAGETAB);
1763}
1764input_seq* Get_ui_key_view_picture_area(void)
1765{
1766   return options_get_input_seq(settings, M32OPTION_UI_KEY_VIEW_PICTURE_AREA);
1767}
1768input_seq* Get_ui_key_view_status(void)
1769{
1770   return options_get_input_seq(settings, M32OPTION_UI_KEY_VIEW_STATUS);
1771}
1772input_seq* Get_ui_key_view_toolbars(void)
1773{
1774   return options_get_input_seq(settings, M32OPTION_UI_KEY_VIEW_TOOLBARS);
1775}
1776
1777input_seq* Get_ui_key_view_tab_cabinet(void)
1778{
1779   return options_get_input_seq(settings, M32OPTION_UI_KEY_VIEW_TAB_CABINET);
1780}
1781input_seq* Get_ui_key_view_tab_cpanel(void)
1782{
1783   return options_get_input_seq(settings, M32OPTION_UI_KEY_VIEW_TAB_CPANEL);
1784}
1785input_seq* Get_ui_key_view_tab_flyer(void)
1786{
1787   return options_get_input_seq(settings, M32OPTION_UI_KEY_VIEW_TAB_FLYER);
1788}
1789input_seq* Get_ui_key_view_tab_history(void)
1790{
1791   return options_get_input_seq(settings, M32OPTION_UI_KEY_VIEW_TAB_HISTORY);
1792}
1793input_seq* Get_ui_key_view_tab_marquee(void)
1794{
1795   return options_get_input_seq(settings, M32OPTION_UI_KEY_VIEW_TAB_MARQUEE);
1796}
1797input_seq* Get_ui_key_view_tab_screenshot(void)
1798{
1799   return options_get_input_seq(settings, M32OPTION_UI_KEY_VIEW_TAB_SCREENSHOT);
1800}
1801input_seq* Get_ui_key_view_tab_title(void)
1802{
1803   return options_get_input_seq(settings, M32OPTION_UI_KEY_VIEW_TAB_TITLE);
1804}
1805input_seq* Get_ui_key_view_tab_pcb(void)
1806{
1807   return options_get_input_seq(settings, M32OPTION_UI_KEY_VIEW_TAB_PCB);
1808}
1809input_seq* Get_ui_key_quit(void)
1810{
1811   return options_get_input_seq(settings, M32OPTION_UI_KEY_QUIT);
1812}
1813
1814
1815
1816static int GetUIJoy(const char *option_name, int joycodeIndex)
1817{
1818   const char *joycodes_string;
1819   int joycodes[4];
1820
1821   assert(0 <= joycodeIndex && joycodeIndex < 4);
1822   joycodes_string = options_get_string(settings, option_name);
1823   ColumnDecodeStringWithCount(joycodes_string, joycodes, ARRAY_LENGTH(joycodes));
1824   return joycodes[joycodeIndex];
1825}
1826
1827static void SetUIJoy(const char *option_name, int joycodeIndex, int val)
1828{
1829   const char *joycodes_string;
1830   int joycodes[4];
1831   char buffer[1024];
1832
1833   assert(0 <= joycodeIndex && joycodeIndex < 4);
1834   joycodes_string = options_get_string(settings, option_name);
1835   ColumnDecodeStringWithCount(joycodes_string, joycodes, ARRAY_LENGTH(joycodes));
1836
1837   joycodes[joycodeIndex] = val;
1838   ColumnEncodeStringWithCount(joycodes, buffer, ARRAY_LENGTH(joycodes));
1839   options_set_string(settings, option_name, buffer, OPTION_PRIORITY_CMDLINE);
1840
1841
1842}
1843
1844int GetUIJoyUp(int joycodeIndex)
1845{
1846   return GetUIJoy(M32OPTION_UI_JOY_UP, joycodeIndex);
1847}
1848
1849void SetUIJoyUp(int joycodeIndex, int val)
1850{
1851   SetUIJoy(M32OPTION_UI_JOY_UP, joycodeIndex, val);
1852}
1853
1854int GetUIJoyDown(int joycodeIndex)
1855{
1856   return GetUIJoy(M32OPTION_UI_JOY_DOWN, joycodeIndex);
1857}
1858
1859void SetUIJoyDown(int joycodeIndex, int val)
1860{
1861   SetUIJoy(M32OPTION_UI_JOY_DOWN, joycodeIndex, val);
1862}
1863
1864int GetUIJoyLeft(int joycodeIndex)
1865{
1866   return GetUIJoy(M32OPTION_UI_JOY_LEFT, joycodeIndex);
1867}
1868
1869void SetUIJoyLeft(int joycodeIndex, int val)
1870{
1871   SetUIJoy(M32OPTION_UI_JOY_LEFT, joycodeIndex, val);
1872}
1873
1874int GetUIJoyRight(int joycodeIndex)
1875{
1876   return GetUIJoy(M32OPTION_UI_JOY_RIGHT, joycodeIndex);
1877}
1878
1879void SetUIJoyRight(int joycodeIndex, int val)
1880{
1881   SetUIJoy(M32OPTION_UI_JOY_RIGHT, joycodeIndex, val);
1882}
1883
1884int GetUIJoyStart(int joycodeIndex)
1885{
1886   return GetUIJoy(M32OPTION_UI_JOY_START, joycodeIndex);
1887}
1888
1889void SetUIJoyStart(int joycodeIndex, int val)
1890{
1891   SetUIJoy(M32OPTION_UI_JOY_START, joycodeIndex, val);
1892}
1893
1894int GetUIJoyPageUp(int joycodeIndex)
1895{
1896   return GetUIJoy(M32OPTION_UI_JOY_PGUP, joycodeIndex);
1897}
1898
1899void SetUIJoyPageUp(int joycodeIndex, int val)
1900{
1901   SetUIJoy(M32OPTION_UI_JOY_PGUP, joycodeIndex, val);
1902}
1903
1904int GetUIJoyPageDown(int joycodeIndex)
1905{
1906   return GetUIJoy(M32OPTION_UI_JOY_PGDWN, joycodeIndex);
1907}
1908
1909void SetUIJoyPageDown(int joycodeIndex, int val)
1910{
1911   SetUIJoy(M32OPTION_UI_JOY_PGDWN, joycodeIndex, val);
1912}
1913
1914int GetUIJoyHome(int joycodeIndex)
1915{
1916   return GetUIJoy(M32OPTION_UI_JOY_HOME, joycodeIndex);
1917}
1918
1919void SetUIJoyHome(int joycodeIndex, int val)
1920{
1921   SetUIJoy(M32OPTION_UI_JOY_HOME, joycodeIndex, val);
1922}
1923
1924int GetUIJoyEnd(int joycodeIndex)
1925{
1926   return GetUIJoy(M32OPTION_UI_JOY_END, joycodeIndex);
1927}
1928
1929void SetUIJoyEnd(int joycodeIndex, int val)
1930{
1931   SetUIJoy(M32OPTION_UI_JOY_END, joycodeIndex, val);
1932}
1933
1934int GetUIJoySSChange(int joycodeIndex)
1935{
1936   return GetUIJoy(M32OPTION_UI_JOY_SS_CHANGE, joycodeIndex);
1937}
1938
1939void SetUIJoySSChange(int joycodeIndex, int val)
1940{
1941   SetUIJoy(M32OPTION_UI_JOY_SS_CHANGE, joycodeIndex, val);
1942}
1943
1944int GetUIJoyHistoryUp(int joycodeIndex)
1945{
1946   return GetUIJoy(M32OPTION_UI_JOY_HISTORY_UP, joycodeIndex);
1947}
1948
1949void SetUIJoyHistoryUp(int joycodeIndex, int val)
1950{
1951   SetUIJoy(M32OPTION_UI_JOY_HISTORY_UP, joycodeIndex, val);
1952}
1953
1954int GetUIJoyHistoryDown(int joycodeIndex)
1955{
1956   return GetUIJoy(M32OPTION_UI_JOY_HISTORY_DOWN, joycodeIndex);
1957}
1958
1959void SetUIJoyHistoryDown(int joycodeIndex, int val)
1960{
1961   SetUIJoy(M32OPTION_UI_JOY_HISTORY_DOWN, joycodeIndex, val);
1962}
1963
1964void SetUIJoyExec(int joycodeIndex, int val)
1965{
1966   SetUIJoy(M32OPTION_UI_JOY_EXEC, joycodeIndex, val);
1967}
1968
1969int GetUIJoyExec(int joycodeIndex)
1970{
1971   return GetUIJoy(M32OPTION_UI_JOY_EXEC, joycodeIndex);
1972}
1973
1974const char * GetExecCommand(void)
1975{
1976   return options_get_string(settings, M32OPTION_EXEC_COMMAND);
1977}
1978
1979void SetExecCommand(char *cmd)
1980{
1981   options_set_string(settings, M32OPTION_EXEC_COMMAND, cmd, OPTION_PRIORITY_CMDLINE);
1982}
1983
1984int GetExecWait(void)
1985{
1986   return options_get_int(settings, M32OPTION_EXEC_WAIT);
1987}
1988
1989void SetExecWait(int wait)
1990{
1991   options_set_int(settings, M32OPTION_EXEC_WAIT, wait, OPTION_PRIORITY_CMDLINE);
1992}
1993 
1994BOOL GetHideMouseOnStartup(void)
1995{
1996   return options_get_bool(settings, M32OPTION_HIDE_MOUSE);
1997}
1998
1999void SetHideMouseOnStartup(BOOL hide)
2000{
2001   options_set_bool(settings, M32OPTION_HIDE_MOUSE, hide, OPTION_PRIORITY_CMDLINE);
2002}
2003
2004BOOL GetRunFullScreen(void)
2005{
2006   return options_get_bool(settings, M32OPTION_FULL_SCREEN);
2007}
2008
2009void SetRunFullScreen(BOOL fullScreen)
2010{
2011   options_set_bool(settings, M32OPTION_FULL_SCREEN, fullScreen, OPTION_PRIORITY_CMDLINE);
2012}
2013
2014/***************************************************************************
2015    Internal functions
2016 ***************************************************************************/
2017
2018static void  CusColorEncodeString(const COLORREF *value, char* str)
2019{
2020   int  i;
2021   char tmpStr[256];
2022
2023   sprintf(tmpStr, "%u", (int) value[0]);
2024   
2025   strcpy(str, tmpStr);
2026
2027   for (i = 1; i < 16; i++)
2028   {
2029      sprintf(tmpStr, ",%u", (unsigned) value[i]);
2030      strcat(str, tmpStr);
2031   }
2032}
2033
2034static void CusColorDecodeString(const char* str, COLORREF *value)
2035{
2036   int  i;
2037   char *s, *p;
2038   char tmpStr[256];
2039
2040   strcpy(tmpStr, str);
2041   p = tmpStr;
2042   
2043   for (i = 0; p && i < 16; i++)
2044   {
2045      s = p;
2046     
2047      if ((p = strchr(s,',')) != NULL && *p == ',')
2048      {
2049         *p = '\0';
2050         p++;
2051      }
2052      value[i] = atoi(s);
2053   }
2054}
2055
2056
2057void ColumnEncodeStringWithCount(const int *value, char *str, int count)
2058{
2059   int  i;
2060   char buffer[100];
2061
2062   snprintf(buffer,sizeof(buffer),"%d",value[0]);
2063   
2064   strcpy(str,buffer);
2065
2066    for (i = 1; i < count; i++)
2067   {
2068      snprintf(buffer,sizeof(buffer),",%d",value[i]);
2069      strcat(str,buffer);
2070   }
2071}
2072
2073void ColumnDecodeStringWithCount(const char* str, int *value, int count)
2074{
2075   int  i;
2076   char *s, *p;
2077   char tmpStr[100];
2078
2079   if (str == NULL)
2080      return;
2081
2082   strcpy(tmpStr, str);
2083   p = tmpStr;
2084   
2085    for (i = 0; p && i < count; i++)
2086   {
2087      s = p;
2088     
2089      if ((p = strchr(s,',')) != NULL && *p == ',')
2090      {
2091         *p = '\0';
2092         p++;
2093      }
2094      value[i] = atoi(s);
2095    }
2096   }
2097
2098static void SplitterEncodeString(const int *value, char* str)
2099{
2100   int  i;
2101   char tmpStr[100];
2102
2103   sprintf(tmpStr, "%d", value[0]);
2104   
2105   strcpy(str, tmpStr);
2106
2107   for (i = 1; i < GetSplitterCount(); i++)
2108   {
2109      sprintf(tmpStr, ",%d", value[i]);
2110      strcat(str, tmpStr);
2111   }
2112}
2113
2114static void SplitterDecodeString(const char *str, int *value)
2115{
2116   int  i;
2117   char *s, *p;
2118   char tmpStr[100];
2119
2120   strcpy(tmpStr, str);
2121   p = tmpStr;
2122   
2123   for (i = 0; p && i < GetSplitterCount(); i++)
2124   {
2125      s = p;
2126     
2127      if ((p = strchr(s,',')) != NULL && *p == ',')
2128      {
2129         *p = '\0';
2130         p++;
2131      }
2132      value[i] = atoi(s);
2133   }
2134}
2135
2136/* Parse the given comma-delimited string into a LOGFONT structure */
2137static void FontDecodeString(const char* str, LOGFONT *f)
2138{
2139   char*    ptr;
2140   TCHAR*     t_ptr;
2141   
2142   sscanf(str, "%li,%li,%li,%li,%li,%i,%i,%i,%i,%i,%i,%i,%i",
2143         &f->lfHeight,
2144         &f->lfWidth,
2145         &f->lfEscapement,
2146         &f->lfOrientation,
2147         &f->lfWeight,
2148         (int*)&f->lfItalic,
2149         (int*)&f->lfUnderline,
2150         (int*)&f->lfStrikeOut,
2151         (int*)&f->lfCharSet,
2152         (int*)&f->lfOutPrecision,
2153         (int*)&f->lfClipPrecision,
2154         (int*)&f->lfQuality,
2155         (int*)&f->lfPitchAndFamily);
2156   ptr = strrchr(str, ',');
2157   if (ptr != NULL) {
2158      t_ptr = tstring_from_utf8(ptr + 1);
2159      if( !t_ptr )
2160         return;
2161      _tcscpy(f->lfFaceName, t_ptr);
2162      free(t_ptr);
2163   }
2164}
2165
2166/* Encode the given LOGFONT structure into a comma-delimited string */
2167static void FontEncodeString(const LOGFONT *f, char *str)
2168{
2169   char* utf8_FaceName = utf8_from_tstring(f->lfFaceName);
2170   if( !utf8_FaceName )
2171      return;
2172   
2173   sprintf(str, "%li,%li,%li,%li,%li,%i,%i,%i,%i,%i,%i,%i,%i,%s",
2174         f->lfHeight,
2175         f->lfWidth,
2176         f->lfEscapement,
2177         f->lfOrientation,
2178         f->lfWeight,
2179         f->lfItalic,
2180         f->lfUnderline,
2181         f->lfStrikeOut,
2182         f->lfCharSet,
2183         f->lfOutPrecision,
2184         f->lfClipPrecision,
2185         f->lfQuality,
2186         f->lfPitchAndFamily,
2187         utf8_FaceName);
2188         
2189   free(utf8_FaceName);
2190}
2191
2192static void TabFlagsEncodeString(int data, char *str)
2193{
2194   int i;
2195   int num_saved = 0;
2196
2197   strcpy(str,"");
2198
2199   // we save the ones that are NOT displayed, so we can add new ones
2200   // and upgraders will see them
2201   for (i=0;i<MAX_TAB_TYPES;i++)
2202   {
2203      if (((data & (1 << i)) == 0) && GetImageTabShortName(i))
2204      {
2205         if (num_saved != 0)
2206            strcat(str, ", ");
2207
2208         strcat(str,GetImageTabShortName(i));
2209         num_saved++;
2210      }
2211   }
2212}
2213
2214static void TabFlagsDecodeString(const char *str, int *data)
2215{
2216   char s[2000];
2217   char *token;
2218
2219   snprintf(s, ARRAY_LENGTH(s), "%s", str);
2220
2221   // simple way to set all tab bits "on"
2222   *data = (1 << MAX_TAB_TYPES) - 1;
2223
2224   token = strtok(s,", \t");
2225   while (token != NULL)
2226   {
2227      int j;
2228
2229      for (j=0;j<MAX_TAB_TYPES;j++)
2230      {
2231         if (!GetImageTabShortName(j) || (strcmp(GetImageTabShortName(j), token) == 0))
2232         {
2233            // turn off this bit
2234            *data &= ~(1 << j);
2235            break;
2236         }
2237      }
2238      token = strtok(NULL,", \t");
2239   }
2240
2241   if (*data == 0)
2242   {
2243      // not allowed to hide all tabs, because then why even show the area?
2244      *data = (1 << TAB_SCREENSHOT);
2245   }
2246}
2247
2248static file_error LoadSettingsFile(core_options *opts, const char *filename)
2249{
2250   core_file *file;
2251   file_error filerr;
2252
2253   filerr = core_fopen(filename, OPEN_FLAG_READ, &file);
2254   if (filerr == FILERR_NONE)
2255   {
2256      options_parse_ini_file(opts, file, OPTION_PRIORITY_CMDLINE);
2257      core_fclose(file);
2258   }
2259   return filerr;
2260}
2261
2262
2263static file_error SaveSettingsFile(core_options *opts, const char *filename)
2264{
2265   core_file *file;
2266   file_error filerr;
2267
2268   if (opts != NULL)
2269   {
2270      filerr = core_fopen(filename, OPEN_FLAG_WRITE | OPEN_FLAG_CREATE | OPEN_FLAG_CREATE_PATHS, &file);
2271      if (filerr == FILERR_NONE)
2272      {
2273         options_output_ini_file(opts, file);
2274         core_fclose(file);
2275      }
2276   }
2277   else
2278   {
2279      filerr = osd_rmfile(filename);
2280   }
2281
2282   return filerr;
2283}
2284
2285
2286
2287static void GetGlobalOptionsFileName(char *filename, size_t filename_size)
2288{
2289   // copy INI directory
2290   snprintf(filename, filename_size, "%s\\%s.ini", GetIniDir(), CONFIGNAME);
2291}
2292
2293/* Register access functions below */
2294static void LoadOptionsAndSettings(void)
2295{
2296   char buffer[MAX_PATH];
2297
2298   // parse MAME32ui.ini - always in the current directory.
2299   LoadSettingsFile(settings, UI_INI_FILENAME);
2300
2301   // parse global options ini/mame32.ini
2302   GetGlobalOptionsFileName(buffer, ARRAY_LENGTH(buffer));
2303   LoadSettingsFile(global, buffer);
2304}
2305
2306const char * GetFolderNameByID(UINT nID)
2307{
2308   UINT i;
2309   extern FOLDERDATA g_folderData[];
2310   extern LPEXFOLDERDATA ExtraFolderData[];
2311
2312   for (i = 0; i < MAX_EXTRA_FOLDERS * MAX_EXTRA_SUBFOLDERS; i++)
2313   {
2314      if( ExtraFolderData[i] )
2315      {
2316         if (ExtraFolderData[i]->m_nFolderId == nID)
2317         {
2318            return ExtraFolderData[i]->m_szTitle;
2319         }
2320      }
2321   }
2322   for( i = 0; i < MAX_FOLDERS; i++)
2323   {
2324      if (g_folderData[i].m_nFolderId == nID)
2325      {
2326         
2327         return g_folderData[i].m_lpTitle;
2328      }
2329   }
2330   return NULL;
2331}
2332
2333
2334DWORD GetFolderFlags(int folder_index)
2335{
2336   LPTREEFOLDER lpFolder = GetFolder(folder_index);
2337
2338   if (lpFolder)
2339      return lpFolder->m_dwFlags & F_MASK;
2340
2341   return 0;
2342#if 0
2343   int i;
2344
2345   for (i=0;i<num_folder_filters;i++)
2346   {
2347      if (folder_filters[i].folder_index == folder_index)
2348      {
2349         //dprintf("found folder filter %i %i",folder_index,folder_filters[i].filters);
2350         return folder_filters[i].filters;
2351      }
2352   }
2353   return 0;
2354#endif
2355}
2356
2357
2358/* Decode the flags into a DWORD */
2359static DWORD DecodeFolderFlags(const char *buf)
2360{
2361   DWORD flags = 0;
2362   int shift = 0;
2363   const char *ptr = buf;
2364
2365   while (*ptr && (1 << shift) & F_MASK)
2366   {
2367      if (*ptr++ == '1')
2368      {
2369         flags |= (1 << shift);
2370      }
2371      shift++;
2372   }
2373   return flags;
2374}
2375
2376/* Encode the flags into a string */
2377static const char * EncodeFolderFlags(DWORD value)
2378{
2379   static char buf[40];
2380   int shift = 0;
2381
2382   memset(buf,'\0', sizeof(buf));
2383
2384   while ((1 << shift) & F_MASK) {
2385      buf[shift] = (value & (1 << shift)) ? '1' : '0';
2386      shift++;
2387   }
2388
2389   return buf;
2390}
2391
2392/* MSH 20080813
2393 * Read the folder filters from MAME32ui.ini.  This must only
2394 * be called AFTER the folders have all been created.
2395 */
2396void LoadFolderFlags(void)
2397{
2398   core_options *opts;
2399   int numFolders;
2400   LPTREEFOLDER lpFolder;
2401   int i;
2402   options_entry entries[2];
2403
2404   memcpy(entries, filterOptions, sizeof(filterOptions));
2405
2406   opts = options_create(memory_error);
2407
2408   if (NULL == opts)
2409   {
2410      return;
2411   }
2412
2413   numFolders = GetNumFolders();
2414
2415   for (i = 0; i < numFolders; i++)
2416   {
2417      lpFolder = GetFolder(i);
2418
2419      if (lpFolder)
2420      {
2421         char folder_name[80];
2422         char *ptr;
2423         astring *option_name;
2424
2425         // Convert spaces to underscores
2426         strcpy(folder_name, lpFolder->m_lpTitle);
2427         ptr = folder_name;
2428         while (*ptr && *ptr != '\0')
2429         {
2430            if (*ptr == ' ')
2431            {
2432               *ptr = '_';
2433            }
2434            ptr++;
2435         }
2436
2437         option_name = astring_assemble_2(astring_alloc(), folder_name, "_filters");
2438         // create entry
2439         entries[0].name = astring_c(option_name);
2440         options_add_entries(opts, entries);
2441         astring_free(option_name);
2442      }
2443   }
2444
2445   // These are overlayed at the end of our UI ini
2446   // The normal read will skip them.
2447    LoadSettingsFile(opts, UI_INI_FILENAME);
2448
2449   // retrive the stored values
2450   for (i = 0; i < numFolders; i++)
2451   {
2452      lpFolder = GetFolder(i);
2453
2454      if (lpFolder)
2455      {
2456         char folder_name[80];
2457         char *ptr;
2458         astring *option_name;
2459         const char *value;
2460
2461         // Convert spaces to underscores
2462         strcpy(folder_name, lpFolder->m_lpTitle);
2463         ptr = folder_name;
2464         while (*ptr && *ptr != '\0')
2465         {
2466            if (*ptr == ' ')
2467            {
2468               *ptr = '_';
2469            }
2470            ptr++;
2471         }
2472         option_name = astring_assemble_2(astring_alloc(), folder_name, "_filters" );
2473         // get entry and decode it
2474         value = options_get_string(opts, astring_c(option_name));
2475         astring_free(option_name);
2476
2477         if (value)
2478         {
2479            lpFolder->m_dwFlags |= DecodeFolderFlags(value) & F_MASK;
2480         }
2481      }
2482   }
2483   // fee the options
2484   options_free(opts);
2485}
2486
2487
2488
2489// Copy options, if entry doesn't exist in the dest, create it.
2490static void copy_options_ex(core_options *pDestOpts, core_options *pSourceOpts)
2491{
2492   options_enumerator *enumerator;
2493   const char *option_name;
2494   const char *option_value;
2495   options_entry entries[2];
2496
2497   memcpy(entries, filterOptions, sizeof(filterOptions));
2498
2499   enumerator = options_enumerator_begin(pSourceOpts);
2500
2501   if (enumerator != NULL)
2502   {
2503      while((option_name = options_enumerator_next(enumerator)) != NULL)
2504      {
2505         option_value = options_get_string(pSourceOpts, option_name);
2506         {
2507            const char *existing = options_get_string(pDestOpts, option_name);
2508            if (NULL == existing || *existing == '\0')
2509            {
2510               entries[0].name = option_name;
2511               // create entry
2512               options_add_entries(pDestOpts, entries);
2513            }
2514            if (strcmp(option_value, existing) != 0)
2515               options_set_string(pDestOpts, option_name, option_value, OPTION_PRIORITY_CMDLINE);
2516         }
2517      }
2518      options_enumerator_free(enumerator);
2519   }
2520}
2521
2522// Adds our folder flags to a temporarty core_options, for saving.
2523static core_options * AddFolderFlags(core_options *settings)
2524{
2525   core_options *opts;
2526   int numFolders;
2527   int i;
2528   LPTREEFOLDER lpFolder;
2529   int num_entries = 0;
2530   options_entry entries[2];
2531
2532   opts = options_create(memory_error);
2533
2534   if (NULL == opts)
2535   {
2536      return NULL;
2537   }
2538
2539   options_add_entries(opts, regSettings);
2540   copy_options_ex(opts, settings);
2541
2542   memcpy(entries, filterOptions, sizeof(filterOptions));
2543   entries[0].name = NULL;
2544   entries[0].defvalue = NULL;
2545   entries[0].flags = OPTION_HEADER;
2546   entries[0].description = "FOLDER FILTERS";
2547   options_add_entries(opts, entries);
2548
2549   memcpy(entries, filterOptions, sizeof(filterOptions));
2550
2551   numFolders = GetNumFolders();
2552
2553   for (i = 0; i < numFolders; i++)
2554   {
2555      lpFolder = GetFolder(i);
2556      if (lpFolder && (lpFolder->m_dwFlags & F_MASK) != 0)
2557      {
2558         char folder_name[80];
2559         char *ptr;
2560         astring *option_name;
2561
2562         // Convert spaces to underscores
2563         strcpy(folder_name, lpFolder->m_lpTitle);
2564         ptr = folder_name;
2565         while (*ptr && *ptr != '\0')
2566         {
2567            if (*ptr == ' ')
2568            {
2569               *ptr = '_';
2570            }
2571            ptr++;
2572         }
2573         
2574         option_name = astring_assemble_2(astring_alloc(), folder_name, "_filters" );
2575         
2576         // create entry
2577         entries[0].name = astring_c(option_name);
2578         options_add_entries(opts, entries);
2579
2580         // store entry
2581            options_set_string(opts, astring_c(option_name), EncodeFolderFlags(lpFolder->m_dwFlags), OPTION_PRIORITY_CMDLINE);
2582         astring_free(option_name);
2583
2584         // increment counter
2585         num_entries++;
2586      }
2587   }
2588   if (num_entries == 0) {
2589      options_free(opts);
2590      opts = NULL;
2591   }
2592   return opts;
2593}
2594
2595// Save the UI ini
2596void SaveOptions(void)
2597{
2598   if (save_gui_settings)
2599   {
2600      // Add the folder flag to settings.
2601      core_options *opts = AddFolderFlags(settings);
2602      // Save opts if it is non-null, else save settings.
2603      // It will be null if there are no filters set.
2604      SaveSettingsFile((opts == NULL) ? settings : opts, UI_INI_FILENAME);
2605      // Free up the opts allocated by AddFolderFlags.
2606      if (opts)
2607      {
2608         options_free(opts);
2609      }
2610   }
2611}
2612
2613
2614void SaveDefaultOptions(void)
2615{
2616   char buffer[MAX_PATH];
2617   GetGlobalOptionsFileName(buffer, ARRAY_LENGTH(buffer));
2618   SaveSettingsFile(global, buffer);
2619}
2620
2621char * GetVersionString(void)
2622{
2623   return build_version;
2624}
2625
2626
2627BOOL IsGlobalOption(const char *option_name)
2628{
2629   static const char *global_options[] =
2630   {
2631      OPTION_ROMPATH,
2632#ifdef MESS
2633      OPTION_HASHPATH,
2634#endif // MESS
2635      OPTION_SAMPLEPATH,
2636      OPTION_ARTPATH,
2637      OPTION_CTRLRPATH,
2638      OPTION_INIPATH,
2639      OPTION_FONTPATH,
2640      OPTION_CFG_DIRECTORY,
2641      OPTION_NVRAM_DIRECTORY,
2642      OPTION_MEMCARD_DIRECTORY,
2643      OPTION_INPUT_DIRECTORY,
2644      OPTION_STATE_DIRECTORY,
2645      OPTION_SNAPSHOT_DIRECTORY,
2646      OPTION_DIFF_DIRECTORY,
2647      OPTION_COMMENT_DIRECTORY
2648   };
2649   int i;
2650   char command_name[128];
2651   char *s;
2652
2653   // determine command name
2654   snprintf(command_name, ARRAY_LENGTH(command_name), "%s", option_name);
2655   s = strchr(command_name, ';');
2656   if (s)
2657      *s = '\0';
2658
2659   for (i = 0; i < ARRAY_LENGTH(global_options); i++)
2660   {
2661      if (!strcmp(command_name, global_options[i]))
2662         return TRUE;
2663   }
2664   return FALSE;
2665}
2666
2667
2668/* ui_parse_ini_file - parse a single INI file */
2669static void ui_parse_ini_file(core_options *opts, const char *name)
2670{
2671   astring *fname;
2672
2673   /* open the file; if we fail, that's ok */
2674   fname = astring_assemble_4(astring_alloc(), GetIniDir(), PATH_SEPARATOR, name, ".ini");
2675   LoadSettingsFile(opts, astring_c(fname));
2676   astring_free(fname);
2677}
2678
2679
2680/*  get options, based on passed in option level. */
2681core_options * load_options(OPTIONS_TYPE opt_type, int game_num)
2682{
2683   core_options *opts;
2684   const game_driver *driver = NULL;
2685
2686   
2687   opts = options_create(memory_error);
2688
2689   if (opts == NULL)
2690   {
2691      return NULL;
2692   }
2693
2694   /* add the options */
2695   AddOptions(opts, mame_core_options, (GLOBAL_OPTIONS == game_num));
2696   AddOptions(opts, mame_win_options, (GLOBAL_OPTIONS == game_num));
2697
2698   /* Copy over the defaults */
2699   options_copy(opts, global);
2700
2701   if (opt_type == OPTIONS_GLOBAL)
2702   {
2703      return opts;
2704   }
2705
2706   /* debug builds: parse "debug.ini" as well */
2707#ifdef MAME_DEBUG
2708   ui_parse_ini_file(opts, "debug");
2709#endif
2710   if (game_num >= 0)
2711   {
2712      driver = drivers[game_num];
2713   }
2714
2715   /* if we have a valid game driver, parse game-specific INI files */
2716   if (driver != NULL)
2717   {
2718      const game_driver *parent = driver_get_clone(driver);
2719      const game_driver *gparent = (parent != NULL) ? driver_get_clone(parent) : NULL;
2720      astring *basename;
2721      astring *srcname;
2722      machine_config drv;
2723
2724      /* expand the machine driver to look at the info */
2725      expand_machine_driver(driver->drv, &drv);
2726
2727      /* parse "vector.ini" for vector games */
2728      if (drv.video_attributes & VIDEO_TYPE_VECTOR)
2729         ui_parse_ini_file(opts, "vector");
2730
2731      if (opt_type == OPTIONS_VECTOR)
2732      {
2733         return opts;
2734      }
2735
2736      /* then parse "<sourcefile>.ini" */
2737      basename = core_filename_extract_base(astring_alloc(), driver->source_file, TRUE);
2738      srcname = astring_assemble_3(astring_alloc(), "source", PATH_SEPARATOR, astring_c(basename));
2739      ui_parse_ini_file(opts, astring_c(srcname));
2740      astring_free(srcname);
2741      astring_free(basename);
2742
2743      if (opt_type == OPTIONS_SOURCE)
2744      {
2745         return opts;
2746      }
2747
2748      /* then parent the grandparent, parent, and game-specific INIs */
2749      if (gparent != NULL)
2750         ui_parse_ini_file(opts, gparent->name);
2751      if (parent != NULL)
2752         ui_parse_ini_file(opts, parent->name);
2753
2754      if (opt_type == OPTIONS_PARENT)
2755      {
2756         return opts;
2757      }
2758
2759      ui_parse_ini_file(opts, driver->name);
2760
2761      if (opt_type == OPTIONS_GAME)
2762      {
2763         return opts;
2764      }
2765   }
2766   options_free(opts);
2767   return NULL;
2768}
2769
2770
2771
2772/* Add an entry to a core_options */
2773static BOOL add_options_entry(core_options *opts, const options_entry *entry)
2774{
2775   options_entry entries[2];
2776
2777   if (NULL != entry)
2778   {
2779        // Add the entry to our opts
2780      memcpy(entries, entry, sizeof(options_entry));
2781      memset(&entries[1], 0, sizeof(options_entry));
2782      options_add_entries(opts, entries);
2783      return TRUE;
2784   }
2785   return FALSE;
2786}
2787
2788/*
2789 * return new core_options with only the differences contained in opts
2790 * different from the values in defaults.
2791 */
2792static core_options * options_prune(core_options *opts1, core_options *opts2)
2793{
2794   const options_entry *entry;
2795   core_options *pruned_options = options_create(memory_error);
2796   int changes = 0;
2797   char name[40];
2798
2799   // walk the core options
2800   entry = mame_core_options;
2801   while (entry->name != NULL || (entry->flags & OPTION_HEADER))
2802   {
2803      if (entry->name != NULL)
2804      {
2805         char *ptr;
2806         const char *value1, *value2;
2807
2808         strcpy(name, entry->name);
2809         // Trim off from ;altname
2810         if ((ptr = strchr(name, ';')) != NULL)
2811            *ptr = '\0';
2812         // Trim off from (min-max)
2813         if ((ptr = strchr(name, '(')) != NULL)
2814            *ptr = '\0';
2815
2816         value1 = options_get_string(opts1, name);
2817         value2 = options_get_string(opts2, name);
2818
2819         if (value1 != NULL  && value2 != NULL)
2820         {
2821            if (strcmp(value1, value2) != 0)
2822            {
2823               if (add_options_entry(pruned_options, entry))
2824               {
2825                  options_set_string(pruned_options, name, value1, OPTION_PRIORITY_CMDLINE);
2826                  changes++;
2827               }
2828            }
2829         }
2830      }
2831      entry++;
2832   }
2833
2834   // walk the win options
2835   entry = mame_win_options;
2836   while (entry->name != NULL || (entry->flags & OPTION_HEADER))
2837   {
2838      if (entry->name != NULL)
2839      {
2840         char *ptr;
2841         const char *value1, *value2;
2842
2843         strcpy(name, entry->name);
2844         // Trim off from ;altname
2845         if ((ptr = strchr(name, ';')) != NULL)
2846            *ptr = '\0';
2847         // Trim off from (min-max)
2848         if ((ptr = strchr(name, '(')) != NULL)
2849            *ptr = '\0';
2850
2851         value1 = options_get_string(opts1, name);
2852         value2 = options_get_string(opts2, name);
2853
2854         if (value1 != NULL  && value2 != NULL)
2855         {
2856            if (strcmp(value1, value2) != 0)
2857            {
2858               if (add_options_entry(pruned_options, entry))
2859               {
2860                  options_set_string(pruned_options, name, value1, OPTION_PRIORITY_CMDLINE);
2861                  changes++;
2862               }
2863            }
2864         }
2865      }
2866      entry++;
2867   }
2868
2869   // no changes made
2870   if (0 == changes)
2871   {
2872      options_free(pruned_options);
2873      pruned_options = NULL;
2874   }
2875   return pruned_options;
2876}
2877
2878/*
2879 * Save ini file based on game_num and passed in opt_type.  If opts are
2880 * NULL, the ini wiil be removed.
2881 *
2882 * game_num must be valid or the driver cannot be expanded and anything
2883 * with a higher priority than OPTIONS_VECTOR will not be saved.
2884 */
2885void save_options(OPTIONS_TYPE opt_type, core_options *opts, int game_num)
2886{
2887
2888   const game_driver *driver = NULL;
2889   astring *filename = NULL;
2890   core_options *save_options = NULL;
2891   BOOL use_opts = TRUE;
2892
2893   if (OPTIONS_GLOBAL != opt_type && NULL != opts && !options_equal(opts, global))
2894   {
2895      core_options *default_options = load_options(opt_type - 1, game_num);
2896      save_options = options_prune(opts, default_options);
2897      options_free(default_options);
2898      use_opts = FALSE;
2899   }
2900
2901   if (game_num >= 0)
2902   {
2903      driver = drivers[game_num];
2904   }
2905
2906   if (opt_type == OPTIONS_GLOBAL)
2907   {
2908      /* Don't try to save a null global options file,  or it will be erased. */
2909      if (NULL == opts)
2910         return;
2911      options_copy(global, opts);
2912      filename = astring_cpyc(astring_alloc(), CONFIGNAME);
2913   } else if (opt_type == OPTIONS_VECTOR)
2914   {
2915      filename = astring_cpyc(astring_alloc(), "vector");
2916   } else if (driver != NULL)
2917   {
2918      astring *basename, *srcname;
2919      machine_config drv;
2920
2921      /* expand the machine driver to look at the info */
2922      expand_machine_driver(driver->drv, &drv);
2923
2924      switch (opt_type)
2925      {
2926      case OPTIONS_SOURCE:
2927         /* determine the <sourcefile> */
2928         basename = core_filename_extract_base(astring_alloc(), driver->source_file, TRUE);
2929         srcname = astring_assemble_3(astring_alloc(), "source", PATH_SEPARATOR, astring_c(basename));
2930         filename = astring_cpyc(astring_alloc(),astring_c(srcname));
2931         astring_free(srcname);
2932         astring_free(basename);
2933         break;
2934      case OPTIONS_GAME:
2935         filename = astring_cpyc(astring_alloc(), driver->name);
2936         break;
2937      default:
2938         break;
2939      }
2940   }
2941   if (filename != NULL)
2942   {
2943      astring *filepath = NULL;
2944      filepath = astring_assemble_4(astring_alloc(), GetIniDir(), PATH_SEPARATOR, astring_c(filename), ".ini");
2945      astring_free(filename);
2946
2947      SaveSettingsFile((use_opts) ? opts : save_options, astring_c(filepath));
2948      astring_free(filepath);
2949   }
2950   if (NULL != save_options)
2951   {
2952      options_free(save_options);
2953   }
2954}
2955
2956/* Remove all the srcname.ini files from inipath/source directory. */
2957static void remove_all_source_options(void) {
2958   WIN32_FIND_DATA findFileData;
2959   HANDLE hFindFile;
2960   astring *pathname, *match;
2961
2962   /*
2963    * Easiest to just open the ini/source folder if it exists,
2964    * then remove all the files in it that end in ini.
2965    */
2966   pathname = astring_assemble_3(astring_alloc(), GetIniDir(), PATH_SEPARATOR, "source");
2967   match = astring_assemble_3(astring_alloc(), astring_c(pathname), PATH_SEPARATOR, "*.ini");
2968   if ((hFindFile = FindFirstFile(astring_c(match), &findFileData)) != INVALID_HANDLE_VALUE)
2969   {
2970      astring_free(match);
2971      match = astring_assemble_3(astring_alloc(), astring_c(pathname), PATH_SEPARATOR, findFileData.cFileName );
2972      osd_rmfile(astring_c(match));
2973      astring_free(match);
2974
2975      while (0 != FindNextFile(hFindFile, &findFileData))
2976      {
2977         match = astring_assemble_3(astring_alloc(), astring_c(pathname), PATH_SEPARATOR, findFileData.cFileName );
2978         osd_rmfile(astring_c(match));
2979         astring_free(match);
2980      }
2981
2982      FindClose(hFindFile);
2983
2984   }
2985   else
2986   {
2987      astring_free(match);
2988   }
2989   astring_free(pathname);
2990
2991}
2992
2993// Reset the given core_options to their default settings.
2994static void ResetToDefaults(core_options *opts, int priority)
2995{
2996   // iterate through the options setting each one back to the default value.
2997   options_revert(opts, priority);
2998}
2999
3000
3001
src/osd/winui/res/toolbar.bmp
src/osd/winui/res/icon_sndn.ico
src/osd/winui/res/custom.ico
src/osd/winui/res/win_clone.ico
src/osd/winui/res/icon_asc.ico
src/osd/winui/res/about.bmp
src/osd/winui/res/header_down.ico
src/osd/winui/res/win_redx.ico
src/osd/winui/res/mame32.manifest
r0r996
1<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
3<assemblyIdentity version="1.0.0.0" processorArchitecture="x86" name="MAME32" type="win32" />
4<description>Multiple Arcade Machine Emulator with built in user interface</description>
5<dependency>
6<dependentAssembly>
7<assemblyIdentity type="win32" name="Microsoft.Windows.Common-Controls" version="6.0.0.0" publicKeyToken="6595b64144ccf1df" language="*" processorArchitecture="x86"/>
8</dependentAssembly>
9</dependency>
10</assembly>
src/osd/winui/res/vert.ico
src/osd/winui/res/working.ico
src/osd/winui/res/horz.ico
src/osd/winui/res/splith.cur
src/osd/winui/res/icon_des.ico
src/osd/winui/res/controller.ico
src/osd/winui/res/cpu.ico
src/osd/winui/res/sound.ico
src/osd/winui/res/win_unkn.ico
src/osd/winui/res/win_noro.ico
src/osd/winui/res/foldsrc.ico
src/osd/winui/res/nonwork.ico
src/osd/winui/res/manufact.ico
src/osd/winui/res/foldyear.ico
src/osd/winui/res/foldopen.ico
src/osd/winui/res/folder.ico
src/osd/winui/res/foldunav.ico
src/osd/winui/res/bkground.bmp
src/osd/winui/res/mame32.ico
src/osd/winui/res/checkmark.ico
src/osd/winui/res/harddisk.ico
src/osd/winui/res/icon_snd.ico
src/osd/winui/res/header_up.ico
src/osd/winui/res/win_roms.ico
src/osd/winui/res/joystick.ico
src/osd/winui/res/source.ico
src/osd/winui/res/keyboard.ico
src/osd/winui/res/bkgnd16.bmp
src/osd/winui/res/year.ico
src/osd/winui/res/foldavail.ico
src/osd/winui/res/samples.ico
src/osd/winui/res/display.ico
src/osd/winui/res/foldmanu.ico
src/osd/winui/dirwatch.h
r0r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11 ***************************************************************************/
12
13typedef struct DirWatcher *PDIRWATCHER;
14
15PDIRWATCHER DirWatcher_Init(HWND hwndTarget, UINT nMessage);
16BOOL DirWatcher_Watch(PDIRWATCHER pWatcher, WORD nIndex, LPCSTR pszPathList, BOOL bWatchSubtrees);
17void DirWatcher_Free(PDIRWATCHER pWatcher);
src/osd/winui/audit32.c
r0r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11 ***************************************************************************/
12 
13 /***************************************************************************
14
15  audit32.c
16
17  Audit dialog
18
19***************************************************************************/
20
21#define WIN32_LEAN_AND_MEAN
22#include <windows.h>
23#include <windowsx.h>
24#include <commctrl.h>
25#include <stdio.h>
26#include <richedit.h>
27#include <tchar.h>
28
29#include "screenshot.h"
30#include "win32ui.h"
31#include "winutf8.h"
32
33#include <audit.h>
34#include <unzip.h>
35
36#include "resource.h"
37
38#include "bitmask.h"
39#include "m32opts.h"
40#include "m32util.h"
41#include "audit32.h"
42#include "properties.h"
43#include "emuopts.h"
44#include "winmain.h"
45#include "strconv.h"
46
47#ifdef _MSC_VER
48#define vsnprintf _vsnprintf
49#endif
50
51/***************************************************************************
52    function prototypes
53 ***************************************************************************/
54
55static DWORD WINAPI AuditThreadProc(LPVOID hDlg);
56static INT_PTR CALLBACK AuditWindowProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam);
57static void ProcessNextRom(void);
58static void ProcessNextSample(void);
59static void CLIB_DECL DetailsPrintf(const char *fmt, ...);
60static const char * StatusString(int iStatus);
61
62/***************************************************************************
63    Internal variables
64 ***************************************************************************/
65
66#define SAMPLES_NOT_USED    3
67#define MAX_AUDITBOX_TEXT   0x7FFFFFFE
68
69HWND hAudit;
70static int rom_index;
71static int roms_correct;
72static int roms_incorrect;
73static int sample_index;
74static int samples_correct;
75static int samples_incorrect;
76
77static BOOL bPaused = FALSE;
78static BOOL bCancel = FALSE;
79
80/***************************************************************************
81    External functions 
82 ***************************************************************************/
83
84void AuditDialog(HWND hParent)
85{
86   HMODULE hModule = NULL;
87   rom_index         = 0;
88   roms_correct      = 0;
89   roms_incorrect    = 0;
90   sample_index      = 0;
91   samples_correct   = 0;
92   samples_incorrect = 0;
93
94   //RS use Riched32.dll
95   hModule = LoadLibrary(TEXT("Riched32.dll"));
96   if( hModule )
97   {
98      DialogBox(GetModuleHandle(NULL),MAKEINTRESOURCE(IDD_AUDIT),hParent,AuditWindowProc);
99      FreeLibrary( hModule );
100      hModule = NULL;
101   }
102   else
103   {
104       MessageBox(GetMainWindow(),TEXT("Unable to Load Riched32.dll"),TEXT("Error"),
105               MB_OK | MB_ICONERROR);
106   }
107}
108
109void InitGameAudit(int gameIndex)
110{
111   rom_index = gameIndex;
112}
113
114const char * GetAuditString(int audit_result)
115{
116   switch (audit_result)
117   {
118   case CORRECT :
119   case BEST_AVAILABLE :
120      return "Yes";
121
122   case NOTFOUND :
123   case INCORRECT :
124      return "No";
125      break;
126
127   case UNKNOWN :
128      return "?";
129
130   default:
131      dprintf("unknown audit value %i",audit_result);
132   }
133
134   return "?";
135}
136
137BOOL IsAuditResultKnown(int audit_result)
138{
139   return audit_result != UNKNOWN;
140}
141
142BOOL IsAuditResultYes(int audit_result)
143{
144   return audit_result == CORRECT || audit_result == BEST_AVAILABLE;
145}
146
147BOOL IsAuditResultNo(int audit_result)
148{
149   return audit_result == NOTFOUND || audit_result == INCORRECT;
150}
151
152
153/***************************************************************************
154    Internal functions
155 ***************************************************************************/
156
157static void Mame32Output(void *param, const char *format, va_list argptr)
158{
159   char buffer[512];
160   vsnprintf(buffer, sizeof(buffer) / sizeof(buffer[0]), format, argptr);
161   DetailsPrintf("%s", buffer);
162}
163
164static int ProcessAuditResults(int game, audit_record *audit, int audit_records)
165{
166   output_callback prevcb;
167   void *prevparam;
168   int res;
169
170   mame_set_output_channel(OUTPUT_CHANNEL_INFO, Mame32Output, NULL, &prevcb, &prevparam);
171   res = audit_summary(drivers[game], audit_records, audit, TRUE);
172   mame_set_output_channel(OUTPUT_CHANNEL_INFO, prevcb ? prevcb : mame_null_output_callback, prevparam, NULL, NULL);
173
174   return res;
175}
176
177// Verifies the ROM set while calling SetRomAuditResults   
178int Mame32VerifyRomSet(int game)
179{
180   audit_record *audit;
181   int audit_records;
182   int res;
183
184   // perform the audit
185   audit_records = audit_images(Mame32Global(), drivers[game], AUDIT_VALIDATE_FAST, &audit);
186   res = ProcessAuditResults(game, audit, audit_records);
187   if (audit_records > 0)
188      free(audit);
189
190   SetRomAuditResults(game, res);
191   return res;
192}
193
194// Verifies the Sample set while calling SetSampleAuditResults   
195int Mame32VerifySampleSet(int game)
196{
197   audit_record *audit;
198   int audit_records;
199   int res;
200
201   // perform the audit
202   audit_records = audit_samples(Mame32Global(), drivers[game], &audit);
203   res = ProcessAuditResults(game, audit, audit_records);
204   if (audit_records > 0)
205      free(audit);
206
207   SetSampleAuditResults(game, res);
208   return res;
209}
210
211static DWORD WINAPI AuditThreadProc(LPVOID hDlg)
212{
213   char buffer[200];
214
215   while (!bCancel)
216   {
217      if (!bPaused)
218      {
219         if (rom_index != -1)
220         {
221            sprintf(buffer, "Checking Game %s - %s",
222               drivers[rom_index]->name, drivers[rom_index]->description);
223            win_set_window_text_utf8(hDlg, buffer);
224            ProcessNextRom();
225         }
226         else
227         {
228            if (sample_index != -1)
229            {
230               sprintf(buffer, "Checking Game %s - %s",
231                  drivers[sample_index]->name, drivers[sample_index]->description);
232               win_set_window_text_utf8(hDlg, buffer);
233               ProcessNextSample();
234            }
235            else
236            {
237               win_set_window_text_utf8(hDlg, "File Audit");
238               EnableWindow(GetDlgItem(hDlg, IDPAUSE), FALSE);
239               ExitThread(1);
240            }
241         }
242      }
243   }
244   return 0;
245}
246
247static INT_PTR CALLBACK AuditWindowProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam)
248{
249   static HANDLE hThread;
250   static DWORD dwThreadID;
251   DWORD dwExitCode;
252   HWND hEdit;
253
254   switch (Msg)
255   {
256   case WM_INITDIALOG:
257      hAudit = hDlg;
258      //RS 20030613 Set Bkg of RichEdit Ctrl
259      hEdit = GetDlgItem(hAudit, IDC_AUDIT_DETAILS);
260      if (hEdit != NULL)
261      {
262         SendMessage( hEdit, EM_SETBKGNDCOLOR, FALSE, GetSysColor(COLOR_BTNFACE) );
263         // MSH - Set to max
264         SendMessage( hEdit, EM_SETLIMITTEXT, MAX_AUDITBOX_TEXT, 0 );
265
266      }
267      SendDlgItemMessage(hDlg, IDC_ROMS_PROGRESS,    PBM_SETRANGE, 0, MAKELPARAM(0, driver_list_get_count(drivers)));
268      SendDlgItemMessage(hDlg, IDC_SAMPLES_PROGRESS, PBM_SETRANGE, 0, MAKELPARAM(0, driver_list_get_count(drivers)));
269      bPaused = FALSE;
270      bCancel = FALSE;
271      rom_index = 0;
272      hThread = CreateThread(NULL, 0, AuditThreadProc, hDlg, 0, &dwThreadID);
273      return 1;
274
275   case WM_COMMAND:
276      switch (LOWORD(wParam))
277      {
278      case IDCANCEL:
279            bPaused = FALSE;
280         if (hThread)
281         {
282            bCancel = TRUE;
283            if (GetExitCodeThread(hThread, &dwExitCode) && dwExitCode == STILL_ACTIVE)
284            {
285               PostMessage(hDlg, WM_COMMAND, wParam, lParam);
286               return 1;
287            }
288            CloseHandle(hThread);
289         }
290         EndDialog(hDlg,0);
291         break;
292
293      case IDPAUSE:
294         if (bPaused)
295         {
296            SendDlgItemMessage(hAudit, IDPAUSE, WM_SETTEXT, 0, (LPARAM)TEXT("Pause"));
297            bPaused = FALSE;
298         }
299         else
300         {
301            SendDlgItemMessage(hAudit, IDPAUSE, WM_SETTEXT, 0, (LPARAM)TEXT("Continue"));
302            bPaused = TRUE;
303         }
304         break;
305      }
306      return 1;
307   }
308   return 0;
309}
310
311/* Callback for the Audit property sheet */
312INT_PTR CALLBACK GameAuditDialogProc(HWND hDlg,UINT Msg,WPARAM wParam,LPARAM lParam)
313{
314   switch (Msg)
315   {
316   case WM_INITDIALOG:
317      FlushFileCaches();
318      hAudit = hDlg;
319      win_set_window_text_utf8(GetDlgItem(hDlg, IDC_PROP_TITLE), GameInfoTitle(OPTIONS_GAME, rom_index));
320      SetTimer(hDlg, 0, 1, NULL);
321      return 1;
322
323   case WM_TIMER:
324      KillTimer(hDlg, 0);
325      {
326         int iStatus;
327         LPCSTR lpStatus;
328
329         iStatus = Mame32VerifyRomSet(rom_index);
330         lpStatus = DriverUsesRoms(rom_index) ? StatusString(iStatus) : "None required";
331         win_set_window_text_utf8(GetDlgItem(hDlg, IDC_PROP_ROMS), lpStatus);
332
333         iStatus = Mame32VerifySampleSet(rom_index);
334         lpStatus = DriverUsesSamples(rom_index) ? StatusString(iStatus) : "None required";
335         win_set_window_text_utf8(GetDlgItem(hDlg, IDC_PROP_SAMPLES), lpStatus);
336      }
337      ShowWindow(hDlg, SW_SHOW);
338      break;
339   }
340   return 0;
341}
342
343static void ProcessNextRom()
344{
345   int retval;
346   TCHAR buffer[200];
347
348   retval = Mame32VerifyRomSet(rom_index);
349   switch (retval)
350   {
351   case BEST_AVAILABLE: /* correct, incorrect or separate count? */
352   case CORRECT:
353      roms_correct++;
354      _stprintf(buffer, TEXT("%i"), roms_correct);
355      SendDlgItemMessage(hAudit, IDC_ROMS_CORRECT, WM_SETTEXT, 0, (LPARAM)buffer);
356      _stprintf(buffer, TEXT("%i"), roms_correct + roms_incorrect);
357      SendDlgItemMessage(hAudit, IDC_ROMS_TOTAL, WM_SETTEXT, 0, (LPARAM)buffer);
358      break;
359
360   case NOTFOUND:
361      break;
362
363   case INCORRECT:
364      roms_incorrect++;
365      _stprintf(buffer, TEXT("%i"), roms_incorrect);
366      SendDlgItemMessage(hAudit, IDC_ROMS_INCORRECT, WM_SETTEXT, 0, (LPARAM)buffer);
367      _stprintf(buffer, TEXT("%i"), roms_correct + roms_incorrect);
368      SendDlgItemMessage(hAudit, IDC_ROMS_TOTAL, WM_SETTEXT, 0, (LPARAM)buffer);
369      break;
370   }
371
372   rom_index++;
373   SendDlgItemMessage(hAudit, IDC_ROMS_PROGRESS, PBM_SETPOS, rom_index, 0);
374
375   if (rom_index == driver_list_get_count(drivers))
376   {
377      sample_index = 0;
378      rom_index = -1;
379   }
380}
381
382static void ProcessNextSample()
383{
384   int  retval;
385   TCHAR buffer[200];
386   
387   retval = Mame32VerifySampleSet(sample_index);
388   
389   switch (retval)
390   {
391   case CORRECT:
392      if (DriverUsesSamples(sample_index))
393      {
394         samples_correct++;
395         _stprintf(buffer, TEXT("%i"), samples_correct);
396         SendDlgItemMessage(hAudit, IDC_SAMPLES_CORRECT, WM_SETTEXT, 0, (LPARAM)buffer);
397         _stprintf(buffer, TEXT("%i"), samples_correct + samples_incorrect);
398         SendDlgItemMessage(hAudit, IDC_SAMPLES_TOTAL, WM_SETTEXT, 0, (LPARAM)buffer);
399         break;
400      }
401
402   case NOTFOUND:
403      break;
404         
405   case INCORRECT:
406      samples_incorrect++;
407      _stprintf(buffer, TEXT("%i"), samples_incorrect);
408      SendDlgItemMessage(hAudit, IDC_SAMPLES_INCORRECT, WM_SETTEXT, 0, (LPARAM)buffer);
409      _stprintf(buffer, TEXT("%i"), samples_correct + samples_incorrect);
410      SendDlgItemMessage(hAudit, IDC_SAMPLES_TOTAL, WM_SETTEXT, 0, (LPARAM)buffer);
411     
412      break;
413   }
414
415   sample_index++;
416   SendDlgItemMessage(hAudit, IDC_SAMPLES_PROGRESS, PBM_SETPOS, sample_index, 0);
417   
418   if (sample_index == driver_list_get_count(drivers))
419   {
420      DetailsPrintf("Audit complete.\n");
421      SendDlgItemMessage(hAudit, IDCANCEL, WM_SETTEXT, 0, (LPARAM)TEXT("Close"));
422      sample_index = -1;
423   }
424}
425
426static void CLIB_DECL DetailsPrintf(const char *fmt, ...)
427{
428   HWND   hEdit;
429   va_list marker;
430   char   buffer[2000];
431   TCHAR*  t_s;
432   int      textLength;
433
434   //RS 20030613 Different Ids for Property Page and Dialog
435   // so see which one's currently instantiated
436   hEdit = GetDlgItem(hAudit, IDC_AUDIT_DETAILS);
437   if (hEdit ==  NULL)
438      hEdit = GetDlgItem(hAudit, IDC_AUDIT_DETAILS_PROP);
439   
440   if (hEdit == NULL)
441   {
442      dprintf("audit detailsprintf() can't find any audit control");
443      return;
444   }
445
446   va_start(marker, fmt);
447   
448   vsprintf(buffer, fmt, marker);
449   
450   va_end(marker);
451
452   t_s = tstring_from_utf8(ConvertToWindowsNewlines(buffer));
453   if( !t_s || strcmp("", t_s) == 0)
454      return;
455
456   textLength = Edit_GetTextLength(hEdit);
457   Edit_SetSel(hEdit, textLength, textLength);
458   SendMessage( hEdit, EM_REPLACESEL, FALSE, (WPARAM)(LPCTSTR)win_tstring_strdup(t_s) );
459   
460   free(t_s);
461}
462
463static const char * StatusString(int iStatus)
464{
465   static const char *ptr;
466
467   ptr = "Unknown";
468
469   switch (iStatus)
470   {
471   case CORRECT:
472      ptr = "Passed";
473      break;
474     
475   case BEST_AVAILABLE:
476      ptr = "Best available";
477      break;
478     
479   case NOTFOUND:
480      ptr = "Not found";
481      break;
482     
483   case INCORRECT:
484      ptr = "Failed";
485      break;
486   }
487
488   return ptr;
489}
src/osd/winui/m32opts.h
r0r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11 ***************************************************************************/
12
13#ifndef M32OPTS_H
14#define M32OPTS_H
15
16#include "osdcomm.h"
17#include "osd_cpu.h"
18#include "bitmask.h"
19#include "options.h"
20#include "inputseq.h" /* for input_seq definition */
21#include <video.h> /* for MAX_SCREENS Definition*/
22
23#ifdef MESS
24#include "optionsms.h"
25#endif
26
27// Various levels of ini's we can edit.
28typedef enum {
29   OPTIONS_GLOBAL = 0,
30   OPTIONS_VECTOR,
31   OPTIONS_SOURCE,
32   OPTIONS_PARENT,
33   OPTIONS_GAME,
34   OPTIONS_MAX
35} OPTIONS_TYPE;
36
37
38enum
39{
40   COLUMN_GAMES = 0,
41   COLUMN_ORIENTATION,
42   //COLUMN_ROMS,
43   COLUMN_SAMPLES,
44   COLUMN_DIRECTORY,
45   COLUMN_TYPE,
46   COLUMN_TRACKBALL,
47   COLUMN_PLAYED,
48   COLUMN_MANUFACTURER,
49   COLUMN_YEAR,
50   COLUMN_CLONE,
51   COLUMN_SRCDRIVERS,
52   COLUMN_PLAYTIME,
53   COLUMN_MAX
54};
55
56
57// can't be the same as the VerifyRomSet() results, listed in audit.h
58enum
59{
60   UNKNOWN   = -1
61};
62
63/* Default input */
64enum
65{
66   INPUT_LAYOUT_STD,
67   INPUT_LAYOUT_HR,
68   INPUT_LAYOUT_HRSE
69};
70
71// clean stretch types
72enum
73{
74   // these must match array of strings clean_stretch_long_name in options.c
75   CLEAN_STRETCH_NONE = 0,
76   CLEAN_STRETCH_AUTO = 1,
77
78   MAX_CLEAN_STRETCH = 5,
79};
80
81#define FOLDER_OPTIONS   -2
82#define GLOBAL_OPTIONS   -1
83
84// d3d effect types
85enum
86{
87   // these must match array of strings d3d_effects_long_name in options.c
88   D3D_EFFECT_NONE = 0,
89   D3D_EFFECT_AUTO = 1,
90
91   MAX_D3D_EFFECTS = 17,
92};
93
94// d3d prescale types
95enum
96{
97   D3D_PRESCALE_NONE = 0,
98   D3D_PRESCALE_AUTO = 1,
99   MAX_D3D_PRESCALE = 10,
100};
101
102typedef struct
103{
104   int x, y, width, height;
105} AREA;
106
107typedef struct
108{
109   char* screen;
110   char* aspect;
111   char* resolution;
112   char* view;
113} ScreenParams;
114
115
116
117// List of artwork types to display in the screen shot area
118enum
119{
120   // these must match array of strings image_tabs_long_name in options.c
121   // if you add new Tabs, be sure to also add them to the ComboBox init in dialogs.c
122   TAB_SCREENSHOT = 0,
123   TAB_FLYER,
124   TAB_CABINET,
125   TAB_MARQUEE,
126   TAB_TITLE,
127   TAB_CONTROL_PANEL,
128   TAB_PCB,
129   TAB_HISTORY,
130
131   MAX_TAB_TYPES,
132   BACKGROUND,
133   TAB_ALL,
134   TAB_NONE
135};
136// Because we have added the Options after MAX_TAB_TYPES, we have to subtract 3 here
137// (that's how many options we have after MAX_TAB_TYPES)
138#define TAB_SUBTRACT 3
139
140BOOL OptionsInit(void);
141void OptionsExit(void);
142
143#define OPTIONS_TYPE_GLOBAL      -1
144#define OPTIONS_TYPE_FOLDER      -2
145
146core_options * load_options(OPTIONS_TYPE opt_type, int game_num);
147void save_options(OPTIONS_TYPE opt_type, core_options *opts, int game_num);
148
149void AddOptions(core_options *opts, const options_entry *entrylist, BOOL is_global);
150core_options * CreateGameOptions(int driver_index);
151
152core_options * Mame32Settings(void);
153core_options * Mame32Global(void);
154
155void LoadFolderFlags(void);
156const char* GetFolderNameByID(UINT nID);
157
158void SaveOptions(void);
159
160void ResetGUI(void);
161void ResetGameDefaults(void);
162void ResetAllGameOptions(void);
163
164const char * GetImageTabLongName(int tab_index);
165const char * GetImageTabShortName(int tab_index);
166
167void SetViewMode(int val);
168int  GetViewMode(void);
169
170void SetGameCheck(BOOL game_check);
171BOOL GetGameCheck(void);
172
173void SetVersionCheck(BOOL version_check);
174BOOL GetVersionCheck(void);
175
176void SetJoyGUI(BOOL use_joygui);
177BOOL GetJoyGUI(void);
178
179void SetKeyGUI(BOOL use_keygui);
180BOOL GetKeyGUI(void);
181
182void SetCycleScreenshot(int cycle_screenshot);
183int GetCycleScreenshot(void);
184
185void SetStretchScreenShotLarger(BOOL stretch);
186BOOL GetStretchScreenShotLarger(void);
187
188void SetScreenshotBorderSize(int size);
189int GetScreenshotBorderSize(void);
190
191void SetScreenshotBorderColor(COLORREF uColor);
192COLORREF GetScreenshotBorderColor(void);
193
194void SetFilterInherit(BOOL inherit);
195BOOL GetFilterInherit(void);
196
197void SetOffsetClones(BOOL offset);
198BOOL GetOffsetClones(void);
199
200void SetGameCaption(BOOL caption);
201BOOL GetGameCaption(void);
202
203void SetBroadcast(BOOL broadcast);
204BOOL GetBroadcast(void);
205
206void SetRandomBackground(BOOL random_bg);
207BOOL GetRandomBackground(void);
208
209void SetSavedFolderID(UINT val);
210UINT GetSavedFolderID(void);
211
212void SetShowScreenShot(BOOL val);
213BOOL GetShowScreenShot(void);
214
215void SetShowFolderList(BOOL val);
216BOOL GetShowFolderList(void);
217
218BOOL GetShowFolder(int folder);
219void SetShowFolder(int folder,BOOL show);
220
221
222void SetShowStatusBar(BOOL val);
223BOOL GetShowStatusBar(void);
224
225void SetShowToolBar(BOOL val);
226BOOL GetShowToolBar(void);
227
228void SetShowTabCtrl(BOOL val);
229BOOL GetShowTabCtrl(void);
230
231void SetCurrentTab(const char *shortname);
232const char *GetCurrentTab(void);
233
234void SetDefaultGame(const char *name);
235const char *GetDefaultGame(void);
236
237void SetWindowArea(const AREA *area);
238void GetWindowArea(AREA *area);
239
240void SetWindowState(UINT state);
241UINT GetWindowState(void);
242
243void SetColumnWidths(int widths[]);
244void GetColumnWidths(int widths[]);
245
246void SetColumnOrder(int order[]);
247void GetColumnOrder(int order[]);
248
249void SetColumnShown(int shown[]);
250void GetColumnShown(int shown[]);
251
252void SetSplitterPos(int splitterId, int pos);
253int  GetSplitterPos(int splitterId);
254
255void SetCustomColor(int iIndex, COLORREF uColor);
256COLORREF GetCustomColor(int iIndex);
257
258void SetListFont(const LOGFONT *font);
259void GetListFont(LOGFONT *font);
260
261DWORD GetFolderFlags(int folder_index);
262
263void SetListFontColor(COLORREF uColor);
264COLORREF GetListFontColor(void);
265
266void SetListCloneColor(COLORREF uColor);
267COLORREF GetListCloneColor(void);
268
269int GetHistoryTab(void);
270void SetHistoryTab(int tab,BOOL show);
271
272int GetShowTab(int tab);
273void SetShowTab(int tab,BOOL show);
274BOOL AllowedToSetShowTab(int tab,BOOL show);
275
276void SetSortColumn(int column);
277int  GetSortColumn(void);
278
279void SetSortReverse(BOOL reverse);
280BOOL GetSortReverse(void);
281
282const char* GetLanguage(void);
283void SetLanguage(const char* lang);
284
285const char* GetRomDirs(void);
286void SetRomDirs(const char* paths);
287
288const char* GetSampleDirs(void);
289void  SetSampleDirs(const char* paths);
290
291const char * GetIniDir(void);
292void SetIniDir(const char *path);
293
294const char* GetCfgDir(void);
295void SetCfgDir(const char* path);
296
297const char* GetNvramDir(void);
298void SetNvramDir(const char* path);
299
300const char* GetInpDir(void);
301void SetInpDir(const char* path);
302
303const char* GetImgDir(void);
304void SetImgDir(const char* path);
305
306const char* GetStateDir(void);
307void SetStateDir(const char* path);
308
309const char* GetArtDir(void);
310void SetArtDir(const char* path);
311
312const char* GetMemcardDir(void);
313void SetMemcardDir(const char* path);
314
315const char* GetFlyerDir(void);
316void SetFlyerDir(const char* path);
317
318const char* GetCabinetDir(void);
319void SetCabinetDir(const char* path);
320
321const char* GetMarqueeDir(void);
322void SetMarqueeDir(const char* path);
323
324const char* GetTitlesDir(void);
325void SetTitlesDir(const char* path);
326
327const char * GetControlPanelDir(void);
328void SetControlPanelDir(const char *path);
329
330const char * GetPcbDir(void);
331void SetPcbDir(const char *path);
332
333const char* GetDiffDir(void);
334void SetDiffDir(const char* path);
335
336const char* GetIconsDir(void);
337void SetIconsDir(const char* path);
338
339const char *GetBgDir(void);
340void SetBgDir(const char *path);
341
342const char* GetCtrlrDir(void);
343void SetCtrlrDir(const char* path);
344
345const char* GetCommentDir(void);
346void SetCommentDir(const char* path);
347
348const char* GetFolderDir(void);
349void SetFolderDir(const char* path);
350
351const char* GetCheatFileName(void);
352void SetCheatFileName(const char* path);
353
354const char* GetHistoryFileName(void);
355void SetHistoryFileName(const char* path);
356
357const char* GetMAMEInfoFileName(void);
358void SetMAMEInfoFileName(const char* path);
359
360void ResetGameOptions(int driver_index);
361
362int GetRomAuditResults(int driver_index);
363void SetRomAuditResults(int driver_index, int audit_results);
364
365int GetSampleAuditResults(int driver_index);
366void SetSampleAuditResults(int driver_index, int audit_results);
367
368void IncrementPlayCount(int driver_index);
369int GetPlayCount(int driver_index);
370void ResetPlayCount(int driver_index);
371
372void IncrementPlayTime(int driver_index,int playtime);
373int GetPlayTime(int driver_index);
374void GetTextPlayTime(int driver_index,char *buf);
375void ResetPlayTime(int driver_index);
376
377char * GetVersionString(void);
378
379void SaveDefaultOptions(void);
380
381BOOL IsGlobalOption(const char *option_name);
382
383
384
385// Keyboard control of ui
386input_seq* Get_ui_key_up(void);
387input_seq* Get_ui_key_down(void);
388input_seq* Get_ui_key_left(void);
389input_seq* Get_ui_key_right(void);
390input_seq* Get_ui_key_start(void);
391input_seq* Get_ui_key_pgup(void);
392input_seq* Get_ui_key_pgdwn(void);
393input_seq* Get_ui_key_home(void);
394input_seq* Get_ui_key_end(void);
395input_seq* Get_ui_key_ss_change(void);
396input_seq* Get_ui_key_history_up(void);
397input_seq* Get_ui_key_history_down(void);
398
399input_seq* Get_ui_key_context_filters(void);
400input_seq* Get_ui_key_select_random(void);
401input_seq* Get_ui_key_game_audit(void);
402input_seq* Get_ui_key_game_properties(void);
403input_seq* Get_ui_key_help_contents(void);
404input_seq* Get_ui_key_update_gamelist(void);
405input_seq* Get_ui_key_view_folders(void);
406input_seq* Get_ui_key_view_fullscreen(void);
407input_seq* Get_ui_key_view_pagetab(void);
408input_seq* Get_ui_key_view_picture_area(void);
409input_seq* Get_ui_key_view_status(void);
410input_seq* Get_ui_key_view_toolbars(void);
411
412input_seq* Get_ui_key_view_tab_cabinet(void);
413input_seq* Get_ui_key_view_tab_cpanel(void);
414input_seq* Get_ui_key_view_tab_flyer(void);
415input_seq* Get_ui_key_view_tab_history(void);
416input_seq* Get_ui_key_view_tab_marquee(void);
417input_seq* Get_ui_key_view_tab_screenshot(void);
418input_seq* Get_ui_key_view_tab_title(void);
419input_seq* Get_ui_key_view_tab_pcb(void);
420input_seq* Get_ui_key_quit(void);
421
422
423int GetUIJoyUp(int joycodeIndex);
424void SetUIJoyUp(int joycodeIndex, int val);
425
426int GetUIJoyDown(int joycodeIndex);
427void SetUIJoyDown(int joycodeIndex, int val);
428
429int GetUIJoyLeft(int joycodeIndex);
430void SetUIJoyLeft(int joycodeIndex, int val);
431
432int GetUIJoyRight(int joycodeIndex);
433void SetUIJoyRight(int joycodeIndex, int val);
434
435int GetUIJoyStart(int joycodeIndex);
436void SetUIJoyStart(int joycodeIndex, int val);
437
438int GetUIJoyPageUp(int joycodeIndex);
439void SetUIJoyPageUp(int joycodeIndex, int val);
440
441int GetUIJoyPageDown(int joycodeIndex);
442void SetUIJoyPageDown(int joycodeIndex, int val);
443
444int GetUIJoyHome(int joycodeIndex);
445void SetUIJoyHome(int joycodeIndex, int val);
446
447int GetUIJoyEnd(int joycodeIndex);
448void SetUIJoyEnd(int joycodeIndex, int val);
449
450int GetUIJoySSChange(int joycodeIndex);
451void SetUIJoySSChange(int joycodeIndex, int val);
452
453int GetUIJoyHistoryUp(int joycodeIndex);
454void SetUIJoyHistoryUp(int joycodeIndex, int val);
455
456int GetUIJoyHistoryDown(int joycodeIndex);
457void SetUIJoyHistoryDown(int joycodeIndex, int val);
458
459int GetUIJoyExec(int joycodeIndex);
460void SetUIJoyExec(int joycodeIndex, int val);
461
462const char* GetExecCommand(void);
463void SetExecCommand(char* cmd);
464
465int GetExecWait(void);
466void SetExecWait(int wait);
467
468BOOL GetHideMouseOnStartup(void);
469void SetHideMouseOnStartup(BOOL hide);
470
471BOOL GetRunFullScreen(void);
472void SetRunFullScreen(BOOL fullScreen);
473
474void ColumnEncodeStringWithCount(const int *value, char *str, int count);
475void ColumnDecodeStringWithCount(const char* str, int *value, int count);
476
477#endif
src/osd/winui/layout.c
r0r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11***************************************************************************/
12
13/***************************************************************************
14
15  layout.c
16
17  MAME specific TreeView definitions (and maybe more in the future)
18
19***************************************************************************/
20
21#define WIN32_LEAN_AND_MEAN
22#include <windows.h>
23#include <windowsx.h>
24#include <shellapi.h>
25#include <commctrl.h>
26#include <stdio.h>  /* for sprintf */
27#include <stdlib.h> /* For malloc and free */
28#include <string.h>
29
30#include "bitmask.h"
31#include "treeview.h"
32#include "m32util.h"
33#include "resource.h"
34#include "directories.h"
35#include "m32opts.h"
36#include "splitters.h"
37#include "help.h"
38#include "audit32.h"
39#include "screenshot.h"
40#include "win32ui.h"
41#include "properties.h"
42
43static BOOL FilterAvailable(int driver_index);
44
45FOLDERDATA g_folderData[] =
46{
47   {"All Games",       "allgames",          FOLDER_ALLGAMES,     IDI_FOLDER,            0,             0,            NULL,                       NULL,                    TRUE },
48   {"Available",       "available",         FOLDER_AVAILABLE,    IDI_FOLDER_AVAILABLE,     F_AVAILABLE,   0,            NULL,                       FilterAvailable,         TRUE },
49#ifdef SHOW_UNAVAILABLE_FOLDER
50   {"Unavailable",     "unavailable",       FOLDER_UNAVAILABLE,  IDI_FOLDER_UNAVAILABLE,   0,             F_AVAILABLE,  NULL,                       FilterAvailable,         FALSE },
51#endif
52   {"Horizontal",      "horizontal",        FOLDER_HORIZONTAL,   IDI_FOLDER_HORIZONTAL,    F_HORIZONTAL,  F_VERTICAL,   NULL,                       DriverIsVertical,        FALSE },
53   {"Vertical",        "vertical",          FOLDER_VERTICAL,     IDI_FOLDER_VERTICAL,      F_VERTICAL,    F_HORIZONTAL, NULL,                       DriverIsVertical,        TRUE },
54   {"Manufacturer",    "manufacturer",      FOLDER_MANUFACTURER, IDI_FOLDER_MANUFACTURER,  0,             0,            CreateManufacturerFolders },
55   {"Year",            "year",              FOLDER_YEAR,         IDI_FOLDER_YEAR,          0,             0,            CreateYearFolders },
56   {"Source",          "source",            FOLDER_SOURCE,       IDI_FOLDER_SOURCE,        0,             0,            CreateSourceFolders },
57   {"CPU",             "cpu",               FOLDER_CPU,          IDI_CPU,                  0,             0,            CreateCPUFolders },
58   {"Sound",           "sound",             FOLDER_SND,          IDI_SOUND,                0,             0,            CreateSoundFolders },
59   {"Imperfect",       "imperfect",         FOLDER_DEFICIENCY,   IDI_FOLDER,               0,             0,            CreateDeficiencyFolders },
60     {"Dumping Status",  "dumping",           FOLDER_DUMPING,      IDI_FOLDER,               0,             0,            CreateDumpingFolders },
61   {"Working",         "working",           FOLDER_WORKING,      IDI_WORKING,              F_WORKING,     F_NONWORKING, NULL,                       DriverIsBroken,          FALSE },
62   {"Not Working",     "nonworking",        FOLDER_NONWORKING,   IDI_NONWORKING,           F_NONWORKING,  F_WORKING,    NULL,                       DriverIsBroken,          TRUE },
63   {"Originals",       "originals",         FOLDER_ORIGINAL,     IDI_FOLDER,               F_ORIGINALS,   F_CLONES,     NULL,                       DriverIsClone,           FALSE },
64   {"Clones",          "clones",            FOLDER_CLONES,       IDI_FOLDER,               F_CLONES,      F_ORIGINALS,  NULL,                       DriverIsClone,           TRUE },
65   {"Raster",          "raster",            FOLDER_RASTER,       IDI_FOLDER,               F_RASTER,      F_VECTOR,     NULL,                       DriverIsVector,          FALSE },
66   {"Vector",          "vector",            FOLDER_VECTOR,       IDI_FOLDER,               F_VECTOR,      F_RASTER,     NULL,                       DriverIsVector,          TRUE },
67   {"Trackball",       "trackball",         FOLDER_TRACKBALL,    IDI_FOLDER,               0,             0,            NULL,                       DriverUsesTrackball,     TRUE },
68   {"Lightgun",        "lightgun",          FOLDER_LIGHTGUN,     IDI_FOLDER,               0,             0,            NULL,                       DriverUsesLightGun,      TRUE },
69   {"Stereo",          "stereo",            FOLDER_STEREO,       IDI_SOUND,                0,             0,            NULL,                       DriverIsStereo,          TRUE },
70   {"CHD",             "harddisk",          FOLDER_HARDDISK,     IDI_HARDDISK,             0,             0,            NULL,                       DriverIsHarddisk,        TRUE },
71     {"Samples",           "samples",           FOLDER_SAMPLES,      IDI_FOLDER,               0,             0,            NULL,                       DriverUsesSamples,       TRUE },
72     {"Save State",       "savestate",         FOLDER_SAVESTATE,    IDI_FOLDER,               0,             0,            NULL,                       DriverSupportsSaveState, TRUE },
73     {"BIOS",          "bios",               FOLDER_BIOS,        IDI_FOLDER,               0,             0,            NULL,                       DriverIsBios,           TRUE },
74   { NULL }
75};
76
77/* list of filter/control Id pairs */
78FILTER_ITEM g_filterList[] =
79{
80   { F_CLONES,       IDC_FILTER_CLONES,      DriverIsClone, TRUE },
81   { F_NONWORKING,   IDC_FILTER_NONWORKING,  DriverIsBroken, TRUE },
82   { F_UNAVAILABLE,  IDC_FILTER_UNAVAILABLE, FilterAvailable, FALSE },
83   { F_RASTER,       IDC_FILTER_RASTER,      DriverIsVector, FALSE },
84   { F_VECTOR,       IDC_FILTER_VECTOR,      DriverIsVector, TRUE },
85   { F_ORIGINALS,    IDC_FILTER_ORIGINALS,   DriverIsClone, FALSE },
86   { F_WORKING,      IDC_FILTER_WORKING,     DriverIsBroken, FALSE },
87   { F_AVAILABLE,    IDC_FILTER_AVAILABLE,   FilterAvailable, TRUE },
88   { F_HORIZONTAL,   IDC_FILTER_HORIZONTAL,  DriverIsVertical, FALSE },
89   { F_VERTICAL,     IDC_FILTER_VERTICAL,    DriverIsVertical, TRUE },
90   { 0 }
91};
92
93DIRECTORYINFO g_directoryInfo[] =
94{
95   { "ROMs",                  GetRomDirs,      SetRomDirs,      TRUE,  DIRDLG_ROMS },
96   { "Samples",               GetSampleDirs,   SetSampleDirs,   TRUE,  DIRDLG_SAMPLES },
97   { "Ini Files",             GetIniDir,       SetIniDir,       FALSE, DIRDLG_INI },
98   { "Config",                GetCfgDir,       SetCfgDir,       FALSE, DIRDLG_CFG },
99   { "Snapshots",             GetImgDir,       SetImgDir,       FALSE, DIRDLG_IMG },
100   { "Input files (*.inp)",   GetInpDir,       SetInpDir,       FALSE, DIRDLG_INP },
101   { "State",                 GetStateDir,     SetStateDir,     FALSE, 0 },
102   { "Artwork",               GetArtDir,       SetArtDir,       FALSE, 0 },
103   { "Memory Card",           GetMemcardDir,   SetMemcardDir,   FALSE, 0 },
104   { "Flyers",                GetFlyerDir,     SetFlyerDir,     FALSE, 0 },
105   { "Cabinets",              GetCabinetDir,   SetCabinetDir,   FALSE, 0 },
106   { "Marquees",              GetMarqueeDir,   SetMarqueeDir,   FALSE, 0 },
107   { "Titles",                GetTitlesDir,    SetTitlesDir,    FALSE, 0 },
108   { "Control Panels",        GetControlPanelDir,SetControlPanelDir, FALSE, 0 },
109   { "PCBs",                   GetPcbDir,       SetPcbDir,       FALSE, 0 },
110   { "NVRAM",                 GetNvramDir,     SetNvramDir,     FALSE, 0 },
111   { "Controller Files",      GetCtrlrDir,     SetCtrlrDir,     FALSE, DIRDLG_CTRLR },
112   { "Hard Drive Difference", GetDiffDir,      SetDiffDir,      FALSE, 0 },
113   { "Icons",                 GetIconsDir,     SetIconsDir,     FALSE, 0 },
114   { "Background Images",     GetBgDir,        SetBgDir,        FALSE, 0 },
115   { "Comment Files",      GetCommentDir,     SetCommentDir,     FALSE, DIRDLG_COMMENT },
116   { NULL }
117};
118
119const SPLITTERINFO g_splitterInfo[] =
120{
121   { 0.25,   IDC_SPLITTER,   IDC_TREE,   IDC_LIST,      AdjustSplitter1Rect },
122   { 0.5,   IDC_SPLITTER2,   IDC_LIST,   IDC_SSFRAME,   AdjustSplitter2Rect },
123   { -1 }
124};
125
126const MAMEHELPINFO g_helpInfo[] =
127{
128   { ID_HELP_CONTENTS,      TRUE,   MAME32HELP "::/html/mame32_overview.htm" },
129   { ID_HELP_WHATS_NEW32,   TRUE,   MAME32HELP "::/html/mame32_changes.txt" },
130   { ID_HELP_TROUBLE,      TRUE,   MAME32HELP "::/html/mame32_support.htm" },
131   { ID_HELP_RELEASE,      FALSE,   "windows.txt" },
132   { ID_HELP_WHATS_NEW,   TRUE,   MAME32HELP "::/docs/whatsnew.txt" },
133   { -1 }
134};
135
136const PROPERTYSHEETINFO g_propSheets[] =
137{
138   { FALSE,   NULL,               IDD_PROP_GAME,         GamePropertiesDialogProc },
139   { FALSE,   NULL,               IDD_PROP_AUDIT,         GameAuditDialogProc },
140   { TRUE,      NULL,               IDD_PROP_DISPLAY,      GameOptionsProc },
141   { TRUE,      NULL,               IDD_PROP_ADVANCED,      GameOptionsProc },
142   { TRUE,      NULL,               IDD_PROP_SCREEN,      GameOptionsProc },
143   { TRUE,      NULL,               IDD_PROP_SOUND,         GameOptionsProc },
144   { TRUE,      NULL,               IDD_PROP_INPUT,         GameOptionsProc },
145   { TRUE,      NULL,               IDD_PROP_CONTROLLER,   GameOptionsProc },
146   { TRUE,      NULL,               IDD_PROP_MISC,         GameOptionsProc },
147   { TRUE,      PropSheetFilter_Vector,   IDD_PROP_VECTOR,      GameOptionsProc },
148   { FALSE }
149};
150
151const ICONDATA g_iconData[] =
152{
153   { IDI_WIN_NOROMS,         "noroms" },
154   { IDI_WIN_ROMS,            "roms" },
155   { IDI_WIN_UNKNOWN,         "unknown" },
156   { IDI_WIN_CLONE,         "clone" },
157   { IDI_WIN_REDX,            "warning" },
158   { 0 }
159};
160
161const TCHAR g_szPlayGameString[] = TEXT("&Play %s");
162const char g_szGameCountString[] = "%d games";
163const char g_szHistoryFileName[] = "history.dat";
164const char g_szMameInfoFileName[] = "mameinfo.dat";
165
166static BOOL FilterAvailable(int driver_index)
167{
168   return IsAuditResultYes(GetRomAuditResults(driver_index));
169}
src/osd/winui/dxdecode.c
r0r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11 ***************************************************************************/
12
13#include <windows.h>
14#include <ddraw.h>
15#include <stdio.h>
16#include "directinput.h"
17#include "dxdecode.h"
18
19/***************************************************************/
20
21typedef struct tagERRORCODE
22{
23   HRESULT     hr;
24   const char *szError;
25} ERRORCODE, * LPERRORCODE;
26
27/***************************************************************/
28static ERRORCODE    g_ErrorCode[] =
29{
30   {   DDERR_ALREADYINITIALIZED,           "DDERR_ALREADYINITIALIZED"},
31   {   DDERR_CANNOTATTACHSURFACE,          "DDERR_CANNOTATTACHSURFACE"},
32   {   DDERR_CANNOTDETACHSURFACE,          "DDERR_CANNOTDETACHSURFACE"},
33   {   DDERR_CURRENTLYNOTAVAIL,            "DDERR_CURRENTLYNOTAVAIL"},
34   {   DDERR_EXCEPTION,                    "DDERR_EXCEPTION"},
35   {   DDERR_GENERIC,                      "DDERR_GENERIC"},
36   {   DDERR_HEIGHTALIGN,                  "DDERR_HEIGHTALIGN"},
37   {   DDERR_INCOMPATIBLEPRIMARY,          "DDERR_INCOMPATIBLEPRIMARY"},
38   {   DDERR_INVALIDCAPS,                  "DDERR_INVALIDCAPS"},
39   {   DDERR_INVALIDCLIPLIST,              "DDERR_INVALIDCLIPLIST"},
40   {   DDERR_INVALIDMODE,                  "DDERR_INVALIDMODE"},
41   {   DDERR_INVALIDOBJECT,                "DDERR_INVALIDOBJECT"},
42   {   DDERR_INVALIDPARAMS,                "DDERR_INVALIDPARAMS"},
43   {   DDERR_INVALIDPIXELFORMAT,           "DDERR_INVALIDPIXELFORMAT"},
44   {   DDERR_INVALIDRECT,                  "DDERR_INVALIDRECT"},
45   {   DDERR_LOCKEDSURFACES,               "DDERR_LOCKEDSURFACES"},
46   {   DDERR_NO3D,                         "DDERR_NO3D"},
47   {   DDERR_NOALPHAHW,                    "DDERR_NOALPHAHW"},
48   {   DDERR_NOCLIPLIST,                   "DDERR_NOCLIPLIST"},
49   {   DDERR_NOCOLORCONVHW,                "DDERR_NOCOLORCONVHW"},
50   {   DDERR_NOCOOPERATIVELEVELSET,        "DDERR_NOCOOPERATIVELEVELSET"},
51   {   DDERR_NOCOLORKEY,                   "DDERR_NOCOLORKEY"},
52   {   DDERR_NOCOLORKEYHW,                 "DDERR_NOCOLORKEYHW"},
53   {   DDERR_NODIRECTDRAWSUPPORT,          "DDERR_NODIRECTDRAWSUPPORT"},
54   {   DDERR_NOEXCLUSIVEMODE,              "DDERR_NOEXCLUSIVEMODE"},
55   {   DDERR_NOFLIPHW,                     "DDERR_NOFLIPHW"},
56   {   DDERR_NOGDI,                        "DDERR_NOGDI"},
57   {   DDERR_NOMIRRORHW,                   "DDERR_NOMIRRORHW"},
58   {   DDERR_NOTFOUND,                     "DDERR_NOTFOUND"},
59   {   DDERR_NOOVERLAYHW,                  "DDERR_NOOVERLAYHW"},
60   {   DDERR_NORASTEROPHW,                 "DDERR_NORASTEROPHW"},
61   {   DDERR_NOROTATIONHW,                 "DDERR_NOROTATIONHW"},
62   {   DDERR_NOSTRETCHHW,                  "DDERR_NOSTRETCHHW"},
63   {   DDERR_NOT4BITCOLOR,                 "DDERR_NOT4BITCOLOR"},
64   {   DDERR_NOT4BITCOLORINDEX,            "DDERR_NOT4BITCOLORINDEX"},
65   {   DDERR_NOT8BITCOLOR,                 "DDERR_NOT8BITCOLOR"},
66   {   DDERR_NOTEXTUREHW,                  "DDERR_NOTEXTUREHW"},
67   {   DDERR_NOVSYNCHW,                    "DDERR_NOVSYNCHW"},
68   {   DDERR_NOZBUFFERHW,                  "DDERR_NOZBUFFERHW"},
69   {   DDERR_NOZOVERLAYHW,                 "DDERR_NOZOVERLAYHW"},
70   {   DDERR_OUTOFCAPS,                    "DDERR_OUTOFCAPS"},
71   {   DDERR_OUTOFMEMORY,                  "DDERR_OUTOFMEMORY"},
72   {   DDERR_OUTOFVIDEOMEMORY,             "DDERR_OUTOFVIDEOMEMORY"},
73   {   DDERR_OVERLAYCANTCLIP,              "DDERR_OVERLAYCANTCLIP"},
74   {   DDERR_OVERLAYCOLORKEYONLYONEACTIVE, "DDERR_OVERLAYCOLORKEYONLYONEACTIVE"},
75   {   DDERR_PALETTEBUSY,                  "DDERR_PALETTEBUSY"},
76   {   DDERR_COLORKEYNOTSET,               "DDERR_COLORKEYNOTSET"},
77   {   DDERR_SURFACEALREADYATTACHED,       "DDERR_SURFACEALREADYATTACHED"},
78   {   DDERR_SURFACEALREADYDEPENDENT,      "DDERR_SURFACEALREADYDEPENDENT"},
79   {   DDERR_SURFACEBUSY,                  "DDERR_SURFACEBUSY"},
80   {   DDERR_CANTLOCKSURFACE,              "DDERR_CANTLOCKSURFACE"},
81   {   DDERR_SURFACEISOBSCURED,            "DDERR_SURFACEISOBSCURED"},
82   {   DDERR_SURFACELOST,                  "DDERR_SURFACELOST"},
83   {   DDERR_SURFACENOTATTACHED,           "DDERR_SURFACENOTATTACHED"},
84   {   DDERR_TOOBIGHEIGHT,                 "DDERR_TOOBIGHEIGHT"},
85   {   DDERR_TOOBIGSIZE,                   "DDERR_TOOBIGSIZE"},
86   {   DDERR_TOOBIGWIDTH,                  "DDERR_TOOBIGWIDTH"},
87   {   DDERR_UNSUPPORTED,                  "DDERR_UNSUPPORTED"},
88   {   DDERR_UNSUPPORTEDFORMAT,            "DDERR_UNSUPPORTEDFORMAT"},
89   {   DDERR_UNSUPPORTEDMASK,              "DDERR_UNSUPPORTEDMASK"},
90   {   DDERR_VERTICALBLANKINPROGRESS,      "DDERR_VERTICALBLANKINPROGRESS"},
91   {   DDERR_WASSTILLDRAWING,              "DDERR_WASSTILLDRAWING"},
92   {   DDERR_XALIGN,                       "DDERR_XALIGN"},
93   {   DDERR_INVALIDDIRECTDRAWGUID,        "DDERR_INVALIDDIRECTDRAWGUID"},
94   {   DDERR_DIRECTDRAWALREADYCREATED,     "DDERR_DIRECTDRAWALREADYCREATED"},
95   {   DDERR_NODIRECTDRAWHW,               "DDERR_NODIRECTDRAWHW"},
96   {   DDERR_PRIMARYSURFACEALREADYEXISTS,  "DDERR_PRIMARYSURFACEALREADYEXISTS"},
97   {   DDERR_NOEMULATION,                  "DDERR_NOEMULATION"},
98   {   DDERR_REGIONTOOSMALL,               "DDERR_REGIONTOOSMALL"},
99   {   DDERR_CLIPPERISUSINGHWND,           "DDERR_CLIPPERISUSINGHWND"},
100   {   DDERR_NOCLIPPERATTACHED,            "DDERR_NOCLIPPERATTACHED"},
101   {   DDERR_NOHWND,                       "DDERR_NOHWND"},
102   {   DDERR_HWNDSUBCLASSED,               "DDERR_HWNDSUBCLASSED"},
103   {   DDERR_HWNDALREADYSET,               "DDERR_HWNDALREADYSET"},
104   {   DDERR_NOPALETTEATTACHED,            "DDERR_NOPALETTEATTACHED"},
105   {   DDERR_NOPALETTEHW,                  "DDERR_NOPALETTEHW"},
106   {   DDERR_BLTFASTCANTCLIP,              "DDERR_BLTFASTCANTCLIP"},
107   {   DDERR_NOBLTHW,                      "DDERR_NOBLTHW"},
108   {   DDERR_NODDROPSHW,                   "DDERR_NODDROPSHW"},
109   {   DDERR_OVERLAYNOTVISIBLE,            "DDERR_OVERLAYNOTVISIBLE"},
110   {   DDERR_NOOVERLAYDEST,                "DDERR_NOOVERLAYDEST"},
111   {   DDERR_INVALIDPOSITION,              "DDERR_INVALIDPOSITION"},
112   {   DDERR_NOTAOVERLAYSURFACE,           "DDERR_NOTAOVERLAYSURFACE"},
113   {   DDERR_EXCLUSIVEMODEALREADYSET,      "DDERR_EXCLUSIVEMODEALREADYSET"},
114   {   DDERR_NOTFLIPPABLE,                 "DDERR_NOTFLIPPABLE"},
115   {   DDERR_CANTDUPLICATE,                "DDERR_CANTDUPLICATE"},
116   {   DDERR_NOTLOCKED,                    "DDERR_NOTLOCKED"},
117   {   DDERR_CANTCREATEDC,                 "DDERR_CANTCREATEDC"},
118   {   DDERR_NODC,                         "DDERR_NODC"},
119   {   DDERR_WRONGMODE,                    "DDERR_WRONGMODE"},
120   {   DDERR_IMPLICITLYCREATED,            "DDERR_IMPLICITLYCREATED"},
121   {   DDERR_NOTPALETTIZED,                "DDERR_NOTPALETTIZED"},
122   {   DDERR_UNSUPPORTEDMODE,              "DDERR_UNSUPPORTEDMODE"},
123   {   DDERR_NOMIPMAPHW,                   "DDERR_NOMIPMAPHW"},
124   {   DDERR_INVALIDSURFACETYPE,           "DDERR_INVALIDSURFACETYPE"},
125
126   {   DDERR_NOOPTIMIZEHW,                 "DDERR_NOOPTIMIZEHW"},
127   {   DDERR_NOTLOADED,                    "DDERR_NOTLOADED"},
128
129   {   DDERR_DCALREADYCREATED,             "DDERR_DCALREADYCREATED"},
130
131   {   DDERR_NONONLOCALVIDMEM,             "DDERR_NONONLOCALVIDMEM"},
132   {   DDERR_CANTPAGELOCK,                 "DDERR_CANTPAGELOCK"},
133   {   DDERR_CANTPAGEUNLOCK,               "DDERR_CANTPAGEUNLOCK"},
134   {   DDERR_NOTPAGELOCKED,                "DDERR_NOTPAGELOCKED"},
135
136   {   DDERR_MOREDATA,                     "DDERR_MOREDATA"},
137   {   DDERR_VIDEONOTACTIVE,               "DDERR_VIDEONOTACTIVE"},
138   {   DDERR_DEVICEDOESNTOWNSURFACE,       "DDERR_DEVICEDOESNTOWNSURFACE"},
139   {   DDERR_NOTINITIALIZED,               "DDERR_NOTINITIALIZED"},
140
141   {   DIERR_OLDDIRECTINPUTVERSION,        "DIERR_OLDDIRECTINPUTVERSION" },
142   {   DIERR_BETADIRECTINPUTVERSION,       "DIERR_BETADIRECTINPUTVERSION" },
143   {   DIERR_BADDRIVERVER,                 "DIERR_BADDRIVERVER" },
144   {   DIERR_DEVICENOTREG,                 "DIERR_DEVICENOTREG" },
145   {   DIERR_NOTFOUND,                     "DIERR_NOTFOUND" },
146   {   DIERR_OBJECTNOTFOUND,               "DIERR_OBJECTNOTFOUND" },
147   {   DIERR_INVALIDPARAM,                 "DIERR_INVALIDPARAM" },
148   {   DIERR_NOINTERFACE,                  "DIERR_NOINTERFACE" },
149   {   DIERR_GENERIC,                      "DIERR_GENERIC" },
150   {   DIERR_OUTOFMEMORY,                  "DIERR_OUTOFMEMORY" },
151   {   DIERR_UNSUPPORTED,                  "DIERR_UNSUPPORTED" },
152   {   DIERR_NOTINITIALIZED,               "DIERR_NOTINITIALIZED" },
153   {   DIERR_ALREADYINITIALIZED,           "DIERR_ALREADYINITIALIZED" },
154   {   DIERR_NOAGGREGATION,                "DIERR_NOAGGREGATION" },
155   {   DIERR_OTHERAPPHASPRIO,              "DIERR_OTHERAPPHASPRIO" },
156   {   DIERR_INPUTLOST,                    "DIERR_INPUTLOST" },
157   {   DIERR_ACQUIRED,                     "DIERR_ACQUIRED" },
158   {   DIERR_NOTACQUIRED,                  "DIERR_NOTACQUIRED" },
159   {   DIERR_READONLY,                     "DIERR_READONLY" },
160   {   DIERR_HANDLEEXISTS,                 "DIERR_HANDLEEXISTS" },
161   {   E_PENDING,                          "E_PENDING" },
162   {   DIERR_INSUFFICIENTPRIVS,            "DIERR_INSUFFICIENTPRIVS" },
163   {   DIERR_DEVICEFULL,                   "DIERR_DEVICEFULL" },
164   {   DIERR_MOREDATA,                     "DIERR_MOREDATA" },
165   {   DIERR_NOTDOWNLOADED,                "DIERR_NOTDOWNLOADED" },
166   {   DIERR_HASEFFECTS,                   "DIERR_HASEFFECTS" },
167   {   DIERR_NOTEXCLUSIVEACQUIRED,         "DIERR_NOTEXCLUSIVEACQUIRED" },
168   {   DIERR_INCOMPLETEEFFECT,             "DIERR_INCOMPLETEEFFECT" },
169   {   DIERR_NOTBUFFERED,                  "DIERR_NOTBUFFERED" },
170   {   DIERR_EFFECTPLAYING,                "DIERR_EFFECTPLAYING" },
171//   {   DIERR_UNPLUGGED,                    "DIERR_UNPLUGGED" },
172
173   {   E_NOINTERFACE,                      "E_NOINTERFACE" },
174
175};
176
177/***************************************************************/
178
179/*
180   DirectXDecodeError:  Return a string description of the given DirectX
181   error code.
182*/
183
184const char * DirectXDecodeError(HRESULT errorval)
185{
186   int i;
187   static char tmp[64];
188   
189   for (i = 0; i < (sizeof(g_ErrorCode) / sizeof(g_ErrorCode[0])); i++)
190   {
191      if (g_ErrorCode[i].hr == errorval)
192      {
193         return g_ErrorCode[i].szError;
194      }
195   }
196   sprintf(tmp, "UNKNOWN: 0x%x", (unsigned int)errorval);
197   return tmp;
198}
src/osd/winui/audit32.h
r0r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11 ***************************************************************************/
12
13#ifndef AUDIT32_H
14#define AUDIT32_H
15
16void AuditDialog(HWND hParent);
17
18// For property sheet Game Audit tab
19void InitGameAudit(int gameIndex);
20INT_PTR CALLBACK GameAuditDialogProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam);
21
22int Mame32VerifyRomSet(int game);
23int Mame32VerifySampleSet(int game);
24
25const char * GetAuditString(int audit_result);
26BOOL IsAuditResultKnown(int audit_result);
27BOOL IsAuditResultYes(int audit_result);
28BOOL IsAuditResultNo(int audit_result);
29
30#endif
src/osd/winui/mkhelp.c
r0r996
1/***************************************************************************
2 
3    mkhelp.c
4 
5    Simple resource HIDC to Help entry tool.
6 
7    MSH - 20070815
8 
9***************************************************************************/
10 
11#include <stdio.h>
12#include "osdcore.h"
13 
14 
15int compare( const void *arg1, const void *arg2 );
16void extract_help_ids(const char *buffer, FILE *fp);
17 
18#ifdef main
19#undef main
20#endif
21 
22/*-------------------------------------------------
23    main - primary entry point
24-------------------------------------------------*/
25 
26int main(int argc, char *argv[])
27{
28   const char *resourcefile, *varname, *type;
29   FILE *src, *dst;
30   char *buffer;
31   int bytes;
32 
33   varname = "dwHelpIDs";
34   type = "DWORD";
35 
36   /* needs at least three arguments */
37   if (argc < 1)
38   {
39      fprintf(stderr,
40         "Usage:\n"
41         "  mkhelp <resource.rc>\n"
42         "\n"
43         "The default <type> is DWORD, with an assumed NULL terminator pair\n"
44      );
45      return 0;
46   }
47 
48   /* extract arguments */
49   resourcefile = argv[1];
50 
51   /* open source file */
52   src = fopen(resourcefile, "rb");
53   if (src == NULL)
54   {
55      fprintf(stderr, "Unable to open resource file '%s'\n", resourcefile);
56      return 1;
57   }
58 
59   /* determine file size */
60   fseek(src, 0, SEEK_END);
61   bytes = ftell(src);
62   fseek(src, 0, SEEK_SET);
63 
64   /* allocate memory */
65   buffer = malloc(bytes + 1);
66   if (buffer == NULL)
67   {
68      fprintf(stderr, "Out of memory allocating %d byte buffer\n", bytes);
69      return 1;
70   }
71 
72   /* read the source file */
73   fread(buffer, 1, bytes, src);
74   buffer[bytes] = 0;
75   fclose(src);
76 
77   /* open dest file */
78   dst = stdout;
79 
80   fprintf(dst,"/*\n * Help ID array - Generated by mkhelp\n */\n\n");
81   fprintf(dst, "#include <windows.h>\n#include \"resource.h\"\n#include \"resource.hm\"\n\n");
82   /* write the initial header */
83   fprintf(dst, "const %s %s[] =\n{\n", type, varname);
84 
85   extract_help_ids(buffer, dst);
86 
87   fprintf(dst, "\n};\n");
88 
89   /* close the files */
90   free(buffer);
91//   fclose(dst);
92   return 0;
93}
94 
95int compare( const void *arg1, const void *arg2 )
96{
97   /* Compare all of both strings: */
98   return _stricmp( * ( char** ) arg1, * ( char** ) arg2 );
99}
100 
101void extract_help_ids(const char *buffer, FILE *fp)
102{
103   const char *ptr = buffer;
104   char **help_ids = malloc(500 * sizeof(char *));
105   int num_help_id = 0;
106   int i;
107 
108   memset(help_ids, '\0', sizeof(help_ids));
109 
110   while(*ptr) {
111      if (strncmp("HIDC_", ptr, 5) == 0) {
112         char id_name[128];
113         char *end = id_name;
114         char *id;
115         memset(id_name, '\0', sizeof(id_name));
116         while (*ptr && *ptr != '\x0d' && *ptr != '\x0a' ) {
117            *end++ = *ptr++;
118         }
119         id = malloc(strlen(id_name));
120         memset(id, '\0', strlen(id_name));
121         memcpy(id, &id_name[1], strlen(&id_name[1]));
122         help_ids[num_help_id] = id;
123         num_help_id++;
124      } else {
125         ptr++;
126      }
127   }
128 
129   /* Sort using Quicksort algorithm: */
130   qsort( (void *)help_ids, (size_t)num_help_id, sizeof( char * ), compare );
131 
132   // Now print them out.
133   ptr = help_ids[0];
134   for (i = 0; i < num_help_id; i++) {
135      if (i > 0) {
136         if (strcmp(ptr, help_ids[i]) == 0) {
137                continue;
138         }
139      }
140      fprintf(fp, "\t%-30s,H%s,\n", help_ids[i], help_ids[i]);
141      ptr = help_ids[i];
142   }
143   fprintf(fp, "\t%-30i,%i\n", 0, 0);
144 
145   // free our allocations.
146   for (i = 0; i < num_help_id; i++) {
147      free(help_ids[i]);
148   }
149   free (help_ids);
150}
151 
src/osd/winui/winui.mak
r0r996
1###########################################################################
2#
3#   winui.mak
4#
5#   winui (Mame32) makefile
6#
7#   Copyright (c) 1996-2007, Nicola Salmoria and the MAME Team.
8#   Visit http://mamedev.org for licensing and usage restrictions.
9#
10###########################################################################
11 
12 
13###########################################################################
14#################   BEGIN USER-CONFIGURABLE OPTIONS   #####################
15###########################################################################
16 
17 
18#-------------------------------------------------
19# specify build options; see each option below
20# for details
21#-------------------------------------------------
22 
23# uncomment next line to enable a build using Microsoft tools
24# MSVC_BUILD = 1
25 
26# uncomment next line to use cygwin compiler
27# CYGWIN_BUILD = 1
28 
29# uncomment next line to enable multi-monitor stubs on Windows 95/NT
30# you will need to find multimon.h and put it into your include
31# path in order to make this work
32# WIN95_MULTIMON = 1
33 
34# uncomment next line to enable a Unicode build
35# UNICODE = 1
36 
37 
38 
39###########################################################################
40##################   END USER-CONFIGURABLE OPTIONS   ######################
41###########################################################################
42 
43 
44#-------------------------------------------------
45# append "32" to the emulator name 
46#-------------------------------------------------
47 
48EMULATOR = $(FULLNAME)32$(EXE)
49 
50 
51 
52#-------------------------------------------------
53# object and source roots
54#-------------------------------------------------
55 
56WINSRC = $(SRC)/osd/windows
57WINOBJ = $(OBJ)/osd/windows
58 
59OBJDIRS += $(WINOBJ)
60 
61# add ui specific src/objs
62UISRC = $(SRC)/osd/$(OSD)
63UIOBJ = $(OBJ)/osd/$(OSD)
64 
65OBJDIRS += $(UIOBJ)
66 
67 
68 
69#-------------------------------------------------
70# configure the resource compiler
71#-------------------------------------------------
72 
73RC = @windres --use-temp-file
74 
75RCDEFS = -DNDEBUG -D_WIN32_IE=0x0400
76 
77# include UISRC direcotry
78RCFLAGS = -O coff -I $(UISRC) -I $(UIOBJ)
79 
80 
81 
82#-------------------------------------------------
83# overrides for the CYGWIN compiler
84#-------------------------------------------------
85 
86ifdef CYGWIN_BUILD
87CFLAGS   += -mno-cygwin
88LDFLAGS   += -mno-cygwin
89endif
90 
91 
92 
93#-------------------------------------------------
94# overrides for the MSVC compiler
95#-------------------------------------------------
96 
97ifdef MSVC_BUILD
98 
99VCONV = $(WINOBJ)/vconv$(EXE)
100 
101# replace the various compilers with vconv.exe prefixes
102CC = @$(VCONV) gcc -I.
103LD = @$(VCONV) ld /profile
104AR = @$(VCONV) ar
105RC = @$(VCONV) windres
106 
107# make sure we use the multithreaded runtime
108CC += /MT
109 
110# turn on link-time codegen if the MAXOPT flag is also set
111ifdef MAXOPT
112CC += /GL
113LD += /LTCG
114endif
115 
116ifdef PTR64
117CC += /wd4267 /wd4312 /Wp64
118endif
119 
120# add some VC++-specific defines
121DEFS += -D_CRT_SECURE_NO_DEPRECATE -DXML_STATIC -D__inline__=__inline -Dsnprintf=_snprintf -Dvsnprintf=_vsnprintf
122 
123# make msvcprep into a pre-build step
124# OSPREBUILD = $(VCONV)
125 
126# add VCONV to the build tools
127BUILD += $(VCONV)
128 
129$(VCONV): $(WINOBJ)/vconv.o
130   @echo Linking $@...
131ifdef PTR64
132   @link.exe /nologo $^ version.lib bufferoverflowu.lib /out:$@
133else
134   @link.exe /nologo $^ version.lib /out:$@
135endif
136 
137$(WINOBJ)/vconv.o: $(WINSRC)/vconv.c
138   @echo Compiling $<...
139   @cl.exe /nologo /O1 -D_CRT_SECURE_NO_DEPRECATE -c $< /Fo$@
140 
141endif
142 
143 
144 
145#-------------------------------------------------
146# due to quirks of using /bin/sh, we need to
147# explicitly specify the current path
148#-------------------------------------------------
149 
150CURPATH = ./
151 
152 
153 
154#-------------------------------------------------
155# Windows-specific debug objects and flags
156#-------------------------------------------------
157 
158# define the x64 ABI to be Windows
159DEFS += -DX64_WINDOWS_ABI
160 
161# debug build: enable guard pages on all memory allocations
162ifdef DEBUG
163DEFS += -DMALLOC_DEBUG
164LDFLAGS += -Wl,--allow-multiple-definition
165endif
166 
167ifdef UNICODE
168DEFS += -DUNICODE -D_UNICODE
169endif
170 
171 
172 
173#-------------------------------------------------
174# Windows-specific flags and libraries
175#-------------------------------------------------
176 
177# add our prefix files to the mix, include WINSRC in UI build
178CFLAGS += -include $(WINSRC)/winprefix.h -I$(WINSRC)
179 
180ifdef WIN95_MULTIMON
181CFLAGS += -DWIN95_MULTIMON
182endif
183 
184# add the windows libaries, 3 additional libs at the end for UI
185LIBS += \
186   -luser32 \
187   -lgdi32 \
188   -lddraw \
189   -ldsound \
190   -ldinput \
191   -ldxguid \
192   -lwinmm \
193   -ladvapi32 \
194   -lcomctl32 \
195   -lshlwapi \
196 
197# add -mwindows for UI
198LDFLAGSEMULATOR += \
199   -mwindows \
200   -lkernel32 \
201   -lshell32 \
202   -lcomdlg32 \
203 
204 
205ifdef PTR64
206LIBS += -lbufferoverflowu
207endif
208 
209 
210 
211#-------------------------------------------------
212# OSD core library
213#-------------------------------------------------
214# still not sure what to do about main.
215 
216OSDCOREOBJS = \
217   $(WINOBJ)/strconv.o   \
218   $(WINOBJ)/windir.o \
219   $(WINOBJ)/winfile.o \
220   $(WINOBJ)/winmisc.o \
221   $(WINOBJ)/winsync.o \
222   $(WINOBJ)/wintime.o \
223   $(WINOBJ)/winutf8.o \
224   $(WINOBJ)/winutil.o \
225   $(WINOBJ)/winwork.o \
226 
227# if malloc debugging is enabled, include the necessary code
228ifneq ($(findstring MALLOC_DEBUG,$(DEFS)),)
229OSDCOREOBJS += \
230   $(WINOBJ)/winalloc.o
231endif
232 
233$(LIBOCORE): $(OSDCOREOBJS)
234 
235 
236 
237#-------------------------------------------------
238# OSD Windows library
239#-------------------------------------------------
240 
241OSDOBJS = \
242   $(WINOBJ)/d3d8intf.o \
243   $(WINOBJ)/d3d9intf.o \
244   $(WINOBJ)/drawd3d.o \
245   $(WINOBJ)/drawdd.o \
246   $(WINOBJ)/drawgdi.o \
247   $(WINOBJ)/drawnone.o \
248   $(WINOBJ)/input.o \
249   $(WINOBJ)/output.o \
250   $(WINOBJ)/sound.o \
251   $(WINOBJ)/video.o \
252   $(WINOBJ)/window.o \
253   $(WINOBJ)/winmain.o \
254 
255 
256# add UI objs
257OSDOBJS += \
258   $(UIOBJ)/m32util.o \
259   $(UIOBJ)/directinput.o \
260   $(UIOBJ)/dijoystick.o \
261   $(UIOBJ)/directdraw.o \
262   $(UIOBJ)/directories.o \
263   $(UIOBJ)/audit32.o \
264   $(UIOBJ)/columnedit.o \
265   $(UIOBJ)/screenshot.o \
266   $(UIOBJ)/treeview.o \
267   $(UIOBJ)/splitters.o \
268   $(UIOBJ)/bitmask.o \
269   $(UIOBJ)/datamap.o \
270   $(UIOBJ)/dxdecode.o \
271   $(UIOBJ)/picker.o \
272   $(UIOBJ)/properties.o \
273   $(UIOBJ)/tabview.o \
274   $(UIOBJ)/help.o \
275   $(UIOBJ)/history.o \
276   $(UIOBJ)/dialogs.o \
277   $(UIOBJ)/m32opts.o \
278   $(UIOBJ)/layout.o \
279   $(UIOBJ)/datafile.o \
280   $(UIOBJ)/dirwatch.o \
281   $(UIOBJ)/win32ui.o \
282   $(UIOBJ)/helpids.o \
283 
284 
285# extra dependencies
286$(WINOBJ)/drawdd.o :    $(SRC)/emu/rendersw.c
287$(WINOBJ)/drawgdi.o :   $(SRC)/emu/rendersw.c
288 
289# add debug-specific files
290ifdef DEBUG
291OSDOBJS += \
292   $(WINOBJ)/debugwin.o
293endif
294 
295# add our UI resources
296RESFILE += $(UIOBJ)/mame32.res
297 
298$(LIBOSD): $(OSDOBJS)
299 
300EMUMAIN = $(UIOBJ)/m32main.o
301 
302 
303 
304#-------------------------------------------------
305# rule for making the ledutil sample
306#
307# Don't build for an MSVC_BUILD
308#-------------------------------------------------
309 
310ledutil$(EXE): $(WINOBJ)/ledutil.o $(WINOBJ)/main.o $(LIBOCORE)
311   @echo Linking $@...
312   $(LD) $(LDFLAGS) $^ $(LIBS) -o $@
313 
314TOOLS += ledutil$(EXE)
315 
316 
317 
318#-------------------------------------------------
319# rules for creating helpids.c 
320#-------------------------------------------------
321 
322$(UISRC)/helpids.c : $(UIOBJ)/mkhelp$(EXE) $(UISRC)/resource.h $(UISRC)/resource.hm $(UISRC)/mame32.rc
323   $(UIOBJ)/mkhelp$(EXE) $(UISRC)/mame32.rc >$@
324 
325# rule to build the generator
326$(UIOBJ)/mkhelp$(EXE): $(UIOBJ)/mkhelp.o
327   @echo Linking $@...
328   $(LD) $(LDFLAGS) $(OSDBGLDFLAGS) $^ $(LIBS) -o $@
329 
330 
331 
332#-------------------------------------------------
333# rule for making the verinfo tool
334#-------------------------------------------------
335 
336VERINFO = $(UIOBJ)/verinfo$(EXE)
337 
338$(VERINFO): $(UIOBJ)/verinfo.o $(LIBOCORE)
339   @echo Linking $@...
340   $(LD) $(LDFLAGS) $^ $(LIBS) -o $@
341 
342BUILD += $(VERINFO)
343 
344 
345 
346#-------------------------------------------------
347# Specific rele to compile verinfo util.
348#-------------------------------------------------
349 
350$(UIOBJ)/verinfo.o : $(WINSRC)/verinfo.c
351   @echo Compiling $<...
352   $(CC) -DWINUI $(CDEFS) $(CFLAGS) -c $< -o $@
353 
354 
355 
356#-------------------------------------------------
357# generic rule for the resource compiler for UI
358#-------------------------------------------------
359 
360$(UIOBJ)/mame32.res: $(UISRC)/mame32.rc $(UIOBJ)/mamevers.rc
361   @echo Compiling mame32 resources $<...
362   $(RC) $(RCDEFS) $(RCFLAGS) -o $@ -i $<
363 
364 
365 
366#-------------------------------------------------
367# rules for resource file
368#-------------------------------------------------
369 
370$(UIOBJ)/mame32.res: $(UISRC)/mame32.rc $(UIOBJ)/mamevers.rc
371 
372$(UIOBJ)/mamevers.rc: $(VERINFO) $(SRC)/version.c
373   @echo Emitting $@...
374   @$(VERINFO) $(SRC)/version.c > $@
375 
376 
377 
378 
379#####  End windui.mak ##############################################
380 
src/osd/winui/dialogs.c
r0r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11***************************************************************************/
12
13/***************************************************************************
14
15  dialogs.c
16
17  Dialog box procedures go here
18
19***************************************************************************/
20
21#define WIN32_LEAN_AND_MEAN
22
23#ifdef _MSC_VER
24#ifndef NONAMELESSUNION
25#define NONAMELESSUNION
26#endif
27#endif
28
29#include <windows.h>
30#include <windowsx.h>
31#include <shellapi.h>
32#include <commctrl.h>
33#include <commdlg.h>
34#include <string.h>
35#include <tchar.h>
36
37#include "bitmask.h"
38#include "treeview.h"
39#include "m32util.h"
40#include "resource.h"
41#include "directories.h"
42#include "m32opts.h"
43#include "splitters.h"
44#include "help.h"
45#include "audit32.h"
46#include "screenshot.h"
47#include "mame32.h"
48#include "properties.h"
49#include "dialogs.h"
50#include "strconv.h"
51#include "winutf8.h"
52
53#ifdef _MSC_VER
54#define snprintf _snprintf
55#endif
56
57#define FILTERTEXT_LEN 256
58
59static char g_FilterText[FILTERTEXT_LEN];
60
61#define NUM_EXCLUSIONS  10
62
63/* Pairs of filters that exclude each other */
64DWORD filterExclusion[NUM_EXCLUSIONS] =
65{
66   IDC_FILTER_CLONES,      IDC_FILTER_ORIGINALS,
67   IDC_FILTER_NONWORKING,  IDC_FILTER_WORKING,
68   IDC_FILTER_UNAVAILABLE, IDC_FILTER_AVAILABLE,
69   IDC_FILTER_RASTER,      IDC_FILTER_VECTOR,
70   IDC_FILTER_HORIZONTAL,  IDC_FILTER_VERTICAL
71};
72
73static void DisableFilterControls(HWND hWnd, LPFOLDERDATA lpFilterRecord,
74                          LPFILTER_ITEM lpFilterItem, DWORD dwFlags);
75static void EnableFilterExclusions(HWND hWnd, DWORD dwCtrlID);
76static DWORD ValidateFilters(LPFOLDERDATA lpFilterRecord, DWORD dwFlags);
77static void OnHScroll(HWND hWnd, HWND hwndCtl, UINT code, int pos);
78
79/***************************************************************************/
80
81const char * GetFilterText(void)
82{
83   return g_FilterText;
84}
85
86INT_PTR CALLBACK ResetDialogProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam)
87{
88   BOOL resetFilters  = FALSE;
89   BOOL resetGames    = FALSE;
90   BOOL resetUI      = FALSE;
91   BOOL resetDefaults = FALSE;
92
93   switch (Msg)
94   {
95   case WM_INITDIALOG:
96      return TRUE;
97
98   case WM_HELP:
99      /* User clicked the ? from the upper right on a control */
100      HelpFunction(((LPHELPINFO)lParam)->hItemHandle, MAME32CONTEXTHELP, HH_TP_HELP_WM_HELP, GetHelpIDs());
101      break;
102
103   case WM_CONTEXTMENU:
104      HelpFunction((HWND)wParam, MAME32CONTEXTHELP, HH_TP_HELP_CONTEXTMENU, GetHelpIDs());
105
106      break;
107
108   case WM_COMMAND :
109      switch (GET_WM_COMMAND_ID(wParam, lParam))
110      {
111      case IDOK :
112         resetFilters  = Button_GetCheck(GetDlgItem(hDlg, IDC_RESET_FILTERS));
113         resetGames     = Button_GetCheck(GetDlgItem(hDlg, IDC_RESET_GAMES));
114         resetDefaults = Button_GetCheck(GetDlgItem(hDlg, IDC_RESET_DEFAULT));
115         resetUI      = Button_GetCheck(GetDlgItem(hDlg, IDC_RESET_UI));
116         if (resetFilters || resetGames || resetUI || resetDefaults)
117         {
118
119            TCHAR temp[400];
120            _tcscpy(temp, TEXT(MAME32NAME));
121            _tcscat(temp, TEXT(" will now reset the following\n"));
122            _tcscat(temp, TEXT("to the default settings:\n\n"));
123
124            if (resetDefaults)
125               _tcscat(temp, TEXT("Global game options\n"));
126            if (resetGames)
127               _tcscat(temp, TEXT("Individual game options\n"));
128            if (resetFilters)
129               _tcscat(temp, TEXT("Custom folder filters\n"));
130            if (resetUI)
131            {
132               _tcscat(temp, TEXT("User interface settings\n\n"));
133               _tcscat(temp, TEXT("Resetting the User Interface options\n"));
134               _tcscat(temp, TEXT("requires exiting "));
135               _tcscat(temp, TEXT(MAME32NAME));
136               _tcscat(temp, TEXT(".\n"));
137            }
138            _tcscat(temp, TEXT("\nDo you wish to continue?"));
139            if (MessageBox(hDlg, temp, TEXT("Restore Settings"), IDOK) == IDOK)
140            {
141               if (resetFilters)
142                  ResetFilters();
143
144               if (resetGames)
145                  ResetAllGameOptions();
146
147               if (resetDefaults)
148                  ResetGameDefaults();
149
150               // This is the only case we need to exit and restart for.
151               if (resetUI)
152               {
153                  ResetGUI();
154                  EndDialog(hDlg, 1);
155                  return TRUE;
156               } else {
157                  EndDialog(hDlg, 0);
158                  return TRUE;
159               }
160            } else {
161               // Give the user a chance to change what they want to reset.
162               break;
163            }
164         }
165      // Nothing was selected but OK, just fall through
166      case IDCANCEL :
167         EndDialog(hDlg, 0);
168         return TRUE;
169      }
170      break;
171   }
172   return 0;
173}
174
175INT_PTR CALLBACK InterfaceDialogProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam)
176{
177   CHOOSECOLOR cc;
178   COLORREF choice_colors[16];
179   TCHAR tmp[4];
180   int i;
181   BOOL bRedrawList = FALSE;
182   int nCurSelection = 0;
183   int nHistoryTab = 0;
184   int nCount = 0;
185   int value;
186
187   switch (Msg)
188   {
189   case WM_INITDIALOG:
190      Button_SetCheck(GetDlgItem(hDlg,IDC_START_GAME_CHECK),GetGameCheck());
191      Button_SetCheck(GetDlgItem(hDlg,IDC_JOY_GUI),GetJoyGUI());
192      Button_SetCheck(GetDlgItem(hDlg,IDC_KEY_GUI),GetKeyGUI());
193      Button_SetCheck(GetDlgItem(hDlg,IDC_BROADCAST),GetBroadcast());
194      Button_SetCheck(GetDlgItem(hDlg,IDC_RANDOM_BG),GetRandomBackground());
195      Button_SetCheck(GetDlgItem(hDlg,IDC_GAME_CAPTION),GetGameCaption());
196     
197      Button_SetCheck(GetDlgItem(hDlg,IDC_HIDE_MOUSE),GetHideMouseOnStartup());
198
199      // Get the current value of the control
200      SendDlgItemMessage(hDlg, IDC_CYCLETIMESEC, TBM_SETRANGE,
201               (WPARAM)FALSE,
202               (LPARAM)MAKELONG(0, 60)); /* [0, 60] */
203      value = GetCycleScreenshot();
204      SendDlgItemMessage(hDlg,IDC_CYCLETIMESEC, TBM_SETPOS, TRUE, value);
205      _itot(value,tmp,10);
206      SendDlgItemMessage(hDlg,IDC_CYCLETIMESECTXT,WM_SETTEXT,0, (WPARAM)tmp);
207
208      Button_SetCheck(GetDlgItem(hDlg,IDC_STRETCH_SCREENSHOT_LARGER),
209                  GetStretchScreenShotLarger());
210      Button_SetCheck(GetDlgItem(hDlg,IDC_FILTER_INHERIT),
211                  GetFilterInherit());
212      Button_SetCheck(GetDlgItem(hDlg,IDC_NOOFFSET_CLONES),
213                  GetOffsetClones());
214      (void)ComboBox_AddString(GetDlgItem(hDlg, IDC_HISTORY_TAB), TEXT("Snapshot"));
215      (void)ComboBox_SetItemData(GetDlgItem(hDlg, IDC_HISTORY_TAB), nCount++, TAB_SCREENSHOT);
216      (void)ComboBox_AddString(GetDlgItem(hDlg, IDC_HISTORY_TAB), TEXT("Flyer"));
217      (void)ComboBox_SetItemData(GetDlgItem(hDlg, IDC_HISTORY_TAB), nCount++, TAB_FLYER);
218      (void)ComboBox_AddString(GetDlgItem(hDlg, IDC_HISTORY_TAB), TEXT("Cabinet"));
219      (void)ComboBox_SetItemData(GetDlgItem(hDlg, IDC_HISTORY_TAB), nCount++, TAB_CABINET);
220      (void)ComboBox_AddString(GetDlgItem(hDlg, IDC_HISTORY_TAB), TEXT("Marquee"));
221      (void)ComboBox_SetItemData(GetDlgItem(hDlg, IDC_HISTORY_TAB), nCount++, TAB_MARQUEE);
222      (void)ComboBox_AddString(GetDlgItem(hDlg, IDC_HISTORY_TAB), TEXT("Title"));
223      (void)ComboBox_SetItemData(GetDlgItem(hDlg, IDC_HISTORY_TAB), nCount++, TAB_TITLE);
224      (void)ComboBox_AddString(GetDlgItem(hDlg, IDC_HISTORY_TAB), TEXT("Control Panel"));
225      (void)ComboBox_SetItemData(GetDlgItem(hDlg, IDC_HISTORY_TAB), nCount++, TAB_CONTROL_PANEL);
226      (void)ComboBox_AddString(GetDlgItem(hDlg, IDC_HISTORY_TAB), TEXT("PCB"));
227      (void)ComboBox_SetItemData(GetDlgItem(hDlg, IDC_HISTORY_TAB), nCount++, TAB_PCB);
228      (void)ComboBox_AddString(GetDlgItem(hDlg, IDC_HISTORY_TAB), TEXT("All"));
229      (void)ComboBox_SetItemData(GetDlgItem(hDlg, IDC_HISTORY_TAB), nCount++, TAB_ALL);
230      (void)ComboBox_AddString(GetDlgItem(hDlg, IDC_HISTORY_TAB), TEXT("None"));
231      (void)ComboBox_SetItemData(GetDlgItem(hDlg, IDC_HISTORY_TAB), nCount++, TAB_NONE);
232      if( GetHistoryTab() < MAX_TAB_TYPES )
233         (void)ComboBox_SetCurSel(GetDlgItem(hDlg, IDC_HISTORY_TAB), GetHistoryTab());
234      else
235         (void)ComboBox_SetCurSel(GetDlgItem(hDlg, IDC_HISTORY_TAB), GetHistoryTab()-TAB_SUBTRACT);
236
237      SendDlgItemMessage(hDlg, IDC_SCREENSHOT_BORDERSIZE, TBM_SETRANGE,
238               (WPARAM)FALSE,
239               (LPARAM)MAKELONG(0, 100)); /* [0, 100] */
240      value = GetScreenshotBorderSize();
241      SendDlgItemMessage(hDlg,IDC_SCREENSHOT_BORDERSIZE, TBM_SETPOS, TRUE, value);
242      _itot(value,tmp,10);
243      SendDlgItemMessage(hDlg,IDC_SCREENSHOT_BORDERSIZETXT,WM_SETTEXT,0, (WPARAM)tmp);
244
245      //return TRUE;
246      break;
247
248   case WM_HELP:
249      /* User clicked the ? from the upper right on a control */
250      HelpFunction(((LPHELPINFO)lParam)->hItemHandle, MAME32CONTEXTHELP, HH_TP_HELP_WM_HELP, GetHelpIDs());
251      break;
252
253   case WM_CONTEXTMENU:
254      HelpFunction((HWND)wParam, MAME32CONTEXTHELP, HH_TP_HELP_CONTEXTMENU, GetHelpIDs());
255      break;
256   case WM_HSCROLL:
257      HANDLE_WM_HSCROLL(hDlg, wParam, lParam, OnHScroll);
258      break;
259   case WM_COMMAND :
260      switch (GET_WM_COMMAND_ID(wParam, lParam))
261      {
262      case IDC_SCREENSHOT_BORDERCOLOR:
263      {
264         for (i=0;i<16;i++)
265             choice_colors[i] = GetCustomColor(i);
266
267         cc.lStructSize = sizeof(CHOOSECOLOR);
268         cc.hwndOwner   = hDlg;
269         cc.rgbResult   = GetScreenshotBorderColor();
270         cc.lpCustColors = choice_colors;
271         cc.Flags       = CC_ANYCOLOR | CC_RGBINIT | CC_SOLIDCOLOR;
272         if (!ChooseColor(&cc))
273            return TRUE;
274          for (i=0;i<16;i++)
275             SetCustomColor(i,choice_colors[i]);
276         SetScreenshotBorderColor(cc.rgbResult);
277         UpdateScreenShot();
278         return TRUE;
279      }
280      case IDOK :
281      {
282         BOOL checked = FALSE;
283
284         SetGameCheck(Button_GetCheck(GetDlgItem(hDlg, IDC_START_GAME_CHECK)));
285         SetJoyGUI(Button_GetCheck(GetDlgItem(hDlg, IDC_JOY_GUI)));
286         SetKeyGUI(Button_GetCheck(GetDlgItem(hDlg, IDC_KEY_GUI)));
287         SetBroadcast(Button_GetCheck(GetDlgItem(hDlg, IDC_BROADCAST)));
288         SetRandomBackground(Button_GetCheck(GetDlgItem(hDlg, IDC_RANDOM_BG)));
289         SetGameCaption(Button_GetCheck(GetDlgItem(hDlg, IDC_GAME_CAPTION)));
290         
291         SetHideMouseOnStartup(Button_GetCheck(GetDlgItem(hDlg,IDC_HIDE_MOUSE)));
292
293         if( Button_GetCheck(GetDlgItem(hDlg,IDC_RESET_PLAYCOUNT ) ) )
294         {
295            ResetPlayCount( -1 );
296            bRedrawList = TRUE;
297         }
298         if( Button_GetCheck(GetDlgItem(hDlg,IDC_RESET_PLAYTIME ) ) )
299         {
300            ResetPlayTime( -1 );
301            bRedrawList = TRUE;
302         }
303         value = SendDlgItemMessage(hDlg,IDC_CYCLETIMESEC, TBM_GETPOS, 0, 0);
304         if( GetCycleScreenshot() != value )
305         {
306            SetCycleScreenshot(value);
307         }
308         value = SendDlgItemMessage(hDlg,IDC_SCREENSHOT_BORDERSIZE, TBM_GETPOS, 0, 0);
309         if( GetScreenshotBorderSize() != value )
310         {
311            SetScreenshotBorderSize(value);
312            UpdateScreenShot();
313         }
314         value = SendDlgItemMessage(hDlg,IDC_HIGH_PRIORITY, TBM_GETPOS, 0, 0);
315         checked = Button_GetCheck(GetDlgItem(hDlg,IDC_STRETCH_SCREENSHOT_LARGER));
316         if (checked != GetStretchScreenShotLarger())
317         {
318            SetStretchScreenShotLarger(checked);
319            UpdateScreenShot();
320         }
321         checked = Button_GetCheck(GetDlgItem(hDlg,IDC_FILTER_INHERIT));
322         if (checked != GetFilterInherit())
323         {
324            SetFilterInherit(checked);
325            // LineUpIcons does just a ResetListView(), which is what we want here
326            PostMessage(GetMainWindow(),WM_COMMAND, MAKEWPARAM(ID_VIEW_LINEUPICONS, FALSE),(LPARAM)NULL);
327          }
328         checked = Button_GetCheck(GetDlgItem(hDlg,IDC_NOOFFSET_CLONES));
329         if (checked != GetOffsetClones())
330         {
331            SetOffsetClones(checked);
332            // LineUpIcons does just a ResetListView(), which is what we want here
333            PostMessage(GetMainWindow(),WM_COMMAND, MAKEWPARAM(ID_VIEW_LINEUPICONS, FALSE),(LPARAM)NULL);
334          }
335         nCurSelection = ComboBox_GetCurSel(GetDlgItem(hDlg,IDC_HISTORY_TAB));
336         if (nCurSelection != CB_ERR)
337            nHistoryTab = ComboBox_GetItemData(GetDlgItem(hDlg,IDC_HISTORY_TAB), nCurSelection);
338         EndDialog(hDlg, 0);
339         if( GetHistoryTab() != nHistoryTab )
340         {
341            SetHistoryTab(nHistoryTab, TRUE);
342            ResizePickerControls(GetMainWindow());
343            UpdateScreenShot();
344         }
345         if( bRedrawList )
346         {
347            UpdateListView();
348         }
349         return TRUE;
350      }
351      case IDCANCEL :
352         EndDialog(hDlg, 0);
353         return TRUE;
354      }
355      break;
356   }
357   return 0;
358}
359
360INT_PTR CALLBACK FilterDialogProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam)
361{
362   static DWORD         dwFilters;
363   static DWORD         dwpFilters;
364   static LPFOLDERDATA      lpFilterRecord;
365   char                strText[250];
366   int                i;
367
368   switch (Msg)
369   {
370   case WM_INITDIALOG:
371   {
372      LPTREEFOLDER folder = GetCurrentFolder();
373      LPTREEFOLDER lpParent = NULL;
374      LPFILTER_ITEM g_lpFilterList = GetFilterList();
375
376      dwFilters = 0;
377
378      if (folder != NULL)
379      {
380         char tmp[80];
381         
382         win_set_window_text_utf8(GetDlgItem(hDlg, IDC_FILTER_EDIT), g_FilterText);
383         Edit_SetSel(GetDlgItem(hDlg, IDC_FILTER_EDIT), 0, -1);
384         // Mask out non filter flags
385         dwFilters = folder->m_dwFlags & F_MASK;
386         // Display current folder name in dialog titlebar
387         snprintf(tmp,ARRAY_LENGTH(tmp),"Filters for %s Folder",folder->m_lpTitle);
388         win_set_window_text_utf8(hDlg, tmp);
389         if ( GetFilterInherit() )
390         {
391            if( folder )
392            {
393               BOOL bShowExplanation = FALSE;
394               lpParent = GetFolder( folder->m_nParent );
395               if( lpParent )
396               {
397                  /* Check the Parent Filters and inherit them on child,
398                   * No need to promote all games to parent folder, works as is */
399                  dwpFilters = lpParent->m_dwFlags & F_MASK;
400                  /*Check all possible Filters if inherited solely from parent, e.g. not being set explicitly on our folder*/
401                  if( (dwpFilters & F_CLONES) && !(dwFilters & F_CLONES) )
402                  {
403                     /*Add a Specifier to the Checkbox to show it was inherited from the parent*/
404                     win_get_window_text_utf8(GetDlgItem(hDlg, IDC_FILTER_CLONES), strText, 250);
405                     strcat(strText, " (*)");
406                     win_set_window_text_utf8(GetDlgItem(hDlg, IDC_FILTER_CLONES), strText);
407                     bShowExplanation = TRUE;
408                  }
409                  if( (dwpFilters & F_NONWORKING) && !(dwFilters & F_NONWORKING) )
410                  {
411                     /*Add a Specifier to the Checkbox to show it was inherited from the parent*/
412                     win_get_window_text_utf8(GetDlgItem(hDlg, IDC_FILTER_NONWORKING), strText, 250);
413                     strcat(strText, " (*)");
414                     win_set_window_text_utf8(GetDlgItem(hDlg, IDC_FILTER_NONWORKING), strText);
415                     bShowExplanation = TRUE;
416                  }
417                  if( (dwpFilters & F_UNAVAILABLE) && !(dwFilters & F_UNAVAILABLE) )
418                  {
419                     /*Add a Specifier to the Checkbox to show it was inherited from the parent*/
420                     win_get_window_text_utf8(GetDlgItem(hDlg, IDC_FILTER_UNAVAILABLE), strText, 250);
421                     strcat(strText, " (*)");
422                     win_set_window_text_utf8(GetDlgItem(hDlg, IDC_FILTER_UNAVAILABLE), strText);
423                     bShowExplanation = TRUE;
424                  }
425                  if( (dwpFilters & F_VECTOR) && !(dwFilters & F_VECTOR) )
426                  {
427                     /*Add a Specifier to the Checkbox to show it was inherited from the parent*/
428                     win_get_window_text_utf8(GetDlgItem(hDlg, IDC_FILTER_VECTOR), strText, 250);
429                     strcat(strText, " (*)");
430                     win_set_window_text_utf8(GetDlgItem(hDlg, IDC_FILTER_VECTOR), strText);
431                     bShowExplanation = TRUE;
432                  }
433                  if( (dwpFilters & F_RASTER) && !(dwFilters & F_RASTER) )
434                  {
435                     /*Add a Specifier to the Checkbox to show it was inherited from the parent*/
436                     win_get_window_text_utf8(GetDlgItem(hDlg, IDC_FILTER_RASTER), strText, 250);
437                     strcat(strText, " (*)");
438                     win_set_window_text_utf8(GetDlgItem(hDlg, IDC_FILTER_RASTER), strText);
439                     bShowExplanation = TRUE;
440                  }
441                  if( (dwpFilters & F_ORIGINALS) && !(dwFilters & F_ORIGINALS) )
442                  {
443                     /*Add a Specifier to the Checkbox to show it was inherited from the parent*/
444                     win_get_window_text_utf8(GetDlgItem(hDlg, IDC_FILTER_ORIGINALS), strText, 250);
445                     strcat(strText, " (*)");
446                     win_set_window_text_utf8(GetDlgItem(hDlg, IDC_FILTER_ORIGINALS), strText);
447                     bShowExplanation = TRUE;
448                  }
449                  if( (dwpFilters & F_WORKING) && !(dwFilters & F_WORKING) )
450                  {
451                     /*Add a Specifier to the Checkbox to show it was inherited from the parent*/
452                     win_get_window_text_utf8(GetDlgItem(hDlg, IDC_FILTER_WORKING), strText, 250);
453                     strcat(strText, " (*)");
454                     win_set_window_text_utf8(GetDlgItem(hDlg, IDC_FILTER_WORKING), strText);
455                     bShowExplanation = TRUE;
456                  }
457                  if( (dwpFilters & F_AVAILABLE) && !(dwFilters & F_AVAILABLE) )
458                  {
459                     /*Add a Specifier to the Checkbox to show it was inherited from the parent*/
460                     win_get_window_text_utf8(GetDlgItem(hDlg, IDC_FILTER_AVAILABLE), strText, 250);
461                     strcat(strText, " (*)");
462                     win_set_window_text_utf8(GetDlgItem(hDlg, IDC_FILTER_AVAILABLE), strText);
463                     bShowExplanation = TRUE;
464                  }
465                  if( (dwpFilters & F_HORIZONTAL) && !(dwFilters & F_HORIZONTAL) )
466                  {
467                     /*Add a Specifier to the Checkbox to show it was inherited from the parent*/
468                     win_get_window_text_utf8(GetDlgItem(hDlg, IDC_FILTER_HORIZONTAL), strText, 250);
469                     strcat(strText, " (*)");
470                     win_set_window_text_utf8(GetDlgItem(hDlg, IDC_FILTER_HORIZONTAL), strText);
471                     bShowExplanation = TRUE;
472                  }
473                  if( (dwpFilters & F_VERTICAL) && !(dwFilters & F_VERTICAL) )
474                  {
475                     /*Add a Specifier to the Checkbox to show it was inherited from the parent*/
476                     win_get_window_text_utf8(GetDlgItem(hDlg, IDC_FILTER_VERTICAL), strText, 250);
477                     strcat(strText, " (*)");
478                     win_set_window_text_utf8(GetDlgItem(hDlg, IDC_FILTER_VERTICAL), strText);
479                     bShowExplanation = TRUE;
480                  }
481                  /*Do not or in the Values of the parent, so that the values of the folder still can be set*/
482                  //dwFilters |= dwpFilters;
483               }
484               if( ! bShowExplanation )
485               {
486                  ShowWindow(GetDlgItem(hDlg, IDC_INHERITED), FALSE );
487               }
488            }
489         }
490         else
491         {
492            ShowWindow(GetDlgItem(hDlg, IDC_INHERITED), FALSE );
493         }
494         // Find the matching filter record if it exists
495         lpFilterRecord = FindFilter(folder->m_nFolderId);
496
497         // initialize and disable appropriate controls
498         for (i = 0; g_lpFilterList[i].m_dwFilterType; i++)
499         {
500            DisableFilterControls(hDlg, lpFilterRecord, &g_lpFilterList[i], dwFilters);
501         }
502      }
503      SetFocus(GetDlgItem(hDlg, IDC_FILTER_EDIT));
504      return FALSE;
505   }
506   case WM_HELP:
507      // User clicked the ? from the upper right on a control
508      HelpFunction(((LPHELPINFO)lParam)->hItemHandle, MAME32CONTEXTHELP,
509                HH_TP_HELP_WM_HELP, GetHelpIDs());
510      break;
511
512   case WM_CONTEXTMENU:
513      HelpFunction((HWND)wParam, MAME32CONTEXTHELP, HH_TP_HELP_CONTEXTMENU, GetHelpIDs());
514      break;
515
516   case WM_COMMAND:
517   {
518      WORD wID       = GET_WM_COMMAND_ID(wParam, lParam);
519      WORD wNotifyCode = GET_WM_COMMAND_CMD(wParam, lParam);
520      LPTREEFOLDER folder = GetCurrentFolder();
521      LPFILTER_ITEM g_lpFilterList = GetFilterList();
522
523      switch (wID)
524      {
525      case IDOK:
526         dwFilters = 0;
527         
528         win_get_window_text_utf8(GetDlgItem(hDlg, IDC_FILTER_EDIT), g_FilterText, FILTERTEXT_LEN);
529         
530         // see which buttons are checked
531         for (i = 0; g_lpFilterList[i].m_dwFilterType; i++)
532         {
533            if (Button_GetCheck(GetDlgItem(hDlg, g_lpFilterList[i].m_dwCtrlID)))
534               dwFilters |= g_lpFilterList[i].m_dwFilterType;
535         }
536
537         // Mask out invalid filters
538         dwFilters = ValidateFilters(lpFilterRecord, dwFilters);
539
540         // Keep non filter flags
541         folder->m_dwFlags &= ~F_MASK;
542
543         // put in the set filters
544         folder->m_dwFlags |= dwFilters;
545
546         EndDialog(hDlg, 1);
547         return TRUE;
548
549      case IDCANCEL:
550         EndDialog(hDlg, 0);
551         return TRUE;
552         
553      default:
554         // Handle unchecking mutually exclusive filters
555         if (wNotifyCode == BN_CLICKED)
556            EnableFilterExclusions(hDlg, wID);
557      }
558   }
559   break;
560   }
561   return 0;
562}
563
564INT_PTR CALLBACK AboutDialogProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam)
565{
566   switch (Msg)
567   {
568   case WM_INITDIALOG:
569      {
570         HBITMAP hBmp;
571         hBmp = (HBITMAP)LoadImage(GetModuleHandle(NULL),
572                             MAKEINTRESOURCE(IDB_ABOUT),
573                             IMAGE_BITMAP, 0, 0, LR_SHARED);
574         SendDlgItemMessage(hDlg, IDC_ABOUT, STM_SETIMAGE,
575                  (WPARAM)IMAGE_BITMAP, (LPARAM)hBmp);
576         win_set_window_text_utf8(GetDlgItem(hDlg, IDC_VERSION), GetVersionString());
577      }
578      return 1;
579
580   case WM_COMMAND:
581      EndDialog(hDlg, 0);
582      return 1;
583   }
584   return 0;
585}
586
587INT_PTR CALLBACK AddCustomFileDialogProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam)
588{
589    static LPTREEFOLDER default_selection = NULL;
590   static int driver_index;
591
592   switch (Msg)
593   {
594   case WM_INITDIALOG:
595   {
596       TREEFOLDER **folders;
597      int num_folders;
598      int i;
599      TVINSERTSTRUCT tvis;
600      TVITEM tvi;
601      BOOL first_entry = TRUE;
602      HIMAGELIST treeview_icons = GetTreeViewIconList();
603
604      // current game passed in using DialogBoxParam()
605      driver_index = lParam;
606
607      (void)TreeView_SetImageList(GetDlgItem(hDlg,IDC_CUSTOM_TREE), treeview_icons, LVSIL_NORMAL);
608
609      GetFolders(&folders,&num_folders);
610
611      // should add "New..."
612
613      // insert custom folders into our tree view
614      for (i=0;i<num_folders;i++)
615      {
616          if (folders[i]->m_dwFlags & F_CUSTOM)
617         {
618             HTREEITEM hti;
619            int jj;
620
621            if (folders[i]->m_nParent == -1)
622            {
623               memset(&tvi, '\0', sizeof(tvi));
624                tvis.hParent = TVI_ROOT;
625               tvis.hInsertAfter = TVI_SORT;
626               tvi.mask = TVIF_TEXT | TVIF_PARAM | TVIF_IMAGE | TVIF_SELECTEDIMAGE;
627               tvi.pszText = folders[i]->m_lptTitle;
628               tvi.lParam = (LPARAM)folders[i];
629               tvi.iImage = GetTreeViewIconIndex(folders[i]->m_nIconId);
630               tvi.iSelectedImage = 0;
631#if defined(__GNUC__) /* bug in commctrl.h */
632               tvis.item = tvi;
633#else
634               tvis.DUMMYUNIONNAME.item = tvi;
635#endif
636               
637               hti = TreeView_InsertItem(GetDlgItem(hDlg,IDC_CUSTOM_TREE),&tvis);
638
639               /* look for children of this custom folder */
640               for (jj=0;jj<num_folders;jj++)
641               {
642                   if (folders[jj]->m_nParent == i)
643                  {
644                      HTREEITEM hti_child;
645                      tvis.hParent = hti;
646                     tvis.hInsertAfter = TVI_SORT;
647                     tvi.mask = TVIF_TEXT | TVIF_PARAM | TVIF_IMAGE | TVIF_SELECTEDIMAGE;
648                     tvi.pszText = folders[jj]->m_lptTitle;
649                     tvi.lParam = (LPARAM)folders[jj];
650                     tvi.iImage = GetTreeViewIconIndex(folders[jj]->m_nIconId);
651                     tvi.iSelectedImage = 0;
652#if defined(__GNUC__) /* bug in commctrl.h */
653                       tvis.item = tvi;
654#else
655                       tvis.DUMMYUNIONNAME.item = tvi;
656#endif                     
657                     hti_child = TreeView_InsertItem(GetDlgItem(hDlg,IDC_CUSTOM_TREE),&tvis);
658                     if (folders[jj] == default_selection)
659                         TreeView_SelectItem(GetDlgItem(hDlg,IDC_CUSTOM_TREE),hti_child);
660                  }
661               }
662
663               /*TreeView_Expand(GetDlgItem(hDlg,IDC_CUSTOM_TREE),hti,TVE_EXPAND);*/
664               if (first_entry || folders[i] == default_selection)
665               {
666                   TreeView_SelectItem(GetDlgItem(hDlg,IDC_CUSTOM_TREE),hti);
667                  first_entry = FALSE;
668               }
669
670            }
671           
672         }
673      }
674     
675      win_set_window_text_utf8(GetDlgItem(hDlg,IDC_CUSTOMFILE_GAME),
676                 ModifyThe(drivers[driver_index]->description));
677
678      return TRUE;
679   }
680   case WM_COMMAND:
681      switch (GET_WM_COMMAND_ID(wParam, lParam))
682      {
683      case IDOK:
684      {
685         TVITEM tvi;
686         tvi.hItem = TreeView_GetSelection(GetDlgItem(hDlg,IDC_CUSTOM_TREE));
687         tvi.mask = TVIF_PARAM;
688         if (TreeView_GetItem(GetDlgItem(hDlg,IDC_CUSTOM_TREE),&tvi) == TRUE)
689         {
690           /* should look for New... */
691         
692           default_selection = (LPTREEFOLDER)tvi.lParam; /* start here next time */
693
694           AddToCustomFolder((LPTREEFOLDER)tvi.lParam,driver_index);
695         }
696
697         EndDialog(hDlg, 0);
698         return TRUE;
699
700         break;
701      }
702      case IDCANCEL:
703         EndDialog(hDlg, 0);
704         return TRUE;
705
706      }
707      break;
708   }
709   return 0;
710}
711
712INT_PTR CALLBACK DirectXDialogProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam)
713{
714   HWND hEdit;
715
716   const char *directx_help =
717      MAME32NAME " requires DirectX version 3 or later, which is a set of operating\r\n"
718      "system extensions by Microsoft for Windows 9x, NT and 2000.\r\n\r\n"
719      "Visit Microsoft's DirectX web page at http://www.microsoft.com/directx\r\n"
720      "download DirectX, install it, and then run " MAME32NAME " again.\r\n";
721
722   switch (Msg)
723   {
724   case WM_INITDIALOG:
725      hEdit = GetDlgItem(hDlg, IDC_DIRECTX_HELP);
726      Edit_SetSel(hEdit, Edit_GetTextLength(hEdit), Edit_GetTextLength(hEdit));
727      Edit_ReplaceSel(hEdit, directx_help);
728      return 1;
729
730   case WM_COMMAND:
731      if (LOWORD(wParam) == IDB_WEB_PAGE)
732         ShellExecute(GetMainWindow(), NULL, TEXT("http://www.microsoft.com/directx"),
733                   NULL, NULL, SW_SHOWNORMAL);
734
735      if (LOWORD(wParam) == IDCANCEL || LOWORD(wParam) == IDB_WEB_PAGE)
736         EndDialog(hDlg, 0);
737      return 1;
738   }
739   return 0;
740}
741
742/***************************************************************************
743    private functions
744 ***************************************************************************/
745
746static void DisableFilterControls(HWND hWnd, LPFOLDERDATA lpFilterRecord,
747                          LPFILTER_ITEM lpFilterItem, DWORD dwFlags)
748{
749   HWND  hWndCtrl = GetDlgItem(hWnd, lpFilterItem->m_dwCtrlID);
750   DWORD dwFilterType = lpFilterItem->m_dwFilterType;
751
752   /* Check the appropriate control */
753   if (dwFilterType & dwFlags)
754      Button_SetCheck(hWndCtrl, MF_CHECKED);
755
756   /* No special rules for this folder? */
757   if (!lpFilterRecord)
758      return;
759
760   /* If this is an excluded filter */
761   if (lpFilterRecord->m_dwUnset & dwFilterType)
762   {
763      /* uncheck it and disable the control */
764      Button_SetCheck(hWndCtrl, MF_UNCHECKED);
765      EnableWindow(hWndCtrl, FALSE);
766   }
767
768   /* If this is an implied filter, check it and disable the control */
769   if (lpFilterRecord->m_dwSet & dwFilterType)
770   {
771      Button_SetCheck(hWndCtrl, MF_CHECKED);
772      EnableWindow(hWndCtrl, FALSE);
773   }
774}
775
776// Handle disabling mutually exclusive controls
777static void EnableFilterExclusions(HWND hWnd, DWORD dwCtrlID)
778{
779   int    i;
780   DWORD   id;
781
782   for (i = 0; i < NUM_EXCLUSIONS; i++)
783   {
784      // is this control in the list?
785      if (filterExclusion[i] == dwCtrlID)
786      {
787         // found the control id
788         break;
789      }
790   }
791
792   // if the control was found
793   if (i < NUM_EXCLUSIONS)
794   {
795      // find the opposing control id
796      if (i % 2)
797         id = filterExclusion[i - 1];
798      else
799         id = filterExclusion[i + 1];
800
801      // Uncheck the other control
802      Button_SetCheck(GetDlgItem(hWnd, id), MF_UNCHECKED);
803   }
804}
805
806// Validate filter setting, mask out inappropriate filters for this folder
807static DWORD ValidateFilters(LPFOLDERDATA lpFilterRecord, DWORD dwFlags)
808{
809   DWORD dwFilters;
810
811   if (lpFilterRecord != (LPFOLDERDATA)0)
812   {
813      // Mask out implied and excluded filters
814      dwFilters = lpFilterRecord->m_dwSet | lpFilterRecord->m_dwUnset;
815      return dwFlags & ~dwFilters;
816   }
817
818   // No special cases - all filters apply
819   return dwFlags;
820}
821
822static void OnHScroll(HWND hwnd, HWND hwndCtl, UINT code, int pos)
823{
824   int value;
825   TCHAR tmp[4];
826   if (hwndCtl == GetDlgItem(hwnd, IDC_CYCLETIMESEC))
827   {
828      value = SendDlgItemMessage(hwnd,IDC_CYCLETIMESEC, TBM_GETPOS, 0, 0);
829      _itot(value,tmp,10);
830      SendDlgItemMessage(hwnd,IDC_CYCLETIMESECTXT,WM_SETTEXT,0, (WPARAM)tmp);
831   }
832   else
833   if (hwndCtl == GetDlgItem(hwnd, IDC_SCREENSHOT_BORDERSIZE))
834   {
835      value = SendDlgItemMessage(hwnd,IDC_SCREENSHOT_BORDERSIZE, TBM_GETPOS, 0, 0);
836      _itot(value,tmp,10);
837      SendDlgItemMessage(hwnd,IDC_SCREENSHOT_BORDERSIZETXT,WM_SETTEXT,0, (WPARAM)tmp);
838   }
839}
src/osd/winui/file.h
r0r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11 ***************************************************************************/
12
13#ifndef FILE_H
14#define FILE_H
15
16// from windows fileio.c
17extern void set_pathlist(int file_type,const char *new_rawpath);
18
19#define OSD_FILETYPE_ICON 1001
20
21#endif
src/osd/winui/dxdecode.h
r0r996
1/* Copyright 1998 Invasion Games.  All Rights Reserved.  Do NOT distribute. */
2
3/* dxdecode.h for client */
4
5/* Main header file for dxdecode.cpp */
6
7#ifndef DXDECODE_H
8#define DXDECODE_H
9
10extern const char* DirectXDecodeError(HRESULT errorval);
11
12#endif /* DXDECODE_H */
src/osd/winui/dialogs.h
r0r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11 ***************************************************************************/
12
13#ifndef DIALOGS_H
14#define DIALOGS_H
15
16const char * GetFilterText(void);
17
18INT_PTR CALLBACK ResetDialogProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam);
19INT_PTR CALLBACK InterfaceDialogProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam);
20INT_PTR CALLBACK FilterDialogProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam);
21INT_PTR CALLBACK AboutDialogProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam);
22INT_PTR CALLBACK AddCustomFileDialogProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam);
23INT_PTR CALLBACK DirectXDialogProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam);
24
25
26#endif
27
src/osd/winui/help.c
r0r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10   
11***************************************************************************/
12
13/***************************************************************************
14
15  help.c
16 
17   Help wrapper code.
18   
19***************************************************************************/
20
21#define WIN32_LEAN_AND_MEAN
22#include <windows.h>
23#include "help.h"
24
25typedef HWND (WINAPI *HtmlHelpProc)(HWND hwndCaller, LPCSTR pszFile, UINT uCommand, DWORD_PTR dwData);
26
27/***************************************************************************
28 Internal structures
29***************************************************************************/
30
31/***************************************************************************
32 function prototypes
33***************************************************************************/
34
35static void Help_Load(void);
36
37/***************************************************************************
38 External function prototypes
39***************************************************************************/
40
41/***************************************************************************
42 External variables
43***************************************************************************/
44
45/***************************************************************************
46 Internal variables
47***************************************************************************/
48
49static HtmlHelpProc g_pHtmlHelp;
50static HMODULE      g_hHelpLib;
51static DWORD        g_dwCookie;
52
53/**************************************************************************
54 External functions
55***************************************************************************/
56
57int HelpInit(void)
58{
59   g_pHtmlHelp = NULL;
60   g_hHelpLib  = NULL;
61
62   g_dwCookie = 0;
63   HelpFunction(NULL, NULL, HH_INITIALIZE, (DWORD)&g_dwCookie);
64   return 0;
65}
66
67void HelpExit(void)
68{
69   HelpFunction(NULL, NULL, HH_CLOSE_ALL, 0);
70   HelpFunction(NULL, NULL, HH_UNINITIALIZE, (DWORD)g_dwCookie);
71
72   g_dwCookie  = 0;
73   g_pHtmlHelp = NULL;
74
75   if (g_hHelpLib)
76   {
77      FreeLibrary(g_hHelpLib);
78      g_hHelpLib = NULL;
79   }
80}
81
82HWND HelpFunction(HWND hwndCaller, LPCSTR pszFile, UINT uCommand, DWORD_PTR dwData)
83{
84   if (g_pHtmlHelp == NULL)
85      Help_Load();
86
87   if (g_pHtmlHelp)
88      return g_pHtmlHelp(hwndCaller, pszFile, uCommand, dwData);
89   else
90      return NULL;
91}
92
93/***************************************************************************
94 Internal functions 
95***************************************************************************/
96
97static void Help_Load(void)
98{
99   g_hHelpLib = LoadLibrary(TEXT("hhctrl.ocx"));
100   if (g_hHelpLib)
101   {
102      FARPROC pProc = NULL;
103      pProc = GetProcAddress(g_hHelpLib, "HtmlHelpA");
104      if (pProc)
105      {
106         g_pHtmlHelp = (HtmlHelpProc)pProc;
107      }
108      else
109      {
110         FreeLibrary(g_hHelpLib);
111         g_hHelpLib = NULL;
112      }
113   }
114}
src/osd/winui/directdraw.c
r0r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11 ***************************************************************************/
12
13/***************************************************************************
14
15   directdraw.c
16
17   Direct Draw routines.
18 
19 ***************************************************************************/
20
21#define WIN32_LEAN_AND_MEAN
22
23#include <windows.h>
24
25#include <ddraw.h>
26#include <tchar.h>
27
28#include "m32util.h"
29#include "screenshot.h"
30#include "mame32.h"
31#include "dxdecode.h"
32#include "directdraw.h"
33
34/***************************************************************************
35   function prototypes
36 ***************************************************************************/
37
38static BOOL WINAPI DDEnumInfo(GUID FAR *lpGUID,
39                       LPTSTR    lpDriverDescription,
40                       LPTSTR    lpDriverName,       
41                       LPVOID   lpContext,
42                       HMONITOR   hm);
43
44static BOOL WINAPI DDEnumOldInfo(GUID FAR *lpGUID,
45                         LPTSTR      lpDriverDescription,
46                         LPTSTR      lpDriverName,     
47                         LPVOID    lpContext);
48
49static void CalculateDisplayModes(void);
50static HRESULT CALLBACK EnumDisplayModesCallback(LPDDSURFACEDESC pddsd, LPVOID Context);
51static HRESULT CALLBACK EnumDisplayModesCallback2(DDSURFACEDESC2* pddsd, LPVOID Context);
52
53/***************************************************************************
54   External variables
55 ***************************************************************************/
56
57/***************************************************************************
58   Internal structures
59 ***************************************************************************/
60
61typedef struct
62{
63   TCHAR* name;
64   GUID* lpguid;
65} display_type;
66
67typedef HRESULT (WINAPI *ddc_proc)(GUID FAR *lpGUID, LPDIRECTDRAW FAR *lplpDD,
68                           IUnknown FAR *pUnkOuter);
69
70/***************************************************************************
71   Internal variables
72 ***************************************************************************/
73
74#define MAX_DISPLAYS 100
75static int               g_nNumDisplays;
76static display_type       g_Displays[MAX_DISPLAYS];
77
78static HANDLE            g_hDLL;
79static BOOL             g_bHWStretch;
80static BOOL             g_bRefresh;
81static struct tDisplayModes g_DisplayModes;
82static IDirectDraw2*      g_pDirectDraw2;
83static IDirectDraw4*      g_pDirectDraw4;
84
85/***************************************************************************
86   External functions   
87 ***************************************************************************/
88
89/****************************************************************************
90 *      DirectDrawInitialize
91 *
92 *      Initialize the DirectDraw variables.
93 *
94 *      This entails the following functions:
95 *
96 *         DirectDrawCreate
97 *
98 ****************************************************************************/
99
100#if !defined(LPDIRECTDRAWENUMERATE)
101#if defined(UNICODE)
102
103typedef HRESULT (WINAPI* LPDIRECTDRAWENUMERATEW)(LPDDENUMCALLBACKW lpCallback, LPVOID lpContext);
104
105#define LPDIRECTDRAWENUMERATE   LPDIRECTDRAWENUMERATEW
106
107#define SDirectDrawEnumerateEx "DirectDrawEnumerateExW"
108#define SDirectDrawEnumerate   "DirectDrawEnumerateW"
109
110#else
111
112typedef HRESULT (WINAPI* LPDIRECTDRAWENUMERATEA)(LPDDENUMCALLBACKA lpCallback, LPVOID lpContext);
113
114#define LPDIRECTDRAWENUMERATE   LPDIRECTDRAWENUMERATEA
115
116#define SDirectDrawEnumerateEx "DirectDrawEnumerateExA"
117#define SDirectDrawEnumerate   "DirectDrawEnumerateA"
118
119#endif
120#endif /* LPDIRECTDRAWENUMERATE */
121
122/****************************************************************************/
123
124BOOL DirectDraw_Initialize(void)
125{
126   HRESULT  hr;
127   UINT    error_mode;
128   ddc_proc ddc;
129   DDCAPS    ddCaps;
130   DDCAPS    ddHelCaps;
131   IDirectDraw* pDirectDraw1;
132   LPDIRECTDRAWENUMERATEEX pDDEnumEx;
133
134   if (g_hDLL != NULL)
135      return TRUE;
136
137   g_nNumDisplays = 0;
138   g_hDLL         = NULL;
139   g_bHWStretch   = FALSE;
140   g_bRefresh      = FALSE;
141   g_pDirectDraw2 = NULL;
142   g_pDirectDraw4 = NULL;
143
144   /* Turn off error dialog for this call */
145   error_mode = SetErrorMode(0);
146   g_hDLL = LoadLibrary(TEXT("ddraw.dll"));
147   SetErrorMode(error_mode);
148
149   if (g_hDLL == NULL)
150      return FALSE;
151
152   ddc = (ddc_proc)GetProcAddress(g_hDLL, "DirectDrawCreate");
153   if (ddc == NULL)
154      return FALSE;
155
156   pDirectDraw1   = NULL;
157   g_pDirectDraw2 = NULL;
158   g_pDirectDraw4 = NULL;
159   hr = ddc(NULL, &pDirectDraw1, NULL);
160   if (FAILED(hr))
161   {
162      ErrorMsg("DirectDrawCreate failed: %s", DirectXDecodeError(hr));
163      return FALSE;
164   }
165
166   hr = IDirectDraw_QueryInterface(pDirectDraw1, &IID_IDirectDraw4, (void**)&g_pDirectDraw4);
167   if (FAILED(hr))
168   {
169      g_pDirectDraw4 = NULL;
170      hr = IDirectDraw_QueryInterface(pDirectDraw1, &IID_IDirectDraw2, (void**)&g_pDirectDraw2);
171      if (FAILED(hr))
172      {
173         ErrorMsg("Query Interface for DirectDraw 2 failed: %s", DirectXDecodeError(hr));
174         g_pDirectDraw2 = NULL;
175         IDirectDraw_Release(pDirectDraw1);
176         return FALSE;
177      }
178   }
179   
180   memset(&ddCaps,    0, sizeof(DDCAPS));
181   memset(&ddHelCaps, 0, sizeof(DDCAPS));
182   ddCaps.dwSize    = sizeof(DDCAPS);
183   ddHelCaps.dwSize = sizeof(DDCAPS);
184   hr = IDirectDraw_GetCaps(pDirectDraw1, &ddCaps, &ddHelCaps); /* 1 2 or 4? */
185   if (FAILED(hr))
186   {
187      ErrorMsg("Error getting DirectDraw capabilities: %s", DirectXDecodeError(hr));
188   }
189   else
190      g_bHWStretch = ((ddCaps.dwCaps & DDCAPS_BLTSTRETCH) != 0) ? TRUE : FALSE;
191
192   IDirectDraw_Release(pDirectDraw1);
193
194   /*
195      Note that you must know which version of the
196      function to retrieve (see the following text).
197      For this example, we use the ANSI version.
198    */
199   pDDEnumEx = (LPDIRECTDRAWENUMERATEEX) GetProcAddress(g_hDLL, SDirectDrawEnumerateEx);
200
201   /*
202      If the function is there, call it to enumerate all display devices
203      attached to the desktop, and any non-display DirectDraw devices.
204    */
205   if (pDDEnumEx)
206   {
207      pDDEnumEx(DDEnumInfo, NULL,
208              DDENUM_ATTACHEDSECONDARYDEVICES | DDENUM_DETACHEDSECONDARYDEVICES);
209   }
210   else
211   {
212      LPDIRECTDRAWENUMERATE lpDDEnum;
213
214      lpDDEnum = (LPDIRECTDRAWENUMERATE) GetProcAddress(g_hDLL, SDirectDrawEnumerate);
215      /*
216       * We must be running on an old version of ddraw. Therefore,
217       * by definiton, multimon isn't supported. Fall back on
218       * DirectDrawEnumerate to enumerate standard devices on a
219       * single monitor system.
220       */
221      if (lpDDEnum)
222      {
223         lpDDEnum(DDEnumOldInfo, NULL);
224      }
225      else
226      {
227         return FALSE;
228      }
229   }
230
231   return TRUE;
232}
233
234/****************************************************************************
235 *
236 *      DirectDraw_Close
237 *
238 *      Terminate our usage of DirectDraw.
239 *
240 ****************************************************************************/
241
242void DirectDraw_Close(void)
243{
244   int i;
245   
246   for (i = 0; i < g_nNumDisplays; i++)
247   {
248      free(g_Displays[i].name);
249      g_Displays[i].name = NULL;
250      if (g_Displays[i].lpguid != NULL)
251      {
252         free(g_Displays[i].lpguid);
253         g_Displays[i].lpguid = NULL;
254      }
255     
256   }
257   g_nNumDisplays = 0;
258   
259   /*
260      Destroy any lingering IDirectDraw object.
261   */
262   if (g_pDirectDraw2)
263   {
264      IDirectDraw2_Release(g_pDirectDraw2);
265      g_pDirectDraw2 = NULL;
266   }
267
268   if (g_pDirectDraw4)
269   {
270      IDirectDraw4_Release(g_pDirectDraw4);
271      g_pDirectDraw4 = NULL;
272   }
273
274   if (g_hDLL)
275   {
276      FreeLibrary(g_hDLL);
277      g_hDLL = NULL;
278   }
279}
280
281/****************************************************************************/
282/*
283   Return a list of 16, 24 and 32 bit DirectDraw modes.
284*/
285struct tDisplayModes* DirectDraw_GetDisplayModes(void)
286{
287   if (g_DisplayModes.m_nNumModes == 0)
288      CalculateDisplayModes();
289
290   return &g_DisplayModes;
291}
292
293int DirectDraw_GetNumDisplays(void)
294{
295   return g_nNumDisplays;
296}
297
298BOOL DirectDraw_HasHWStretch(void)
299{
300   return g_bHWStretch;
301}
302
303BOOL DirectDraw_HasRefresh(void)
304{
305   return g_bRefresh;
306}
307
308LPCTSTR DirectDraw_GetDisplayName(int num_display)
309{
310   return g_Displays[num_display].name;
311}
312
313/****************************************************************************/
314/* internal functions */
315/****************************************************************************/
316
317static BOOL WINAPI DDEnumInfo(GUID FAR *lpGUID,
318                       LPTSTR    lpDriverDescription,
319                       LPTSTR    lpDriverName,       
320                       LPVOID   lpContext,
321                       HMONITOR   hm)
322{
323   g_Displays[g_nNumDisplays].name = malloc((_tcslen(lpDriverDescription) + 1) * sizeof(TCHAR));
324   _tcscpy(g_Displays[g_nNumDisplays].name, lpDriverDescription);
325   
326   if (lpGUID == NULL)
327      g_Displays[g_nNumDisplays].lpguid = NULL;
328   else
329   {
330      g_Displays[g_nNumDisplays].lpguid = (LPGUID)malloc(sizeof(GUID));
331      memcpy(g_Displays[g_nNumDisplays].lpguid, lpGUID, sizeof(GUID));
332   }
333   
334   g_nNumDisplays++;
335   if (g_nNumDisplays == MAX_DISPLAYS)
336      return DDENUMRET_CANCEL;
337   else
338      return DDENUMRET_OK;
339}
340
341static BOOL WINAPI DDEnumOldInfo(GUID FAR *lpGUID,
342                         LPTSTR      lpDriverDescription,
343                         LPTSTR      lpDriverName,     
344                         LPVOID    lpContext)
345{
346   return DDEnumInfo(lpGUID, lpDriverDescription, lpDriverName, lpContext, NULL);
347}
348
349static HRESULT CALLBACK EnumDisplayModesCallback(LPDDSURFACEDESC pddsd, LPVOID Context)
350{
351   DWORD dwDepth = pddsd->ddpfPixelFormat.dwRGBBitCount;
352
353   struct tDisplayModes* pDisplayModes = (struct tDisplayModes*)Context;
354   if (dwDepth == 16
355   ||   dwDepth == 24
356   ||   dwDepth == 32)
357   {
358      pDisplayModes->m_Modes[pDisplayModes->m_nNumModes].m_dwWidth   = pddsd->dwWidth;
359      pDisplayModes->m_Modes[pDisplayModes->m_nNumModes].m_dwHeight  = pddsd->dwHeight;
360      pDisplayModes->m_Modes[pDisplayModes->m_nNumModes].m_dwBPP      = dwDepth;
361      pDisplayModes->m_Modes[pDisplayModes->m_nNumModes].m_dwRefresh = 0;
362      pDisplayModes->m_nNumModes++;
363   }
364
365   if (pDisplayModes->m_nNumModes == MAXMODES)
366      return DDENUMRET_CANCEL;
367   else
368      return DDENUMRET_OK;
369}
370
371static HRESULT CALLBACK EnumDisplayModesCallback2(DDSURFACEDESC2* pddsd2, LPVOID Context)
372{
373   struct tDisplayModes* pDisplayModes = (struct tDisplayModes*)Context;
374
375   DWORD dwDepth = pddsd2->ddpfPixelFormat.dwRGBBitCount;
376
377   if (dwDepth == 16
378   ||   dwDepth == 24
379   ||   dwDepth == 32)
380   {
381      pDisplayModes->m_Modes[pDisplayModes->m_nNumModes].m_dwWidth   = pddsd2->dwWidth;
382      pDisplayModes->m_Modes[pDisplayModes->m_nNumModes].m_dwHeight  = pddsd2->dwHeight;
383      pDisplayModes->m_Modes[pDisplayModes->m_nNumModes].m_dwBPP      = dwDepth;
384      pDisplayModes->m_Modes[pDisplayModes->m_nNumModes].m_dwRefresh = pddsd2->dwRefreshRate;
385      pDisplayModes->m_nNumModes++;
386
387      if (pddsd2->dwRefreshRate != 0)
388         g_bRefresh = TRUE;
389   }
390   
391   if (pDisplayModes->m_nNumModes == MAXMODES)
392      return DDENUMRET_CANCEL;
393   else
394      return DDENUMRET_OK;
395}
396
397static void CalculateDisplayModes(void)
398{
399   g_DisplayModes.m_nNumModes = 0;
400
401   if (g_pDirectDraw4)
402      IDirectDraw4_EnumDisplayModes(g_pDirectDraw4, DDEDM_REFRESHRATES, NULL, &g_DisplayModes, EnumDisplayModesCallback2);
403   else
404   if (g_pDirectDraw2)
405      IDirectDraw2_EnumDisplayModes(g_pDirectDraw2, 0, NULL, &g_DisplayModes, EnumDisplayModesCallback);
406}
407
408
src/osd/winui/mame32.h
r0r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11 ***************************************************************************/
12
13#ifndef MAME32_H
14#define MAME32_H
15
16#include "win32ui.h"
17
18#ifndef MESS
19#define MAME32NAME   "MAME32"
20#define MAMENAME   "MAME"
21#else
22#define MAME32NAME   "MESS"
23#define MAMENAME   "MESS"
24#endif
25
26#endif
src/osd/winui/treeview.c
r0r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11***************************************************************************/
12
13/***************************************************************************
14
15  TreeView.c
16
17  TreeView support routines - MSH 11/19/1998
18
19***************************************************************************/
20
21#define WIN32_LEAN_AND_MEAN
22#include <windows.h>
23#include <windowsx.h>
24#include <shellapi.h>
25#include <commctrl.h>
26#include <stdio.h>  /* for sprintf */
27#include <stdlib.h> /* For malloc and free */
28#include <ctype.h> /* For tolower */
29#include <string.h>
30#include <sys/stat.h>
31#include <sys/types.h>
32#ifdef _MSC_VER
33#include <direct.h>
34#endif
35#include <tchar.h>
36
37#include <io.h>
38#include <driver.h>
39#include "hash.h"
40#include "m32util.h"
41#include "bitmask.h"
42#include "screenshot.h"
43#include "mame32.h"
44#include "treeview.h"
45#include "resource.h"
46#include "m32opts.h"
47#include "properties.h"
48#include "help.h"
49#include "dialogs.h"
50#include "winutf8.h"
51#include "strconv.h"
52
53#ifdef _MSC_VER
54#define snprintf _snprintf
55#endif
56
57#define MAX_EXTRA_FOLDERS 256
58
59/***************************************************************************
60    public structures
61 ***************************************************************************/
62
63#define ICON_MAX (sizeof(treeIconNames) / sizeof(treeIconNames[0]))
64
65/* Name used for user-defined custom icons */
66/* external *.ico file to look for. */
67
68typedef struct
69{
70   int      nResourceID;
71   LPCSTR   lpName;
72} TREEICON;
73
74static TREEICON treeIconNames[] =
75{
76   { IDI_FOLDER_OPEN,         "foldopen" },
77   { IDI_FOLDER,              "folder" },
78   { IDI_FOLDER_AVAILABLE,    "foldavail" },
79   { IDI_FOLDER_MANUFACTURER, "foldmanu" },
80   { IDI_FOLDER_UNAVAILABLE,  "foldunav" },
81   { IDI_FOLDER_YEAR,         "foldyear" },
82   { IDI_FOLDER_SOURCE,       "foldsrc" },
83   { IDI_FOLDER_HORIZONTAL,   "horz" },
84   { IDI_FOLDER_VERTICAL,     "vert" },
85   { IDI_MANUFACTURER,        "manufact" },
86   { IDI_WORKING,             "working" },
87   { IDI_NONWORKING,          "nonwork" },
88   { IDI_YEAR,                "year" },
89   { IDI_SOUND,               "sound" },
90   { IDI_CPU,                 "cpu" },
91   { IDI_HARDDISK,            "harddisk" },
92   { IDI_SOURCE,              "source" }
93};
94
95/***************************************************************************
96    private variables
97 ***************************************************************************/
98
99/* this has an entry for every folder eventually in the UI, including subfolders */
100static TREEFOLDER **treeFolders = 0;
101static UINT         numFolders  = 0;        /* Number of folder in the folder array */
102static UINT         next_folder_id = MAX_FOLDERS;
103static UINT         folderArrayLength = 0;  /* Size of the folder array */
104static LPTREEFOLDER lpCurrentFolder = 0;    /* Currently selected folder */
105static UINT         nCurrentFolder = 0;     /* Current folder ID */
106static WNDPROC      g_lpTreeWndProc = 0;    /* for subclassing the TreeView */
107static HIMAGELIST   hTreeSmall = 0;         /* TreeView Image list of icons */
108
109/* this only has an entry for each TOP LEVEL extra folder + SubFolders*/
110LPEXFOLDERDATA      ExtraFolderData[MAX_EXTRA_FOLDERS * MAX_EXTRA_SUBFOLDERS];
111int                 numExtraFolders = 0;
112static int          numExtraIcons = 0;
113static char         *ExtraFolderIcons[MAX_EXTRA_FOLDERS];
114
115// built in folders and filters
116static LPFOLDERDATA  g_lpFolderData;
117static LPFILTER_ITEM g_lpFilterList;   
118
119/***************************************************************************
120    private function prototypes
121 ***************************************************************************/
122
123extern BOOL         InitFolders(void);
124static BOOL         CreateTreeIcons(void);
125static void         TreeCtrlOnPaint(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
126static const char*   ParseManufacturer(const char *s, int *pParsedChars );
127static const char*   TrimManufacturer(const char *s);
128static void         CreateAllChildFolders(void);
129static BOOL         AddFolder(LPTREEFOLDER lpFolder);
130static LPTREEFOLDER NewFolder(const char *lpTitle,
131                              UINT nFolderId, int nParent, UINT nIconId,
132                              DWORD dwFlags);
133static void         DeleteFolder(LPTREEFOLDER lpFolder);
134
135static LRESULT CALLBACK TreeWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
136
137static int InitExtraFolders(void);
138static void FreeExtraFolders(void);
139static void SetExtraIcons(char *name, int *id);
140static BOOL TryAddExtraFolderAndChildren(int parent_index);
141
142static BOOL TrySaveExtraFolder(LPTREEFOLDER lpFolder);
143
144/***************************************************************************
145    public functions
146 ***************************************************************************/
147
148/**************************************************************************
149 *      ci_strncmp - case insensitive character array compare
150 *
151 *      Returns zero if the first n characters of s1 and s2 are equal,
152 *      ignoring case.
153 *      stolen from datafile.c
154 **************************************************************************/
155static int ci_strncmp (const char *s1, const char *s2, int n)
156{
157        int c1, c2;
158
159        while (n)
160        {
161                if ((c1 = tolower (*s1)) != (c2 = tolower (*s2)))
162                        return (c1 - c2);
163                else if (!c1)
164                        break;
165                --n;
166
167                s1++;
168                s2++;
169        }
170        return 0;
171}
172
173
174
175/* De-allocate all folder memory */
176void FreeFolders(void)
177{
178   int i = 0;
179
180   if (treeFolders != NULL)
181   {
182      if (numExtraFolders)
183      {
184         FreeExtraFolders();
185         numFolders -= numExtraFolders;
186      }
187
188      for (i = numFolders - 1; i >= 0; i--)
189      {
190         DeleteFolder(treeFolders[i]);
191         treeFolders[i] = NULL;
192         numFolders--;
193      }
194      free(treeFolders);
195      treeFolders = NULL;
196   }
197   numFolders = 0;
198}
199
200/* Reset folder filters */
201void ResetFilters(void)
202{
203   int i = 0;
204
205   if (treeFolders != 0)
206   {
207      for (i = 0; i < (int)numFolders; i++)
208      {
209         treeFolders[i]->m_dwFlags &= ~F_MASK;
210      }
211   }
212}
213
214void InitTree(LPFOLDERDATA lpFolderData, LPFILTER_ITEM lpFilterList)
215{
216   g_lpFolderData = lpFolderData;
217   g_lpFilterList = lpFilterList;
218
219   InitFolders();
220
221   /* this will subclass the treeview (where WM_DRAWITEM gets sent for
222      the header control) */
223   g_lpTreeWndProc = (WNDPROC)(LONG)(int)GetWindowLong(GetTreeView(), GWL_WNDPROC);
224   SetWindowLong(GetTreeView(), GWL_WNDPROC, (LONG)TreeWndProc);
225}
226
227void DestroyTree(HWND hWnd)
228{
229    if ( hTreeSmall )
230    {
231        ImageList_Destroy( hTreeSmall );
232        hTreeSmall = NULL;
233    }
234}
235
236void SetCurrentFolder(LPTREEFOLDER lpFolder)
237{
238   lpCurrentFolder = (lpFolder == 0) ? treeFolders[0] : lpFolder;
239   nCurrentFolder = (lpCurrentFolder) ? lpCurrentFolder->m_nFolderId : 0;
240}
241
242LPTREEFOLDER GetCurrentFolder(void)
243{
244   return lpCurrentFolder;
245}
246
247UINT GetCurrentFolderID(void)
248{
249   return nCurrentFolder;
250}
251
252int GetNumFolders(void)
253{
254   return numFolders;
255}
256
257LPTREEFOLDER GetFolder(UINT nFolder)
258{
259   return (nFolder < numFolders) ? treeFolders[nFolder] : NULL;
260}
261
262LPTREEFOLDER GetFolderByID(UINT nID)
263{
264   UINT i;
265
266   for (i = 0; i < numFolders; i++)
267   {
268      if (treeFolders[i]->m_nFolderId == nID)
269      {
270         return treeFolders[i];
271      }
272   }
273
274   return (LPTREEFOLDER)0;
275}
276
277void AddGame(LPTREEFOLDER lpFolder, UINT nGame)
278{
279   if (lpFolder)
280      SetBit(lpFolder->m_lpGameBits, nGame);
281}
282
283void RemoveGame(LPTREEFOLDER lpFolder, UINT nGame)
284{
285   ClearBit(lpFolder->m_lpGameBits, nGame);
286}
287
288int FindGame(LPTREEFOLDER lpFolder, int nGame)
289{
290   return FindBit(lpFolder->m_lpGameBits, nGame, TRUE);
291}
292
293// Called to re-associate games with folders
294void ResetWhichGamesInFolders(void)
295{
296   UINT   i, jj, k;
297   BOOL b;
298   int nGames = driver_list_get_count(drivers);
299
300   for (i = 0; i < numFolders; i++)
301   {
302      LPTREEFOLDER lpFolder = treeFolders[i];
303
304      // setup the games in our built-in folders
305      for (k = 0; g_lpFolderData[k].m_lpTitle; k++)
306      {
307         if (lpFolder->m_nFolderId == g_lpFolderData[k].m_nFolderId)
308         {
309            if (g_lpFolderData[k].m_pfnQuery || g_lpFolderData[k].m_bExpectedResult)
310            {
311               SetAllBits(lpFolder->m_lpGameBits, FALSE);
312               for (jj = 0; jj < nGames; jj++)
313               {
314                  // invoke the query function
315                  b = g_lpFolderData[k].m_pfnQuery ? g_lpFolderData[k].m_pfnQuery(jj) : TRUE;
316
317                  // if we expect FALSE, flip the result
318                  if (!g_lpFolderData[k].m_bExpectedResult)
319                     b = !b;
320
321                  // if we like what we hear, add the game
322                  if (b)
323                     AddGame(lpFolder, jj);
324               }
325            }
326            break;
327         }
328      }
329   }
330}
331
332
333/* Used to build the GameList */
334BOOL GameFiltered(int nGame, DWORD dwMask)
335{
336   int i;
337   LPTREEFOLDER lpFolder = GetCurrentFolder();
338   LPTREEFOLDER lpParent = NULL;
339
340   //Filter out the Bioses on all Folders, except for the Bios Folder
341   if( lpFolder->m_nFolderId != FOLDER_BIOS )
342   {
343      if( !( (drivers[nGame]->flags & GAME_IS_BIOS_ROOT ) == 0) )
344         return TRUE;
345   }
346    // Filter games--return TRUE if the game should be HIDDEN in this view
347   if( GetFilterInherit() )
348   {
349      if( lpFolder )
350      {
351         lpParent = GetFolder( lpFolder->m_nParent );
352         if( lpParent )
353         {
354            /* Check the Parent Filters and inherit them on child,
355             * The inherited filters don't display on the custom Filter Dialog for the Child folder
356             * No need to promote all games to parent folder, works as is */
357            dwMask |= lpParent->m_dwFlags;
358         }
359      }
360   }
361
362   if (strlen(GetSearchText()) && _stricmp(GetSearchText(), SEARCH_PROMPT))
363   {
364      if (MyStrStrI(drivers[nGame]->description,GetSearchText()) == NULL &&
365         MyStrStrI(drivers[nGame]->name,GetSearchText()) == NULL)
366         return TRUE;
367   }
368   /*Filter Text is already global*/
369   if (MyStrStrI(drivers[nGame]->description,GetFilterText()) == NULL &&
370      MyStrStrI(drivers[nGame]->name,GetFilterText()) == NULL &&
371      MyStrStrI(drivers[nGame]->source_file,GetFilterText()) == NULL &&
372      MyStrStrI(drivers[nGame]->manufacturer,GetFilterText()) == NULL)
373   {
374      return TRUE;
375   }
376   // Are there filters set on this folder?
377   if ((dwMask & F_MASK) == 0)
378      return FALSE;
379
380   // Filter out clones?
381   if (dwMask & F_CLONES && DriverIsClone(nGame))
382      return TRUE;
383
384   for (i = 0; g_lpFilterList[i].m_dwFilterType; i++)
385   {
386      if (dwMask & g_lpFilterList[i].m_dwFilterType)
387      {
388         if (g_lpFilterList[i].m_pfnQuery(nGame) == g_lpFilterList[i].m_bExpectedResult)
389            return TRUE;
390      }
391   }
392   return FALSE;
393}
394
395/* Get the parent of game in this view */
396BOOL GetParentFound(int nGame)
397{
398   int nParentIndex = -1;
399   LPTREEFOLDER lpFolder = GetCurrentFolder();
400
401   if( lpFolder )
402   {
403      nParentIndex = GetParentIndex(drivers[nGame]);
404
405      /* return FALSE if no parent is there in this view */
406      if( nParentIndex == -1)
407         return FALSE;
408
409      /* return FALSE if the folder should be HIDDEN in this view */
410      if (TestBit(lpFolder->m_lpGameBits, nParentIndex) == 0)
411         return FALSE;
412
413      /* return FALSE if the game should be HIDDEN in this view */
414      if (GameFiltered(nParentIndex, lpFolder->m_dwFlags))
415         return FALSE;
416
417      return TRUE;
418   }
419
420   return FALSE;
421}
422
423LPFILTER_ITEM GetFilterList(void)
424{
425   return g_lpFilterList;
426}
427
428/***************************************************************************
429   private functions
430 ***************************************************************************/
431
432void CreateSourceFolders(int parent_index)
433{
434   int i,jj, k=0;
435   int nGames = driver_list_get_count(drivers);
436   int start_folder = numFolders;
437   LPTREEFOLDER lpFolder = treeFolders[parent_index];
438
439   // no games in top level folder
440   SetAllBits(lpFolder->m_lpGameBits,FALSE);
441   for (jj = 0; jj < nGames; jj++)
442   {
443      const char *s = GetDriverFilename(jj);
444                         
445      if (s == NULL || s[0] == '\0')
446         continue;
447
448      // look for an existant source treefolder for this game
449      // (likely to be the previous one, so start at the end)
450      for (i=numFolders-1;i>=start_folder;i--)
451      {
452         if (strcmp(treeFolders[i]->m_lpTitle,s) == 0)
453         {
454            AddGame(treeFolders[i],jj);
455            break;
456         }
457      }
458      if (i == start_folder-1)
459      {
460         // nope, it's a source file we haven't seen before, make it.
461         LPTREEFOLDER lpTemp;
462         lpTemp = NewFolder(s, next_folder_id, parent_index, IDI_SOURCE,
463                           GetFolderFlags(numFolders));
464         ExtraFolderData[next_folder_id] = malloc(sizeof(EXFOLDERDATA) );
465         memset(ExtraFolderData[next_folder_id], 0, sizeof(EXFOLDERDATA));
466
467         ExtraFolderData[next_folder_id]->m_nFolderId = next_folder_id;
468         ExtraFolderData[next_folder_id]->m_nIconId = IDI_SOURCE;
469         ExtraFolderData[next_folder_id]->m_nParent = lpFolder->m_nFolderId;
470         ExtraFolderData[next_folder_id]->m_nSubIconId = -1;
471         strcpy( ExtraFolderData[next_folder_id]->m_szTitle, s );
472         ExtraFolderData[next_folder_id]->m_dwFlags = 0;
473
474         // Increment next_folder_id here in case code is added above
475         next_folder_id++;
476
477         AddFolder(lpTemp);
478         AddGame(lpTemp,jj);
479      }
480   }
481   SetNumOptionFolders(k-1);
482}
483
484void CreateManufacturerFolders(int parent_index)
485{
486   int i,jj;
487   int nGames = driver_list_get_count(drivers);
488   int start_folder = numFolders;
489   LPTREEFOLDER lpFolder = treeFolders[parent_index];
490    LPTREEFOLDER lpTemp;
491
492   // no games in top level folder
493   SetAllBits(lpFolder->m_lpGameBits,FALSE);
494
495   for (jj = 0; jj < nGames; jj++)
496   {
497      const char *manufacturer = drivers[jj]->manufacturer;
498      int iChars = 0;
499      while( manufacturer != NULL && manufacturer[0] != '\0' )
500      {
501         const char *s = ParseManufacturer(manufacturer, &iChars);
502         manufacturer += iChars;
503         //shift to next start char
504         if( s != NULL && strlen(s) > 0 )
505          {
506            const char *t = TrimManufacturer(s);
507            for (i=numFolders-1;i>=start_folder;i--)
508            {
509               //RS Made it case insensitive
510               if (ci_strncmp(treeFolders[i]->m_lpTitle,t,20) == 0 )
511               {
512                  AddGame(treeFolders[i],jj);
513                  break;
514               }
515            }
516            if (i == start_folder-1)
517            {
518               // nope, it's a manufacturer we haven't seen before, make it.
519               lpTemp = NewFolder(t, next_folder_id, parent_index, IDI_MANUFACTURER,
520                              GetFolderFlags(numFolders));
521               ExtraFolderData[next_folder_id] = malloc(sizeof(EXFOLDERDATA) );
522               memset(ExtraFolderData[next_folder_id], 0, sizeof(EXFOLDERDATA));
523
524               ExtraFolderData[next_folder_id]->m_nFolderId = next_folder_id;
525               ExtraFolderData[next_folder_id]->m_nIconId = IDI_MANUFACTURER;
526               ExtraFolderData[next_folder_id]->m_nParent = lpFolder->m_nFolderId;
527               ExtraFolderData[next_folder_id]->m_nSubIconId = -1;
528               strcpy( ExtraFolderData[next_folder_id]->m_szTitle, s );
529               ExtraFolderData[next_folder_id++]->m_dwFlags = 0;
530               AddFolder(lpTemp);
531               AddGame(lpTemp,jj);
532            }
533         }
534      }
535   }
536}
537
538/* Make a reasonable name out of the one found in the driver array */
539static const char* ParseManufacturer(const char *s, int *pParsedChars )
540{
541   static char tmp[256];
542    char* ptmp;
543   char *t;
544   *pParsedChars= 0;
545
546   if ( *s == '?' || *s == '<' || s[3] == '?' )
547    {
548      (*pParsedChars) = strlen(s);
549      return "<unknown>";
550    }
551
552    ptmp = tmp;
553   /*if first char is a space, skip it*/
554   if( *s == ' ' )
555   {
556      (*pParsedChars)++;
557        ++s;
558   }
559   while( *s )
560   {
561        /* combinations where to end string */
562     
563      if (
564            ( (*s == ' ') && ( s[1] == '(' || s[1] == '/' || s[1] == '+' ) ) ||
565            ( *s == ']' ) ||
566            ( *s == '/' ) ||
567            ( *s == '?' )
568            )
569        {
570      (*pParsedChars)++;
571         if( s[1] == '/' || s[1] == '+' )
572            (*pParsedChars)++;
573         break;
574        }
575      if( s[0] == ' ' && s[1] == '?' )
576      {
577         (*pParsedChars) += 2;
578         s+=2;
579      }
580
581        /* skip over opening braces*/
582
583      if ( *s != '[' )
584        {
585         *ptmp++ = *s;
586       }
587      (*pParsedChars)++;
588      /*for "distributed by" and "supported by" handling*/
589      if( ( (s[1] == ',') && (s[2] == ' ') && ( (s[3] == 's') || (s[3] == 'd') ) ) )
590      {
591         //*ptmp++ = *s;
592         ++s;
593         break;
594   }
595        ++s;
596   }
597   *ptmp = '\0';
598   t = tmp;
599   if( tmp[0] == '(' || tmp[strlen(tmp)-1] == ')' || tmp[0] == ',')
600   {
601      ptmp = strchr( tmp,'(' );
602      if ( ptmp == NULL )
603      {
604         ptmp = strchr( tmp,',' );
605         if( ptmp != NULL)
606         {
607            //parse the new "supported by" and "distributed by"
608            ptmp++;
609
610            if (ci_strncmp(ptmp, " supported by", 13) == 0)
611            {
612               ptmp += 13;
613            }
614            else if (ci_strncmp(ptmp, " distributed by", 15) == 0)
615            {
616               ptmp += 15;
617            }
618            else
619            {
620               return NULL;
621            }
622         }
623         else
624         {
625            ptmp = tmp;
626            if ( ptmp == NULL )
627            {
628               return NULL;
629            }
630         }
631      }
632      if( tmp[0] == '(' || tmp[0] == ',')
633      {
634         ptmp++;
635      }
636      if (ci_strncmp(ptmp, "licensed from ", 14) == 0)
637      {
638         ptmp += 14;
639      }
640      // for the licenced from case
641      if (ci_strncmp(ptmp, "licenced from ", 14) == 0)
642      {
643         ptmp += 14;
644      }
645     
646      while ( (*ptmp != ')' ) && (*ptmp != '/' ) && *ptmp != '\0')
647      {
648         if (*ptmp == ' ' && ci_strncmp(ptmp, " license", 8) == 0)
649         {
650            break;
651         }
652         if (*ptmp == ' ' && ci_strncmp(ptmp, " licence", 8) == 0)
653         {
654            break;
655         }
656         *t++ = *ptmp++;
657      }
658     
659      *t = '\0';
660   }
661
662   *ptmp = '\0';
663   return tmp;
664}
665
666/* Analyze Manufacturer Names for typical patterns, that don't distinguish between companies (e.g. Co., Ltd., Inc., etc. */
667static const char* TrimManufacturer(const char *s)
668{
669   //Also remove Country specific suffixes (e.g. Japan, Italy, America, USA, ...)
670   int i=0;
671   char strTemp[256];
672   static char strTemp2[256];
673   int j=0;
674   int k=0;
675   int l = 0;
676   memset(strTemp, '\0', 256 );
677   memset(strTemp2, '\0', 256 );
678   //start analyzing from the back, as these are usually suffixes
679   for(i=strlen(s)-1; i>=0;i-- )
680   {
681     
682      l = strlen(strTemp);
683      for(k=l;k>=0; k--)
684         strTemp[k+1] = strTemp[k];
685      strTemp[0] = s[i];
686      strTemp[++l] = '\0';
687      switch (l)
688      {
689         case 2:
690            if( ci_strncmp(strTemp, "co", 2) == 0 )
691            {
692               j=l;
693               while( s[strlen(s)-j-1] == ' ' || s[strlen(s)-j-1] == ',' )
694               {
695                  j++;
696               }
697               if( j!=l)
698               {
699                  memset(strTemp2, '\0', 256 );
700                  strncpy(strTemp2, s, strlen(s)-j );   
701               }
702            }
703            break;
704         case 3:
705            if( ci_strncmp(strTemp, "co.", 3) == 0 || ci_strncmp(strTemp, "ltd", 3) == 0 || ci_strncmp(strTemp, "inc", 3) == 0  || ci_strncmp(strTemp, "SRL", 3) == 0 || ci_strncmp(strTemp, "USA", 3) == 0)
706            {
707               j=l;
708               while( s[strlen(s)-j-1] == ' ' || s[strlen(s)-j-1] == ',' )
709               {
710                  j++;
711               }
712               if( j!=l)
713               {
714                  memset(strTemp2, '\0', 256 );
715                  strncpy(strTemp2, s, strlen(s)-j );   
716               }
717            }
718            break;
719         case 4:
720            if( ci_strncmp(strTemp, "inc.", 4) == 0 || ci_strncmp(strTemp, "ltd.", 4) == 0 || ci_strncmp(strTemp, "corp", 4) == 0 || ci_strncmp(strTemp, "game", 4) == 0)
721            {
722               j=l;
723               while( s[strlen(s)-j-1] == ' ' || s[strlen(s)-j-1] == ',' )
724               {
725                  j++;
726               }
727               if( j!=l)
728               {
729                  memset(strTemp2, '\0', 256 );
730                  strncpy(strTemp2, s, strlen(s)-j );   
731               }
732            }
733            break;
734         case 5:
735            if( ci_strncmp(strTemp, "corp.", 5) == 0 || ci_strncmp(strTemp, "Games", 5) == 0 || ci_strncmp(strTemp, "Italy", 5) == 0 || ci_strncmp(strTemp, "Japan", 5) == 0)
736            {
737               j=l;
738               while( s[strlen(s)-j-1] == ' ' || s[strlen(s)-j-1] == ',' )
739               {
740                  j++;
741               }
742               if( j!=l)
743               {
744                  memset(strTemp2, '\0', 256 );
745                  strncpy(strTemp2, s, strlen(s)-j );   
746               }
747            }
748            break;
749         case 6:
750            if( ci_strncmp(strTemp, "co-ltd", 6) == 0 || ci_strncmp(strTemp, "S.R.L.", 6) == 0)
751            {
752               j=l;
753               while( s[strlen(s)-j-1] == ' ' || s[strlen(s)-j-1] == ',' )
754               {
755                  j++;
756               }
757               if( j!=l)
758               {
759                  memset(strTemp2, '\0', 256 );
760                  strncpy(strTemp2, s, strlen(s)-j );   
761               }
762            }
763            break;
764         case 7:
765            if( ci_strncmp(strTemp, "co. ltd", 7) == 0  || ci_strncmp(strTemp, "America", 7) == 0)
766            {
767               j=l;
768               while( s[strlen(s)-j-1] == ' ' || s[strlen(s)-j-1] == ',' )
769               {
770                  j++;
771               }
772               if( j!=l)
773               {
774                  memset(strTemp2, '\0', 256 );
775                  strncpy(strTemp2, s, strlen(s)-j );   
776               }
777            }
778            break;
779         case 8:
780            if( ci_strncmp(strTemp, "co. ltd.", 8) == 0  )
781            {
782               j=l;
783               while( s[strlen(s)-j-1] == ' ' || s[strlen(s)-j-1] == ',' )
784               {
785                  j++;
786               }
787               if( j!=l)
788               {
789                  memset(strTemp2, '\0', 256 );
790                  strncpy(strTemp2, s, strlen(s)-j );   
791               }
792            }
793            break;
794         case 9:
795            if( ci_strncmp(strTemp, "co., ltd.", 9) == 0 || ci_strncmp(strTemp, "gmbh & co", 9) == 0 )
796            {
797               j=l;
798               while( s[strlen(s)-j-1] == ' ' || s[strlen(s)-j-1] == ',' )
799               {
800                  j++;
801               }
802               if( j!=l)
803               {
804                  memset(strTemp2, '\0', 256 );
805                  strncpy(strTemp2, s, strlen(s)-j );   
806               }
807            }
808            break;
809         case 10:
810            if( ci_strncmp(strTemp, "corp, ltd.", 10) == 0  || ci_strncmp(strTemp, "industries", 10) == 0  || ci_strncmp(strTemp, "of America", 10) == 0)
811            {
812               j=l;
813               while( s[strlen(s)-j-1] == ' ' || s[strlen(s)-j-1] == ',' )
814               {
815                  j++;
816               }
817               if( j!=l)
818               {
819                  memset(strTemp2, '\0', 256 );
820                  strncpy(strTemp2, s, strlen(s)-j );   
821               }
822            }
823            break;
824         case 11:
825            if( ci_strncmp(strTemp, "corporation", 11) == 0 || ci_strncmp(strTemp, "enterprises", 11) == 0 )
826            {
827               j=l;
828               while( s[strlen(s)-j-1] == ' ' || s[strlen(s)-j-1] == ',' )
829               {
830                  j++;
831               }
832               if( j!=l)
833               {
834                  memset(strTemp2, '\0', 256 );
835                  strncpy(strTemp2, s, strlen(s)-j );   
836               }
837            }
838            break;
839         case 16:
840            if( ci_strncmp(strTemp, "industries japan", 16) == 0 )
841            {
842               j=l;
843               while( s[strlen(s)-j-1] == ' ' || s[strlen(s)-j-1] == ',' )
844               {
845                  j++;
846               }
847               if( j!=l)
848               {
849                  memset(strTemp2, '\0', 256 );
850                  strncpy(strTemp2, s, strlen(s)-j );   
851               }
852            }
853            break;
854         default:
855            break;
856      }
857   }
858   if( strlen(strTemp2) == 0 )
859      return s;
860   return strTemp2;
861}
862
863
864
865void CreateCPUFolders(int parent_index)
866{
867   int i,jj;
868   int nGames = driver_list_get_count(drivers);
869   int nFolder = numFolders;
870   LPTREEFOLDER lpFolder = treeFolders[parent_index];
871   LPTREEFOLDER map[CPU_COUNT];
872
873   ZeroMemory(map, sizeof(map));
874   cpuintrf_init(NULL);
875
876   // no games in top level folder
877   SetAllBits(lpFolder->m_lpGameBits,FALSE);
878
879   for (i=1;i<CPU_COUNT;i++)
880   {
881      LPTREEFOLDER lpTemp;
882
883      for (jj = 1; jj < i; jj++)
884         if (!strcmp(cputype_name(i), cputype_name(jj)))
885            break;
886
887      if (i != jj)
888      {
889         map[i] = map[jj];
890         continue;
891      }
892      if( strlen( cputype_name(i) ) <=0 )
893         continue;
894      lpTemp = NewFolder(cputype_name(i), next_folder_id, parent_index, IDI_CPU,
895                      GetFolderFlags(numFolders));
896      ExtraFolderData[next_folder_id] = malloc(sizeof(EXFOLDERDATA) );
897      memset(ExtraFolderData[next_folder_id], 0, sizeof(EXFOLDERDATA));
898
899      ExtraFolderData[next_folder_id]->m_nFolderId = next_folder_id;
900      ExtraFolderData[next_folder_id]->m_nIconId = IDI_CPU;
901      ExtraFolderData[next_folder_id]->m_nParent = lpFolder->m_nFolderId;
902      ExtraFolderData[next_folder_id]->m_nSubIconId = -1;
903      strcpy( ExtraFolderData[next_folder_id]->m_szTitle, cputype_name(i) );
904      ExtraFolderData[next_folder_id++]->m_dwFlags = 0;
905      AddFolder(lpTemp);
906      map[i] = treeFolders[nFolder++];
907   }
908
909   for (jj = 0; jj < nGames; jj++)
910   {
911      int n;
912      machine_config drv;
913      expand_machine_driver(drivers[jj]->drv,&drv);
914      for (n = 0; n < MAX_CPU; n++)
915         if (drv.cpu[n].cpu_type != CPU_DUMMY)
916         {
917            // cpu type #'s are one-based
918            AddGame(map[drv.cpu[n].cpu_type],jj);
919         }
920   }
921}
922
923void CreateSoundFolders(int parent_index)
924{
925   int i,jj;
926   int nGames = driver_list_get_count(drivers);
927   int nFolder = numFolders;
928   LPTREEFOLDER lpFolder = treeFolders[parent_index];
929   LPTREEFOLDER map[SOUND_COUNT];
930
931   sndintrf_init(NULL);
932
933   // no games in top level folder
934   SetAllBits(lpFolder->m_lpGameBits,FALSE);
935
936   for (i = 1 ; i < MAX_SOUND ; i++)
937   {
938      LPTREEFOLDER lpTemp;
939      // Init to NULL here in case it doesn't get assigned below.     
940      map[i] = NULL;
941      // empty fields get filled in with SOUND_DUMMY, so check for this and
942      // don't add it
943      if (strcmp(sndtype_name(SOUND_DUMMY),sndtype_name(i)) == 0)
944         continue;
945
946      //dprintf("%i %s\n",i,sndtype_name(i));
947      lpTemp = NewFolder(sndtype_name(i), next_folder_id, parent_index, IDI_SOUND,
948                      GetFolderFlags(numFolders));
949      ExtraFolderData[next_folder_id] = malloc(sizeof(EXFOLDERDATA) );
950      memset(ExtraFolderData[next_folder_id], 0, sizeof(EXFOLDERDATA));
951
952      ExtraFolderData[next_folder_id]->m_nFolderId = next_folder_id;
953      ExtraFolderData[next_folder_id]->m_nIconId = IDI_SOUND;
954      ExtraFolderData[next_folder_id]->m_nParent = lpFolder->m_nFolderId;
955      ExtraFolderData[next_folder_id]->m_nSubIconId = -1;
956      strcpy( ExtraFolderData[next_folder_id]->m_szTitle, sndtype_name(i) );
957      ExtraFolderData[next_folder_id++]->m_dwFlags = 0;
958      AddFolder(lpTemp);
959      map[i] = treeFolders[nFolder++];
960   }
961   for (jj = 0; jj < nGames; jj++)
962   {
963      int n;
964      machine_config drv;
965      expand_machine_driver(drivers[jj]->drv,&drv);
966      // Additional range and null checking.
967      for (n = 0; n < MAX_SOUND ; n++)
968         if (drv.sound[n].sound_type > SOUND_DUMMY &&
969            drv.sound[n].sound_type < MAX_SOUND)
970         {
971            if (map[drv.sound[n].sound_type] != NULL) {
972               // sound type #'s are one-based, though that doesn't affect us here
973               AddGame(map[drv.sound[n].sound_type],jj);
974            }
975         }
976   }
977
978}
979
980void CreateDeficiencyFolders(int parent_index)
981{
982   int jj;
983   int nGames = driver_list_get_count(drivers);
984   LPTREEFOLDER lpFolder = treeFolders[parent_index];
985
986   // create our two subfolders
987   LPTREEFOLDER lpProt, lpWrongCol, lpImpCol, lpImpGraph, lpMissSnd, lpImpSnd, lpFlip;
988   lpProt = NewFolder("Unemulated Protection", next_folder_id, parent_index, IDI_FOLDER,
989                   GetFolderFlags(numFolders));
990   ExtraFolderData[next_folder_id] = malloc(sizeof(EXFOLDERDATA) );
991   memset(ExtraFolderData[next_folder_id], 0, sizeof(EXFOLDERDATA));
992
993   ExtraFolderData[next_folder_id]->m_nFolderId = next_folder_id;
994   ExtraFolderData[next_folder_id]->m_nIconId = IDI_FOLDER;
995   ExtraFolderData[next_folder_id]->m_nParent = lpFolder->m_nFolderId;
996   ExtraFolderData[next_folder_id]->m_nSubIconId = -1;
997   strcpy( ExtraFolderData[next_folder_id]->m_szTitle, "Unemulated Protection" );
998   ExtraFolderData[next_folder_id++]->m_dwFlags = 0;
999   AddFolder(lpProt);
1000   lpWrongCol = NewFolder("Wrong Colors", next_folder_id, parent_index, IDI_FOLDER,
1001                   GetFolderFlags(numFolders));
1002   ExtraFolderData[next_folder_id] = malloc(sizeof(EXFOLDERDATA) );
1003   memset(ExtraFolderData[next_folder_id], 0, sizeof(EXFOLDERDATA));
1004
1005   ExtraFolderData[next_folder_id]->m_nFolderId = next_folder_id;
1006   ExtraFolderData[next_folder_id]->m_nIconId = IDI_FOLDER;
1007   ExtraFolderData[next_folder_id]->m_nParent = lpFolder->m_nFolderId;
1008   ExtraFolderData[next_folder_id]->m_nSubIconId = -1;
1009   strcpy( ExtraFolderData[next_folder_id]->m_szTitle, "Wrong Colors" );
1010   ExtraFolderData[next_folder_id++]->m_dwFlags = 0;
1011   AddFolder(lpWrongCol);
1012
1013   lpImpCol = NewFolder("Imperfect Colors", next_folder_id, parent_index, IDI_FOLDER,
1014                   GetFolderFlags(numFolders));
1015   ExtraFolderData[next_folder_id] = malloc(sizeof(EXFOLDERDATA) );
1016   memset(ExtraFolderData[next_folder_id], 0, sizeof(EXFOLDERDATA));
1017
1018   ExtraFolderData[next_folder_id]->m_nFolderId = next_folder_id;
1019   ExtraFolderData[next_folder_id]->m_nIconId = IDI_FOLDER;
1020   ExtraFolderData[next_folder_id]->m_nParent = lpFolder->m_nFolderId;
1021   ExtraFolderData[next_folder_id]->m_nSubIconId = -1;
1022   strcpy( ExtraFolderData[next_folder_id]->m_szTitle, "Imperfect Colors" );
1023   ExtraFolderData[next_folder_id++]->m_dwFlags = 0;
1024   AddFolder(lpImpCol);
1025
1026   lpImpGraph = NewFolder("Imperfect Graphics", next_folder_id, parent_index, IDI_FOLDER,
1027                   GetFolderFlags(numFolders));
1028   ExtraFolderData[next_folder_id] = malloc(sizeof(EXFOLDERDATA) );
1029   memset(ExtraFolderData[next_folder_id], 0, sizeof(EXFOLDERDATA));
1030
1031   ExtraFolderData[next_folder_id]->m_nFolderId = next_folder_id;
1032   ExtraFolderData[next_folder_id]->m_nIconId = IDI_FOLDER;
1033   ExtraFolderData[next_folder_id]->m_nParent = lpFolder->m_nFolderId;
1034   ExtraFolderData[next_folder_id]->m_nSubIconId = -1;
1035   strcpy( ExtraFolderData[next_folder_id]->m_szTitle, "Imperfect Graphics" );
1036   ExtraFolderData[next_folder_id++]->m_dwFlags = 0;
1037   AddFolder(lpImpGraph);
1038
1039   lpMissSnd = NewFolder("Missing Sound", next_folder_id, parent_index, IDI_FOLDER,
1040                   GetFolderFlags(numFolders));
1041   ExtraFolderData[next_folder_id] = malloc(sizeof(EXFOLDERDATA) );
1042   memset(ExtraFolderData[next_folder_id], 0, sizeof(EXFOLDERDATA));
1043
1044   ExtraFolderData[next_folder_id]->m_nFolderId = next_folder_id;
1045   ExtraFolderData[next_folder_id]->m_nIconId = IDI_FOLDER;
1046   ExtraFolderData[next_folder_id]->m_nParent = lpFolder->m_nFolderId;
1047   ExtraFolderData[next_folder_id]->m_nSubIconId = -1;
1048   strcpy( ExtraFolderData[next_folder_id]->m_szTitle, "Missing Sound" );
1049   ExtraFolderData[next_folder_id++]->m_dwFlags = 0;
1050   AddFolder(lpMissSnd);
1051
1052   lpImpSnd = NewFolder("Imperfect Sound", next_folder_id, parent_index, IDI_FOLDER,
1053                   GetFolderFlags(numFolders));
1054   ExtraFolderData[next_folder_id] = malloc(sizeof(EXFOLDERDATA) );
1055   memset(ExtraFolderData[next_folder_id], 0, sizeof(EXFOLDERDATA));
1056
1057   ExtraFolderData[next_folder_id]->m_nFolderId = next_folder_id;
1058   ExtraFolderData[next_folder_id]->m_nIconId = IDI_FOLDER;
1059   ExtraFolderData[next_folder_id]->m_nParent = lpFolder->m_nFolderId;
1060   ExtraFolderData[next_folder_id]->m_nSubIconId = -1;
1061   strcpy( ExtraFolderData[next_folder_id]->m_szTitle, "Imperfect Sound" );
1062   ExtraFolderData[next_folder_id++]->m_dwFlags = 0;
1063   AddFolder(lpImpSnd);
1064
1065   lpFlip = NewFolder("No Cocktail", next_folder_id, parent_index, IDI_FOLDER,
1066                   GetFolderFlags(numFolders));
1067   ExtraFolderData[next_folder_id] = malloc(sizeof(EXFOLDERDATA) );
1068   memset(ExtraFolderData[next_folder_id], 0, sizeof(EXFOLDERDATA));
1069
1070   ExtraFolderData[next_folder_id]->m_nFolderId = next_folder_id;
1071   ExtraFolderData[next_folder_id]->m_nIconId = IDI_FOLDER;
1072   ExtraFolderData[next_folder_id]->m_nParent = lpFolder->m_nFolderId;
1073   ExtraFolderData[next_folder_id]->m_nSubIconId = -1;
1074   strcpy( ExtraFolderData[next_folder_id]->m_szTitle, "No Cocktail" );
1075   ExtraFolderData[next_folder_id++]->m_dwFlags = 0;
1076   AddFolder(lpFlip);
1077
1078   // no games in top level folder
1079   SetAllBits(lpFolder->m_lpGameBits,FALSE);
1080
1081   for (jj = 0; jj < nGames; jj++)
1082   {
1083      if (drivers[jj]->flags & GAME_WRONG_COLORS)
1084      {
1085         AddGame(lpWrongCol,jj);
1086      }
1087      if (drivers[jj]->flags & GAME_UNEMULATED_PROTECTION)
1088      {
1089         AddGame(lpProt,jj);
1090      }
1091      if (drivers[jj]->flags & GAME_IMPERFECT_COLORS)
1092      {
1093         AddGame(lpImpCol,jj);
1094      }
1095      if (drivers[jj]->flags & GAME_IMPERFECT_GRAPHICS)
1096      {
1097         AddGame(lpImpGraph,jj);
1098      }
1099      if (drivers[jj]->flags & GAME_NO_SOUND)
1100      {
1101         AddGame(lpMissSnd,jj);
1102      }
1103      if (drivers[jj]->flags & GAME_IMPERFECT_SOUND)
1104      {
1105         AddGame(lpImpSnd,jj);
1106      }
1107      if (drivers[jj]->flags & GAME_NO_COCKTAIL)
1108      {
1109         AddGame(lpFlip,jj);
1110      }
1111   }
1112}
1113
1114void CreateDumpingFolders(int parent_index)
1115{
1116   int jj;
1117   BOOL bBadDump  = FALSE;
1118   BOOL bNoDump = FALSE;
1119   int nGames = driver_list_get_count(drivers);
1120   LPTREEFOLDER lpFolder = treeFolders[parent_index];
1121   const rom_entry *region, *rom;
1122   const char *name;
1123   const game_driver *gamedrv;
1124
1125   // create our two subfolders
1126   LPTREEFOLDER lpBad, lpNo;
1127   lpBad = NewFolder("Bad Dump", next_folder_id, parent_index, IDI_FOLDER,
1128                   GetFolderFlags(numFolders));
1129   ExtraFolderData[next_folder_id] = malloc(sizeof(EXFOLDERDATA) );
1130   memset(ExtraFolderData[next_folder_id], 0, sizeof(EXFOLDERDATA));
1131
1132   ExtraFolderData[next_folder_id]->m_nFolderId = next_folder_id;
1133   ExtraFolderData[next_folder_id]->m_nIconId = IDI_FOLDER;
1134   ExtraFolderData[next_folder_id]->m_nParent = lpFolder->m_nFolderId;
1135   ExtraFolderData[next_folder_id]->m_nSubIconId = -1;
1136   strcpy( ExtraFolderData[next_folder_id]->m_szTitle, "Bad Dump" );
1137   ExtraFolderData[next_folder_id++]->m_dwFlags = 0;
1138   AddFolder(lpBad);
1139   lpNo = NewFolder("No Dump", next_folder_id, parent_index, IDI_FOLDER,
1140                   GetFolderFlags(numFolders));
1141   ExtraFolderData[next_folder_id] = malloc(sizeof(EXFOLDERDATA) );
1142   memset(ExtraFolderData[next_folder_id], 0, sizeof(EXFOLDERDATA));
1143
1144   ExtraFolderData[next_folder_id]->m_nFolderId = next_folder_id;
1145   ExtraFolderData[next_folder_id]->m_nIconId = IDI_FOLDER;
1146   ExtraFolderData[next_folder_id]->m_nParent = lpFolder->m_nFolderId;
1147   ExtraFolderData[next_folder_id]->m_nSubIconId = -1;
1148   strcpy( ExtraFolderData[next_folder_id]->m_szTitle, "No Dump" );
1149   ExtraFolderData[next_folder_id++]->m_dwFlags = 0;
1150   AddFolder(lpNo);
1151
1152   // no games in top level folder
1153   SetAllBits(lpFolder->m_lpGameBits,FALSE);
1154
1155   for (jj = 0; jj < nGames; jj++)
1156   {
1157      gamedrv = drivers[jj];
1158
1159      if (!gamedrv->rom)
1160         continue;
1161      bBadDump = FALSE;
1162      bNoDump = FALSE;
1163      for (region = rom_first_region(gamedrv); region; region = rom_next_region(region))
1164      {
1165         for (rom = rom_first_file(region); rom; rom = rom_next_file(rom))
1166         {
1167            if (ROMREGION_ISROMDATA(region) || ROMREGION_ISDISKDATA(region) )
1168            {
1169               name = ROM_GETNAME(rom);
1170               if (hash_data_has_info(ROM_GETHASHDATA(rom), HASH_INFO_BAD_DUMP))           
1171                  bBadDump = TRUE;
1172               if (hash_data_has_info(ROM_GETHASHDATA(rom), HASH_INFO_NO_DUMP))           
1173                  bNoDump = TRUE;
1174            }
1175         }
1176      }
1177      if (bBadDump)
1178      {
1179         AddGame(lpBad,jj);
1180      }
1181      if (bNoDump)
1182      {
1183         AddGame(lpNo,jj);
1184      }
1185   }
1186}
1187
1188
1189void CreateYearFolders(int parent_index)
1190{
1191   int i,jj;
1192   int nGames = driver_list_get_count(drivers);
1193   int start_folder = numFolders;
1194   LPTREEFOLDER lpFolder = treeFolders[parent_index];
1195
1196   // no games in top level folder
1197   SetAllBits(lpFolder->m_lpGameBits,FALSE);
1198
1199   for (jj = 0; jj < nGames; jj++)
1200   {
1201      char s[100];
1202      strcpy(s,drivers[jj]->year);
1203
1204      if (s[0] == '\0' || s[0] == '?')
1205         continue;
1206
1207      if (s[4] == '?')
1208         s[4] = '\0';
1209     
1210      // look for an extant year treefolder for this game
1211      // (likely to be the previous one, so start at the end)
1212      for (i=numFolders-1;i>=start_folder;i--)
1213      {
1214         if (strncmp(treeFolders[i]->m_lpTitle,s,4) == 0)
1215         {
1216            AddGame(treeFolders[i],jj);
1217            break;
1218         }
1219      }
1220      if (i == start_folder-1)
1221      {
1222         // nope, it's a year we haven't seen before, make it.
1223         LPTREEFOLDER lpTemp;
1224         lpTemp = NewFolder(s, next_folder_id, parent_index, IDI_YEAR,
1225                         GetFolderFlags(numFolders));
1226         ExtraFolderData[next_folder_id] = malloc(sizeof(EXFOLDERDATA) );
1227         memset(ExtraFolderData[next_folder_id], 0, sizeof(EXFOLDERDATA));
1228
1229         ExtraFolderData[next_folder_id]->m_nFolderId = next_folder_id;
1230         ExtraFolderData[next_folder_id]->m_nIconId = IDI_YEAR;
1231         ExtraFolderData[next_folder_id]->m_nParent = lpFolder->m_nFolderId;
1232         ExtraFolderData[next_folder_id]->m_nSubIconId = -1;
1233         strcpy( ExtraFolderData[next_folder_id]->m_szTitle, s );
1234         ExtraFolderData[next_folder_id++]->m_dwFlags = 0;
1235         AddFolder(lpTemp);
1236         AddGame(lpTemp,jj);
1237      }
1238   }
1239}
1240
1241// creates child folders of all the top level folders, including custom ones
1242void CreateAllChildFolders(void)
1243{
1244   int num_top_level_folders = numFolders;
1245   int i, j;
1246
1247   for (i = 0; i < num_top_level_folders; i++)
1248   {
1249      LPTREEFOLDER lpFolder = treeFolders[i];
1250      LPFOLDERDATA lpFolderData = NULL;
1251
1252      for (j = 0; g_lpFolderData[j].m_lpTitle; j++)
1253      {
1254         if (g_lpFolderData[j].m_nFolderId == lpFolder->m_nFolderId)
1255         {
1256            lpFolderData = &g_lpFolderData[j];
1257            break;
1258         }
1259      }
1260
1261      if (lpFolderData != NULL)
1262      {
1263         //dprintf("Found built-in-folder id %i %i",i,lpFolder->m_nFolderId);
1264         if (lpFolderData->m_pfnCreateFolders != NULL)
1265            lpFolderData->m_pfnCreateFolders(i);
1266      }
1267      else
1268      {
1269         if ((lpFolder->m_dwFlags & F_CUSTOM) == 0)
1270         {
1271            dprintf("Internal inconsistency with non-built-in folder, but not custom");
1272            continue;
1273         }
1274
1275         //dprintf("Loading custom folder %i %i",i,lpFolder->m_nFolderId);
1276
1277         // load the extra folder files, which also adds children
1278         if (TryAddExtraFolderAndChildren(i) == FALSE)
1279         {
1280            lpFolder->m_nFolderId = FOLDER_NONE;
1281         }
1282      }
1283   }
1284}
1285
1286// adds these folders to the treeview
1287void ResetTreeViewFolders(void)
1288{
1289   HWND hTreeView = GetTreeView();
1290   int i;
1291   TVITEM tvi;
1292   TVINSERTSTRUCT   tvs;
1293
1294   HTREEITEM shti; // for current child branches
1295
1296   // currently "cached" parent
1297   HTREEITEM hti_parent = NULL;
1298   int index_parent = -1;         
1299
1300   TreeView_DeleteAllItems(hTreeView);
1301
1302   //dprintf("Adding folders to tree ui indices %i to %i",start_index,end_index);
1303
1304   tvs.hInsertAfter = TVI_SORT;
1305
1306   for (i=0;i<numFolders;i++)
1307   {
1308      LPTREEFOLDER lpFolder = treeFolders[i];
1309
1310      if (lpFolder->m_nParent == -1)
1311      {
1312         if (lpFolder->m_nFolderId < MAX_FOLDERS)
1313         {
1314            // it's a built in folder, let's see if we should show it
1315            if (GetShowFolder(lpFolder->m_nFolderId) == FALSE)
1316            {
1317               continue;
1318            }
1319         }
1320
1321         tvi.mask   = TVIF_TEXT | TVIF_PARAM | TVIF_IMAGE | TVIF_SELECTEDIMAGE;
1322         tvs.hParent = TVI_ROOT;
1323         tvi.pszText = lpFolder->m_lptTitle;
1324         tvi.lParam   = (LPARAM)lpFolder;
1325         tvi.iImage   = GetTreeViewIconIndex(lpFolder->m_nIconId);
1326         tvi.iSelectedImage = 0;
1327
1328#if defined(__GNUC__) /* bug in commctrl.h */
1329         tvs.item = tvi;
1330#else
1331         tvs.item = tvi;
1332#endif
1333
1334         // Add root branch
1335         hti_parent = TreeView_InsertItem(hTreeView, &tvs);
1336
1337         continue;
1338      }
1339
1340      // not a top level branch, so look for parent
1341      if (treeFolders[i]->m_nParent != index_parent)
1342      {
1343         
1344         hti_parent = TreeView_GetRoot(hTreeView);
1345         while (1)
1346         {
1347            if (hti_parent == NULL)
1348            {
1349               // couldn't find parent folder, so it's a built-in but
1350               // not shown folder
1351               break;
1352            }
1353
1354            tvi.hItem = hti_parent;
1355            tvi.mask = TVIF_PARAM;
1356            TreeView_GetItem(hTreeView,&tvi);
1357            if (((LPTREEFOLDER)tvi.lParam) == treeFolders[treeFolders[i]->m_nParent])
1358               break;
1359
1360            hti_parent = TreeView_GetNextSibling(hTreeView,hti_parent);
1361         }
1362
1363         // if parent is not shown, then don't show the child either obviously!
1364         if (hti_parent == NULL)
1365            continue;
1366
1367         index_parent = treeFolders[i]->m_nParent;
1368      }
1369
1370      tvi.mask   = TVIF_TEXT | TVIF_PARAM | TVIF_IMAGE | TVIF_SELECTEDIMAGE;
1371      tvs.hParent = hti_parent;
1372      tvi.iImage   = GetTreeViewIconIndex(treeFolders[i]->m_nIconId);
1373      tvi.iSelectedImage = 0;
1374      tvi.pszText = treeFolders[i]->m_lptTitle;
1375      tvi.lParam   = (LPARAM)treeFolders[i];
1376     
1377#if defined(__GNUC__) /* bug in commctrl.h */
1378      tvs.item = tvi;
1379#else
1380      tvs.item = tvi;
1381#endif
1382      // Add it to this tree branch
1383      shti = TreeView_InsertItem(hTreeView, &tvs);
1384
1385   }
1386}
1387
1388void SelectTreeViewFolder(int folder_id)
1389{
1390   HWND hTreeView = GetTreeView();
1391   HTREEITEM hti;
1392   TVITEM tvi;
1393
1394   memset(&tvi,0,sizeof(tvi));
1395
1396   hti = TreeView_GetRoot(hTreeView);
1397
1398   while (hti != NULL)
1399   {
1400      HTREEITEM hti_next;
1401
1402      tvi.hItem = hti;
1403      tvi.mask = TVIF_PARAM;
1404      TreeView_GetItem(hTreeView,&tvi);
1405
1406      if (((LPTREEFOLDER)tvi.lParam)->m_nFolderId == folder_id)
1407      {
1408         TreeView_SelectItem(hTreeView,tvi.hItem);
1409         SetCurrentFolder((LPTREEFOLDER)tvi.lParam);
1410         return;
1411      }
1412     
1413      hti_next = TreeView_GetChild(hTreeView,hti);
1414      if (hti_next == NULL)
1415      {
1416         hti_next = TreeView_GetNextSibling(hTreeView,hti);
1417         if (hti_next == NULL)
1418         {
1419            hti_next = TreeView_GetParent(hTreeView,hti);
1420            if (hti_next != NULL)
1421               hti_next = TreeView_GetNextSibling(hTreeView,hti_next);
1422         }
1423      }
1424      hti = hti_next;
1425   }
1426
1427   // could not find folder to select
1428   // make sure we select something
1429   tvi.hItem = TreeView_GetRoot(hTreeView);
1430   tvi.mask = TVIF_PARAM;
1431   TreeView_GetItem(hTreeView,&tvi);
1432
1433   TreeView_SelectItem(hTreeView,tvi.hItem);
1434   SetCurrentFolder((LPTREEFOLDER)tvi.lParam);
1435
1436}
1437
1438/*
1439 * Does this folder have an INI associated with it?
1440 * Currently only TRUE for FOLDER_VECTOR and children
1441 * of FOLDER_SOURCE.
1442 */
1443static BOOL FolderHasIni(LPTREEFOLDER lpFolder) {
1444   if (FOLDER_VECTOR == lpFolder->m_nFolderId) {
1445      return TRUE;
1446   }
1447   if (lpFolder->m_nParent != -1
1448      && FOLDER_SOURCE == treeFolders[lpFolder->m_nParent]->m_nFolderId) {
1449      return TRUE;
1450   }
1451   return FALSE;
1452}
1453
1454/* Add a folder to the list.  Does not allocate */
1455static BOOL AddFolder(LPTREEFOLDER lpFolder)
1456{
1457   if (numFolders + 1 >= folderArrayLength)
1458   {
1459      folderArrayLength += 500;
1460      treeFolders = realloc(treeFolders,sizeof(TREEFOLDER **) * folderArrayLength);
1461   }
1462
1463   /* Is there an folder.ini that can be edited? */
1464   if (FolderHasIni(lpFolder)) {
1465      lpFolder->m_dwFlags |= F_INIEDIT;
1466   }
1467
1468   treeFolders[numFolders] = lpFolder;
1469   numFolders++;
1470
1471   return TRUE;
1472}
1473
1474/* Allocate and initialize a NEW TREEFOLDER */
1475static LPTREEFOLDER NewFolder(const char *lpTitle,
1476                  UINT nFolderId, int nParent, UINT nIconId, DWORD dwFlags)
1477{
1478   LPTREEFOLDER lpFolder = (LPTREEFOLDER)malloc(sizeof(TREEFOLDER));
1479
1480   memset(lpFolder, '\0', sizeof (TREEFOLDER));
1481   lpFolder->m_lpTitle = (LPSTR)malloc(strlen(lpTitle) + 1);
1482   strcpy((char *)lpFolder->m_lpTitle,lpTitle);
1483   lpFolder->m_lptTitle = tstring_from_utf8(lpFolder->m_lpTitle);
1484   lpFolder->m_lpGameBits = NewBits(driver_list_get_count(drivers));
1485   lpFolder->m_nFolderId = nFolderId;
1486   lpFolder->m_nParent = nParent;
1487   lpFolder->m_nIconId = nIconId;
1488   lpFolder->m_dwFlags = dwFlags;
1489
1490   return lpFolder;
1491}
1492
1493/* Deallocate the passed in LPTREEFOLDER */
1494static void DeleteFolder(LPTREEFOLDER lpFolder)
1495{
1496   if (lpFolder)
1497   {
1498      if (lpFolder->m_lpGameBits)
1499      {
1500         DeleteBits(lpFolder->m_lpGameBits);
1501         lpFolder->m_lpGameBits = 0;
1502      }
1503      free(lpFolder->m_lptTitle);
1504      lpFolder->m_lptTitle = 0;
1505      free(lpFolder->m_lpTitle);
1506      lpFolder->m_lpTitle = 0;
1507      free(lpFolder);
1508      lpFolder = 0;
1509   }
1510}
1511
1512/* Can be called to re-initialize the array of treeFolders */
1513BOOL InitFolders(void)
1514{
1515   int          i = 0;
1516   DWORD         dwFolderFlags;
1517   LPFOLDERDATA   fData = 0;
1518
1519   if (treeFolders != NULL)
1520   {
1521      for (i = numFolders - 1; i >= 0; i--)
1522      {
1523         DeleteFolder(treeFolders[i]);
1524         treeFolders[i] = 0;
1525         numFolders--;
1526      }
1527   }
1528   numFolders = 0;
1529   if (folderArrayLength == 0)
1530   {
1531      folderArrayLength = 200;
1532      treeFolders = (TREEFOLDER **)malloc(sizeof(TREEFOLDER **) * folderArrayLength);
1533      if (!treeFolders)
1534      {
1535         folderArrayLength = 0;
1536         return 0;
1537      }
1538      else
1539      {
1540         memset(treeFolders,'\0', sizeof(TREEFOLDER **) * folderArrayLength);
1541      }
1542   }
1543   // built-in top level folders
1544   for (i = 0; g_lpFolderData[i].m_lpTitle; i++)
1545   {
1546      fData = &g_lpFolderData[i];
1547      /* get the saved folder flags */
1548      dwFolderFlags = GetFolderFlags(numFolders);
1549      /* create the folder */
1550      AddFolder(NewFolder(fData->m_lpTitle, fData->m_nFolderId, -1,
1551                     fData->m_nIconId, dwFolderFlags));
1552   }
1553   
1554   numExtraFolders = InitExtraFolders();
1555
1556   for (i = 0; i < numExtraFolders; i++)
1557   {
1558      LPEXFOLDERDATA  fExData = ExtraFolderData[i];
1559
1560      // OR in the saved folder flags
1561      dwFolderFlags = fExData->m_dwFlags | GetFolderFlags(numFolders);
1562      // create the folder
1563      //dprintf("creating top level custom folder with icon %i",fExData->m_nIconId);
1564      AddFolder(NewFolder(fExData->m_szTitle,fExData->m_nFolderId,fExData->m_nParent,
1565                     fExData->m_nIconId,dwFolderFlags));
1566   }
1567
1568   CreateAllChildFolders();
1569
1570   CreateTreeIcons();
1571
1572   ResetWhichGamesInFolders();
1573
1574   ResetTreeViewFolders();
1575
1576   SelectTreeViewFolder(GetSavedFolderID());
1577
1578   LoadFolderFlags();
1579
1580   return TRUE;
1581}
1582
1583// create iconlist and Treeview control
1584static BOOL CreateTreeIcons()
1585{
1586   HICON   hIcon;
1587   INT    i;
1588   HINSTANCE hInst = GetModuleHandle(0);
1589
1590   int numIcons = ICON_MAX + numExtraIcons;
1591
1592   hTreeSmall = ImageList_Create (16, 16, ILC_COLORDDB | ILC_MASK, numIcons, numIcons);
1593
1594   //dprintf("Trying to load %i normal icons",ICON_MAX);
1595   for (i = 0; i < ICON_MAX; i++)
1596   {
1597      hIcon = LoadIconFromFile(treeIconNames[i].lpName);
1598      if (!hIcon)
1599         hIcon = LoadIcon(hInst, MAKEINTRESOURCE(treeIconNames[i].nResourceID));
1600
1601      if (ImageList_AddIcon (hTreeSmall, hIcon) == -1)
1602      {
1603         ErrorMsg("Error creating icon on regular folder, %i %i",i,hIcon != NULL);
1604         return FALSE;
1605      }
1606   }
1607
1608   //dprintf("Trying to load %i extra custom-folder icons",numExtraIcons);
1609   for (i = 0; i < numExtraIcons; i++)
1610   {
1611      if ((hIcon = LoadIconFromFile(ExtraFolderIcons[i])) == 0)
1612         hIcon = LoadIcon (hInst, MAKEINTRESOURCE(IDI_FOLDER));
1613
1614      if (ImageList_AddIcon(hTreeSmall, hIcon) == -1)
1615      {
1616         ErrorMsg("Error creating icon on extra folder, %i %i",i,hIcon != NULL);
1617         return FALSE;
1618      }
1619   }
1620
1621   // Be sure that all the small icons were added.
1622   if (ImageList_GetImageCount(hTreeSmall) < numIcons)
1623   {
1624      ErrorMsg("Error with icon list--too few images.  %i %i",
1625            ImageList_GetImageCount(hTreeSmall),numIcons);
1626      return FALSE;
1627   }
1628
1629   // Be sure that all the small icons were added.
1630
1631   if (ImageList_GetImageCount (hTreeSmall) < ICON_MAX)
1632   {
1633      ErrorMsg("Error with icon list--too few images.  %i < %i",
1634             ImageList_GetImageCount(hTreeSmall),ICON_MAX);
1635      return FALSE;
1636   }
1637
1638   // Associate the image lists with the list view control.
1639   (void)TreeView_SetImageList(GetTreeView(), hTreeSmall, TVSIL_NORMAL);
1640
1641   return TRUE;
1642}
1643
1644
1645static void TreeCtrlOnPaint(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
1646{
1647   PAINTSTRUCT ps;
1648   HDC       hDC;
1649   RECT      rcClip, rcClient;
1650   HDC       memDC;
1651   HBITMAP    bitmap;
1652   HBITMAP    hOldBitmap;
1653
1654   HBITMAP hBackground = GetBackgroundBitmap();
1655   MYBITMAPINFO *bmDesc = GetBackgroundInfo();
1656
1657   hDC = BeginPaint(hWnd, &ps);
1658
1659   GetClipBox(hDC, &rcClip);
1660   GetClientRect(hWnd, &rcClient);
1661   
1662   // Create a compatible memory DC
1663   memDC = CreateCompatibleDC(hDC);
1664
1665   // Select a compatible bitmap into the memory DC
1666   bitmap = CreateCompatibleBitmap(hDC, rcClient.right - rcClient.left,
1667                           rcClient.bottom - rcClient.top);
1668   hOldBitmap = SelectObject(memDC, bitmap);
1669   
1670   // First let the control do its default drawing.
1671   CallWindowProc(g_lpTreeWndProc, hWnd, uMsg, (WPARAM)memDC, 0);
1672
1673   // Draw bitmap in the background
1674
1675   {
1676      HPALETTE hPAL;       
1677      HDC maskDC;
1678      HBITMAP maskBitmap;
1679      HDC tempDC;
1680      HDC imageDC;
1681      HBITMAP bmpImage;
1682      HBITMAP hOldBmpImage;
1683      HBITMAP hOldMaskBitmap;
1684      HBITMAP hOldHBitmap;
1685      int i, j;
1686      RECT rcRoot;
1687
1688      // Now create a mask
1689      maskDC = CreateCompatibleDC(hDC);   
1690     
1691      // Create monochrome bitmap for the mask
1692      maskBitmap = CreateBitmap(rcClient.right - rcClient.left,
1693                          rcClient.bottom - rcClient.top,
1694                          1, 1, NULL);
1695
1696      hOldMaskBitmap = SelectObject(maskDC, maskBitmap);
1697      SetBkColor(memDC, GetSysColor(COLOR_WINDOW));
1698
1699      // Create the mask from the memory DC
1700      BitBlt(maskDC, 0, 0, rcClient.right - rcClient.left,
1701            rcClient.bottom - rcClient.top, memDC,
1702            rcClient.left, rcClient.top, SRCCOPY);
1703
1704      tempDC = CreateCompatibleDC(hDC);
1705      hOldHBitmap = SelectObject(tempDC, hBackground);
1706
1707      imageDC = CreateCompatibleDC(hDC);
1708      bmpImage = CreateCompatibleBitmap(hDC,
1709                                rcClient.right - rcClient.left,
1710                                rcClient.bottom - rcClient.top);
1711      hOldBmpImage = SelectObject(imageDC, bmpImage);
1712
1713      hPAL = GetBackgroundPalette();
1714      if (hPAL == NULL)
1715         hPAL = CreateHalftonePalette(hDC);
1716
1717      if (GetDeviceCaps(hDC, RASTERCAPS) & RC_PALETTE && hPAL != NULL)
1718      {
1719         SelectPalette(hDC, hPAL, FALSE);
1720         RealizePalette(hDC);
1721         SelectPalette(imageDC, hPAL, FALSE);
1722      }
1723     
1724      // Get x and y offset
1725      TreeView_GetItemRect(hWnd, TreeView_GetRoot(hWnd), &rcRoot, FALSE);
1726      rcRoot.left = -GetScrollPos(hWnd, SB_HORZ);
1727
1728      // Draw bitmap in tiled manner to imageDC
1729      for (i = rcRoot.left; i < rcClient.right; i += bmDesc->bmWidth)
1730         for (j = rcRoot.top; j < rcClient.bottom; j += bmDesc->bmHeight)
1731            BitBlt(imageDC,  i, j, bmDesc->bmWidth, bmDesc->bmHeight,
1732                  tempDC, 0, 0, SRCCOPY);
1733
1734      // Set the background in memDC to black. Using SRCPAINT with black and any other
1735      // color results in the other color, thus making black the transparent color
1736      SetBkColor(memDC, RGB(0,0,0));
1737      SetTextColor(memDC, RGB(255,255,255));
1738      BitBlt(memDC, rcClip.left, rcClip.top, rcClip.right - rcClip.left,
1739            rcClip.bottom - rcClip.top,
1740            maskDC, rcClip.left, rcClip.top, SRCAND);
1741
1742      // Set the foreground to black. See comment above.
1743      SetBkColor(imageDC, RGB(255,255,255));
1744      SetTextColor(imageDC, RGB(0,0,0));
1745      BitBlt(imageDC, rcClip.left, rcClip.top, rcClip.right - rcClip.left,
1746            rcClip.bottom - rcClip.top,
1747            maskDC, rcClip.left, rcClip.top, SRCAND);
1748
1749      // Combine the foreground with the background
1750      BitBlt(imageDC, rcClip.left, rcClip.top, rcClip.right - rcClip.left,
1751            rcClip.bottom - rcClip.top,
1752            memDC, rcClip.left, rcClip.top, SRCPAINT);
1753
1754      // Draw the final image to the screen
1755      BitBlt(hDC, rcClip.left, rcClip.top, rcClip.right - rcClip.left,
1756            rcClip.bottom - rcClip.top,
1757            imageDC, rcClip.left, rcClip.top, SRCCOPY);
1758     
1759      SelectObject(maskDC, hOldMaskBitmap);
1760      SelectObject(tempDC, hOldHBitmap);
1761      SelectObject(imageDC, hOldBmpImage);
1762
1763      DeleteDC(maskDC);
1764      DeleteDC(imageDC);
1765      DeleteDC(tempDC);
1766      DeleteObject(bmpImage);
1767      DeleteObject(maskBitmap);
1768
1769      if (GetBackgroundPalette() == NULL)
1770      {
1771         DeleteObject(hPAL);
1772         hPAL = 0;
1773      }
1774   }
1775
1776   SelectObject(memDC, hOldBitmap);
1777   DeleteObject(bitmap);
1778   DeleteDC(memDC);
1779   EndPaint(hWnd, &ps);
1780   ReleaseDC(hWnd, hDC);
1781}
1782
1783/* Header code - Directional Arrows */
1784static LRESULT CALLBACK TreeWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
1785{
1786   if (GetBackgroundBitmap() != NULL)
1787   {
1788      switch (uMsg)
1789      {   
1790       case WM_MOUSEMOVE:
1791      {
1792         if (MouseHasBeenMoved())
1793            ShowCursor(TRUE);
1794         break;
1795      }
1796
1797      case WM_KEYDOWN :
1798         if (wParam == VK_F2)
1799         {
1800            if (lpCurrentFolder->m_dwFlags & F_CUSTOM)
1801            {
1802               TreeView_EditLabel(hWnd,TreeView_GetSelection(hWnd));
1803               return TRUE;
1804            }
1805         }
1806         break;
1807
1808      case WM_ERASEBKGND:
1809         return TRUE;
1810         break;
1811
1812      case WM_PAINT:
1813         TreeCtrlOnPaint(hWnd, uMsg, wParam, lParam);
1814         UpdateWindow(hWnd);
1815         break;
1816      }
1817   }
1818
1819   /* message not handled */
1820   return CallWindowProc(g_lpTreeWndProc, hWnd, uMsg, wParam, lParam);
1821}
1822
1823/*
1824 * Filter code - should be moved to filter.c/filter.h
1825 * Added 01/09/99 - MSH <mhaaland@hypertech.com>
1826 */
1827
1828/* find a FOLDERDATA by folderID */
1829LPFOLDERDATA FindFilter(DWORD folderID)
1830{
1831   int i;
1832
1833   for (i = 0; g_lpFolderData[i].m_lpTitle; i++)
1834   {
1835      if (g_lpFolderData[i].m_nFolderId == folderID)
1836         return &g_lpFolderData[i];
1837   }
1838   return (LPFOLDERDATA) 0;
1839}
1840
1841/***************************************************************************
1842    private structures
1843 ***************************************************************************/
1844
1845/***************************************************************************
1846    private functions prototypes
1847 ***************************************************************************/
1848
1849/***************************************************************************
1850    private functions
1851 ***************************************************************************/
1852
1853/**************************************************************************/
1854
1855LPTREEFOLDER GetFolderByName(int nParentId, const char *pszFolderName)
1856{
1857   int i = 0, nParent;
1858
1859   //First Get the Parent TreeviewItem
1860   //Enumerate Children
1861   for(i = 0; i < numFolders/* ||treeFolders[i] != NULL*/; i++)
1862   {
1863      if (!strcmp(treeFolders[i]->m_lpTitle, pszFolderName))
1864      {
1865         nParent = treeFolders[i]->m_nParent;
1866         if ((nParent >= 0) && treeFolders[nParent]->m_nFolderId == nParentId)
1867            return treeFolders[i];
1868      }
1869   }
1870   return NULL;
1871}
1872
1873static int InitExtraFolders(void)
1874{
1875   struct stat     stat_buffer;
1876   struct _finddata_t files;
1877   int             i, count = 0;
1878   long            hLong;
1879   char*           ext;
1880   char            buf[256];
1881   char            curdir[MAX_PATH];
1882   const char*     dir = GetFolderDir();
1883
1884   memset(ExtraFolderData, 0, (MAX_EXTRA_FOLDERS * MAX_EXTRA_SUBFOLDERS)* sizeof(LPEXFOLDERDATA));
1885
1886   /* NPW 9-Feb-2003 - MSVC stat() doesn't like stat() called with an empty
1887    * string
1888    */
1889   if (dir[0] == '\0')
1890      dir = ".";
1891
1892   // Why create the directory if it doesn't exist, just return 0 folders.
1893   if (stat(dir, &stat_buffer) != 0)
1894    {
1895      return 0; // _mkdir(dir);
1896    }
1897
1898   _getcwd(curdir, MAX_PATH);
1899
1900   _chdir(dir);
1901
1902   hLong = _findfirst("*", &files);
1903
1904   for (i = 0; i < MAX_EXTRA_FOLDERS; i++)
1905    {
1906      ExtraFolderIcons[i] = NULL;
1907    }
1908
1909   numExtraIcons = 0;
1910
1911   while (!_findnext(hLong, &files))
1912   {
1913      if ((files.attrib & _A_SUBDIR) == 0)
1914      {
1915         FILE *fp;
1916
1917         fp = fopen(files.name, "r");
1918         if (fp != NULL)
1919         {
1920            int icon[2] = { 0, 0 };
1921            char *p, *name;
1922
1923            while (fgets(buf, 256, fp))
1924            {
1925               if (buf[0] == '[')
1926               {
1927                  p = strchr(buf, ']');
1928                  if (p == NULL)
1929                     continue;
1930
1931                  *p = '\0';
1932                  name = &buf[1];
1933                  if (!strcmp(name, "FOLDER_SETTINGS"))
1934                  {
1935                     while (fgets(buf, 256, fp))
1936                     {
1937                        name = strtok(buf, " =\r\n");
1938                        if (name == NULL)
1939                           break;
1940
1941                        if (!strcmp(name, "RootFolderIcon"))
1942                        {
1943                           name = strtok(NULL, " =\r\n");
1944                           if (name != NULL)
1945                              SetExtraIcons(name, &icon[0]);
1946                        }
1947                        if (!strcmp(name, "SubFolderIcon"))
1948                        {
1949                           name = strtok(NULL, " =\r\n");
1950                           if (name != NULL)
1951                              SetExtraIcons(name, &icon[1]);
1952                        }
1953                     }
1954                     break;
1955                  }
1956               }
1957            }
1958            fclose(fp);
1959
1960            strcpy(buf, files.name);
1961            ext = strrchr(buf, '.');
1962
1963            if (ext && *(ext + 1) && !mame_stricmp(ext + 1, "ini"))
1964            {
1965               ExtraFolderData[count] = malloc(sizeof(EXFOLDERDATA));
1966               if (ExtraFolderData[count])
1967               {
1968                  *ext = '\0';
1969
1970                  memset(ExtraFolderData[count], 0, sizeof(EXFOLDERDATA));
1971
1972                  strncpy(ExtraFolderData[count]->m_szTitle, buf, 63);
1973                  ExtraFolderData[count]->m_nFolderId   = next_folder_id++;
1974                  ExtraFolderData[count]->m_nParent     = -1;
1975                  ExtraFolderData[count]->m_dwFlags     = F_CUSTOM;
1976                  ExtraFolderData[count]->m_nIconId     = icon[0] ? -icon[0] : IDI_FOLDER;
1977                  ExtraFolderData[count]->m_nSubIconId  = icon[1] ? -icon[1] : IDI_FOLDER;
1978                  //dprintf("extra folder with icon %i, subicon %i",
1979                  //ExtraFolderData[count]->m_nIconId,
1980                  //ExtraFolderData[count]->m_nSubIconId);
1981                  count++;
1982               }
1983            }
1984         }
1985      }
1986   }
1987
1988   _chdir(curdir);
1989   return count;
1990}
1991
1992void FreeExtraFolders(void)
1993{
1994   int i;
1995
1996   for (i = 0; i < numExtraFolders; i++)
1997   {
1998      if (ExtraFolderData[i])
1999      {
2000         free(ExtraFolderData[i]);
2001         ExtraFolderData[i] = NULL;
2002      }
2003   }
2004
2005   for (i = 0; i < numExtraIcons; i++)
2006    {
2007      free(ExtraFolderIcons[i]);
2008    }
2009
2010   numExtraIcons = 0;
2011
2012}
2013
2014
2015static void SetExtraIcons(char *name, int *id)
2016{
2017   char *p = strchr(name, '.');
2018
2019   if (p != NULL)
2020      *p = '\0';
2021
2022   ExtraFolderIcons[numExtraIcons] = malloc(strlen(name) + 1);
2023   if (ExtraFolderIcons[numExtraIcons])
2024   {
2025      *id = ICON_MAX + numExtraIcons;
2026      strcpy(ExtraFolderIcons[numExtraIcons], name);
2027      numExtraIcons++;
2028   }
2029}
2030
2031
2032// Called to add child folders of the top level extra folders already created
2033BOOL TryAddExtraFolderAndChildren(int parent_index)
2034{
2035    FILE*   fp = NULL;
2036    char    fname[MAX_PATH];
2037    char    readbuf[256];
2038    char*   p;
2039    char*   name;
2040    int     id, current_id, i;
2041    LPTREEFOLDER lpTemp = NULL;
2042   LPTREEFOLDER lpFolder = treeFolders[parent_index];
2043
2044    current_id = lpFolder->m_nFolderId;
2045   
2046    id = lpFolder->m_nFolderId - MAX_FOLDERS;
2047
2048    /* "folder\title.ini" */
2049
2050    sprintf( fname, "%s\\%s.ini",
2051        GetFolderDir(),
2052        ExtraFolderData[id]->m_szTitle);
2053   
2054    fp = fopen(fname, "r");
2055    if (fp == NULL)
2056        return FALSE;
2057   
2058    while ( fgets(readbuf, 256, fp) )
2059    {
2060        /* do we have [...] ? */
2061
2062        if (readbuf[0] == '[')
2063        {
2064            p = strchr(readbuf, ']');
2065            if (p == NULL)
2066            {
2067                continue;
2068            }
2069           
2070            *p = '\0';
2071            name = &readbuf[1];
2072     
2073            /* is it [FOLDER_SETTINGS]? */
2074
2075            if (strcmp(name, "FOLDER_SETTINGS") == 0)
2076            {
2077                current_id = -1;
2078                continue;
2079            }
2080            else
2081            {
2082                /* it it [ROOT_FOLDER]? */
2083
2084                if (!strcmp(name, "ROOT_FOLDER"))
2085                {
2086                    current_id = lpFolder->m_nFolderId;
2087                    lpTemp = lpFolder;
2088
2089                }
2090                else
2091                {
2092                    /* must be [folder name] */
2093
2094                    current_id = next_folder_id++;
2095               /* create a new folder with this name,
2096                  and the flags for this folder as read from the registry */
2097               lpTemp = NewFolder(name,current_id,parent_index,
2098                               ExtraFolderData[id]->m_nSubIconId,
2099                               GetFolderFlags(numFolders) | F_CUSTOM);
2100               ExtraFolderData[current_id] = malloc(sizeof(EXFOLDERDATA) );
2101               memset(ExtraFolderData[current_id], 0, sizeof(EXFOLDERDATA));
2102
2103               ExtraFolderData[current_id]->m_nFolderId = current_id - MAX_EXTRA_FOLDERS;
2104               ExtraFolderData[current_id]->m_nIconId = ExtraFolderData[id]->m_nSubIconId;
2105               ExtraFolderData[current_id]->m_nParent = ExtraFolderData[id]->m_nFolderId;
2106               ExtraFolderData[current_id]->m_nSubIconId = -1;
2107               strcpy( ExtraFolderData[current_id]->m_szTitle, name );
2108               ExtraFolderData[current_id]->m_dwFlags = ExtraFolderData[id]->m_dwFlags;
2109                    AddFolder(lpTemp);
2110                }
2111            }
2112        }
2113        else if (current_id != -1)
2114        {
2115            /* string on a line by itself -- game name */
2116
2117            name = strtok(readbuf, " \t\r\n");
2118            if (name == NULL)
2119            {
2120                current_id = -1;
2121                continue;
2122            }
2123
2124            /* IMPORTANT: This assumes that all driver names are lowercase! */
2125         for (i = 0; name[i]; i++)
2126            name[i] = tolower(name[i]);
2127
2128         if (lpTemp == NULL)
2129         {
2130            ErrorMsg("Error parsing %s: missing [folder name] or [ROOT_FOLDER]",
2131                   fname);
2132            current_id = lpFolder->m_nFolderId;
2133            lpTemp = lpFolder;
2134         }
2135         AddGame(lpTemp,GetGameNameIndex(name));
2136        }
2137    }
2138
2139    if ( fp )
2140    {
2141        fclose( fp );
2142    }
2143
2144    return TRUE;
2145}
2146
2147
2148void GetFolders(TREEFOLDER ***folders,int *num_folders)
2149{
2150   *folders = treeFolders;
2151   *num_folders = numFolders;
2152}
2153
2154BOOL TryRenameCustomFolderIni(LPTREEFOLDER lpFolder,const char *old_name,const char *new_name)
2155{
2156   char filename[MAX_PATH];
2157   char new_filename[MAX_PATH];
2158   LPTREEFOLDER lpParent = NULL;
2159   if (lpFolder->m_nParent >= 0)
2160   {
2161      //it is a custom SubFolder
2162      lpParent = GetFolder( lpFolder->m_nParent );
2163      if( lpParent )
2164      {
2165         snprintf(filename,ARRAY_LENGTH(filename),"%s\\%s\\%s.ini",GetIniDir(),lpParent->m_lpTitle, old_name );
2166         snprintf(new_filename,ARRAY_LENGTH(new_filename),"%s\\%s\\%s.ini",GetIniDir(),lpParent->m_lpTitle, new_name );
2167         win_move_file_utf8(filename,new_filename);
2168      }
2169   }
2170   else
2171   {
2172      //Rename the File, if it exists
2173      snprintf(filename,ARRAY_LENGTH(filename),"%s\\%s.ini",GetIniDir(),old_name );
2174      snprintf(new_filename,ARRAY_LENGTH(new_filename),"%s\\%s.ini",GetIniDir(), new_name );
2175      win_move_file_utf8(filename,new_filename);
2176      //Rename the Directory, if it exists
2177      snprintf(filename,ARRAY_LENGTH(filename),"%s\\%s",GetIniDir(),old_name );
2178      snprintf(new_filename,ARRAY_LENGTH(new_filename),"%s\\%s",GetIniDir(), new_name );
2179      win_move_file_utf8(filename,new_filename);
2180   }
2181   return TRUE;
2182}
2183
2184BOOL TryRenameCustomFolder(LPTREEFOLDER lpFolder, const char *new_name)
2185{
2186   BOOL retval;
2187   char filename[MAX_PATH];
2188   char new_filename[MAX_PATH];
2189   
2190   if (lpFolder->m_nParent >= 0)
2191   {
2192      // a child extra folder was renamed, so do the rename and save the parent
2193
2194      // save old title
2195      char *old_title = lpFolder->m_lpTitle;
2196
2197      // set new title
2198      lpFolder->m_lpTitle = (char *)malloc(strlen(new_name) + 1);
2199      strcpy(lpFolder->m_lpTitle,new_name);
2200
2201      // try to save
2202      if (TrySaveExtraFolder(lpFolder) == FALSE)
2203      {
2204         // failed, so free newly allocated title and restore old
2205         free(lpFolder->m_lpTitle);
2206         lpFolder->m_lpTitle = old_title;
2207         return FALSE;
2208      }
2209      TryRenameCustomFolderIni(lpFolder, old_title, new_name);
2210      // successful, so free old title
2211      free(old_title);
2212      return TRUE;
2213   }
2214   
2215   // a parent extra folder was renamed, so rename the file
2216
2217   snprintf(new_filename,ARRAY_LENGTH(new_filename),"%s\\%s.ini",GetFolderDir(),new_name);
2218   snprintf(filename,ARRAY_LENGTH(filename),"%s\\%s.ini",GetFolderDir(),lpFolder->m_lpTitle);
2219
2220   retval = win_move_file_utf8(filename,new_filename);
2221
2222   if (retval)
2223   {
2224      TryRenameCustomFolderIni(lpFolder, lpFolder->m_lpTitle, new_name);
2225      free(lpFolder->m_lpTitle);
2226      lpFolder->m_lpTitle = (char *)malloc(strlen(new_name) + 1);
2227      strcpy(lpFolder->m_lpTitle,new_name);
2228   }
2229   else
2230   {
2231      char buf[500];
2232      snprintf(buf,ARRAY_LENGTH(buf),"Error while renaming custom file %s to %s",
2233             filename,new_filename);
2234      win_message_box_utf8(GetMainWindow(), buf, MAME32NAME, MB_OK | MB_ICONERROR);
2235   }
2236   return retval;
2237}
2238
2239void AddToCustomFolder(LPTREEFOLDER lpFolder,int driver_index)
2240{
2241    if ((lpFolder->m_dwFlags & F_CUSTOM) == 0)
2242   {
2243       win_message_box_utf8(GetMainWindow(),"Unable to add game to non-custom folder",
2244               MAME32NAME,MB_OK | MB_ICONERROR);
2245      return;
2246   }
2247
2248   if (TestBit(lpFolder->m_lpGameBits,driver_index) == 0)
2249   {
2250      AddGame(lpFolder,driver_index);
2251      if (TrySaveExtraFolder(lpFolder) == FALSE)
2252         RemoveGame(lpFolder,driver_index); // undo on error
2253   }
2254}
2255
2256void RemoveFromCustomFolder(LPTREEFOLDER lpFolder,int driver_index)
2257{
2258    if ((lpFolder->m_dwFlags & F_CUSTOM) == 0)
2259   {
2260       win_message_box_utf8(GetMainWindow(),"Unable to remove game from non-custom folder",
2261               MAME32NAME,MB_OK | MB_ICONERROR);
2262      return;
2263   }
2264
2265   if (TestBit(lpFolder->m_lpGameBits,driver_index) != 0)
2266   {
2267      RemoveGame(lpFolder,driver_index);
2268      if (TrySaveExtraFolder(lpFolder) == FALSE)
2269         AddGame(lpFolder,driver_index); // undo on error
2270   }
2271}
2272
2273BOOL TrySaveExtraFolder(LPTREEFOLDER lpFolder)
2274{
2275    char fname[MAX_PATH];
2276   FILE *fp;
2277   BOOL error = FALSE;
2278    int i,j;
2279
2280   LPTREEFOLDER root_folder = NULL;
2281   LPEXFOLDERDATA extra_folder = NULL;
2282
2283   for (i=0;i<numExtraFolders;i++)
2284   {
2285       if (ExtraFolderData[i]->m_nFolderId == lpFolder->m_nFolderId)
2286      {
2287          root_folder = lpFolder;
2288          extra_folder = ExtraFolderData[i];
2289         break;
2290      }
2291
2292      if (lpFolder->m_nParent >= 0 &&
2293         ExtraFolderData[i]->m_nFolderId == treeFolders[lpFolder->m_nParent]->m_nFolderId)
2294      {
2295         root_folder = treeFolders[lpFolder->m_nParent];
2296         extra_folder = ExtraFolderData[i];
2297         break;
2298      }
2299   }
2300
2301   if (extra_folder == NULL || root_folder == NULL)
2302   {
2303      MessageBox(GetMainWindow(), TEXT("Error finding custom file name to save"), TEXT(MAME32NAME), MB_OK | MB_ICONERROR);
2304      return FALSE;
2305   }
2306    /* "folder\title.ini" */
2307
2308    snprintf( fname, sizeof(fname), "%s\\%s.ini", GetFolderDir(), extra_folder->m_szTitle);
2309
2310    fp = fopen(fname, "wt");
2311    if (fp == NULL)
2312      error = TRUE;
2313   else
2314   {
2315      TREEFOLDER *folder_data;
2316
2317
2318      fprintf(fp,"[FOLDER_SETTINGS]\n");
2319      // negative values for icons means it's custom, so save 'em
2320      if (extra_folder->m_nIconId < 0)
2321      {
2322         fprintf(fp, "RootFolderIcon %s\n",
2323               ExtraFolderIcons[(-extra_folder->m_nIconId) - ICON_MAX]);
2324      }
2325      if (extra_folder->m_nSubIconId < 0)
2326      {
2327         fprintf(fp,"SubFolderIcon %s\n",
2328               ExtraFolderIcons[(-extra_folder->m_nSubIconId) - ICON_MAX]);
2329      }
2330
2331      /* need to loop over all our TREEFOLDERs--first the root one, then each child.
2332        start with the root */
2333
2334      folder_data = root_folder;
2335
2336      fprintf(fp,"\n[ROOT_FOLDER]\n");
2337
2338      for (i=0;i<driver_list_get_count(drivers);i++)
2339      {
2340         int driver_index = GetIndexFromSortedIndex(i);
2341         if (TestBit(folder_data->m_lpGameBits,driver_index))
2342         {
2343            fprintf(fp,"%s\n",drivers[driver_index]->name);
2344         }
2345      }
2346
2347      /* look through the custom folders for ones with our root as parent */
2348      for (j=0;j<numFolders;j++)
2349      {
2350         folder_data = treeFolders[j];
2351
2352         if (folder_data->m_nParent >= 0 &&
2353            treeFolders[folder_data->m_nParent] == root_folder)
2354         {
2355            fprintf(fp,"\n[%s]\n",folder_data->m_lpTitle);
2356           
2357            for (i=0;i<driver_list_get_count(drivers);i++)
2358            {
2359               int driver_index = GetIndexFromSortedIndex(i);
2360               if (TestBit(folder_data->m_lpGameBits,driver_index))
2361               {
2362                  fprintf(fp,"%s\n",drivers[driver_index]->name);
2363               }
2364            }
2365         }
2366      }
2367      if (fclose(fp) != 0)
2368         error = TRUE;
2369   }
2370
2371   if (error)
2372   {
2373      char buf[500];
2374      snprintf(buf,ARRAY_LENGTH(buf),"Error while saving custom file %s",fname);
2375      win_message_box_utf8(GetMainWindow(), buf, MAME32NAME, MB_OK | MB_ICONERROR);
2376   }
2377   return !error;
2378}
2379
2380HIMAGELIST GetTreeViewIconList(void)
2381{
2382    return hTreeSmall;
2383}
2384
2385int GetTreeViewIconIndex(int icon_id)
2386{
2387   int i;
2388
2389   if (icon_id < 0)
2390      return -icon_id;
2391
2392   for (i = 0; i < sizeof(treeIconNames) / sizeof(treeIconNames[0]); i++)
2393   {
2394      if (icon_id == treeIconNames[i].nResourceID)
2395         return i;
2396   }
2397
2398   return -1;
2399}
2400
2401/* End of source file */
src/osd/winui/properties.c
r0r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11***************************************************************************/
12 
13/***************************************************************************
14
15  Properties.c
16
17    Properties Popup and Misc UI support routines.
18   
19    Created 8/29/98 by Mike Haaland (mhaaland@hypertech.com)
20
21***************************************************************************/
22
23/***************************************************************************
24
25MSH - 20070809
26--
27Notes on properties and ini files, reset and reset to default.
28----------------------------------------------------------------------------
29Each ini contains a complete option set.
30
31Priority order for option sets (Lowest to Highest):
32
33built-in defaults
34program    ini (executable root filename ini)
35debug      ini (if running a debug build)
36vector     ini (really is vector.ini!)
37driver     ini (source code root filename in which this driver is found)
38granparent ini (grandparent, not sure these exist, but it is possible)
39parent     ini (where parent is the name of the parent driver)
40game       ini (where game is the driver name for this game)
41
42To determine which option set to use, start at the top level (lowest
43priority), and overlay all higher priority ini's until the desired level
44is reached.
45
46The 'default' option set is the next priority higher up the list from
47the desired level. For the default (program.ini) level, it is also the
48default.
49
50When MAME is run, the desired level is game ini.
51
52Expected Code behavior:
53----------------------------------------------------------------------------
54This approach requires 3 option sets, 'current', 'original' and 'default'.
55
56'current': used to populate the property pages, and to initialize the
57'original' set.
58
59'original': used to evaluate if the 'Reset' button is enabled.
60If 'current' matches 'original', the 'Reset' button is disabled,
61otherwise it is enabled.
62
63'default': used to evaluate if the 'Restore to Defaults' button is enabled.
64If 'current' matches 'default', the 'Restore to Defaults' button is disabled,
65otherwise it is enabled.
66
67When editing any option set, the desired level is set to the one being
68edited, the default set for that level, is the next lower priority set found.
69
70Upon entering the properties dialog:
71a) 'current' is initialized
72b) 'original' is initialized by 'current'
73c) 'default' is initialized
74d) Populate Property pages with 'current'
75e) 'Reset' and 'Restore to Defaults' buttons are evaluated.
76
77After any change:
78a) 'current' is updated
79b) 'Reset' and 'Restore to Defaults' buttons are re-evaluated.
80
81Reset:
82a) 'current' is reinitialized to 'original'
83b) Re-populate Property pages with 'current'
84c) 'Reset' and 'Restore to Defaults' buttons are re-evaluated.
85
86Restore to Defaults:
87a) 'current' is reinitialized to 'default'
88b) Re-populate Property pages with 'current'
89b) 'Reset' and 'Restore to Defaults' buttons are re-evaluated.
90
91Apply:
92a) 'original' is reinitialized to 'current'
93b) 'Reset' and 'Restore to defaults' are re-evaluated.
94c) If they 'current' matches 'default', remove the ini from disk.
95   Otherwise, write the ini to disk.
96
97Cancel:
98a) Exit the dialog.
99
100OK:
101a) If they 'current' matches 'default', remove the ini from disk.
102   Otherwise, write the ini to disk.
103b) Exit the dialog.
104
105
106***************************************************************************/
107
108#define WIN32_LEAN_AND_MEAN
109#include <windows.h>
110#include <windowsx.h>
111#include <commctrl.h>
112#include <commdlg.h>
113#include <ddraw.h>
114#include <stdio.h>
115#include <string.h>
116#include <sys/stat.h>
117#include <tchar.h>
118
119#include <driver.h>
120#include <info.h>
121#include "audit.h"
122#include "audit32.h"
123#include "bitmask.h"
124#include "m32opts.h"
125#include "file.h"
126#include "resource.h"
127#include "dijoystick.h"     /* For DIJoystick avalibility. */
128#include "m32util.h"
129#include "directdraw.h"
130#include "properties.h"
131#include "treeview.h"
132#include "win32ui.h"
133#include "screenshot.h"
134#include "mame32.h"
135#include "datamap.h"
136#include "help.h"
137#include "resource.hm"
138#include "winmain.h"
139#include "strconv.h"
140#include "winutf8.h"
141#include "m32util.h"
142
143typedef HANDLE HTHEME;
144
145#ifdef _MSC_VER
146#define snprintf _snprintf
147#endif
148
149#ifdef MESS
150// done like this until I figure out a better idea
151#include "messopts.h"
152#include "resourcems.h"
153#include "propertiesms.h"
154#endif
155
156// missing win32 api defines
157#ifndef TBCD_TICS
158#define TBCD_TICS 1
159#endif
160#ifndef TBCD_THUMB
161#define TBCD_THUMB 2
162#endif
163#ifndef TBCD_CHANNEL
164#define TBCD_CHANNEL 3
165#endif
166
167#if defined(__GNUC__)
168/* fix warning: cast does not match function type */
169#undef  PropSheet_GetTabControl
170#define PropSheet_GetTabControl(d) (HWND)(LRESULT)(int)SendMessage((d),PSM_GETTABCONTROL,0,0)
171#endif /* defined(__GNUC__) */
172
173/***************************************************************
174 * Imported function prototypes
175 ***************************************************************/
176
177/**************************************************************
178 * Local function prototypes
179 **************************************************************/
180
181static void SetStereoEnabled(HWND hWnd, int nIndex);
182static void SetYM3812Enabled(HWND hWnd, int nIndex);
183static void SetSamplesEnabled(HWND hWnd, int nIndex, BOOL bSoundEnabled);
184static void InitializeOptions(HWND hDlg);
185static void InitializeMisc(HWND hDlg);
186static void OptOnHScroll(HWND hWnd, HWND hwndCtl, UINT code, int pos);
187static void NumScreensSelectionChange(HWND hwnd);
188static void RefreshSelectionChange(HWND hWnd, HWND hWndCtrl);
189static void InitializeSoundUI(HWND hwnd);
190static void InitializeSkippingUI(HWND hwnd);
191static void InitializeRotateUI(HWND hwnd);
192static void UpdateSelectScreenUI(HWND hwnd);
193static void InitializeSelectScreenUI(HWND hwnd);
194static void InitializeD3DVersionUI(HWND hwnd);
195static void InitializeVideoUI(HWND hwnd);
196static void InitializeEffectUI(HWND hWnd);
197static void InitializeBIOSUI(HWND hwnd);
198static void InitializeControllerMappingUI(HWND hwnd);
199static void UpdateOptions(HWND hDlg, datamap *properties_datamap, core_options *opts);
200static void UpdateProperties(HWND hDlg, datamap *properties_datamap, core_options *opts);
201static void PropToOptions(HWND hWnd, core_options *o);
202static void OptionsToProp(HWND hWnd, core_options *o);
203static void SetPropEnabledControls(HWND hWnd);
204static BOOL SelectEffect(HWND hWnd);
205static BOOL ResetEffect(HWND hWnd);
206
207static void BuildDataMap(void);
208static void ResetDataMap(HWND hWnd);
209
210static BOOL IsControlOptionValue(HWND hDlg,HWND hwnd_ctrl, core_options *opts );
211
212static void UpdateBackgroundBrush(HWND hwndTab);
213HBRUSH hBkBrush;
214
215/**************************************************************
216 * Local private variables
217 **************************************************************/
218
219static core_options *pOrigOpts, *pDefaultOpts;
220static BOOL orig_uses_defaults;
221static core_options *pCurrentOpts = NULL;
222static datamap *properties_datamap;
223
224static int  g_nGame            = 0;
225static int  g_nFolder          = 0;
226static int  g_nFolderGame      = 0;
227static int  g_nPropertyMode    = 0;
228static BOOL g_bUseDefaults     = FALSE;
229static BOOL g_bReset           = FALSE;
230static BOOL  g_bAutoAspect[MAX_SCREENS] = {FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE};
231static HICON g_hIcon = NULL;
232
233/* Property sheets */
234
235#define HIGHLIGHT_COLOR RGB(0,196,0)
236HBRUSH highlight_brush = NULL;
237HBRUSH background_brush = NULL;
238#define VECTOR_COLOR RGB( 190, 0, 0) //DARK RED
239#define FOLDER_COLOR RGB( 0, 128, 0 ) // DARK GREEN
240#define PARENT_COLOR RGB( 190, 128, 192 ) // PURPLE
241#define GAME_COLOR RGB( 0, 128, 192 ) // DARK BLUE
242
243BOOL PropSheetFilter_Vector(const machine_config *drv, const game_driver *gamedrv)
244{
245   return (drv->video_attributes & VIDEO_TYPE_VECTOR) != 0;
246}
247
248/* Help IDs - moved to auto-generated helpids.c */
249extern const DWORD dwHelpIDs[];
250
251static struct ComboBoxVideo
252{
253   const TCHAR*   m_pText;
254   const char*      m_pData;
255} g_ComboBoxVideo[] =
256{
257   { TEXT("GDI"),                  "gdi"    },
258   { TEXT("DirectDraw"),           "ddraw"   },
259   { TEXT("Direct3D"),             "d3d"     },
260};
261#define NUMVIDEO (sizeof(g_ComboBoxVideo) / sizeof(g_ComboBoxVideo[0]))
262
263static struct ComboBoxD3DVersion
264{
265   const TCHAR*   m_pText;
266   const int      m_pData;
267} g_ComboBoxD3DVersion[] =
268{
269   { TEXT("Version 9"),           9   },
270   { TEXT("Version 8"),           8   },
271};
272
273#define NUMD3DVERSIONS (sizeof(g_ComboBoxD3DVersion) / sizeof(g_ComboBoxD3DVersion[0]))
274
275static struct ComboBoxSelectScreen
276{
277   const TCHAR*   m_pText;
278   const int      m_pData;
279} g_ComboBoxSelectScreen[] =
280{
281   { TEXT("Screen 0"),             0    },
282   { TEXT("Screen 1"),             1    },
283   { TEXT("Screen 2"),             2    },
284   { TEXT("Screen 3"),             3    },
285};
286#define NUMSELECTSCREEN (sizeof(g_ComboBoxSelectScreen) / sizeof(g_ComboBoxSelectScreen[0]))
287
288static struct ComboBoxView
289{
290   const TCHAR*   m_pText;
291   const char*      m_pData;
292} g_ComboBoxView[] =
293{
294   { TEXT("Auto"),              "auto"        },
295   { TEXT("Standard"),         "standard"    },
296   { TEXT("Pixel Aspect"),     "pixel"       },
297   { TEXT("Cocktail"),         "cocktail"    },
298};
299#define NUMVIEW (sizeof(g_ComboBoxView) / sizeof(g_ComboBoxView[0]))
300
301
302
303static struct ComboBoxDevices
304{
305   const TCHAR*   m_pText;
306   const char*    m_pData;
307} g_ComboBoxDevice[] =
308{
309   { TEXT("None"),                  "none"      },
310   { TEXT("Keyboard"),              "keyboard"  },
311   { TEXT("Mouse"),             "mouse"     },
312   { TEXT("Joystick"),              "joystick"  },
313   { TEXT("Lightgun"),              "lightgun"  },
314};
315
316#define NUMDEVICES (sizeof(g_ComboBoxDevice) / sizeof(g_ComboBoxDevice[0]))
317
318/***************************************************************
319 * Public functions
320 ***************************************************************/
321
322// Called by MESS, to avoid MESS specific hacks in properties.c
323int PropertiesCurrentGame(HWND hDlg)
324{
325   return g_nGame;
326}
327
328DWORD GetHelpIDs(void)
329{
330   return (DWORD) (LPSTR) dwHelpIDs;
331}
332
333// This function (and the code that use it) is a gross hack - but at least the vile
334// and disgusting global variables are gone, making it less gross than what came before
335static int GetSelectedScreen(HWND hWnd)
336{
337   int nSelectedScreen = 0;
338   HWND hCtrl = GetDlgItem(hWnd, IDC_SCREENSELECT);
339   if (hCtrl)
340      nSelectedScreen = ComboBox_GetCurSel(hCtrl);
341   if ((nSelectedScreen < 0) || (nSelectedScreen >= MAX_SCREENS))
342      nSelectedScreen = 0;
343   return nSelectedScreen;
344
345}
346
347static PROPSHEETPAGE *CreatePropSheetPages(HINSTANCE hInst, BOOL bOnlyDefault,
348   const game_driver *gamedrv, UINT *pnMaxPropSheets, BOOL isGame )
349{
350   PROPSHEETPAGE *pspages;
351   int maxPropSheets;
352   int possiblePropSheets;
353   int i;
354   machine_config drv;
355
356   if (gamedrv)
357       expand_machine_driver(gamedrv->drv, &drv);
358
359   i = ( isGame ) ? 0 : 2;
360
361   for (; g_propSheets[i].pfnDlgProc; i++)
362      ;
363
364   possiblePropSheets = (isGame) ? i + 1 : i - 1;
365
366   pspages = malloc(sizeof(PROPSHEETPAGE) * possiblePropSheets);
367   if (!pspages)
368      return NULL;
369
370   memset(pspages, 0, sizeof(PROPSHEETPAGE) * possiblePropSheets);
371
372   maxPropSheets = 0;
373   
374   i = ( isGame ) ? 0 : 2;
375
376   for (; g_propSheets[i].pfnDlgProc; i++)
377   {
378      if ((gamedrv != NULL) || g_propSheets[i].bOnDefaultPage)
379      {
380         if (!gamedrv || !g_propSheets[i].pfnFilterProc || g_propSheets[i].pfnFilterProc(&drv, gamedrv))
381         {
382            pspages[maxPropSheets].dwSize      = sizeof(PROPSHEETPAGE);
383            pspages[maxPropSheets].dwFlags     = 0;
384            pspages[maxPropSheets].hInstance   = hInst;
385            pspages[maxPropSheets].pszTemplate = MAKEINTRESOURCE(g_propSheets[i].dwDlgID);
386            pspages[maxPropSheets].pfnCallback = NULL;
387            pspages[maxPropSheets].lParam      = 0;
388            pspages[maxPropSheets].pfnDlgProc  = g_propSheets[i].pfnDlgProc;
389            maxPropSheets++;
390         }
391      }
392   }
393   
394   if (pnMaxPropSheets)
395      *pnMaxPropSheets = maxPropSheets;
396
397   return pspages;
398}
399
400void InitDefaultPropertyPage(HINSTANCE hInst, HWND hWnd)
401{
402   PROPSHEETHEADER pshead;
403   PROPSHEETPAGE   *pspage;
404
405   // clear globals
406   pCurrentOpts = NULL;
407
408   g_nGame = GLOBAL_OPTIONS;
409
410   /* Get default options to populate property sheets */
411   pCurrentOpts = load_options(OPTIONS_GLOBAL, g_nGame); //GetDefaultOptions(-1, FALSE);
412   pDefaultOpts = load_options(OPTIONS_GLOBAL, g_nGame);
413   g_bUseDefaults = FALSE;
414   /* Stash the result for comparing later */
415   pOrigOpts = CreateGameOptions(OPTIONS_TYPE_GLOBAL);
416   options_copy(pOrigOpts, pCurrentOpts);
417   orig_uses_defaults = FALSE;
418   g_bReset = FALSE;
419   g_nPropertyMode = OPTIONS_GLOBAL;
420   BuildDataMap();
421
422   ZeroMemory(&pshead, sizeof(pshead));
423
424   pspage = CreatePropSheetPages(hInst, TRUE, NULL, &pshead.nPages, FALSE);
425   if (!pspage)
426      return;
427
428   /* Fill in the property sheet header */
429   pshead.hwndParent   = hWnd;
430   pshead.dwSize       = sizeof(PROPSHEETHEADER);
431   pshead.dwFlags      = PSH_PROPSHEETPAGE | PSH_USEICONID | PSH_PROPTITLE;
432   pshead.hInstance    = hInst;
433   pshead.pszCaption   = TEXT("Default Game");
434   pshead.nStartPage   = 0;
435   pshead.pszIcon      = MAKEINTRESOURCE(IDI_MAME32_ICON);
436   pshead.ppsp         = pspage;
437
438   /* Create the Property sheet and display it */
439   if (PropertySheet(&pshead) == -1)
440   {
441      char temp[100];
442      DWORD dwError = GetLastError();
443      sprintf(temp, "Propery Sheet Error %d %X", (int)dwError, (int)dwError);
444      win_message_box_utf8(0, temp, "Error", IDOK);
445   }
446
447   free(pspage);
448}
449
450/* Initilize the property pages for anything but the Default option set */
451void InitPropertyPage(HINSTANCE hInst, HWND hWnd, HICON hIcon, OPTIONS_TYPE opt_type, int folder_id, int game_num)
452{
453   InitPropertyPageToPage(hInst, hWnd, hIcon, opt_type, folder_id, game_num, PROPERTIES_PAGE);
454}
455
456void InitPropertyPageToPage(HINSTANCE hInst, HWND hWnd, HICON hIcon, OPTIONS_TYPE opt_type, int folder_id, int game_num, int start_page )
457{
458   PROPSHEETHEADER pshead;
459   PROPSHEETPAGE   *pspage;
460   TCHAR*          t_description = 0;
461   OPTIONS_TYPE    default_type = opt_type;
462   
463   if (highlight_brush == NULL)
464      highlight_brush = CreateSolidBrush(HIGHLIGHT_COLOR);
465
466   if (background_brush == NULL)
467      background_brush = CreateSolidBrush(GetSysColor(COLOR_3DFACE));
468
469   // Initialize the options
470
471   // Load the current options, this will pickup the highest priority option set.
472   pCurrentOpts = load_options(opt_type, game_num);
473
474   // Load the default options, pickup the next lower options set than the current level.
475   if (opt_type > OPTIONS_GLOBAL)
476   {
477      default_type -= 1;
478   }
479   pDefaultOpts = load_options(default_type, game_num);
480
481   // Copy current_options to original options
482   pOrigOpts = CreateGameOptions(OPTIONS_TYPE_GLOBAL);
483   options_copy(pOrigOpts, pCurrentOpts);
484
485   // Copy icon to use for the property pages
486   g_hIcon = CopyIcon(hIcon);
487
488   // These MUST be valid, they are used as indicies
489   g_nGame = game_num;
490   g_nFolder = folder_id;
491
492   // Keep track of OPTIONS_TYPE that was passed in.
493   g_nPropertyMode = opt_type;
494
495   // Evaluate if the current set uses the Default set
496   g_bUseDefaults = options_equal(pCurrentOpts, pDefaultOpts);
497   g_bReset = FALSE;
498   BuildDataMap();
499
500   ZeroMemory(&pshead, sizeof(PROPSHEETHEADER));
501
502   // Set the game to audio to this game
503   InitGameAudit(game_num);
504
505   // Create the propery sheets
506   if( OPTIONS_GAME == opt_type )
507   {
508      pspage = CreatePropSheetPages(hInst, FALSE, drivers[game_num], &pshead.nPages, TRUE);
509   }
510   else
511   {
512      pspage = CreatePropSheetPages(hInst, FALSE, NULL, &pshead.nPages, FALSE);
513   }
514   if (!pspage)
515      return;
516
517
518   // Get the description use as the dialog caption.
519   switch( opt_type )
520   {
521   case OPTIONS_GAME:
522      t_description = tstring_from_utf8(ModifyThe(drivers[g_nGame]->description));
523      break;
524   case OPTIONS_VECTOR:
525   case OPTIONS_SOURCE:
526      t_description = tstring_from_utf8(GetFolderNameByID(g_nFolder));
527      break;
528   case OPTIONS_GLOBAL:
529      t_description = tstring_from_utf8("Default Settings");
530      break;
531   default:
532      return;
533   }
534   // If we have no descrption, return.
535   if( !t_description )
536      return;
537
538   /* Fill in the property sheet header */
539   pshead.pszCaption = t_description;
540   pshead.hwndParent = hWnd;
541   pshead.dwSize     = sizeof(PROPSHEETHEADER);
542   pshead.dwFlags    = PSH_PROPSHEETPAGE | PSH_USEICONID | PSH_PROPTITLE;
543   pshead.hInstance  = hInst;
544   pshead.nStartPage = start_page;
545   pshead.pszIcon    = MAKEINTRESOURCE(IDI_MAME32_ICON);
546   pshead.ppsp       = pspage;
547
548   /* Create the Property sheet and display it */
549   if (PropertySheet(&pshead) == -1)
550   {
551      char temp[100];
552      DWORD dwError = GetLastError();
553      sprintf(temp, "Propery Sheet Error %d %X", (int)dwError, (int)dwError);
554      win_message_box_utf8(0, temp, "Error", IDOK);
555   }
556
557   free(t_description);
558   free(pspage);
559}
560
561
562/*********************************************************************
563 * Local Functions
564 *********************************************************************/
565
566/* Build CPU info string */
567static char *GameInfoCPU(UINT nIndex)
568{
569   int i;
570   static char buf[1024] = "";
571   machine_config drv;
572   expand_machine_driver(drivers[nIndex]->drv,&drv);
573
574   ZeroMemory(buf, sizeof(buf));
575
576   cpuintrf_init(NULL);
577
578   i = 0;
579   while (i < MAX_CPU && drv.cpu[i].cpu_type)
580   {
581      if (drv.cpu[i].cpu_clock >= 1000000)
582         sprintf(&buf[strlen(buf)], "%s %d.%06d MHz",
583               cputype_name(drv.cpu[i].cpu_type),
584               drv.cpu[i].cpu_clock / 1000000,
585               drv.cpu[i].cpu_clock % 1000000);
586      else
587         sprintf(&buf[strlen(buf)], "%s %d.%03d kHz",
588               cputype_name(drv.cpu[i].cpu_type),
589               drv.cpu[i].cpu_clock / 1000,
590               drv.cpu[i].cpu_clock % 1000);
591
592      strcat(buf, "\n");
593
594      i++;
595    }
596
597   return buf;
598}
599
600/* Build Sound system info string */
601static char *GameInfoSound(UINT nIndex)
602{
603   int i;
604   static char buf[1024];
605   machine_config drv;
606   expand_machine_driver(drivers[nIndex]->drv,&drv);
607
608   buf[0] = 0;
609
610   i = 0;
611   while (i < MAX_SOUND && drv.sound[i].sound_type)
612   {
613      int clock,sound_type,count;
614
615      sound_type = drv.sound[i].sound_type;
616      clock = drv.sound[i].clock;
617
618      count = 1;
619      i++;
620
621      while (i < MAX_SOUND
622            && drv.sound[i].sound_type == sound_type
623            && drv.sound[i].clock == clock)
624      {
625         count++;
626         i++;
627      }
628
629      if (count > 1)
630         sprintf(&buf[strlen(buf)],"%dx",count);
631
632      sprintf(&buf[strlen(buf)],"%s",sndtype_name(sound_type));
633
634      if (clock)
635      {
636         if (clock >= 1000000)
637            sprintf(&buf[strlen(buf)]," %d.%06d MHz",
638                  clock / 1000000,
639                  clock % 1000000);
640         else
641            sprintf(&buf[strlen(buf)]," %d.%03d kHz",
642                  clock / 1000,
643                  clock % 1000);
644      }
645
646      strcat(buf,"\n");
647   }
648
649   return buf;
650}
651
652/* Build Display info string */
653static char *GameInfoScreen(UINT nIndex)
654{
655   static char buf[1024];
656   machine_config drv;
657   expand_machine_driver(drivers[nIndex]->drv,&drv);
658
659   if (drv.video_attributes & VIDEO_TYPE_VECTOR)
660      strcpy(buf, "Vector Game");
661   else
662   {
663      if (drivers[nIndex]->flags & ORIENTATION_SWAP_XY)
664         sprintf(buf,"%d x %d (V) %f Hz",
665         drv.screen[0].defstate.visarea.max_y - drv.screen[0].defstate.visarea.min_y + 1,
666               drv.screen[0].defstate.visarea.max_x - drv.screen[0].defstate.visarea.min_x + 1,
667               SUBSECONDS_TO_HZ(drv.screen[0].defstate.refresh));
668      else
669         sprintf(buf,"%d x %d (H) %f Hz",
670               drv.screen[0].defstate.visarea.max_x - drv.screen[0].defstate.visarea.min_x + 1,
671               drv.screen[0].defstate.visarea.max_y - drv.screen[0].defstate.visarea.min_y + 1,
672               SUBSECONDS_TO_HZ(drv.screen[0].defstate.refresh));
673   }
674   return buf;
675}
676
677/* Build color information string */
678static char *GameInfoColors(UINT nIndex)
679{
680   static char buf[1024];
681   machine_config drv;
682   expand_machine_driver(drivers[nIndex]->drv,&drv);
683
684   ZeroMemory(buf, sizeof(buf));
685   sprintf(buf, "%d colors ", drv.total_colors);
686
687   return buf;
688}
689
690/* Build game status string */
691const char *GameInfoStatus(int driver_index, BOOL bRomStatus)
692{
693   static char buffer[1024];
694   int audit_result = GetRomAuditResults(driver_index);
695   memset(buffer,0,sizeof(char)*1024);
696   if ( bRomStatus )
697    {
698      if (IsAuditResultKnown(audit_result) == FALSE)
699       {
700         strcpy(buffer, "Unknown");
701      }
702      else if (IsAuditResultYes(audit_result))
703      {
704         if (DriverIsBroken(driver_index))
705          {
706            strcpy(buffer, "Not working");
707           
708            if (drivers[driver_index]->flags & GAME_UNEMULATED_PROTECTION)
709            {
710               if (*buffer != '\0')
711                  strcat(buffer, "\r\n");
712               strcat(buffer, "Game protection isn't fully emulated");
713            }
714            if (drivers[driver_index]->flags & GAME_WRONG_COLORS)
715            {
716               if (*buffer != '\0')
717                  strcat(buffer, "\r\n");
718               strcat(buffer, "Colors are completely wrong");
719            }
720            if (drivers[driver_index]->flags & GAME_IMPERFECT_COLORS)
721            {
722               if (*buffer != '\0')
723                  strcat(buffer, "\r\n");
724               strcat(buffer, "Colors aren't 100% accurate");
725            }
726            if (drivers[driver_index]->flags & GAME_IMPERFECT_GRAPHICS)
727            {
728               if (*buffer != '\0')
729                  strcat(buffer, "\r\n");
730               strcat(buffer, "Video emulation isn't 100% accurate");
731            }
732            if (drivers[driver_index]->flags & GAME_NO_SOUND)
733            {
734               if (*buffer != '\0')
735                  strcat(buffer, "\r\n");
736               strcat(buffer, "Game lacks sound");
737            }
738            if (drivers[driver_index]->flags & GAME_IMPERFECT_SOUND)
739            {
740               if (*buffer != '\0')
741                  strcat(buffer, "\r\n");
742               strcat(buffer, "Sound emulation isn't 100% accurate");
743            }
744            if (drivers[driver_index]->flags & GAME_NO_COCKTAIL)
745            {
746               if (*buffer != '\0')
747                  strcat(buffer, "\r\n");
748               strcat(buffer, "Screen flipping is not supported");
749            }
750          }
751         else
752         {
753            strcpy(buffer, "Working");
754           
755            if (drivers[driver_index]->flags & GAME_UNEMULATED_PROTECTION)
756            {
757               if (*buffer != '\0')
758                  strcat(buffer, "\r\n");
759               strcat(buffer, "Game protection isn't fully emulated");
760            }
761            if (drivers[driver_index]->flags & GAME_WRONG_COLORS)
762            {
763               if (*buffer != '\0')
764                  strcat(buffer, "\r\n");
765               strcat(buffer, "Colors are completely wrong");
766            }
767            if (drivers[driver_index]->flags & GAME_IMPERFECT_COLORS)
768            {
769               if (*buffer != '\0')
770                  strcat(buffer, "\r\n");
771               strcat(buffer, "Colors aren't 100% accurate");
772            }
773            if (drivers[driver_index]->flags & GAME_IMPERFECT_GRAPHICS)
774            {
775               if (*buffer != '\0')
776                  strcat(buffer, "\r\n");
777               strcat(buffer, "Video emulation isn't 100% accurate");
778            }
779            if (drivers[driver_index]->flags & GAME_NO_SOUND)
780            {
781               if (*buffer != '\0')
782                  strcat(buffer, "\r\n");
783               strcat(buffer, "Game lacks sound");
784            }
785            if (drivers[driver_index]->flags & GAME_IMPERFECT_SOUND)
786            {
787               if (*buffer != '\0')
788                  strcat(buffer, "\r\n");
789               strcat(buffer, "Sound emulation isn't 100% accurate");
790            }
791            if (drivers[driver_index]->flags & GAME_NO_COCKTAIL)
792            {
793               if (*buffer != '\0')
794                  strcat(buffer, "\r\n");
795               strcat(buffer, "Screen flipping is not supported");
796            }
797         }
798      }
799      else
800      {
801         // audit result is no
802   #ifdef MESS
803         strcpy(buffer, "BIOS missing");
804   #else
805         strcpy(buffer, "ROMs missing");
806   #endif
807      }
808   }
809   else
810   {
811      //Just show the emulation flags
812      if (DriverIsBroken(driver_index))
813      {
814         strcpy(buffer, "Not working");
815      }
816      else
817      {
818         strcpy(buffer, "Working");
819      }   
820      if (drivers[driver_index]->flags & GAME_UNEMULATED_PROTECTION)
821      {
822         if (*buffer != '\0')
823            strcat(buffer, "\r\n");
824         strcat(buffer, "Game protection isn't fully emulated");
825      }
826      if (drivers[driver_index]->flags & GAME_WRONG_COLORS)
827      {
828      if (*buffer != '\0')
829            strcat(buffer, "\r\n");
830         strcat(buffer, "Colors are completely wrong");
831      }
832      if (drivers[driver_index]->flags & GAME_IMPERFECT_COLORS)
833      {
834         if (*buffer != '\0')
835            strcat(buffer, "\r\n");
836         strcat(buffer, "Colors aren't 100% accurate");
837      }
838      if (drivers[driver_index]->flags & GAME_IMPERFECT_GRAPHICS)
839      {
840         if (*buffer != '\0')
841            strcat(buffer, "\r\n");
842         strcat(buffer, "Video emulation isn't 100% accurate");
843      }
844      if (drivers[driver_index]->flags & GAME_NO_SOUND)
845      {
846         if (*buffer != '\0')
847            strcat(buffer, "\r\n");
848         strcat(buffer, "Game lacks sound");
849      }
850      if (drivers[driver_index]->flags & GAME_IMPERFECT_SOUND)
851      {
852         if (*buffer != '\0')
853            strcat(buffer, "\r\n");
854         strcat(buffer, "Sound emulation isn't 100% accurate");
855      }
856      if (drivers[driver_index]->flags & GAME_NO_COCKTAIL)
857      {
858         if (*buffer != '\0')
859            strcat(buffer, "\r\n");
860         strcat(buffer, "Screen flipping is not supported");
861      }
862   }
863   return buffer;
864}
865
866/* Build game manufacturer string */
867static char *GameInfoManufactured(UINT nIndex)
868{
869   static char buffer[1024];
870
871   snprintf(buffer,sizeof(buffer),"%s %s",drivers[nIndex]->year,drivers[nIndex]->manufacturer);
872   return buffer;
873}
874
875/* Build Game title string */
876char *GameInfoTitle(OPTIONS_TYPE opt_type, UINT nIndex)
877{
878   static char buf[1024];
879
880   if (OPTIONS_GLOBAL == opt_type)
881      strcpy(buf, "Global game options\nDefault options used by all games");
882   else if (OPTIONS_SOURCE == opt_type || OPTIONS_VECTOR == opt_type)
883      strcpy(buf, "Global folder options\nDefault options used by all games in the folder");
884   else
885      sprintf(buf, "%s\n\"%s\"", ModifyThe(drivers[nIndex]->description), drivers[nIndex]->name);
886   return buf;
887}
888
889/* Build game clone infromation string */
890static char *GameInfoCloneOf(UINT nIndex)
891{
892   static char buf[1024];
893   int nParentIndex= -1;
894
895   buf[0] = '\0';
896
897   if (DriverIsClone(nIndex))
898   {
899      nParentIndex = GetParentIndex(drivers[nIndex]);
900      sprintf(buf, "%s - \"%s\"",
901         ConvertAmpersandString(ModifyThe(drivers[nParentIndex]->description)),
902         drivers[nParentIndex]->name);
903   }
904
905   return buf;
906}
907
908static const char * GameInfoSource(UINT nIndex)
909{
910   return GetDriverFilename(nIndex);
911}
912
913/* Handle the information property page */
914INT_PTR CALLBACK GamePropertiesDialogProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam)
915{
916HWND hWnd;
917   switch (Msg)
918   {
919   case WM_INITDIALOG:
920      if (g_hIcon)
921         SendDlgItemMessage(hDlg, IDC_GAME_ICON, STM_SETICON, (WPARAM) g_hIcon, 0);
922#if defined(USE_SINGLELINE_TABCONTROL)
923      {
924         HWND hWnd = PropSheet_GetTabControl(GetParent(hDlg));
925         DWORD tabStyle = (GetWindowLong(hWnd,GWL_STYLE) & ~TCS_MULTILINE);
926         SetWindowLong(hWnd,GWL_STYLE,tabStyle | TCS_SINGLELINE);
927      }
928#endif
929
930      win_set_window_text_utf8(GetDlgItem(hDlg, IDC_PROP_TITLE),         GameInfoTitle(g_nPropertyMode, g_nGame));
931      win_set_window_text_utf8(GetDlgItem(hDlg, IDC_PROP_MANUFACTURED),  GameInfoManufactured(g_nGame));
932      win_set_window_text_utf8(GetDlgItem(hDlg, IDC_PROP_STATUS),        GameInfoStatus(g_nGame, FALSE));
933      win_set_window_text_utf8(GetDlgItem(hDlg, IDC_PROP_CPU),           GameInfoCPU(g_nGame));
934      win_set_window_text_utf8(GetDlgItem(hDlg, IDC_PROP_SOUND),         GameInfoSound(g_nGame));
935      win_set_window_text_utf8(GetDlgItem(hDlg, IDC_PROP_SCREEN),        GameInfoScreen(g_nGame));
936      win_set_window_text_utf8(GetDlgItem(hDlg, IDC_PROP_COLORS),        GameInfoColors(g_nGame));
937      win_set_window_text_utf8(GetDlgItem(hDlg, IDC_PROP_CLONEOF),       GameInfoCloneOf(g_nGame));
938      win_set_window_text_utf8(GetDlgItem(hDlg, IDC_PROP_SOURCE),        GameInfoSource(g_nGame));
939     
940      if (DriverIsClone(g_nGame))
941      {
942         ShowWindow(GetDlgItem(hDlg, IDC_PROP_CLONEOF_TEXT), SW_SHOW);
943      }
944      else
945      {
946         ShowWindow(GetDlgItem(hDlg, IDC_PROP_CLONEOF_TEXT), SW_HIDE);
947      }
948      hWnd = PropSheet_GetTabControl(GetParent(hDlg));
949      UpdateBackgroundBrush(hWnd);
950      ShowWindow(hDlg, SW_SHOW);
951      return 1;
952
953   }
954    return 0;
955}
956
957/* Handle all options property pages */
958INT_PTR CALLBACK GameOptionsProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam)
959{
960//   RECT rc;
961//   int nParentIndex = -1;
962   switch (Msg)
963   {
964   case WM_INITDIALOG:
965      /* Fill in the Game info at the top of the sheet */
966      win_set_window_text_utf8(GetDlgItem(hDlg, IDC_PROP_TITLE), GameInfoTitle(g_nPropertyMode, g_nGame));
967      InitializeOptions(hDlg);
968      InitializeMisc(hDlg);
969
970      UpdateProperties(hDlg, properties_datamap, pCurrentOpts);
971
972      g_bUseDefaults = options_equal(pCurrentOpts, pDefaultOpts);
973      g_bReset = options_equal(pCurrentOpts, pOrigOpts) ? FALSE : TRUE;
974
975      if (g_nGame == GLOBAL_OPTIONS)
976         ShowWindow(GetDlgItem(hDlg, IDC_USE_DEFAULT), SW_HIDE);
977      else
978         EnableWindow(GetDlgItem(hDlg, IDC_USE_DEFAULT), (g_bUseDefaults) ? FALSE : TRUE);
979#ifndef _DEBUG
980      ShowWindow(GetDlgItem(hDlg, IDC_DEBUG), SW_HIDE);
981#endif
982      EnableWindow(GetDlgItem(hDlg, IDC_PROP_RESET), g_bReset);
983      ShowWindow(hDlg, SW_SHOW);
984   
985      return 1;
986
987   case WM_HSCROLL:
988      /* slider changed */
989      HANDLE_WM_HSCROLL(hDlg, wParam, lParam, OptOnHScroll);
990      //g_bUseDefaults = FALSE;
991      //g_bReset = TRUE;
992      EnableWindow(GetDlgItem(hDlg, IDC_USE_DEFAULT), TRUE);
993      PropSheet_Changed(GetParent(hDlg), hDlg);
994
995      // make sure everything's copied over, to determine what's changed
996      UpdateOptions(hDlg, properties_datamap, pCurrentOpts);
997
998      // redraw it, it might be a new color now
999      InvalidateRect((HWND)lParam,NULL,TRUE);
1000
1001      break;
1002
1003   case WM_COMMAND:
1004      {
1005         /* Below, 'changed' is used to signify the 'Apply'
1006          * button should be enabled.
1007          */
1008         WORD wID         = GET_WM_COMMAND_ID(wParam, lParam);
1009         HWND hWndCtrl    = GET_WM_COMMAND_HWND(wParam, lParam);
1010         WORD wNotifyCode = GET_WM_COMMAND_CMD(wParam, lParam);
1011         BOOL changed     = FALSE;
1012         int nCurSelection = 0;
1013         TCHAR szClass[256];
1014
1015         switch (wID)
1016         {
1017         case IDC_REFRESH:
1018            if (wNotifyCode == LBN_SELCHANGE)
1019            {
1020               RefreshSelectionChange(hDlg, hWndCtrl);
1021               changed = TRUE;
1022            }
1023            break;
1024
1025         case IDC_ASPECT:
1026            nCurSelection = Button_GetCheck( GetDlgItem(hDlg, IDC_ASPECT));
1027            if( g_bAutoAspect[GetSelectedScreen(hDlg)] != nCurSelection )
1028            {
1029               changed = TRUE;
1030               g_bAutoAspect[GetSelectedScreen(hDlg)] = nCurSelection;
1031            }
1032            break;
1033
1034         case IDC_SELECT_EFFECT:
1035            changed = SelectEffect(hDlg);
1036            break;
1037
1038         case IDC_RESET_EFFECT:
1039            changed = ResetEffect(hDlg);
1040            break;
1041
1042         case IDC_PROP_RESET:
1043            if (wNotifyCode != BN_CLICKED)
1044               break;
1045
1046            options_copy(pCurrentOpts, pOrigOpts);
1047            UpdateProperties(hDlg, properties_datamap, pCurrentOpts);
1048
1049            g_bUseDefaults = options_equal(pCurrentOpts, pDefaultOpts);
1050            g_bReset = FALSE;
1051            PropSheet_UnChanged(GetParent(hDlg), hDlg);
1052            EnableWindow(GetDlgItem(hDlg, IDC_USE_DEFAULT), (g_bUseDefaults) ? FALSE : TRUE);
1053            break;
1054
1055         case IDC_USE_DEFAULT:
1056            // Copy the pDefaultOpts into pCurrentOpts
1057            options_copy(pCurrentOpts, pDefaultOpts);
1058            // repopulate the controls with the new data
1059            UpdateProperties(hDlg, properties_datamap, pCurrentOpts);
1060           
1061            g_bUseDefaults = options_equal(pCurrentOpts, pDefaultOpts);
1062            // This evaluates properly
1063            g_bReset = options_equal(pCurrentOpts, pOrigOpts) ? FALSE : TRUE;
1064            // Enable/Dispable the Reset to Defaults button
1065            EnableWindow(GetDlgItem(hDlg, IDC_USE_DEFAULT), (g_bUseDefaults) ? FALSE : TRUE);
1066            // Tell the dialog to enable/disable the apply button.
1067            if (g_nGame != GLOBAL_OPTIONS)
1068            {
1069               if (g_bReset)
1070               {
1071                  PropSheet_Changed(GetParent(hDlg), hDlg);
1072               }
1073               else
1074               {
1075                  PropSheet_UnChanged(GetParent(hDlg), hDlg);
1076               }
1077            }
1078            break;
1079
1080            // MSH 20070813 - Update all related controls
1081         case IDC_SCREENSELECT:
1082         case IDC_SCREEN:
1083            // NPW 3-Apr-2007:  Ugh I'm only perpetuating the vile hacks in this code
1084            if ((wNotifyCode == CBN_SELCHANGE) || (wNotifyCode == CBN_SELENDOK))
1085            {
1086               changed = datamap_read_control(properties_datamap, hDlg, pCurrentOpts, wID);
1087               datamap_populate_control(properties_datamap, hDlg, pCurrentOpts, IDC_SIZES);
1088               //MSH 20070814 - Hate to do this, but its either this, or update each individual
1089               // control on the SCREEN tab.
1090               UpdateProperties(hDlg, properties_datamap, pCurrentOpts);
1091               changed = TRUE;
1092               /*
1093               datamap_populate_control(properties_datamap, hDlg, pCurrentOpts, IDC_SCREENSELECT);
1094               datamap_populate_control(properties_datamap, hDlg, pCurrentOpts, IDC_SCREEN);
1095               datamap_populate_control(properties_datamap, hDlg, pCurrentOpts, IDC_REFRESH);
1096               datamap_populate_control(properties_datamap, hDlg, pCurrentOpts, IDC_SIZES);
1097               datamap_populate_control(properties_datamap, hDlg, pCurrentOpts, IDC_VIEW);
1098               datamap_populate_control(properties_datamap, hDlg, pCurrentOpts, IDC_SWITCHRES);
1099
1100               if (strcmp(options_get_string(pCurrentOpts, "screen0"), options_get_string(pOrigOpts, "screen0")) ||
1101                  strcmp(options_get_string(pCurrentOpts, "screen1"), options_get_string(pOrigOpts, "screen1")) ||
1102                  strcmp(options_get_string(pCurrentOpts, "screen2"), options_get_string(pOrigOpts, "screen2")) ||
1103                  strcmp(options_get_string(pCurrentOpts, "screen3"), options_get_string(pOrigOpts, "screen3")))
1104               {
1105                  changed = TRUE;
1106               }
1107               */
1108            }
1109            break;
1110         default:
1111#ifdef MESS
1112            if (MessPropertiesCommand(hDlg, wNotifyCode, wID, &changed))
1113               break;
1114#endif // MESS
1115
1116            // use default behavior; try to get the result out of the datamap if
1117            // appropriate
1118            GetClassName(hWndCtrl, szClass, ARRAY_LENGTH(szClass));
1119            if (!_tcscmp(szClass, WC_COMBOBOX))
1120            {
1121               // combo box
1122               if ((wNotifyCode == CBN_SELCHANGE) || (wNotifyCode == CBN_SELENDOK))
1123               {
1124                   changed = datamap_read_control(properties_datamap, hDlg, pCurrentOpts, wID);
1125               }
1126            }
1127            else if (!_tcscmp(szClass, WC_BUTTON) && (GetWindowLong(hWndCtrl, GWL_STYLE) & BS_CHECKBOX))
1128            {
1129               // check box
1130               changed = datamap_read_control(properties_datamap, hDlg, pCurrentOpts, wID);
1131            }
1132            break;
1133         }
1134
1135         if (changed == TRUE)
1136         {
1137            // make sure everything's copied over, to determine what's changed
1138            UpdateOptions(hDlg, properties_datamap, pCurrentOpts);
1139            // enable the apply button
1140            PropSheet_Changed(GetParent(hDlg), hDlg);
1141            g_bUseDefaults = options_equal(pCurrentOpts, pDefaultOpts);
1142            g_bReset = options_equal(pCurrentOpts, pOrigOpts) ? FALSE : TRUE;
1143            EnableWindow(GetDlgItem(hDlg, IDC_USE_DEFAULT), (g_bUseDefaults) ? FALSE : TRUE);
1144         }
1145
1146         // If we are closing, pCurrentOpts may be null
1147         if (NULL != pCurrentOpts)
1148         {
1149            // make sure everything's copied over, to determine what's changed
1150            UpdateOptions(hDlg, properties_datamap, pCurrentOpts);
1151            SetPropEnabledControls(hDlg);
1152            // redraw it, it might be a new color now
1153            if (GetDlgItem(hDlg,wID))
1154               InvalidateRect(GetDlgItem(hDlg,wID),NULL,FALSE);
1155         }
1156      }
1157      break;
1158
1159   case WM_NOTIFY:
1160      {
1161         // Set to true if we are exiting the properites dialog
1162         BOOL bClosing = ((LPPSHNOTIFY) lParam)->lParam;
1163
1164         switch (((NMHDR *) lParam)->code)
1165         {
1166            //We'll need to use a CheckState Table
1167            //Because this one gets called for all kinds of other things too, and not only if a check is set
1168         case PSN_SETACTIVE:
1169            /* Initialize the controls. */
1170            UpdateProperties(hDlg, properties_datamap, pCurrentOpts);
1171            g_bUseDefaults = options_equal(pCurrentOpts, pDefaultOpts);
1172            g_bReset = options_equal(pCurrentOpts, pOrigOpts) ? FALSE : TRUE;
1173
1174            // Sync RESET TO DEFAULTS buttons.
1175            EnableWindow(GetDlgItem(hDlg, IDC_USE_DEFAULT), (g_bUseDefaults) ? FALSE : TRUE);
1176            break;
1177
1178         case PSN_APPLY:
1179            // Handle more than one PSN_APPLY, since this proc handles more tha one
1180            // property sheet and can be called multiple times when it's time to exit,
1181            // and we may have already freed the core_options.
1182            if (bClosing)
1183            {
1184               if (NULL == pCurrentOpts)
1185                  return TRUE;
1186            }
1187
1188            // Read the datamap
1189            UpdateOptions(hDlg, properties_datamap, pCurrentOpts);
1190
1191            // Copy current options to orignal options.
1192            options_copy(pOrigOpts, pCurrentOpts);
1193           
1194            // Repopulate the controls?  WTF?  We just read them, they should be fine.
1195            UpdateProperties(hDlg, properties_datamap, pCurrentOpts);
1196
1197            // Determine button states.
1198            g_bUseDefaults = options_equal(pCurrentOpts, pDefaultOpts);
1199            g_bReset = FALSE;
1200
1201            orig_uses_defaults = g_bUseDefaults;
1202
1203            // Sync RESET and RESET TO DEFAULTS buttons.
1204            EnableWindow(GetDlgItem(hDlg, IDC_USE_DEFAULT), (g_bUseDefaults) ? FALSE : TRUE);
1205            EnableWindow(GetDlgItem(hDlg, IDC_PROP_RESET), g_bReset);
1206
1207            // Save or remove the current options
1208            save_options(g_nPropertyMode, (g_bUseDefaults) ? NULL : pCurrentOpts, g_nGame);
1209
1210            // Disable apply button
1211            PropSheet_UnChanged(GetParent(hDlg), hDlg);
1212            SetWindowLong(hDlg, DWL_MSGRESULT, PSNRET_NOERROR);
1213
1214            // If we a closing, free the core_options
1215            if (bClosing)
1216            {
1217               if (pCurrentOpts) options_free(pCurrentOpts);
1218               if (pOrigOpts)    options_free(pOrigOpts);
1219               if (pDefaultOpts) options_free(pDefaultOpts);
1220               pCurrentOpts = pOrigOpts = pDefaultOpts = NULL;
1221            }
1222            return TRUE;
1223
1224         case PSN_KILLACTIVE:
1225            /* Save Changes to the options here. */
1226            UpdateOptions(hDlg, properties_datamap, pCurrentOpts);
1227            // Determine button states.
1228            g_bUseDefaults = options_equal(pCurrentOpts, pDefaultOpts);
1229
1230            ResetDataMap(hDlg);
1231            SetWindowLong(hDlg, DWL_MSGRESULT, FALSE);
1232            return 1; 
1233
1234         case PSN_RESET:
1235            // Reset to the original values. Disregard changes
1236            options_copy(pCurrentOpts, pOrigOpts);
1237            SetWindowLong(hDlg, DWL_MSGRESULT, FALSE);
1238            break;
1239
1240         case PSN_HELP:
1241            // User wants help for this property page
1242            break;
1243         }
1244      }
1245      break;
1246#if 0
1247   /* FIXME - Not sure what to do here. */
1248   case WM_CTLCOLORSTATIC :
1249   case WM_CTLCOLOREDIT :
1250     
1251      if( g_nGame >= 0 )
1252      {
1253         if( DriverIsClone(g_nGame) )
1254         {
1255            nParentIndex = GetParentIndex( drivers[g_nGame] );
1256         }
1257      }
1258      //Set the Coloring of the elements
1259      if (GetWindowLong((HWND)lParam, GWL_ID) < 0)
1260         break;
1261      if (IsControlOptionValue(hDlg,(HWND)lParam, GetDefaultOptions( -1, FALSE) ) )
1262      {
1263         //Normal Black case
1264         SetTextColor((HDC)wParam,COLOR_WINDOWTEXT);
1265      }
1266      else if (IsControlOptionValue(hDlg,(HWND)lParam, GetVectorOptions() )  && DriverIsVector(g_nFolderGame) )
1267      {
1268         SetTextColor((HDC)wParam,VECTOR_COLOR);
1269      }
1270      else if (IsControlOptionValue(hDlg,(HWND)lParam, GetSourceOptions(g_nFolderGame ) ) )
1271      {
1272         SetTextColor((HDC)wParam,FOLDER_COLOR);
1273      }
1274      else if ((nParentIndex >=0) && (IsControlOptionValue(hDlg,(HWND)lParam, GetGameOptions(nParentIndex, g_nFolder ) ) ) )
1275      {
1276         SetTextColor((HDC)wParam,PARENT_COLOR);
1277      }
1278//      else if ( (g_nGame >= 0) && (IsControlOptionValue(hDlg,(HWND)lParam, GetGameOptions(g_nGame, g_nFolder) ) ) )
1279      else if ( (g_nGame >= 0) && (IsControlOptionValue(hDlg,(HWND)lParam, pOrigOpts ) ) )
1280      {
1281         SetTextColor((HDC)wParam,GAME_COLOR);
1282      }
1283      else
1284      {
1285         switch ( g_nPropertyMode )
1286         {
1287            case OPTIONS_GAME:
1288               SetTextColor((HDC)wParam,GAME_COLOR);
1289               break;
1290            case OPTIONS_SOURCE:
1291               SetTextColor((HDC)wParam,FOLDER_COLOR);
1292               break;
1293            case OPTIONS_VECTOR:
1294               SetTextColor((HDC)wParam,VECTOR_COLOR);
1295               break;
1296            default:
1297            case OPTIONS_GLOBAL:
1298               SetTextColor((HDC)wParam,COLOR_WINDOWTEXT);
1299               break;
1300         }
1301      }
1302      if( Msg == WM_CTLCOLORSTATIC )
1303      {
1304         if (SafeIsAppThemed())
1305         {
1306            HWND hWnd = PropSheet_GetTabControl(GetParent(hDlg));
1307            // Set the background mode to transparent
1308            SetBkMode((HDC)wParam, TRANSPARENT);
1309
1310            // Get the controls window dimensions
1311            GetWindowRect((HWND)lParam, &rc);
1312
1313            // Map the coordinates to coordinates with the upper left corner of dialog control as base
1314            MapWindowPoints(NULL, hWnd, (LPPOINT)(&rc), 2);
1315
1316            // Adjust the position of the brush for this control (else we see the top left of the brush as background)
1317            SetBrushOrgEx((HDC)wParam, -rc.left, -rc.top, NULL);
1318
1319            // Return the brush
1320            return (INT_PTR)(hBkBrush);
1321         }
1322         else
1323         {
1324            SetBkColor((HDC) wParam,GetSysColor(COLOR_3DFACE) );
1325         }
1326      }
1327      else
1328         SetBkColor((HDC)wParam,RGB(255,255,255) );
1329      UnrealizeObject(background_brush);
1330      return (DWORD)background_brush;
1331      break;
1332#endif // 0 Not sure what to do here
1333
1334   case WM_HELP:
1335      /* User clicked the ? from the upper right on a control */
1336      HelpFunction(((LPHELPINFO)lParam)->hItemHandle, MAME32CONTEXTHELP, HH_TP_HELP_WM_HELP, GetHelpIDs());
1337      break;
1338
1339   case WM_CONTEXTMENU:
1340      HelpFunction((HWND)wParam, MAME32CONTEXTHELP, HH_TP_HELP_CONTEXTMENU, GetHelpIDs());
1341      break;
1342
1343   }
1344   EnableWindow(GetDlgItem(hDlg, IDC_PROP_RESET), g_bReset);
1345
1346   return 0;
1347}
1348
1349/* Read controls that are not handled in the DataMap */
1350static void PropToOptions(HWND hWnd, core_options *o)
1351{
1352   HWND hCtrl;
1353   HWND hCtrl2;
1354   HWND hCtrl3;
1355
1356   // It appears these are here to clear the global struct we are removing!
1357   // FIXME
1358   //if (g_nGame > -1)
1359   //   SetGameUsesDefaults(g_nGame,g_bUseDefaults);
1360
1361   /* aspect ratio */
1362   hCtrl  = GetDlgItem(hWnd, IDC_ASPECTRATION);
1363   hCtrl2 = GetDlgItem(hWnd, IDC_ASPECTRATIOD);
1364   hCtrl3 = GetDlgItem(hWnd, IDC_ASPECT);
1365   if (hCtrl && hCtrl2 && hCtrl3)
1366   {
1367      char aspect_option[32];
1368      snprintf(aspect_option, ARRAY_LENGTH(aspect_option), "aspect%d", GetSelectedScreen(hWnd));
1369
1370      if (Button_GetCheck(hCtrl3))
1371      {
1372         options_set_string(o, aspect_option, "auto", OPTION_PRIORITY_CMDLINE);
1373      }
1374      else
1375      {
1376         int n = 0;
1377         int d = 0;
1378         TCHAR buffer[200];
1379         char buffer2[200];
1380
1381         Edit_GetText(hCtrl,buffer,sizeof(buffer));
1382         _stscanf(buffer,TEXT("%d"),&n);
1383
1384         Edit_GetText(hCtrl2,buffer,sizeof(buffer));
1385         _stscanf(buffer,TEXT("%d"),&d);
1386
1387         if (n == 0 || d == 0)
1388         {
1389            n = 4;
1390            d = 3;
1391         }
1392
1393         snprintf(buffer2,sizeof(buffer2),"%d:%d",n,d);
1394         options_set_string(o, aspect_option, buffer2, OPTION_PRIORITY_CMDLINE);
1395      }
1396   }
1397}
1398
1399/* Update options from the dialog */
1400static void UpdateOptions(HWND hDlg, datamap *properties_datamap, core_options *opts)
1401{
1402   /* These are always called together, so make one conveniece function. */
1403   datamap_read_all_controls(properties_datamap, hDlg, opts);
1404   PropToOptions(hDlg, opts);
1405}
1406
1407/* Update the dialog from the options */
1408static void UpdateProperties(HWND hDlg, datamap *properties_datamap, core_options *opts)
1409{
1410   /* These are always called together, so make one conviniece function. */
1411   datamap_populate_all_controls(properties_datamap, hDlg, opts);
1412   OptionsToProp(hDlg, opts);
1413   SetPropEnabledControls(hDlg);
1414}
1415
1416/* Populate controls that are not handled in the DataMap */
1417static void OptionsToProp(HWND hWnd, core_options* o)
1418{
1419   HWND hCtrl;
1420   HWND hCtrl2;
1421   TCHAR buf[100];
1422   int  n = 0;
1423   int  d = 0;
1424
1425   /* video */
1426
1427   /* Setup refresh list based on depth. */
1428   datamap_update_control(properties_datamap, hWnd, pCurrentOpts, IDC_REFRESH);
1429   /* Setup Select screen*/
1430   UpdateSelectScreenUI(hWnd );
1431
1432   hCtrl = GetDlgItem(hWnd, IDC_ASPECT);
1433   if (hCtrl)
1434   {
1435      Button_SetCheck(hCtrl, g_bAutoAspect[GetSelectedScreen(hWnd)] )   ;
1436   }
1437
1438   /* Bios select list */
1439   hCtrl = GetDlgItem(hWnd, IDC_BIOS);
1440   if (hCtrl)
1441   {
1442      const char* cBuffer;
1443      int i = 0;
1444      int iCount = ComboBox_GetCount( hCtrl );
1445      for( i=0; i< iCount; i++ )
1446      {
1447         cBuffer = (const char*)ComboBox_GetItemData( hCtrl, i );
1448         if (strcmp(cBuffer, options_get_string(pCurrentOpts, OPTION_BIOS) ) == 0)
1449         {
1450            (void)ComboBox_SetCurSel(hCtrl, i);
1451            break;
1452         }
1453
1454      }
1455   }
1456
1457
1458   hCtrl = GetDlgItem(hWnd, IDC_ASPECT);
1459   if (hCtrl)
1460   {
1461      char aspect_option[32];
1462      snprintf(aspect_option, ARRAY_LENGTH(aspect_option), "aspect%d", GetSelectedScreen(hWnd));
1463      if( strcmp(options_get_string(o, aspect_option), "auto") == 0)
1464      {
1465         Button_SetCheck(hCtrl, TRUE);
1466         g_bAutoAspect[GetSelectedScreen(hWnd)] = TRUE;
1467      }
1468      else
1469      {
1470         Button_SetCheck(hCtrl, FALSE);
1471         g_bAutoAspect[GetSelectedScreen(hWnd)] = FALSE;
1472      }
1473   }
1474
1475   /* aspect ratio */
1476   hCtrl  = GetDlgItem(hWnd, IDC_ASPECTRATION);
1477   hCtrl2 = GetDlgItem(hWnd, IDC_ASPECTRATIOD);
1478   if (hCtrl && hCtrl2)
1479   {
1480      char aspect_option[32];
1481      snprintf(aspect_option, ARRAY_LENGTH(aspect_option), "aspect%d", GetSelectedScreen(hWnd));
1482
1483      n = 0;
1484      d = 0;
1485      if (options_get_string(o, aspect_option))
1486      {
1487         if (sscanf(options_get_string(o, aspect_option), "%d:%d", &n, &d) == 2 && n != 0 && d != 0)
1488         {
1489            _stprintf(buf, TEXT("%d"), n);
1490            Edit_SetText(hCtrl, buf);
1491            _stprintf(buf, TEXT("%d"), d);
1492            Edit_SetText(hCtrl2, buf);
1493         }
1494         else
1495         {
1496            Edit_SetText(hCtrl,  TEXT("4"));
1497            Edit_SetText(hCtrl2, TEXT("3"));
1498         }
1499      }
1500      else
1501      {
1502         Edit_SetText(hCtrl,  TEXT("4"));
1503         Edit_SetText(hCtrl2, TEXT("3"));
1504      }
1505   }
1506   hCtrl = GetDlgItem(hWnd, IDC_EFFECT);
1507   if (hCtrl) {
1508      const char* effect = options_get_string(o, WINOPTION_EFFECT);
1509      if (effect == NULL) {
1510         effect = "none";
1511         options_set_string(o, WINOPTION_EFFECT, effect, OPTION_PRIORITY_CMDLINE);
1512      }
1513      win_set_window_text_utf8(hCtrl, effect);
1514   }
1515}
1516
1517/* Adjust controls - tune them to the currently selected game */
1518static void SetPropEnabledControls(HWND hWnd)
1519{
1520   HWND hCtrl;
1521   int  nIndex;
1522   int  sound;
1523   BOOL ddraw = FALSE;
1524   BOOL d3d = FALSE;
1525   BOOL gdi = FALSE;
1526   BOOL useart = TRUE;
1527   BOOL multimon = (DirectDraw_GetNumDisplays() >= 2);
1528   int joystick_attached = 0;
1529   int in_window = 0;
1530
1531   nIndex = g_nGame;
1532   
1533   d3d = !mame_stricmp(options_get_string(pCurrentOpts, WINOPTION_VIDEO), "d3d");
1534   ddraw = !mame_stricmp(options_get_string(pCurrentOpts, WINOPTION_VIDEO), "ddraw");
1535   gdi = !d3d && !ddraw;
1536
1537   in_window = options_get_bool(pCurrentOpts, WINOPTION_WINDOW);
1538   Button_SetCheck(GetDlgItem(hWnd, IDC_ASPECT), g_bAutoAspect[GetSelectedScreen(hWnd)] );
1539
1540   EnableWindow(GetDlgItem(hWnd, IDC_WAITVSYNC), !gdi);
1541   EnableWindow(GetDlgItem(hWnd, IDC_TRIPLE_BUFFER), !gdi);
1542   EnableWindow(GetDlgItem(hWnd, IDC_PRESCALE), !gdi);
1543   EnableWindow(GetDlgItem(hWnd, IDC_PRESCALEDISP), !gdi);
1544   EnableWindow(GetDlgItem(hWnd, IDC_HWSTRETCH),       ddraw && DirectDraw_HasHWStretch());
1545   EnableWindow(GetDlgItem(hWnd, IDC_SWITCHRES), TRUE);
1546   EnableWindow(GetDlgItem(hWnd, IDC_SYNCREFRESH),     TRUE);
1547   EnableWindow(GetDlgItem(hWnd, IDC_REFRESH),         !in_window );
1548   EnableWindow(GetDlgItem(hWnd, IDC_REFRESHTEXT),     !in_window );
1549   EnableWindow(GetDlgItem(hWnd, IDC_FSGAMMA),      !in_window);
1550   EnableWindow(GetDlgItem(hWnd, IDC_FSGAMMATEXT),  !in_window);
1551   EnableWindow(GetDlgItem(hWnd, IDC_FSGAMMADISP),  !in_window);
1552   EnableWindow(GetDlgItem(hWnd, IDC_FSBRIGHTNESS),      !in_window);
1553   EnableWindow(GetDlgItem(hWnd, IDC_FSBRIGHTNESSTEXT),  !in_window);
1554   EnableWindow(GetDlgItem(hWnd, IDC_FSBRIGHTNESSDISP),  !in_window);
1555   EnableWindow(GetDlgItem(hWnd, IDC_FSCONTRAST),      !in_window);
1556   EnableWindow(GetDlgItem(hWnd, IDC_FSCONTRASTTEXT),  !in_window);
1557   EnableWindow(GetDlgItem(hWnd, IDC_FSCONTRASTDISP),  !in_window);
1558
1559   EnableWindow(GetDlgItem(hWnd, IDC_ASPECTRATIOTEXT), !g_bAutoAspect[GetSelectedScreen(hWnd)]);
1560   EnableWindow(GetDlgItem(hWnd, IDC_ASPECTRATION), !g_bAutoAspect[GetSelectedScreen(hWnd)]);
1561   EnableWindow(GetDlgItem(hWnd, IDC_ASPECTRATIOD), !g_bAutoAspect[GetSelectedScreen(hWnd)]);
1562
1563   EnableWindow(GetDlgItem(hWnd,IDC_D3D_FILTER),d3d);
1564   EnableWindow(GetDlgItem(hWnd,IDC_D3D_VERSION),d3d);
1565   
1566   //Switchres and D3D or ddraw enable the per screen parameters
1567
1568   EnableWindow(GetDlgItem(hWnd, IDC_NUMSCREENS),                 (ddraw || d3d) && multimon);
1569   EnableWindow(GetDlgItem(hWnd, IDC_NUMSCREENSDISP),             (ddraw || d3d) && multimon);
1570   EnableWindow(GetDlgItem(hWnd, IDC_SCREENSELECT),               (ddraw || d3d) && multimon);
1571   EnableWindow(GetDlgItem(hWnd, IDC_SCREENSELECTTEXT),           (ddraw || d3d) && multimon);
1572
1573   EnableWindow(GetDlgItem(hWnd, IDC_ARTWORK_CROP),   useart);
1574   EnableWindow(GetDlgItem(hWnd, IDC_BACKDROPS),      useart);
1575   EnableWindow(GetDlgItem(hWnd, IDC_BEZELS),         useart);
1576   EnableWindow(GetDlgItem(hWnd, IDC_OVERLAYS),      useart);
1577   EnableWindow(GetDlgItem(hWnd, IDC_ARTMISCTEXT),      useart);
1578
1579   /* Joystick options */
1580   joystick_attached = DIJoystick.Available();
1581
1582   Button_Enable(GetDlgItem(hWnd,IDC_JOYSTICK),      joystick_attached);
1583   EnableWindow(GetDlgItem(hWnd, IDC_JDZTEXT),         joystick_attached);
1584   EnableWindow(GetDlgItem(hWnd, IDC_JDZDISP),         joystick_attached);
1585   EnableWindow(GetDlgItem(hWnd, IDC_JDZ),            joystick_attached);
1586   EnableWindow(GetDlgItem(hWnd, IDC_JSATTEXT),         joystick_attached);
1587   EnableWindow(GetDlgItem(hWnd, IDC_JSATDISP),         joystick_attached);
1588   EnableWindow(GetDlgItem(hWnd, IDC_JSAT),            joystick_attached);
1589   /* Trackball / Mouse options */
1590   if (nIndex <= -1 || DriverUsesTrackball(nIndex) || DriverUsesLightGun(nIndex))
1591      Button_Enable(GetDlgItem(hWnd,IDC_USE_MOUSE),TRUE);
1592   else
1593      Button_Enable(GetDlgItem(hWnd,IDC_USE_MOUSE),FALSE);
1594
1595   if (!in_window && (nIndex <= -1 || DriverUsesLightGun(nIndex)))
1596   {
1597      // on WinXP the Lightgun and Dual Lightgun switches are no longer supported use mouse instead
1598      OSVERSIONINFOEX osvi;
1599      BOOL bOsVersionInfoEx;
1600      // Try calling GetVersionEx using the OSVERSIONINFOEX structure.
1601      // If that fails, try using the OSVERSIONINFO structure.
1602
1603      ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
1604      osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
1605
1606      if( !(bOsVersionInfoEx = GetVersionEx ((OSVERSIONINFO *) &osvi)) )
1607      {
1608         osvi.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
1609         bOsVersionInfoEx = GetVersionEx ( (OSVERSIONINFO *) &osvi);
1610      }
1611
1612      if( bOsVersionInfoEx && (osvi.dwPlatformId == VER_PLATFORM_WIN32_NT) && (osvi.dwMajorVersion >= 5) )
1613      {
1614         BOOL use_lightgun;
1615         //XP and above...
1616         Button_Enable(GetDlgItem(hWnd,IDC_LIGHTGUN),FALSE);
1617         use_lightgun = Button_GetCheck(GetDlgItem(hWnd,IDC_USE_MOUSE));
1618         Button_Enable(GetDlgItem(hWnd,IDC_DUAL_LIGHTGUN),FALSE);
1619         Button_Enable(GetDlgItem(hWnd,IDC_RELOAD),use_lightgun);
1620      }
1621      else
1622      {
1623         BOOL use_lightgun;
1624         // Older than XP
1625         Button_Enable(GetDlgItem(hWnd,IDC_LIGHTGUN),TRUE);
1626         use_lightgun = Button_GetCheck(GetDlgItem(hWnd,IDC_LIGHTGUN));
1627         Button_Enable(GetDlgItem(hWnd,IDC_DUAL_LIGHTGUN),use_lightgun);
1628         Button_Enable(GetDlgItem(hWnd,IDC_RELOAD),use_lightgun);
1629      }
1630   }
1631   else
1632   {
1633      Button_Enable(GetDlgItem(hWnd,IDC_LIGHTGUN),FALSE);
1634      Button_Enable(GetDlgItem(hWnd,IDC_DUAL_LIGHTGUN),FALSE);
1635      Button_Enable(GetDlgItem(hWnd,IDC_RELOAD),FALSE);
1636   }
1637
1638
1639   /* Sound options */
1640   hCtrl = GetDlgItem(hWnd, IDC_USE_SOUND);
1641   if (hCtrl)
1642   {
1643      sound = Button_GetCheck(hCtrl);
1644      ComboBox_Enable(GetDlgItem(hWnd, IDC_SAMPLERATE), (sound != 0));
1645
1646      EnableWindow(GetDlgItem(hWnd,IDC_VOLUME),sound);
1647      EnableWindow(GetDlgItem(hWnd,IDC_RATETEXT),sound);
1648      EnableWindow(GetDlgItem(hWnd,IDC_VOLUMEDISP),sound);
1649      EnableWindow(GetDlgItem(hWnd,IDC_VOLUMETEXT),sound);
1650      EnableWindow(GetDlgItem(hWnd,IDC_AUDIO_LATENCY),sound);
1651      EnableWindow(GetDlgItem(hWnd,IDC_AUDIO_LATENCY_DISP),sound);
1652      EnableWindow(GetDlgItem(hWnd,IDC_AUDIO_LATENCY_TEXT),sound);
1653      SetSamplesEnabled(hWnd, nIndex, sound);
1654      SetStereoEnabled(hWnd, nIndex);
1655      SetYM3812Enabled(hWnd, nIndex);
1656   }
1657   
1658   if (Button_GetCheck(GetDlgItem(hWnd, IDC_AUTOFRAMESKIP)))
1659      EnableWindow(GetDlgItem(hWnd, IDC_FRAMESKIP), FALSE);
1660   else
1661      EnableWindow(GetDlgItem(hWnd, IDC_FRAMESKIP), TRUE);
1662
1663   if (nIndex <= -1 || DriverHasOptionalBIOS(nIndex))
1664      EnableWindow(GetDlgItem(hWnd,IDC_BIOS),TRUE);
1665   else
1666      EnableWindow(GetDlgItem(hWnd,IDC_BIOS),FALSE);
1667
1668}
1669
1670//============================================================
1671//  CONTROL HELPER FUNCTIONS FOR DATA EXCHANGE
1672//============================================================
1673
1674static BOOL RotateReadControl(datamap *map, HWND dialog, HWND control, core_options *opts, const char *option_name)
1675{
1676   int selected_index = ComboBox_GetCurSel(control);
1677   int original_selection = 0;
1678
1679   // Figure out what the original selection value is
1680   if (options_get_bool(opts, OPTION_ROR) && !options_get_bool(opts, OPTION_ROL))
1681      original_selection = 1;
1682   else if (!options_get_bool(opts, OPTION_ROR) && options_get_bool(opts, OPTION_ROL))
1683      original_selection = 2;
1684   else if (!options_get_bool(opts, OPTION_ROTATE))
1685      original_selection = 3;
1686   else if (options_get_bool(opts, OPTION_AUTOROR))
1687      original_selection = 4;
1688   else if (options_get_bool(opts, OPTION_AUTOROL))
1689      original_selection = 5;
1690
1691   // Any work to do?  If so, make the changes and return TRUE.
1692   if (selected_index != original_selection)
1693   {
1694      // Set the options based on the new selection.
1695      options_set_bool(opts, OPTION_ROR,      selected_index == 1, OPTION_PRIORITY_CMDLINE);
1696      options_set_bool(opts, OPTION_ROL,      selected_index == 2, OPTION_PRIORITY_CMDLINE);
1697      options_set_bool(opts, OPTION_ROTATE,   selected_index != 3, OPTION_PRIORITY_CMDLINE);
1698      options_set_bool(opts, OPTION_AUTOROR,   selected_index == 4, OPTION_PRIORITY_CMDLINE);
1699      options_set_bool(opts, OPTION_AUTOROL,   selected_index == 5, OPTION_PRIORITY_CMDLINE);
1700      return TRUE;
1701   }
1702
1703   // No changes
1704   return FALSE;
1705}
1706
1707
1708
1709static BOOL RotatePopulateControl(datamap *map, HWND dialog, HWND control, core_options *opts, const char *option_name)
1710{
1711   int selected_index = 0;
1712   if (options_get_bool(opts, OPTION_ROR) && !options_get_bool(opts, OPTION_ROL))
1713      selected_index = 1;
1714   else if (!options_get_bool(opts, OPTION_ROR) && options_get_bool(opts, OPTION_ROL))
1715      selected_index = 2;
1716   else if (!options_get_bool(opts, OPTION_ROTATE))
1717      selected_index = 3;
1718   else if (options_get_bool(opts, OPTION_AUTOROR))
1719      selected_index = 4;
1720   else if (options_get_bool(opts, OPTION_AUTOROL))
1721      selected_index = 5;
1722
1723   (void)ComboBox_SetCurSel(control, selected_index);
1724   return FALSE;
1725}
1726
1727
1728
1729static BOOL ScreenReadControl(datamap *map, HWND dialog, HWND control, core_options *opts, const char *option_name)
1730{
1731   char screen_option_name[32];
1732   const char *screen_option_value;
1733   int selected_screen;
1734   int screen_option_index;
1735
1736   selected_screen = GetSelectedScreen(dialog);
1737   screen_option_index = ComboBox_GetCurSel(control);
1738   screen_option_value = (const char *) ComboBox_GetItemData(control, screen_option_index);
1739   snprintf(screen_option_name, ARRAY_LENGTH(screen_option_name), "screen%d", selected_screen);
1740   options_set_string(opts, screen_option_name, screen_option_value, OPTION_PRIORITY_CMDLINE);
1741   return FALSE;
1742}
1743
1744
1745
1746static BOOL ScreenPopulateControl(datamap *map, HWND dialog, HWND control, core_options *opts, const char *option_name)
1747{
1748   int iMonitors;
1749   DISPLAY_DEVICE dd;
1750   int i = 0;
1751   int nSelection = 0;
1752   TCHAR* t_option = 0;
1753
1754   /* Remove all items in the list. */
1755   (void)ComboBox_ResetContent(control);
1756   (void)ComboBox_InsertString(control, 0, TEXT("Auto"));
1757   (void)ComboBox_SetItemData(control, 0, (const char*)mame_strdup("auto"));
1758
1759   //Dynamically populate it, by enumerating the Monitors
1760   iMonitors = GetSystemMetrics(SM_CMONITORS); // this gets the count of monitors attached
1761   ZeroMemory(&dd, sizeof(dd));
1762   dd.cb = sizeof(dd);
1763   for(i=0; EnumDisplayDevices(NULL, i, &dd, 0); i++)
1764   {
1765      if( !(dd.StateFlags & DISPLAY_DEVICE_MIRRORING_DRIVER) )
1766      {
1767         char screen_option[32];
1768
1769         //we have to add 1 to account for the "auto" entry
1770         (void)ComboBox_InsertString(control, i+1, win_tstring_strdup(dd.DeviceName));
1771         (void)ComboBox_SetItemData(control, i+1, (void*)win_tstring_strdup(dd.DeviceName));
1772
1773         snprintf(screen_option, ARRAY_LENGTH(screen_option), "screen%d", GetSelectedScreen(dialog));
1774         t_option = tstring_from_utf8(options_get_string(opts, screen_option));
1775         if( !t_option )
1776            return FALSE;
1777         if (_tcscmp(t_option, dd.DeviceName) == 0)
1778            nSelection = i+1;
1779         free(t_option);
1780      }
1781   }
1782   (void)ComboBox_SetCurSel(control, nSelection);
1783   return FALSE;
1784}
1785
1786
1787
1788static void ViewSetOptionName(datamap *map, HWND dialog, HWND control, char *buffer, size_t buffer_size)
1789{
1790   snprintf(buffer, buffer_size, "view%d", GetSelectedScreen(dialog));
1791}
1792
1793
1794
1795static BOOL ViewPopulateControl(datamap *map, HWND dialog, HWND control, core_options *opts, const char *option_name)
1796{
1797   int i;
1798   int selected_index = 0;
1799   char view_option[32];
1800   const char *view;
1801
1802   // determine the view option value
1803   snprintf(view_option, ARRAY_LENGTH(view_option), "view%d", GetSelectedScreen(dialog));
1804   view = options_get_string(opts, view_option);
1805
1806   (void)ComboBox_ResetContent(control);
1807   for (i = 0; i < NUMVIEW; i++)
1808   {
1809      (void)ComboBox_InsertString(control, i, g_ComboBoxView[i].m_pText);
1810      (void)ComboBox_SetItemData(control, i, g_ComboBoxView[i].m_pData);
1811
1812      if (!strcmp(view, g_ComboBoxView[i].m_pData))
1813         selected_index = i;
1814   }
1815   (void)ComboBox_SetCurSel(control, selected_index);
1816   return FALSE;
1817}
1818
1819
1820static BOOL DefaultInputPopulateControl(datamap *map, HWND dialog, HWND control, core_options *opts, const char *option_name)
1821{
1822   WIN32_FIND_DATA FindFileData;
1823   HANDLE hFind;
1824   TCHAR *ext;
1825   TCHAR root[256];
1826   TCHAR path[256];
1827   int selected = 0;
1828   int index = 0;
1829   LPCTSTR t_ctrlr_option = 0;
1830   LPTSTR buf = 0;
1831   const char *ctrlr_option;
1832   TCHAR* t_ctrldir;
1833
1834   // determine the ctrlr option
1835   ctrlr_option = options_get_string(opts, OPTION_CTRLR);
1836   if( ctrlr_option != NULL )
1837   {
1838      buf = tstring_from_utf8(ctrlr_option);
1839      if( !buf )
1840         return FALSE;
1841      t_ctrlr_option = buf;
1842   }
1843   else
1844   {
1845      t_ctrlr_option = TEXT("");
1846   }
1847
1848   // reset the controllers dropdown
1849   (void)ComboBox_ResetContent(control);
1850   (void)ComboBox_InsertString(control, index, TEXT("Standard"));
1851   (void)ComboBox_SetItemData(control, index, "");
1852   index++;
1853   
1854   t_ctrldir = tstring_from_utf8(GetCtrlrDir());
1855   if( !t_ctrldir )
1856   {
1857      if( buf )
1858         free(buf);
1859      return FALSE;
1860   }
1861
1862   _stprintf (path, TEXT("%s\\*.*"), t_ctrldir);
1863   
1864   free(t_ctrldir);
1865
1866   hFind = FindFirstFile(path, &FindFileData);
1867
1868   if (hFind != INVALID_HANDLE_VALUE)
1869   {
1870      do
1871      {
1872         // copy the filename
1873         _tcscpy (root,FindFileData.cFileName);
1874
1875         // find the extension
1876         ext = _tcsrchr (root,'.');
1877         if (ext)
1878         {
1879            // check if it's a cfg file
1880            if (_tcscmp (ext, TEXT(".cfg")) == 0)
1881            {
1882               // and strip off the extension
1883               *ext = 0;
1884
1885               // set the option?
1886               if (!_tcscmp(root, t_ctrlr_option))
1887                  selected = index;
1888
1889               // add it as an option
1890               (void)ComboBox_InsertString(control, index, root);
1891               (void)ComboBox_SetItemData(control, index, (void*)win_tstring_strdup(root));   // FIXME - leaks memory!
1892               index++;
1893            }
1894         }
1895      }
1896      while (FindNextFile (hFind, &FindFileData) != 0);
1897     
1898      FindClose (hFind);
1899   }
1900
1901   (void)ComboBox_SetCurSel(control, selected);
1902   
1903   if( buf )
1904      free(buf);
1905
1906   return FALSE;
1907}
1908
1909
1910
1911static void ResolutionSetOptionName(datamap *map, HWND dialog, HWND control, char *buffer, size_t buffer_size)
1912{
1913   snprintf(buffer, buffer_size, "resolution%d", GetSelectedScreen(dialog));
1914}
1915
1916
1917static BOOL ResolutionReadControl(datamap *map, HWND dialog, HWND control, core_options *opts, const char *option_name)
1918{
1919   HWND refresh_control = GetDlgItem(dialog, IDC_REFRESH);
1920   HWND sizes_control = GetDlgItem(dialog, IDC_SIZES);
1921   int refresh_index, refresh_value, width, height;
1922   char option_value[256];
1923   TCHAR buffer[256];
1924
1925   if (refresh_control && sizes_control)
1926   {
1927      (void)ComboBox_GetText(sizes_control, buffer, ARRAY_LENGTH(buffer) - 1);
1928      if (_stscanf(buffer, TEXT("%d x %d"), &width, &height) == 2)
1929      {
1930         refresh_index = ComboBox_GetCurSel(refresh_control);
1931         refresh_value = ComboBox_GetItemData(refresh_control, refresh_index);
1932         snprintf(option_value, ARRAY_LENGTH(option_value), "%dx%d@%d", width, height, refresh_value);
1933      }
1934      else
1935      {
1936         snprintf(option_value, ARRAY_LENGTH(option_value), "auto");
1937      }
1938      options_set_string(opts, option_name, option_value, OPTION_PRIORITY_CMDLINE);
1939   }
1940   return FALSE;
1941}
1942
1943
1944
1945static BOOL ResolutionPopulateControl(datamap *map, HWND dialog, HWND control_, core_options *opts, const char *option_name)
1946{
1947   HWND sizes_control = GetDlgItem(dialog, IDC_SIZES);
1948   HWND refresh_control = GetDlgItem(dialog, IDC_REFRESH);
1949   int width, height, refresh;
1950   const char *option_value;
1951   int sizes_index = 0;
1952   int refresh_index = 0;
1953   int sizes_selection = 0;
1954   int refresh_selection = 0;
1955   char screen_option[32];
1956   const char *screen;
1957   LPTSTR t_screen;
1958   TCHAR buf[16];
1959   int i;
1960   DEVMODE devmode;
1961
1962   if (sizes_control && refresh_control)
1963   {
1964      // determine the resolution
1965      option_value = options_get_string(opts, option_name);
1966      if (sscanf(option_value, "%dx%d@%d", &width, &height, &refresh) != 3)
1967      {
1968         width = 0;
1969         height = 0;
1970         refresh = 0;
1971      }
1972
1973      // reset sizes control
1974      (void)ComboBox_ResetContent(sizes_control);
1975      (void)ComboBox_InsertString(sizes_control, sizes_index, TEXT("Auto"));
1976      (void)ComboBox_SetItemData(sizes_control, sizes_index, 0);
1977      sizes_index++;
1978
1979      // reset refresh control
1980      (void)ComboBox_ResetContent(refresh_control);
1981      (void)ComboBox_InsertString(refresh_control, refresh_index, TEXT("Auto"));
1982      (void)ComboBox_SetItemData(refresh_control, refresh_index, 0);
1983      refresh_index++;
1984
1985      // determine which screen we're using
1986      snprintf(screen_option, ARRAY_LENGTH(screen_option), "screen%d", GetSelectedScreen(dialog));
1987      screen = options_get_string(opts, screen_option);
1988      t_screen = tstring_from_utf8(screen);
1989
1990      // retrieve screen information
1991      devmode.dmSize = sizeof(devmode);
1992      for (i = 0; EnumDisplaySettings(t_screen, i, &devmode); i++)
1993      {
1994         if ((devmode.dmBitsPerPel == 32 ) // Only 32 bit depth supported by core
1995            &&(devmode.dmDisplayFrequency == refresh || refresh == 0))
1996         {
1997            _sntprintf(buf, ARRAY_LENGTH(buf), TEXT("%li x %li"),
1998               devmode.dmPelsWidth, devmode.dmPelsHeight);
1999
2000            if (ComboBox_FindString(sizes_control, 0, buf) == CB_ERR)
2001            {
2002               (void)ComboBox_InsertString(sizes_control, sizes_index, buf);
2003
2004               if ((width == devmode.dmPelsWidth) && (height == devmode.dmPelsHeight))
2005                  sizes_selection = sizes_index;
2006               sizes_index++;
2007
2008            }
2009         }
2010         if (devmode.dmDisplayFrequency >= 10 )
2011         {
2012            // I have some devmode "vga" which specifes 1 Hz, which is probably bogus, so we filter it out
2013
2014            _sntprintf(buf, ARRAY_LENGTH(buf), TEXT("%li Hz"), devmode.dmDisplayFrequency);
2015
2016            if (ComboBox_FindString(refresh_control, 0, buf) == CB_ERR)
2017            {
2018               (void)ComboBox_InsertString(refresh_control, refresh_index, buf);
2019               (void)ComboBox_SetItemData(refresh_control, refresh_index, devmode.dmDisplayFrequency);
2020
2021               if (refresh == devmode.dmDisplayFrequency)
2022                  refresh_selection = refresh_index;
2023
2024               refresh_index++;
2025            }
2026         }
2027      }
2028      free(t_screen);
2029
2030      (void)ComboBox_SetCurSel(sizes_control, sizes_selection);
2031      (void)ComboBox_SetCurSel(refresh_control, refresh_selection);
2032   }
2033   return FALSE;
2034}
2035
2036
2037
2038//============================================================
2039
2040/************************************************************
2041 * DataMap initializers
2042 ************************************************************/
2043
2044/* Initialize local helper variables */
2045static void ResetDataMap(HWND hWnd)
2046{
2047   char screen_option[32];
2048
2049   snprintf(screen_option, ARRAY_LENGTH(screen_option), "screen%d", GetSelectedScreen(hWnd));
2050
2051   if (options_get_string(pCurrentOpts, screen_option) == NULL
2052      || (mame_stricmp(options_get_string(pCurrentOpts, screen_option), "") == 0 )
2053      || (mame_stricmp(options_get_string(pCurrentOpts, screen_option), "auto") == 0 ) )
2054   {
2055      options_set_string(pCurrentOpts, screen_option, "auto", OPTION_PRIORITY_CMDLINE);
2056   }
2057}
2058
2059
2060/* Build the control mapping by adding all needed information to the DataMap */
2061static void BuildDataMap(void)
2062{
2063   properties_datamap = datamap_create();
2064
2065   // core state options
2066   datamap_add(properties_datamap, IDC_ENABLE_AUTOSAVE,      DM_BOOL,   OPTION_AUTOSAVE);
2067
2068   // core performance options
2069    datamap_add(properties_datamap, IDC_AUTOFRAMESKIP,         DM_BOOL,   OPTION_AUTOFRAMESKIP);
2070   datamap_add(properties_datamap, IDC_FRAMESKIP,            DM_INT,      OPTION_FRAMESKIP);
2071   // Missing -seconds_to_run OPTION_SECONDS_TO_RUN
2072   datamap_add(properties_datamap, IDC_THROTTLE,            DM_BOOL,   OPTION_THROTTLE);
2073   datamap_add(properties_datamap, IDC_SLEEP,               DM_BOOL,   OPTION_SLEEP);
2074   datamap_add(properties_datamap, IDC_SPEED,                DM_FLOAT,   OPTION_SPEED);
2075   datamap_add(properties_datamap, IDC_SPEEDDISP,            DM_FLOAT,   OPTION_SPEED);
2076   datamap_add(properties_datamap, IDC_REFRESHSPEED,         DM_BOOL,   OPTION_REFRESHSPEED);
2077
2078   // Ccore retation options
2079   datamap_add(properties_datamap, IDC_ROTATE,               DM_INT,      NULL);
2080   // ror, rol, autoror, autorol handled by callback
2081   datamap_add(properties_datamap, IDC_FLIPX,               DM_BOOL,   OPTION_FLIPX);
2082   datamap_add(properties_datamap, IDC_FLIPY,               DM_BOOL,   OPTION_FLIPY);
2083
2084   // core artwork options
2085   datamap_add(properties_datamap, IDC_ARTWORK_CROP,         DM_BOOL,   OPTION_ARTWORK_CROP);
2086   datamap_add(properties_datamap, IDC_BACKDROPS,            DM_BOOL,   OPTION_USE_BACKDROPS);
2087   datamap_add(properties_datamap, IDC_OVERLAYS,            DM_BOOL,   OPTION_USE_OVERLAYS);
2088   datamap_add(properties_datamap, IDC_BEZELS,               DM_BOOL,   OPTION_USE_BEZELS);
2089
2090   // core screen options
2091   datamap_add(properties_datamap, IDC_BRIGHTCORRECT,         DM_FLOAT,   OPTION_BRIGHTNESS);
2092   datamap_add(properties_datamap, IDC_BRIGHTCORRECTDISP,      DM_FLOAT,   OPTION_BRIGHTNESS);
2093   datamap_add(properties_datamap, IDC_CONTRAST,            DM_FLOAT,   OPTION_CONTRAST);
2094   datamap_add(properties_datamap, IDC_CONTRASTDISP,         DM_FLOAT,   OPTION_CONTRAST);
2095   datamap_add(properties_datamap, IDC_GAMMA,               DM_FLOAT,   OPTION_GAMMA);
2096   datamap_add(properties_datamap, IDC_GAMMADISP,            DM_FLOAT,   OPTION_GAMMA);
2097   datamap_add(properties_datamap, IDC_PAUSEBRIGHT,         DM_FLOAT,   OPTION_PAUSE_BRIGHTNESS);
2098   datamap_add(properties_datamap, IDC_PAUSEBRIGHTDISP,      DM_FLOAT,   OPTION_PAUSE_BRIGHTNESS);
2099
2100   // core vector options
2101   datamap_add(properties_datamap, IDC_ANTIALIAS,            DM_BOOL,   OPTION_ANTIALIAS);
2102   datamap_add(properties_datamap, IDC_BEAM,               DM_FLOAT,   OPTION_BEAM);
2103   datamap_add(properties_datamap, IDC_BEAMDISP,            DM_FLOAT,   OPTION_BEAM);
2104   datamap_add(properties_datamap, IDC_FLICKER,            DM_FLOAT,   OPTION_FLICKER);
2105   datamap_add(properties_datamap, IDC_FLICKERDISP,         DM_FLOAT,   OPTION_FLICKER);
2106
2107   // core sound options
2108   datamap_add(properties_datamap, IDC_SAMPLERATE,            DM_INT,      OPTION_SAMPLERATE);
2109   datamap_add(properties_datamap, IDC_SAMPLES,            DM_BOOL,   OPTION_SAMPLES);
2110   datamap_add(properties_datamap, IDC_USE_SOUND,            DM_BOOL,   OPTION_SOUND);
2111   datamap_add(properties_datamap, IDC_VOLUME,               DM_INT,      OPTION_VOLUME);
2112   datamap_add(properties_datamap, IDC_VOLUMEDISP,            DM_INT,      OPTION_VOLUME);
2113
2114   // core input options
2115   datamap_add(properties_datamap, IDC_DEFAULT_INPUT,         DM_STRING,   OPTION_CTRLR);
2116   datamap_add(properties_datamap, IDC_USE_MOUSE,            DM_BOOL,   OPTION_MOUSE);
2117   datamap_add(properties_datamap, IDC_JOYSTICK,            DM_BOOL,   OPTION_JOYSTICK);
2118   datamap_add(properties_datamap, IDC_LIGHTGUN,            DM_BOOL,   OPTION_LIGHTGUN);
2119   datamap_add(properties_datamap, IDC_STEADYKEY,            DM_BOOL,   OPTION_STEADYKEY);
2120   datamap_add(properties_datamap, IDC_MULTIKEYBOARD,         DM_BOOL,   OPTION_MULTIKEYBOARD);
2121   datamap_add(properties_datamap, IDC_MULTIMOUSE,            DM_BOOL,   OPTION_MULTIMOUSE);
2122   datamap_add(properties_datamap, IDC_RELOAD,               DM_BOOL,   OPTION_OFFSCREEN_RELOAD);
2123   //  missing joystick_map
2124   datamap_add(properties_datamap, IDC_JDZ,               DM_FLOAT,   OPTION_JOYSTICK_DEADZONE);
2125   datamap_add(properties_datamap, IDC_JDZDISP,            DM_FLOAT,   OPTION_JOYSTICK_DEADZONE);
2126   datamap_add(properties_datamap, IDC_JSAT,               DM_FLOAT,   OPTION_JOYSTICK_SATURATION);
2127   datamap_add(properties_datamap, IDC_JSATDISP,            DM_FLOAT,   OPTION_JOYSTICK_SATURATION);
2128
2129   // core input automatic enable options
2130   datamap_add(properties_datamap, IDC_PADDLE,               DM_STRING,   OPTION_PADDLE_DEVICE);
2131   datamap_add(properties_datamap, IDC_ADSTICK,            DM_STRING,   OPTION_ADSTICK_DEVICE);
2132   datamap_add(properties_datamap, IDC_PEDAL,               DM_STRING,   OPTION_PEDAL_DEVICE);
2133   datamap_add(properties_datamap, IDC_DIAL,               DM_STRING,   OPTION_DIAL_DEVICE);
2134   datamap_add(properties_datamap, IDC_TRACKBALL,            DM_STRING,   OPTION_TRACKBALL_DEVICE);
2135   datamap_add(properties_datamap, IDC_LIGHTGUNDEVICE,         DM_STRING,   OPTION_LIGHTGUN_DEVICE);
2136   datamap_add(properties_datamap, IDC_POSITIONAL,            DM_STRING,   OPTION_POSITIONAL_DEVICE);
2137   datamap_add(properties_datamap, IDC_MOUSE,               DM_STRING,   OPTION_MOUSE_DEVICE);
2138
2139   // core debugging options
2140   datamap_add(properties_datamap, IDC_LOG,               DM_BOOL,   OPTION_LOG);
2141#ifdef _DEBUG
2142   datamap_add(properties_datamap, IDC_DEBUG,               DM_BOOL,   OPTION_DEBUG);
2143#endif
2144
2145   // core misc options
2146   datamap_add(properties_datamap, IDC_BIOS,               DM_STRING,   OPTION_BIOS);
2147   datamap_add(properties_datamap, IDC_CHEAT,               DM_BOOL,   OPTION_CHEAT);
2148   datamap_add(properties_datamap, IDC_SKIP_GAME_INFO,         DM_BOOL,   OPTION_SKIP_GAMEINFO);
2149
2150   // windows debuggin options
2151   // oslog?  missing
2152
2153   // windows performance options
2154   datamap_add(properties_datamap, IDC_HIGH_PRIORITY,         DM_INT,      WINOPTION_PRIORITY);
2155   datamap_add(properties_datamap, IDC_HIGH_PRIORITYTXT,      DM_INT,      WINOPTION_PRIORITY);
2156   datamap_add(properties_datamap, IDC_MULTITHREAD_RENDERING,   DM_BOOL,   WINOPTION_MULTITHREADING);
2157
2158   // windows video options
2159   datamap_add(properties_datamap, IDC_VIDEO_MODE,            DM_STRING,   WINOPTION_VIDEO);
2160   datamap_add(properties_datamap, IDC_NUMSCREENS,            DM_INT,      WINOPTION_NUMSCREENS);
2161   datamap_add(properties_datamap, IDC_NUMSCREENSDISP,         DM_INT,      WINOPTION_NUMSCREENS);
2162   datamap_add(properties_datamap, IDC_WINDOWED,            DM_BOOL,   WINOPTION_WINDOW);
2163   datamap_add(properties_datamap, IDC_MAXIMIZE,            DM_BOOL,   WINOPTION_MAXIMIZE);
2164   datamap_add(properties_datamap, IDC_KEEPASPECT,            DM_BOOL,   WINOPTION_KEEPASPECT);
2165   datamap_add(properties_datamap, IDC_PRESCALE,            DM_INT,      WINOPTION_PRESCALE);
2166   datamap_add(properties_datamap, IDC_PRESCALEDISP,         DM_INT,      WINOPTION_PRESCALE);
2167   // datamap_add(properties_datamap, IDC_EFFECT,               DM_STRING,   WINOPTION_EFFECT);
2168   datamap_add(properties_datamap, IDC_WAITVSYNC,            DM_BOOL,   WINOPTION_WAITVSYNC);
2169   datamap_add(properties_datamap, IDC_SYNCREFRESH,         DM_BOOL,   WINOPTION_SYNCREFRESH);
2170
2171   // DirectDraw specific options
2172   datamap_add(properties_datamap, IDC_HWSTRETCH,            DM_BOOL,   WINOPTION_HWSTRETCH);
2173
2174   // Direct3D specific options
2175   datamap_add(properties_datamap, IDC_D3D_VERSION,         DM_INT,      WINOPTION_D3DVERSION);
2176   datamap_add(properties_datamap, IDC_D3D_FILTER,            DM_BOOL,   WINOPTION_FILTER);
2177
2178   // per window video options
2179   datamap_add(properties_datamap, IDC_SCREEN,               DM_STRING,   NULL);
2180   datamap_add(properties_datamap, IDC_SCREENSELECT,         DM_STRING,   NULL);
2181   datamap_add(properties_datamap, IDC_VIEW,               DM_STRING,   NULL);
2182   datamap_add(properties_datamap, IDC_ASPECTRATIOD,         DM_STRING,  NULL);
2183   datamap_add(properties_datamap, IDC_ASPECTRATION,         DM_STRING,  NULL);
2184   datamap_add(properties_datamap, IDC_REFRESH,            DM_STRING,  NULL);
2185   datamap_add(properties_datamap, IDC_SIZES,               DM_STRING,  NULL);
2186
2187   // full screen options
2188   datamap_add(properties_datamap, IDC_TRIPLE_BUFFER,         DM_BOOL,   WINOPTION_TRIPLEBUFFER);
2189   datamap_add(properties_datamap, IDC_SWITCHRES,            DM_BOOL,   WINOPTION_SWITCHRES);
2190   datamap_add(properties_datamap, IDC_FSBRIGHTNESS,         DM_FLOAT,   WINOPTION_FULLSCREENBRIGHTNESS);
2191   datamap_add(properties_datamap, IDC_FSBRIGHTNESSDISP,      DM_FLOAT,   WINOPTION_FULLSCREENBRIGHTNESS);
2192   datamap_add(properties_datamap, IDC_FSCONTRAST,            DM_FLOAT,   WINOPTION_FULLLSCREENCONTRAST);
2193   datamap_add(properties_datamap, IDC_FSCONTRASTDISP,         DM_FLOAT,   WINOPTION_FULLLSCREENCONTRAST);
2194   datamap_add(properties_datamap, IDC_FSGAMMA,            DM_FLOAT,   WINOPTION_FULLSCREENGAMMA);
2195   datamap_add(properties_datamap, IDC_FSGAMMADISP,         DM_FLOAT,   WINOPTION_FULLSCREENGAMMA);
2196
2197   // windows sound options
2198   datamap_add(properties_datamap, IDC_AUDIO_LATENCY,         DM_INT,      WINOPTION_AUDIO_LATENCY);
2199   datamap_add(properties_datamap, IDC_AUDIO_LATENCY_DISP,      DM_INT,      WINOPTION_AUDIO_LATENCY);
2200
2201   // input device options
2202   datamap_add(properties_datamap, IDC_DUAL_LIGHTGUN,         DM_BOOL,   WINOPTION_DUAL_LIGHTGUN);
2203
2204   // set up callbacks
2205   datamap_set_callback(properties_datamap, IDC_ROTATE,      DCT_READ_CONTROL,      RotateReadControl);
2206   datamap_set_callback(properties_datamap, IDC_ROTATE,      DCT_POPULATE_CONTROL,   RotatePopulateControl);
2207   datamap_set_callback(properties_datamap, IDC_SCREEN,      DCT_READ_CONTROL,      ScreenReadControl);
2208   datamap_set_callback(properties_datamap, IDC_SCREEN,      DCT_POPULATE_CONTROL,   ScreenPopulateControl);
2209   datamap_set_callback(properties_datamap, IDC_VIEW,         DCT_POPULATE_CONTROL,   ViewPopulateControl);
2210   datamap_set_callback(properties_datamap, IDC_REFRESH,      DCT_READ_CONTROL,      ResolutionReadControl);
2211   datamap_set_callback(properties_datamap, IDC_REFRESH,      DCT_POPULATE_CONTROL,   ResolutionPopulateControl);
2212   datamap_set_callback(properties_datamap, IDC_SIZES,         DCT_READ_CONTROL,      ResolutionReadControl);
2213   datamap_set_callback(properties_datamap, IDC_SIZES,         DCT_POPULATE_CONTROL,   ResolutionPopulateControl);
2214   datamap_set_callback(properties_datamap, IDC_DEFAULT_INPUT,   DCT_POPULATE_CONTROL,   DefaultInputPopulateControl);
2215
2216   datamap_set_option_name_callback(properties_datamap, IDC_VIEW,      ViewSetOptionName);
2217   datamap_set_option_name_callback(properties_datamap, IDC_REFRESH,   ResolutionSetOptionName);
2218   datamap_set_option_name_callback(properties_datamap, IDC_SIZES,      ResolutionSetOptionName);
2219
2220   // formats
2221   datamap_set_int_format(properties_datamap, IDC_VOLUMEDISP,         "%ddB");
2222   datamap_set_int_format(properties_datamap, IDC_AUDIO_LATENCY_DISP,   "%d/5");
2223   datamap_set_float_format(properties_datamap, IDC_BEAMDISP,         "%03.2f");
2224   datamap_set_float_format(properties_datamap, IDC_FLICKERDISP,      "%03.2f");
2225   datamap_set_float_format(properties_datamap, IDC_GAMMADISP,         "%03.2f");
2226   datamap_set_float_format(properties_datamap, IDC_BRIGHTCORRECTDISP,   "%03.2f");
2227   datamap_set_float_format(properties_datamap, IDC_CONTRASTDISP,      "%03.2f");
2228   datamap_set_float_format(properties_datamap, IDC_PAUSEBRIGHTDISP,   "%03.2f");
2229   datamap_set_float_format(properties_datamap, IDC_FSGAMMADISP,      "%03.2f");
2230   datamap_set_float_format(properties_datamap, IDC_FSBRIGHTNESSDISP,   "%03.2f");
2231   datamap_set_float_format(properties_datamap, IDC_FSCONTRASTDISP,   "%03.2f");
2232   datamap_set_float_format(properties_datamap, IDC_JDZDISP,         "%03.2f");
2233   datamap_set_float_format(properties_datamap, IDC_JSATDISP,         "%03.2f");
2234   datamap_set_float_format(properties_datamap, IDC_SPEEDDISP,         "%03.2f");
2235
2236   // trackbar ranges
2237   datamap_set_trackbar_range(properties_datamap, IDC_PRESCALE,    1, 10, 1);
2238   datamap_set_trackbar_range(properties_datamap, IDC_JDZ,         0.00,  1.00, 0.05);
2239   datamap_set_trackbar_range(properties_datamap, IDC_JSAT,        0.00,  1.00, 0.05);
2240   datamap_set_trackbar_range(properties_datamap, IDC_SPEED,       0.00,  3.00, 0.01);
2241
2242#ifdef MESS
2243   // MESS specific stuff
2244   MessBuildDataMap(properties_datamap);
2245#endif // MESS
2246}
2247
2248BOOL IsControlOptionValue(HWND hDlg,HWND hwnd_ctrl, core_options *opts )
2249{
2250   int control_id = GetWindowLong(hwnd_ctrl, GWL_ID);
2251
2252   // certain controls we need to handle specially
2253   switch (control_id)
2254   {
2255      case IDC_ASPECTRATION :
2256      {
2257         char aspect_option[32];
2258         int n1 = 0, n2 = 0;
2259         int d1 = 0, d2 = 0;
2260
2261         snprintf(aspect_option, ARRAY_LENGTH(aspect_option), "aspect%d", GetSelectedScreen(hDlg));
2262
2263         sscanf(options_get_string(pCurrentOpts, aspect_option), "%d:%d", &n1, &d1);
2264         sscanf(options_get_string(opts, aspect_option), "%d:%d", &n2, &d2);
2265
2266         return n1 == n2;
2267      }
2268      case IDC_ASPECTRATIOD :
2269      {
2270         char aspect_option[32];
2271         int n1 = 0, n2 = 0;
2272         int d1 = 0, d2 = 0;
2273
2274         snprintf(aspect_option, ARRAY_LENGTH(aspect_option), "aspect%d", GetSelectedScreen(hDlg));
2275
2276         sscanf(options_get_string(pCurrentOpts, aspect_option), "%d:%d", &n1, &d1);
2277         sscanf(options_get_string(opts, aspect_option), "%d:%d", &n2, &d2);
2278
2279         return d1 == d2;
2280      }
2281      case IDC_SIZES :
2282      {
2283         char resolution_option[32];
2284         int x1=0,y1=0,x2=0,y2=0;
2285
2286         snprintf(resolution_option, ARRAY_LENGTH(resolution_option), "resolution%d", GetSelectedScreen(hDlg));
2287
2288         if ((strcmp(options_get_string(pCurrentOpts, resolution_option), "auto") == 0) &&
2289            (strcmp(options_get_string(opts, resolution_option), "auto") == 0))
2290            return TRUE;
2291         
2292         sscanf(options_get_string(pCurrentOpts, resolution_option),"%d x %d",&x1,&y1);
2293         sscanf(options_get_string(opts, resolution_option),"%d x %d",&x2,&y2);
2294
2295         return x1 == x2 && y1 == y2;     
2296      }
2297      case IDC_ROTATE :
2298      {
2299         datamap_read_control(properties_datamap, hDlg, pCurrentOpts, control_id);
2300
2301         return (options_get_bool(pCurrentOpts, OPTION_ROR) == options_get_bool(opts, OPTION_ROR))
2302            || (options_get_bool(pCurrentOpts, OPTION_ROL) == options_get_bool(opts, OPTION_ROL))
2303            || (options_get_bool(pCurrentOpts, OPTION_AUTOROR) == options_get_bool(opts, OPTION_AUTOROR))
2304            || (options_get_bool(pCurrentOpts, OPTION_AUTOROL) == options_get_bool(opts, OPTION_AUTOROL));
2305      }
2306   }
2307
2308   // most options we can compare using data in the data map
2309   //if (IsControlDifferent(hDlg,hwnd_ctrl,pCurrentOpts,opts))
2310   //   return FALSE;
2311
2312   return TRUE;
2313}
2314
2315
2316static void SetStereoEnabled(HWND hWnd, int nIndex)
2317{
2318   BOOL enabled = FALSE;
2319   HWND hCtrl;
2320   machine_config drv;
2321   int speakernum, num_speakers;
2322
2323   num_speakers = 0;
2324
2325   if ( nIndex > -1)
2326   {
2327      expand_machine_driver(drivers[nIndex]->drv,&drv);
2328      for (speakernum = 0; speakernum < MAX_SPEAKER; speakernum++)
2329         if (drv.speaker[speakernum].tag != NULL)
2330            num_speakers++;
2331   }
2332
2333   hCtrl = GetDlgItem(hWnd, IDC_STEREO);
2334   if (hCtrl)
2335   {
2336      if (nIndex <= -1 || num_speakers == 2)
2337         enabled = TRUE;
2338
2339      EnableWindow(hCtrl, enabled);
2340   }
2341}
2342
2343static void SetYM3812Enabled(HWND hWnd, int nIndex)
2344{
2345   int i;
2346   BOOL enabled;
2347   HWND hCtrl;
2348   machine_config drv;
2349
2350   if (nIndex > -1)
2351      expand_machine_driver(drivers[nIndex]->drv,&drv);
2352
2353   hCtrl = GetDlgItem(hWnd, IDC_USE_FM_YM3812);
2354   if (hCtrl)
2355   {
2356      enabled = FALSE;
2357      for (i = 0; i < MAX_SOUND; i++)
2358      {
2359         if (nIndex <= -1
2360#if HAS_YM3812
2361         ||  drv.sound[i].sound_type == SOUND_YM3812
2362#endif
2363#if HAS_YM3526
2364         ||  drv.sound[i].sound_type == SOUND_YM3526
2365#endif
2366#if HAS_YM2413
2367         ||  drv.sound[i].sound_type == SOUND_YM2413
2368#endif
2369         )
2370            enabled = TRUE;
2371      }
2372   
2373      EnableWindow(hCtrl, enabled);
2374   }
2375}
2376
2377static void SetSamplesEnabled(HWND hWnd, int nIndex, BOOL bSoundEnabled)
2378{
2379#if (HAS_SAMPLES == 1) || (HAS_VLM5030 == 1)
2380   int i;
2381   BOOL enabled = FALSE;
2382   HWND hCtrl;
2383   machine_config drv;
2384
2385   hCtrl = GetDlgItem(hWnd, IDC_SAMPLES);
2386
2387   if ( nIndex > -1 )
2388      expand_machine_driver(drivers[nIndex]->drv,&drv);
2389   
2390   if (hCtrl)
2391   {
2392      for (i = 0; i < MAX_SOUND; i++)
2393      {
2394         if (nIndex <= -1
2395         ||  drv.sound[i].sound_type == SOUND_SAMPLES
2396#if HAS_VLM5030
2397         ||  drv.sound[i].sound_type == SOUND_VLM5030
2398#endif
2399         )
2400            enabled = TRUE;
2401      }
2402      enabled = enabled && bSoundEnabled;
2403      EnableWindow(hCtrl, enabled);
2404   }
2405#endif
2406}
2407
2408/* Moved here cause it's called in a few places */
2409static void InitializeOptions(HWND hDlg)
2410{
2411   InitializeSoundUI(hDlg);
2412   InitializeSkippingUI(hDlg);
2413   InitializeRotateUI(hDlg);
2414   InitializeSelectScreenUI(hDlg);
2415   InitializeEffectUI(hDlg);
2416   InitializeBIOSUI(hDlg);
2417   InitializeControllerMappingUI(hDlg);
2418   InitializeD3DVersionUI(hDlg);
2419   InitializeVideoUI(hDlg);
2420}
2421
2422/* Moved here because it is called in several places */
2423static void InitializeMisc(HWND hDlg)
2424{
2425   Button_Enable(GetDlgItem(hDlg, IDC_JOYSTICK), DIJoystick.Available());
2426}
2427
2428static void OptOnHScroll(HWND hwnd, HWND hwndCtl, UINT code, int pos)
2429{
2430   if (hwndCtl == GetDlgItem(hwnd, IDC_NUMSCREENS))
2431   {
2432      NumScreensSelectionChange(hwnd);
2433   }
2434}
2435
2436/* Handle changes to the Numscreens slider */
2437static void NumScreensSelectionChange(HWND hwnd)
2438{
2439   //Also Update the ScreenSelect Combo with the new number of screens
2440   UpdateSelectScreenUI(hwnd );
2441}
2442
2443/* Handle changes to the Refresh drop down */
2444static void RefreshSelectionChange(HWND hWnd, HWND hWndCtrl)
2445{
2446   int nCurSelection;
2447
2448   nCurSelection = ComboBox_GetCurSel(hWndCtrl);
2449   if (nCurSelection != CB_ERR)
2450   {
2451      datamap_populate_control(properties_datamap, hWnd, pCurrentOpts, IDC_SIZES);
2452   }
2453}
2454
2455/* Initialize the sound options */
2456static void InitializeSoundUI(HWND hwnd)
2457{
2458   HWND    hCtrl;
2459   int i = 0;
2460
2461   hCtrl = GetDlgItem(hwnd, IDC_SAMPLERATE);
2462   if (hCtrl)
2463   {
2464      (void)ComboBox_AddString(hCtrl, TEXT("11025"));
2465      (void)ComboBox_SetItemData(hCtrl, i++, 11025);
2466      (void)ComboBox_AddString(hCtrl, TEXT("22050"));
2467      (void)ComboBox_SetItemData(hCtrl, i++, 22050);
2468      (void)ComboBox_AddString(hCtrl, TEXT("44100"));
2469      (void)ComboBox_SetItemData(hCtrl, i++, 44100);
2470      (void)ComboBox_AddString(hCtrl, TEXT("48000"));
2471      (void)ComboBox_SetItemData(hCtrl, i++, 48000);
2472      (void)ComboBox_SetCurSel(hCtrl, 1);
2473   }
2474}
2475
2476/* Populate the Frame Skipping drop down */
2477static void InitializeSkippingUI(HWND hwnd)
2478{
2479   HWND hCtrl = GetDlgItem(hwnd, IDC_FRAMESKIP);
2480   int i = 0;
2481
2482   if (hCtrl)
2483   {
2484      (void)ComboBox_AddString(hCtrl, TEXT("Draw every frame"));
2485      (void)ComboBox_SetItemData(hCtrl, i++, 0);
2486      (void)ComboBox_AddString(hCtrl, TEXT("Skip 1 of 12 frames"));
2487      (void)ComboBox_SetItemData(hCtrl, i++, 1);
2488      (void)ComboBox_AddString(hCtrl, TEXT("Skip 2 of 12 frames"));
2489      (void)ComboBox_SetItemData(hCtrl, i++, 2);
2490      (void)ComboBox_AddString(hCtrl, TEXT("Skip 3 of 12 frames"));
2491      (void)ComboBox_SetItemData(hCtrl, i++, 3);
2492      (void)ComboBox_AddString(hCtrl, TEXT("Skip 4 of 12 frames"));
2493      (void)ComboBox_SetItemData(hCtrl, i++, 4);
2494      (void)ComboBox_AddString(hCtrl, TEXT("Skip 5 of 12 frames"));
2495      (void)ComboBox_SetItemData(hCtrl, i++, 5);
2496      (void)ComboBox_AddString(hCtrl, TEXT("Skip 6 of 12 frames"));
2497      (void)ComboBox_SetItemData(hCtrl, i++, 6);
2498      (void)ComboBox_AddString(hCtrl, TEXT("Skip 7 of 12 frames"));
2499      (void)ComboBox_SetItemData(hCtrl, i++, 7);
2500      (void)ComboBox_AddString(hCtrl, TEXT("Skip 8 of 12 frames"));
2501      (void)ComboBox_SetItemData(hCtrl, i++, 8);
2502      (void)ComboBox_AddString(hCtrl, TEXT("Skip 9 of 12 frames"));
2503      (void)ComboBox_SetItemData(hCtrl, i++, 9);
2504      (void)ComboBox_AddString(hCtrl, TEXT("Skip 10 of 12 frames"));
2505      (void)ComboBox_SetItemData(hCtrl, i++, 10);
2506      (void)ComboBox_AddString(hCtrl, TEXT("Skip 11 of 12 frames"));
2507      (void)ComboBox_SetItemData(hCtrl, i++, 11);
2508   }
2509}
2510
2511/* Populate the Rotate drop down */
2512static void InitializeRotateUI(HWND hwnd)
2513{
2514   HWND hCtrl = GetDlgItem(hwnd, IDC_ROTATE);
2515
2516   if (hCtrl)
2517   {
2518      (void)ComboBox_AddString(hCtrl, TEXT("Default"));             // 0
2519      (void)ComboBox_AddString(hCtrl, TEXT("Clockwise"));           // 1
2520      (void)ComboBox_AddString(hCtrl, TEXT("Anti-clockwise"));      // 2
2521      (void)ComboBox_AddString(hCtrl, TEXT("None"));                // 3
2522      (void)ComboBox_AddString(hCtrl, TEXT("Auto clockwise"));      // 4
2523      (void)ComboBox_AddString(hCtrl, TEXT("Auto anti-clockwise")); // 5
2524   }
2525}
2526
2527/* Populate the Video Mode drop down */
2528static void InitializeVideoUI(HWND hwnd)
2529{
2530   HWND    hCtrl;
2531
2532   hCtrl = GetDlgItem(hwnd, IDC_VIDEO_MODE);
2533   if (hCtrl)
2534   {
2535      int i;
2536      for (i = 0; i < NUMVIDEO; i++)
2537      {
2538         (void)ComboBox_InsertString(hCtrl, i, g_ComboBoxVideo[i].m_pText);
2539         (void)ComboBox_SetItemData( hCtrl, i, g_ComboBoxVideo[i].m_pData);
2540      }
2541   }
2542}
2543
2544/* Populate the D3D Version drop down */
2545static void InitializeD3DVersionUI(HWND hwnd)
2546{
2547   HWND hCtrl = GetDlgItem(hwnd, IDC_D3D_VERSION);
2548   if (hCtrl)
2549   {
2550      int i;
2551      for (i = 0; i < NUMD3DVERSIONS; i++)
2552      {
2553         (void)ComboBox_InsertString(hCtrl, i, g_ComboBoxD3DVersion[i].m_pText);
2554         (void)ComboBox_SetItemData( hCtrl, i, g_ComboBoxD3DVersion[i].m_pData);
2555      }
2556   }
2557}
2558
2559static void UpdateSelectScreenUI(HWND hwnd)
2560{
2561   HWND hCtrl = GetDlgItem(hwnd, IDC_SCREENSELECT);
2562   if (hCtrl)
2563   {
2564      int i, curSel;
2565      curSel = ComboBox_GetCurSel(hCtrl);
2566      if ((curSel < 0) || (curSel >= MAX_SCREENS))
2567         curSel = 0;
2568      (void)ComboBox_ResetContent(hCtrl );
2569      for (i = 0; i < NUMSELECTSCREEN && i < options_get_int(pCurrentOpts, WINOPTION_NUMSCREENS) ; i++)
2570      {
2571         (void)ComboBox_InsertString(hCtrl, i, g_ComboBoxSelectScreen[i].m_pText);
2572         (void)ComboBox_SetItemData( hCtrl, i, g_ComboBoxSelectScreen[i].m_pData);
2573      }
2574      // Smaller Amount of screens was selected, so use 0
2575      if( i< curSel )
2576         (void)ComboBox_SetCurSel(hCtrl, 0 );
2577      else
2578         (void)ComboBox_SetCurSel(hCtrl, curSel );
2579   }
2580}
2581
2582/* Populate the Select Screen drop down */
2583static void InitializeSelectScreenUI(HWND hwnd)
2584{
2585   UpdateSelectScreenUI(hwnd);
2586}
2587
2588static void InitializeEffectUI(HWND hwnd)
2589{
2590}
2591
2592static void InitializeControllerMappingUI(HWND hwnd)
2593{
2594   int i;
2595   HWND hCtrl  = GetDlgItem(hwnd,IDC_PADDLE);
2596   HWND hCtrl1 = GetDlgItem(hwnd,IDC_ADSTICK);
2597   HWND hCtrl2 = GetDlgItem(hwnd,IDC_PEDAL);
2598   HWND hCtrl3 = GetDlgItem(hwnd,IDC_MOUSE);
2599   HWND hCtrl4 = GetDlgItem(hwnd,IDC_DIAL);
2600   HWND hCtrl5 = GetDlgItem(hwnd,IDC_TRACKBALL);
2601   HWND hCtrl6 = GetDlgItem(hwnd,IDC_LIGHTGUNDEVICE);
2602   HWND hCtrl7 = GetDlgItem(hwnd,IDC_POSITIONAL);
2603
2604   if (hCtrl)
2605   {
2606      for (i = 0; i < NUMDEVICES; i++)
2607      {
2608         (void)ComboBox_InsertString(hCtrl, i, g_ComboBoxDevice[i].m_pText);
2609         (void)ComboBox_SetItemData( hCtrl, i, g_ComboBoxDevice[i].m_pData);
2610      }
2611   }
2612   if (hCtrl1)
2613   {
2614      for (i = 0; i < NUMDEVICES; i++)
2615      {
2616         (void)ComboBox_InsertString(hCtrl1, i, g_ComboBoxDevice[i].m_pText);
2617         (void)ComboBox_SetItemData( hCtrl1, i, g_ComboBoxDevice[i].m_pData);
2618      }
2619   }
2620   if (hCtrl2)
2621   {
2622      for (i = 0; i < NUMDEVICES; i++)
2623      {
2624         (void)ComboBox_InsertString(hCtrl2, i, g_ComboBoxDevice[i].m_pText);
2625         (void)ComboBox_SetItemData( hCtrl2, i, g_ComboBoxDevice[i].m_pData);
2626      }
2627   }
2628   if (hCtrl3)
2629   {
2630      for (i = 0; i < NUMDEVICES; i++)
2631      {
2632         (void)ComboBox_InsertString(hCtrl3, i, g_ComboBoxDevice[i].m_pText);
2633         (void)ComboBox_SetItemData( hCtrl3, i, g_ComboBoxDevice[i].m_pData);
2634      }
2635   }
2636   if (hCtrl4)
2637   {
2638      for (i = 0; i < NUMDEVICES; i++)
2639      {
2640         (void)ComboBox_InsertString(hCtrl4, i, g_ComboBoxDevice[i].m_pText);
2641         (void)ComboBox_SetItemData( hCtrl4, i, g_ComboBoxDevice[i].m_pData);
2642      }
2643   }
2644   if (hCtrl5)
2645   {
2646      for (i = 0; i < NUMDEVICES; i++)
2647      {
2648         (void)ComboBox_InsertString(hCtrl5, i, g_ComboBoxDevice[i].m_pText);
2649         (void)ComboBox_SetItemData( hCtrl5, i, g_ComboBoxDevice[i].m_pData);
2650      }
2651   }
2652   if (hCtrl6)
2653   {
2654      for (i = 0; i < NUMDEVICES; i++)
2655      {
2656         (void)ComboBox_InsertString(hCtrl6, i, g_ComboBoxDevice[i].m_pText);
2657         (void)ComboBox_SetItemData( hCtrl6, i, g_ComboBoxDevice[i].m_pData);
2658      }
2659   }
2660   if (hCtrl7)
2661   {
2662      for (i = 0; i < NUMDEVICES; i++)
2663      {
2664         (void)ComboBox_InsertString(hCtrl7, i, g_ComboBoxDevice[i].m_pText);
2665         (void)ComboBox_SetItemData( hCtrl7, i, g_ComboBoxDevice[i].m_pData);
2666      }
2667   }
2668}
2669
2670
2671static void InitializeBIOSUI(HWND hwnd)
2672{
2673   HWND hCtrl = GetDlgItem(hwnd,IDC_BIOS);
2674   int i = 0;
2675   TCHAR* t_s;
2676   if (hCtrl)
2677   {
2678      const game_driver *gamedrv = drivers[g_nGame];
2679      const rom_entry *rom;
2680
2681      if (g_nGame == GLOBAL_OPTIONS)
2682      {
2683         (void)ComboBox_InsertString(hCtrl, i, TEXT("None"));
2684         (void)ComboBox_SetItemData( hCtrl, i++, "none");
2685         return;
2686      }
2687      if (g_nGame == FOLDER_OPTIONS) //Folder Options
2688      {
2689         gamedrv = drivers[g_nFolderGame];
2690         if (DriverHasOptionalBIOS(g_nFolderGame) == FALSE)
2691         {
2692            (void)ComboBox_InsertString(hCtrl, i, TEXT("None"));
2693            (void)ComboBox_SetItemData( hCtrl, i++, "default");
2694            return;
2695         }
2696         (void)ComboBox_InsertString(hCtrl, i, TEXT("Default"));
2697         (void)ComboBox_SetItemData( hCtrl, i++, "default");
2698
2699         if (gamedrv->rom != NULL)
2700         {
2701            for (rom = gamedrv->rom; !ROMENTRY_ISEND(rom); rom++)
2702            {
2703               if (ROMENTRY_ISSYSTEM_BIOS(rom))
2704               {
2705                  const char *name = ROM_GETHASHDATA(rom);
2706                  t_s = tstring_from_utf8(name);
2707                  if( !t_s )
2708                     return;
2709                  (void)ComboBox_InsertString(hCtrl, i, win_tstring_strdup(t_s));
2710                  (void)ComboBox_SetItemData( hCtrl, i++, name);
2711                  free(t_s);
2712               }
2713            }
2714         }
2715         return;
2716      }
2717
2718      if (DriverHasOptionalBIOS(g_nGame) == FALSE)
2719      {
2720         (void)ComboBox_InsertString(hCtrl, i, TEXT("None"));
2721         (void)ComboBox_SetItemData( hCtrl, i++, "none");
2722         return;
2723      }
2724      (void)ComboBox_InsertString(hCtrl, i, TEXT("Default"));
2725      (void)ComboBox_SetItemData( hCtrl, i++, "default");
2726
2727      if (gamedrv->rom != NULL)
2728      {
2729         for (rom = gamedrv->rom; !ROMENTRY_ISEND(rom); rom++)
2730         {
2731            if (ROMENTRY_ISSYSTEM_BIOS(rom))
2732            {
2733               const char *name = ROM_GETHASHDATA(rom);
2734               t_s = tstring_from_utf8(name);
2735               if( !t_s )
2736                  return;
2737               (void)ComboBox_InsertString(hCtrl, i, win_tstring_strdup(t_s));
2738               (void)ComboBox_SetItemData( hCtrl, i++, name);
2739               free(t_s);
2740            }
2741         }
2742      }
2743   }
2744}
2745
2746static BOOL SelectEffect(HWND hWnd)
2747{
2748   char filename[MAX_PATH];
2749   BOOL changed = FALSE;
2750
2751   *filename = 0;
2752   if (CommonFileDialog(GetOpenFileName, filename, FILETYPE_EFFECT_FILES))
2753   {
2754      //strip Path and extension
2755      char buff[MAX_PATH];
2756      int i, j = 0, k = 0, l = 0;
2757      for(i=0; i<strlen(filename); i++ )
2758      {
2759         if( filename[i] == '\\' )
2760            j = i;
2761         if( filename[i] == '.' )
2762            k = i;
2763      }
2764      for(i=j+1;i<k;i++)
2765      {
2766         buff[l++] = filename[i];
2767      }
2768      buff[l] = '\0';
2769
2770      if (strcmp(buff, options_get_string(pCurrentOpts, WINOPTION_EFFECT)))
2771      {
2772         HWND control = GetDlgItem(hWnd, IDC_EFFECT);
2773         options_set_string(pCurrentOpts, WINOPTION_EFFECT, buff, OPTION_PRIORITY_CMDLINE);
2774         win_set_window_text_utf8(control, buff);
2775         // datamap_populate_control(properties_datamap, hWnd, pCurrentOpts, IDC_EFFECT);
2776         changed = TRUE;
2777      }
2778   }
2779   return changed;
2780}
2781
2782static BOOL ResetEffect(HWND hWnd)
2783{
2784   BOOL changed = FALSE;
2785   const char *new_value = "none";
2786
2787   if (strcmp(new_value, options_get_string(pCurrentOpts, WINOPTION_EFFECT)))
2788   {
2789      HWND control = GetDlgItem(hWnd, IDC_EFFECT);
2790      options_set_string(pCurrentOpts, WINOPTION_EFFECT, new_value, OPTION_PRIORITY_CMDLINE);
2791      win_set_window_text_utf8(control, new_value);
2792      // datamap_populate_control(properties_datamap, hWnd, pCurrentOpts, IDC_EFFECT);
2793      changed = TRUE;
2794   }
2795   return changed;
2796}
2797
2798
2799void UpdateBackgroundBrush(HWND hwndTab)
2800{
2801    // Destroy old brush
2802    if (hBkBrush)
2803        DeleteObject(hBkBrush);
2804
2805    hBkBrush = NULL;
2806
2807    // Only do this if the theme is active
2808    if (SafeIsAppThemed())
2809    {
2810        RECT rc;
2811        HDC hDC, hDCMem;
2812      HBITMAP hBmp, hBmpOld;
2813        // Get tab control dimensions
2814        GetWindowRect( hwndTab, &rc);
2815
2816        // Get the tab control DC
2817      hDC = GetDC(hwndTab);
2818
2819        // Create a compatible DC
2820        hDCMem = CreateCompatibleDC(hDC);
2821        hBmp = CreateCompatibleBitmap(hDC,
2822               rc.right - rc.left, rc.bottom - rc.top);
2823        hBmpOld = (HBITMAP)(SelectObject(hDCMem, hBmp));
2824
2825        // Tell the tab control to paint in our DC
2826        SendMessage(hwndTab, WM_PRINTCLIENT, (WPARAM)(hDCMem),
2827           (LPARAM)(PRF_ERASEBKGND | PRF_CLIENT | PRF_NONCLIENT));
2828
2829        // Create a pattern brush from the bitmap selected in our DC
2830        hBkBrush = CreatePatternBrush(hBmp);
2831
2832        // Restore the bitmap
2833        SelectObject(hDCMem, hBmpOld);
2834
2835        // Cleanup
2836        DeleteObject(hBmp);
2837        DeleteDC(hDCMem);
2838        ReleaseDC(hwndTab, hDC);
2839    }
2840}
2841
2842
2843/* End of source file */
src/osd/winui/help.h
r0r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11 ***************************************************************************/
12
13#ifndef HELP_H
14#define HELP_H
15
16#if defined(__GNUC__)
17#define HH_DISPLAY_TOPIC      0
18#define HH_TP_HELP_CONTEXTMENU   16
19#define HH_TP_HELP_WM_HELP      17
20#define HH_CLOSE_ALL         18
21#define HH_INITIALIZE         28
22#define HH_UNINITIALIZE         29
23#else
24#include <htmlhelp.h>
25#endif
26
27typedef struct
28{
29   int      nMenuItem;
30   BOOL   bIsHtmlHelp;
31   LPCSTR   lpFile;
32} MAMEHELPINFO;
33
34extern const MAMEHELPINFO g_helpInfo[];
35
36#if !defined(MAME32HELP)
37#define MAME32HELP "mame32.chm"
38#endif
39
40#if !defined(MAME32CONTEXTHELP)
41#define MAME32CONTEXTHELP "mame32.chm::/cntx_help.txt"
42#endif
43
44extern int HelpInit(void);
45extern void HelpExit(void);
46extern HWND HelpFunction(HWND hwndCaller, LPCSTR pszFile, UINT uCommand, DWORD_PTR dwData);
47
48#endif
src/osd/winui/directdraw.h
r0r996
1/***************************************************************************
2
3  M.A.M.E.32  -  Multiple Arcade Machine Emulator for Win32
4  Win32 Portions Copyright (C) 1997-2003 Michael Soderstrom and Chris Kirmse
5
6  This file is part of MAME32, and may only be used, modified and
7  distributed under the terms of the MAME license, in "readme.txt".
8  By continuing to use, modify or distribute this file you indicate
9  that you have read the license and understand and accept it fully.
10
11 ***************************************************************************/
12
13#ifndef DIRECTDRAW_H
14#define DIRECTDRAW_H
15
16#include <ddraw.h>
17
18#define MAXMODES    256 /* Maximum number of DirectDraw Display modes. */
19
20/* Display mode node */
21struct tDisplayMode
22{
23   DWORD m_dwWidth;
24   DWORD m_dwHeight;
25   DWORD m_dwBPP;
26   DWORD m_dwRefresh;
27};
28
29/* EnumDisplayMode Context */
30struct tDisplayModes
31{
32   struct tDisplayMode m_Modes[MAXMODES];
33   int                 m_nNumModes;
34};
35
36extern BOOL DirectDraw_Initialize(void);
37extern void DirectDraw_Close(void);
38
39extern struct tDisplayModes* DirectDraw_GetDisplayModes(void);
40extern int            DirectDraw_GetNumDisplays(void);
41extern BOOL           DirectDraw_HasHWStretch(void);
42extern BOOL           DirectDraw_HasRefresh(void);
43extern LPCTSTR        DirectDraw_GetDisplayName(int num_display);
44
45#endif
src/mess/osd/windows/mess.rc
r995r996
154154// Icon
155155//
156156
157IDI_ICON_CART           ICON    DISCARDABLE     "../../osd/windows/ui/res/cpu.ico"
158IDI_ICON_HARD           ICON    DISCARDABLE     "../../osd/windows/ui/res/harddisk.ico"
159IDI_ICON_CASS           ICON    DISCARDABLE     "../../mess/osd/windows/ui/res/win_cass.ico"
160IDI_ICON_FLOP           ICON    DISCARDABLE     "../../mess/osd/windows/ui/res/win_flop.ico"
161IDI_ICON_PRIN           ICON    DISCARDABLE     "../../mess/osd/windows/ui/res/win_prin.ico"
162IDI_ICON_SERL           ICON    DISCARDABLE     "../../mess/osd/windows/ui/res/win_serl.ico"
163IDI_ICON_SNAP           ICON    DISCARDABLE     "../../mess/osd/windows/ui/res/win_snap.ico"
157IDI_ICON_CART           ICON    DISCARDABLE     "../../osd/winui/res/cpu.ico"
158IDI_ICON_HARD           ICON    DISCARDABLE     "../../osd/winui/res/harddisk.ico"
159IDI_ICON_CASS           ICON    DISCARDABLE     "../../mess/osd/winui/res/win_cass.ico"
160IDI_ICON_FLOP           ICON    DISCARDABLE     "../../mess/osd/winui/res/win_flop.ico"
161IDI_ICON_PRIN           ICON    DISCARDABLE     "../../mess/osd/winui/res/win_prin.ico"
162IDI_ICON_SERL           ICON    DISCARDABLE     "../../mess/osd/winui/res/win_serl.ico"
163IDI_ICON_SNAP           ICON    DISCARDABLE     "../../mess/osd/winui/res/win_snap.ico"
164164
165165
166166/////////////////////////////////////////////////////////////////////////////
src/mess/osd/windows/ui/mess32.rc
r995r996
1#include "resource.h"
2#include "resourcems.h"
3#include "windows.h"
4#include "commctrl.h"
5
6/////////////////////////////////////////////////////////////////////////////
7//
8// Dialog
9//
10
11IDD_PROP_SOFTWARE DIALOGEX 0, 0, 220, 220
12STYLE WS_CHILD | WS_CAPTION
13CAPTION "Software"
14FONT 8, "MS Sans Serif"
15BEGIN
16    ICON            IDI_WIN_FLOP,IDC_STATIC,20,10,20,20
17    LTEXT           "Title\nDirectory\nExtra",IDC_PROP_TITLE,52,9,161,25,
18                    SS_NOPREFIX
19    CONTROL         "",IDC_STATIC,"Static",SS_ETCHEDHORZ,20,38,178,1
20    LTEXT           "Additional directories:",IDC_STATIC,7,40,157,8
21    CONTROL         "List1",IDC_DIR_LIST,"SysListView32",LVS_REPORT |
22                    LVS_SINGLESEL | LVS_SHOWSELALWAYS | LVS_EDITLABELS |
23                    LVS_ALIGNLEFT | LVS_NOCOLUMNHEADER | WS_BORDER |
24                    WS_TABSTOP,7,50,206,120
25    PUSHBUTTON      "Browse...",IDC_DIR_BROWSE,7,180,50,14
26    PUSHBUTTON      "Insert",IDC_DIR_INSERT,85,180,50,14
27    PUSHBUTTON      "Delete",IDC_DIR_DELETE,163,180,50,14
28END
29
30
31IDD_PROP_CONFIGURATION DIALOGEX 0, 0, 220, 220
32STYLE WS_CHILD | WS_CAPTION
33CAPTION "Configuration"
34FONT 8, "MS Sans Serif"
35BEGIN
36    ICON            IDI_MAME32_ICON,IDC_STATIC,20,10,20,20
37    LTEXT           "Title\nDirectory\nExtra",IDC_PROP_TITLE,52,9,161,25,
38                    SS_NOPREFIX
39    CONTROL         "",IDC_STATIC,"Static",SS_ETCHEDHORZ,20,38,178,1
40    LTEXT           "RAM size",IDC_RAM_CAPTION,20,50,50,10
41    COMBOBOX        IDC_RAM_COMBOBOX,70,50,100,76,CBS_DROPDOWNLIST | WS_VSCROLL |
42                    WS_TABSTOP
43END
44
45/////////////////////////////////////////////////////////////////////////////
46
47#include "ui/mame32.rc"
src/mess/osd/windows/ui/cfgfile.c
r995r996
1
2#define WIN32_LEAN_AND_MEAN
3
4#include <windows.h>
5#include <windowsx.h>
6#include <winreg.h>
7#include <commctrl.h>
8#include <assert.h>
9#include <stdio.h>
10#include <sys/stat.h>
11#include <malloc.h>
12#include <math.h>
13#include <direct.h>
14#include <driver.h>
15
16#include "screenshot.h"
17#include "bitmask.h"
18#include "mame32.h"
19#include "m32util.h"
20#include "resource.h"
21#include "treeview.h"
22#include "file.h"
23#include "splitters.h"
24#include "dijoystick.h"
25#include "audit.h"
26#include "optcore.h"
27#include "options.h"
28#include "picker.h"
29#include "windows/config.h"
30
31
32
33static BOOL SettingsFileName(DWORD nSettingsFile, char *buffer, size_t bufsize)
34{
35   extern FOLDERDATA g_folderData[];
36   extern LPEXFOLDERDATA ExtraFolderData[];
37   char *ptr;
38   int i;
39   BOOL success = TRUE;
40   char title[32];
41   DWORD arg = nSettingsFile & 0x0FFFFFFF;
42   const char *pParent;
43
44   switch(nSettingsFile & 0xF0000000)
45   {
46      case SETTINGS_FILE_UI:
47         _snprintf(buffer, bufsize, "%s", MAME32NAME "ui.ini");
48         break;
49
50      case SETTINGS_FILE_GLOBAL:
51         _snprintf(buffer, bufsize, "%s", "default.cfg");
52         break;
53
54      case SETTINGS_FILE_GAME:
55         snprintf(buffer, bufsize, "%s", drivers[arg]->name);
56         break;
57
58      case SETTINGS_FILE_FOLDER:
59         snprintf(buffer, bufsize, "%s", g_folderData[arg].m_lpTitle);
60         break;
61
62      case SETTINGS_FILE_EXFOLDER:
63         snprintf(buffer, bufsize, "%s", ExtraFolderData[arg]->m_szTitle );
64         break;
65
66      case SETTINGS_FILE_SOURCEFILE:
67         //we have a source ini to create, so remove the ".c" at the end of the title
68         assert(arg >= 0);
69         assert(arg < GetNumGames());
70         strncpy(title, drivers[arg]->source_file, strlen(drivers[arg]->source_file)-2 );
71         title[strlen(drivers[arg]->source_file)-2] = '\0';
72
73         //Core expects it there
74         snprintf(buffer, bufsize, "drivers\\%s", title );
75         break;
76
77      case SETTINGS_FILE_EXFOLDERPARENT:
78         pParent = GetFolderNameByID(ExtraFolderData[arg]->m_nParent);
79         snprintf(buffer, bufsize, "%s\\%s", pParent, ExtraFolderData[arg]->m_szTitle );
80         break;
81
82      default:
83         success = FALSE;
84         break;
85   }
86   return success;
87}
88
89
90
91BOOL LoadSettingsFileEx(DWORD nSettingsFile, const struct SettingsHandler *handlers)
92{
93   char buffer[256];
94   mame_file *file = NULL;
95   struct xml_data_node *node = NULL;
96   BOOL success = FALSE;
97
98   if (!SettingsFileName(nSettingsFile, buffer, sizeof(buffer) / sizeof(buffer[0])))
99      goto done;
100
101   file = mame_fopen(buffer, 0, FILETYPE_CONFIG, 0);
102   if (!file)
103      goto done;
104
105   node = xml_file_read(file);
106   if (!node)
107      goto done;
108
109done:
110   if (node)
111      xml_file_free(node);
112   if (file)
113      mame_fclose(file);
114   return success;
115}
116
117
118
119BOOL SaveSettingsFileEx(DWORD nSettingsFile, const struct SettingsHandler *handlers)
120{
121   char buffer[256];
122   mame_file *file = NULL;
123   struct xml_data_node *node = NULL;
124   BOOL success = FALSE;
125
126   if (!SettingsFileName(nSettingsFile, buffer, sizeof(buffer) / sizeof(buffer[0])))
127      goto done;
128
129   file = mame_fopen(buffer, 0, FILETYPE_CONFIG, 0);
130   if (!file)
131      goto done;
132
133   node = xml_file_read(file);
134   if (!node)
135      goto done;
136
137   mame_fclose(file);
138   file = mame_fopen(buffer, 0, FILETYPE_CONFIG, 1);
139   if (!file)
140      goto done;
141
142   xml_file_write(node, file);
143
144done:
145   if (node)
146      xml_file_free(node);
147   if (file)
148      mame_fclose(file);
149   return success;
150}
src/mess/osd/windows/ui/optionsms.h
r995r996
1#ifndef OPTIONSMS_H
2#define OPTIONSMS_H
3
4#include "device.h"
5#include "options.h"
6
7enum
8{
9   MESS_COLUMN_IMAGES,
10   MESS_COLUMN_GOODNAME,
11   MESS_COLUMN_MANUFACTURER,
12   MESS_COLUMN_YEAR,
13   MESS_COLUMN_PLAYABLE,
14   MESS_COLUMN_CRC,
15   MESS_COLUMN_SHA1,
16   MESS_COLUMN_MD5,
17   MESS_COLUMN_MAX
18};
19
20void MessSetupSettings(core_options *settings);
21void MessSetupGameOptions(core_options *opts, int driver_index);
22
23void SetMessColumnWidths(int widths[]);
24void GetMessColumnWidths(int widths[]);
25
26void SetMessColumnOrder(int order[]);
27void GetMessColumnOrder(int order[]);
28
29void SetMessColumnShown(int shown[]);
30void GetMessColumnShown(int shown[]);
31
32void SetMessSortColumn(int column);
33int  GetMessSortColumn(void);
34
35void SetMessSortReverse(BOOL reverse);
36BOOL GetMessSortReverse(void);
37
38const char* GetSoftwareDirs(void);
39void  SetSoftwareDirs(const char* paths);
40
41void SetHashDirs(const char *dir);
42const char *GetHashDirs(void);
43
44void SetSelectedSoftware(int driver_index, const device_class *devclass, int device_inst, const char *software);
45const char *GetSelectedSoftware(int driver_index, const device_class *devclass, int device_inst);
46
47void SetExtraSoftwarePaths(int driver_index, const char *extra_paths);
48const char *GetExtraSoftwarePaths(int driver_index);
49
50void SetCurrentSoftwareTab(const char *shortname);
51const char *GetCurrentSoftwareTab(void);
52
53#endif /* OPTIONSMS_H */
54
src/mess/osd/windows/ui/propertiesms.h
r995r996
1#ifndef PROPERTIESMS_H
2#define PROPERTIESMS_H
3
4#include "ui/properties.h"
5#include "ui/datamap.h"
6
7BOOL MessPropertiesCommand(HWND hWnd, WORD wNotifyCode, WORD wID, BOOL *changed);
8
9INT_PTR CALLBACK GameMessOptionsProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam);
10BOOL PropSheetFilter_Config(const machine_config *drv, const game_driver *gamedrv);
11
12void MessBuildDataMap(datamap *properties_datamap);
13
14#endif /* PROPERTIESMS_H */
src/mess/osd/windows/ui/devview.c
r995r996
1// ------------------------------------------------------------------------
2// Software Device View class                                             
3// ------------------------------------------------------------------------
4
5#define WIN32_LEAN_AND_MEAN
6#include <assert.h>
7#include <string.h>
8#include <windows.h>
9#include <shellapi.h>
10#include <commctrl.h>
11#include <commdlg.h>
12#include <wingdi.h>
13#include <winuser.h>
14#include <tchar.h>
15
16#include "driver.h"
17#include "devview.h"
18#include "optionsms.h"
19#include "uitext.h"
20#include "strconv.h"
21#include "winutf8.h"
22#include "ui/m32util.h"
23
24#define DEVVIEW_PADDING   10
25
26
27struct DevViewInfo
28{
29   HFONT hFont;
30   int nGame;
31   int nWidth;
32   BOOL bSurpressFilenameChanged;
33   const struct IODevice *pDevices;
34   const struct DevViewCallbacks *pCallbacks;
35   struct DevViewEntry *pEntries;
36};
37
38
39
40struct DevViewEntry
41{
42   const struct IODevice *dev;
43   int id;
44   HWND hwndStatic;
45   HWND hwndEdit;
46   HWND hwndBrowseButton;
47   WNDPROC pfnEditWndProc;
48};
49
50
51
52static struct DevViewInfo *GetDevViewInfo(HWND hwndDevView)
53{
54   LONG_PTR l;
55   l = GetWindowLongPtr(hwndDevView, GWLP_USERDATA);
56   return (struct DevViewInfo *) l;
57}
58
59
60
61static void DevView_Clear(HWND hwndDevView)
62{
63   struct DevViewInfo *pDevViewInfo;
64   int i;
65
66   pDevViewInfo = GetDevViewInfo(hwndDevView);
67
68   if (pDevViewInfo->pEntries != NULL)
69   {
70      for (i = 0; pDevViewInfo->pEntries[i].dev; i++)
71      {
72         DestroyWindow(pDevViewInfo->pEntries[i].hwndStatic);
73         DestroyWindow(pDevViewInfo->pEntries[i].hwndEdit);
74         DestroyWindow(pDevViewInfo->pEntries[i].hwndBrowseButton);
75      }
76      free(pDevViewInfo->pEntries);
77      pDevViewInfo->pEntries = NULL;
78   }
79
80   if (pDevViewInfo->pDevices != NULL)
81   {
82      devices_free(pDevViewInfo->pDevices);
83      pDevViewInfo->pDevices = NULL;
84   }
85}
86
87
88
89static void DevView_GetColumns(HWND hwndDevView, int *pnStaticPos, int *pnStaticWidth,
90   int *pnEditPos, int *pnEditWidth, int *pnButtonPos, int *pnButtonWidth)
91{
92   struct DevViewInfo *pDevViewInfo;
93   RECT r;
94
95   pDevViewInfo = GetDevViewInfo(hwndDevView);
96
97   GetClientRect(hwndDevView, &r);
98
99   *pnStaticPos = DEVVIEW_PADDING;
100   *pnStaticWidth = pDevViewInfo->nWidth;
101
102   *pnButtonWidth = 25;
103   *pnButtonPos = (r.right - r.left) - *pnButtonWidth - DEVVIEW_PADDING;
104
105   *pnEditPos = *pnStaticPos + *pnStaticWidth + DEVVIEW_PADDING;
106   *pnEditWidth = *pnButtonPos - *pnEditPos - DEVVIEW_PADDING;
107   if (*pnEditWidth < 0)
108      *pnEditWidth = 0;
109}
110
111
112
113void DevView_Refresh(HWND hwndDevView)
114{
115   struct DevViewInfo *pDevViewInfo;
116   int i;
117   LPCTSTR pszSelection;
118   TCHAR szBuffer[MAX_PATH];
119
120   pDevViewInfo = GetDevViewInfo(hwndDevView);
121
122   if (pDevViewInfo->pEntries)
123   {
124      for (i = 0; pDevViewInfo->pEntries[i].dev; i++)
125      {
126         pszSelection = pDevViewInfo->pCallbacks->pfnGetSelectedSoftware(
127            hwndDevView,
128            pDevViewInfo->nGame,
129            pDevViewInfo->pEntries[i].dev,
130            pDevViewInfo->pEntries[i].id,
131            szBuffer, sizeof(szBuffer) / sizeof(szBuffer[0]));
132
133         if (!pszSelection)
134            pszSelection = TEXT("");
135
136         pDevViewInfo->bSurpressFilenameChanged = TRUE;
137         SetWindowText(pDevViewInfo->pEntries[i].hwndEdit, pszSelection);
138         pDevViewInfo->bSurpressFilenameChanged = FALSE;
139      }
140   }
141}
142
143
144
145static void DevView_TextChanged(HWND hwndDevView, int nChangedEntry, LPCTSTR pszFilename)
146{
147   struct DevViewInfo *pDevViewInfo;
148   
149   pDevViewInfo = GetDevViewInfo(hwndDevView);
150   if (!pDevViewInfo->bSurpressFilenameChanged && pDevViewInfo->pCallbacks->pfnSetSelectedSoftware)
151   {
152      pDevViewInfo->pCallbacks->pfnSetSelectedSoftware(hwndDevView,
153         pDevViewInfo->nGame,
154         pDevViewInfo->pEntries[nChangedEntry].dev,
155         pDevViewInfo->pEntries[nChangedEntry].id,
156         pszFilename);
157   }
158}
159
160
161
162static LRESULT CALLBACK DevView_EditWndProc(HWND hwndEdit, UINT nMessage, WPARAM wParam, LPARAM lParam)
163{
164   struct DevViewInfo *pDevViewInfo;
165   struct DevViewEntry *pEnt;
166   LRESULT rc;
167   HWND hwndDevView;
168   LONG_PTR l;
169
170   l = GetWindowLongPtr(hwndEdit, GWLP_USERDATA);
171   pEnt = (struct DevViewEntry *) l;
172   if (IsWindowUnicode(hwndEdit))
173      rc = CallWindowProcW(pEnt->pfnEditWndProc, hwndEdit, nMessage, wParam, lParam);
174   else
175      rc = CallWindowProcA(pEnt->pfnEditWndProc, hwndEdit, nMessage, wParam, lParam);
176
177   if (nMessage == WM_SETTEXT)
178   {
179      hwndDevView = GetParent(hwndEdit);
180      pDevViewInfo = GetDevViewInfo(hwndDevView);
181      DevView_TextChanged(hwndDevView, pEnt - pDevViewInfo->pEntries, (LPCTSTR) lParam);
182   }
183   return rc;
184}
185
186
187
188BOOL DevView_SetDriver(HWND hwndDevView, int nGame)
189{
190   struct DevViewInfo *pDevViewInfo;
191   const game_driver *drv;
192   const struct IODevice *devices;
193   const struct IODevice *dev;
194   struct DevViewEntry *pEnt;
195   int i, id;
196   int y, nHeight, nDevCount;
197   int nStaticPos, nStaticWidth, nEditPos, nEditWidth, nButtonPos, nButtonWidth;
198   HDC hDc;
199   LPTSTR *ppszDevices;
200   LPTSTR s;
201   SIZE sz;
202   char buf[128];
203   LONG_PTR l;
204   const char* utf8_s;
205
206   pDevViewInfo = GetDevViewInfo(hwndDevView);
207
208   // already selected this driver?
209   if (nGame == pDevViewInfo->nGame)
210      return TRUE;
211
212   DevView_Clear(hwndDevView);
213   drv = drivers[nGame];
214   devices = pDevViewInfo->pDevices = devices_allocate(drv);
215
216   // Count total amount of devices
217   nDevCount = 0;
218   for (dev = devices; dev->type < IO_COUNT; dev++)
219      nDevCount += dev->count;
220
221   if (nDevCount > 0)
222   {
223      // Get the names of all of the devices
224      ppszDevices = (LPTSTR *) alloca(nDevCount * sizeof(*ppszDevices));
225      i = 0;
226      for (dev = devices; dev->type < IO_COUNT; dev++)
227      {
228         for (id = 0; id < dev->count; id++)
229         {
230            utf8_s = dev->name(dev, id, buf, sizeof(buf) / sizeof(buf[0]));
231            s = tstring_from_utf8(utf8_s);
232            ppszDevices[i] = alloca((_tcslen(s) + 1) * sizeof(TCHAR));
233            _tcscpy(ppszDevices[i], s);
234            free(s);
235            i++;
236         }
237      }
238
239      // Calculate the requisite size for the device column
240      pDevViewInfo->nWidth = 0;
241      if (nDevCount > 0)
242      {
243         hDc = GetDC(hwndDevView);
244         for (i = 0; i < nDevCount; i++)
245         {
246            GetTextExtentPoint32(hDc, ppszDevices[i], _tcslen(ppszDevices[i]), &sz);
247            if (sz.cx > pDevViewInfo->nWidth)
248               pDevViewInfo->nWidth = sz.cx;
249         }
250         ReleaseDC(hwndDevView, hDc);
251      }
252
253      pEnt = (struct DevViewEntry *) malloc(sizeof(struct DevViewEntry) * (nDevCount + 1));
254      if (!pEnt)
255         return FALSE;
256      memset(pEnt, 0, sizeof(struct DevViewEntry) * (nDevCount + 1));
257      pDevViewInfo->pEntries = pEnt;
258
259      y = 10;
260      nHeight = 21;
261      DevView_GetColumns(hwndDevView, &nStaticPos, &nStaticWidth,
262         &nEditPos, &nEditWidth, &nButtonPos, &nButtonWidth);
263
264      for (dev = devices; dev->type < IO_COUNT; dev++)
265      {
266         for (id = 0; id < dev->count; id++)
267         {
268            pEnt->dev = dev;
269            pEnt->id = id;
270
271            pEnt->hwndStatic = win_create_window_ex_utf8(0, "STATIC", dev->name(dev, id, buf, sizeof(buf) / sizeof(buf[0])),
272               WS_VISIBLE | WS_CHILD, nStaticPos, y, nStaticWidth, nHeight,
273               hwndDevView, NULL, NULL, NULL);
274
275            pEnt->hwndEdit = win_create_window_ex_utf8(0, "EDIT", "",
276               WS_VISIBLE | WS_CHILD | WS_BORDER | ES_AUTOHSCROLL, nEditPos, y, nEditWidth, nHeight,
277               hwndDevView, NULL, NULL, NULL);
278
279            pEnt->hwndBrowseButton = win_create_window_ex_utf8(0, "BUTTON", "...",
280               WS_VISIBLE | WS_CHILD, nButtonPos, y, nButtonWidth, nHeight,
281               hwndDevView, NULL, NULL, NULL);
282
283            if (pEnt->hwndStatic)
284            {
285               SendMessage(pEnt->hwndStatic, WM_SETFONT, (WPARAM) pDevViewInfo->hFont, TRUE);
286            }
287            if (pEnt->hwndEdit)
288            {
289               SendMessage(pEnt->hwndEdit, WM_SETFONT, (WPARAM) pDevViewInfo->hFont, TRUE);
290               l = (LONG_PTR) DevView_EditWndProc;
291               l = SetWindowLongPtr(pEnt->hwndEdit, GWLP_WNDPROC, l);
292               pEnt->pfnEditWndProc = (WNDPROC) l;
293               SetWindowLongPtr(pEnt->hwndEdit, GWLP_USERDATA, (LONG_PTR) pEnt);
294            }
295            if (pEnt->hwndBrowseButton)
296            {
297               SetWindowLongPtr(pEnt->hwndBrowseButton, GWLP_USERDATA, (LONG_PTR) pEnt);
298            }
299
300            y += nHeight;
301            pEnt++;
302         }
303      }
304   }
305
306   pDevViewInfo->nGame = nGame;
307   DevView_Refresh(hwndDevView);
308   return TRUE;
309}
310
311
312
313static void DevView_ButtonClick(HWND hwndDevView, struct DevViewEntry *pEnt, HWND hwndButton)
314{
315   struct DevViewInfo *pDevViewInfo;
316   HMENU hMenu;
317   RECT r;
318   int rc;
319   BOOL b;
320   TCHAR szPath[MAX_PATH];
321
322   pDevViewInfo = GetDevViewInfo(hwndDevView);
323
324   hMenu = CreatePopupMenu();
325
326   if (pDevViewInfo->pCallbacks->pfnGetOpenFileName)
327      AppendMenu(hMenu, MF_STRING, 1, TEXT("Mount..."));
328
329   if (pEnt->dev->creatable)
330   {
331      if (pDevViewInfo->pCallbacks->pfnGetCreateFileName)
332         AppendMenu(hMenu, MF_STRING, 2, TEXT("Create..."));
333   }
334
335   AppendMenu(hMenu, MF_STRING, 3, TEXT("Unmount"));
336
337   GetWindowRect(hwndButton, &r);
338   rc = TrackPopupMenu(hMenu, TPM_TOPALIGN | TPM_NONOTIFY | TPM_RETURNCMD,
339      r.left, r.bottom, 0, hwndDevView, NULL);
340
341   switch(rc)
342   {
343      case 1:
344         b = pDevViewInfo->pCallbacks->pfnGetOpenFileName(hwndDevView, pEnt->dev,
345            szPath, sizeof(szPath) / sizeof(szPath[0]));
346         break;
347      case 2:
348         b = pDevViewInfo->pCallbacks->pfnGetCreateFileName(hwndDevView, pEnt->dev,
349            szPath, sizeof(szPath) / sizeof(szPath[0]));
350         break;
351      case 3:
352         memset(szPath, 0, sizeof(szPath));
353         b = TRUE;
354         break;
355      default:
356         b = FALSE;
357         break;
358   }
359   if (!b)
360      return;
361   SetWindowText(pEnt->hwndEdit, szPath);
362}
363
364
365
366static BOOL DevView_Setup(HWND hwndDevView)
367{
368   struct DevViewInfo *pDevViewInfo;
369
370   pDevViewInfo = malloc(sizeof(struct DevViewInfo));
371   if (!pDevViewInfo)
372      return FALSE;
373   memset(pDevViewInfo, 0, sizeof(*pDevViewInfo));
374   pDevViewInfo->nGame = -1;
375   SetWindowLongPtr(hwndDevView, GWLP_USERDATA, (LONG_PTR) pDevViewInfo);
376
377   pDevViewInfo->hFont = CreateFont(10, 0, 0, 0, FW_NORMAL, 0, 0, 0, 0, 0,
378      0, 0, 0, TEXT("MS Sans Serif"));
379   SendMessage(hwndDevView, WM_SETFONT, (WPARAM) pDevViewInfo->hFont, FALSE);
380   return TRUE;
381}
382
383
384
385static void DevView_Free(HWND hwndDevView)
386{
387   struct DevViewInfo *pDevViewInfo;
388
389   DevView_Clear(hwndDevView);
390   pDevViewInfo = GetDevViewInfo(hwndDevView);
391   DeleteObject(pDevViewInfo->hFont);
392   free(pDevViewInfo);
393}
394
395
396
397static LRESULT CALLBACK DevView_WndProc(HWND hwndDevView, UINT nMessage, WPARAM wParam, LPARAM lParam)
398{
399   struct DevViewInfo *pDevViewInfo;
400   struct DevViewEntry *pEnt;
401   int nStaticPos, nStaticWidth, nEditPos, nEditWidth, nButtonPos, nButtonWidth;
402   RECT r;
403   LONG_PTR l;
404   LRESULT rc = 0;
405   BOOL bHandled = FALSE;
406   HWND hwndButton;
407
408   switch(nMessage)
409   {
410      case WM_DESTROY:
411         DevView_Free(hwndDevView);
412         break;
413
414      case WM_SHOWWINDOW:
415         if (wParam)
416         {
417            pDevViewInfo = GetDevViewInfo(hwndDevView);
418            DevView_Refresh(hwndDevView);
419         }
420         break;
421
422      case WM_COMMAND:
423         switch(HIWORD(wParam))
424         {
425            case BN_CLICKED:
426               hwndButton = (HWND) lParam;
427               l = GetWindowLongPtr(hwndButton, GWLP_USERDATA);
428               pEnt = (struct DevViewEntry *) l;
429               DevView_ButtonClick(hwndDevView, pEnt, hwndButton);
430               break;           
431         }
432         break;
433   }
434
435   if (!bHandled)
436      rc = DefWindowProc(hwndDevView, nMessage, wParam, lParam);
437
438   switch(nMessage)
439   {
440      case WM_CREATE:
441         if (!DevView_Setup(hwndDevView))
442            return -1;
443         break;
444
445      case WM_MOVE:
446      case WM_SIZE:
447         pDevViewInfo = GetDevViewInfo(hwndDevView);
448         pEnt = pDevViewInfo->pEntries;
449         if (pEnt)
450         {
451            DevView_GetColumns(hwndDevView, &nStaticPos, &nStaticWidth,
452               &nEditPos, &nEditWidth, &nButtonPos, &nButtonWidth);
453            while(pEnt->dev)
454            {
455               GetClientRect(pEnt->hwndStatic, &r);
456               MapWindowPoints(pEnt->hwndStatic, hwndDevView, ((POINT *) &r), 2);
457               MoveWindow(pEnt->hwndStatic, nStaticPos, r.top, nStaticWidth, r.bottom - r.top, FALSE);
458               MoveWindow(pEnt->hwndEdit, nEditPos, r.top, nEditWidth, r.bottom - r.top, FALSE);
459               MoveWindow(pEnt->hwndBrowseButton, nButtonPos, r.top, nButtonWidth, r.bottom - r.top, FALSE);
460               pEnt++;
461            }
462         }
463         break;
464   }
465   return rc;
466}
467
468
469
470void DevView_SetCallbacks(HWND hwndDevView, const struct DevViewCallbacks *pCallbacks)
471{
472   struct DevViewInfo *pDevViewInfo;
473   pDevViewInfo = GetDevViewInfo(hwndDevView);
474   pDevViewInfo->pCallbacks = pCallbacks;
475}
476
477
478
479void DevView_RegisterClass(void)
480{
481   WNDCLASS wc;
482   memset(&wc, 0, sizeof(wc));
483   wc.lpszClassName = TEXT("MessSoftwareDevView");
484   wc.hInstance = GetModuleHandle(NULL);
485   wc.lpfnWndProc = DevView_WndProc;
486   wc.hbrBackground = GetSysColorBrush(COLOR_BTNFACE);
487   RegisterClass(&wc);
488}
489
490
491
src/mess/osd/windows/ui/mess32ui.c
r995r996
1//============================================================
2//
3//   mess32ui.c - MESS extensions to src/ui/win32ui.c
4//
5//============================================================
6
7#define WIN32_LEAN_AND_MEAN
8#include <assert.h>
9#include <string.h>
10#include <windows.h>
11#include <shellapi.h>
12#include <commctrl.h>
13#include <commdlg.h>
14#include <wingdi.h>
15#include <winuser.h>
16#include <tchar.h>
17
18#include "ui/screenshot.h"
19#include "ui/bitmask.h"
20#include "ui/mame32.h"
21#include "ui/resourcems.h"
22#include "ui/m32opts.h"
23#include "ui/picker.h"
24#include "ui/tabview.h"
25#include "ui/m32util.h"
26#include "ui/columnedit.h"
27#include "mess.h"
28#include "configms.h"
29#include "softwarepicker.h"
30#include "devview.h"
31#include "windows/window.h"
32#include "utils.h"
33#include "uitext.h"
34#include "strconv.h"
35#include "mess32ui.h"
36#include "winutf8.h"
37
38#define LOG_SOFTWARE   0
39
40static int requested_device_type(char *tchar);
41
42static void SoftwarePicker_OnHeaderContextMenu(POINT pt, int nColumn);
43
44static LPCSTR SoftwareTabView_GetTabShortName(int tab);
45static LPCSTR SoftwareTabView_GetTabLongName(int tab);
46static void SoftwareTabView_OnSelectionChanged(void);
47static void SoftwareTabView_OnMoveSize(void);
48static void SetupSoftwareTabView(void);
49
50static LPCTSTR mess_column_names[] =
51{
52    TEXT("Software"),
53   TEXT("Goodname"),
54    TEXT("Manufacturer"),
55    TEXT("Year"),
56    TEXT("Playable"),
57   TEXT("CRC"),
58   TEXT("SHA-1"),
59   TEXT("MD5")
60};
61
62static int *mess_icon_index;
63
64static void MessOpenOtherSoftware(int iDevice);
65static void MessCreateDevice(int iDevice);
66static void MessRefreshPicker(int nGame);
67
68static int SoftwarePicker_GetItemImage(HWND hwndPicker, int nItem);
69static void SoftwarePicker_LeavingItem(HWND hwndSoftwarePicker, int nItem);
70static void SoftwarePicker_EnteringItem(HWND hwndSoftwarePicker, int nItem);
71
72static BOOL DevView_GetOpenFileName(HWND hwndDevView, const struct IODevice *dev, LPTSTR pszFilename, UINT nFilenameLength);
73static BOOL DevView_GetCreateFileName(HWND hwndDevView, const struct IODevice *dev, LPTSTR pszFilename, UINT nFilenameLength);
74static void DevView_SetSelectedSoftware(HWND hwndDevView, int nDriverIndex, const struct IODevice *dev, int nID, LPCTSTR pszFilename);
75static LPCTSTR DevView_GetSelectedSoftware(HWND hwndDevView, int nDriverIndex, const struct IODevice *dev, int nID, LPTSTR pszBuffer, UINT nBufferLength);
76
77#ifdef MAME_DEBUG
78static void MessTestsBegin(void);
79#endif /* MAME_DEBUG */
80
81char g_szSelectedItem[MAX_PATH];
82
83static int s_nGame;
84static BOOL s_bIgnoreSoftwarePickerNotifies;
85
86struct deviceentry
87{
88   int dev_type;
89   const char *icon_name;
90   const char *dlgname;
91};
92
93static const struct PickerCallbacks s_softwareListCallbacks =
94{
95   SetMessSortColumn,               // pfnSetSortColumn
96   GetMessSortColumn,               // pfnGetSortColumn
97   SetMessSortReverse,               // pfnSetSortReverse
98   GetMessSortReverse,               // pfnGetSortReverse
99   NULL,                        // pfnSetViewMode
100   GetViewMode,                  // pfnGetViewMode
101   SetMessColumnWidths,            // pfnSetColumnWidths
102   GetMessColumnWidths,            // pfnGetColumnWidths
103   SetMessColumnOrder,               // pfnSetColumnOrder
104   GetMessColumnOrder,               // pfnGetColumnOrder
105   SetMessColumnShown,               // pfnSetColumnShown
106   GetMessColumnShown,               // pfnGetColumnShown
107   NULL,                        // pfnGetOffsetChildren
108
109   NULL,                        // pfnCompare
110   MamePlayGame,                  // pfnDoubleClick
111   SoftwarePicker_GetItemString,      // pfnGetItemString
112   SoftwarePicker_GetItemImage,      // pfnGetItemImage
113   SoftwarePicker_LeavingItem,         // pfnLeavingItem
114   SoftwarePicker_EnteringItem,      // pfnEnteringItem
115   NULL,                        // pfnBeginListViewDrag
116   NULL,                        // pfnFindItemParent
117   SoftwarePicker_Idle,            // pfnIdle
118   SoftwarePicker_OnHeaderContextMenu,   // pfnOnHeaderContextMenu
119   NULL                        // pfnOnBodyContextMenu
120};
121
122
123
124static const struct TabViewCallbacks s_softwareTabViewCallbacks =
125{
126   NULL,                        // pfnGetShowTabCtrl
127   SetCurrentSoftwareTab,            // pfnSetCurrentTab
128   GetCurrentSoftwareTab,            // pfnGetCurrentTab
129   NULL,                        // pfnSetShowTab
130   NULL,                        // pfnGetShowTab
131
132   SoftwareTabView_GetTabShortName,   // pfnGetTabShortName
133   SoftwareTabView_GetTabLongName,      // pfnGetTabLongName
134
135   SoftwareTabView_OnSelectionChanged,   // pfnOnSelectionChanged
136   SoftwareTabView_OnMoveSize         // pfnOnMoveSize
137};
138
139
140
141// ------------------------------------------------------------------------
142// Image types
143//
144// IO_ZIP is used for ZIP files
145// IO_ALIAS is used for unknown types
146// IO_COUNT is used for bad files
147// ------------------------------------------------------------------------
148
149#define IO_ZIP      (IO_COUNT + 0)
150#define IO_BAD      (IO_COUNT + 1)
151#define IO_UNKNOWN   (IO_COUNT + 2)
152
153// TODO - We need to make icons for Cylinders, Punch Cards, and Punch Tape!
154static const struct deviceentry s_devices[] =
155{
156   { IO_CARTSLOT,   "roms",      "Cartridge images" },
157   { IO_FLOPPY,   "floppy",   "Floppy disk images" },
158   { IO_HARDDISK,   "hard",      "Hard disk images" },
159   { IO_CYLINDER,   NULL,      "Cylinders" },         
160   { IO_CASSETTE,   NULL,      "Cassette images" },
161   { IO_PUNCHCARD,   NULL,      "Punchcard images" },
162   { IO_PUNCHTAPE,   NULL,      "Punchtape images" },
163   { IO_PRINTER,   NULL,      "Printer Output" },
164   { IO_SERIAL,   NULL,      "Serial Output" },
165   { IO_PARALLEL,   NULL,      "Parallel Output" },
166   { IO_SNAPSHOT,   "snapshot",   "Snapshots" },
167   { IO_QUICKLOAD,   "snapshot",   "Quickloads" },
168   { IO_MEMCARD,   NULL,      "Memory cards" },
169   { IO_CDROM,      NULL,      "CD-ROM images" }
170};
171
172
173
174static void AssertValidDevice(int d)
175{
176   assert((sizeof(s_devices) / sizeof(s_devices[0])) == IO_COUNT);
177   assert(((d >= 0) && (d < IO_COUNT)) || (d == IO_UNKNOWN) || (d == IO_BAD) || (d == IO_ZIP));
178}
179
180
181
182static const struct deviceentry *lookupdevice(int d)
183{
184   assert(d >= 0);
185   assert(d < IO_COUNT);
186   AssertValidDevice(d);
187   return &s_devices[d];
188}
189
190
191
192// ------------------------------------------------------------------------
193
194static int requested_device_type(char *tchar)
195{
196   int device = -1;
197   int i;
198
199    logerror("Requested device is %s\n", tchar);
200
201   if (*tchar == '-')
202   {
203      tchar++;
204
205      for (i = 1; i < IO_COUNT; i++)
206      {
207         if (!mame_stricmp(tchar, device_typename(i)) || !mame_stricmp(tchar, device_brieftypename(i)))
208         {
209            device = i;
210            break;
211         }
212      }
213   }
214
215   return device;
216}
217
218
219
220// ------------------------------------------------------------------------
221// UI
222// ------------------------------------------------------------------------
223
224BOOL CreateMessIcons(void)
225{
226    int i;
227   HWND hwndSoftwareList;
228   HIMAGELIST hSmall;
229   HIMAGELIST hLarge;
230
231   // create the icon index, if we havn't already
232    if (!mess_icon_index)
233   {
234      mess_icon_index = pool_malloc(GetMame32MemoryPool(), driver_list_get_count(drivers) * IO_COUNT * sizeof(*mess_icon_index));
235    }
236
237    for (i = 0; i < (driver_list_get_count(drivers) * IO_COUNT); i++)
238        mess_icon_index[i] = 0;
239
240   // Associate the image lists with the list view control.
241   hwndSoftwareList = GetDlgItem(GetMainWindow(), IDC_SWLIST);
242   hSmall = GetSmallImageList();
243   hLarge = GetLargeImageList();
244   (void)ListView_SetImageList(hwndSoftwareList, hSmall, LVSIL_SMALL);
245   (void)ListView_SetImageList(hwndSoftwareList, hLarge, LVSIL_NORMAL);
246   return TRUE;
247}
248
249
250
251static int GetMessIcon(int nGame, int nSoftwareType)
252{
253    int the_index;
254    int nIconPos = 0;
255    HICON hIcon = 0;
256    const game_driver *drv;
257    char buffer[32];
258   const char *iconname;
259
260   assert(nGame >= 0);
261   assert(nGame < driver_list_get_count(drivers));
262
263    if ((nSoftwareType >= 0) && (nSoftwareType < IO_COUNT))
264   {
265      iconname = device_brieftypename(nSoftwareType);
266        the_index = (nGame * IO_COUNT) + nSoftwareType;
267
268        nIconPos = mess_icon_index[the_index];
269        if (nIconPos >= 0)
270      {
271         for (drv = drivers[nGame]; drv; drv = driver_get_clone(drv))
272         {
273            _snprintf(buffer, sizeof(buffer) / sizeof(buffer[0]), "%s/%s", drv->name, iconname);
274            hIcon = LoadIconFromFile(buffer);
275            if (hIcon)
276               break;
277         }
278
279         if (hIcon)
280         {
281            nIconPos = ImageList_AddIcon(GetSmallImageList(), hIcon);
282            ImageList_AddIcon(GetLargeImageList(), hIcon);
283            if (nIconPos != -1)
284               mess_icon_index[the_index] = nIconPos;
285         }
286        }
287    }
288    return nIconPos;
289}
290
291
292
293static void MessHashErrorProc(const char *message)
294{
295   SetStatusBarTextF(0, "Hash file: %s", message);
296}
297
298
299
300static BOOL AddSoftwarePickerDirs(HWND hwndPicker, LPCSTR pszDirectories, LPCSTR pszSubDir)
301{
302   LPCSTR s;
303   LPSTR pszNewString;
304   char cSeparator = ';';
305   int nLength;
306
307   do
308   {
309      s = pszDirectories;
310      while(*s && (*s != cSeparator))
311         s++;
312
313      nLength = s - pszDirectories;
314      if (nLength > 0)
315      {
316         pszNewString = (LPSTR) alloca((nLength + 1 + (pszSubDir ? strlen(pszSubDir) + 1 : 0)));
317         memcpy(pszNewString, pszDirectories, nLength);
318         pszNewString[nLength] = '\0';
319
320         if (pszSubDir)
321         {
322            pszNewString[nLength++] = '\\';
323            strcpy(&pszNewString[nLength], pszSubDir);
324         }
325
326         if (!SoftwarePicker_AddDirectory(hwndPicker, pszNewString))
327            return FALSE;
328      }
329      pszDirectories = s + 1;
330   }
331   while(*s);
332   return TRUE;
333}
334
335
336
337void MyFillSoftwareList(int nGame, BOOL bForce)
338{
339   const game_driver *drv;
340   HWND hwndSoftwarePicker;
341   HWND hwndSoftwareDevView;
342   
343   hwndSoftwarePicker = GetDlgItem(GetMainWindow(), IDC_SWLIST);
344   hwndSoftwareDevView = GetDlgItem(GetMainWindow(), IDC_SWDEVVIEW);
345
346   // Set up the device view
347   DevView_SetDriver(hwndSoftwareDevView, nGame);
348
349   if (!bForce && (s_nGame == nGame))
350      return;
351   s_nGame = nGame;
352
353   // Set up the software picker
354   SoftwarePicker_Clear(hwndSoftwarePicker);
355   drv = drivers[nGame];
356   SoftwarePicker_SetDriver(hwndSoftwarePicker, drv);
357   while(drv)
358   {
359      AddSoftwarePickerDirs(hwndSoftwarePicker, GetSoftwareDirs(), drv->name);
360      drv = mess_next_compatible_driver(drv);
361   }
362   AddSoftwarePickerDirs(hwndSoftwarePicker, GetExtraSoftwarePaths(nGame), NULL);
363}
364
365
366
367void MessUpdateSoftwareList(void)
368{
369   HWND hwndList = GetDlgItem(GetMainWindow(), IDC_LIST);
370   MyFillSoftwareList(Picker_GetSelectedItem(hwndList), TRUE);
371}
372
373
374
375BOOL MessApproveImageList(HWND hParent, int nGame)
376{
377   int i, nPos, devindex;
378   const struct IODevice *devices;
379   const game_driver *pDriver;
380   char szMessage[256];
381   LPCSTR pszSoftware;
382   BOOL bResult = FALSE;
383
384   begin_resource_tracking();
385
386   pDriver = drivers[nGame];
387   devices = devices_allocate(pDriver);
388
389   nPos = 0;
390   for (devindex = 0; devices[devindex].type < IO_COUNT; devindex++)
391   {
392      // confirm any mandatory devices are loaded
393      if (devices[devindex].must_be_loaded)
394      {
395         for (i = 0; i < devices[devindex].count; i++)
396         {
397            pszSoftware = GetSelectedSoftware(nGame, &devices[devindex].devclass, i);
398            if (!pszSoftware || !*pszSoftware)
399            {
400               snprintf(szMessage, sizeof(szMessage) / sizeof(szMessage[0]),
401                  "System '%s' requires that device %s must have an image to load\n",
402                  pDriver->description,
403                  device_typename(devices[devindex].type));
404               goto done;
405            }
406         }
407      }
408
409      nPos += devices[devindex].count;
410   }
411   bResult = TRUE;
412
413done:
414   if (!bResult)
415   {
416      win_message_box_utf8(hParent, szMessage, MAME32NAME, MB_OK);
417   }
418
419   devices_free(devices);
420   return bResult;
421}
422
423
424
425// this is a wrapper call to wrap the idiosycracies of SetSelectedSoftware()
426static void InternalSetSelectedSoftware(int nGame, const device_class *devclass, int device_inst, const char *pszSoftware)
427{
428   if (!pszSoftware)
429      pszSoftware = "";
430
431   // only call SetSelectedSoftware() if this value is different
432   if (strcmp(GetSelectedSoftware(nGame, devclass, device_inst), pszSoftware))
433   {
434      SetSelectedSoftware(nGame, devclass, device_inst, pszSoftware);
435      SetGameUsesDefaults(nGame, FALSE);
436      SaveGameOptions(nGame);
437   }
438}
439
440
441
442// Places the specified image in the specified slot; nID = -1 means don't matter
443static void MessSpecifyImage(int nGame, const device_class *devclass, int nID, LPCSTR pszFilename)
444{
445   const struct IODevice *devices;
446   const struct IODevice *dev;
447   const char *s;
448   int i;
449
450   devices = devices_allocate(devclass->gamedrv);
451
452   for (dev = devices; dev->type < IO_COUNT; dev++)
453   {
454      if (dev->devclass.get_info == devclass->get_info)
455         break;
456   }
457
458   if (LOG_SOFTWARE)
459   {
460      dprintf("MessSpecifyImage(): nID=%d pszFilename='%s'\n", nID, pszFilename);
461   }
462
463   if (nID < 0)
464   {
465      // special case; first try to find existing image
466      for (i = 0; i < dev->count; i++)
467      {
468         s = GetSelectedSoftware(nGame, &dev->devclass, i);
469         if (s && !mame_stricmp(s, pszFilename))
470         {
471            nID = i;
472            break;
473         }
474      }
475   }
476
477   if (nID < 0)
478   {
479      // still not found?  locate an empty slot
480      for (i = 0; i < dev->count; i++)
481      {
482         s = GetSelectedSoftware(nGame, &dev->devclass, i);
483         if (!s || !*s || !mame_stricmp(s, pszFilename))
484         {
485            nID = i;
486            break;
487         }
488      }
489   }
490
491   if (nID >= 0)
492      InternalSetSelectedSoftware(nGame, &dev->devclass, nID, pszFilename);
493   else if (LOG_SOFTWARE)
494      dprintf("MessSpecifyImage(): Failed to place image '%s'\n", pszFilename);
495
496   devices_free(devices);
497}
498
499
500
501static void MessRemoveImage(int nGame, device_class devclass, LPCSTR pszFilename)
502{
503   int i, nPos;
504   const struct IODevice *devices;
505   const struct IODevice *dev;
506
507   if (devclass.gamedrv)
508   {
509      devices = devices_allocate(devclass.gamedrv);
510
511      nPos = 0;
512      for (dev = devices; dev->type < IO_COUNT; dev++)
513      {
514         if (dev->devclass.get_info == devclass.get_info)
515            break;
516         nPos += dev->count;
517      }
518
519      if (dev->type < IO_COUNT)
520      {
521         for (i = 0; i < dev->count; i++)
522         {
523            if (!mame_stricmp(pszFilename, GetSelectedSoftware(nGame, &dev->devclass, i)))
524            {
525               MessSpecifyImage(nGame, &devclass, i, NULL);
526               break;
527            }
528         }
529      }
530
531      devices_free(devices);
532   }
533}
534
535
536
537void MessReadMountedSoftware(int nGame)
538{
539   // First read stuff into device view
540   DevView_Refresh(GetDlgItem(GetMainWindow(), IDC_SWDEVVIEW));
541
542   // Now read stuff into picker
543   MessRefreshPicker(nGame);
544}
545
546
547
548static void MessRefreshPicker(int nGame)
549{
550   HWND hwndSoftware;
551   int i, id;
552   LVFINDINFO lvfi;
553   const game_driver *pDriver;
554   const struct IODevice *pDeviceList;
555   const struct IODevice *pDevice;
556   LPCSTR pszSoftware;
557
558   hwndSoftware = GetDlgItem(GetMainWindow(), IDC_SWLIST);
559   pDriver = drivers[nGame];
560   pDeviceList = devices_allocate(pDriver);
561   if (!pDeviceList)
562      goto done;
563
564   s_bIgnoreSoftwarePickerNotifies = TRUE;
565
566   // Now clear everything out; this may call back into us but it should not
567   // be problematic
568   ListView_SetItemState(hwndSoftware, -1, 0, LVIS_SELECTED);
569
570   for (pDevice = pDeviceList; pDevice->type < IO_COUNT; pDevice++)
571   {
572      for (id = 0; id < pDevice->count; id++)
573      {
574         pszSoftware = GetSelectedSoftware(nGame, &pDevice->devclass, id);
575         if (pszSoftware && *pszSoftware)
576         {
577            i = SoftwarePicker_LookupIndex(hwndSoftware, pszSoftware);
578            if (i < 0)
579            {
580               SoftwarePicker_AddFile(hwndSoftware, pszSoftware);
581               i = SoftwarePicker_LookupIndex(hwndSoftware, pszSoftware);
582            }
583            if (i >= 0)
584            {
585               memset(&lvfi, 0, sizeof(lvfi));
586               lvfi.flags = LVFI_PARAM;
587               lvfi.lParam = i;
588               i = ListView_FindItem(hwndSoftware, -1, &lvfi);
589               ListView_SetItemState(hwndSoftware, i, LVIS_SELECTED, LVIS_SELECTED);
590            }
591         }
592      }
593   }
594
595
596done:
597   devices_free(pDeviceList);
598   s_bIgnoreSoftwarePickerNotifies = FALSE;
599}
600
601
602
603void InitMessPicker(void)
604{
605   struct PickerOptions opts;
606   HWND hwndSoftware;
607
608   s_nGame = -1;
609   hwndSoftware = GetDlgItem(GetMainWindow(), IDC_SWLIST);
610
611   memset(&opts, 0, sizeof(opts));
612   opts.pCallbacks = &s_softwareListCallbacks;
613   opts.nColumnCount = MESS_COLUMN_MAX;
614   opts.ppszColumnNames = mess_column_names;
615   SetupSoftwarePicker(hwndSoftware, &opts);
616
617   SetWindowLong(hwndSoftware, GWL_STYLE, GetWindowLong(hwndSoftware, GWL_STYLE)
618      | LVS_REPORT | LVS_SHOWSELALWAYS | LVS_OWNERDRAWFIXED);
619
620   SetupSoftwareTabView();
621
622   {
623      static const struct DevViewCallbacks s_devViewCallbacks =
624      {
625         DevView_GetOpenFileName,
626         DevView_GetCreateFileName,
627         DevView_SetSelectedSoftware,
628         DevView_GetSelectedSoftware
629      };
630      DevView_SetCallbacks(GetDlgItem(GetMainWindow(), IDC_SWDEVVIEW), &s_devViewCallbacks);
631   }
632}
633
634
635
636// ------------------------------------------------------------------------
637// Open others dialog
638// ------------------------------------------------------------------------
639
640typedef struct
641{
642   const struct IODevice *dev;
643    const char *ext;
644} mess_image_type;
645
646static BOOL CommonFileImageDialog(LPTSTR the_last_directory, common_file_dialog_proc cfd, LPTSTR filename, mess_image_type *imagetypes)
647{
648    BOOL success;
649    OPENFILENAME of;
650    char szFilter[2048];
651    LPSTR s;
652   const char *typname;
653    int i;
654    TCHAR* t_filter;
655    TCHAR* t_buffer;
656
657   s = szFilter;
658    *filename = 0;
659
660    // Common image types
661    strcpy(s, "Common image types");
662    s += strlen(s);
663    *(s++) = '|';
664    for (i = 0; imagetypes[i].ext; i++)
665   {
666        *(s++) = '*';
667        *(s++) = '.';
668        strcpy(s, imagetypes[i].ext);
669        s += strlen(s);
670        *(s++) = ';';
671    }
672    *(s++) = '|';
673
674    // All files
675    strcpy(s, "All files (*.*)");
676    s += strlen(s);
677    *(s++) = '|';
678    strcpy(s, "*.*");
679    s += strlen(s);
680    *(s++) = '|';
681
682    // The others
683    for (i = 0; imagetypes[i].ext; i++)
684   {
685      if (!imagetypes[i].dev)
686         typname = "Compressed images";
687      else
688         typname = lookupdevice(imagetypes[i].dev->type)->dlgname;
689
690        strcpy(s, typname);
691        s += strlen(s);
692        strcpy(s, " (*.");
693        s += strlen(s);
694        strcpy(s, imagetypes[i].ext);
695        s += strlen(s);
696        *(s++) = ')';
697        *(s++) = '|';
698        *(s++) = '*';
699        *(s++) = '.';
700        strcpy(s, imagetypes[i].ext);
701        s += strlen(s);
702        *(s++) = '|';
703    }
704    *(s++) = '|';
705   
706    t_buffer = tstring_from_utf8(szFilter);
707    if( !t_buffer )
708       return FALSE;
709
710   // convert a pipe-char delimited string into a NUL delimited string
711   t_filter = (LPTSTR) alloca((_tcslen(t_buffer) + 2) * sizeof(*t_filter));
712   for (i = 0; t_buffer[i] != '\0'; i++)
713      t_filter[i] = (t_buffer[i] != '|') ? t_buffer[i] : '\0';
714   t_filter[i++] = '\0';
715   t_filter[i++] = '\0';
716   free(t_buffer);
717
718    of.lStructSize = sizeof(of);
719    of.hwndOwner = GetMainWindow();
720    of.hInstance = NULL;
721    of.lpstrFilter = t_filter;
722    of.lpstrCustomFilter = NULL;
723    of.nMaxCustFilter = 0;
724    of.nFilterIndex = 1;
725    of.lpstrFile = filename;
726    of.nMaxFile = MAX_PATH;
727    of.lpstrFileTitle = NULL;
728    of.nMaxFileTitle = 0;
729    of.lpstrInitialDir = last_directory;
730    of.lpstrTitle = NULL;
731    of.Flags = OFN_EXPLORER | OFN_NOCHANGEDIR | OFN_PATHMUSTEXIST | OFN_HIDEREADONLY;
732    of.nFileOffset = 0;
733    of.nFileExtension = 0;
734    of.lpstrDefExt = TEXT("rom");
735    of.lCustData = 0;
736    of.lpfnHook = NULL;
737    of.lpTemplateName = NULL;
738
739    success = cfd(&of);
740    if (success)
741    {
742        //GetDirectory(filename,last_directory,sizeof(last_directory));
743    }
744   
745    return success;
746}
747
748
749
750/* Specify IO_COUNT for type if you want all types */
751static void SetupImageTypes(const struct IODevice *devices, mess_image_type *types, int count, BOOL bZip, int type)
752{
753    int num_extensions = 0;
754   int devindex;
755
756   memset(types, 0, sizeof(*types) * count);
757    count--;
758
759    if (bZip)
760   {
761      types[num_extensions].ext = "zip";
762      types[num_extensions].dev = NULL;
763      num_extensions++;
764    }
765
766   if (devices != NULL)
767   {
768      for (devindex = 0; devices[devindex].type < IO_COUNT; devindex++)
769      {
770         if (devices[devindex].type != IO_PRINTER)
771         {
772            const char *ext = devices[devindex].file_extensions;
773            if (ext)
774            {
775               while(*ext)
776               {
777                  if ((type == IO_COUNT) || (type == devices[devindex].type))
778                  {
779                     if (num_extensions < count)
780                     {
781                        types[num_extensions].dev = &devices[devindex];
782                        types[num_extensions].ext = ext;
783                        num_extensions++;
784                     }
785                  }
786                  ext += strlen(ext) + 1;
787               }
788            }
789         }
790      }
791   }
792}
793
794
795
796static void MessSetupDevice(common_file_dialog_proc cfd, int iDevice)
797{
798   TCHAR filename[MAX_PATH];
799   mess_image_type imagetypes[64];
800   int nGame;
801   HWND hwndList;
802   char* utf8_filename;
803   const struct IODevice *devices;
804
805   begin_resource_tracking();
806
807   hwndList = GetDlgItem(GetMainWindow(), IDC_LIST);
808   nGame = Picker_GetSelectedItem(hwndList);
809   devices = devices_allocate(drivers[nGame]);
810   SetupImageTypes(devices, imagetypes, sizeof(imagetypes) / sizeof(imagetypes[0]), TRUE, iDevice);
811
812   if (CommonFileImageDialog(last_directory, cfd, filename, imagetypes))
813   {
814      utf8_filename = utf8_from_tstring(filename);
815      if( !utf8_filename )
816         return;
817      // TODO - this should go against InternalSetSelectedSoftware()
818      SoftwarePicker_AddFile(GetDlgItem(GetMainWindow(), IDC_SWLIST), utf8_filename);
819      free(utf8_filename);
820   }
821
822   if (devices != NULL)
823      devices_free(devices);
824}
825
826
827
828static void MessOpenOtherSoftware(int iDevice)
829{
830   MessSetupDevice(GetOpenFileName, iDevice);
831}
832
833
834
835static void MessCreateDevice(int iDevice)
836{
837   MessSetupDevice(GetSaveFileName, iDevice);
838}
839
840
841
842static BOOL DevView_GetOpenFileName(HWND hwndDevView, const struct IODevice *dev, LPTSTR pszFilename, UINT nFilenameLength)
843{
844   BOOL bResult;
845   mess_image_type imagetypes[64];
846   HWND hwndList;
847   int gamenum;
848   const struct IODevice *devices;
849
850   hwndList = GetDlgItem(GetMainWindow(), IDC_LIST);
851   gamenum = Picker_GetSelectedItem(hwndList);
852   devices = devices_allocate(drivers[gamenum]);
853   SetupImageTypes(devices, imagetypes, sizeof(imagetypes) / sizeof(imagetypes[0]), TRUE, dev->type);
854   bResult = CommonFileImageDialog(last_directory, GetOpenFileName, pszFilename, imagetypes);
855
856   if (devices != NULL)
857      devices_free(devices);
858   return bResult;
859}
860
861
862
863static BOOL DevView_GetCreateFileName(HWND hwndDevView, const struct IODevice *dev, LPTSTR pszFilename, UINT nFilenameLength)
864{
865   BOOL bResult;
866   mess_image_type imagetypes[64];
867   HWND hwndList;
868   int gamenum;
869   const struct IODevice *devices;
870
871   hwndList = GetDlgItem(GetMainWindow(), IDC_LIST);
872   gamenum = Picker_GetSelectedItem(hwndList);
873   devices = devices_allocate(drivers[gamenum]);
874   SetupImageTypes(devices, imagetypes, sizeof(imagetypes) / sizeof(imagetypes[0]), TRUE, dev->type);
875   bResult = CommonFileImageDialog(last_directory, GetSaveFileName, pszFilename, imagetypes);
876
877   if (devices != NULL)
878      devices_free(devices);
879   return bResult;
880}
881
882
883
884static void DevView_SetSelectedSoftware(HWND hwndDevView, int nGame,
885   const struct IODevice *dev, int nID, LPCTSTR pszFilename)
886{
887   char* utf8_filename = utf8_from_tstring(pszFilename);
888   if( !utf8_filename )
889      return;
890   MessSpecifyImage(nGame, &dev->devclass, nID, utf8_filename);
891   MessRefreshPicker(nGame);
892   free(utf8_filename);
893}
894
895
896
897static LPCTSTR DevView_GetSelectedSoftware(HWND hwndDevView, int nDriverIndex,
898   const struct IODevice *dev, int nID, LPTSTR pszBuffer, UINT nBufferLength)
899{
900   LPCTSTR t_buffer = NULL;
901   TCHAR* t_s;
902   LPCSTR s = GetSelectedSoftware(nDriverIndex, &dev->devclass, nID);
903   
904   t_s = tstring_from_utf8(s);
905   if( !t_s )
906      return t_buffer;
907   
908   _sntprintf(pszBuffer, nBufferLength, TEXT("%s"), t_s);
909   free(t_s);   
910   t_buffer = pszBuffer;
911   
912   return t_buffer;
913}
914
915
916
917// ------------------------------------------------------------------------
918// Software List Class
919// ------------------------------------------------------------------------
920
921static int SoftwarePicker_GetItemImage(HWND hwndPicker, int nItem)
922{
923    int nType;
924    int nIcon;
925   int nGame;
926   const char *icon_name;
927   HWND hwndGamePicker;
928   HWND hwndSoftwarePicker;
929
930   hwndGamePicker = GetDlgItem(GetMainWindow(), IDC_LIST);
931   hwndSoftwarePicker = GetDlgItem(GetMainWindow(), IDC_SWLIST);
932   nGame = Picker_GetSelectedItem(hwndGamePicker);
933    nType = SoftwarePicker_GetImageType(hwndSoftwarePicker, nItem);
934    nIcon = GetMessIcon(nGame, nType);
935    if (!nIcon)
936   {
937      if (nType < 0)
938         nType = IO_BAD;
939      switch(nType)
940      {
941         case IO_UNKNOWN:
942            // Unknowns
943            nIcon = FindIconIndex(IDI_WIN_UNKNOWN);
944            break;
945
946         case IO_BAD:
947         case IO_ZIP:
948            // Bad files
949            nIcon = FindIconIndex(IDI_WIN_REDX);
950            break;
951
952         default:
953            icon_name = lookupdevice(nType)->icon_name;
954            if (!icon_name)
955               icon_name = device_typename(nType);
956            nIcon = FindIconIndexByName(icon_name);
957            if (nIcon < 0)
958               nIcon = FindIconIndexByName("unknown");
959            break;
960      }
961    }
962    return nIcon;
963}
964
965
966
967static void SoftwarePicker_LeavingItem(HWND hwndSoftwarePicker, int nItem)
968{
969   int nGame;
970   device_class devclass;
971   LPCSTR pszFullName;
972   HWND hwndList;
973
974   if (!s_bIgnoreSoftwarePickerNotifies)
975   {
976      hwndList = GetDlgItem(GetMainWindow(), IDC_LIST);
977      nGame = Picker_GetSelectedItem(hwndList);
978      devclass = SoftwarePicker_LookupDevice(hwndSoftwarePicker, nItem);
979      pszFullName = SoftwarePicker_LookupFilename(hwndSoftwarePicker, nItem);
980
981      MessRemoveImage(nGame, devclass, pszFullName);
982   }
983}
984
985
986
987static void SoftwarePicker_EnteringItem(HWND hwndSoftwarePicker, int nItem)
988{
989   LPCSTR pszFullName;
990   LPCSTR pszName;
991   LPSTR s;
992   int nGame;
993   device_class devclass;
994   HWND hwndList;
995
996   hwndList = GetDlgItem(GetMainWindow(), IDC_LIST);
997
998   if (!s_bIgnoreSoftwarePickerNotifies)
999   {
1000      nGame = Picker_GetSelectedItem(hwndList);
1001
1002      // Get the fullname and partialname for this file
1003      pszFullName = SoftwarePicker_LookupFilename(hwndSoftwarePicker, nItem);
1004      s = strchr(pszFullName, '\\');
1005      pszName = s ? s + 1 : pszFullName;
1006
1007      // Do the dirty work
1008      devclass = SoftwarePicker_LookupDevice(hwndSoftwarePicker, nItem);
1009      if (!devclass.gamedrv)
1010         return;
1011      MessSpecifyImage(nGame, &devclass, -1, pszFullName);
1012
1013      // Set up s_szSelecteItem, for the benefit of UpdateScreenShot()
1014      strncpyz(g_szSelectedItem, pszName, sizeof(g_szSelectedItem) / sizeof(g_szSelectedItem[0]));
1015      s = strrchr(g_szSelectedItem, '.');
1016      if (s)
1017         *s = '\0';
1018
1019      UpdateScreenShot();
1020   }
1021}
1022
1023
1024
1025// ------------------------------------------------------------------------
1026// Header context menu stuff
1027// ------------------------------------------------------------------------
1028
1029static HWND MyColumnDialogProc_hwndPicker;
1030static int *MyColumnDialogProc_order;
1031static int *MyColumnDialogProc_shown;
1032
1033static void MyGetRealColumnOrder(int *order)
1034{
1035   int i, nColumnCount;
1036   nColumnCount = Picker_GetColumnCount(MyColumnDialogProc_hwndPicker);
1037   for (i = 0; i < nColumnCount; i++)
1038      order[i] = Picker_GetRealColumnFromViewColumn(MyColumnDialogProc_hwndPicker, i);
1039}
1040
1041
1042
1043static void MyGetColumnInfo(int *order, int *shown)
1044{
1045   const struct PickerCallbacks *pCallbacks;
1046   pCallbacks = Picker_GetCallbacks(MyColumnDialogProc_hwndPicker);
1047   pCallbacks->pfnGetColumnOrder(order);
1048   pCallbacks->pfnGetColumnShown(shown);
1049}
1050
1051
1052
1053static void MySetColumnInfo(int *order, int *shown)
1054{
1055   const struct PickerCallbacks *pCallbacks;
1056   pCallbacks = Picker_GetCallbacks(MyColumnDialogProc_hwndPicker);
1057   pCallbacks->pfnSetColumnOrder(order);
1058   pCallbacks->pfnSetColumnShown(shown);
1059}
1060
1061
1062
1063static INT_PTR CALLBACK MyColumnDialogProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam)
1064{
1065   INT_PTR result = 0;
1066   int nColumnCount = Picker_GetColumnCount(MyColumnDialogProc_hwndPicker);
1067   LPCTSTR *ppszColumnNames = Picker_GetColumnNames(MyColumnDialogProc_hwndPicker);
1068   
1069   result = InternalColumnDialogProc(hDlg, Msg, wParam, lParam, nColumnCount,
1070      MyColumnDialogProc_shown, MyColumnDialogProc_order, ppszColumnNames,
1071      MyGetRealColumnOrder, MyGetColumnInfo, MySetColumnInfo);
1072     
1073   return result;
1074}
1075
1076
1077
1078static BOOL RunColumnDialog(HWND hwndPicker)
1079{
1080   BOOL bResult;
1081   int nColumnCount;
1082
1083   MyColumnDialogProc_hwndPicker = hwndPicker;
1084   nColumnCount = Picker_GetColumnCount(MyColumnDialogProc_hwndPicker);
1085
1086   MyColumnDialogProc_order = alloca(nColumnCount * sizeof(int));
1087   MyColumnDialogProc_shown = alloca(nColumnCount * sizeof(int));
1088   bResult = DialogBox(GetModuleHandle(NULL), MAKEINTRESOURCE(IDD_COLUMNS), GetMainWindow(), MyColumnDialogProc);
1089   return bResult;
1090}
1091
1092
1093
1094static void SoftwarePicker_OnHeaderContextMenu(POINT pt, int nColumn)
1095{
1096   HMENU hMenu;
1097   HMENU hMenuLoad;
1098   HWND hwndPicker;
1099   int nMenuItem;
1100
1101   hMenuLoad = LoadMenu(NULL, MAKEINTRESOURCE(IDR_CONTEXT_HEADER));
1102   hMenu = GetSubMenu(hMenuLoad, 0);
1103
1104   nMenuItem = (int) TrackPopupMenu(hMenu,
1105      TPM_LEFTALIGN | TPM_RIGHTBUTTON | TPM_RETURNCMD,
1106      pt.x,
1107      pt.y,
1108      0,
1109      GetMainWindow(),
1110      NULL);
1111
1112   DestroyMenu(hMenuLoad);
1113
1114   hwndPicker = GetDlgItem(GetMainWindow(), IDC_SWLIST);
1115
1116   switch(nMenuItem) {
1117   case ID_SORT_ASCENDING:
1118      SetMessSortReverse(FALSE);
1119      SetMessSortColumn(Picker_GetRealColumnFromViewColumn(hwndPicker, nColumn));
1120      Picker_Sort(hwndPicker);
1121      break;
1122
1123   case ID_SORT_DESCENDING:
1124      SetMessSortReverse(TRUE);
1125      SetMessSortColumn(Picker_GetRealColumnFromViewColumn(hwndPicker, nColumn));
1126      Picker_Sort(hwndPicker);
1127      break;
1128
1129   case ID_CUSTOMIZE_FIELDS:
1130      if (RunColumnDialog(hwndPicker))
1131         Picker_ResetColumnDisplay(hwndPicker);
1132      break;
1133   }
1134}
1135
1136
1137
1138// ------------------------------------------------------------------------
1139// MessCommand
1140// ------------------------------------------------------------------------
1141
1142BOOL MessCommand(HWND hwnd,int id, HWND hwndCtl, UINT codeNotify)
1143{
1144   switch (id) {
1145   case ID_MESS_OPEN_SOFTWARE:
1146      MessOpenOtherSoftware(IO_COUNT);
1147      break;
1148
1149   case ID_MESS_CREATE_SOFTWARE:
1150      MessCreateDevice(IO_COUNT);
1151      break;
1152
1153#ifdef MAME_DEBUG
1154   case ID_MESS_RUN_TESTS:
1155      MessTestsBegin();
1156      break;
1157#endif /* MAME_DEBUG */
1158   }
1159   return FALSE;
1160}
1161
1162
1163
1164// ------------------------------------------------------------------------
1165// Software Tab View
1166// ------------------------------------------------------------------------
1167
1168static LPCSTR s_tabs[] =
1169{
1170   "picker\0Picker",
1171   "devview\0Device View"
1172};
1173
1174
1175
1176static LPCSTR SoftwareTabView_GetTabShortName(int tab)
1177{
1178   return s_tabs[tab];
1179}
1180
1181
1182
1183static LPCSTR SoftwareTabView_GetTabLongName(int tab)
1184{
1185   return s_tabs[tab] + strlen(s_tabs[tab]) + 1;
1186}
1187
1188
1189
1190static void SoftwareTabView_OnSelectionChanged(void)
1191{
1192   int nTab;
1193   HWND hwndSoftwarePicker;
1194   HWND hwndSoftwareDevView;
1195
1196   hwndSoftwarePicker = GetDlgItem(GetMainWindow(), IDC_SWLIST);
1197   hwndSoftwareDevView = GetDlgItem(GetMainWindow(), IDC_SWDEVVIEW);
1198
1199   nTab = TabView_GetCurrentTab(GetDlgItem(GetMainWindow(), IDC_SWTAB));
1200
1201   switch(nTab)
1202   {
1203      case 0:
1204         ShowWindow(hwndSoftwarePicker, SW_SHOW);
1205         ShowWindow(hwndSoftwareDevView, SW_HIDE);
1206         break;
1207
1208      case 1:
1209         ShowWindow(hwndSoftwarePicker, SW_HIDE);
1210         ShowWindow(hwndSoftwareDevView, SW_SHOW);
1211         break;
1212   }
1213}
1214
1215
1216
1217static void SoftwareTabView_OnMoveSize(void)
1218{
1219   HWND hwndSoftwareTabView;
1220   HWND hwndSoftwarePicker;
1221   HWND hwndSoftwareDevView;
1222   RECT rMain, rSoftwareTabView, rClient, rTab;
1223
1224   hwndSoftwareTabView = GetDlgItem(GetMainWindow(), IDC_SWTAB);
1225   hwndSoftwarePicker = GetDlgItem(GetMainWindow(), IDC_SWLIST);
1226   hwndSoftwareDevView = GetDlgItem(GetMainWindow(), IDC_SWDEVVIEW);
1227
1228   GetWindowRect(hwndSoftwareTabView, &rSoftwareTabView);
1229   GetClientRect(GetMainWindow(), &rMain);
1230   ClientToScreen(GetMainWindow(), &((POINT *) &rMain)[0]);
1231   ClientToScreen(GetMainWindow(), &((POINT *) &rMain)[1]);
1232
1233   // Calculate rClient from rSoftwareTabView in terms of rMain coordinates
1234   rClient.left = rSoftwareTabView.left - rMain.left;
1235   rClient.top = rSoftwareTabView.top - rMain.top;
1236   rClient.right = rSoftwareTabView.right - rMain.left;
1237   rClient.bottom = rSoftwareTabView.bottom - rMain.top;
1238
1239   // If the tabs are visible, then make sure that the tab view's tabs are
1240   // not being covered up
1241   if (GetWindowLong(hwndSoftwareTabView, GWL_STYLE) & WS_VISIBLE)
1242   {
1243      TabCtrl_GetItemRect(hwndSoftwareTabView, 0, &rTab);
1244      rClient.top += rTab.bottom - rTab.top + 4;
1245   }
1246
1247   /* Now actually move the controls */
1248   MoveWindow(hwndSoftwarePicker, rClient.left, rClient.top,
1249      rClient.right - rClient.left, rClient.bottom - rClient.top,
1250      TRUE);
1251   MoveWindow(hwndSoftwareDevView, rClient.left, rClient.top,
1252      rClient.right - rClient.left, rClient.bottom - rClient.top,
1253      TRUE);
1254}
1255
1256
1257
1258static void SetupSoftwareTabView(void)
1259{
1260   struct TabViewOptions opts;
1261
1262   memset(&opts, 0, sizeof(opts));
1263   opts.pCallbacks = &s_softwareTabViewCallbacks;
1264   opts.nTabCount = sizeof(s_tabs) / sizeof(s_tabs[0]);
1265
1266   SetupTabView(GetDlgItem(GetMainWindow(), IDC_SWTAB), &opts);
1267}
1268
1269
1270
1271void MessCopyDeviceOption(core_options *opts, const game_driver *gamedrv, const device_class *devclass, int device_index, int global_index)
1272{
1273   const char *dev_name;
1274   const char *opt_value;
1275
1276   dev_name = device_instancename(devclass, device_index);
1277   opt_value = options_get_string(opts, dev_name);
1278   options_set_string(mame_options(), dev_name, opt_value, OPTION_PRIORITY_CMDLINE);
1279}
1280
1281
1282
1283// ------------------------------------------------------------------------
1284// Mess32 Diagnostics
1285// ------------------------------------------------------------------------
1286
1287#ifdef MAME_DEBUG
1288
1289static int s_nOriginalPick;
1290static UINT_PTR s_nTestingTimer;
1291static BOOL s_bInTimerProc;
1292
1293static void MessTestsColumns(void)
1294{
1295   int i, j;
1296   int oldshown[MESS_COLUMN_MAX];
1297   int shown[MESS_COLUMN_MAX];
1298
1299   GetMessColumnShown(oldshown);
1300
1301   shown[0] = 1;
1302   for (i = 0; i < (1<<(MESS_COLUMN_MAX-1)); i++)
1303   {
1304      for (j = 1; j < MESS_COLUMN_MAX; j++)
1305         shown[j] = (i & (1<<(j-1))) ? 1 : 0;
1306
1307      SetMessColumnShown(shown);
1308      Picker_ResetColumnDisplay(GetDlgItem(GetMainWindow(), IDC_SWLIST));
1309   }
1310
1311   SetMessColumnShown(oldshown);
1312   Picker_ResetColumnDisplay(GetDlgItem(GetMainWindow(), IDC_SWLIST));
1313}
1314
1315
1316
1317
1318static void CALLBACK MessTestsTimerProc(HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime)
1319{
1320   int nNewGame;
1321   HWND hwndList = GetDlgItem(GetMainWindow(), IDC_LIST);
1322
1323   // if either of the pickers have further idle work to do, or we are
1324   // already in this timerproc, do not do anything
1325   if (s_bInTimerProc || Picker_IsIdling(hwndList)
1326      || Picker_IsIdling(GetDlgItem(GetMainWindow(), IDC_SWLIST)))
1327      return;
1328   s_bInTimerProc = TRUE;
1329
1330   nNewGame = GetSelectedPick() + 1;
1331
1332   if (nNewGame >= driver_list_get_count(drivers))
1333   {
1334      /* We are done */
1335      Picker_SetSelectedPick(hwndList, s_nOriginalPick);
1336
1337      KillTimer(NULL, s_nTestingTimer);
1338      s_nTestingTimer = 0;
1339
1340      MessageBox(GetMainWindow(), TEXT("Tests successfully completed!"), TEXT(MAME32NAME), MB_OK);
1341   }
1342   else
1343   {
1344//      MessTestsFlex(GetDlgItem(GetMainWindow(), IDC_SWLIST), drivers[Picker_GetSelectedItem(hwndList)]);
1345      Picker_SetSelectedPick(hwndList, nNewGame);
1346   }
1347   s_bInTimerProc = FALSE;
1348}
1349
1350
1351
1352static void MessTestsBegin(void)
1353{
1354   int nOriginalPick;
1355   HWND hwndList = GetDlgItem(GetMainWindow(), IDC_LIST);
1356
1357   nOriginalPick = GetSelectedPick();
1358
1359   // If we are not currently running tests, set up the timer and keep track
1360   // of the original selected pick item
1361   if (!s_nTestingTimer)
1362   {
1363      s_nTestingTimer = SetTimer(NULL, 0, 50, MessTestsTimerProc);
1364      if (!s_nTestingTimer)
1365         return;
1366      s_nOriginalPick = nOriginalPick;
1367   }
1368
1369   MessTestsColumns();
1370
1371   if (nOriginalPick == 0)
1372      Picker_SetSelectedPick(hwndList, 1);
1373   Picker_SetSelectedPick(hwndList, 0);
1374}
1375
1376
1377
1378#endif // MAME_DEBUG
src/mess/osd/windows/ui/layoutms.c
r995r996
1/***************************************************************************
2
3  layoutms.c
4
5  MESS specific TreeView definitions (and maybe more in the future)
6
7***************************************************************************/
8
9#define WIN32_LEAN_AND_MEAN
10#include <windows.h>
11#include <windowsx.h>
12#include <shellapi.h>
13#include <commctrl.h>
14#include <stdio.h>  /* for sprintf */
15#include <stdlib.h> /* For malloc and free */
16#include <string.h>
17
18#include "ui/bitmask.h"
19#include "ui/TreeView.h"
20#include "ui/M32Util.h"
21#include "ui/resource.h"
22#include "ui/directories.h"
23#include "ui/m32opts.h"
24#include "ui/splitters.h"
25#include "ui/help.h"
26#include "ui/audit32.h"
27#include "ui/screenshot.h"
28#include "ui/win32ui.h"
29#include "ui/properties.h"
30
31#include "ui/ms32util.h"
32#include "ui/resourcems.h"
33#include "ui/propertiesms.h"
34
35static BOOL FilterAvailable(int driver_index);
36
37FOLDERDATA g_folderData[] =
38{
39   {"All Systems",     "allgames",          FOLDER_ALLGAMES,     IDI_FOLDER,            0,             0,            NULL,                       NULL,              TRUE },
40   {"Available",       "available",         FOLDER_AVAILABLE,    IDI_FOLDER_AVAILABLE,     F_AVAILABLE,   0,            NULL,                       FilterAvailable,              TRUE },
41#ifdef SHOW_UNAVAILABLE_FOLDER
42   {"Unavailable",     "unavailable",       FOLDER_UNAVAILABLE,  IDI_FOLDER_UNAVAILABLE,   0,             F_AVAILABLE,  NULL,                       FilterAvailable,              FALSE },
43#endif
44   {"Console",         "console",           FOLDER_CONSOLE,      IDI_FOLDER,            F_CONSOLE,     F_COMPUTER,   NULL,                       DriverIsComputer,  FALSE },
45   {"Computer",        "computer",          FOLDER_COMPUTER,     IDI_FOLDER,            F_COMPUTER,    F_CONSOLE,    NULL,                       DriverIsComputer,  TRUE },
46   {"Modified/Hacked", "modified",          FOLDER_MODIFIED,     IDI_FOLDER,            0,             0,            NULL,                       DriverIsModified,  TRUE },
47   {"Manufacturer",    "manufacturer",      FOLDER_MANUFACTURER, IDI_FOLDER_MANUFACTURER,  0,             0,            CreateManufacturerFolders },
48   {"Year",            "year",              FOLDER_YEAR,         IDI_FOLDER_YEAR,          0,             0,            CreateYearFolders },
49   {"Source",          "source",            FOLDER_SOURCE,       IDI_FOLDER_SOURCE,        0,             0,            CreateSourceFolders },
50   {"CPU",             "cpu",               FOLDER_CPU,          IDI_FOLDER,               0,             0,            CreateCPUFolders },
51   {"Sound",           "sound",             FOLDER_SND,          IDI_FOLDER,               0,             0,            CreateSoundFolders },
52   {"Orientation",     "orientation",       FOLDER_ORIENTATION,  IDI_FOLDER,               0,             0,            CreateOrientationFolders },
53   {"Imperfect",       "imperfect",         FOLDER_DEFICIENCY,   IDI_FOLDER,               0,             0,            CreateDeficiencyFolders },
54     {"Dumping Status",  "dumping",           FOLDER_DUMPING,      IDI_FOLDER,               0,             0,            CreateDumpingFolders },
55   {"Working",         "working",           FOLDER_WORKING,      IDI_WORKING,              F_WORKING,     F_NONWORKING, NULL,                       DriverIsBroken,    FALSE },
56   {"Not Working",     "nonworking",        FOLDER_NONWORKING,   IDI_NONWORKING,           F_NONWORKING,  F_WORKING,    NULL,                       DriverIsBroken,    TRUE },
57   {"Originals",       "originals",         FOLDER_ORIGINAL,     IDI_FOLDER,               F_ORIGINALS,   F_CLONES,     NULL,                       DriverIsClone,     FALSE },
58   {"Clones",          "clones",            FOLDER_CLONES,       IDI_FOLDER,               F_CLONES,      F_ORIGINALS,  NULL,                       DriverIsClone,     TRUE },
59   {"Raster",          "raster",            FOLDER_RASTER,       IDI_FOLDER,               F_RASTER,      F_VECTOR,     NULL,                       DriverIsVector,    FALSE },
60   {"Vector",          "vector",            FOLDER_VECTOR,       IDI_FOLDER,               F_VECTOR,      F_RASTER,     NULL,                       DriverIsVector,    TRUE },
61   {"Mouse",           "mouse",             FOLDER_MOUSE,        IDI_FOLDER,               0,             0,            NULL,                       DriverUsesMouse,   TRUE },
62   {"Trackball",       "trackball",         FOLDER_TRACKBALL,    IDI_FOLDER,               0,             0,            NULL,                       DriverUsesTrackball,   TRUE },
63   {"Stereo",          "stereo",            FOLDER_STEREO,       IDI_SOUND,                0,             0,            NULL,                       DriverIsStereo,    TRUE },
64   { NULL }
65};
66
67/* list of filter/control Id pairs */
68FILTER_ITEM g_filterList[] =
69{
70   { F_COMPUTER,     IDC_FILTER_COMPUTER,    DriverIsComputer, TRUE },
71   { F_CONSOLE,      IDC_FILTER_CONSOLE,     DriverIsComputer, FALSE },
72   { F_MODIFIED,     IDC_FILTER_MODIFIED,    DriverIsModified, TRUE },
73   { F_CLONES,       IDC_FILTER_CLONES,      DriverIsClone, TRUE },
74   { F_NONWORKING,   IDC_FILTER_NONWORKING,  DriverIsBroken, TRUE },
75   { F_UNAVAILABLE,  IDC_FILTER_UNAVAILABLE, FilterAvailable, FALSE },
76   { F_RASTER,       IDC_FILTER_RASTER,      DriverIsVector, FALSE },
77   { F_VECTOR,       IDC_FILTER_VECTOR,      DriverIsVector, TRUE },
78   { F_ORIGINALS,    IDC_FILTER_ORIGINALS,   DriverIsClone, FALSE },
79   { F_WORKING,      IDC_FILTER_WORKING,     DriverIsBroken, FALSE },
80   { F_AVAILABLE,    IDC_FILTER_AVAILABLE,   FilterAvailable, TRUE },
81   { 0 }
82};
83
84DIRECTORYINFO g_directoryInfo[] =
85{
86   { "ROMs",                  GetRomDirs,      SetRomDirs,      TRUE,  DIRDLG_ROMS },
87   { "Software",              GetSoftwareDirs, SetSoftwareDirs, TRUE,  DIRDLG_SOFTWARE },
88   { "Ini Files",             GetIniDir,       SetIniDir,       FALSE, DIRDLG_INI },
89   { "Hash",                  GetHashDirs,     SetHashDirs,     FALSE, 0 },
90   { "Config",                GetCfgDir,       SetCfgDir,       FALSE, DIRDLG_CFG },
91   { "Snapshots",             GetImgDir,       SetImgDir,       FALSE, DIRDLG_IMG },
92   { "Input files (*.inp)",   GetInpDir,       SetInpDir,       FALSE, DIRDLG_INP },
93   { "State",                 GetStateDir,     SetStateDir,     FALSE, 0 },
94   { "Artwork",               GetArtDir,       SetArtDir,       FALSE, 0 },
95   { "Memory Card",           GetMemcardDir,   SetMemcardDir,   FALSE, 0 },
96   { "Flyers",                GetFlyerDir,     SetFlyerDir,     FALSE, 0 },
97   { "Cabinets",              GetCabinetDir,   SetCabinetDir,   FALSE, 0 },
98   { "Marquees",              GetMarqueeDir,   SetMarqueeDir,   FALSE, 0 },
99   { "Titles",                GetTitlesDir,    SetTitlesDir,    FALSE, 0 },
100   { "Control Panels",        GetControlPanelDir,SetControlPanelDir, FALSE, 0 },
101   { "NVRAM",                 GetNvramDir,     SetNvramDir,     FALSE, 0 },
102   { "Controller Files",      GetCtrlrDir,     SetCtrlrDir,     FALSE, DIRDLG_CTRLR },
103   { "Hard Drive Difference", GetDiffDir,      SetDiffDir,      FALSE, 0 },
104   { "Icons",                 GetIconsDir,     SetIconsDir,     FALSE, 0 },
105   { "Background Images",     GetBgDir,        SetBgDir,        FALSE, 0 },
106   { "Comment Files",      GetCommentDir,     SetCommentDir,     FALSE, DIRDLG_COMMENT },
107   { NULL }
108};
109
110const SPLITTERINFO g_splitterInfo[] =
111{
112   { 0.2,   IDC_SPLITTER,   IDC_TREE,   IDC_LIST,      AdjustSplitter1Rect },
113   { 0.4,   IDC_SPLITTER2,   IDC_LIST,   IDC_SWLIST,      AdjustSplitter1Rect },
114//   { 0.6,   IDC_SPLITTER3,   IDC_SWLIST,   IDC_SSFRAME,   AdjustSplitter2Rect },
115   { 0.6,   IDC_SPLITTER3,   IDC_SWTAB,   IDC_SSFRAME,   AdjustSplitter2Rect },
116   { -1 }
117};
118
119const MAMEHELPINFO g_helpInfo[] =
120{
121   { ID_HELP_CONTENTS,      TRUE,   "mess.chm::/html/mess_overview.htm" },
122   { ID_HELP_RELEASE,      TRUE,   "mess.chm" },
123   { ID_HELP_WHATS_NEW,   TRUE,   "mess.chm::/messnew.txt" },
124   { -1 }
125};
126
127const PROPERTYSHEETINFO g_propSheets[] =
128{
129   { FALSE,   NULL,               IDD_PROP_GAME,         GamePropertiesDialogProc },
130   { FALSE,   NULL,               IDD_PROP_AUDIT,         GameAuditDialogProc },
131   { TRUE,      NULL,               IDD_PROP_DISPLAY,      GameOptionsProc },
132   { TRUE,      NULL,               IDD_PROP_ADVANCED,      GameOptionsProc },
133   { TRUE,      NULL,               IDD_PROP_SCREEN,      GameOptionsProc },
134   { TRUE,      NULL,               IDD_PROP_SOUND,         GameOptionsProc },
135   { TRUE,      NULL,               IDD_PROP_INPUT,         GameOptionsProc },
136   { TRUE,      NULL,               IDD_PROP_CONTROLLER,   GameOptionsProc },
137   { TRUE,      NULL,               IDD_PROP_MISC,         GameOptionsProc },
138   { FALSE,   NULL,               IDD_PROP_SOFTWARE,      GameMessOptionsProc },
139   { FALSE,   PropSheetFilter_Config,   IDD_PROP_CONFIGURATION,   GameMessOptionsProc },
140   { TRUE,      PropSheetFilter_Vector,   IDD_PROP_VECTOR,      GameOptionsProc },
141   { FALSE }
142};
143
144const ICONDATA g_iconData[] =
145{
146   { IDI_WIN_NOROMS,         "noroms" },
147   { IDI_WIN_ROMS,            "roms" },
148   { IDI_WIN_UNKNOWN,         "unknown" },
149   { IDI_WIN_CLONE,         "clone" },
150   { IDI_WIN_REDX,            "warning" },
151   { IDI_WIN_NOROMSNEEDED,      "noromsneeded" },
152   { IDI_WIN_MISSINGOPTROM,   "missingoptrom" },
153   { IDI_WIN_FLOP,            "floppy" },
154   { IDI_WIN_CASS,            "cassette" },
155   { IDI_WIN_SERL,            "serial" },
156   { IDI_WIN_SNAP,            "snapshot" },
157   { IDI_WIN_PRIN,            "printer" },
158   { IDI_WIN_HARD,            "hard" },
159   { 0 }
160};
161
162const TCHAR g_szPlayGameString[] = TEXT("&Run %s");
163const char g_szGameCountString[] = "%d systems";
164const char g_szHistoryFileName[] = "sysinfo.dat";
165const char g_szMameInfoFileName[] = "messinfo.dat";
166
167static BOOL FilterAvailable(int driver_index)
168{
169   return !DriverUsesRoms(driver_index) || IsAuditResultYes(GetRomAuditResults(driver_index));
170}
src/mess/osd/windows/ui/devview.h
r995r996
1#ifndef DEVVIEW_H
2#define DEVVIEW_H
3
4struct DevViewCallbacks
5{
6   BOOL (*pfnGetOpenFileName)(HWND hwndDevView, const struct IODevice *dev, LPTSTR pszFilename, UINT nFilenameLength);
7   BOOL (*pfnGetCreateFileName)(HWND hwndDevView, const struct IODevice *dev, LPTSTR pszFilename, UINT nFilenameLength);
8   void (*pfnSetSelectedSoftware)(HWND hwndDevView, int nGame, const struct IODevice *dev, int nID, LPCTSTR pszFilename);
9   LPCTSTR (*pfnGetSelectedSoftware)(HWND hwndDevView, int nGame, const struct IODevice *dev, int nID, LPTSTR pszBuffer, UINT nBufferLength);
10};
11
12void DevView_SetCallbacks(HWND hwndDevView, const struct DevViewCallbacks *pCallbacks);
13BOOL DevView_SetDriver(HWND hwndDevView, int nGame);
14void DevView_RegisterClass(void);
15void DevView_Refresh(HWND hwndDevView);
16
17#endif // DEVVIEW_H
src/mess/osd/windows/ui/mess32ui.h
r995r996
1#ifndef __MESS32UI_H__
2#define __MESS32UI_H__
3
4#include "driver.h"
5#include "resourcems.h"
6#include "devview.h"
7#include "uitext.h"
8#include "options.h"
9
10extern char g_szSelectedItem[MAX_PATH];
11
12void InitMessPicker(void);
13void MessUpdateSoftwareList(void);
14void MyFillSoftwareList(int nGame, BOOL bForce);
15BOOL MessCommand(HWND hwnd,int id, HWND hwndCtl, UINT codeNotify);
16void MessReadMountedSoftware(int nGame);
17BOOL CreateMessIcons(void);
18BOOL MessApproveImageList(HWND hParent, int nDriver);
19
20void MessCopyDeviceOption(core_options *opts, const game_driver *gamedrv, const device_class *devclass, int device_index, int global_index);
21
22#endif // __MESS32UI_H__
src/mess/osd/windows/ui/ms32util.c
r995r996
1#include "driver.h"
2#include "device.h"
3#include "ms32util.h"
4
5BOOL DriverIsComputer(int driver_index)
6{
7   return (drivers[driver_index]->flags & GAME_COMPUTER) != 0;
8}
9
10BOOL DriverIsModified(int driver_index)
11{
12   return (drivers[driver_index]->flags & GAME_COMPUTER_MODIFIED) != 0;
13}
14
15BOOL DriverUsesMouse(int driver_index)
16{
17   const input_port_entry *input_ports;
18   BOOL retval = FALSE;
19
20   if (drivers[driver_index]->ipt)
21   {
22      begin_resource_tracking();
23      input_ports = input_port_allocate(drivers[driver_index]->ipt, NULL);
24
25      while (input_ports->type != IPT_END)
26      {
27         if (input_ports->type == IPT_MOUSE_X || input_ports->type == IPT_MOUSE_Y)
28         {
29            retval = TRUE;
30            break;
31         }
32         input_ports++;
33      }
34
35      end_resource_tracking();
36   }
37
38   return retval;
39}
40
41BOOL DriverHasDevice(const game_driver *gamedrv, iodevice_t type)
42{
43   BOOL b;
44   const struct IODevice *devices;
45
46   devices = devices_allocate(gamedrv);
47   b = device_find(devices, IO_PRINTER) ? TRUE : FALSE;
48   devices_free(devices);
49   return b;
50}
51
52
src/mess/osd/windows/ui/ms32util.h
r995r996
1#ifndef MS32UTIL_H
2#define MS32UTIL_H
3
4#include <windows.h>
5
6BOOL DriverIsComputer(int driver_index);
7BOOL DriverIsModified(int driver_index);
8BOOL DriverUsesMouse(int driver_index);
9BOOL DriverHasDevice(const game_driver *gamedrv, iodevice_t type);
10
11#endif /* MS32UTIL_H */
12
src/mess/osd/windows/ui/softwarepicker.c
r995r996
1//============================================================
2//
3//   softwarepicker.c - MESS's software picker
4//
5//============================================================
6
7#define WIN32_LEAN_AND_MEAN
8#include <assert.h>
9#include <string.h>
10#include <windows.h>
11#include <shellapi.h>
12#include <commctrl.h>
13#include <commdlg.h>
14#include <wingdi.h>
15#include <winuser.h>
16#include <tchar.h>
17#include <ctype.h>
18
19#include "driver.h"
20#include "unzip.h"
21#include "strconv.h"
22#include "hashfile.h"
23#include "ui/picker.h"
24#include "ui/screenshot.h"
25#include "ui/bitmask.h"
26#include "ui/mame32.h"
27#include "ui/resourcems.h"
28#include "ui/m32opts.h"
29#include "softwarepicker.h"
30#include "ui/m32util.h"
31
32
33
34struct FileInfo
35{
36   device_class devclass;
37
38   // hash information
39   char szHash[HASH_BUF_SIZE];
40   BOOL bHashRealized;
41   const struct hash_info *pHashInfo;
42
43   LPCSTR pszZipEntryName;
44   LPCSTR pszSubName;
45   char szFilename[1];
46};
47
48struct DirectorySearchInfo
49{
50   struct DirectorySearchInfo *pNext;
51   HANDLE hFind;
52   WIN32_FIND_DATA fd;
53   char szDirectory[1];
54};
55
56struct SoftwarePickerInfo
57{
58   WNDPROC pfnOldWndProc;
59   struct FileInfo **ppIndex;
60   int nIndexLength;
61   int nHashesRealized;
62   int nCurrentPosition;
63   struct DirectorySearchInfo *pFirstSearchInfo;
64   struct DirectorySearchInfo *pLastSearchInfo;
65   const game_driver *pDriver;
66   hash_file *pHashFile;
67   void (*pfnErrorProc)(const char *message);
68};
69
70
71
72static const TCHAR s_szSoftwarePickerProp[] = TEXT("SWPICKER");
73
74
75
76static LPCSTR NormalizePath(LPCSTR pszPath, LPSTR pszBuffer, size_t nBufferSize)
77{
78   BOOL bChanged = FALSE;
79   LPSTR s;
80   int i, j;
81
82   if (pszPath[0] == '\\')
83   {
84      win_get_current_directory_utf8(nBufferSize, pszBuffer);
85      pszBuffer[2] = '\0';
86      bChanged = TRUE;
87   }
88   else if (!_istalpha(pszPath[0]) || (pszPath[1] != ':'))
89   {
90      win_get_current_directory_utf8(nBufferSize, pszBuffer);
91      bChanged = TRUE;
92   }
93
94   if (bChanged)
95   {
96      s = (LPSTR) alloca(strlen(pszBuffer) + 1);
97      strcpy(s, pszBuffer);
98      snprintf(pszBuffer, nBufferSize, "%s\\%s", s, pszPath);
99      pszPath = pszBuffer;
100
101      // Remove double path separators
102      i = 0;
103      j = 0;
104      while(pszBuffer[i])
105      {
106         while ((pszBuffer[i] == '\\') && (pszBuffer[i+1] == '\\'))
107            i++;
108         pszBuffer[j++] = pszBuffer[i++];
109      }
110      pszBuffer[j] = '\0';
111   }
112   return pszPath;
113}
114
115
116
117static struct SoftwarePickerInfo *GetSoftwarePickerInfo(HWND hwndPicker)
118{
119   HANDLE h;
120   h = GetProp(hwndPicker, s_szSoftwarePickerProp);
121   assert(h);
122   return (struct SoftwarePickerInfo *) h;
123}
124
125
126
127LPCSTR SoftwarePicker_LookupFilename(HWND hwndPicker, int nIndex)
128{
129   struct SoftwarePickerInfo *pPickerInfo;
130   pPickerInfo = GetSoftwarePickerInfo(hwndPicker);
131   if ((nIndex < 0) || (nIndex >= pPickerInfo->nIndexLength))
132      return NULL;
133   return pPickerInfo->ppIndex[nIndex]->szFilename;
134}
135
136
137
138device_class SoftwarePicker_LookupDevice(HWND hwndPicker, int nIndex)
139{
140   struct SoftwarePickerInfo *pPickerInfo;
141   pPickerInfo = GetSoftwarePickerInfo(hwndPicker);
142   if ((nIndex < 0) || (nIndex >= pPickerInfo->nIndexLength))
143   {
144      device_class dummy;
145      memset(&dummy, 0, sizeof(dummy));
146      return dummy;
147   }
148   return pPickerInfo->ppIndex[nIndex]->devclass;
149}
150
151
152
153int SoftwarePicker_LookupIndex(HWND hwndPicker, LPCSTR pszFilename)
154{
155   struct SoftwarePickerInfo *pPickerInfo;
156   int i;
157
158   pPickerInfo = GetSoftwarePickerInfo(hwndPicker);
159   for (i = 0; i < pPickerInfo->nIndexLength; i++)
160   {
161      if (!mame_stricmp(pPickerInfo->ppIndex[i]->szFilename, pszFilename))
162         return i;
163   }
164   return -1;
165}
166
167
168
169iodevice_t SoftwarePicker_GetImageType(HWND hwndPicker, int nIndex)
170{
171   struct SoftwarePickerInfo *pPickerInfo;
172   const device_class *devclass;
173
174   pPickerInfo = GetSoftwarePickerInfo(hwndPicker);
175   if ((nIndex < 0) || (nIndex >= pPickerInfo->nIndexLength))
176      return -1;
177
178   devclass = &pPickerInfo->ppIndex[nIndex]->devclass;
179   if (!devclass->gamedrv)
180      return -1;
181   return (iodevice_t) (int) device_get_info_int(devclass, DEVINFO_INT_TYPE);
182}
183
184
185
186void SoftwarePicker_SetDriver(HWND hwndPicker, const game_driver *pDriver)
187{
188   struct SoftwarePickerInfo *pPickerInfo;
189   int i;
190
191   pPickerInfo = GetSoftwarePickerInfo(hwndPicker);
192
193   if (pPickerInfo->pDriver != pDriver)
194   {
195      if (pPickerInfo->pHashFile)
196      {
197         hashfile_close(pPickerInfo->pHashFile);
198         pPickerInfo->pHashFile = NULL;
199
200         for (i = 0; i < pPickerInfo->nIndexLength; i++)
201         {
202            pPickerInfo->ppIndex[i]->pHashInfo = NULL;
203            pPickerInfo->ppIndex[i]->bHashRealized = FALSE;
204         }
205         pPickerInfo->nHashesRealized = 0;
206      }
207     
208
209      pPickerInfo->pDriver = pDriver;
210     
211      if (pDriver)
212      {
213         while(pDriver && !pPickerInfo->pHashFile)
214         {
215            pPickerInfo->pHashFile = hashfile_open_options(Mame32Global(), pDriver->name, TRUE, pPickerInfo->pfnErrorProc);
216            pDriver = mess_next_compatible_driver(pDriver);
217         }
218      }
219   }
220}
221
222
223
224void SoftwarePicker_SetErrorProc(HWND hwndPicker, void (*pfnErrorProc)(const char *message))
225{
226   struct SoftwarePickerInfo *pPickerInfo;
227   pPickerInfo = GetSoftwarePickerInfo(hwndPicker);
228   pPickerInfo->pfnErrorProc = pfnErrorProc;
229}
230
231
232
233static void ComputeFileHash(struct SoftwarePickerInfo *pPickerInfo,
234   struct FileInfo *pFileInfo, const unsigned char *pBuffer, unsigned int nLength)
235{
236   unsigned int nFunctions;
237   iodevice_t type;
238   device_partialhash_handler partialhash;
239
240   type = (iodevice_t) (int) device_get_info_int(&pFileInfo->devclass, DEVINFO_INT_TYPE);
241   partialhash = (device_partialhash_handler) device_get_info_fct(&pFileInfo->devclass, DEVINFO_PTR_PARTIAL_HASH);
242
243   nFunctions = hashfile_functions_used(pPickerInfo->pHashFile, type);
244
245   if (partialhash)
246   {
247      partialhash(pFileInfo->szHash, pBuffer, nLength, nFunctions);
248   }
249   else
250   {
251      hash_compute(pFileInfo->szHash, pBuffer, nLength, nFunctions);
252   }
253}
254
255
256
257static BOOL SoftwarePicker_CalculateHash(HWND hwndPicker, int nIndex)
258{
259   struct SoftwarePickerInfo *pPickerInfo;
260   struct FileInfo *pFileInfo;
261   LPSTR pszZipName;
262   BOOL rc = FALSE;
263   unsigned char *pBuffer;
264   unsigned int nLength;
265   HANDLE hFile, hFileMapping;
266   LVFINDINFO lvfi;
267
268   pPickerInfo = GetSoftwarePickerInfo(hwndPicker);
269   assert((nIndex >= 0) && (nIndex < pPickerInfo->nIndexLength));
270   pFileInfo = pPickerInfo->ppIndex[nIndex];
271
272   if (pFileInfo->pszZipEntryName)
273   {
274      // this is in a ZIP file
275      zip_file *zip;
276      zip_error ziperr;
277      const zip_file_header *zipent;
278
279      // open the ZIP file
280      nLength = pFileInfo->pszZipEntryName - pFileInfo->szFilename;
281      pszZipName = (LPSTR) alloca(nLength);
282      memcpy(pszZipName, pFileInfo->szFilename, nLength);
283      pszZipName[nLength - 1] = '\0';
284
285      // get the entry name
286      ziperr = zip_file_open(pszZipName, &zip);
287      if (ziperr == ZIPERR_NONE)
288      {
289         zipent = zip_file_first_file(zip);
290         while(!rc && zipent)
291         {
292            if (!mame_stricmp(zipent->filename, pFileInfo->pszZipEntryName))
293            {
294               pBuffer = malloc(zipent->uncompressed_length);
295               if (pBuffer)
296               {
297                  ziperr = zip_file_decompress(zip, pBuffer, zipent->uncompressed_length);
298                  if (ziperr == ZIPERR_NONE)
299                  {
300                     ComputeFileHash(pPickerInfo, pFileInfo, pBuffer, zipent->uncompressed_length);
301                     rc = TRUE;
302                  }
303                  free(pBuffer);
304               }
305            }
306            zipent = zip_file_next_file(zip);
307         }
308         zip_file_close(zip);
309      }
310   }
311   else
312   {
313      // plain open file; map it into memory and calculate the hash
314      hFile = win_create_file_utf8(pFileInfo->szFilename, GENERIC_READ, FILE_SHARE_READ, NULL,
315         OPEN_EXISTING, 0, NULL);
316      if (hFile != INVALID_HANDLE_VALUE)
317      {
318         nLength = GetFileSize(hFile, NULL);
319         hFileMapping = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
320         if (hFileMapping)
321         {
322            pBuffer = MapViewOfFile(hFileMapping, FILE_MAP_READ, 0, 0, 0);
323            if (pBuffer)
324            {
325               ComputeFileHash(pPickerInfo, pFileInfo, pBuffer, nLength);
326               UnmapViewOfFile(pBuffer);
327               rc = TRUE;
328            }
329            CloseHandle(hFileMapping);
330         }
331         CloseHandle(hFile);
332      }
333   }
334
335   if (rc)
336   {
337      memset(&lvfi, 0, sizeof(lvfi));
338      lvfi.flags = LVFI_PARAM;
339      lvfi.lParam = nIndex;
340      nIndex = ListView_FindItem(hwndPicker, -1, &lvfi);
341      if (nIndex > 0)
342         ListView_RedrawItems(hwndPicker, nIndex, nIndex);
343   }
344
345   return rc;
346}
347
348
349
350static void SoftwarePicker_RealizeHash(HWND hwndPicker, int nIndex)
351{
352   struct SoftwarePickerInfo *pPickerInfo;
353   struct FileInfo *pFileInfo;
354   unsigned int nHashFunctionsUsed = 0;
355   unsigned int nCalculatedHashes = 0;
356   iodevice_t type;
357
358   pPickerInfo = GetSoftwarePickerInfo(hwndPicker);
359   assert((nIndex >= 0) && (nIndex < pPickerInfo->nIndexLength));
360   pFileInfo = pPickerInfo->ppIndex[nIndex];
361
362   // Determine which hash functions we need to use for this file, and which hashes
363   // have already been calculated
364   if ((pPickerInfo->pHashFile != NULL) && (pFileInfo->devclass.get_info != NULL))
365   {
366      type = (iodevice_t) (int) device_get_info_int(&pFileInfo->devclass, DEVINFO_INT_TYPE);
367      if (type < IO_COUNT)
368           nHashFunctionsUsed = hashfile_functions_used(pPickerInfo->pHashFile, type);
369      nCalculatedHashes = hash_data_used_functions(pFileInfo->szHash);
370   }
371
372   // Did we fully compute all hashes?
373   if ((nHashFunctionsUsed & ~nCalculatedHashes) == 0)
374   {
375      // We have calculated all hashs for this file; mark it as realized
376      pPickerInfo->ppIndex[nIndex]->bHashRealized = TRUE;
377      pPickerInfo->nHashesRealized++;
378
379      if (pPickerInfo->pHashFile)
380      {
381         pPickerInfo->ppIndex[nIndex]->pHashInfo = hashfile_lookup(pPickerInfo->pHashFile,
382            pPickerInfo->ppIndex[nIndex]->szHash);
383      }
384   }
385}
386
387
388
389static BOOL SoftwarePicker_AddFileEntry(HWND hwndPicker, LPCSTR pszFilename,
390   UINT nZipEntryNameLength, UINT32 nCrc, BOOL bForce)
391{
392   struct SoftwarePickerInfo *pPickerInfo;
393   struct FileInfo **ppNewIndex;
394   struct FileInfo *pInfo;
395   int nIndex, nSize, devindex;
396   LPCSTR pszExtension = NULL, s;
397   const struct IODevice *devices = NULL;
398   device_class devclass = {0,};
399
400   // first check to see if it is already here
401   if (SoftwarePicker_LookupIndex(hwndPicker, pszFilename) >= 0)
402      return TRUE;
403
404   pPickerInfo = GetSoftwarePickerInfo(hwndPicker);
405
406   // look up the device
407   if (strrchr(pszFilename, '.'))
408      pszExtension = strrchr(pszFilename, '.');
409   if (pszExtension && pPickerInfo->pDriver)
410   {
411      pszExtension++;
412
413      devices = devices_allocate(pPickerInfo->pDriver);
414      if (devices != NULL)
415      {
416         for (devindex = 0; devices[devindex].type < IO_COUNT; devindex++)
417         {
418            s = devices[devindex].file_extensions;
419            if (s)
420            {
421               while(*s && mame_stricmp(pszExtension, s))
422                  s += strlen(s) + 1;
423               if (*s)
424               {
425                  devclass = devices[devindex].devclass;
426                  break;
427               }
428            }
429         }
430         devices_free(devices);
431      }
432   }
433
434   // no device?  cop out unless bForce is on
435   if (!devclass.gamedrv && !bForce)
436      return TRUE;
437
438   // create the FileInfo structure
439   nSize = sizeof(struct FileInfo) + strlen(pszFilename);
440   pInfo = (struct FileInfo *) malloc(nSize);
441   if (!pInfo)
442      goto error;
443   memset(pInfo, 0, nSize);
444
445   // copy the filename
446   strcpy(pInfo->szFilename, pszFilename);
447   
448   // set up device and CRC, if specified
449   pInfo->devclass = devclass;
450   if (devclass.gamedrv && device_get_info_fct(&devclass, DEVINFO_PTR_PARTIAL_HASH))
451      nCrc = 0;
452   if (nCrc != 0)
453      snprintf(pInfo->szHash, sizeof(pInfo->szHash) / sizeof(pInfo->szHash[0]), "c:%08x#", nCrc);
454
455   // set up zip entry name length, if specified
456   if (nZipEntryNameLength > 0)
457      pInfo->pszZipEntryName = pInfo->szFilename + strlen(pInfo->szFilename) - nZipEntryNameLength;
458
459   // calculate the subname
460   pInfo->pszSubName = strrchr(pInfo->szFilename, '\\');
461   if (pInfo->pszSubName)
462      pInfo->pszSubName++;
463   else
464      pInfo->pszSubName = pInfo->szFilename;
465
466   ppNewIndex = realloc(pPickerInfo->ppIndex, (pPickerInfo->nIndexLength + 1) * sizeof(*pPickerInfo->ppIndex));
467   if (!ppNewIndex)
468      goto error;
469
470   nIndex = pPickerInfo->nIndexLength++;
471   pPickerInfo->ppIndex = ppNewIndex;
472   pPickerInfo->ppIndex[nIndex] = pInfo;
473
474   // Realize the hash
475   SoftwarePicker_RealizeHash(hwndPicker, nIndex);
476
477   // Actually insert the item into the picker
478   Picker_InsertItemSorted(hwndPicker, nIndex);
479   return TRUE;
480
481error:
482   if (pInfo)
483      free(pInfo);
484   return FALSE;
485}
486
487
488
489static BOOL SoftwarePicker_AddZipEntFile(HWND hwndPicker, LPCSTR pszZipPath,
490   BOOL bForce, zip_file *pZip, const zip_file_header *pZipEnt)
491{
492   LPSTR s;
493   LPCSTR temp = pZipEnt->filename;
494   int nLength;
495   int nZipEntryNameLength;
496
497   // special case; skip first two characters if they are './'
498   if ((pZipEnt->filename[0] == '.') && (pZipEnt->filename[1] == '/'))
499   {
500      while(*(++temp) == '/')
501         ;
502   }
503
504   nZipEntryNameLength = strlen(pZipEnt->filename);
505   nLength = strlen(pszZipPath) + 1 + nZipEntryNameLength + 1;
506   s = (LPSTR) alloca(nLength);
507   snprintf(s, nLength, "%s\\%s", pszZipPath, pZipEnt->filename);
508
509   return SoftwarePicker_AddFileEntry(hwndPicker, s,
510      nZipEntryNameLength, pZipEnt->crc, bForce);
511}
512
513static BOOL SoftwarePicker_InternalAddFile(HWND hwndPicker, LPCSTR pszFilename,
514   BOOL bForce)
515{
516   LPCSTR s;
517   BOOL rc = TRUE;
518   zip_error ziperr;
519   zip_file *pZip;
520   const zip_file_header *pZipEnt;
521
522   s = strrchr(pszFilename, '.');
523   if (s && !mame_stricmp(s, ".zip"))
524   {
525      ziperr = zip_file_open(pszFilename, &pZip);
526      if (ziperr  == ZIPERR_NONE)
527      {
528         pZipEnt = zip_file_first_file(pZip);
529         while(rc && pZipEnt)
530         {
531            rc = SoftwarePicker_AddZipEntFile(hwndPicker, pszFilename,
532               bForce, pZip, pZipEnt);
533            pZipEnt = zip_file_next_file(pZip);
534         }
535         zip_file_close(pZip);
536      }
537   }
538   else
539   {
540      rc = SoftwarePicker_AddFileEntry(hwndPicker, pszFilename, 0, 0, bForce);
541   }
542   return rc;
543}
544
545
546
547BOOL SoftwarePicker_AddFile(HWND hwndPicker, LPCSTR pszFilename)
548{
549   char szBuffer[MAX_PATH];
550
551   Picker_ResetIdle(hwndPicker);
552   pszFilename = NormalizePath(pszFilename, szBuffer, sizeof(szBuffer)
553      / sizeof(szBuffer[0]));
554
555   return SoftwarePicker_InternalAddFile(hwndPicker, pszFilename, TRUE);
556}
557
558
559
560BOOL SoftwarePicker_AddDirectory(HWND hwndPicker, LPCSTR pszDirectory)
561{
562   struct SoftwarePickerInfo *pPickerInfo;
563   struct DirectorySearchInfo *pSearchInfo;
564   struct DirectorySearchInfo **ppLast;
565   size_t nSearchInfoSize;
566   char szBuffer[MAX_PATH];
567
568   pszDirectory = NormalizePath(pszDirectory, szBuffer, sizeof(szBuffer)
569      / sizeof(szBuffer[0]));
570
571   Picker_ResetIdle(hwndPicker);
572   pPickerInfo = GetSoftwarePickerInfo(hwndPicker);
573
574   nSearchInfoSize = sizeof(struct DirectorySearchInfo) + strlen(pszDirectory);
575   pSearchInfo = malloc(nSearchInfoSize);
576   if (!pSearchInfo)
577      return FALSE;
578   memset(pSearchInfo, 0, nSearchInfoSize);
579   pSearchInfo->hFind = INVALID_HANDLE_VALUE;
580
581   strcpy(pSearchInfo->szDirectory, pszDirectory);
582
583   // insert into linked list
584   if (pPickerInfo->pLastSearchInfo)
585      ppLast = &pPickerInfo->pLastSearchInfo->pNext;
586   else
587      ppLast = &pPickerInfo->pFirstSearchInfo;
588   *ppLast = pSearchInfo;
589   pPickerInfo->pLastSearchInfo = pSearchInfo;
590   return TRUE;
591}
592
593
594
595static void SoftwarePicker_FreeSearchInfo(struct DirectorySearchInfo *pSearchInfo)
596{
597   if (pSearchInfo->hFind != INVALID_HANDLE_VALUE)
598      FindClose(pSearchInfo->hFind);
599   free(pSearchInfo);
600}
601
602
603
604static void SoftwarePicker_InternalClear(struct SoftwarePickerInfo *pPickerInfo)
605{
606   struct DirectorySearchInfo *p;
607   int i;
608
609   for (i = 0; i < pPickerInfo->nIndexLength; i++)
610      free(pPickerInfo->ppIndex[i]);
611
612   while(pPickerInfo->pFirstSearchInfo)
613   {
614      p = pPickerInfo->pFirstSearchInfo->pNext;
615      SoftwarePicker_FreeSearchInfo(pPickerInfo->pFirstSearchInfo);
616      pPickerInfo->pFirstSearchInfo = p;
617   }
618
619   pPickerInfo->ppIndex = NULL;
620   pPickerInfo->nIndexLength = 0;
621   pPickerInfo->nCurrentPosition = 0;
622   pPickerInfo->pLastSearchInfo = NULL;
623}
624
625
626
627void SoftwarePicker_Clear(HWND hwndPicker)
628{
629   struct SoftwarePickerInfo *pPickerInfo;
630   pPickerInfo = GetSoftwarePickerInfo(hwndPicker);
631   SoftwarePicker_InternalClear(pPickerInfo);
632   ListView_DeleteAllItems(hwndPicker);
633}
634
635
636
637static BOOL SoftwarePicker_AddEntry(HWND hwndPicker,
638   struct DirectorySearchInfo *pSearchInfo)
639{
640   struct SoftwarePickerInfo *pPickerInfo;
641   LPSTR pszFilename;
642   BOOL rc;
643   char* utf8_FileName;
644
645   pPickerInfo = GetSoftwarePickerInfo(hwndPicker);
646   
647   utf8_FileName = utf8_from_tstring(pSearchInfo->fd.cFileName);
648   if( !utf8_FileName )
649      return FALSE;
650
651   if (!strcmp(utf8_FileName, ".") || !strcmp(utf8_FileName, "..")) {
652      free(utf8_FileName);
653      return TRUE;
654   }
655
656   pszFilename = alloca(strlen(pSearchInfo->szDirectory) + 1 + strlen(utf8_FileName) + 1);
657   strcpy(pszFilename, pSearchInfo->szDirectory);
658   strcat(pszFilename, "\\");
659   strcat(pszFilename, utf8_FileName);
660
661   if (pSearchInfo->fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
662      rc = SoftwarePicker_AddDirectory(hwndPicker, pszFilename);
663   else
664      rc = SoftwarePicker_InternalAddFile(hwndPicker, pszFilename, FALSE);
665     
666      free(utf8_FileName);
667   return rc;
668}
669
670
671
672BOOL SoftwarePicker_Idle(HWND hwndPicker)
673{
674   struct SoftwarePickerInfo *pPickerInfo;
675   struct FileInfo *pFileInfo;
676   static const char szWildcards[] = "\\*.*";
677   struct DirectorySearchInfo *pSearchInfo;
678   LPSTR pszFilter;
679   BOOL bSuccess;
680   int nCount;
681   BOOL bDone = FALSE;
682   iodevice_t type;
683
684   pPickerInfo = GetSoftwarePickerInfo(hwndPicker);
685
686   pSearchInfo = pPickerInfo->pFirstSearchInfo;
687   if (pSearchInfo)
688   {
689      // searching through directories
690      if (pSearchInfo->hFind != INVALID_HANDLE_VALUE)
691      {
692         bSuccess = FindNextFile(pSearchInfo->hFind, &pSearchInfo->fd);
693      }
694      else
695      {
696         pszFilter = alloca(strlen(pSearchInfo->szDirectory) + strlen(szWildcards) + 1);
697         strcpy(pszFilter, pSearchInfo->szDirectory);
698         strcat(pszFilter, szWildcards);
699         pSearchInfo->hFind = win_find_first_file_utf8(pszFilter, &pSearchInfo->fd);
700         bSuccess = pSearchInfo->hFind != INVALID_HANDLE_VALUE;
701      }
702
703      if (bSuccess)
704      {
705         SoftwarePicker_AddEntry(hwndPicker, pSearchInfo);
706      }
707      else
708      {
709         pPickerInfo->pFirstSearchInfo = pSearchInfo->pNext;
710         if (!pPickerInfo->pFirstSearchInfo)
711            pPickerInfo->pLastSearchInfo = NULL;
712         SoftwarePicker_FreeSearchInfo(pSearchInfo);
713      }
714   }
715   else if (pPickerInfo->pHashFile && (pPickerInfo->nHashesRealized
716      < pPickerInfo->nIndexLength))
717   {
718      // time to realize some hashes
719      nCount = 100;
720
721      while((nCount > 0) && pPickerInfo->ppIndex[pPickerInfo->nCurrentPosition]->bHashRealized)
722      {
723         pPickerInfo->nCurrentPosition++;
724         pPickerInfo->nCurrentPosition %= pPickerInfo->nIndexLength;
725         nCount--;
726      }
727
728      pFileInfo = pPickerInfo->ppIndex[pPickerInfo->nCurrentPosition];
729      if (!pFileInfo->bHashRealized)
730      {
731         type = (iodevice_t) (int) device_get_info_int(&pFileInfo->devclass, DEVINFO_INT_TYPE);
732         if (hashfile_functions_used(pPickerInfo->pHashFile, type))
733         {
734            // only calculate the hash if it is appropriate for this device
735            if (!SoftwarePicker_CalculateHash(hwndPicker, pPickerInfo->nCurrentPosition))
736               return FALSE;
737         }
738         SoftwarePicker_RealizeHash(hwndPicker, pPickerInfo->nCurrentPosition);
739
740         // under normal circumstances this will be redundant, but in the unlikely
741         // event of a failure, we do not want to keep running into a brick wall
742         // by calculating this hash over and over
743         if (!pPickerInfo->ppIndex[pPickerInfo->nCurrentPosition]->bHashRealized)
744         {
745            pPickerInfo->ppIndex[pPickerInfo->nCurrentPosition]->bHashRealized = TRUE;
746            pPickerInfo->nHashesRealized++;
747         }
748      }
749   }
750   else
751   {
752      // we are done!
753      bDone = TRUE;
754   }
755
756   return !bDone;
757}
758
759
760
761LPCTSTR SoftwarePicker_GetItemString(HWND hwndPicker, int nRow, int nColumn,
762   TCHAR *pszBuffer, UINT nBufferLength)
763{
764   struct SoftwarePickerInfo *pPickerInfo;
765   const struct FileInfo *pFileInfo;
766   LPCTSTR s = NULL;
767   const char *pszUtf8 = NULL;
768   unsigned int nHashFunction = 0;
769   char szBuffer[256];
770   TCHAR* t_buf;
771   
772   pPickerInfo = GetSoftwarePickerInfo(hwndPicker);
773   if ((nRow < 0) || (nRow >= pPickerInfo->nIndexLength))
774      return NULL;
775
776   pFileInfo = pPickerInfo->ppIndex[nRow];
777
778   switch(nColumn)
779   {
780      case MESS_COLUMN_IMAGES:
781         t_buf = tstring_from_utf8(pFileInfo->pszSubName);
782         if( !t_buf )
783            return s;
784         _sntprintf(pszBuffer, nBufferLength, TEXT("%s"), t_buf);   
785         s = pszBuffer;
786         free(t_buf);
787         break;
788
789      case MESS_COLUMN_GOODNAME:
790      case MESS_COLUMN_MANUFACTURER:
791      case MESS_COLUMN_YEAR:
792      case MESS_COLUMN_PLAYABLE:
793         if (pFileInfo->pHashInfo)
794         {
795            switch(nColumn)
796            {
797               case MESS_COLUMN_GOODNAME:
798                  pszUtf8 = pFileInfo->pHashInfo->longname;
799                  break;
800               case MESS_COLUMN_MANUFACTURER:
801                  pszUtf8 = pFileInfo->pHashInfo->manufacturer;
802                  break;
803               case MESS_COLUMN_YEAR:
804                  pszUtf8 = pFileInfo->pHashInfo->year;
805                  break;
806               case MESS_COLUMN_PLAYABLE:
807                  pszUtf8 = pFileInfo->pHashInfo->playable;
808                  break;
809            }
810            if (pszUtf8)
811            {
812               t_buf = tstring_from_utf8(pszUtf8);
813               if( !t_buf )
814                  return s;
815               _sntprintf(pszBuffer, nBufferLength, TEXT("%s"), t_buf);   
816               s = pszBuffer;
817               free(t_buf);
818            }
819         }
820         break;
821
822      case MESS_COLUMN_CRC:
823      case MESS_COLUMN_MD5:
824      case MESS_COLUMN_SHA1:
825      switch (nColumn)
826         {
827            case MESS_COLUMN_CRC:   nHashFunction = HASH_CRC;   break;
828            case MESS_COLUMN_MD5:   nHashFunction = HASH_MD5;   break;
829            case MESS_COLUMN_SHA1:   nHashFunction = HASH_SHA1;   break;
830         }
831         if (hash_data_extract_printable_checksum(pFileInfo->szHash, nHashFunction, szBuffer))
832         {
833            t_buf = tstring_from_utf8(szBuffer);
834            if( !t_buf )
835               return s;   
836            _sntprintf(pszBuffer, nBufferLength, TEXT("%s"), t_buf);
837            s = pszBuffer;
838            free(t_buf);
839         }
840         break;
841   }
842   return s;
843}
844
845
846
847static LRESULT CALLBACK SoftwarePicker_WndProc(HWND hwndPicker, UINT nMessage,
848   WPARAM wParam, LPARAM lParam)
849{
850   struct SoftwarePickerInfo *pPickerInfo;
851   LRESULT rc;
852   
853   pPickerInfo = GetSoftwarePickerInfo(hwndPicker);
854   rc = CallWindowProc(pPickerInfo->pfnOldWndProc, hwndPicker, nMessage, wParam, lParam);
855
856   if (nMessage == WM_DESTROY)
857   {
858      SoftwarePicker_InternalClear(pPickerInfo);
859      SoftwarePicker_SetDriver(hwndPicker, NULL);
860      free(pPickerInfo);
861   }
862
863   return rc;
864}
865
866
867
868BOOL SetupSoftwarePicker(HWND hwndPicker, const struct PickerOptions *pOptions)
869{
870   struct SoftwarePickerInfo *pPickerInfo = NULL;
871   LONG_PTR l;
872
873   if (!SetupPicker(hwndPicker, pOptions))
874      goto error;
875
876   pPickerInfo = malloc(sizeof(*pPickerInfo));
877   if (!pPickerInfo)
878      goto error;
879   memset(pPickerInfo, 0, sizeof(*pPickerInfo));
880
881   if (!SetProp(hwndPicker, s_szSoftwarePickerProp, (HANDLE) pPickerInfo))
882      goto error;
883   
884   l = (LONG_PTR) SoftwarePicker_WndProc;
885   l = SetWindowLongPtr(hwndPicker, GWLP_WNDPROC, l);
886   pPickerInfo->pfnOldWndProc = (WNDPROC) l;
887   return TRUE;
888
889error:
890   if (pPickerInfo)
891      free(pPickerInfo);
892   return FALSE;
893}
src/mess/osd/windows/ui/guimain.c
r995r996
1//============================================================
2//
3//   guimain.c - Win32 GUI entry point
4//
5//============================================================
6
7// standard windows headers
8#define WIN32_LEAN_AND_MEAN
9#include <windows.h>
10
11int __declspec(dllimport) mess_gui_main(HINSTANCE    hInstance,
12                   HINSTANCE    hPrevInstance,
13                   LPSTR        lpCmdLine,
14                   int          nCmdShow);
15
16int WINAPI WinMain(HINSTANCE    hInstance,
17                   HINSTANCE    hPrevInstance,
18                   LPSTR        lpCmdLine,
19                   int          nCmdShow)
20{
21   return mess_gui_main(hInstance, hPrevInstance, lpCmdLine, nCmdShow);
22}
src/mess/osd/windows/ui/optionsms.c
r995r996
1#define WIN32_LEAN_AND_MEAN
2#include <assert.h>
3#include <string.h>
4#include <windows.h>
5#include <shellapi.h>
6#include <commctrl.h>
7#include <commdlg.h>
8#include <wingdi.h>
9#include <winuser.h>
10#include <tchar.h>
11
12#include "ui/m32util.h"
13#include "ui/m32opts.h"
14#include "optionsms.h"
15#include "emuopts.h"
16#include "driver.h"
17#include "messopts.h"
18#include "osd/windows/configms.h"
19#include "winmain.h"
20
21#define WINGUIOPTION_SOFTWARE_COLUMN_SHOWN      "mess_column_shown"
22#define WINGUIOPTION_SOFTWARE_COLUMN_WIDTHS      "mess_column_widths"
23#define WINGUIOPTION_SOFTWARE_COLUMN_ORDER      "mess_column_order"
24#define WINGUIOPTION_SOFTWARE_SORT_REVERSED      "mess_sort_reversed"
25#define WINGUIOPTION_SOFTWARE_SORT_COLUMN      "mess_sort_column"
26#define WINGUIOPTION_SOFTWARE_TAB            "current_software_tab"
27#define WINGUIOPTION_SOFTWAREPATH            "softwarepath"
28
29#define LOG_SOFTWARE   0
30
31static const options_entry mess_wingui_settings[] =
32{
33   { WINGUIOPTION_SOFTWARE_COLUMN_WIDTHS,   "186, 230, 88, 84, 84, 68, 248, 248",   0,            NULL },
34   { WINGUIOPTION_SOFTWARE_COLUMN_ORDER,   "0,   1,    2,  3,  4,  5,   6,   7",   0,            NULL },
35   { WINGUIOPTION_SOFTWARE_COLUMN_SHOWN,   "1,   1,    1,  1,  1,  0,   0,   0",   0,            NULL },
36
37   { WINGUIOPTION_SOFTWARE_SORT_COLUMN,   "0",                           0,            NULL },
38   { WINGUIOPTION_SOFTWARE_SORT_REVERSED,   "0",                           OPTION_BOOLEAN,   NULL },
39
40   { WINGUIOPTION_SOFTWARE_TAB,         "0",                           0,            NULL },
41   { WINGUIOPTION_SOFTWAREPATH,         "software",                        0,            NULL },
42   { NULL }
43};
44
45void MessSetupSettings(core_options *settings)
46{
47   options_add_entries(settings, mess_wingui_settings);
48}
49
50void MessSetupGameOptions(core_options *opts, int driver_index)
51{
52   BOOL is_global = (driver_index == OPTIONS_TYPE_GLOBAL);
53   AddOptions(opts, mess_core_options, is_global);
54   AddOptions(opts, mess_win_options, is_global);
55
56   if (driver_index >= 0)
57   {
58      mess_add_device_options(opts, drivers[driver_index]);
59   }
60}
61
62void SetMessColumnOrder(int order[])
63{
64   char column_order_string[10000];
65   ColumnEncodeStringWithCount(order, column_order_string, MESS_COLUMN_MAX);
66   options_set_string(Mame32Settings(), WINGUIOPTION_SOFTWARE_COLUMN_ORDER, column_order_string, OPTION_PRIORITY_CMDLINE);
67}
68
69void GetMessColumnOrder(int order[])
70{
71   const char *column_order_string;
72   column_order_string = options_get_string(Mame32Settings(), WINGUIOPTION_SOFTWARE_COLUMN_ORDER);
73   ColumnDecodeStringWithCount(column_order_string, order, MESS_COLUMN_MAX);
74}
75
76void SetMessColumnShown(int shown[])
77{
78   char column_shown_string[10000];
79   ColumnEncodeStringWithCount(shown, column_shown_string, MESS_COLUMN_MAX);
80   options_set_string(Mame32Settings(), WINGUIOPTION_SOFTWARE_COLUMN_SHOWN, column_shown_string, OPTION_PRIORITY_CMDLINE);
81}
82
83void GetMessColumnShown(int shown[])
84{
85   const char *column_shown_string;
86   column_shown_string = options_get_string(Mame32Settings(), WINGUIOPTION_SOFTWARE_COLUMN_SHOWN);
87   ColumnDecodeStringWithCount(column_shown_string, shown, MESS_COLUMN_MAX);
88}
89
90void SetMessColumnWidths(int width[])
91{
92   char column_width_string[10000];
93   ColumnEncodeStringWithCount(width, column_width_string, MESS_COLUMN_MAX);
94   options_set_string(Mame32Settings(), WINGUIOPTION_SOFTWARE_COLUMN_WIDTHS, column_width_string, OPTION_PRIORITY_CMDLINE);
95}
96
97void GetMessColumnWidths(int width[])
98{
99   const char *column_width_string;
100   column_width_string = options_get_string(Mame32Settings(), WINGUIOPTION_SOFTWARE_COLUMN_WIDTHS);
101   ColumnDecodeStringWithCount(column_width_string, width, MESS_COLUMN_MAX);
102}
103
104void SetMessSortColumn(int column)
105{
106   options_set_int(Mame32Settings(), WINGUIOPTION_SOFTWARE_SORT_COLUMN, column, OPTION_PRIORITY_CMDLINE);
107}
108
109int GetMessSortColumn(void)
110{
111   return options_get_int(Mame32Settings(), WINGUIOPTION_SOFTWARE_SORT_COLUMN);
112}
113
114void SetMessSortReverse(BOOL reverse)
115{
116   options_set_bool(Mame32Settings(), WINGUIOPTION_SOFTWARE_SORT_REVERSED, reverse, OPTION_PRIORITY_CMDLINE);
117}
118
119BOOL GetMessSortReverse(void)
120{
121   return options_get_bool(Mame32Settings(), WINGUIOPTION_SOFTWARE_SORT_REVERSED);
122}
123
124const char* GetSoftwareDirs(void)
125{
126   return options_get_string(Mame32Settings(), WINGUIOPTION_SOFTWAREPATH);
127}
128
129void SetSoftwareDirs(const char* paths)
130{
131   options_set_string(Mame32Settings(), WINGUIOPTION_SOFTWAREPATH, paths, OPTION_PRIORITY_CMDLINE);
132}
133
134const char *GetHashDirs(void)
135{
136   return options_get_string(Mame32Global(), OPTION_HASHPATH);
137}
138
139void SetHashDirs(const char *paths)
140{
141   options_set_string(Mame32Global(), OPTION_HASHPATH, paths, OPTION_PRIORITY_CMDLINE);
142}
143
144void SetSelectedSoftware(int driver_index, const device_class *devclass, int device_inst, const char *software)
145{
146   const char *opt_name = device_instancename(devclass, device_inst);
147   core_options *o;
148
149   if (LOG_SOFTWARE)
150   {
151      dprintf("SetSelectedSoftware(): driver_index=%d (\'%s\') devclass=%p device_inst=%d software='%s'\n",
152         driver_index, drivers[driver_index]->name, devclass, device_inst, software);
153   }
154
155   o = GetGameOptions(driver_index, -1);
156   opt_name = device_instancename(devclass, device_inst);
157   options_set_string(o, opt_name, software, OPTION_PRIORITY_CMDLINE);
158}
159
160const char *GetSelectedSoftware(int driver_index, const device_class *devclass, int device_inst)
161{
162   const char *opt_name = device_instancename(devclass, device_inst);
163   const char *software;
164   core_options *o;
165
166   o = GetGameOptions(driver_index, -1);
167   opt_name = device_instancename(devclass, device_inst);
168   software = options_get_string(o, opt_name);
169   return software ? software : "";
170}
171
172void SetExtraSoftwarePaths(int driver_index, const char *extra_paths)
173{
174   char opt_name[32];
175
176   assert(0 <= driver_index && driver_index < driver_list_get_count(drivers));
177
178   snprintf(opt_name, ARRAY_LENGTH(opt_name), "%s_extra_software", drivers[driver_index]->name);
179   options_set_string(Mame32Settings(), opt_name, extra_paths, OPTION_PRIORITY_CMDLINE);
180}
181
182const char *GetExtraSoftwarePaths(int driver_index)
183{
184   char opt_name[32];
185   const char *paths;
186
187   assert(0 <= driver_index && driver_index < driver_list_get_count(drivers));
188
189   snprintf(opt_name, ARRAY_LENGTH(opt_name), "%s_extra_software", drivers[driver_index]->name);
190   paths = options_get_string(Mame32Settings(), opt_name);
191   return paths ? paths : "";
192}
193
194void SetCurrentSoftwareTab(const char *shortname)
195{
196   options_set_string(Mame32Settings(), WINGUIOPTION_SOFTWARE_TAB, shortname, OPTION_PRIORITY_CMDLINE);
197}
198
199const char *GetCurrentSoftwareTab(void)
200{
201   return options_get_string(Mame32Settings(), WINGUIOPTION_SOFTWARE_TAB);
202}
src/mess/osd/windows/ui/resourcems.h
r995r996
1#ifndef RESOURCEMS_H
2#define RESOURCEMS_H
3
4#include "ui/resource.h"
5
6#define IDC_SPLITTER3                2000
7#define IDC_SWTAB                       2001
8#define IDC_SWLIST                      2002
9#define IDC_SWDEVVIEW                   2003
10#define IDC_FILTER_COMPUTER             2004
11#define IDC_FILTER_CONSOLE              2005
12#define IDC_FILTER_MODIFIED             2006
13#define IDC_USE_NEW_UI                  2007
14#define IDC_RAM_COMBOBOX            2008
15#define IDC_RAM_CAPTION               2009
16#define IDC_SKIP_WARNINGS               2013
17#define IDI_WIN_NOROMSNEEDED         2100
18#define IDI_WIN_MISSINGOPTROM         2101
19#define IDI_WIN_FLOP                    2102
20#define IDI_WIN_CASS                    2103
21#define IDI_WIN_SERL                    2104
22#define IDI_WIN_SNAP                    2105
23#define IDI_WIN_PRIN                    2106
24#define IDI_WIN_HARD                    2107
25#define IDI_WIN_CYLN                    2110
26#define IDI_WIN_PTAP                    2111
27#define IDI_WIN_PCRD                    2112
28#define ID_MESS_OPEN_SOFTWARE           2200
29#define ID_MESS_CREATE_SOFTWARE         2201
30#define ID_MESS_RUN_TESTS            2299
31#define IDD_PROP_SOFTWARE               2202
32#define IDD_PROP_CONFIGURATION          2203
33
34#endif /* RESOURCEMS_H */
src/mess/osd/windows/ui/propertiesms.c
r995r996
1#define WIN32_LEAN_AND_MEAN
2
3#ifndef _MSC_VER
4#define NONAMELESSUNION 1
5#endif
6
7#include <windows.h>
8#include <string.h>
9#include <assert.h>
10#include <commctrl.h>
11#include <commdlg.h>
12#include <windowsx.h>
13#include <sys/stat.h>
14#include <stdio.h>
15#include <tchar.h>
16
17#include "driver.h"
18#include "device.h"
19#include "ui/screenshot.h"
20#include "ui/datamap.h"
21#include "ui/bitmask.h"
22#include "ui/mame32.h"
23#include "ui/directories.h"
24#include "ui/m32util.h"
25#include "ui/m32opts.h"
26#include "resourcems.h"
27#include "mess.h"
28#include "utils.h"
29#include "propertiesms.h"
30#include "optionsms.h"
31#include "ms32util.h"
32#include "messopts.h"
33#include "strconv.h"
34
35static BOOL SoftwareDirectories_OnInsertBrowse(HWND hDlg, BOOL bBrowse, LPCTSTR lpItem);
36static BOOL SoftwareDirectories_OnDelete(HWND hDlg);
37static BOOL SoftwareDirectories_OnBeginLabelEdit(HWND hDlg, NMHDR* pNMHDR);
38static BOOL SoftwareDirectories_OnEndLabelEdit(HWND hDlg, NMHDR* pNMHDR);
39
40extern BOOL BrowseForDirectory(HWND hwnd, LPCTSTR pStartDir, TCHAR* pResult);
41BOOL g_bModifiedSoftwarePaths = FALSE;
42
43
44
45static void MarkChanged(HWND hDlg)
46{
47   HWND hCtrl;
48
49   /* fake a CBN_SELCHANGE event from IDC_SIZES to force it to be changed */
50   hCtrl = GetDlgItem(hDlg, IDC_SIZES);
51   PostMessage(hDlg, WM_COMMAND, (CBN_SELCHANGE << 16) | IDC_SIZES, (LPARAM) hCtrl);
52}
53
54
55
56static void AppendList(HWND hList, LPCTSTR lpItem, int nItem)
57{
58    LV_ITEM Item;
59   memset(&Item, 0, sizeof(LV_ITEM));
60   Item.mask = LVIF_TEXT;
61   Item.pszText = (LPTSTR) lpItem;
62   Item.iItem = nItem;
63   ListView_InsertItem(hList, &Item);
64}
65
66
67
68static BOOL SoftwareDirectories_OnInsertBrowse(HWND hDlg, BOOL bBrowse, LPCTSTR lpItem)
69{
70    int nItem;
71    TCHAR inbuf[MAX_PATH];
72    TCHAR outbuf[MAX_PATH];
73    HWND hList;
74   LPTSTR lpIn;
75
76   g_bModifiedSoftwarePaths = TRUE;
77
78    hList = GetDlgItem(hDlg, IDC_DIR_LIST);
79    nItem = ListView_GetNextItem(hList, -1, LVNI_SELECTED);
80
81    if (nItem == -1)
82        return FALSE;
83
84    /* Last item is placeholder for append */
85    if (nItem == ListView_GetItemCount(hList) - 1)
86    {
87        bBrowse = FALSE;
88    }
89
90   if (!lpItem) {
91      if (bBrowse) {
92         ListView_GetItemText(hList, nItem, 0, inbuf, ARRAY_LENGTH(inbuf));
93         lpIn = inbuf;
94      }
95      else {
96         lpIn = NULL;
97      }
98
99      if (!BrowseForDirectory(hDlg, lpIn, outbuf))
100           return FALSE;
101      lpItem = outbuf;
102   }
103
104   AppendList(hList, lpItem, nItem);
105   if (bBrowse)
106      ListView_DeleteItem(hList, nItem+1);
107   MarkChanged(hDlg);
108   return TRUE;
109}
110
111
112
113static BOOL SoftwareDirectories_OnDelete(HWND hDlg)
114{
115    int     nCount;
116    int     nSelect;
117    int     nItem;
118    HWND    hList = GetDlgItem(hDlg, IDC_DIR_LIST);
119
120   g_bModifiedSoftwarePaths = TRUE;
121
122    nItem = ListView_GetNextItem(hList, -1, LVNI_SELECTED | LVNI_ALL);
123
124    if (nItem == -1)
125        return FALSE;
126
127    /* Don't delete "Append" placeholder. */
128    if (nItem == ListView_GetItemCount(hList) - 1)
129        return FALSE;
130
131   ListView_DeleteItem(hList, nItem);
132
133    nCount = ListView_GetItemCount(hList);
134    if (nCount <= 1)
135        return FALSE;
136
137    /* If the last item was removed, select the item above. */
138    if (nItem == nCount - 1)
139        nSelect = nCount - 2;
140    else
141        nSelect = nItem;
142
143    ListView_SetItemState(hList, nSelect, LVIS_FOCUSED | LVIS_SELECTED, LVIS_FOCUSED | LVIS_SELECTED);
144   MarkChanged(hDlg);
145   return TRUE;
146}
147
148
149
150static BOOL SoftwareDirectories_OnBeginLabelEdit(HWND hDlg, NMHDR* pNMHDR)
151{
152   BOOL          bResult = FALSE;
153   NMLVDISPINFO* pDispInfo = (NMLVDISPINFO*)pNMHDR;
154   LVITEM*       pItem = &pDispInfo->item;
155   HWND    hList = GetDlgItem(hDlg, IDC_DIR_LIST);
156
157   /* Last item is placeholder for append */
158   if (pItem->iItem == ListView_GetItemCount(hList) - 1)
159   {
160      HWND hEdit = (HWND) (int) SendMessage(hList, LVM_GETEDITCONTROL, 0, 0);
161      Edit_SetText(hEdit, TEXT(""));
162   }
163
164   return bResult;
165}
166
167
168
169static BOOL SoftwareDirectories_OnEndLabelEdit(HWND hDlg, NMHDR* pNMHDR)
170{
171    BOOL          bResult = FALSE;
172    NMLVDISPINFO* pDispInfo = (NMLVDISPINFO*)pNMHDR;
173    LVITEM*       pItem = &pDispInfo->item;
174
175    if (pItem->pszText != NULL)
176    {
177        struct _stat file_stat;
178
179        /* Don't allow empty entries. */
180        if (!_tcscmp(pItem->pszText, TEXT("")))
181        {
182            return FALSE;
183        }
184
185        /* Check validity of edited directory. */
186        if (_tstat(pItem->pszText, &file_stat) == 0
187        &&  (file_stat.st_mode & S_IFDIR))
188        {
189            bResult = TRUE;
190        }
191        else
192        {
193            if (MessageBox(NULL, TEXT("Directory does not exist, continue anyway?"), TEXT(MAME32NAME), MB_OKCANCEL) == IDOK)
194                bResult = TRUE;
195        }
196    }
197
198    if (bResult == TRUE)
199    {
200      SoftwareDirectories_OnInsertBrowse(hDlg, TRUE, pItem->pszText);
201    }
202
203    return bResult;
204}
205
206
207
208BOOL PropSheetFilter_Config(const machine_config *drv, const game_driver *gamedrv)
209{
210   return (ram_option_count(gamedrv) > 0) || DriverHasDevice(gamedrv, IO_PRINTER);
211}
212
213
214
215INT_PTR CALLBACK GameMessOptionsProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam)
216{
217   INT_PTR rc = 0;
218   BOOL bHandled = FALSE;
219
220   switch (Msg) {
221   case WM_NOTIFY:
222      switch (((NMHDR *) lParam)->code) {
223      case LVN_ENDLABELEDIT:
224         rc = SoftwareDirectories_OnEndLabelEdit(hDlg, (NMHDR *) lParam);
225         bHandled = TRUE;
226         break;
227
228      case LVN_BEGINLABELEDIT:
229         rc = SoftwareDirectories_OnBeginLabelEdit(hDlg, (NMHDR *) lParam);
230         bHandled = TRUE;
231         break;
232      }
233   }
234
235   if (!bHandled)
236      rc = GameOptionsProc(hDlg, Msg, wParam, lParam);
237   return rc;
238}
239
240
241
242BOOL MessPropertiesCommand(HWND hWnd, WORD wNotifyCode, WORD wID, BOOL *changed)
243{
244   BOOL handled = TRUE;
245
246   switch(wID)
247   {
248      case IDC_DIR_BROWSE:
249         if (wNotifyCode == BN_CLICKED)
250            *changed = SoftwareDirectories_OnInsertBrowse(hWnd, TRUE, NULL);
251         break;
252
253      case IDC_DIR_INSERT:
254         if (wNotifyCode == BN_CLICKED)
255            *changed = SoftwareDirectories_OnInsertBrowse(hWnd, FALSE, NULL);
256         break;
257
258      case IDC_DIR_DELETE:
259         if (wNotifyCode == BN_CLICKED)
260            *changed = SoftwareDirectories_OnDelete(hWnd);
261         break;
262
263      default:
264         handled = FALSE;
265         break;
266   }
267   return handled;
268}
269
270
271
272//============================================================
273//  DATAMAP HANDLERS
274//============================================================
275
276static void DirListReadControl(datamap *map, HWND dialog, HWND control, core_options *opts, const char *option_name)
277{
278   int directory_count;
279    LV_ITEM lvi;
280   TCHAR buffer[2048];
281   char *dir_list;
282   int i, pos, driver_index;
283
284   // determine the directory count; note that one item is the "<    >" entry
285   directory_count = ListView_GetItemCount(control);
286   if (directory_count > 0)
287      directory_count--;
288
289   buffer[0] = '\0';
290   pos = 0;
291
292   for (i = 0; i < directory_count; i++)
293   {
294      // append a semicolon, if we're past the first entry
295      if (i > 0)
296         pos += _sntprintf(&buffer[pos], ARRAY_LENGTH(buffer) - pos, TEXT(";"));
297
298      // retrieve the next entry
299      memset(&lvi, '\0', sizeof(lvi));
300      lvi.mask = LVIF_TEXT;
301      lvi.iItem = i;
302      lvi.pszText = &buffer[pos];
303      lvi.cchTextMax = ARRAY_LENGTH(buffer) - pos;
304      ListView_GetItem(control, &lvi);
305
306      // advance the position
307      pos += _tcslen(&buffer[pos]);
308   }
309
310   dir_list = utf8_from_tstring(buffer);
311   if (dir_list != NULL)
312   {
313      driver_index = PropertiesCurrentGame(dialog);
314      SetExtraSoftwarePaths(driver_index, dir_list);
315      free(dir_list);
316   }
317}
318
319
320
321static void DirListPopulateControl(datamap *map, HWND dialog, HWND control, core_options *opts, const char *option_name)
322{
323   int driver_index, pos, new_pos, current_item;
324   const char *dir_list;
325   TCHAR *t_dir_list;
326   TCHAR *s;
327   LV_COLUMN lvc;
328   RECT r;
329
330   // access the directory list, and convert to TCHARs
331   driver_index = PropertiesCurrentGame(dialog);
332   dir_list = GetExtraSoftwarePaths(driver_index);
333   t_dir_list = tstring_from_utf8(dir_list);
334   if (!t_dir_list)
335      return;
336
337   // delete all items in the list control
338   ListView_DeleteAllItems(control);
339
340   // add the column
341   GetClientRect(control, &r);
342   memset(&lvc, 0, sizeof(LVCOLUMN));
343   lvc.mask = LVCF_WIDTH;
344   lvc.cx = r.right - r.left - GetSystemMetrics(SM_CXHSCROLL);
345   ListView_InsertColumn(control, 0, &lvc);
346
347   // add each of the directories
348   pos = 0;
349   current_item = 0;
350   while(t_dir_list[pos] != '\0')
351   {
352      // parse off this item
353      s = _tcschr(&t_dir_list[pos], ';');
354      if (s != NULL)
355      {
356         *s = '\0';
357         new_pos = s - &t_dir_list[pos] + 1;
358      }
359      else
360      {
361         new_pos = pos + _tcslen(&t_dir_list[pos]);
362      }
363
364      // append this item
365      AppendList(control, &t_dir_list[pos], current_item);
366
367      // advance to next item
368      pos = new_pos;
369      current_item++;
370   }
371
372   // finish up
373   AppendList(control, TEXT(DIRLIST_NEWENTRYTEXT), current_item);
374   ListView_SetItemState(control, 0, LVIS_SELECTED, LVIS_SELECTED);
375   free(t_dir_list);
376}
377
378
379
380static void RamPopulateControl(datamap *map, HWND dialog, HWND control, core_options *opts, const char *option_name)
381{
382   int count, i, current_index, driver_index;
383   const game_driver *gamedrv;
384   UINT32 ram, current_ram;
385   char buffer[64];
386   const char *this_ram_string;
387   TCHAR* t_ramstring;
388
389   // identify the driver
390   driver_index = PropertiesCurrentGame(dialog);
391   gamedrv = drivers[driver_index];
392
393   // clear out the combo box
394   (void)ComboBox_ResetContent(control);
395
396   // identify how many options that we have
397   count = ram_option_count(gamedrv);
398   EnableWindow(control, count > 0);
399
400   // we can only do something meaningful if there is more than one option
401   if (count > 0)
402   {
403      // identify the current amount of RAM
404      this_ram_string = options_get_string(opts, OPTION_RAMSIZE);
405      current_ram = (this_ram_string != NULL) ? ram_parse_string(this_ram_string) : 0;
406      if (current_ram == 0)
407         current_ram = ram_default(gamedrv);
408
409      // by default, assume index 0
410      current_index = 0;
411
412      // loop through all options
413      for (i = 0; i < count; i++)
414      {
415         // identify this option
416         ram = ram_option(gamedrv, i);
417         this_ram_string = ram_string(buffer, ram);
418
419         t_ramstring = tstring_from_utf8(this_ram_string);
420         if( !t_ramstring )
421            return;
422
423         // add this option to the combo box
424         (void)ComboBox_InsertString(control, i, win_tstring_strdup(t_ramstring));
425         (void)ComboBox_SetItemData(control, i, ram);
426         
427         free(t_ramstring);
428
429         // is this the current option?  record the index if so
430         if (ram == current_ram)
431            current_index = i;
432      }
433
434      // set the combo box
435      (void)ComboBox_SetCurSel(control, current_index);
436   }
437}
438
439
440
441//============================================================
442//  DATAMAP SETUP
443//============================================================
444
445void MessBuildDataMap(datamap *properties_datamap)
446{
447   // MESS specific stuff
448   datamap_add(properties_datamap, IDC_DIR_LIST,            DM_STRING,   NULL);
449   datamap_add(properties_datamap, IDC_RAM_COMBOBOX,         DM_INT,      OPTION_RAMSIZE);
450   datamap_add(properties_datamap, IDC_SKIP_WARNINGS,         DM_BOOL,   OPTION_SKIP_WARNINGS);
451   datamap_add(properties_datamap, IDC_USE_NEW_UI,            DM_BOOL,   "newui");
452
453   // set up callbacks
454   datamap_set_callback(properties_datamap, IDC_DIR_LIST,      DCT_READ_CONTROL,      DirListReadControl);
455   datamap_set_callback(properties_datamap, IDC_DIR_LIST,      DCT_POPULATE_CONTROL,   DirListPopulateControl);
456   datamap_set_callback(properties_datamap, IDC_RAM_COMBOBOX,   DCT_POPULATE_CONTROL,   RamPopulateControl);
457}
src/mess/osd/windows/ui/softwarepicker.h
r995r996
1//============================================================
2//
3//   softwarepicker.h - MESS's software picker
4//
5//============================================================
6
7LPCSTR SoftwarePicker_LookupFilename(HWND hwndPicker, int nIndex);
8device_class SoftwarePicker_LookupDevice(HWND hwndPicker, int nIndex);
9int SoftwarePicker_LookupIndex(HWND hwndPicker, LPCSTR pszFilename);
10iodevice_t SoftwarePicker_GetImageType(HWND hwndPicker, int nIndex);
11BOOL SoftwarePicker_AddFile(HWND hwndPicker, LPCSTR pszFilename);
12BOOL SoftwarePicker_AddDirectory(HWND hwndPicker, LPCSTR pszDirectory);
13void SoftwarePicker_Clear(HWND hwndPicker);
14void SoftwarePicker_SetDriver(HWND hwndPicker, const game_driver *pDriver);
15void SoftwarePicker_SetErrorProc(HWND hwndPicker, void (*pfnErrorProc)(const char *message));
16
17// PickerOptions callbacks
18LPCTSTR SoftwarePicker_GetItemString(HWND hwndPicker, int nRow, int nColumn,
19   TCHAR *pszBuffer, UINT nBufferLength);
20BOOL SoftwarePicker_Idle(HWND hwndPicker);
21
22BOOL SetupSoftwarePicker(HWND hwndPicker, const struct PickerOptions *pOptions);
src/mess/osd/winui/mess32.rc
r0r996
1#include "resource.h"
2#include "resourcems.h"
3#include "windows.h"
4#include "commctrl.h"
5
6/////////////////////////////////////////////////////////////////////////////
7//
8// Dialog
9//
10
11IDD_PROP_SOFTWARE DIALOGEX 0, 0, 220, 220
12STYLE WS_CHILD | WS_CAPTION
13CAPTION "Software"
14FONT 8, "MS Sans Serif"
15BEGIN
16    ICON            IDI_WIN_FLOP,IDC_STATIC,20,10,20,20
17    LTEXT           "Title\nDirectory\nExtra",IDC_PROP_TITLE,52,9,161,25,
18                    SS_NOPREFIX
19    CONTROL         "",IDC_STATIC,"Static",SS_ETCHEDHORZ,20,38,178,1
20    LTEXT           "Additional directories:",IDC_STATIC,7,40,157,8
21    CONTROL         "List1",IDC_DIR_LIST,"SysListView32",LVS_REPORT |
22                    LVS_SINGLESEL | LVS_SHOWSELALWAYS | LVS_EDITLABELS |
23                    LVS_ALIGNLEFT | LVS_NOCOLUMNHEADER | WS_BORDER |
24                    WS_TABSTOP,7,50,206,120
25    PUSHBUTTON      "Browse...",IDC_DIR_BROWSE,7,180,50,14
26    PUSHBUTTON      "Insert",IDC_DIR_INSERT,85,180,50,14
27    PUSHBUTTON      "Delete",IDC_DIR_DELETE,163,180,50,14
28END
29
30
31IDD_PROP_CONFIGURATION DIALOGEX 0, 0, 220, 220
32STYLE WS_CHILD | WS_CAPTION
33CAPTION "Configuration"
34FONT 8, "MS Sans Serif"
35BEGIN
36    ICON            IDI_MAME32_ICON,IDC_STATIC,20,10,20,20
37    LTEXT           "Title\nDirectory\nExtra",IDC_PROP_TITLE,52,9,161,25,
38                    SS_NOPREFIX
39    CONTROL         "",IDC_STATIC,"Static",SS_ETCHEDHORZ,20,38,178,1
40    LTEXT           "RAM size",IDC_RAM_CAPTION,20,50,50,10
41    COMBOBOX        IDC_RAM_COMBOBOX,70,50,100,76,CBS_DROPDOWNLIST | WS_VSCROLL |
42                    WS_TABSTOP
43END
44
45/////////////////////////////////////////////////////////////////////////////
46
47#include "mame32.rc"
src/mess/osd/winui/cfgfile.c
r0r996
1
2#define WIN32_LEAN_AND_MEAN
3
4#include <windows.h>
5#include <windowsx.h>
6#include <winreg.h>
7#include <commctrl.h>
8#include <assert.h>
9#include <stdio.h>
10#include <sys/stat.h>
11#include <malloc.h>
12#include <math.h>
13#include <direct.h>
14#include <driver.h>
15
16#include "screenshot.h"
17#include "bitmask.h"
18#include "mame32.h"
19#include "m32util.h"
20#include "resource.h"
21#include "treeview.h"
22#include "file.h"
23#include "splitters.h"
24#include "dijoystick.h"
25#include "audit.h"
26#include "optcore.h"
27#include "options.h"
28#include "picker.h"
29#include "windows/config.h"
30
31
32
33static BOOL SettingsFileName(DWORD nSettingsFile, char *buffer, size_t bufsize)
34{
35   extern FOLDERDATA g_folderData[];
36   extern LPEXFOLDERDATA ExtraFolderData[];
37   char *ptr;
38   int i;
39   BOOL success = TRUE;
40   char title[32];
41   DWORD arg = nSettingsFile & 0x0FFFFFFF;
42   const char *pParent;
43
44   switch(nSettingsFile & 0xF0000000)
45   {
46      case SETTINGS_FILE_UI:
47         _snprintf(buffer, bufsize, "%s", MAME32NAME "ui.ini");
48         break;
49
50      case SETTINGS_FILE_GLOBAL:
51         _snprintf(buffer, bufsize, "%s", "default.cfg");
52         break;
53
54      case SETTINGS_FILE_GAME:
55         snprintf(buffer, bufsize, "%s", drivers[arg]->name);
56         break;
57
58      case SETTINGS_FILE_FOLDER:
59         snprintf(buffer, bufsize, "%s", g_folderData[arg].m_lpTitle);
60         break;
61
62      case SETTINGS_FILE_EXFOLDER:
63         snprintf(buffer, bufsize, "%s", ExtraFolderData[arg]->m_szTitle );
64         break;
65
66      case SETTINGS_FILE_SOURCEFILE:
67         //we have a source ini to create, so remove the ".c" at the end of the title
68         assert(arg >= 0);
69         assert(arg < GetNumGames());
70         strncpy(title, drivers[arg]->source_file, strlen(drivers[arg]->source_file)-2 );
71         title[strlen(drivers[arg]->source_file)-2] = '\0';
72
73         //Core expects it there
74         snprintf(buffer, bufsize, "drivers\\%s", title );
75         break;
76
77      case SETTINGS_FILE_EXFOLDERPARENT:
78         pParent = GetFolderNameByID(ExtraFolderData[arg]->m_nParent);
79         snprintf(buffer, bufsize, "%s\\%s", pParent, ExtraFolderData[arg]->m_szTitle );
80         break;
81
82      default:
83         success = FALSE;
84         break;
85   }
86   return success;
87}
88
89
90
91BOOL LoadSettingsFileEx(DWORD nSettingsFile, const struct SettingsHandler *handlers)
92{
93   char buffer[256];
94   mame_file *file = NULL;
95   struct xml_data_node *node = NULL;
96   BOOL success = FALSE;
97
98   if (!SettingsFileName(nSettingsFile, buffer, sizeof(buffer) / sizeof(buffer[0])))
99      goto done;
100
101   file = mame_fopen(buffer, 0, FILETYPE_CONFIG, 0);
102   if (!file)
103      goto done;
104
105   node = xml_file_read(file);
106   if (!node)
107      goto done;
108
109done:
110   if (node)
111      xml_file_free(node);
112   if (file)
113      mame_fclose(file);
114   return success;
115}
116
117
118
119BOOL SaveSettingsFileEx(DWORD nSettingsFile, const struct SettingsHandler *handlers)
120{
121   char buffer[256];
122   mame_file *file = NULL;
123   struct xml_data_node *node = NULL;
124   BOOL success = FALSE;
125
126   if (!SettingsFileName(nSettingsFile, buffer, sizeof(buffer) / sizeof(buffer[0])))
127      goto done;
128
129   file = mame_fopen(buffer, 0, FILETYPE_CONFIG, 0);
130   if (!file)
131      goto done;
132
133   node = xml_file_read(file);
134   if (!node)
135      goto done;
136
137   mame_fclose(file);
138   file = mame_fopen(buffer, 0, FILETYPE_CONFIG, 1);
139   if (!file)
140      goto done;
141
142   xml_file_write(node, file);
143
144done:
145   if (node)
146      xml_file_free(node);
147   if (file)
148      mame_fclose(file);
149   return success;
150}
src/mess/osd/winui/optionsms.h
r0r996
1#ifndef OPTIONSMS_H
2#define OPTIONSMS_H
3
4#include "device.h"
5#include "options.h"
6
7enum
8{
9   MESS_COLUMN_IMAGES,
10   MESS_COLUMN_GOODNAME,
11   MESS_COLUMN_MANUFACTURER,
12   MESS_COLUMN_YEAR,
13   MESS_COLUMN_PLAYABLE,
14   MESS_COLUMN_CRC,
15   MESS_COLUMN_SHA1,
16   MESS_COLUMN_MD5,
17   MESS_COLUMN_MAX
18};
19
20void MessSetupSettings(core_options *settings);
21void MessSetupGameOptions(core_options *opts, int driver_index);
22
23void SetMessColumnWidths(int widths[]);
24void GetMessColumnWidths(int widths[]);
25
26void SetMessColumnOrder(int order[]);
27void GetMessColumnOrder(int order[]);
28
29void SetMessColumnShown(int shown[]);
30void GetMessColumnShown(int shown[]);
31
32void SetMessSortColumn(int column);
33int  GetMessSortColumn(void);
34
35void SetMessSortReverse(BOOL reverse);
36BOOL GetMessSortReverse(void);
37
38const char* GetSoftwareDirs(void);
39void  SetSoftwareDirs(const char* paths);
40
41void SetHashDirs(const char *dir);
42const char *GetHashDirs(void);
43
44void SetSelectedSoftware(int driver_index, const device_class *devclass, int device_inst, const char *software);
45const char *GetSelectedSoftware(int driver_index, const device_class *devclass, int device_inst);
46
47void SetExtraSoftwarePaths(int driver_index, const char *extra_paths);
48const char *GetExtraSoftwarePaths(int driver_index);
49
50void SetCurrentSoftwareTab(const char *shortname);
51const char *GetCurrentSoftwareTab(void);
52
53#endif /* OPTIONSMS_H */
54
src/mess/osd/winui/propertiesms.h
r0r996
1#ifndef PROPERTIESMS_H
2#define PROPERTIESMS_H
3
4#include "properties.h"
5#include "datamap.h"
6
7BOOL MessPropertiesCommand(HWND hWnd, WORD wNotifyCode, WORD wID, BOOL *changed);
8
9INT_PTR CALLBACK GameMessOptionsProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam);
10BOOL PropSheetFilter_Config(const machine_config *drv, const game_driver *gamedrv);
11
12void MessBuildDataMap(datamap *properties_datamap);
13
14#endif /* PROPERTIESMS_H */
src/mess/osd/winui/res/win_cass.ico
src/mess/osd/winui/res/mess.ico
src/mess/osd/winui/res/win_noor.ico
src/mess/osd/winui/res/win_hard.ico
src/mess/osd/winui/res/mess32.ico
src/mess/osd/winui/res/win_flop.ico
src/mess/osd/winui/res/win_nrnd.ico
src/mess/osd/winui/res/win_snap.ico
src/mess/osd/winui/res/win_ptap.ico
src/mess/osd/winui/res/win_cyln.ico
src/mess/osd/winui/res/win_serl.ico
src/mess/osd/winui/res/about_mess.bmp
src/mess/osd/winui/res/bkgnd16-mess.bmp
src/mess/osd/winui/res/win_pcrd.ico
src/mess/osd/winui/res/win_prin.ico
src/mess/osd/winui/devview.c
r0r996
1// ------------------------------------------------------------------------
2// Software Device View class                                             
3// ------------------------------------------------------------------------
4
5#define WIN32_LEAN_AND_MEAN
6#include <assert.h>
7#include <string.h>
8#include <windows.h>
9#include <shellapi.h>
10#include <commctrl.h>
11#include <commdlg.h>
12#include <wingdi.h>
13#include <winuser.h>
14#include <tchar.h>
15
16#include "driver.h"
17#include "devview.h"
18#include "optionsms.h"
19#include "uitext.h"
20#include "strconv.h"
21#include "winutf8.h"
22#include "m32util.h"
23
24#define DEVVIEW_PADDING   10
25
26
27struct DevViewInfo
28{
29   HFONT hFont;
30   int nGame;
31   int nWidth;
32   BOOL bSurpressFilenameChanged;
33   const struct IODevice *pDevices;
34   const struct DevViewCallbacks *pCallbacks;
35   struct DevViewEntry *pEntries;
36};
37
38
39
40struct DevViewEntry
41{
42   const struct IODevice *dev;
43   int id;
44   HWND hwndStatic;
45   HWND hwndEdit;
46   HWND hwndBrowseButton;
47   WNDPROC pfnEditWndProc;
48};
49
50
51
52static struct DevViewInfo *GetDevViewInfo(HWND hwndDevView)
53{
54   LONG_PTR l;
55   l = GetWindowLongPtr(hwndDevView, GWLP_USERDATA);
56   return (struct DevViewInfo *) l;
57}
58
59
60
61static void DevView_Clear(HWND hwndDevView)
62{
63   struct DevViewInfo *pDevViewInfo;
64   int i;
65
66   pDevViewInfo = GetDevViewInfo(hwndDevView);
67
68   if (pDevViewInfo->pEntries != NULL)
69   {
70      for (i = 0; pDevViewInfo->pEntries[i].dev; i++)
71      {
72         DestroyWindow(pDevViewInfo->pEntries[i].hwndStatic);
73         DestroyWindow(pDevViewInfo->pEntries[i].hwndEdit);
74         DestroyWindow(pDevViewInfo->pEntries[i].hwndBrowseButton);
75      }
76      free(pDevViewInfo->pEntries);
77      pDevViewInfo->pEntries = NULL;
78   }
79
80   if (pDevViewInfo->pDevices != NULL)
81   {
82      devices_free(pDevViewInfo->pDevices);
83      pDevViewInfo->pDevices = NULL;
84   }
85}
86
87
88
89static void DevView_GetColumns(HWND hwndDevView, int *pnStaticPos, int *pnStaticWidth,
90   int *pnEditPos, int *pnEditWidth, int *pnButtonPos, int *pnButtonWidth)
91{
92   struct DevViewInfo *pDevViewInfo;
93   RECT r;
94
95   pDevViewInfo = GetDevViewInfo(hwndDevView);
96
97   GetClientRect(hwndDevView, &r);
98
99   *pnStaticPos = DEVVIEW_PADDING;
100   *pnStaticWidth = pDevViewInfo->nWidth;
101
102   *pnButtonWidth = 25;
103   *pnButtonPos = (r.right - r.left) - *pnButtonWidth - DEVVIEW_PADDING;
104
105   *pnEditPos = *pnStaticPos + *pnStaticWidth + DEVVIEW_PADDING;
106   *pnEditWidth = *pnButtonPos - *pnEditPos - DEVVIEW_PADDING;
107   if (*pnEditWidth < 0)
108      *pnEditWidth = 0;
109}
110
111
112
113void DevView_Refresh(HWND hwndDevView)
114{
115   struct DevViewInfo *pDevViewInfo;
116   int i;
117   LPCTSTR pszSelection;
118   TCHAR szBuffer[MAX_PATH];
119
120   pDevViewInfo = GetDevViewInfo(hwndDevView);
121
122   if (pDevViewInfo->pEntries)
123   {
124      for (i = 0; pDevViewInfo->pEntries[i].dev; i++)
125      {
126         pszSelection = pDevViewInfo->pCallbacks->pfnGetSelectedSoftware(
127            hwndDevView,
128            pDevViewInfo->nGame,
129            pDevViewInfo->pEntries[i].dev,
130            pDevViewInfo->pEntries[i].id,
131            szBuffer, sizeof(szBuffer) / sizeof(szBuffer[0]));
132
133         if (!pszSelection)
134            pszSelection = TEXT("");
135
136         pDevViewInfo->bSurpressFilenameChanged = TRUE;
137         SetWindowText(pDevViewInfo->pEntries[i].hwndEdit, pszSelection);
138         pDevViewInfo->bSurpressFilenameChanged = FALSE;
139      }
140   }
141}
142
143
144
145static void DevView_TextChanged(HWND hwndDevView, int nChangedEntry, LPCTSTR pszFilename)
146{
147   struct DevViewInfo *pDevViewInfo;
148   
149   pDevViewInfo = GetDevViewInfo(hwndDevView);
150   if (!pDevViewInfo->bSurpressFilenameChanged && pDevViewInfo->pCallbacks->pfnSetSelectedSoftware)
151   {
152      pDevViewInfo->pCallbacks->pfnSetSelectedSoftware(hwndDevView,
153         pDevViewInfo->nGame,
154         pDevViewInfo->pEntries[nChangedEntry].dev,
155         pDevViewInfo->pEntries[nChangedEntry].id,
156         pszFilename);
157   }
158}
159
160
161
162static LRESULT CALLBACK DevView_EditWndProc(HWND hwndEdit, UINT nMessage, WPARAM wParam, LPARAM lParam)
163{
164   struct DevViewInfo *pDevViewInfo;
165   struct DevViewEntry *pEnt;
166   LRESULT rc;
167   HWND hwndDevView;
168   LONG_PTR l;
169
170   l = GetWindowLongPtr(hwndEdit, GWLP_USERDATA);
171   pEnt = (struct DevViewEntry *) l;
172   if (IsWindowUnicode(hwndEdit))
173      rc = CallWindowProcW(pEnt->pfnEditWndProc, hwndEdit, nMessage, wParam, lParam);
174   else
175      rc = CallWindowProcA(pEnt->pfnEditWndProc, hwndEdit, nMessage, wParam, lParam);
176
177   if (nMessage == WM_SETTEXT)
178   {
179      hwndDevView = GetParent(hwndEdit);
180      pDevViewInfo = GetDevViewInfo(hwndDevView);
181      DevView_TextChanged(hwndDevView, pEnt - pDevViewInfo->pEntries, (LPCTSTR) lParam);
182   }
183   return rc;
184}
185
186
187
188BOOL DevView_SetDriver(HWND hwndDevView, int nGame)
189{
190   struct DevViewInfo *pDevViewInfo;
191   const game_driver *drv;
192   const struct IODevice *devices;
193   const struct IODevice *dev;
194   struct DevViewEntry *pEnt;
195   int i, id;
196   int y, nHeight, nDevCount;
197   int nStaticPos, nStaticWidth, nEditPos, nEditWidth, nButtonPos, nButtonWidth;
198   HDC hDc;
199   LPTSTR *ppszDevices;
200   LPTSTR s;
201   SIZE sz;
202   char buf[128];
203   LONG_PTR l;
204   const char* utf8_s;
205
206   pDevViewInfo = GetDevViewInfo(hwndDevView);
207
208   // already selected this driver?
209   if (nGame == pDevViewInfo->nGame)
210      return TRUE;
211
212   DevView_Clear(hwndDevView);
213   drv = drivers[nGame];
214   devices = pDevViewInfo->pDevices = devices_allocate(drv);
215
216   // Count total amount of devices
217   nDevCount = 0;
218   for (dev = devices; dev->type < IO_COUNT; dev++)
219      nDevCount += dev->count;
220
221   if (nDevCount > 0)
222   {
223      // Get the names of all of the devices
224      ppszDevices = (LPTSTR *) alloca(nDevCount * sizeof(*ppszDevices));
225      i = 0;
226      for (dev = devices; dev->type < IO_COUNT; dev++)
227      {
228         for (id = 0; id < dev->count; id++)
229         {
230            utf8_s = dev->name(dev, id, buf, sizeof(buf) / sizeof(buf[0]));
231            s = tstring_from_utf8(utf8_s);
232            ppszDevices[i] = alloca((_tcslen(s) + 1) * sizeof(TCHAR));
233            _tcscpy(ppszDevices[i], s);
234            free(s);
235            i++;
236         }
237      }
238
239      // Calculate the requisite size for the device column
240      pDevViewInfo->nWidth = 0;
241      if (nDevCount > 0)
242      {
243         hDc = GetDC(hwndDevView);
244         for (i = 0; i < nDevCount; i++)
245         {
246            GetTextExtentPoint32(hDc, ppszDevices[i], _tcslen(ppszDevices[i]), &sz);
247            if (sz.cx > pDevViewInfo->nWidth)
248               pDevViewInfo->nWidth = sz.cx;
249         }
250         ReleaseDC(hwndDevView, hDc);
251      }
252
253      pEnt = (struct DevViewEntry *) malloc(sizeof(struct DevViewEntry) * (nDevCount + 1));
254      if (!pEnt)
255         return FALSE;
256      memset(pEnt, 0, sizeof(struct DevViewEntry) * (nDevCount + 1));
257      pDevViewInfo->pEntries = pEnt;
258
259      y = 10;
260      nHeight = 21;
261      DevView_GetColumns(hwndDevView, &nStaticPos, &nStaticWidth,
262         &nEditPos, &nEditWidth, &nButtonPos, &nButtonWidth);
263
264      for (dev = devices; dev->type < IO_COUNT; dev++)
265      {
266         for (id = 0; id < dev->count; id++)
267         {
268            pEnt->dev = dev;
269            pEnt->id = id;
270
271            pEnt->hwndStatic = win_create_window_ex_utf8(0, "STATIC", dev->name(dev, id, buf, sizeof(buf) / sizeof(buf[0])),
272               WS_VISIBLE | WS_CHILD, nStaticPos, y, nStaticWidth, nHeight,
273               hwndDevView, NULL, NULL, NULL);
274
275            pEnt->hwndEdit = win_create_window_ex_utf8(0, "EDIT", "",
276               WS_VISIBLE | WS_CHILD | WS_BORDER | ES_AUTOHSCROLL, nEditPos, y, nEditWidth, nHeight,
277               hwndDevView, NULL, NULL, NULL);
278
279            pEnt->hwndBrowseButton = win_create_window_ex_utf8(0, "BUTTON", "...",
280               WS_VISIBLE | WS_CHILD, nButtonPos, y, nButtonWidth, nHeight,
281               hwndDevView, NULL, NULL, NULL);
282
283            if (pEnt->hwndStatic)
284            {
285               SendMessage(pEnt->hwndStatic, WM_SETFONT, (WPARAM) pDevViewInfo->hFont, TRUE);
286            }
287            if (pEnt->hwndEdit)
288            {
289               SendMessage(pEnt->hwndEdit, WM_SETFONT, (WPARAM) pDevViewInfo->hFont, TRUE);
290               l = (LONG_PTR) DevView_EditWndProc;
291               l = SetWindowLongPtr(pEnt->hwndEdit, GWLP_WNDPROC, l);
292               pEnt->pfnEditWndProc = (WNDPROC) l;
293               SetWindowLongPtr(pEnt->hwndEdit, GWLP_USERDATA, (LONG_PTR) pEnt);
294            }
295            if (pEnt->hwndBrowseButton)
296            {
297               SetWindowLongPtr(pEnt->hwndBrowseButton, GWLP_USERDATA, (LONG_PTR) pEnt);
298            }
299
300            y += nHeight;
301            pEnt++;
302         }
303      }
304   }
305
306   pDevViewInfo->nGame = nGame;
307   DevView_Refresh(hwndDevView);
308   return TRUE;
309}
310
311
312
313static void DevView_ButtonClick(HWND hwndDevView, struct DevViewEntry *pEnt, HWND hwndButton)
314{
315   struct DevViewInfo *pDevViewInfo;
316   HMENU hMenu;
317   RECT r;
318   int rc;
319   BOOL b;
320   TCHAR szPath[MAX_PATH];
321
322   pDevViewInfo = GetDevViewInfo(hwndDevView);
323
324   hMenu = CreatePopupMenu();
325
326   if (pDevViewInfo->pCallbacks->pfnGetOpenFileName)
327      AppendMenu(hMenu, MF_STRING, 1, TEXT("Mount..."));
328
329   if (pEnt->dev->creatable)
330   {
331      if (pDevViewInfo->pCallbacks->pfnGetCreateFileName)
332         AppendMenu(hMenu, MF_STRING, 2, TEXT("Create..."));
333   }
334
335   AppendMenu(hMenu, MF_STRING, 3, TEXT("Unmount"));
336
337   GetWindowRect(hwndButton, &r);
338   rc = TrackPopupMenu(hMenu, TPM_TOPALIGN | TPM_NONOTIFY | TPM_RETURNCMD,
339      r.left, r.bottom, 0, hwndDevView, NULL);
340
341   switch(rc)
342   {
343      case 1:
344         b = pDevViewInfo->pCallbacks->pfnGetOpenFileName(hwndDevView, pEnt->dev,
345            szPath, sizeof(szPath) / sizeof(szPath[0]));
346         break;
347      case 2:
348         b = pDevViewInfo->pCallbacks->pfnGetCreateFileName(hwndDevView, pEnt->dev,
349            szPath, sizeof(szPath) / sizeof(szPath[0]));
350         break;
351      case 3:
352         memset(szPath, 0, sizeof(szPath));
353         b = TRUE;
354         break;
355      default:
356         b = FALSE;
357         break;
358   }
359   if (!b)
360      return;
361   SetWindowText(pEnt->hwndEdit, szPath);
362}
363
364
365
366static BOOL DevView_Setup(HWND hwndDevView)
367{
368   struct DevViewInfo *pDevViewInfo;
369
370   pDevViewInfo = malloc(sizeof(struct DevViewInfo));
371   if (!pDevViewInfo)
372      return FALSE;
373   memset(pDevViewInfo, 0, sizeof(*pDevViewInfo));
374   pDevViewInfo->nGame = -1;
375   SetWindowLongPtr(hwndDevView, GWLP_USERDATA, (LONG_PTR) pDevViewInfo);
376
377   pDevViewInfo->hFont = CreateFont(10, 0, 0, 0, FW_NORMAL, 0, 0, 0, 0, 0,
378      0, 0, 0, TEXT("MS Sans Serif"));
379   SendMessage(hwndDevView, WM_SETFONT, (WPARAM) pDevViewInfo->hFont, FALSE);
380   return TRUE;
381}
382
383
384
385static void DevView_Free(HWND hwndDevView)
386{
387   struct DevViewInfo *pDevViewInfo;
388
389   DevView_Clear(hwndDevView);
390   pDevViewInfo = GetDevViewInfo(hwndDevView);
391   DeleteObject(pDevViewInfo->hFont);
392   free(pDevViewInfo);
393}
394
395
396
397static LRESULT CALLBACK DevView_WndProc(HWND hwndDevView, UINT nMessage, WPARAM wParam, LPARAM lParam)
398{
399   struct DevViewInfo *pDevViewInfo;
400   struct DevViewEntry *pEnt;
401   int nStaticPos, nStaticWidth, nEditPos, nEditWidth, nButtonPos, nButtonWidth;
402   RECT r;
403   LONG_PTR l;
404   LRESULT rc = 0;
405   BOOL bHandled = FALSE;
406   HWND hwndButton;
407
408   switch(nMessage)
409   {
410      case WM_DESTROY:
411         DevView_Free(hwndDevView);
412         break;
413
414      case WM_SHOWWINDOW:
415         if (wParam)
416         {
417            pDevViewInfo = GetDevViewInfo(hwndDevView);
418            DevView_Refresh(hwndDevView);
419         }
420         break;
421
422      case WM_COMMAND:
423         switch(HIWORD(wParam))
424         {
425            case BN_CLICKED:
426               hwndButton = (HWND) lParam;
427               l = GetWindowLongPtr(hwndButton, GWLP_USERDATA);
428               pEnt = (struct DevViewEntry *) l;
429               DevView_ButtonClick(hwndDevView, pEnt, hwndButton);
430               break;           
431         }
432         break;
433   }
434
435   if (!bHandled)
436      rc = DefWindowProc(hwndDevView, nMessage, wParam, lParam);
437
438   switch(nMessage)
439   {
440      case WM_CREATE:
441         if (!DevView_Setup(hwndDevView))
442            return -1;
443         break;
444
445      case WM_MOVE:
446      case WM_SIZE:
447         pDevViewInfo = GetDevViewInfo(hwndDevView);
448         pEnt = pDevViewInfo->pEntries;
449         if (pEnt)
450         {
451            DevView_GetColumns(hwndDevView, &nStaticPos, &nStaticWidth,
452               &nEditPos, &nEditWidth, &nButtonPos, &nButtonWidth);
453            while(pEnt->dev)
454            {
455               GetClientRect(pEnt->hwndStatic, &r);
456               MapWindowPoints(pEnt->hwndStatic, hwndDevView, ((POINT *) &r), 2);
457               MoveWindow(pEnt->hwndStatic, nStaticPos, r.top, nStaticWidth, r.bottom - r.top, FALSE);
458               MoveWindow(pEnt->hwndEdit, nEditPos, r.top, nEditWidth, r.bottom - r.top, FALSE);
459               MoveWindow(pEnt->hwndBrowseButton, nButtonPos, r.top, nButtonWidth, r.bottom - r.top, FALSE);
460               pEnt++;
461            }
462         }
463         break;
464   }
465   return rc;
466}
467
468
469
470void DevView_SetCallbacks(HWND hwndDevView, const struct DevViewCallbacks *pCallbacks)
471{
472   struct DevViewInfo *pDevViewInfo;
473   pDevViewInfo = GetDevViewInfo(hwndDevView);
474   pDevViewInfo->pCallbacks = pCallbacks;
475}
476
477
478
479void DevView_RegisterClass(void)
480{
481   WNDCLASS wc;
482   memset(&wc, 0, sizeof(wc));
483   wc.lpszClassName = TEXT("MessSoftwareDevView");
484   wc.hInstance = GetModuleHandle(NULL);
485   wc.lpfnWndProc = DevView_WndProc;
486   wc.hbrBackground = GetSysColorBrush(COLOR_BTNFACE);
487   RegisterClass(&wc);
488}
489
490
491
src/mess/osd/winui/mess32ui.c
r0r996
1//============================================================
2//
3//   mess32ui.c - MESS extensions to src/ui/win32ui.c
4//
5//============================================================
6
7#define WIN32_LEAN_AND_MEAN
8#include <assert.h>
9#include <string.h>
10#include <windows.h>
11#include <shellapi.h>
12#include <commctrl.h>
13#include <commdlg.h>
14#include <wingdi.h>
15#include <winuser.h>
16#include <tchar.h>
17
18#include "screenshot.h"
19#include "bitmask.h"
20#include "mame32.h"
21#include "resourcems.h"
22#include "m32opts.h"
23#include "picker.h"
24#include "tabview.h"
25#include "m32util.h"
26#include "columnedit.h"
27#include "mess.h"
28#include "configms.h"
29#include "softwarepicker.h"
30#include "devview.h"
31#include "windows/window.h"
32#include "utils.h"
33#include "uitext.h"
34#include "strconv.h"
35#include "mess32ui.h"
36#include "winutf8.h"
37
38#define LOG_SOFTWARE   0
39
40static int requested_device_type(char *tchar);
41
42static void SoftwarePicker_OnHeaderContextMenu(POINT pt, int nColumn);
43
44static LPCSTR SoftwareTabView_GetTabShortName(int tab);
45static LPCSTR SoftwareTabView_GetTabLongName(int tab);
46static void SoftwareTabView_OnSelectionChanged(void);
47static void SoftwareTabView_OnMoveSize(void);
48static void SetupSoftwareTabView(void);
49
50static LPCTSTR mess_column_names[] =
51{
52    TEXT("Software"),
53   TEXT("Goodname"),
54    TEXT("Manufacturer"),
55    TEXT("Year"),
56    TEXT("Playable"),
57   TEXT("CRC"),
58   TEXT("SHA-1"),
59   TEXT("MD5")
60};
61
62static int *mess_icon_index;
63
64static void MessOpenOtherSoftware(int iDevice);
65static void MessCreateDevice(int iDevice);
66static void MessRefreshPicker(int nGame);
67
68static int SoftwarePicker_GetItemImage(HWND hwndPicker, int nItem);
69static void SoftwarePicker_LeavingItem(HWND hwndSoftwarePicker, int nItem);
70static void SoftwarePicker_EnteringItem(HWND hwndSoftwarePicker, int nItem);
71
72static BOOL DevView_GetOpenFileName(HWND hwndDevView, const struct IODevice *dev, LPTSTR pszFilename, UINT nFilenameLength);
73static BOOL DevView_GetCreateFileName(HWND hwndDevView, const struct IODevice *dev, LPTSTR pszFilename, UINT nFilenameLength);
74static void DevView_SetSelectedSoftware(HWND hwndDevView, int nDriverIndex, const struct IODevice *dev, int nID, LPCTSTR pszFilename);
75static LPCTSTR DevView_GetSelectedSoftware(HWND hwndDevView, int nDriverIndex, const struct IODevice *dev, int nID, LPTSTR pszBuffer, UINT nBufferLength);
76
77#ifdef MAME_DEBUG
78static void MessTestsBegin(void);
79#endif /* MAME_DEBUG */
80
81char g_szSelectedItem[MAX_PATH];
82
83static int s_nGame;
84static BOOL s_bIgnoreSoftwarePickerNotifies;
85
86struct deviceentry
87{
88   int dev_type;
89   const char *icon_name;
90   const char *dlgname;
91};
92
93static const struct PickerCallbacks s_softwareListCallbacks =
94{
95   SetMessSortColumn,               // pfnSetSortColumn
96   GetMessSortColumn,               // pfnGetSortColumn
97   SetMessSortReverse,               // pfnSetSortReverse
98   GetMessSortReverse,               // pfnGetSortReverse
99   NULL,                        // pfnSetViewMode
100   GetViewMode,                  // pfnGetViewMode
101   SetMessColumnWidths,            // pfnSetColumnWidths
102   GetMessColumnWidths,            // pfnGetColumnWidths
103   SetMessColumnOrder,               // pfnSetColumnOrder
104   GetMessColumnOrder,               // pfnGetColumnOrder
105   SetMessColumnShown,               // pfnSetColumnShown
106   GetMessColumnShown,               // pfnGetColumnShown
107   NULL,                        // pfnGetOffsetChildren
108
109   NULL,                        // pfnCompare
110   MamePlayGame,                  // pfnDoubleClick
111   SoftwarePicker_GetItemString,      // pfnGetItemString
112   SoftwarePicker_GetItemImage,      // pfnGetItemImage
113   SoftwarePicker_LeavingItem,         // pfnLeavingItem
114   SoftwarePicker_EnteringItem,      // pfnEnteringItem
115   NULL,                        // pfnBeginListViewDrag
116   NULL,                        // pfnFindItemParent
117   SoftwarePicker_Idle,            // pfnIdle
118   SoftwarePicker_OnHeaderContextMenu,   // pfnOnHeaderContextMenu
119   NULL                        // pfnOnBodyContextMenu
120};
121
122
123
124static const struct TabViewCallbacks s_softwareTabViewCallbacks =
125{
126   NULL,                        // pfnGetShowTabCtrl
127   SetCurrentSoftwareTab,            // pfnSetCurrentTab
128   GetCurrentSoftwareTab,            // pfnGetCurrentTab
129   NULL,                        // pfnSetShowTab
130   NULL,                        // pfnGetShowTab
131
132   SoftwareTabView_GetTabShortName,   // pfnGetTabShortName
133   SoftwareTabView_GetTabLongName,      // pfnGetTabLongName
134
135   SoftwareTabView_OnSelectionChanged,   // pfnOnSelectionChanged
136   SoftwareTabView_OnMoveSize         // pfnOnMoveSize
137};
138
139
140
141// ------------------------------------------------------------------------
142// Image types
143//
144// IO_ZIP is used for ZIP files
145// IO_ALIAS is used for unknown types
146// IO_COUNT is used for bad files
147// ------------------------------------------------------------------------
148
149#define IO_ZIP      (IO_COUNT + 0)
150#define IO_BAD      (IO_COUNT + 1)
151#define IO_UNKNOWN   (IO_COUNT + 2)
152
153// TODO - We need to make icons for Cylinders, Punch Cards, and Punch Tape!
154static const struct deviceentry s_devices[] =
155{
156   { IO_CARTSLOT,   "roms",      "Cartridge images" },
157   { IO_FLOPPY,   "floppy",   "Floppy disk images" },
158   { IO_HARDDISK,   "hard",      "Hard disk images" },
159   { IO_CYLINDER,   NULL,      "Cylinders" },         
160   { IO_CASSETTE,   NULL,      "Cassette images" },
161   { IO_PUNCHCARD,   NULL,      "Punchcard images" },
162   { IO_PUNCHTAPE,   NULL,      "Punchtape images" },
163   { IO_PRINTER,   NULL,      "Printer Output" },
164   { IO_SERIAL,   NULL,      "Serial Output" },
165   { IO_PARALLEL,   NULL,      "Parallel Output" },
166   { IO_SNAPSHOT,   "snapshot",   "Snapshots" },
167   { IO_QUICKLOAD,   "snapshot",   "Quickloads" },
168   { IO_MEMCARD,   NULL,      "Memory cards" },
169   { IO_CDROM,      NULL,      "CD-ROM images" }
170};
171
172
173
174static void AssertValidDevice(int d)
175{
176   assert((sizeof(s_devices) / sizeof(s_devices[0])) == IO_COUNT);
177   assert(((d >= 0) && (d < IO_COUNT)) || (d == IO_UNKNOWN) || (d == IO_BAD) || (d == IO_ZIP));
178}
179
180
181
182static const struct deviceentry *lookupdevice(int d)
183{
184   assert(d >= 0);
185   assert(d < IO_COUNT);
186   AssertValidDevice(d);
187   return &s_devices[d];
188}
189
190
191
192// ------------------------------------------------------------------------
193
194static int requested_device_type(char *tchar)
195{
196   int device = -1;
197   int i;
198
199    logerror("Requested device is %s\n", tchar);
200
201   if (*tchar == '-')
202   {
203      tchar++;
204
205      for (i = 1; i < IO_COUNT; i++)
206      {
207         if (!mame_stricmp(tchar, device_typename(i)) || !mame_stricmp(tchar, device_brieftypename(i)))
208         {
209            device = i;
210            break;
211         }
212      }
213   }
214
215   return device;
216}
217
218
219
220// ------------------------------------------------------------------------
221// UI
222// ------------------------------------------------------------------------
223
224BOOL CreateMessIcons(void)
225{
226    int i;
227   HWND hwndSoftwareList;
228   HIMAGELIST hSmall;
229   HIMAGELIST hLarge;
230
231   // create the icon index, if we havn't already
232    if (!mess_icon_index)
233   {
234      mess_icon_index = pool_malloc(GetMame32MemoryPool(), driver_list_get_count(drivers) * IO_COUNT * sizeof(*mess_icon_index));
235    }
236
237    for (i = 0; i < (driver_list_get_count(drivers) * IO_COUNT); i++)
238        mess_icon_index[i] = 0;
239
240   // Associate the image lists with the list view control.
241   hwndSoftwareList = GetDlgItem(GetMainWindow(), IDC_SWLIST);
242   hSmall = GetSmallImageList();
243   hLarge = GetLargeImageList();
244   (void)ListView_SetImageList(hwndSoftwareList, hSmall, LVSIL_SMALL);
245   (void)ListView_SetImageList(hwndSoftwareList, hLarge, LVSIL_NORMAL);
246   return TRUE;
247}
248
249
250
251static int GetMessIcon(int nGame, int nSoftwareType)
252{
253    int the_index;
254    int nIconPos = 0;
255    HICON hIcon = 0;
256    const game_driver *drv;
257    char buffer[32];
258   const char *iconname;
259
260   assert(nGame >= 0);
261   assert(nGame < driver_list_get_count(drivers));
262
263    if ((nSoftwareType >= 0) && (nSoftwareType < IO_COUNT))
264   {
265      iconname = device_brieftypename(nSoftwareType);
266        the_index = (nGame * IO_COUNT) + nSoftwareType;
267
268        nIconPos = mess_icon_index[the_index];
269        if (nIconPos >= 0)
270      {
271         for (drv = drivers[nGame]; drv; drv = driver_get_clone(drv))
272         {
273            _snprintf(buffer, sizeof(buffer) / sizeof(buffer[0]), "%s/%s", drv->name, iconname);
274            hIcon = LoadIconFromFile(buffer);
275            if (hIcon)
276               break;
277         }
278
279         if (hIcon)
280         {
281            nIconPos = ImageList_AddIcon(GetSmallImageList(), hIcon);
282            ImageList_AddIcon(GetLargeImageList(), hIcon);
283            if (nIconPos != -1)
284               mess_icon_index[the_index] = nIconPos;
285         }
286        }
287    }
288    return nIconPos;
289}
290
291
292
293static void MessHashErrorProc(const char *message)
294{
295   SetStatusBarTextF(0, "Hash file: %s", message);
296}
297
298
299
300static BOOL AddSoftwarePickerDirs(HWND hwndPicker, LPCSTR pszDirectories, LPCSTR pszSubDir)
301{
302   LPCSTR s;
303   LPSTR pszNewString;
304   char cSeparator = ';';
305   int nLength;
306
307   do
308   {
309      s = pszDirectories;
310      while(*s && (*s != cSeparator))
311         s++;
312
313      nLength = s - pszDirectories;
314      if (nLength > 0)
315      {
316         pszNewString = (LPSTR) alloca((nLength + 1 + (pszSubDir ? strlen(pszSubDir) + 1 : 0)));
317         memcpy(pszNewString, pszDirectories, nLength);
318         pszNewString[nLength] = '\0';
319
320         if (pszSubDir)
321         {
322            pszNewString[nLength++] = '\\';
323            strcpy(&pszNewString[nLength], pszSubDir);
324         }
325
326         if (!SoftwarePicker_AddDirectory(hwndPicker, pszNewString))
327            return FALSE;
328      }
329      pszDirectories = s + 1;
330   }
331   while(*s);
332   return TRUE;
333}
334
335
336
337void MyFillSoftwareList(int nGame, BOOL bForce)
338{
339   const game_driver *drv;
340   HWND hwndSoftwarePicker;
341   HWND hwndSoftwareDevView;
342   
343   hwndSoftwarePicker = GetDlgItem(GetMainWindow(), IDC_SWLIST);
344   hwndSoftwareDevView = GetDlgItem(GetMainWindow(), IDC_SWDEVVIEW);
345
346   // Set up the device view
347   DevView_SetDriver(hwndSoftwareDevView, nGame);
348
349   if (!bForce && (s_nGame == nGame))
350      return;
351   s_nGame = nGame;
352
353   // Set up the software picker
354   SoftwarePicker_Clear(hwndSoftwarePicker);
355   drv = drivers[nGame];
356   SoftwarePicker_SetDriver(hwndSoftwarePicker, drv);
357   while(drv)
358   {
359      AddSoftwarePickerDirs(hwndSoftwarePicker, GetSoftwareDirs(), drv->name);
360      drv = mess_next_compatible_driver(drv);
361   }
362   AddSoftwarePickerDirs(hwndSoftwarePicker, GetExtraSoftwarePaths(nGame), NULL);
363}
364
365
366
367void MessUpdateSoftwareList(void)
368{
369   HWND hwndList = GetDlgItem(GetMainWindow(), IDC_LIST);
370   MyFillSoftwareList(Picker_GetSelectedItem(hwndList), TRUE);
371}
372
373
374
375BOOL MessApproveImageList(HWND hParent, int nGame)
376{
377   int i, nPos, devindex;
378   const struct IODevice *devices;
379   const game_driver *pDriver;
380   char szMessage[256];
381   LPCSTR pszSoftware;
382   BOOL bResult = FALSE;
383
384   begin_resource_tracking();
385
386   pDriver = drivers[nGame];
387   devices = devices_allocate(pDriver);
388
389   nPos = 0;
390   for (devindex = 0; devices[devindex].type < IO_COUNT; devindex++)
391   {
392      // confirm any mandatory devices are loaded
393      if (devices[devindex].must_be_loaded)
394      {
395         for (i = 0; i < devices[devindex].count; i++)
396         {
397            pszSoftware = GetSelectedSoftware(nGame, &devices[devindex].devclass, i);
398            if (!pszSoftware || !*pszSoftware)
399            {
400               snprintf(szMessage, sizeof(szMessage) / sizeof(szMessage[0]),
401                  "System '%s' requires that device %s must have an image to load\n",
402                  pDriver->description,
403                  device_typename(devices[devindex].type));
404               goto done;
405            }
406         }
407      }
408
409      nPos += devices[devindex].count;
410   }
411   bResult = TRUE;
412
413done:
414   if (!bResult)
415   {
416      win_message_box_utf8(hParent, szMessage, MAME32NAME, MB_OK);
417   }
418
419   devices_free(devices);
420   return bResult;
421}
422
423
424
425// this is a wrapper call to wrap the idiosycracies of SetSelectedSoftware()
426static void InternalSetSelectedSoftware(int nGame, const device_class *devclass, int device_inst, const char *pszSoftware)
427{
428   if (!pszSoftware)
429      pszSoftware = "";
430
431   // only call SetSelectedSoftware() if this value is different
432   if (strcmp(GetSelectedSoftware(nGame, devclass, device_inst), pszSoftware))
433   {
434      SetSelectedSoftware(nGame, devclass, device_inst, pszSoftware);
435   }
436}
437
438
439
440// Places the specified image in the specified slot; nID = -1 means don't matter
441static void MessSpecifyImage(int nGame, const device_class *devclass, int nID, LPCSTR pszFilename)
442{
443   const struct IODevice *devices;
444   const struct IODevice *dev;
445   const char *s;
446   int i;
447
448   devices = devices_allocate(devclass->gamedrv);
449
450   for (dev = devices; dev->type < IO_COUNT; dev++)
451   {
452      if (dev->devclass.get_info == devclass->get_info)
453         break;
454   }
455
456   if (LOG_SOFTWARE)
457   {
458      dprintf("MessSpecifyImage(): nID=%d pszFilename='%s'\n", nID, pszFilename);
459   }
460
461   if (nID < 0)
462   {
463      // special case; first try to find existing image
464      for (i = 0; i < dev->count; i++)
465      {
466         s = GetSelectedSoftware(nGame, &dev->devclass, i);
467         if (s && !mame_stricmp(s, pszFilename))
468         {
469            nID = i;
470            break;
471         }
472      }
473   }
474
475   if (nID < 0)
476   {
477      // still not found?  locate an empty slot
478      for (i = 0; i < dev->count; i++)
479      {
480         s = GetSelectedSoftware(nGame, &dev->devclass, i);
481         if (!s || !*s || !mame_stricmp(s, pszFilename))
482         {
483            nID = i;
484            break;
485         }
486      }
487   }
488
489   if (nID >= 0)
490      InternalSetSelectedSoftware(nGame, &dev->devclass, nID, pszFilename);
491   else if (LOG_SOFTWARE)
492      dprintf("MessSpecifyImage(): Failed to place image '%s'\n", pszFilename);
493
494   devices_free(devices);
495}
496
497
498
499static void MessRemoveImage(int nGame, device_class devclass, LPCSTR pszFilename)
500{
501   int i, nPos;
502   const struct IODevice *devices;
503   const struct IODevice *dev;
504
505   if (devclass.gamedrv)
506   {
507      devices = devices_allocate(devclass.gamedrv);
508
509      nPos = 0;
510      for (dev = devices; dev->type < IO_COUNT; dev++)
511      {
512         if (dev->devclass.get_info == devclass.get_info)
513            break;
514         nPos += dev->count;
515      }
516
517      if (dev->type < IO_COUNT)
518      {
519         for (i = 0; i < dev->count; i++)
520         {
521            if (!mame_stricmp(pszFilename, GetSelectedSoftware(nGame, &dev->devclass, i)))
522            {
523               MessSpecifyImage(nGame, &devclass, i, NULL);
524               break;
525            }
526         }
527      }
528
529      devices_free(devices);
530   }
531}
532
533
534
535void MessReadMountedSoftware(int nGame)
536{
537   // First read stuff into device view
538   DevView_Refresh(GetDlgItem(GetMainWindow(), IDC_SWDEVVIEW));
539
540   // Now read stuff into picker
541   MessRefreshPicker(nGame);
542}
543
544
545
546static void MessRefreshPicker(int nGame)
547{
548   HWND hwndSoftware;
549   int i, id;
550   LVFINDINFO lvfi;
551   const game_driver *pDriver;
552   const struct IODevice *pDeviceList;
553   const struct IODevice *pDevice;
554   LPCSTR pszSoftware;
555
556   hwndSoftware = GetDlgItem(GetMainWindow(), IDC_SWLIST);
557   pDriver = drivers[nGame];
558   pDeviceList = devices_allocate(pDriver);
559   if (!pDeviceList)
560      goto done;
561
562   s_bIgnoreSoftwarePickerNotifies = TRUE;
563
564   // Now clear everything out; this may call back into us but it should not
565   // be problematic
566   ListView_SetItemState(hwndSoftware, -1, 0, LVIS_SELECTED);
567
568   for (pDevice = pDeviceList; pDevice->type < IO_COUNT; pDevice++)
569   {
570      for (id = 0; id < pDevice->count; id++)
571      {
572         pszSoftware = GetSelectedSoftware(nGame, &pDevice->devclass, id);
573         if (pszSoftware && *pszSoftware)
574         {
575            i = SoftwarePicker_LookupIndex(hwndSoftware, pszSoftware);
576            if (i < 0)
577            {
578               SoftwarePicker_AddFile(hwndSoftware, pszSoftware);
579               i = SoftwarePicker_LookupIndex(hwndSoftware, pszSoftware);
580            }
581            if (i >= 0)
582            {
583               memset(&lvfi, 0, sizeof(lvfi));
584               lvfi.flags = LVFI_PARAM;
585               lvfi.lParam = i;
586               i = ListView_FindItem(hwndSoftware, -1, &lvfi);
587               ListView_SetItemState(hwndSoftware, i, LVIS_SELECTED, LVIS_SELECTED);
588            }
589         }
590      }
591   }
592
593
594done:
595   devices_free(pDeviceList);
596   s_bIgnoreSoftwarePickerNotifies = FALSE;
597}
598
599
600
601void InitMessPicker(void)
602{
603   struct PickerOptions opts;
604   HWND hwndSoftware;
605
606   s_nGame = -1;
607   hwndSoftware = GetDlgItem(GetMainWindow(), IDC_SWLIST);
608
609   memset(&opts, 0, sizeof(opts));
610   opts.pCallbacks = &s_softwareListCallbacks;
611   opts.nColumnCount = MESS_COLUMN_MAX;
612   opts.ppszColumnNames = mess_column_names;
613   SetupSoftwarePicker(hwndSoftware, &opts);
614
615   SetWindowLong(hwndSoftware, GWL_STYLE, GetWindowLong(hwndSoftware, GWL_STYLE)
616      | LVS_REPORT | LVS_SHOWSELALWAYS | LVS_OWNERDRAWFIXED);
617
618   SetupSoftwareTabView();
619
620   {
621      static const struct DevViewCallbacks s_devViewCallbacks =
622      {
623         DevView_GetOpenFileName,
624         DevView_GetCreateFileName,
625         DevView_SetSelectedSoftware,
626         DevView_GetSelectedSoftware
627      };
628      DevView_SetCallbacks(GetDlgItem(GetMainWindow(), IDC_SWDEVVIEW), &s_devViewCallbacks);
629   }
630}
631
632
633
634// ------------------------------------------------------------------------
635// Open others dialog
636// ------------------------------------------------------------------------
637
638typedef struct
639{
640   const struct IODevice *dev;
641    const char *ext;
642} mess_image_type;
643
644static BOOL CommonFileImageDialog(LPTSTR the_last_directory, common_file_dialog_proc cfd, LPTSTR filename, mess_image_type *imagetypes)
645{
646    BOOL success;
647    OPENFILENAME of;
648    char szFilter[2048];
649    LPSTR s;
650   const char *typname;
651    int i;
652    TCHAR* t_filter;
653    TCHAR* t_buffer;
654
655   s = szFilter;
656    *filename = 0;
657
658    // Common image types
659    strcpy(s, "Common image types");
660    s += strlen(s);
661    *(s++) = '|';
662    for (i = 0; imagetypes[i].ext; i++)
663   {
664        *(s++) = '*';
665        *(s++) = '.';
666        strcpy(s, imagetypes[i].ext);
667        s += strlen(s);
668        *(s++) = ';';
669    }
670    *(s++) = '|';
671
672    // All files
673    strcpy(s, "All files (*.*)");
674    s += strlen(s);
675    *(s++) = '|';
676    strcpy(s, "*.*");
677    s += strlen(s);
678    *(s++) = '|';
679
680    // The others
681    for (i = 0; imagetypes[i].ext; i++)
682   {
683      if (!imagetypes[i].dev)
684         typname = "Compressed images";
685      else
686         typname = lookupdevice(imagetypes[i].dev->type)->dlgname;
687
688        strcpy(s, typname);
689        s += strlen(s);
690        strcpy(s, " (*.");
691        s += strlen(s);
692        strcpy(s, imagetypes[i].ext);
693        s += strlen(s);
694        *(s++) = ')';
695        *(s++) = '|';
696        *(s++) = '*';
697        *(s++) = '.';
698        strcpy(s, imagetypes[i].ext);
699        s += strlen(s);
700        *(s++) = '|';
701    }
702    *(s++) = '|';
703   
704    t_buffer = tstring_from_utf8(szFilter);
705    if( !t_buffer )
706       return FALSE;
707
708   // convert a pipe-char delimited string into a NUL delimited string
709   t_filter = (LPTSTR) alloca((_tcslen(t_buffer) + 2) * sizeof(*t_filter));
710   for (i = 0; t_buffer[i] != '\0'; i++)
711      t_filter[i] = (t_buffer[i] != '|') ? t_buffer[i] : '\0';
712   t_filter[i++] = '\0';
713   t_filter[i++] = '\0';
714   free(t_buffer);
715
716    of.lStructSize = sizeof(of);
717    of.hwndOwner = GetMainWindow();
718    of.hInstance = NULL;
719    of.lpstrFilter = t_filter;
720    of.lpstrCustomFilter = NULL;
721    of.nMaxCustFilter = 0;
722    of.nFilterIndex = 1;
723    of.lpstrFile = filename;
724    of.nMaxFile = MAX_PATH;
725    of.lpstrFileTitle = NULL;
726    of.nMaxFileTitle = 0;
727    of.lpstrInitialDir = last_directory;
728    of.lpstrTitle = NULL;
729    of.Flags = OFN_EXPLORER | OFN_NOCHANGEDIR | OFN_PATHMUSTEXIST | OFN_HIDEREADONLY;
730    of.nFileOffset = 0;
731    of.nFileExtension = 0;
732    of.lpstrDefExt = TEXT("rom");
733    of.lCustData = 0;
734    of.lpfnHook = NULL;
735    of.lpTemplateName = NULL;
736
737    success = cfd(&of);
738    if (success)
739    {
740        //GetDirectory(filename,last_directory,sizeof(last_directory));
741    }
742   
743    return success;
744}
745
746
747
748/* Specify IO_COUNT for type if you want all types */
749static void SetupImageTypes(const struct IODevice *devices, mess_image_type *types, int count, BOOL bZip, int type)
750{
751    int num_extensions = 0;
752   int devindex;
753
754   memset(types, 0, sizeof(*types) * count);
755    count--;
756
757    if (bZip)
758   {
759      types[num_extensions].ext = "zip";
760      types[num_extensions].dev = NULL;
761      num_extensions++;
762    }
763
764   if (devices != NULL)
765   {
766      for (devindex = 0; devices[devindex].type < IO_COUNT; devindex++)
767      {
768         if (devices[devindex].type != IO_PRINTER)
769         {
770            const char *ext = devices[devindex].file_extensions;
771            if (ext)
772            {
773               while(*ext)
774               {
775                  if ((type == IO_COUNT) || (type == devices[devindex].type))
776                  {
777                     if (num_extensions < count)
778                     {
779                        types[num_extensions].dev = &devices[devindex];
780                        types[num_extensions].ext = ext;
781                        num_extensions++;
782                     }
783                  }
784                  ext += strlen(ext) + 1;
785               }
786            }
787         }
788      }
789   }
790}
791
792
793
794static void MessSetupDevice(common_file_dialog_proc cfd, int iDevice)
795{
796   TCHAR filename[MAX_PATH];
797   mess_image_type imagetypes[64];
798   int nGame;
799   HWND hwndList;
800   char* utf8_filename;
801   const struct IODevice *devices;
802
803   begin_resource_tracking();
804
805   hwndList = GetDlgItem(GetMainWindow(), IDC_LIST);
806   nGame = Picker_GetSelectedItem(hwndList);
807   devices = devices_allocate(drivers[nGame]);
808   SetupImageTypes(devices, imagetypes, sizeof(imagetypes) / sizeof(imagetypes[0]), TRUE, iDevice);
809
810   if (CommonFileImageDialog(last_directory, cfd, filename, imagetypes))
811   {
812      utf8_filename = utf8_from_tstring(filename);
813      if( !utf8_filename )
814         return;
815      // TODO - this should go against InternalSetSelectedSoftware()
816      SoftwarePicker_AddFile(GetDlgItem(GetMainWindow(), IDC_SWLIST), utf8_filename);
817      free(utf8_filename);
818   }
819
820   if (devices != NULL)
821      devices_free(devices);
822}
823
824
825
826static void MessOpenOtherSoftware(int iDevice)
827{
828   MessSetupDevice(GetOpenFileName, iDevice);
829}
830
831
832
833static void MessCreateDevice(int iDevice)
834{
835   MessSetupDevice(GetSaveFileName, iDevice);
836}
837
838
839
840static BOOL DevView_GetOpenFileName(HWND hwndDevView, const struct IODevice *dev, LPTSTR pszFilename, UINT nFilenameLength)
841{
842   BOOL bResult;
843   mess_image_type imagetypes[64];
844   HWND hwndList;
845   int gamenum;
846   const struct IODevice *devices;
847
848   hwndList = GetDlgItem(GetMainWindow(), IDC_LIST);
849   gamenum = Picker_GetSelectedItem(hwndList);
850   devices = devices_allocate(drivers[gamenum]);
851   SetupImageTypes(devices, imagetypes, sizeof(imagetypes) / sizeof(imagetypes[0]), TRUE, dev->type);
852   bResult = CommonFileImageDialog(last_directory, GetOpenFileName, pszFilename, imagetypes);
853
854   if (devices != NULL)
855      devices_free(devices);
856   return bResult;
857}
858
859
860
861static BOOL DevView_GetCreateFileName(HWND hwndDevView, const struct IODevice *dev, LPTSTR pszFilename, UINT nFilenameLength)
862{
863   BOOL bResult;
864   mess_image_type imagetypes[64];
865   HWND hwndList;
866   int gamenum;
867   const struct IODevice *devices;
868
869   hwndList = GetDlgItem(GetMainWindow(), IDC_LIST);
870   gamenum = Picker_GetSelectedItem(hwndList);
871   devices = devices_allocate(drivers[gamenum]);
872   SetupImageTypes(devices, imagetypes, sizeof(imagetypes) / sizeof(imagetypes[0]), TRUE, dev->type);
873   bResult = CommonFileImageDialog(last_directory, GetSaveFileName, pszFilename, imagetypes);
874
875   if (devices != NULL)
876      devices_free(devices);
877   return bResult;
878}
879
880
881
882static void DevView_SetSelectedSoftware(HWND hwndDevView, int nGame,
883   const struct IODevice *dev, int nID, LPCTSTR pszFilename)
884{
885   char* utf8_filename = utf8_from_tstring(pszFilename);
886   if( !utf8_filename )
887      return;
888   MessSpecifyImage(nGame, &dev->devclass, nID, utf8_filename);
889   MessRefreshPicker(nGame);
890   free(utf8_filename);
891}
892
893
894
895static LPCTSTR DevView_GetSelectedSoftware(HWND hwndDevView, int nDriverIndex,
896   const struct IODevice *dev, int nID, LPTSTR pszBuffer, UINT nBufferLength)
897{
898   LPCTSTR t_buffer = NULL;
899   TCHAR* t_s;
900   LPCSTR s = GetSelectedSoftware(nDriverIndex, &dev->devclass, nID);
901   
902   t_s = tstring_from_utf8(s);
903   if( !t_s )
904      return t_buffer;
905   
906   _sntprintf(pszBuffer, nBufferLength, TEXT("%s"), t_s);
907   free(t_s);   
908   t_buffer = pszBuffer;
909   
910   return t_buffer;
911}
912
913
914
915// ------------------------------------------------------------------------
916// Software List Class
917// ------------------------------------------------------------------------
918
919static int SoftwarePicker_GetItemImage(HWND hwndPicker, int nItem)
920{
921    int nType;
922    int nIcon;
923   int nGame;
924   const char *icon_name;
925   HWND hwndGamePicker;
926   HWND hwndSoftwarePicker;
927
928   hwndGamePicker = GetDlgItem(GetMainWindow(), IDC_LIST);
929   hwndSoftwarePicker = GetDlgItem(GetMainWindow(), IDC_SWLIST);
930   nGame = Picker_GetSelectedItem(hwndGamePicker);
931    nType = SoftwarePicker_GetImageType(hwndSoftwarePicker, nItem);
932    nIcon = GetMessIcon(nGame, nType);
933    if (!nIcon)
934   {
935      if (nType < 0)
936         nType = IO_BAD;
937      switch(nType)
938      {
939         case IO_UNKNOWN:
940            // Unknowns
941            nIcon = FindIconIndex(IDI_WIN_UNKNOWN);
942            break;
943
944         case IO_BAD:
945         case IO_ZIP:
946            // Bad files
947            nIcon = FindIconIndex(IDI_WIN_REDX);
948            break;
949
950         default:
951            icon_name = lookupdevice(nType)->icon_name;
952            if (!icon_name)
953               icon_name = device_typename(nType);
954            nIcon = FindIconIndexByName(icon_name);
955            if (nIcon < 0)
956               nIcon = FindIconIndexByName("unknown");
957            break;
958      }
959    }
960    return nIcon;
961}
962
963
964
965static void SoftwarePicker_LeavingItem(HWND hwndSoftwarePicker, int nItem)
966{
967   int nGame;
968   device_class devclass;
969   LPCSTR pszFullName;
970   HWND hwndList;
971
972   if (!s_bIgnoreSoftwarePickerNotifies)
973   {
974      hwndList = GetDlgItem(GetMainWindow(), IDC_LIST);
975      nGame = Picker_GetSelectedItem(hwndList);
976      devclass = SoftwarePicker_LookupDevice(hwndSoftwarePicker, nItem);
977      pszFullName = SoftwarePicker_LookupFilename(hwndSoftwarePicker, nItem);
978
979      MessRemoveImage(nGame, devclass, pszFullName);
980   }
981}
982
983
984
985static void SoftwarePicker_EnteringItem(HWND hwndSoftwarePicker, int nItem)
986{
987   LPCSTR pszFullName;
988   LPCSTR pszName;
989   LPSTR s;
990   int nGame;
991   device_class devclass;
992   HWND hwndList;
993
994   hwndList = GetDlgItem(GetMainWindow(), IDC_LIST);
995
996   if (!s_bIgnoreSoftwarePickerNotifies)
997   {
998      nGame = Picker_GetSelectedItem(hwndList);
999
1000      // Get the fullname and partialname for this file
1001      pszFullName = SoftwarePicker_LookupFilename(hwndSoftwarePicker, nItem);
1002      s = strchr(pszFullName, '\\');
1003      pszName = s ? s + 1 : pszFullName;
1004
1005      // Do the dirty work
1006      devclass = SoftwarePicker_LookupDevice(hwndSoftwarePicker, nItem);
1007      if (!devclass.gamedrv)
1008         return;
1009      MessSpecifyImage(nGame, &devclass, -1, pszFullName);
1010
1011      // Set up s_szSelecteItem, for the benefit of UpdateScreenShot()
1012      strncpyz(g_szSelectedItem, pszName, sizeof(g_szSelectedItem) / sizeof(g_szSelectedItem[0]));
1013      s = strrchr(g_szSelectedItem, '.');
1014      if (s)
1015         *s = '\0';
1016
1017      UpdateScreenShot();
1018   }
1019}
1020
1021
1022
1023// ------------------------------------------------------------------------
1024// Header context menu stuff
1025// ------------------------------------------------------------------------
1026
1027static HWND MyColumnDialogProc_hwndPicker;
1028static int *MyColumnDialogProc_order;
1029static int *MyColumnDialogProc_shown;
1030
1031static void MyGetRealColumnOrder(int *order)
1032{
1033   int i, nColumnCount;
1034   nColumnCount = Picker_GetColumnCount(MyColumnDialogProc_hwndPicker);
1035   for (i = 0; i < nColumnCount; i++)
1036      order[i] = Picker_GetRealColumnFromViewColumn(MyColumnDialogProc_hwndPicker, i);
1037}
1038
1039
1040
1041static void MyGetColumnInfo(int *order, int *shown)
1042{
1043   const struct PickerCallbacks *pCallbacks;
1044   pCallbacks = Picker_GetCallbacks(MyColumnDialogProc_hwndPicker);
1045   pCallbacks->pfnGetColumnOrder(order);
1046   pCallbacks->pfnGetColumnShown(shown);
1047}
1048
1049
1050
1051static void MySetColumnInfo(int *order, int *shown)
1052{
1053   const struct PickerCallbacks *pCallbacks;
1054   pCallbacks = Picker_GetCallbacks(MyColumnDialogProc_hwndPicker);
1055   pCallbacks->pfnSetColumnOrder(order);
1056   pCallbacks->pfnSetColumnShown(shown);
1057}
1058
1059
1060
1061static INT_PTR CALLBACK MyColumnDialogProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam)
1062{
1063   INT_PTR result = 0;
1064   int nColumnCount = Picker_GetColumnCount(MyColumnDialogProc_hwndPicker);
1065   LPCTSTR *ppszColumnNames = Picker_GetColumnNames(MyColumnDialogProc_hwndPicker);
1066   
1067   result = InternalColumnDialogProc(hDlg, Msg, wParam, lParam, nColumnCount,
1068      MyColumnDialogProc_shown, MyColumnDialogProc_order, ppszColumnNames,
1069      MyGetRealColumnOrder, MyGetColumnInfo, MySetColumnInfo);
1070     
1071   return result;
1072}
1073
1074
1075
1076static BOOL RunColumnDialog(HWND hwndPicker)
1077{
1078   BOOL bResult;
1079   int nColumnCount;
1080
1081   MyColumnDialogProc_hwndPicker = hwndPicker;
1082   nColumnCount = Picker_GetColumnCount(MyColumnDialogProc_hwndPicker);
1083
1084   MyColumnDialogProc_order = alloca(nColumnCount * sizeof(int));
1085   MyColumnDialogProc_shown = alloca(nColumnCount * sizeof(int));
1086   bResult = DialogBox(GetModuleHandle(NULL), MAKEINTRESOURCE(IDD_COLUMNS), GetMainWindow(), MyColumnDialogProc);
1087   return bResult;
1088}
1089
1090
1091
1092static void SoftwarePicker_OnHeaderContextMenu(POINT pt, int nColumn)
1093{
1094   HMENU hMenu;
1095   HMENU hMenuLoad;
1096   HWND hwndPicker;
1097   int nMenuItem;
1098
1099   hMenuLoad = LoadMenu(NULL, MAKEINTRESOURCE(IDR_CONTEXT_HEADER));
1100   hMenu = GetSubMenu(hMenuLoad, 0);
1101
1102   nMenuItem = (int) TrackPopupMenu(hMenu,
1103      TPM_LEFTALIGN | TPM_RIGHTBUTTON | TPM_RETURNCMD,
1104      pt.x,
1105      pt.y,
1106      0,
1107      GetMainWindow(),
1108      NULL);
1109
1110   DestroyMenu(hMenuLoad);
1111
1112   hwndPicker = GetDlgItem(GetMainWindow(), IDC_SWLIST);
1113
1114   switch(nMenuItem) {
1115   case ID_SORT_ASCENDING:
1116      SetMessSortReverse(FALSE);
1117      SetMessSortColumn(Picker_GetRealColumnFromViewColumn(hwndPicker, nColumn));
1118      Picker_Sort(hwndPicker);
1119      break;
1120
1121   case ID_SORT_DESCENDING:
1122      SetMessSortReverse(TRUE);
1123      SetMessSortColumn(Picker_GetRealColumnFromViewColumn(hwndPicker, nColumn));
1124      Picker_Sort(hwndPicker);
1125      break;
1126
1127   case ID_CUSTOMIZE_FIELDS:
1128      if (RunColumnDialog(hwndPicker))
1129         Picker_ResetColumnDisplay(hwndPicker);
1130      break;
1131   }
1132}
1133
1134
1135
1136// ------------------------------------------------------------------------
1137// MessCommand
1138// ------------------------------------------------------------------------
1139
1140BOOL MessCommand(HWND hwnd,int id, HWND hwndCtl, UINT codeNotify)
1141{
1142   switch (id) {
1143   case ID_MESS_OPEN_SOFTWARE:
1144      MessOpenOtherSoftware(IO_COUNT);
1145      break;
1146
1147   case ID_MESS_CREATE_SOFTWARE:
1148      MessCreateDevice(IO_COUNT);
1149      break;
1150
1151#ifdef MAME_DEBUG
1152   case ID_MESS_RUN_TESTS:
1153      MessTestsBegin();
1154      break;
1155#endif /* MAME_DEBUG */
1156   }
1157   return FALSE;
1158}
1159
1160
1161
1162// ------------------------------------------------------------------------
1163// Software Tab View
1164// ------------------------------------------------------------------------
1165
1166static LPCSTR s_tabs[] =
1167{
1168   "picker\0Picker",
1169   "devview\0Device View"
1170};
1171
1172
1173
1174static LPCSTR SoftwareTabView_GetTabShortName(int tab)
1175{
1176   return s_tabs[tab];
1177}
1178
1179
1180
1181static LPCSTR SoftwareTabView_GetTabLongName(int tab)
1182{
1183   return s_tabs[tab] + strlen(s_tabs[tab]) + 1;
1184}
1185
1186
1187
1188static void SoftwareTabView_OnSelectionChanged(void)
1189{
1190   int nTab;
1191   HWND hwndSoftwarePicker;
1192   HWND hwndSoftwareDevView;
1193
1194   hwndSoftwarePicker = GetDlgItem(GetMainWindow(), IDC_SWLIST);
1195   hwndSoftwareDevView = GetDlgItem(GetMainWindow(), IDC_SWDEVVIEW);
1196
1197   nTab = TabView_GetCurrentTab(GetDlgItem(GetMainWindow(), IDC_SWTAB));
1198
1199   switch(nTab)
1200   {
1201      case 0:
1202         ShowWindow(hwndSoftwarePicker, SW_SHOW);
1203         ShowWindow(hwndSoftwareDevView, SW_HIDE);
1204         break;
1205
1206      case 1:
1207         ShowWindow(hwndSoftwarePicker, SW_HIDE);
1208         ShowWindow(hwndSoftwareDevView, SW_SHOW);
1209         break;
1210   }
1211}
1212
1213
1214
1215static void SoftwareTabView_OnMoveSize(void)
1216{
1217   HWND hwndSoftwareTabView;
1218   HWND hwndSoftwarePicker;
1219   HWND hwndSoftwareDevView;
1220   RECT rMain, rSoftwareTabView, rClient, rTab;
1221
1222   hwndSoftwareTabView = GetDlgItem(GetMainWindow(), IDC_SWTAB);
1223   hwndSoftwarePicker = GetDlgItem(GetMainWindow(), IDC_SWLIST);
1224   hwndSoftwareDevView = GetDlgItem(GetMainWindow(), IDC_SWDEVVIEW);
1225
1226   GetWindowRect(hwndSoftwareTabView, &rSoftwareTabView);
1227   GetClientRect(GetMainWindow(), &rMain);
1228   ClientToScreen(GetMainWindow(), &((POINT *) &rMain)[0]);
1229   ClientToScreen(GetMainWindow(), &((POINT *) &rMain)[1]);
1230
1231   // Calculate rClient from rSoftwareTabView in terms of rMain coordinates
1232   rClient.left = rSoftwareTabView.left - rMain.left;
1233   rClient.top = rSoftwareTabView.top - rMain.top;
1234   rClient.right = rSoftwareTabView.right - rMain.left;
1235   rClient.bottom = rSoftwareTabView.bottom - rMain.top;
1236
1237   // If the tabs are visible, then make sure that the tab view's tabs are
1238   // not being covered up
1239   if (GetWindowLong(hwndSoftwareTabView, GWL_STYLE) & WS_VISIBLE)
1240   {
1241      TabCtrl_GetItemRect(hwndSoftwareTabView, 0, &rTab);
1242      rClient.top += rTab.bottom - rTab.top + 4;
1243   }
1244
1245   /* Now actually move the controls */
1246   MoveWindow(hwndSoftwarePicker, rClient.left, rClient.top,
1247      rClient.right - rClient.left, rClient.bottom - rClient.top,
1248      TRUE);
1249   MoveWindow(hwndSoftwareDevView, rClient.left, rClient.top,
1250      rClient.right - rClient.left, rClient.bottom - rClient.top,
1251      TRUE);
1252}
1253
1254
1255
1256static void SetupSoftwareTabView(void)
1257{
1258   struct TabViewOptions opts;
1259
1260   memset(&opts, 0, sizeof(opts));
1261   opts.pCallbacks = &s_softwareTabViewCallbacks;
1262   opts.nTabCount = sizeof(s_tabs) / sizeof(s_tabs[0]);
1263
1264   SetupTabView(GetDlgItem(GetMainWindow(), IDC_SWTAB), &opts);
1265}
1266
1267
1268
1269void MessCopyDeviceOption(core_options *opts, const game_driver *gamedrv, const device_class *devclass, int device_index, int global_index)
1270{
1271   const char *dev_name;
1272   const char *opt_value;
1273
1274   dev_name = device_instancename(devclass, device_index);
1275   opt_value = options_get_string(opts, dev_name);
1276   options_set_string(mame_options(), dev_name, opt_value, OPTION_PRIORITY_CMDLINE);
1277}
1278
1279
1280
1281// ------------------------------------------------------------------------
1282// Mess32 Diagnostics
1283// ------------------------------------------------------------------------
1284
1285#ifdef MAME_DEBUG
1286
1287static int s_nOriginalPick;
1288static UINT_PTR s_nTestingTimer;
1289static BOOL s_bInTimerProc;
1290
1291static void MessTestsColumns(void)
1292{
1293   int i, j;
1294   int oldshown[MESS_COLUMN_MAX];
1295   int shown[MESS_COLUMN_MAX];
1296
1297   GetMessColumnShown(oldshown);
1298
1299   shown[0] = 1;
1300   for (i = 0; i < (1<<(MESS_COLUMN_MAX-1)); i++)
1301   {
1302      for (j = 1; j < MESS_COLUMN_MAX; j++)
1303         shown[j] = (i & (1<<(j-1))) ? 1 : 0;
1304
1305      SetMessColumnShown(shown);
1306      Picker_ResetColumnDisplay(GetDlgItem(GetMainWindow(), IDC_SWLIST));
1307   }
1308
1309   SetMessColumnShown(oldshown);
1310   Picker_ResetColumnDisplay(GetDlgItem(GetMainWindow(), IDC_SWLIST));
1311}
1312
1313
1314
1315
1316static void CALLBACK MessTestsTimerProc(HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime)
1317{
1318   int nNewGame;
1319   HWND hwndList = GetDlgItem(GetMainWindow(), IDC_LIST);
1320
1321   // if either of the pickers have further idle work to do, or we are
1322   // already in this timerproc, do not do anything
1323   if (s_bInTimerProc || Picker_IsIdling(hwndList)
1324      || Picker_IsIdling(GetDlgItem(GetMainWindow(), IDC_SWLIST)))
1325      return;
1326   s_bInTimerProc = TRUE;
1327
1328   nNewGame = GetSelectedPick() + 1;
1329
1330   if (nNewGame >= driver_list_get_count(drivers))
1331   {
1332      /* We are done */
1333      Picker_SetSelectedPick(hwndList, s_nOriginalPick);
1334
1335      KillTimer(NULL, s_nTestingTimer);
1336      s_nTestingTimer = 0;
1337
1338      MessageBox(GetMainWindow(), TEXT("Tests successfully completed!"), TEXT(MAME32NAME), MB_OK);
1339   }
1340   else
1341   {
1342//      MessTestsFlex(GetDlgItem(GetMainWindow(), IDC_SWLIST), drivers[Picker_GetSelectedItem(hwndList)]);
1343      Picker_SetSelectedPick(hwndList, nNewGame);
1344   }
1345   s_bInTimerProc = FALSE;
1346}
1347
1348
1349
1350static void MessTestsBegin(void)
1351{
1352   int nOriginalPick;
1353   HWND hwndList = GetDlgItem(GetMainWindow(), IDC_LIST);
1354
1355   nOriginalPick = GetSelectedPick();
1356
1357   // If we are not currently running tests, set up the timer and keep track
1358   // of the original selected pick item
1359   if (!s_nTestingTimer)
1360   {
1361      s_nTestingTimer = SetTimer(NULL, 0, 50, MessTestsTimerProc);
1362      if (!s_nTestingTimer)
1363         return;
1364      s_nOriginalPick = nOriginalPick;
1365   }
1366
1367   MessTestsColumns();
1368
1369   if (nOriginalPick == 0)
1370      Picker_SetSelectedPick(hwndList, 1);
1371   Picker_SetSelectedPick(hwndList, 0);
1372}
1373
1374
1375
1376#endif // MAME_DEBUG
src/mess/osd/winui/layoutms.c
r0r996
1/***************************************************************************
2
3  layoutms.c
4
5  MESS specific TreeView definitions (and maybe more in the future)
6
7***************************************************************************/
8
9#define WIN32_LEAN_AND_MEAN
10#include <windows.h>
11#include <windowsx.h>
12#include <shellapi.h>
13#include <commctrl.h>
14#include <stdio.h>  /* for sprintf */
15#include <stdlib.h> /* For malloc and free */
16#include <string.h>
17
18#include "bitmask.h"
19#include "TreeView.h"
20#include "M32Util.h"
21#include "resource.h"
22#include "directories.h"
23#include "m32opts.h"
24#include "splitters.h"
25#include "help.h"
26#include "audit32.h"
27#include "screenshot.h"
28#include "win32ui.h"
29#include "properties.h"
30
31#include "ms32util.h"
32#include "resourcems.h"
33#include "propertiesms.h"
34
35static BOOL FilterAvailable(int driver_index);
36
37FOLDERDATA g_folderData[] =
38{
39   {"All Systems",     "allgames",          FOLDER_ALLGAMES,     IDI_FOLDER,            0,             0,            NULL,                       NULL,              TRUE },
40   {"Available",       "available",         FOLDER_AVAILABLE,    IDI_FOLDER_AVAILABLE,     F_AVAILABLE,   0,            NULL,                       FilterAvailable,              TRUE },
41#ifdef SHOW_UNAVAILABLE_FOLDER
42   {"Unavailable",     "unavailable",       FOLDER_UNAVAILABLE,  IDI_FOLDER_UNAVAILABLE,   0,             F_AVAILABLE,  NULL,                       FilterAvailable,              FALSE },
43#endif
44   {"Console",         "console",           FOLDER_CONSOLE,      IDI_FOLDER,            F_CONSOLE,     F_COMPUTER,   NULL,                       DriverIsComputer,  FALSE },
45   {"Computer",        "computer",          FOLDER_COMPUTER,     IDI_FOLDER,            F_COMPUTER,    F_CONSOLE,    NULL,                       DriverIsComputer,  TRUE },
46   {"Modified/Hacked", "modified",          FOLDER_MODIFIED,     IDI_FOLDER,            0,             0,            NULL,                       DriverIsModified,  TRUE },
47   {"Manufacturer",    "manufacturer",      FOLDER_MANUFACTURER, IDI_FOLDER_MANUFACTURER,  0,             0,            CreateManufacturerFolders },
48   {"Year",            "year",              FOLDER_YEAR,         IDI_FOLDER_YEAR,          0,             0,            CreateYearFolders },
49   {"Source",          "source",            FOLDER_SOURCE,       IDI_FOLDER_SOURCE,        0,             0,            CreateSourceFolders },
50   {"CPU",             "cpu",               FOLDER_CPU,          IDI_FOLDER,               0,             0,            CreateCPUFolders },
51   {"Sound",           "sound",             FOLDER_SND,          IDI_FOLDER,               0,             0,            CreateSoundFolders },
52   {"Imperfect",       "imperfect",         FOLDER_DEFICIENCY,   IDI_FOLDER,               0,             0,            CreateDeficiencyFolders },
53     {"Dumping Status",  "dumping",           FOLDER_DUMPING,      IDI_FOLDER,               0,             0,            CreateDumpingFolders },
54   {"Working",         "working",           FOLDER_WORKING,      IDI_WORKING,              F_WORKING,     F_NONWORKING, NULL,                       DriverIsBroken,    FALSE },
55   {"Not Working",     "nonworking",        FOLDER_NONWORKING,   IDI_NONWORKING,           F_NONWORKING,  F_WORKING,    NULL,                       DriverIsBroken,    TRUE },
56   {"Originals",       "originals",         FOLDER_ORIGINAL,     IDI_FOLDER,               F_ORIGINALS,   F_CLONES,     NULL,                       DriverIsClone,     FALSE },
57   {"Clones",          "clones",            FOLDER_CLONES,       IDI_FOLDER,               F_CLONES,      F_ORIGINALS,  NULL,                       DriverIsClone,     TRUE },
58   {"Raster",          "raster",            FOLDER_RASTER,       IDI_FOLDER,               F_RASTER,      F_VECTOR,     NULL,                       DriverIsVector,    FALSE },
59   {"Vector",          "vector",            FOLDER_VECTOR,       IDI_FOLDER,               F_VECTOR,      F_RASTER,     NULL,                       DriverIsVector,    TRUE },
60   {"Mouse",           "mouse",             FOLDER_MOUSE,        IDI_FOLDER,               0,             0,            NULL,                       DriverUsesMouse,   TRUE },
61   {"Trackball",       "trackball",         FOLDER_TRACKBALL,    IDI_FOLDER,               0,             0,            NULL,                       DriverUsesTrackball,   TRUE },
62   {"Stereo",          "stereo",            FOLDER_STEREO,       IDI_SOUND,                0,             0,            NULL,                       DriverIsStereo,    TRUE },
63   { NULL }
64};
65
66/* list of filter/control Id pairs */
67FILTER_ITEM g_filterList[] =
68{
69   { F_COMPUTER,     IDC_FILTER_COMPUTER,    DriverIsComputer, TRUE },
70   { F_CONSOLE,      IDC_FILTER_CONSOLE,     DriverIsComputer, FALSE },
71   { F_MODIFIED,     IDC_FILTER_MODIFIED,    DriverIsModified, TRUE },
72   { F_CLONES,       IDC_FILTER_CLONES,      DriverIsClone, TRUE },
73   { F_NONWORKING,   IDC_FILTER_NONWORKING,  DriverIsBroken, TRUE },
74   { F_UNAVAILABLE,  IDC_FILTER_UNAVAILABLE, FilterAvailable, FALSE },
75   { F_RASTER,       IDC_FILTER_RASTER,      DriverIsVector, FALSE },
76   { F_VECTOR,       IDC_FILTER_VECTOR,      DriverIsVector, TRUE },
77   { F_ORIGINALS,    IDC_FILTER_ORIGINALS,   DriverIsClone, FALSE },
78   { F_WORKING,      IDC_FILTER_WORKING,     DriverIsBroken, FALSE },
79   { F_AVAILABLE,    IDC_FILTER_AVAILABLE,   FilterAvailable, TRUE },
80   { 0 }
81};
82
83DIRECTORYINFO g_directoryInfo[] =
84{
85   { "ROMs",                  GetRomDirs,      SetRomDirs,      TRUE,  DIRDLG_ROMS },
86   { "Software",              GetSoftwareDirs, SetSoftwareDirs, TRUE,  DIRDLG_SOFTWARE },
87   { "Ini Files",             GetIniDir,       SetIniDir,       FALSE, DIRDLG_INI },
88   { "Hash",                  GetHashDirs,     SetHashDirs,     FALSE, 0 },
89   { "Config",                GetCfgDir,       SetCfgDir,       FALSE, DIRDLG_CFG },
90   { "Snapshots",             GetImgDir,       SetImgDir,       FALSE, DIRDLG_IMG },
91   { "Input files (*.inp)",   GetInpDir,       SetInpDir,       FALSE, DIRDLG_INP },
92   { "State",                 GetStateDir,     SetStateDir,     FALSE, 0 },
93   { "Artwork",               GetArtDir,       SetArtDir,       FALSE, 0 },
94   { "Memory Card",           GetMemcardDir,   SetMemcardDir,   FALSE, 0 },
95   { "Flyers",                GetFlyerDir,     SetFlyerDir,     FALSE, 0 },
96   { "Cabinets",              GetCabinetDir,   SetCabinetDir,   FALSE, 0 },
97   { "Marquees",              GetMarqueeDir,   SetMarqueeDir,   FALSE, 0 },
98   { "Titles",                GetTitlesDir,    SetTitlesDir,    FALSE, 0 },
99   { "Control Panels",        GetControlPanelDir,SetControlPanelDir, FALSE, 0 },
100   { "NVRAM",                 GetNvramDir,     SetNvramDir,     FALSE, 0 },
101   { "Controller Files",      GetCtrlrDir,     SetCtrlrDir,     FALSE, DIRDLG_CTRLR },
102   { "Hard Drive Difference", GetDiffDir,      SetDiffDir,      FALSE, 0 },
103   { "Icons",                 GetIconsDir,     SetIconsDir,     FALSE, 0 },
104   { "Background Images",     GetBgDir,        SetBgDir,        FALSE, 0 },
105   { "Comment Files",      GetCommentDir,     SetCommentDir,     FALSE, DIRDLG_COMMENT },
106   { NULL }
107};
108
109const SPLITTERINFO g_splitterInfo[] =
110{
111   { 0.2,   IDC_SPLITTER,   IDC_TREE,   IDC_LIST,      AdjustSplitter1Rect },
112   { 0.4,   IDC_SPLITTER2,   IDC_LIST,   IDC_SWLIST,      AdjustSplitter1Rect },
113//   { 0.6,   IDC_SPLITTER3,   IDC_SWLIST,   IDC_SSFRAME,   AdjustSplitter2Rect },
114   { 0.6,   IDC_SPLITTER3,   IDC_SWTAB,   IDC_SSFRAME,   AdjustSplitter2Rect },
115   { -1 }
116};
117
118const MAMEHELPINFO g_helpInfo[] =
119{
120   { ID_HELP_CONTENTS,      TRUE,   "mess.chm::/html/mess_overview.htm" },
121   { ID_HELP_RELEASE,      TRUE,   "mess.chm" },
122   { ID_HELP_WHATS_NEW,   TRUE,   "mess.chm::/messnew.txt" },
123   { -1 }
124};
125
126const PROPERTYSHEETINFO g_propSheets[] =
127{
128   { FALSE,   NULL,               IDD_PROP_GAME,         GamePropertiesDialogProc },
129   { FALSE,   NULL,               IDD_PROP_AUDIT,         GameAuditDialogProc },
130   { TRUE,      NULL,               IDD_PROP_DISPLAY,      GameOptionsProc },
131   { TRUE,      NULL,               IDD_PROP_ADVANCED,      GameOptionsProc },
132   { TRUE,      NULL,               IDD_PROP_SCREEN,      GameOptionsProc },
133   { TRUE,      NULL,               IDD_PROP_SOUND,         GameOptionsProc },
134   { TRUE,      NULL,               IDD_PROP_INPUT,         GameOptionsProc },
135   { TRUE,      NULL,               IDD_PROP_CONTROLLER,   GameOptionsProc },
136   { TRUE,      NULL,               IDD_PROP_MISC,         GameOptionsProc },
137   { FALSE,   NULL,               IDD_PROP_SOFTWARE,      GameMessOptionsProc },
138   { FALSE,   PropSheetFilter_Config,   IDD_PROP_CONFIGURATION,   GameMessOptionsProc },
139   { TRUE,      PropSheetFilter_Vector,   IDD_PROP_VECTOR,      GameOptionsProc },
140   { FALSE }
141};
142
143const ICONDATA g_iconData[] =
144{
145   { IDI_WIN_NOROMS,         "noroms" },
146   { IDI_WIN_ROMS,            "roms" },
147   { IDI_WIN_UNKNOWN,         "unknown" },
148   { IDI_WIN_CLONE,         "clone" },
149   { IDI_WIN_REDX,            "warning" },
150   { IDI_WIN_NOROMSNEEDED,      "noromsneeded" },
151   { IDI_WIN_MISSINGOPTROM,   "missingoptrom" },
152   { IDI_WIN_FLOP,            "floppy" },
153   { IDI_WIN_CASS,            "cassette" },
154   { IDI_WIN_SERL,            "serial" },
155   { IDI_WIN_SNAP,            "snapshot" },
156   { IDI_WIN_PRIN,            "printer" },
157   { IDI_WIN_HARD,            "hard" },
158   { 0 }
159};
160
161const TCHAR g_szPlayGameString[] = TEXT("&Run %s");
162const char g_szGameCountString[] = "%d systems";
163const char g_szHistoryFileName[] = "sysinfo.dat";
164const char g_szMameInfoFileName[] = "messinfo.dat";
165
166static BOOL FilterAvailable(int driver_index)
167{
168   return !DriverUsesRoms(driver_index) || IsAuditResultYes(GetRomAuditResults(driver_index));
169}
src/mess/osd/winui/devview.h
r0r996
1#ifndef DEVVIEW_H
2#define DEVVIEW_H
3
4struct DevViewCallbacks
5{
6   BOOL (*pfnGetOpenFileName)(HWND hwndDevView, const struct IODevice *dev, LPTSTR pszFilename, UINT nFilenameLength);
7   BOOL (*pfnGetCreateFileName)(HWND hwndDevView, const struct IODevice *dev, LPTSTR pszFilename, UINT nFilenameLength);
8   void (*pfnSetSelectedSoftware)(HWND hwndDevView, int nGame, const struct IODevice *dev, int nID, LPCTSTR pszFilename);
9   LPCTSTR (*pfnGetSelectedSoftware)(HWND hwndDevView, int nGame, const struct IODevice *dev, int nID, LPTSTR pszBuffer, UINT nBufferLength);
10};
11
12void DevView_SetCallbacks(HWND hwndDevView, const struct DevViewCallbacks *pCallbacks);
13BOOL DevView_SetDriver(HWND hwndDevView, int nGame);
14void DevView_RegisterClass(void);
15void DevView_Refresh(HWND hwndDevView);
16
17#endif // DEVVIEW_H
src/mess/osd/winui/mess32ui.h
r0r996
1#ifndef __MESS32UI_H__
2#define __MESS32UI_H__
3
4#include "driver.h"
5#include "resourcems.h"
6#include "devview.h"
7#include "uitext.h"
8#include "options.h"
9
10extern char g_szSelectedItem[MAX_PATH];
11
12void InitMessPicker(void);
13void MessUpdateSoftwareList(void);
14void MyFillSoftwareList(int nGame, BOOL bForce);
15BOOL MessCommand(HWND hwnd,int id, HWND hwndCtl, UINT codeNotify);
16void MessReadMountedSoftware(int nGame);
17BOOL CreateMessIcons(void);
18BOOL MessApproveImageList(HWND hParent, int nDriver);
19
20void MessCopyDeviceOption(core_options *opts, const game_driver *gamedrv, const device_class *devclass, int device_index, int global_index);
21
22#endif // __MESS32UI_H__
src/mess/osd/winui/ms32util.c
r0r996
1#include "driver.h"
2#include "device.h"
3#include "ms32util.h"
4
5BOOL DriverIsComputer(int driver_index)
6{
7   return (drivers[driver_index]->flags & GAME_COMPUTER) != 0;
8}
9
10BOOL DriverIsModified(int driver_index)
11{
12   return (drivers[driver_index]->flags & GAME_COMPUTER_MODIFIED) != 0;
13}
14
15BOOL DriverUsesMouse(int driver_index)
16{
17   const input_port_entry *input_ports;
18   BOOL retval = FALSE;
19
20   if (drivers[driver_index]->ipt)
21   {
22      begin_resource_tracking();
23      input_ports = input_port_allocate(drivers[driver_index]->ipt, NULL);
24
25      while (input_ports->type != IPT_END)
26      {
27         if (input_ports->type == IPT_MOUSE_X || input_ports->type == IPT_MOUSE_Y)
28         {
29            retval = TRUE;
30            break;
31         }
32         input_ports++;
33      }
34
35      end_resource_tracking();
36   }
37
38   return retval;
39}
40
41BOOL DriverHasDevice(const game_driver *gamedrv, iodevice_t type)
42{
43   BOOL b;
44   const struct IODevice *devices;
45
46   devices = devices_allocate(gamedrv);
47   b = device_find(devices, IO_PRINTER) ? TRUE : FALSE;
48   devices_free(devices);
49   return b;
50}
51
52
src/mess/osd/winui/ms32util.h
r0r996
1#ifndef MS32UTIL_H
2#define MS32UTIL_H
3
4#include <windows.h>
5
6BOOL DriverIsComputer(int driver_index);
7BOOL DriverIsModified(int driver_index);
8BOOL DriverUsesMouse(int driver_index);
9BOOL DriverHasDevice(const game_driver *gamedrv, iodevice_t type);
10
11#endif /* MS32UTIL_H */
12
src/mess/osd/winui/softwarepicker.c
r0r996
1//============================================================
2//
3//   softwarepicker.c - MESS's software picker
4//
5//============================================================
6
7#define WIN32_LEAN_AND_MEAN
8#include <assert.h>
9#include <string.h>
10#include <windows.h>
11#include <shellapi.h>
12#include <commctrl.h>
13#include <commdlg.h>
14#include <wingdi.h>
15#include <winuser.h>
16#include <tchar.h>
17#include <ctype.h>
18
19#include "driver.h"
20#include "unzip.h"
21#include "strconv.h"
22#include "hashfile.h"
23#include "picker.h"
24#include "screenshot.h"
25#include "bitmask.h"
26#include "mame32.h"
27#include "resourcems.h"
28#include "m32opts.h"
29#include "softwarepicker.h"
30#include "m32util.h"
31
32
33
34struct FileInfo
35{
36   device_class devclass;
37
38   // hash information
39   char szHash[HASH_BUF_SIZE];
40   BOOL bHashRealized;
41   const struct hash_info *pHashInfo;
42
43   LPCSTR pszZipEntryName;
44   LPCSTR pszSubName;
45   char szFilename[1];
46};
47
48struct DirectorySearchInfo
49{
50   struct DirectorySearchInfo *pNext;
51   HANDLE hFind;
52   WIN32_FIND_DATA fd;
53   char szDirectory[1];
54};
55
56struct SoftwarePickerInfo
57{
58   WNDPROC pfnOldWndProc;
59   struct FileInfo **ppIndex;
60   int nIndexLength;
61   int nHashesRealized;
62   int nCurrentPosition;
63   struct DirectorySearchInfo *pFirstSearchInfo;
64   struct DirectorySearchInfo *pLastSearchInfo;
65   const game_driver *pDriver;
66   hash_file *pHashFile;
67   void (*pfnErrorProc)(const char *message);
68};
69
70
71
72static const TCHAR s_szSoftwarePickerProp[] = TEXT("SWPICKER");
73
74
75
76static LPCSTR NormalizePath(LPCSTR pszPath, LPSTR pszBuffer, size_t nBufferSize)
77{
78   BOOL bChanged = FALSE;
79   LPSTR s;
80   int i, j;
81
82   if (pszPath[0] == '\\')
83   {
84      win_get_current_directory_utf8(nBufferSize, pszBuffer);
85      pszBuffer[2] = '\0';
86      bChanged = TRUE;
87   }
88   else if (!_istalpha(pszPath[0]) || (pszPath[1] != ':'))
89   {
90      win_get_current_directory_utf8(nBufferSize, pszBuffer);
91      bChanged = TRUE;
92   }
93
94   if (bChanged)
95   {
96      s = (LPSTR) alloca(strlen(pszBuffer) + 1);
97      strcpy(s, pszBuffer);
98      snprintf(pszBuffer, nBufferSize, "%s\\%s", s, pszPath);
99      pszPath = pszBuffer;
100
101      // Remove double path separators
102      i = 0;
103      j = 0;
104      while(pszBuffer[i])
105      {
106         while ((pszBuffer[i] == '\\') && (pszBuffer[i+1] == '\\'))
107            i++;
108         pszBuffer[j++] = pszBuffer[i++];
109      }
110      pszBuffer[j] = '\0';
111   }
112   return pszPath;
113}
114
115
116
117static struct SoftwarePickerInfo *GetSoftwarePickerInfo(HWND hwndPicker)
118{
119   HANDLE h;
120   h = GetProp(hwndPicker, s_szSoftwarePickerProp);
121   assert(h);
122   return (struct SoftwarePickerInfo *) h;
123}
124
125
126
127LPCSTR SoftwarePicker_LookupFilename(HWND hwndPicker, int nIndex)
128{
129   struct SoftwarePickerInfo *pPickerInfo;
130   pPickerInfo = GetSoftwarePickerInfo(hwndPicker);
131   if ((nIndex < 0) || (nIndex >= pPickerInfo->nIndexLength))
132      return NULL;
133   return pPickerInfo->ppIndex[nIndex]->szFilename;
134}
135
136
137
138device_class SoftwarePicker_LookupDevice(HWND hwndPicker, int nIndex)
139{
140   struct SoftwarePickerInfo *pPickerInfo;
141   pPickerInfo = GetSoftwarePickerInfo(hwndPicker);
142   if ((nIndex < 0) || (nIndex >= pPickerInfo->nIndexLength))
143   {
144      device_class dummy;
145      memset(&dummy, 0, sizeof(dummy));
146      return dummy;
147   }
148   return pPickerInfo->ppIndex[nIndex]->devclass;
149}
150
151
152
153int SoftwarePicker_LookupIndex(HWND hwndPicker, LPCSTR pszFilename)
154{
155   struct SoftwarePickerInfo *pPickerInfo;
156   int i;
157
158   pPickerInfo = GetSoftwarePickerInfo(hwndPicker);
159   for (i = 0; i < pPickerInfo->nIndexLength; i++)
160   {
161      if (!mame_stricmp(pPickerInfo->ppIndex[i]->szFilename, pszFilename))
162         return i;
163   }
164   return -1;
165}
166
167
168
169iodevice_t SoftwarePicker_GetImageType(HWND hwndPicker, int nIndex)
170{
171   struct SoftwarePickerInfo *pPickerInfo;
172   const device_class *devclass;
173
174   pPickerInfo = GetSoftwarePickerInfo(hwndPicker);
175   if ((nIndex < 0) || (nIndex >= pPickerInfo->nIndexLength))
176      return -1;
177
178   devclass = &pPickerInfo->ppIndex[nIndex]->devclass;
179   if (!devclass->gamedrv)
180      return -1;
181   return (iodevice_t) (int) device_get_info_int(devclass, DEVINFO_INT_TYPE);
182}
183
184
185
186void SoftwarePicker_SetDriver(HWND hwndPicker, const game_driver *pDriver)
187{
188   struct SoftwarePickerInfo *pPickerInfo;
189   int i;
190
191   pPickerInfo = GetSoftwarePickerInfo(hwndPicker);
192
193   if (pPickerInfo->pDriver != pDriver)
194   {
195      if (pPickerInfo->pHashFile)
196      {
197         hashfile_close(pPickerInfo->pHashFile);
198         pPickerInfo->pHashFile = NULL;
199
200         for (i = 0; i < pPickerInfo->nIndexLength; i++)
201         {
202            pPickerInfo->ppIndex[i]->pHashInfo = NULL;
203            pPickerInfo->ppIndex[i]->bHashRealized = FALSE;
204         }
205         pPickerInfo->nHashesRealized = 0;
206      }
207     
208
209      pPickerInfo->pDriver = pDriver;
210     
211      if (pDriver)
212      {
213         while(pDriver && !pPickerInfo->pHashFile)
214         {
215            pPickerInfo->pHashFile = hashfile_open_options(Mame32Global(), pDriver->name, TRUE, pPickerInfo->pfnErrorProc);
216            pDriver = mess_next_compatible_driver(pDriver);
217         }
218      }
219   }
220}
221
222
223
224void SoftwarePicker_SetErrorProc(HWND hwndPicker, void (*pfnErrorProc)(const char *message))
225{
226   struct SoftwarePickerInfo *pPickerInfo;
227   pPickerInfo = GetSoftwarePickerInfo(hwndPicker);
228   pPickerInfo->pfnErrorProc = pfnErrorProc;
229}
230
231
232
233static void ComputeFileHash(struct SoftwarePickerInfo *pPickerInfo,
234   struct FileInfo *pFileInfo, const unsigned char *pBuffer, unsigned int nLength)
235{
236   unsigned int nFunctions;
237   iodevice_t type;
238   device_partialhash_handler partialhash;
239
240   type = (iodevice_t) (int) device_get_info_int(&pFileInfo->devclass, DEVINFO_INT_TYPE);
241   partialhash = (device_partialhash_handler) device_get_info_fct(&pFileInfo->devclass, DEVINFO_PTR_PARTIAL_HASH);
242
243   nFunctions = hashfile_functions_used(pPickerInfo->pHashFile, type);
244
245   if (partialhash)
246   {
247      partialhash(pFileInfo->szHash, pBuffer, nLength, nFunctions);
248   }
249   else
250   {
251      hash_compute(pFileInfo->szHash, pBuffer, nLength, nFunctions);
252   }
253}
254
255
256
257static BOOL SoftwarePicker_CalculateHash(HWND hwndPicker, int nIndex)
258{
259   struct SoftwarePickerInfo *pPickerInfo;
260   struct FileInfo *pFileInfo;
261   LPSTR pszZipName;
262   BOOL rc = FALSE;
263   unsigned char *pBuffer;
264   unsigned int nLength;
265   HANDLE hFile, hFileMapping;
266   LVFINDINFO lvfi;
267
268   pPickerInfo = GetSoftwarePickerInfo(hwndPicker);
269   assert((nIndex >= 0) && (nIndex < pPickerInfo->nIndexLength));
270   pFileInfo = pPickerInfo->ppIndex[nIndex];
271
272   if (pFileInfo->pszZipEntryName)
273   {
274      // this is in a ZIP file
275      zip_file *zip;
276      zip_error ziperr;
277      const zip_file_header *zipent;
278
279      // open the ZIP file
280      nLength = pFileInfo->pszZipEntryName - pFileInfo->szFilename;
281      pszZipName = (LPSTR) alloca(nLength);
282      memcpy(pszZipName, pFileInfo->szFilename, nLength);
283      pszZipName[nLength - 1] = '\0';
284
285      // get the entry name
286      ziperr = zip_file_open(pszZipName, &zip);
287      if (ziperr == ZIPERR_NONE)
288      {
289         zipent = zip_file_first_file(zip);
290         while(!rc && zipent)
291         {
292            if (!mame_stricmp(zipent->filename, pFileInfo->pszZipEntryName))
293            {
294               pBuffer = malloc(zipent->uncompressed_length);
295               if (pBuffer)
296               {
297                  ziperr = zip_file_decompress(zip, pBuffer, zipent->uncompressed_length);
298                  if (ziperr == ZIPERR_NONE)
299                  {
300                     ComputeFileHash(pPickerInfo, pFileInfo, pBuffer, zipent->uncompressed_length);
301                     rc = TRUE;
302                  }
303                  free(pBuffer);
304               }
305            }
306            zipent = zip_file_next_file(zip);
307         }
308         zip_file_close(zip);
309      }
310   }
311   else
312   {
313      // plain open file; map it into memory and calculate the hash
314      hFile = win_create_file_utf8(pFileInfo->szFilename, GENERIC_READ, FILE_SHARE_READ, NULL,
315         OPEN_EXISTING, 0, NULL);
316      if (hFile != INVALID_HANDLE_VALUE)
317      {
318         nLength = GetFileSize(hFile, NULL);
319         hFileMapping = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
320         if (hFileMapping)
321         {
322            pBuffer = MapViewOfFile(hFileMapping, FILE_MAP_READ, 0, 0, 0);
323            if (pBuffer)
324            {
325               ComputeFileHash(pPickerInfo, pFileInfo, pBuffer, nLength);
326               UnmapViewOfFile(pBuffer);
327               rc = TRUE;
328            }
329            CloseHandle(hFileMapping);
330         }
331         CloseHandle(hFile);
332      }
333   }
334
335   if (rc)
336   {
337      memset(&lvfi, 0, sizeof(lvfi));
338      lvfi.flags = LVFI_PARAM;
339      lvfi.lParam = nIndex;
340      nIndex = ListView_FindItem(hwndPicker, -1, &lvfi);
341      if (nIndex > 0)
342         ListView_RedrawItems(hwndPicker, nIndex, nIndex);
343   }
344
345   return rc;
346}
347
348
349
350static void SoftwarePicker_RealizeHash(HWND hwndPicker, int nIndex)
351{
352   struct SoftwarePickerInfo *pPickerInfo;
353   struct FileInfo *pFileInfo;
354   unsigned int nHashFunctionsUsed = 0;
355   unsigned int nCalculatedHashes = 0;
356   iodevice_t type;
357
358   pPickerInfo = GetSoftwarePickerInfo(hwndPicker);
359   assert((nIndex >= 0) && (nIndex < pPickerInfo->nIndexLength));
360   pFileInfo = pPickerInfo->ppIndex[nIndex];
361
362   // Determine which hash functions we need to use for this file, and which hashes
363   // have already been calculated
364   if ((pPickerInfo->pHashFile != NULL) && (pFileInfo->devclass.get_info != NULL))
365   {
366      type = (iodevice_t) (int) device_get_info_int(&pFileInfo->devclass, DEVINFO_INT_TYPE);
367      if (type < IO_COUNT)
368           nHashFunctionsUsed = hashfile_functions_used(pPickerInfo->pHashFile, type);
369      nCalculatedHashes = hash_data_used_functions(pFileInfo->szHash);
370   }
371
372   // Did we fully compute all hashes?
373   if ((nHashFunctionsUsed & ~nCalculatedHashes) == 0)
374   {
375      // We have calculated all hashs for this file; mark it as realized
376      pPickerInfo->ppIndex[nIndex]->bHashRealized = TRUE;
377      pPickerInfo->nHashesRealized++;
378
379      if (pPickerInfo->pHashFile)
380      {
381         pPickerInfo->ppIndex[nIndex]->pHashInfo = hashfile_lookup(pPickerInfo->pHashFile,
382            pPickerInfo->ppIndex[nIndex]->szHash);
383      }
384   }
385}
386
387
388
389static BOOL SoftwarePicker_AddFileEntry(HWND hwndPicker, LPCSTR pszFilename,
390   UINT nZipEntryNameLength, UINT32 nCrc, BOOL bForce)
391{
392   struct SoftwarePickerInfo *pPickerInfo;
393   struct FileInfo **ppNewIndex;
394   struct FileInfo *pInfo;
395   int nIndex, nSize, devindex;
396   LPCSTR pszExtension = NULL, s;
397   const struct IODevice *devices = NULL;
398   device_class devclass = {0,};
399
400   // first check to see if it is already here
401   if (SoftwarePicker_LookupIndex(hwndPicker, pszFilename) >= 0)
402      return TRUE;
403
404   pPickerInfo = GetSoftwarePickerInfo(hwndPicker);
405
406   // look up the device
407   if (strrchr(pszFilename, '.'))
408      pszExtension = strrchr(pszFilename, '.');
409   if (pszExtension && pPickerInfo->pDriver)
410   {
411      pszExtension++;
412
413      devices = devices_allocate(pPickerInfo->pDriver);
414      if (devices != NULL)
415      {
416         for (devindex = 0; devices[devindex].type < IO_COUNT; devindex++)
417         {
418            s = devices[devindex].file_extensions;
419            if (s)
420            {
421               while(*s && mame_stricmp(pszExtension, s))
422                  s += strlen(s) + 1;
423               if (*s)
424               {
425                  devclass = devices[devindex].devclass;
426                  break;
427               }
428            }
429         }
430         devices_free(devices);
431      }
432   }
433
434   // no device?  cop out unless bForce is on
435   if (!devclass.gamedrv && !bForce)
436      return TRUE;
437
438   // create the FileInfo structure
439   nSize = sizeof(struct FileInfo) + strlen(pszFilename);
440   pInfo = (struct FileInfo *) malloc(nSize);
441   if (!pInfo)
442      goto error;
443   memset(pInfo, 0, nSize);
444
445   // copy the filename
446   strcpy(pInfo->szFilename, pszFilename);
447   
448   // set up device and CRC, if specified
449   pInfo->devclass = devclass;
450   if (devclass.gamedrv && device_get_info_fct(&devclass, DEVINFO_PTR_PARTIAL_HASH))
451      nCrc = 0;
452   if (nCrc != 0)
453      snprintf(pInfo->szHash, sizeof(pInfo->szHash) / sizeof(pInfo->szHash[0]), "c:%08x#", nCrc);
454
455   // set up zip entry name length, if specified
456   if (nZipEntryNameLength > 0)
457      pInfo->pszZipEntryName = pInfo->szFilename + strlen(pInfo->szFilename) - nZipEntryNameLength;
458
459   // calculate the subname
460   pInfo->pszSubName = strrchr(pInfo->szFilename, '\\');
461   if (pInfo->pszSubName)
462      pInfo->pszSubName++;
463   else
464      pInfo->pszSubName = pInfo->szFilename;
465
466   ppNewIndex = realloc(pPickerInfo->ppIndex, (pPickerInfo->nIndexLength + 1) * sizeof(*pPickerInfo->ppIndex));
467   if (!ppNewIndex)
468      goto error;
469
470   nIndex = pPickerInfo->nIndexLength++;
471   pPickerInfo->ppIndex = ppNewIndex;
472   pPickerInfo->ppIndex[nIndex] = pInfo;
473
474   // Realize the hash
475   SoftwarePicker_RealizeHash(hwndPicker, nIndex);
476
477   // Actually insert the item into the picker
478   Picker_InsertItemSorted(hwndPicker, nIndex);
479   return TRUE;
480
481error:
482   if (pInfo)
483      free(pInfo);
484   return FALSE;
485}
486
487
488
489static BOOL SoftwarePicker_AddZipEntFile(HWND hwndPicker, LPCSTR pszZipPath,
490   BOOL bForce, zip_file *pZip, const zip_file_header *pZipEnt)
491{
492   LPSTR s;
493   LPCSTR temp = pZipEnt->filename;
494   int nLength;
495   int nZipEntryNameLength;
496
497   // special case; skip first two characters if they are './'
498   if ((pZipEnt->filename[0] == '.') && (pZipEnt->filename[1] == '/'))
499   {
500      while(*(++temp) == '/')
501         ;
502   }
503
504   nZipEntryNameLength = strlen(pZipEnt->filename);
505   nLength = strlen(pszZipPath) + 1 + nZipEntryNameLength + 1;
506   s = (LPSTR) alloca(nLength);
507   snprintf(s, nLength, "%s\\%s", pszZipPath, pZipEnt->filename);
508
509   return SoftwarePicker_AddFileEntry(hwndPicker, s,
510      nZipEntryNameLength, pZipEnt->crc, bForce);
511}
512
513static BOOL SoftwarePicker_InternalAddFile(HWND hwndPicker, LPCSTR pszFilename,
514   BOOL bForce)
515{
516   LPCSTR s;
517   BOOL rc = TRUE;
518   zip_error ziperr;
519   zip_file *pZip;
520   const zip_file_header *pZipEnt;
521
522   s = strrchr(pszFilename, '.');
523   if (s && !mame_stricmp(s, ".zip"))
524   {
525      ziperr = zip_file_open(pszFilename, &pZip);
526      if (ziperr  == ZIPERR_NONE)
527      {
528         pZipEnt = zip_file_first_file(pZip);
529         while(rc && pZipEnt)
530         {
531            rc = SoftwarePicker_AddZipEntFile(hwndPicker, pszFilename,
532               bForce, pZip, pZipEnt);
533            pZipEnt = zip_file_next_file(pZip);
534         }
535         zip_file_close(pZip);
536      }
537   }
538   else
539   {
540      rc = SoftwarePicker_AddFileEntry(hwndPicker, pszFilename, 0, 0, bForce);
541   }
542   return rc;
543}
544
545
546
547BOOL SoftwarePicker_AddFile(HWND hwndPicker, LPCSTR pszFilename)
548{
549   char szBuffer[MAX_PATH];
550
551   Picker_ResetIdle(hwndPicker);
552   pszFilename = NormalizePath(pszFilename, szBuffer, sizeof(szBuffer)
553      / sizeof(szBuffer[0]));
554
555   return SoftwarePicker_InternalAddFile(hwndPicker, pszFilename, TRUE);
556}
557
558
559
560BOOL SoftwarePicker_AddDirectory(HWND hwndPicker, LPCSTR pszDirectory)
561{
562   struct SoftwarePickerInfo *pPickerInfo;
563   struct DirectorySearchInfo *pSearchInfo;
564   struct DirectorySearchInfo **ppLast;
565   size_t nSearchInfoSize;
566   char szBuffer[MAX_PATH];
567
568   pszDirectory = NormalizePath(pszDirectory, szBuffer, sizeof(szBuffer)
569      / sizeof(szBuffer[0]));
570
571   Picker_ResetIdle(hwndPicker);
572   pPickerInfo = GetSoftwarePickerInfo(hwndPicker);
573
574   nSearchInfoSize = sizeof(struct DirectorySearchInfo) + strlen(pszDirectory);
575   pSearchInfo = malloc(nSearchInfoSize);
576   if (!pSearchInfo)
577      return FALSE;
578   memset(pSearchInfo, 0, nSearchInfoSize);
579   pSearchInfo->hFind = INVALID_HANDLE_VALUE;
580
581   strcpy(pSearchInfo->szDirectory, pszDirectory);
582
583   // insert into linked list
584   if (pPickerInfo->pLastSearchInfo)
585      ppLast = &pPickerInfo->pLastSearchInfo->pNext;
586   else
587      ppLast = &pPickerInfo->pFirstSearchInfo;
588   *ppLast = pSearchInfo;
589   pPickerInfo->pLastSearchInfo = pSearchInfo;
590   return TRUE;
591}
592
593
594
595static void SoftwarePicker_FreeSearchInfo(struct DirectorySearchInfo *pSearchInfo)
596{
597   if (pSearchInfo->hFind != INVALID_HANDLE_VALUE)
598      FindClose(pSearchInfo->hFind);
599   free(pSearchInfo);
600}
601
602
603
604static void SoftwarePicker_InternalClear(struct SoftwarePickerInfo *pPickerInfo)
605{
606   struct DirectorySearchInfo *p;
607   int i;
608
609   for (i = 0; i < pPickerInfo->nIndexLength; i++)
610      free(pPickerInfo->ppIndex[i]);
611
612   while(pPickerInfo->pFirstSearchInfo)
613   {
614      p = pPickerInfo->pFirstSearchInfo->pNext;
615      SoftwarePicker_FreeSearchInfo(pPickerInfo->pFirstSearchInfo);
616      pPickerInfo->pFirstSearchInfo = p;
617   }
618
619   pPickerInfo->ppIndex = NULL;
620   pPickerInfo->nIndexLength = 0;
621   pPickerInfo->nCurrentPosition = 0;
622   pPickerInfo->pLastSearchInfo = NULL;
623}
624
625
626
627void SoftwarePicker_Clear(HWND hwndPicker)
628{
629   struct SoftwarePickerInfo *pPickerInfo;
630   pPickerInfo = GetSoftwarePickerInfo(hwndPicker);
631   SoftwarePicker_InternalClear(pPickerInfo);
632   ListView_DeleteAllItems(hwndPicker);
633}
634
635
636
637static BOOL SoftwarePicker_AddEntry(HWND hwndPicker,
638   struct DirectorySearchInfo *pSearchInfo)
639{
640   struct SoftwarePickerInfo *pPickerInfo;
641   LPSTR pszFilename;
642   BOOL rc;
643   char* utf8_FileName;
644
645   pPickerInfo = GetSoftwarePickerInfo(hwndPicker);
646   
647   utf8_FileName = utf8_from_tstring(pSearchInfo->fd.cFileName);
648   if( !utf8_FileName )
649      return FALSE;
650
651   if (!strcmp(utf8_FileName, ".") || !strcmp(utf8_FileName, "..")) {
652      free(utf8_FileName);
653      return TRUE;
654   }
655
656   pszFilename = alloca(strlen(pSearchInfo->szDirectory) + 1 + strlen(utf8_FileName) + 1);
657   strcpy(pszFilename, pSearchInfo->szDirectory);
658   strcat(pszFilename, "\\");
659   strcat(pszFilename, utf8_FileName);
660
661   if (pSearchInfo->fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
662      rc = SoftwarePicker_AddDirectory(hwndPicker, pszFilename);
663   else
664      rc = SoftwarePicker_InternalAddFile(hwndPicker, pszFilename, FALSE);
665     
666      free(utf8_FileName);
667   return rc;
668}
669
670
671
672BOOL SoftwarePicker_Idle(HWND hwndPicker)
673{
674   struct SoftwarePickerInfo *pPickerInfo;
675   struct FileInfo *pFileInfo;
676   static const char szWildcards[] = "\\*.*";
677   struct DirectorySearchInfo *pSearchInfo;
678   LPSTR pszFilter;
679   BOOL bSuccess;
680   int nCount;
681   BOOL bDone = FALSE;
682   iodevice_t type;
683
684   pPickerInfo = GetSoftwarePickerInfo(hwndPicker);
685
686   pSearchInfo = pPickerInfo->pFirstSearchInfo;
687   if (pSearchInfo)
688   {
689      // searching through directories
690      if (pSearchInfo->hFind != INVALID_HANDLE_VALUE)
691      {
692         bSuccess = FindNextFile(pSearchInfo->hFind, &pSearchInfo->fd);
693      }
694      else
695      {
696         pszFilter = alloca(strlen(pSearchInfo->szDirectory) + strlen(szWildcards) + 1);
697         strcpy(pszFilter, pSearchInfo->szDirectory);
698         strcat(pszFilter, szWildcards);
699         pSearchInfo->hFind = win_find_first_file_utf8(pszFilter, &pSearchInfo->fd);
700         bSuccess = pSearchInfo->hFind != INVALID_HANDLE_VALUE;
701      }
702
703      if (bSuccess)
704      {
705         SoftwarePicker_AddEntry(hwndPicker, pSearchInfo);
706      }
707      else
708      {
709         pPickerInfo->pFirstSearchInfo = pSearchInfo->pNext;
710         if (!pPickerInfo->pFirstSearchInfo)
711            pPickerInfo->pLastSearchInfo = NULL;
712         SoftwarePicker_FreeSearchInfo(pSearchInfo);
713      }
714   }
715   else if (pPickerInfo->pHashFile && (pPickerInfo->nHashesRealized
716      < pPickerInfo->nIndexLength))
717   {
718      // time to realize some hashes
719      nCount = 100;
720
721      while((nCount > 0) && pPickerInfo->ppIndex[pPickerInfo->nCurrentPosition]->bHashRealized)
722      {
723         pPickerInfo->nCurrentPosition++;
724         pPickerInfo->nCurrentPosition %= pPickerInfo->nIndexLength;
725         nCount--;
726      }
727
728      pFileInfo = pPickerInfo->ppIndex[pPickerInfo->nCurrentPosition];
729      if (!pFileInfo->bHashRealized)
730      {
731         type = (iodevice_t) (int) device_get_info_int(&pFileInfo->devclass, DEVINFO_INT_TYPE);
732         if (hashfile_functions_used(pPickerInfo->pHashFile, type))
733         {
734            // only calculate the hash if it is appropriate for this device
735            if (!SoftwarePicker_CalculateHash(hwndPicker, pPickerInfo->nCurrentPosition))
736               return FALSE;
737         }
738         SoftwarePicker_RealizeHash(hwndPicker, pPickerInfo->nCurrentPosition);
739
740         // under normal circumstances this will be redundant, but in the unlikely
741         // event of a failure, we do not want to keep running into a brick wall
742         // by calculating this hash over and over
743         if (!pPickerInfo->ppIndex[pPickerInfo->nCurrentPosition]->bHashRealized)
744         {
745            pPickerInfo->ppIndex[pPickerInfo->nCurrentPosition]->bHashRealized = TRUE;
746            pPickerInfo->nHashesRealized++;
747         }
748      }
749   }
750   else
751   {
752      // we are done!
753      bDone = TRUE;
754   }
755
756   return !bDone;
757}
758
759
760
761LPCTSTR SoftwarePicker_GetItemString(HWND hwndPicker, int nRow, int nColumn,
762   TCHAR *pszBuffer, UINT nBufferLength)
763{
764   struct SoftwarePickerInfo *pPickerInfo;
765   const struct FileInfo *pFileInfo;
766   LPCTSTR s = NULL;
767   const char *pszUtf8 = NULL;
768   unsigned int nHashFunction = 0;
769   char szBuffer[256];
770   TCHAR* t_buf;
771   
772   pPickerInfo = GetSoftwarePickerInfo(hwndPicker);
773   if ((nRow < 0) || (nRow >= pPickerInfo->nIndexLength))
774      return NULL;
775
776   pFileInfo = pPickerInfo->ppIndex[nRow];
777
778   switch(nColumn)
779   {
780      case MESS_COLUMN_IMAGES:
781         t_buf = tstring_from_utf8(pFileInfo->pszSubName);
782         if( !t_buf )
783            return s;
784         _sntprintf(pszBuffer, nBufferLength, TEXT("%s"), t_buf);   
785         s = pszBuffer;
786         free(t_buf);
787         break;
788
789      case MESS_COLUMN_GOODNAME:
790      case MESS_COLUMN_MANUFACTURER:
791      case MESS_COLUMN_YEAR:
792      case MESS_COLUMN_PLAYABLE:
793         if (pFileInfo->pHashInfo)
794         {
795            switch(nColumn)
796            {
797               case MESS_COLUMN_GOODNAME:
798                  pszUtf8 = pFileInfo->pHashInfo->longname;
799                  break;
800               case MESS_COLUMN_MANUFACTURER:
801                  pszUtf8 = pFileInfo->pHashInfo->manufacturer;
802                  break;
803               case MESS_COLUMN_YEAR:
804                  pszUtf8 = pFileInfo->pHashInfo->year;
805                  break;
806               case MESS_COLUMN_PLAYABLE:
807                  pszUtf8 = pFileInfo->pHashInfo->playable;
808                  break;
809            }
810            if (pszUtf8)
811            {
812               t_buf = tstring_from_utf8(pszUtf8);
813               if( !t_buf )
814                  return s;
815               _sntprintf(pszBuffer, nBufferLength, TEXT("%s"), t_buf);   
816               s = pszBuffer;
817               free(t_buf);
818            }
819         }
820         break;
821
822      case MESS_COLUMN_CRC:
823      case MESS_COLUMN_MD5:
824      case MESS_COLUMN_SHA1:
825      switch (nColumn)
826         {
827            case MESS_COLUMN_CRC:   nHashFunction = HASH_CRC;   break;
828            case MESS_COLUMN_MD5:   nHashFunction = HASH_MD5;   break;
829            case MESS_COLUMN_SHA1:   nHashFunction = HASH_SHA1;   break;
830         }
831         if (hash_data_extract_printable_checksum(pFileInfo->szHash, nHashFunction, szBuffer))
832         {
833            t_buf = tstring_from_utf8(szBuffer);
834            if( !t_buf )
835               return s;   
836            _sntprintf(pszBuffer, nBufferLength, TEXT("%s"), t_buf);
837            s = pszBuffer;
838            free(t_buf);
839         }
840         break;
841   }
842   return s;
843}
844
845
846
847static LRESULT CALLBACK SoftwarePicker_WndProc(HWND hwndPicker, UINT nMessage,
848   WPARAM wParam, LPARAM lParam)
849{
850   struct SoftwarePickerInfo *pPickerInfo;
851   LRESULT rc;
852   
853   pPickerInfo = GetSoftwarePickerInfo(hwndPicker);
854   rc = CallWindowProc(pPickerInfo->pfnOldWndProc, hwndPicker, nMessage, wParam, lParam);
855
856   if (nMessage == WM_DESTROY)
857   {
858      SoftwarePicker_InternalClear(pPickerInfo);
859      SoftwarePicker_SetDriver(hwndPicker, NULL);
860      free(pPickerInfo);
861   }
862
863   return rc;
864}
865
866
867
868BOOL SetupSoftwarePicker(HWND hwndPicker, const struct PickerOptions *pOptions)
869{
870   struct SoftwarePickerInfo *pPickerInfo = NULL;
871   LONG_PTR l;
872
873   if (!SetupPicker(hwndPicker, pOptions))
874      goto error;
875
876   pPickerInfo = malloc(sizeof(*pPickerInfo));
877   if (!pPickerInfo)
878      goto error;
879   memset(pPickerInfo, 0, sizeof(*pPickerInfo));
880
881   if (!SetProp(hwndPicker, s_szSoftwarePickerProp, (HANDLE) pPickerInfo))
882      goto error;
883   
884   l = (LONG_PTR) SoftwarePicker_WndProc;
885   l = SetWindowLongPtr(hwndPicker, GWLP_WNDPROC, l);
886   pPickerInfo->pfnOldWndProc = (WNDPROC) l;
887   return TRUE;
888
889error:
890   if (pPickerInfo)
891      free(pPickerInfo);
892   return FALSE;
893}
src/mess/osd/winui/guimain.c
r0r996
1//============================================================
2//
3//   guimain.c - Win32 GUI entry point
4//
5//============================================================
6
7// standard windows headers
8#define WIN32_LEAN_AND_MEAN
9#include <windows.h>
10
11int __declspec(dllimport) mess_gui_main(HINSTANCE    hInstance,
12                   HINSTANCE    hPrevInstance,
13                   LPSTR        lpCmdLine,
14                   int          nCmdShow);
15
16int WINAPI WinMain(HINSTANCE    hInstance,
17                   HINSTANCE    hPrevInstance,
18                   LPSTR        lpCmdLine,
19                   int          nCmdShow)
20{
21   return mess_gui_main(hInstance, hPrevInstance, lpCmdLine, nCmdShow);
22}
src/mess/osd/winui/optionsms.c
r0r996
1#define WIN32_LEAN_AND_MEAN
2#include <assert.h>
3#include <string.h>
4#include <windows.h>
5#include <shellapi.h>
6#include <commctrl.h>
7#include <commdlg.h>
8#include <wingdi.h>
9#include <winuser.h>
10#include <tchar.h>
11
12#include "m32util.h"
13#include "m32opts.h"
14#include "optionsms.h"
15#include "emuopts.h"
16#include "driver.h"
17#include "messopts.h"
18#include "osd/windows/configms.h"
19#include "winmain.h"
20
21#define WINGUIOPTION_SOFTWARE_COLUMN_SHOWN      "mess_column_shown"
22#define WINGUIOPTION_SOFTWARE_COLUMN_WIDTHS      "mess_column_widths"
23#define WINGUIOPTION_SOFTWARE_COLUMN_ORDER      "mess_column_order"
24#define WINGUIOPTION_SOFTWARE_SORT_REVERSED      "mess_sort_reversed"
25#define WINGUIOPTION_SOFTWARE_SORT_COLUMN      "mess_sort_column"
26#define WINGUIOPTION_SOFTWARE_TAB            "current_software_tab"
27#define WINGUIOPTION_SOFTWAREPATH            "softwarepath"
28
29#define LOG_SOFTWARE   0
30
31static const options_entry mess_wingui_settings[] =
32{
33   { WINGUIOPTION_SOFTWARE_COLUMN_WIDTHS,   "186, 230, 88, 84, 84, 68, 248, 248",   0,            NULL },
34   { WINGUIOPTION_SOFTWARE_COLUMN_ORDER,   "0,   1,    2,  3,  4,  5,   6,   7",   0,            NULL },
35   { WINGUIOPTION_SOFTWARE_COLUMN_SHOWN,   "1,   1,    1,  1,  1,  0,   0,   0",   0,            NULL },
36
37   { WINGUIOPTION_SOFTWARE_SORT_COLUMN,   "0",                           0,            NULL },
38   { WINGUIOPTION_SOFTWARE_SORT_REVERSED,   "0",                           OPTION_BOOLEAN,   NULL },
39
40   { WINGUIOPTION_SOFTWARE_TAB,         "0",                           0,            NULL },
41   { WINGUIOPTION_SOFTWAREPATH,         "software",                        0,            NULL },
42   { NULL }
43};
44
45void MessSetupSettings(core_options *settings)
46{
47   options_add_entries(settings, mess_wingui_settings);
48}
49
50void MessSetupGameOptions(core_options *opts, int driver_index)
51{
52   BOOL is_global = (driver_index == OPTIONS_TYPE_GLOBAL);
53   AddOptions(opts, mess_core_options, is_global);
54   AddOptions(opts, mess_win_options, is_global);
55
56   if (driver_index >= 0)
57   {
58      mess_add_device_options(opts, drivers[driver_index]);
59   }
60}
61
62void SetMessColumnOrder(int order[])
63{
64   char column_order_string[10000];
65   ColumnEncodeStringWithCount(order, column_order_string, MESS_COLUMN_MAX);
66   options_set_string(Mame32Settings(), WINGUIOPTION_SOFTWARE_COLUMN_ORDER, column_order_string, OPTION_PRIORITY_CMDLINE);
67}
68
69void GetMessColumnOrder(int order[])
70{
71   const char *column_order_string;
72   column_order_string = options_get_string(Mame32Settings(), WINGUIOPTION_SOFTWARE_COLUMN_ORDER);
73   ColumnDecodeStringWithCount(column_order_string, order, MESS_COLUMN_MAX);
74}
75
76void SetMessColumnShown(int shown[])
77{
78   char column_shown_string[10000];
79   ColumnEncodeStringWithCount(shown, column_shown_string, MESS_COLUMN_MAX);
80   options_set_string(Mame32Settings(), WINGUIOPTION_SOFTWARE_COLUMN_SHOWN, column_shown_string, OPTION_PRIORITY_CMDLINE);
81}
82
83void GetMessColumnShown(int shown[])
84{
85   const char *column_shown_string;
86   column_shown_string = options_get_string(Mame32Settings(), WINGUIOPTION_SOFTWARE_COLUMN_SHOWN);
87   ColumnDecodeStringWithCount(column_shown_string, shown, MESS_COLUMN_MAX);
88}
89
90void SetMessColumnWidths(int width[])
91{
92   char column_width_string[10000];
93   ColumnEncodeStringWithCount(width, column_width_string, MESS_COLUMN_MAX);
94   options_set_string(Mame32Settings(), WINGUIOPTION_SOFTWARE_COLUMN_WIDTHS, column_width_string, OPTION_PRIORITY_CMDLINE);
95}
96
97void GetMessColumnWidths(int width[])
98{
99   const char *column_width_string;
100   column_width_string = options_get_string(Mame32Settings(), WINGUIOPTION_SOFTWARE_COLUMN_WIDTHS);
101   ColumnDecodeStringWithCount(column_width_string, width, MESS_COLUMN_MAX);
102}
103
104void SetMessSortColumn(int column)
105{
106   options_set_int(Mame32Settings(), WINGUIOPTION_SOFTWARE_SORT_COLUMN, column, OPTION_PRIORITY_CMDLINE);
107}
108
109int GetMessSortColumn(void)
110{
111   return options_get_int(Mame32Settings(), WINGUIOPTION_SOFTWARE_SORT_COLUMN);
112}
113
114void SetMessSortReverse(BOOL reverse)
115{
116   options_set_bool(Mame32Settings(), WINGUIOPTION_SOFTWARE_SORT_REVERSED, reverse, OPTION_PRIORITY_CMDLINE);
117}
118
119BOOL GetMessSortReverse(void)
120{
121   return options_get_bool(Mame32Settings(), WINGUIOPTION_SOFTWARE_SORT_REVERSED);
122}
123
124const char* GetSoftwareDirs(void)
125{
126   return options_get_string(Mame32Settings(), WINGUIOPTION_SOFTWAREPATH);
127}
128
129void SetSoftwareDirs(const char* paths)
130{
131   options_set_string(Mame32Settings(), WINGUIOPTION_SOFTWAREPATH, paths, OPTION_PRIORITY_CMDLINE);
132}
133
134const char *GetHashDirs(void)
135{
136   return options_get_string(Mame32Global(), OPTION_HASHPATH);
137}
138
139void SetHashDirs(const char *paths)
140{
141   options_set_string(Mame32Global(), OPTION_HASHPATH, paths, OPTION_PRIORITY_CMDLINE);
142}
143
144void SetSelectedSoftware(int driver_index, const device_class *devclass, int device_inst, const char *software)
145{
146   const char *opt_name = device_instancename(devclass, device_inst);
147   core_options *o;
148
149   if (LOG_SOFTWARE)
150   {
151      dprintf("SetSelectedSoftware(): driver_index=%d (\'%s\') devclass=%p device_inst=%d software='%s'\n",
152         driver_index, drivers[driver_index]->name, devclass, device_inst, software);
153   }
154
155   o = load_options(OPTIONS_GAME, driver_index);
156   opt_name = device_instancename(devclass, device_inst);
157   options_set_string(o, opt_name, software, OPTION_PRIORITY_CMDLINE);
158   save_options(OPTIONS_GAME, o, driver_index);
159   options_free(o);
160}
161
162const char *GetSelectedSoftware(int driver_index, const device_class *devclass, int device_inst)
163{
164   const char *opt_name = device_instancename(devclass, device_inst);
165   const char *software;
166   core_options *o;
167
168   o = load_options(OPTIONS_GAME, driver_index);
169   opt_name = device_instancename(devclass, device_inst);
170   software = options_get_string(o, opt_name);
171   return software ? software : "";
172}
173
174void SetExtraSoftwarePaths(int driver_index, const char *extra_paths)
175{
176   char opt_name[32];
177
178   assert(0 <= driver_index && driver_index < driver_list_get_count(drivers));
179
180   snprintf(opt_name, ARRAY_LENGTH(opt_name), "%s_extra_software", drivers[driver_index]->name);
181   options_set_string(Mame32Settings(), opt_name, extra_paths, OPTION_PRIORITY_CMDLINE);
182}
183
184const char *GetExtraSoftwarePaths(int driver_index)
185{
186   char opt_name[32];
187   const char *paths;
188
189   assert(0 <= driver_index && driver_index < driver_list_get_count(drivers));
190
191   snprintf(opt_name, ARRAY_LENGTH(opt_name), "%s_extra_software", drivers[driver_index]->name);
192   paths = options_get_string(Mame32Settings(), opt_name);
193   return paths ? paths : "";
194}
195
196void SetCurrentSoftwareTab(const char *shortname)
197{
198   options_set_string(Mame32Settings(), WINGUIOPTION_SOFTWARE_TAB, shortname, OPTION_PRIORITY_CMDLINE);
199}
200
201const char *GetCurrentSoftwareTab(void)
202{
203   return options_get_string(Mame32Settings(), WINGUIOPTION_SOFTWARE_TAB);
204}
src/mess/osd/winui/resourcems.h
r0r996
1#ifndef RESOURCEMS_H
2#define RESOURCEMS_H
3
4#include "resource.h"
5
6#define IDC_SPLITTER3                2000
7#define IDC_SWTAB                       2001
8#define IDC_SWLIST                      2002
9#define IDC_SWDEVVIEW                   2003
10#define IDC_FILTER_COMPUTER             2004
11#define IDC_FILTER_CONSOLE              2005
12#define IDC_FILTER_MODIFIED             2006
13#define IDC_USE_NEW_UI                  2007
14#define IDC_RAM_COMBOBOX            2008
15#define IDC_RAM_CAPTION               2009
16#define IDC_SKIP_WARNINGS               2013
17#define IDI_WIN_NOROMSNEEDED         2100
18#define IDI_WIN_MISSINGOPTROM         2101
19#define IDI_WIN_FLOP                    2102
20#define IDI_WIN_CASS                    2103
21#define IDI_WIN_SERL                    2104
22#define IDI_WIN_SNAP                    2105
23#define IDI_WIN_PRIN                    2106
24#define IDI_WIN_HARD                    2107
25#define IDI_WIN_CYLN                    2110
26#define IDI_WIN_PTAP                    2111
27#define IDI_WIN_PCRD                    2112
28#define ID_MESS_OPEN_SOFTWARE           2200
29#define ID_MESS_CREATE_SOFTWARE         2201
30#define ID_MESS_RUN_TESTS            2299
31#define IDD_PROP_SOFTWARE               2202
32#define IDD_PROP_CONFIGURATION          2203
33
34#endif /* RESOURCEMS_H */
src/mess/osd/winui/propertiesms.c
r0r996
1#define WIN32_LEAN_AND_MEAN
2
3#ifndef _MSC_VER
4#define NONAMELESSUNION 1
5#endif
6
7#include <windows.h>
8#include <string.h>
9#include <assert.h>
10#include <commctrl.h>
11#include <commdlg.h>
12#include <windowsx.h>
13#include <sys/stat.h>
14#include <stdio.h>
15#include <tchar.h>
16
17#include "driver.h"
18#include "device.h"
19#include "screenshot.h"
20#include "datamap.h"
21#include "bitmask.h"
22#include "mame32.h"
23#include "directories.h"
24#include "m32util.h"
25#include "m32opts.h"
26#include "resourcems.h"
27#include "mess.h"
28#include "utils.h"
29#include "propertiesms.h"
30#include "optionsms.h"
31#include "ms32util.h"
32#include "messopts.h"
33#include "strconv.h"
34
35static BOOL SoftwareDirectories_OnInsertBrowse(HWND hDlg, BOOL bBrowse, LPCTSTR lpItem);
36static BOOL SoftwareDirectories_OnDelete(HWND hDlg);
37static BOOL SoftwareDirectories_OnBeginLabelEdit(HWND hDlg, NMHDR* pNMHDR);
38static BOOL SoftwareDirectories_OnEndLabelEdit(HWND hDlg, NMHDR* pNMHDR);
39
40extern BOOL BrowseForDirectory(HWND hwnd, LPCTSTR pStartDir, TCHAR* pResult);
41BOOL g_bModifiedSoftwarePaths = FALSE;
42
43
44
45static void MarkChanged(HWND hDlg)
46{
47   HWND hCtrl;
48
49   /* fake a CBN_SELCHANGE event from IDC_SIZES to force it to be changed */
50   hCtrl = GetDlgItem(hDlg, IDC_SIZES);
51   PostMessage(hDlg, WM_COMMAND, (CBN_SELCHANGE << 16) | IDC_SIZES, (LPARAM) hCtrl);
52}
53
54
55
56static void AppendList(HWND hList, LPCTSTR lpItem, int nItem)
57{
58    LV_ITEM Item;
59   memset(&Item, 0, sizeof(LV_ITEM));
60   Item.mask = LVIF_TEXT;
61   Item.pszText = (LPTSTR) lpItem;
62   Item.iItem = nItem;
63   ListView_InsertItem(hList, &Item);
64}
65
66
67
68static BOOL SoftwareDirectories_OnInsertBrowse(HWND hDlg, BOOL bBrowse, LPCTSTR lpItem)
69{
70    int nItem;
71    TCHAR inbuf[MAX_PATH];
72    TCHAR outbuf[MAX_PATH];
73    HWND hList;
74   LPTSTR lpIn;
75
76   g_bModifiedSoftwarePaths = TRUE;
77
78    hList = GetDlgItem(hDlg, IDC_DIR_LIST);
79    nItem = ListView_GetNextItem(hList, -1, LVNI_SELECTED);
80
81    if (nItem == -1)
82        return FALSE;
83
84    /* Last item is placeholder for append */
85    if (nItem == ListView_GetItemCount(hList) - 1)
86    {
87        bBrowse = FALSE;
88    }
89
90   if (!lpItem) {
91      if (bBrowse) {
92         ListView_GetItemText(hList, nItem, 0, inbuf, ARRAY_LENGTH(inbuf));
93         lpIn = inbuf;
94      }
95      else {
96         lpIn = NULL;
97      }
98
99      if (!BrowseForDirectory(hDlg, lpIn, outbuf))
100           return FALSE;
101      lpItem = outbuf;
102   }
103
104   AppendList(hList, lpItem, nItem);
105   if (bBrowse)
106      ListView_DeleteItem(hList, nItem+1);
107   MarkChanged(hDlg);
108   return TRUE;
109}
110
111
112
113static BOOL SoftwareDirectories_OnDelete(HWND hDlg)
114{
115    int     nCount;
116    int     nSelect;
117    int     nItem;
118    HWND    hList = GetDlgItem(hDlg, IDC_DIR_LIST);
119
120   g_bModifiedSoftwarePaths = TRUE;
121
122    nItem = ListView_GetNextItem(hList, -1, LVNI_SELECTED | LVNI_ALL);
123
124    if (nItem == -1)
125        return FALSE;
126
127    /* Don't delete "Append" placeholder. */
128    if (nItem == ListView_GetItemCount(hList) - 1)
129        return FALSE;
130
131   ListView_DeleteItem(hList, nItem);
132
133    nCount = ListView_GetItemCount(hList);
134    if (nCount <= 1)
135        return FALSE;
136
137    /* If the last item was removed, select the item above. */
138    if (nItem == nCount - 1)
139        nSelect = nCount - 2;
140    else
141        nSelect = nItem;
142
143    ListView_SetItemState(hList, nSelect, LVIS_FOCUSED | LVIS_SELECTED, LVIS_FOCUSED | LVIS_SELECTED);
144   MarkChanged(hDlg);
145   return TRUE;
146}
147
148
149
150static BOOL SoftwareDirectories_OnBeginLabelEdit(HWND hDlg, NMHDR* pNMHDR)
151{
152   BOOL          bResult = FALSE;
153   NMLVDISPINFO* pDispInfo = (NMLVDISPINFO*)pNMHDR;
154   LVITEM*       pItem = &pDispInfo->item;
155   HWND    hList = GetDlgItem(hDlg, IDC_DIR_LIST);
156
157   /* Last item is placeholder for append */
158   if (pItem->iItem == ListView_GetItemCount(hList) - 1)
159   {
160      HWND hEdit = (HWND) (int) SendMessage(hList, LVM_GETEDITCONTROL, 0, 0);
161      Edit_SetText(hEdit, TEXT(""));
162   }
163
164   return bResult;
165}
166
167
168
169static BOOL SoftwareDirectories_OnEndLabelEdit(HWND hDlg, NMHDR* pNMHDR)
170{
171    BOOL          bResult = FALSE;
172    NMLVDISPINFO* pDispInfo = (NMLVDISPINFO*)pNMHDR;
173    LVITEM*       pItem = &pDispInfo->item;
174
175    if (pItem->pszText != NULL)
176    {
177        struct _stat file_stat;
178
179        /* Don't allow empty entries. */
180        if (!_tcscmp(pItem->pszText, TEXT("")))
181        {
182            return FALSE;
183        }
184
185        /* Check validity of edited directory. */
186        if (_tstat(pItem->pszText, &file_stat) == 0
187        &&  (file_stat.st_mode & S_IFDIR))
188        {
189            bResult = TRUE;
190        }
191        else
192        {
193            if (MessageBox(NULL, TEXT("Directory does not exist, continue anyway?"), TEXT(MAME32NAME), MB_OKCANCEL) == IDOK)
194                bResult = TRUE;
195        }
196    }
197
198    if (bResult == TRUE)
199    {
200      SoftwareDirectories_OnInsertBrowse(hDlg, TRUE, pItem->pszText);
201    }
202
203    return bResult;
204}
205
206
207
208BOOL PropSheetFilter_Config(const machine_config *drv, const game_driver *gamedrv)
209{
210   return (ram_option_count(gamedrv) > 0) || DriverHasDevice(gamedrv, IO_PRINTER);
211}
212
213
214
215INT_PTR CALLBACK GameMessOptionsProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam)
216{
217   INT_PTR rc = 0;
218   BOOL bHandled = FALSE;
219
220   switch (Msg) {
221   case WM_NOTIFY:
222      switch (((NMHDR *) lParam)->code) {
223      case LVN_ENDLABELEDIT:
224         rc = SoftwareDirectories_OnEndLabelEdit(hDlg, (NMHDR *) lParam);
225         bHandled = TRUE;
226         break;
227
228      case LVN_BEGINLABELEDIT:
229         rc = SoftwareDirectories_OnBeginLabelEdit(hDlg, (NMHDR *) lParam);
230         bHandled = TRUE;
231         break;
232      }
233   }
234
235   if (!bHandled)
236      rc = GameOptionsProc(hDlg, Msg, wParam, lParam);
237   return rc;
238}
239
240
241
242BOOL MessPropertiesCommand(HWND hWnd, WORD wNotifyCode, WORD wID, BOOL *changed)
243{
244   BOOL handled = TRUE;
245
246   switch(wID)
247   {
248      case IDC_DIR_BROWSE:
249         if (wNotifyCode == BN_CLICKED)
250            *changed = SoftwareDirectories_OnInsertBrowse(hWnd, TRUE, NULL);
251         break;
252
253      case IDC_DIR_INSERT:
254         if (wNotifyCode == BN_CLICKED)
255            *changed = SoftwareDirectories_OnInsertBrowse(hWnd, FALSE, NULL);
256         break;
257
258      case IDC_DIR_DELETE:
259         if (wNotifyCode == BN_CLICKED)
260            *changed = SoftwareDirectories_OnDelete(hWnd);
261         break;
262
263      default:
264         handled = FALSE;
265         break;
266   }
267   return handled;
268}
269
270
271
272//============================================================
273//  DATAMAP HANDLERS
274//============================================================
275
276static BOOL DirListReadControl(datamap *map, HWND dialog, HWND control, core_options *opts, const char *option_name)
277{
278   int directory_count;
279    LV_ITEM lvi;
280   TCHAR buffer[2048];
281   char *dir_list;
282   int i, pos, driver_index;
283
284   // determine the directory count; note that one item is the "<    >" entry
285   directory_count = ListView_GetItemCount(control);
286   if (directory_count > 0)
287      directory_count--;
288
289   buffer[0] = '\0';
290   pos = 0;
291
292   for (i = 0; i < directory_count; i++)
293   {
294      // append a semicolon, if we're past the first entry
295      if (i > 0)
296         pos += _sntprintf(&buffer[pos], ARRAY_LENGTH(buffer) - pos, TEXT(";"));
297
298      // retrieve the next entry
299      memset(&lvi, '\0', sizeof(lvi));
300      lvi.mask = LVIF_TEXT;
301      lvi.iItem = i;
302      lvi.pszText = &buffer[pos];
303      lvi.cchTextMax = ARRAY_LENGTH(buffer) - pos;
304      ListView_GetItem(control, &lvi);
305
306      // advance the position
307      pos += _tcslen(&buffer[pos]);
308   }
309
310   dir_list = utf8_from_tstring(buffer);
311   if (dir_list != NULL)
312   {
313      driver_index = PropertiesCurrentGame(dialog);
314      SetExtraSoftwarePaths(driver_index, dir_list);
315      free(dir_list);
316   }
317   return TRUE;
318}
319
320
321
322static BOOL DirListPopulateControl(datamap *map, HWND dialog, HWND control, core_options *opts, const char *option_name)
323{
324   int driver_index, pos, new_pos, current_item;
325   const char *dir_list;
326   TCHAR *t_dir_list;
327   TCHAR *s;
328   LV_COLUMN lvc;
329   RECT r;
330
331   // access the directory list, and convert to TCHARs
332   driver_index = PropertiesCurrentGame(dialog);
333   dir_list = GetExtraSoftwarePaths(driver_index);
334   t_dir_list = tstring_from_utf8(dir_list);
335   if (!t_dir_list)
336      return FALSE;
337
338   // delete all items in the list control
339   ListView_DeleteAllItems(control);
340
341   // add the column
342   GetClientRect(control, &r);
343   memset(&lvc, 0, sizeof(LVCOLUMN));
344   lvc.mask = LVCF_WIDTH;
345   lvc.cx = r.right - r.left - GetSystemMetrics(SM_CXHSCROLL);
346   ListView_InsertColumn(control, 0, &lvc);
347
348   // add each of the directories
349   pos = 0;
350   current_item = 0;
351   while(t_dir_list[pos] != '\0')
352   {
353      // parse off this item
354      s = _tcschr(&t_dir_list[pos], ';');
355      if (s != NULL)
356      {
357         *s = '\0';
358         new_pos = s - &t_dir_list[pos] + 1;
359      }
360      else
361      {
362         new_pos = pos + _tcslen(&t_dir_list[pos]);
363      }
364
365      // append this item
366      AppendList(control, &t_dir_list[pos], current_item);
367
368      // advance to next item
369      pos = new_pos;
370      current_item++;
371   }
372
373   // finish up
374   AppendList(control, TEXT(DIRLIST_NEWENTRYTEXT), current_item);
375   ListView_SetItemState(control, 0, LVIS_SELECTED, LVIS_SELECTED);
376   free(t_dir_list);
377   return TRUE;
378}
379
380
381
382static BOOL RamPopulateControl(datamap *map, HWND dialog, HWND control, core_options *opts, const char *option_name)
383{
384   int count, i, current_index, driver_index;
385   const game_driver *gamedrv;
386   UINT32 ram, current_ram;
387   char buffer[64];
388   const char *this_ram_string;
389   TCHAR* t_ramstring;
390
391   // identify the driver
392   driver_index = PropertiesCurrentGame(dialog);
393   gamedrv = drivers[driver_index];
394
395   // clear out the combo box
396   (void)ComboBox_ResetContent(control);
397
398   // identify how many options that we have
399   count = ram_option_count(gamedrv);
400   EnableWindow(control, count > 0);
401
402   // we can only do something meaningful if there is more than one option
403   if (count > 0)
404   {
405      // identify the current amount of RAM
406      this_ram_string = options_get_string(opts, OPTION_RAMSIZE);
407      current_ram = (this_ram_string != NULL) ? ram_parse_string(this_ram_string) : 0;
408      if (current_ram == 0)
409         current_ram = ram_default(gamedrv);
410
411      // by default, assume index 0
412      current_index = 0;
413
414      // loop through all options
415      for (i = 0; i < count; i++)
416      {
417         // identify this option
418         ram = ram_option(gamedrv, i);
419         this_ram_string = ram_string(buffer, ram);
420
421         t_ramstring = tstring_from_utf8(this_ram_string);
422         if( !t_ramstring )
423            return FALSE;
424
425         // add this option to the combo box
426         (void)ComboBox_InsertString(control, i, win_tstring_strdup(t_ramstring));
427         (void)ComboBox_SetItemData(control, i, ram);
428         
429         free(t_ramstring);
430
431         // is this the current option?  record the index if so
432         if (ram == current_ram)
433            current_index = i;
434      }
435
436      // set the combo box
437      (void)ComboBox_SetCurSel(control, current_index);
438   }
439   return TRUE;
440}
441
442
443
444//============================================================
445//  DATAMAP SETUP
446//============================================================
447
448void MessBuildDataMap(datamap *properties_datamap)
449{
450   // MESS specific stuff
451   datamap_add(properties_datamap, IDC_DIR_LIST,            DM_STRING,   NULL);
452   datamap_add(properties_datamap, IDC_RAM_COMBOBOX,         DM_INT,      OPTION_RAMSIZE);
453   datamap_add(properties_datamap, IDC_SKIP_WARNINGS,         DM_BOOL,   OPTION_SKIP_WARNINGS);
454   datamap_add(properties_datamap, IDC_USE_NEW_UI,            DM_BOOL,   "newui");
455
456   // set up callbacks
457   datamap_set_callback(properties_datamap, IDC_DIR_LIST,      DCT_READ_CONTROL,      DirListReadControl);
458   datamap_set_callback(properties_datamap, IDC_DIR_LIST,      DCT_POPULATE_CONTROL,   DirListPopulateControl);
459   datamap_set_callback(properties_datamap, IDC_RAM_COMBOBOX,   DCT_POPULATE_CONTROL,   RamPopulateControl);
460}
src/mess/osd/winui/softwarepicker.h
r0r996
1//============================================================
2//
3//   softwarepicker.h - MESS's software picker
4//
5//============================================================
6
7LPCSTR SoftwarePicker_LookupFilename(HWND hwndPicker, int nIndex);
8device_class SoftwarePicker_LookupDevice(HWND hwndPicker, int nIndex);
9int SoftwarePicker_LookupIndex(HWND hwndPicker, LPCSTR pszFilename);
10iodevice_t SoftwarePicker_GetImageType(HWND hwndPicker, int nIndex);
11BOOL SoftwarePicker_AddFile(HWND hwndPicker, LPCSTR pszFilename);
12BOOL SoftwarePicker_AddDirectory(HWND hwndPicker, LPCSTR pszDirectory);
13void SoftwarePicker_Clear(HWND hwndPicker);
14void SoftwarePicker_SetDriver(HWND hwndPicker, const game_driver *pDriver);
15void SoftwarePicker_SetErrorProc(HWND hwndPicker, void (*pfnErrorProc)(const char *message));
16
17// PickerOptions callbacks
18LPCTSTR SoftwarePicker_GetItemString(HWND hwndPicker, int nRow, int nColumn,
19   TCHAR *pszBuffer, UINT nBufferLength);
20BOOL SoftwarePicker_Idle(HWND hwndPicker);
21
22BOOL SetupSoftwarePicker(HWND hwndPicker, const struct PickerOptions *pOptions);

Previous 15994 Revisions Next


© 1998-2018 The MESS Team