Release 960717
[wine] / misc / main.c
1 /*
2  * Main function.
3  *
4  * Copyright 1994 Alexandre Julliard
5  */
6
7 #include <stdio.h>
8 #include <stdlib.h>
9 #include <string.h>
10 #include <unistd.h>
11 #include <ctype.h>
12 #include <locale.h>
13 #ifdef MALLOC_DEBUGGING
14 #include <malloc.h>
15 #endif
16 #include <X11/Xlib.h>
17 #include <X11/Xresource.h>
18 #include <X11/Xutil.h>
19 #include <X11/cursorfont.h>
20 #include "message.h"
21 #include "module.h"
22 #include "msdos.h"
23 #include "windows.h"
24 #include "winsock.h"
25 #include "options.h"
26 #include "desktop.h"
27 #include "registers.h"
28 #include "shell.h"
29 #include "winbase.h"
30 #include "string32.h"
31 #define DEBUG_DEFINE_VARIABLES
32 #include "stddebug.h"
33 #include "debug.h"
34 #include "xmalloc.h"
35
36 const char people[] = "Wine is available thanks to the work of "
37 "Bob Amstadt, Dag Asheim, Martin Ayotte, Ross Biro, Uwe Bonnes, Erik Bos, "
38 "Fons Botman, John Brezak, Andrew Bulhak, John Burton, "
39 "Niels de Carpentier, Roman Dolejsi, Frans van Dorsselaer, Paul Falstad, "
40 "Olaf Flebbe, Peter Galbavy, Ramon Garcia, Hans de Graaff, "
41 "Charles M. Hannum, John Harvey, Cameron Heide, Jochen Hoenicke, "
42 "Onno Hovers, Jeffrey Hsu, Miguel de Icaza, Jukka Iivonen, "
43 "Alexandre Julliard, Jochen Karrer, Andreas Kirschbaum, Albrecht Kleine, "
44 "Jon Konrath, Alex Korobka, Greg Kreider, Anand Kumria, Scott A. Laird, "
45 "Martin von Loewis, Kenneth MacDonald, Peter MacDonald, William Magro, "
46 "Juergen Marquardt, Marcus Meissner, Graham Menhennitt, David Metcalfe, "
47 "Steffen Moeller, Philippe De Muyter, Itai Nahshon, Michael Patra, "
48 "Jim Peterson, Robert Pouliot, Keith Reynolds, John Richardson, "
49 "Johannes Ruscheinski, Thomas Sandford, Constantine Sapuntzakis, "
50 "Daniel Schepler, Ulrich Schmid, Bernd Schmidt, Yngvi Sigurjonsson, "
51 "Rick Sladkey, William Smith, Erik Svendsen, Tristan Tarrant, "
52 "Andrew Taylor, Duncan C Thomson, Goran Thyni, Jimmy Tirtawangsa, "
53 "Jon Tombs, Linus Torvalds, Gregory Trubetskoy, Michael Veksler, "
54 "Sven Verdoolaege, Eric Warnke, Manfred Weichel, Morten Welinder, "
55 "Jan Willamowius, Carl Williams, Karl Guenter Wuensch, Eric Youngdale, "
56 "and James Youngman. ";
57
58 const char * langNames[] =
59 {
60     "En",  /* LANG_En */
61     "Es",  /* LANG_Es */
62     "De",  /* LANG_De */
63     "No",  /* LANG_No */
64     "Fr",  /* LANG_Fr */
65     "Fi",  /* LANG_Fi */
66     "Da",  /* LANG_Da */
67     "Cz",  /* LANG_Cz */
68     "Eo",  /* LANG_Eo */
69     "It",  /* LANG_It */
70     "Ko",  /* LANG_Ko */
71     NULL
72 };
73
74 #define WINE_CLASS    "Wine"    /* Class name for resources */
75
76 typedef struct tagENVENTRY {
77   LPSTR                 Name;
78   LPSTR                 Value;
79   WORD                  wSize;
80   struct tagENVENTRY    *Prev;
81   struct tagENVENTRY    *Next;
82 } ENVENTRY, *LPENVENTRY;
83
84 LPENVENTRY      lpEnvList = NULL;
85
86 Display *display;
87 Screen *screen;
88 Window rootWindow;
89 int screenWidth = 0, screenHeight = 0;  /* Desktop window dimensions */
90 int screenDepth = 0;  /* Screen depth to use */
91 int desktopX = 0, desktopY = 0;  /* Desktop window position (if any) */
92 int getVersion16 = 0;
93 int getVersion32 = 0;
94 OSVERSIONINFO32A getVersionEx;
95
96 struct options Options =
97 {  /* default options */
98     NULL,           /* desktopGeometry */
99     NULL,           /* programName */
100     FALSE,          /* usePrivateMap */
101     FALSE,          /* useFixedMap */
102     FALSE,          /* synchronous */
103     FALSE,          /* backing store */
104     SW_SHOWNORMAL,  /* cmdShow */
105     FALSE,
106     FALSE,          /* AllowReadOnly */
107     MODE_ENHANCED,  /* Enhanced mode */
108     FALSE,          /* IPC enabled */
109 #ifdef DEFAULT_LANG
110     DEFAULT_LANG,   /* Default language */
111 #else
112     LANG_En,
113 #endif
114     FALSE,          /* Managed windows */
115     FALSE           /* Perfect graphics */
116 };
117
118
119 static XrmOptionDescRec optionsTable[] =
120 {
121     { "-backingstore",  ".backingstore",    XrmoptionNoArg,  (caddr_t)"on" },
122     { "-desktop",       ".desktop",         XrmoptionSepArg, (caddr_t)NULL },
123     { "-depth",         ".depth",           XrmoptionSepArg, (caddr_t)NULL },
124     { "-display",       ".display",         XrmoptionSepArg, (caddr_t)NULL },
125     { "-iconic",        ".iconic",          XrmoptionNoArg,  (caddr_t)"on" },
126     { "-ipc",           ".ipc",             XrmoptionNoArg,  (caddr_t)"off"},
127     { "-language",      ".language",        XrmoptionSepArg, (caddr_t)"En" },
128     { "-name",          ".name",            XrmoptionSepArg, (caddr_t)NULL },
129     { "-perfect",       ".perfect",         XrmoptionNoArg,  (caddr_t)"on" },
130     { "-privatemap",    ".privatemap",      XrmoptionNoArg,  (caddr_t)"on" },
131     { "-fixedmap",      ".fixedmap",        XrmoptionNoArg,  (caddr_t)"on" },
132     { "-synchronous",   ".synchronous",     XrmoptionNoArg,  (caddr_t)"on" },
133     { "-debug",         ".debug",           XrmoptionNoArg,  (caddr_t)"on" },
134     { "-debugmsg",      ".debugmsg",        XrmoptionSepArg, (caddr_t)NULL },
135     { "-dll",           ".dll",             XrmoptionSepArg, (caddr_t)NULL },
136     { "-allowreadonly", ".allowreadonly",   XrmoptionNoArg,  (caddr_t)"on" },
137     { "-mode",          ".mode",            XrmoptionSepArg, (caddr_t)NULL },
138     { "-managed",       ".managed",         XrmoptionNoArg,  (caddr_t)"off"},
139     { "-winver",        ".winver",          XrmoptionSepArg, (caddr_t)NULL }
140 };
141
142 #define NB_OPTIONS  (sizeof(optionsTable) / sizeof(optionsTable[0]))
143
144 #define USAGE \
145   "Usage:  %s [options] program_name [arguments]\n" \
146   "\n" \
147   "Options:\n" \
148   "    -allowreadonly  Read only files may be opened in write mode\n" \
149   "    -backingstore   Turn on backing store\n" \
150   "    -debug          Enter debugger before starting application\n" \
151   "    -debugmsg name  Turn debugging-messages on or off\n" \
152   "    -depth n        Change the depth to use for multiple-depth screens\n" \
153   "    -desktop geom   Use a desktop window of the given geometry\n" \
154   "    -display name   Use the specified display\n" \
155   "    -dll name       Enable or disable built-in DLLs\n" \
156   "    -fixedmap       Use a \"standard\" color map\n" \
157   "    -iconic         Start as an icon\n" \
158   "    -ipc            Enable IPC facilities\n" \
159   "    -language xx    Set the language (one of En,Es,De,No,Fr,Fi,Da,Cz,Eo,It,Ko)\n" \
160   "    -managed        Allow the window manager to manage created windows\n" \
161   "    -mode mode      Start Wine in a particular mode (standard or enhanced)\n" \
162   "    -name name      Set the application name\n" \
163   "    -perfect        Favor correctness over speed for graphical operations\n" \
164   "    -privatemap     Use a private color map\n" \
165   "    -synchronous    Turn on synchronous display mode\n" \
166   "    -winver         Version to imitate (one of win31,win95,nt351)\n"
167
168
169
170 /***********************************************************************
171  *           MAIN_Usage
172  */
173 #ifndef WINELIB32
174 static void MAIN_Usage( char *name )
175 {
176     fprintf( stderr, USAGE, name );
177     exit(1);
178 }
179 #endif
180
181
182 /***********************************************************************
183  *           MAIN_GetProgramName
184  *
185  * Get the program name. The name is specified by (in order of precedence):
186  * - the option '-name'.
187  * - the environment variable 'WINE_NAME'.
188  * - the last component of argv[0].
189  */
190 static char *MAIN_GetProgramName( int argc, char *argv[] )
191 {
192     int i;
193     char *p;
194
195     for (i = 1; i < argc-1; i++)
196         if (!strcmp( argv[i], "-name" )) return argv[i+1];
197     if ((p = getenv( "WINE_NAME" )) != NULL) return p;
198     if ((p = strrchr( argv[0], '/' )) != NULL) return p+1;
199     return argv[0];
200 }
201
202
203 /***********************************************************************
204  *           MAIN_GetResource
205  *
206  * Fetch the value of resource 'name' using the correct instance name.
207  * 'name' must begin with '.' or '*'
208  */
209 static int MAIN_GetResource( XrmDatabase db, char *name, XrmValue *value )
210 {
211     char *buff_instance, *buff_class;
212     char *dummy;
213     int retval;
214
215     buff_instance = (char *)xmalloc(strlen(Options.programName)+strlen(name)+1);
216     buff_class    = (char *)xmalloc( strlen(WINE_CLASS) + strlen(name) + 1 );
217
218     strcpy( buff_instance, Options.programName );
219     strcat( buff_instance, name );
220     strcpy( buff_class, WINE_CLASS );
221     strcat( buff_class, name );
222     retval = XrmGetResource( db, buff_instance, buff_class, &dummy, value );
223     free( buff_instance );
224     free( buff_class );
225     return retval;
226 }
227
228
229 /***********************************************************************
230  *                    ParseDebugOptions
231  *
232  *  Turns specific debug messages on or off, according to "options".
233  *  Returns TRUE if parsing was successful
234  */
235 #ifdef DEBUG_RUNTIME
236
237 BOOL ParseDebugOptions(char *options)
238 {
239   int l;
240   if (strlen(options)<3)
241     return FALSE;
242   do
243   {
244     if ((*options!='+')&&(*options!='-'))
245       return FALSE;
246     if (strchr(options,','))
247       l=strchr(options,',')-options;
248     else
249       l=strlen(options);
250     if (!lstrncmpi32A(options+1,"all",l-1))
251       {
252         int i;
253         for (i=0;i<sizeof(debug_msg_enabled)/sizeof(short);i++)
254           debug_msg_enabled[i]=(*options=='+');
255       }
256     else
257       {
258         int i;
259         for (i=0;i<sizeof(debug_msg_enabled)/sizeof(short);i++)
260           if (debug_msg_name && (!lstrncmpi32A(options+1,debug_msg_name[i],l-1)))
261             {
262               debug_msg_enabled[i]=(*options=='+');
263               break;
264             }
265         if (i==sizeof(debug_msg_enabled)/sizeof(short))
266           return FALSE;
267       }
268     options+=l;
269   }
270   while((*options==',')&&(*(++options)));
271   if (*options)
272     return FALSE;
273   else
274     return TRUE;
275 }
276
277 #endif
278
279
280 /***********************************************************************
281  *           MAIN_ParseLanguageOption
282  *
283  * Parse -language option.
284  */
285 static void MAIN_ParseLanguageOption( char *arg )
286 {
287     const char **p = langNames;
288
289     Options.language = LANG_En;  /* First language */
290     for (p = langNames; *p; p++)
291     {
292         if (!lstrcmpi32A( *p, arg )) return;
293         Options.language++;
294     }
295     fprintf( stderr, "Invalid language specified '%s'. Supported languages are: ", arg );
296     for (p = langNames; *p; p++) fprintf( stderr, "%s ", *p );
297     fprintf( stderr, "\n" );
298     exit(1);
299 }
300
301
302 /***********************************************************************
303  *           MAIN_ParseModeOption
304  *
305  * Parse -mode option.
306  */
307 static void MAIN_ParseModeOption( char *arg )
308 {
309     if (!lstrcmpi32A("enhanced", arg)) Options.mode = MODE_ENHANCED;
310     else if (!lstrcmpi32A("standard", arg)) Options.mode = MODE_STANDARD;
311     else
312     {
313         fprintf(stderr, "Invalid mode '%s' specified.\n", arg);
314         fprintf(stderr, "Valid modes are: 'standard', 'enhanced' (default).\n");
315         exit(1);
316     }
317 }
318
319 /**********************************************************************
320  *           MAIN_ParseVersion
321  */
322 static void MAIN_ParseVersion( char *arg )
323 {
324     /* If you add any other options, 
325        verify the values you return on the real thing */
326     if(strcmp(arg,"win31")==0) 
327     {
328         getVersion16 = 0x06160A03;
329         /* FIXME: My Win32s installation failed to execute the
330            MSVC 4 test program. So check these values */
331         getVersion32 = 0x80000A03;
332         getVersionEx.dwMajorVersion=3;
333         getVersionEx.dwMinorVersion=10;
334         getVersionEx.dwBuildNumber=0;
335         getVersionEx.dwPlatformId=VER_PLATFORM_WIN32s;
336         strcpy(getVersionEx.szCSDVersion,"Win32s 1.3");
337     }
338     else if(strcmp(arg, "win95")==0)
339     {
340         getVersion16 = 0x07005F03;
341         getVersion32 = 0xC0000004;
342         getVersionEx.dwMajorVersion=4;
343         getVersionEx.dwMinorVersion=0;
344         getVersionEx.dwBuildNumber=0x40003B6;
345         getVersionEx.dwPlatformId=VER_PLATFORM_WIN32_WINDOWS;
346         strcpy(getVersionEx.szCSDVersion,"");
347     }
348     else if(strcmp(arg, "nt351")==0)
349     {
350         getVersion16 = 0x05000A03;
351         getVersion32 = 0x04213303;
352         getVersionEx.dwMajorVersion=3;
353         getVersionEx.dwMinorVersion=51;
354         getVersionEx.dwBuildNumber=0x421;
355         getVersionEx.dwPlatformId=VER_PLATFORM_WIN32_NT;
356         strcpy(getVersionEx.szCSDVersion,"Service Pack 2");
357     }
358     else fprintf(stderr, "Unknown winver system code - ignored\n");
359 }
360
361 /***********************************************************************
362  *           MAIN_ParseOptions
363  *
364  * Parse command line options and open display.
365  */
366 static void MAIN_ParseOptions( int *argc, char *argv[] )
367 {
368     char *display_name;
369     XrmValue value;
370     XrmDatabase db = XrmGetFileDatabase("/usr/lib/X11/app-defaults/Wine");
371
372       /* Parse command line */
373     Options.programName = MAIN_GetProgramName( *argc, argv );
374     XrmParseCommand( &db, optionsTable, NB_OPTIONS,
375                      Options.programName, argc, argv );
376
377 #ifdef WINELIB
378     /* Need to assemble command line and pass it to WinMain */
379 #else
380     if (*argc < 2 || lstrcmpi32A(argv[1], "-h") == 0) 
381         MAIN_Usage( argv[0] );
382 #endif
383
384       /* Open display */
385
386     if (MAIN_GetResource( db, ".display", &value )) display_name = value.addr;
387     else display_name = NULL;
388
389     if (!(display = XOpenDisplay( display_name )))
390     {
391         fprintf( stderr, "%s: Can't open display: %s\n",
392                  argv[0], display_name ? display_name : "(none specified)" );
393         exit(1);
394     }
395
396       /* Get all options */
397     if (MAIN_GetResource( db, ".iconic", &value ))
398         Options.cmdShow = SW_SHOWMINIMIZED;
399     if (MAIN_GetResource( db, ".privatemap", &value ))
400         Options.usePrivateMap = TRUE;
401     if (MAIN_GetResource( db, ".fixedmap", &value ))
402         Options.useFixedMap = TRUE;
403     if (MAIN_GetResource( db, ".synchronous", &value ))
404         Options.synchronous = TRUE;
405     if (MAIN_GetResource( db, ".backingstore", &value ))
406         Options.backingstore = TRUE;    
407     if (MAIN_GetResource( db, ".debug", &value ))
408         Options.debug = TRUE;
409     if (MAIN_GetResource( db, ".allowreadonly", &value ))
410         Options.allowReadOnly = TRUE;
411     if (MAIN_GetResource( db, ".ipc", &value ))
412         Options.ipc = TRUE;
413     if (MAIN_GetResource( db, ".perfect", &value ))
414         Options.perfectGraphics = TRUE;
415     if (MAIN_GetResource( db, ".depth", &value))
416         screenDepth = atoi( value.addr );
417     if (MAIN_GetResource( db, ".desktop", &value))
418         Options.desktopGeometry = value.addr;
419     if (MAIN_GetResource( db, ".language", &value))
420         MAIN_ParseLanguageOption( (char *)value.addr );
421     if (MAIN_GetResource( db, ".managed", &value))
422         Options.managed = TRUE;
423     if (MAIN_GetResource( db, ".mode", &value))
424         MAIN_ParseModeOption( (char *)value.addr );
425
426 #ifdef DEBUG_RUNTIME
427     if (MAIN_GetResource( db, ".debugoptions", &value))
428         ParseDebugOptions((char*)value.addr);
429 #endif
430     if (MAIN_GetResource( db, ".debugmsg", &value))
431       {
432 #ifndef DEBUG_RUNTIME
433         fprintf(stderr,"%s: Option \"-debugmsg\" not implemented.\n" \
434           "    Recompile with DEBUG_RUNTIME in include/stddebug.h defined.\n",
435           argv[0]);
436         exit(1);
437 #else
438         if (ParseDebugOptions((char*)value.addr)==FALSE)
439           {
440             int i;
441             fprintf(stderr,"%s: Syntax: -debugmsg +xxx,...  or -debugmsg -xxx,...\n",argv[0]);
442             fprintf(stderr,"Example: -debugmsg +all,-heap    turn on all messages except heap messages\n");
443             fprintf(stderr,"Available message types:\n");
444             fprintf(stderr,"%-9s ","all");
445             for(i=0;i<sizeof(debug_msg_enabled)/sizeof(short);i++)
446               if(debug_msg_name[i])
447                 fprintf(stderr,"%-9s%c",debug_msg_name[i],
448                         (((i+2)%8==0)?'\n':' '));
449             fprintf(stderr,"\n\n");
450             exit(1);
451           }
452 #endif
453       }
454
455       if(MAIN_GetResource( db, ".dll", &value))
456       {
457 #ifndef WINELIB
458           if (!BUILTIN_ParseDLLOptions( (char*)value.addr ))
459           {
460               fprintf(stderr,"%s: Syntax: -dll +xxx,... or -dll -xxx,...\n",argv[0]);
461               fprintf(stderr,"Example: -dll -ole2    Do not use emulated OLE2.DLL\n");
462               fprintf(stderr,"Available DLLs:\n");
463               BUILTIN_PrintDLLs();
464               exit(1);
465           }
466 #else
467           fprintf(stderr,"-dll not supported in libwine\n");
468 #endif
469       }
470
471       if(MAIN_GetResource( db, ".winver", &value))
472           MAIN_ParseVersion( (char*)value.addr );
473 }
474
475
476 /***********************************************************************
477  *           MAIN_CreateDesktop
478  */
479 static void MAIN_CreateDesktop( int argc, char *argv[] )
480 {
481     int flags;
482     unsigned int width = 640, height = 480;  /* Default size = 640x480 */
483     char *name = "Wine desktop";
484     XSizeHints *size_hints;
485     XWMHints   *wm_hints;
486     XClassHint *class_hints;
487     XSetWindowAttributes win_attr;
488     XTextProperty window_name;
489     Atom XA_WM_DELETE_WINDOW;
490
491     flags = XParseGeometry( Options.desktopGeometry,
492                             &desktopX, &desktopY, &width, &height );
493     screenWidth  = width;
494     screenHeight = height;
495
496       /* Create window */
497
498     win_attr.event_mask = ExposureMask | KeyPressMask | KeyReleaseMask |
499                          PointerMotionMask | ButtonPressMask |
500                          ButtonReleaseMask | EnterWindowMask | 
501                          StructureNotifyMask;
502     win_attr.cursor = XCreateFontCursor( display, XC_top_left_arrow );
503
504     rootWindow = XCreateWindow( display, DefaultRootWindow(display),
505                                 desktopX, desktopY, width, height, 0,
506                                 CopyFromParent, InputOutput, CopyFromParent,
507                                 CWEventMask | CWCursor, &win_attr );
508
509       /* Set window manager properties */
510
511     size_hints  = XAllocSizeHints();
512     wm_hints    = XAllocWMHints();
513     class_hints = XAllocClassHint();
514     if (!size_hints || !wm_hints || !class_hints)
515     {
516         fprintf( stderr, "Not enough memory for window manager hints.\n" );
517         exit(1);
518     }
519     size_hints->min_width = size_hints->max_width = width;
520     size_hints->min_height = size_hints->max_height = height;
521     size_hints->flags = PMinSize | PMaxSize;
522     if (flags & (XValue | YValue)) size_hints->flags |= USPosition;
523     if (flags & (WidthValue | HeightValue)) size_hints->flags |= USSize;
524     else size_hints->flags |= PSize;
525
526     wm_hints->flags = InputHint | StateHint;
527     wm_hints->input = True;
528     wm_hints->initial_state = NormalState;
529     class_hints->res_name = argv[0];
530     class_hints->res_class = "Wine";
531
532     XStringListToTextProperty( &name, 1, &window_name );
533     XSetWMProperties( display, rootWindow, &window_name, &window_name,
534                       argv, argc, size_hints, wm_hints, class_hints );
535     XA_WM_DELETE_WINDOW = XInternAtom( display, "WM_DELETE_WINDOW", False );
536     XSetWMProtocols( display, rootWindow, &XA_WM_DELETE_WINDOW, 1 );
537     XFree( size_hints );
538     XFree( wm_hints );
539     XFree( class_hints );
540
541       /* Map window */
542
543     XMapWindow( display, rootWindow );
544 }
545
546
547 XKeyboardState keyboard_state;
548
549 /***********************************************************************
550  *           MAIN_SaveSetup
551  */
552 static void MAIN_SaveSetup(void)
553 {
554     XGetKeyboardControl(display, &keyboard_state);
555 }
556
557 /***********************************************************************
558  *           MAIN_RestoreSetup
559  */
560 static void MAIN_RestoreSetup(void)
561 {
562     XKeyboardControl keyboard_value;
563
564     keyboard_value.key_click_percent    = keyboard_state.key_click_percent;
565     keyboard_value.bell_percent         = keyboard_state.bell_percent;
566     keyboard_value.bell_pitch           = keyboard_state.bell_pitch;
567     keyboard_value.bell_duration        = keyboard_state.bell_duration;
568     keyboard_value.auto_repeat_mode     = keyboard_state.global_auto_repeat;
569
570     XChangeKeyboardControl(display, KBKeyClickPercent | KBBellPercent | 
571         KBBellPitch | KBBellDuration | KBAutoRepeatMode, &keyboard_value);
572 }
573
574
575 static void called_at_exit(void)
576 {
577     MAIN_RestoreSetup();
578     WSACleanup();
579 }
580
581 /***********************************************************************
582  *           main
583  */
584 #if defined(WINELIB) && defined(WINELIBDLL)
585 int _wine_main (int argc, char *argv[])
586 #else
587 int main( int argc, char *argv[] )
588 #endif
589 {    
590     int ret_val;
591     int depth_count, i;
592     int *depth_list;
593     struct timeval tv;
594
595     extern int _WinMain(int argc, char **argv);
596
597 #ifdef MALLOC_DEBUGGING
598     char *trace;
599
600     mcheck(NULL);
601     if (!(trace = getenv("MALLOC_TRACE")))
602     {       
603         fprintf( stderr, "MALLOC_TRACE not set. No trace generated\n" );
604     }
605     else
606     {
607         fprintf( stderr, "malloc trace goes to %s\n", trace );
608         mtrace();
609     }
610 #endif
611
612     setbuf(stdout,NULL);
613     setbuf(stderr,NULL);
614
615     setlocale(LC_CTYPE,"");
616     gettimeofday( &tv, NULL);
617     MSG_WineStartTicks = (tv.tv_sec * 1000) + (tv.tv_usec / 1000);
618
619     XrmInitialize();
620     
621     MAIN_ParseOptions( &argc, argv );
622
623     if (Options.desktopGeometry && Options.managed)
624     {
625         fprintf( stderr, "%s: -managed and -desktop options cannot be used together\n",
626                  Options.programName );
627         exit(1);
628     }
629
630     screen       = DefaultScreenOfDisplay( display );
631     screenWidth  = WidthOfScreen( screen );
632     screenHeight = HeightOfScreen( screen );
633     if (screenDepth)  /* -depth option specified */
634     {
635         depth_list = XListDepths(display,DefaultScreen(display),&depth_count);
636         for (i = 0; i < depth_count; i++)
637             if (depth_list[i] == screenDepth) break;
638         XFree( depth_list );
639         if (i >= depth_count)
640         {
641             fprintf( stderr, "%s: Depth %d not supported on this screen.\n",
642                               Options.programName, screenDepth );
643             exit(1);
644         }
645     }
646     else screenDepth  = DefaultDepthOfScreen( screen );
647     if (Options.synchronous) XSynchronize( display, True );
648     if (Options.desktopGeometry) MAIN_CreateDesktop( argc, argv );
649     else rootWindow = DefaultRootWindow( display );
650
651     MAIN_SaveSetup();
652     atexit(called_at_exit);
653
654     ret_val = _WinMain( argc, argv );
655
656     return ret_val;
657 }
658
659
660 /***********************************************************************
661  *           MessageBeep    (USER.104)
662  */
663 void MessageBeep(WORD i)
664 {
665         XBell(display, 100);
666 }
667
668
669 /***********************************************************************
670  *           Beep   (KERNEL32.11)
671  */
672 BOOL32 Beep( DWORD dwFreq, DWORD dwDur )
673 {
674     /* dwFreq and dwDur are ignored by Win95 */
675     XBell(display, 100);
676     return TRUE;
677 }
678
679
680 /***********************************************************************
681  *      GetVersion (KERNEL.3)
682  */
683 LONG GetVersion(void)
684 {
685     if (getVersion16) return getVersion16;
686     return MAKELONG( WINVERSION, WINDOSVER );
687 }
688
689
690 /***********************************************************************
691  *      GetVersion32
692  */
693 LONG GetVersion32(void)
694 {
695     if (getVersion32) return getVersion32;
696     return MAKELONG( 4, DOSVERSION);
697 }
698
699
700 /***********************************************************************
701  *      GetVersionExA
702  */
703 BOOL32 GetVersionEx32A(OSVERSIONINFO32A *v)
704 {
705     if(v->dwOSVersionInfoSize!=sizeof(OSVERSIONINFO32A))
706     {
707         fprintf(stddeb,"wrong OSVERSIONINFO size from app");
708         return FALSE;
709     }
710     if(!getVersion32)
711     {
712         /* Return something like NT 3.5 */
713         v->dwMajorVersion = 3;
714         v->dwMinorVersion = 5;
715         v->dwBuildNumber = 42;
716         v->dwPlatformId = VER_PLATFORM_WIN32_NT;
717         strcpy(v->szCSDVersion, "Wine is not an emulator");
718         return TRUE;
719     }
720     v->dwMajorVersion = getVersionEx.dwMajorVersion;
721     v->dwMinorVersion = getVersionEx.dwMinorVersion;
722     v->dwBuildNumber = getVersionEx.dwBuildNumber;
723     v->dwPlatformId = getVersionEx.dwPlatformId;
724     strcpy(v->szCSDVersion, getVersionEx.szCSDVersion);
725     return TRUE;
726 }
727
728
729 /***********************************************************************
730  *     GetVersionExW
731  */
732 BOOL32 GetVersionEx32W(OSVERSIONINFO32W *v)
733 {
734         OSVERSIONINFO32A v1;
735         if(v->dwOSVersionInfoSize!=sizeof(OSVERSIONINFO32W))
736         {
737                 fprintf(stddeb,"wrong OSVERSIONINFO size from app");
738                 return FALSE;
739         }
740         v1.dwOSVersionInfoSize=sizeof(v1);
741         GetVersionEx32A(&v1);
742         v->dwMajorVersion = v1.dwMajorVersion;
743         v->dwMinorVersion = v1.dwMinorVersion;
744         v->dwBuildNumber = v1.dwBuildNumber;
745         v->dwPlatformId = v1.dwPlatformId;
746         STRING32_AnsiToUni(v->szCSDVersion, v1.szCSDVersion);
747         return TRUE;
748 }
749
750 /***********************************************************************
751  *      GetWinFlags (KERNEL.132)
752  */
753 LONG GetWinFlags(void)
754 {
755   static const long cpuflags[5] =
756     { WF_CPU086, WF_CPU186, WF_CPU286, WF_CPU386, WF_CPU486 };
757
758   long result = 0;
759
760   /* There doesn't seem to be any Pentium flag.  */
761 #ifndef WINELIB
762   long cpuflag = cpuflags[MIN (runtime_cpu (), 4)];
763 #else
764   long cpuflag = cpuflags[4];
765 #endif
766
767   switch(Options.mode) {
768   case MODE_STANDARD:
769     result = (WF_STANDARD | cpuflag | WF_PMODE | WF_80x87);
770     break;
771
772   case MODE_ENHANCED:
773     result = (WF_ENHANCED | cpuflag | WF_PMODE | WF_80x87 | WF_PAGING);
774     break;
775
776   default:
777     fprintf(stderr, "Unknown mode set? This shouldn't happen. Check GetWinFlags()!\n");
778     break;
779   }
780
781   return result;
782 }
783
784 /***********************************************************************
785  *      SetEnvironment (GDI.132)
786  */
787 int SetEnvironment(LPCSTR lpPortName, LPCSTR lpEnviron, WORD nCount)
788 {
789     LPENVENTRY  lpNewEnv;
790     LPENVENTRY  lpEnv = lpEnvList;
791     dprintf_env(stddeb, "SetEnvironment('%s', '%s', %d) !\n", 
792                 lpPortName, lpEnviron, nCount);
793     if (lpPortName == NULL) return -1;
794     while (lpEnv != NULL) {
795         if (lpEnv->Name != NULL && strcmp(lpEnv->Name, lpPortName) == 0) {
796             if (nCount == 0 || lpEnviron == NULL) {
797                 if (lpEnv->Prev != NULL) lpEnv->Prev->Next = lpEnv->Next;
798                 if (lpEnv->Next != NULL) lpEnv->Next->Prev = lpEnv->Prev;
799                 free(lpEnv->Value);
800                 free(lpEnv->Name);
801                 free(lpEnv);
802                 dprintf_env(stddeb, "SetEnvironment() // entry deleted !\n");
803                 return -1;
804             }
805             free(lpEnv->Value);
806             lpEnv->Value = malloc(nCount);
807             if (lpEnv->Value == NULL) {
808                 dprintf_env(stddeb, "SetEnvironment() // Error allocating entry value !\n");
809                 return 0;
810             }
811             memcpy(lpEnv->Value, lpEnviron, nCount);
812             lpEnv->wSize = nCount;
813             dprintf_env(stddeb, "SetEnvironment() // entry modified !\n");
814             return nCount;
815         }
816         if (lpEnv->Next == NULL) break;
817         lpEnv = lpEnv->Next;
818     }
819     if (nCount == 0 || lpEnviron == NULL) return -1;
820     dprintf_env(stddeb, "SetEnvironment() // new entry !\n");
821     lpNewEnv = malloc(sizeof(ENVENTRY));
822     if (lpNewEnv == NULL) {
823         dprintf_env(stddeb, "SetEnvironment() // Error allocating new entry !\n");
824         return 0;
825     }
826     if (lpEnvList == NULL) {
827         lpEnvList = lpNewEnv;
828         lpNewEnv->Prev = NULL;
829     }
830     else 
831     {
832         lpEnv->Next = lpNewEnv;
833         lpNewEnv->Prev = lpEnv;
834     }
835     lpNewEnv->Next = NULL;
836     lpNewEnv->Name = malloc(strlen(lpPortName) + 1);
837     if (lpNewEnv->Name == NULL) {
838         dprintf_env(stddeb, "SetEnvironment() // Error allocating entry name !\n");
839         return 0;
840     }
841     strcpy(lpNewEnv->Name, lpPortName);
842     lpNewEnv->Value = malloc(nCount);
843     if (lpNewEnv->Value == NULL) {
844         dprintf_env(stddeb, "SetEnvironment() // Error allocating entry value !\n");
845         return 0;
846     }
847     memcpy(lpNewEnv->Value, lpEnviron, nCount);
848     lpNewEnv->wSize = nCount;
849     return nCount;
850 }
851
852
853 /***********************************************************************
854  *      SetEnvironmentVariable32A   (KERNEL32.484)
855  */
856 BOOL32 SetEnvironmentVariable32A( LPCSTR lpName, LPCSTR lpValue )
857 {
858     int rc;
859
860     rc = SetEnvironment(lpName, lpValue, strlen(lpValue) + 1);
861     return (rc > 0) ? 1 : 0;
862 }
863
864
865 /***********************************************************************
866  *      SetEnvironmentVariable32W   (KERNEL32.485)
867  */
868 BOOL32 SetEnvironmentVariable32W( LPCWSTR lpName, LPCWSTR lpValue )
869 {
870     LPSTR lpAName, lpAValue;
871     BOOL ret;
872
873     lpAName = STRING32_DupUniToAnsi( lpName );
874     lpAValue = STRING32_DupUniToAnsi ( lpValue );
875     ret = SetEnvironment(lpAName, lpAValue, strlen(lpAValue) + 1);
876     free (lpAName);
877     free (lpAValue);
878     return (ret > 0) ? 1 : 0;    
879 }
880
881
882 /***********************************************************************
883  *      GetEnvironment (GDI.134)
884  */
885 int GetEnvironment(LPSTR lpPortName, LPSTR lpEnviron, WORD nMaxSiz)
886 {
887     WORD       nCount;
888     LPENVENTRY lpEnv = lpEnvList;
889     dprintf_env(stddeb, "GetEnvironment('%s', '%s', %d) !\n",
890                 lpPortName, lpEnviron, nMaxSiz);
891     while (lpEnv != NULL) {
892         if (lpEnv->Name != NULL && strcmp(lpEnv->Name, lpPortName) == 0) {
893             nCount = MIN(nMaxSiz, lpEnv->wSize);
894             memcpy(lpEnviron, lpEnv->Value, nCount);
895             dprintf_env(stddeb, "GetEnvironment() // found '%s' !\n", lpEnviron);
896             return nCount;
897         }
898         lpEnv = lpEnv->Next;
899     }
900     dprintf_env(stddeb, "GetEnvironment() // not found !\n");
901     return 0;
902 }
903
904 /***********************************************************************
905  *      GetEnvironmentVariableA (KERNEL32.213)
906  */
907 DWORD GetEnvironmentVariableA(LPSTR lpName, LPSTR lpValue, DWORD size)
908 {
909     return GetEnvironment(lpName, lpValue, size);
910 }
911
912 /***********************************************************************
913  *      GetEnvironmentStrings (KERNEL32.210)
914  */
915 LPVOID GetEnvironmentStrings(void)
916 {
917     int count;
918     LPENVENTRY lpEnv;
919     char *envtable, *envptr;
920
921     /* Count the total number of bytes we'll need for the string
922      * table.  Include the trailing nuls and the final double nul.
923      */
924     count = 1;
925     lpEnv = lpEnvList;
926     while(lpEnv != NULL)
927     {
928         if(lpEnv->Name != NULL)
929         {
930             count += strlen(lpEnv->Name) + 1;
931             count += strlen(lpEnv->Value) + 1;
932         }
933         lpEnv = lpEnv->Next;
934     }
935
936     envtable = malloc(count);
937     if(envtable)
938     {
939         lpEnv = lpEnvList;
940         envptr = envtable;
941
942         while(lpEnv != NULL)
943         {
944             if(lpEnv->Name != NULL)
945             {
946                 count = sprintf(envptr, "%s=%s", lpEnv->Name, lpEnv->Value);
947                 envptr += count + 1;
948             }
949             lpEnv = lpEnv->Next;
950         }
951         *envptr = '\0';
952     }
953
954     return envtable;
955 }
956
957
958 LPVOID GetEnvironmentStringsW(void)
959 {
960     int count,len;
961     LPENVENTRY lpEnv;
962     char *envtable, *envptr;
963         WCHAR *wenvtable;
964
965     /* Count the total number of bytes we'll need for the string
966      * table.  Include the trailing nuls and the final double nul.
967      */
968     count = 1;
969     lpEnv = lpEnvList;
970     while(lpEnv != NULL)
971     {
972         if(lpEnv->Name != NULL)
973         {
974             count += strlen(lpEnv->Name) + 1;
975             count += strlen(lpEnv->Value) + 1;
976         }
977         lpEnv = lpEnv->Next;
978     }
979
980         len=count;
981     envtable = malloc(count);
982     if(envtable)
983     {
984         lpEnv = lpEnvList;
985         envptr = envtable;
986
987         while(lpEnv != NULL)
988         {
989             if(lpEnv->Name != NULL)
990             {
991                 count = sprintf(envptr, "%s=%s", lpEnv->Name, lpEnv->Value);
992                 envptr += count + 1;
993             }
994             lpEnv = lpEnv->Next;
995         }
996         *envptr = '\0';
997     }
998
999         wenvtable = malloc(2*len);
1000         for(count=0;count<len;count++)
1001                 wenvtable[count]=(WCHAR)envtable[count];
1002         free(envtable);
1003
1004     return envtable;
1005 }
1006
1007 void FreeEnvironmentStringsA(void *e)
1008 {
1009         free(e);
1010 }
1011
1012 void FreeEnvironmentStringsW(void* e)
1013 {
1014         free(e);
1015 }
1016
1017 /***********************************************************************
1018  *      GetTimerResolution (USER.14)
1019  */
1020 LONG GetTimerResolution(void)
1021 {
1022         return (1000);
1023 }
1024
1025 /***********************************************************************
1026  *      SystemParametersInfo (USER.483)
1027  */
1028 BOOL SystemParametersInfo (UINT uAction, UINT uParam, LPVOID lpvParam, UINT fuWinIni)
1029 {
1030         int timeout, temp;
1031         char buffer[256];
1032         XKeyboardState          keyboard_state;
1033         XKeyboardControl        keyboard_value;
1034
1035
1036         switch (uAction) {
1037                 case SPI_GETBEEP:
1038                         XGetKeyboardControl(display, &keyboard_state);
1039                         if (keyboard_state.bell_percent == 0)
1040                                 *(BOOL *) lpvParam = FALSE;
1041                         else
1042                                 *(BOOL *) lpvParam = TRUE;
1043                         break;
1044                 
1045                 case SPI_GETBORDER:
1046                         *(INT *)lpvParam = GetSystemMetrics( SM_CXFRAME );
1047                         break;
1048
1049                 case SPI_GETFASTTASKSWITCH:
1050                         *(BOOL *) lpvParam = FALSE;
1051                         /* FIXME GetProfileInt( "windows", "CoolSwitch", 1 ) */
1052                         break;
1053
1054                 case SPI_GETGRIDGRANULARITY:
1055                         *(INT *) lpvParam = 1;
1056                 /* FIXME GetProfileInt( "desktop", "GridGranularity", 1 ) */
1057                         break;
1058
1059                 case SPI_GETICONTITLEWRAP:
1060                         *(BOOL *) lpvParam = FALSE;
1061                         /* FIXME GetProfileInt( "desktop", "?", True ) */
1062                         break;
1063
1064                 case SPI_GETKEYBOARDDELAY:
1065                         *(INT *) lpvParam = 1;
1066                         /* FIXME */
1067                         break;
1068
1069                 case SPI_GETKEYBOARDSPEED:
1070                         *(WORD *) lpvParam = 30;
1071                         /* FIXME */
1072                         break;
1073
1074                 case SPI_GETMENUDROPALIGNMENT:
1075                         *(BOOL *) lpvParam = GetSystemMetrics( SM_MENUDROPALIGNMENT ); /* XXX check this */
1076                         break;
1077
1078                 case SPI_GETSCREENSAVEACTIVE:
1079                         /* FIXME GetProfileInt( "windows", "ScreenSaveActive", 1 ); */
1080                         *(BOOL *) lpvParam = FALSE;
1081                         break;
1082
1083                 case SPI_GETSCREENSAVETIMEOUT:
1084                         /* FIXME GetProfileInt( "windows", "ScreenSaveTimeout", 300 ); */
1085                         XGetScreenSaver(display, &timeout, &temp,&temp,&temp);
1086                         *(INT *) lpvParam = timeout * 1000;
1087                         break;
1088
1089                 case SPI_ICONHORIZONTALSPACING:
1090                         if (lpvParam == NULL)
1091                                 fprintf(stderr, "SystemParametersInfo: Horizontal icon spacing set to %d\n.", uParam);
1092                         else
1093                                 *(INT *) lpvParam = GetSystemMetrics( SM_CXICONSPACING );
1094                         break;
1095
1096                 case SPI_ICONVERTICALSPACING:
1097                         if (lpvParam == NULL)
1098                                 fprintf(stderr, "SystemParametersInfo: Vertical icon spacing set to %d\n.", uParam);
1099                         else
1100                                 *(INT *) lpvParam = GetSystemMetrics( SM_CYICONSPACING );
1101                         break;
1102
1103                 case SPI_SETBEEP:
1104                         if (uParam == TRUE)
1105                                 keyboard_value.bell_percent = -1;
1106                         else
1107                                 keyboard_value.bell_percent = 0;                        
1108                         XChangeKeyboardControl(display, KBBellPercent, 
1109                                                         &keyboard_value);
1110                         break;
1111
1112                 case SPI_SETSCREENSAVEACTIVE:
1113                         if (uParam == TRUE)
1114                                 XActivateScreenSaver(display);
1115                         else
1116                                 XResetScreenSaver(display);
1117                         break;
1118
1119                 case SPI_SETSCREENSAVETIMEOUT:
1120                         XSetScreenSaver(display, uParam, 60, DefaultBlanking, 
1121                                                 DefaultExposures);
1122                         break;
1123
1124                 case SPI_SETDESKWALLPAPER:
1125                         return (SetDeskWallPaper((LPSTR) lpvParam));
1126                         break;
1127
1128                 case SPI_SETDESKPATTERN:
1129                         if ((INT) uParam == -1) {
1130                                 GetProfileString("Desktop", "Pattern", 
1131                                                 "170 85 170 85 170 85 170 85", 
1132                                                 buffer, sizeof(buffer) );
1133                                 return (DESKTOP_SetPattern((LPSTR) buffer));
1134                         } else
1135                                 return (DESKTOP_SetPattern((LPSTR) lpvParam));
1136                         break;
1137
1138                 case SPI_GETICONTITLELOGFONT: 
1139                 {
1140                     /* FIXME GetProfileString( "?", "?", "?" ) */
1141                   LPLOGFONT16 lpLogFont = (LPLOGFONT16)lpvParam;
1142                   lpLogFont->lfHeight = 10;
1143                   lpLogFont->lfWidth = 0;
1144                   lpLogFont->lfEscapement = lpLogFont->lfOrientation = 0;
1145                   lpLogFont->lfWeight = FW_NORMAL;
1146                   lpLogFont->lfItalic = lpLogFont->lfStrikeOut = lpLogFont->lfUnderline = FALSE;
1147                   lpLogFont->lfCharSet = ANSI_CHARSET;
1148                   lpLogFont->lfOutPrecision = OUT_DEFAULT_PRECIS;
1149                   lpLogFont->lfClipPrecision = CLIP_DEFAULT_PRECIS;
1150                   lpLogFont->lfPitchAndFamily = DEFAULT_PITCH | FF_SWISS;
1151                   break;
1152                 }
1153                 case SPI_LANGDRIVER:
1154                 case SPI_SETBORDER:
1155                 case SPI_SETDOUBLECLKHEIGHT:
1156                 case SPI_SETDOUBLECLICKTIME:
1157                 case SPI_SETDOUBLECLKWIDTH:
1158                 case SPI_SETFASTTASKSWITCH:
1159                 case SPI_SETKEYBOARDDELAY:
1160                 case SPI_SETKEYBOARDSPEED:
1161                         fprintf(stderr, "SystemParametersInfo: option %d ignored.\n", uParam);
1162                         break;
1163
1164                 default:
1165                         fprintf(stderr, "SystemParametersInfo: unknown option %d.\n", uParam);
1166                         break;
1167         }
1168         return 1;
1169 }
1170
1171 /***********************************************************************
1172 *       COPY (GDI.250)
1173 */
1174 void Copy(LPVOID lpSource, LPVOID lpDest, WORD nBytes)
1175 {
1176         memcpy(lpDest, lpSource, nBytes);
1177 }
1178
1179 /***********************************************************************
1180 *       SWAPMOUSEBUTTON (USER.186)
1181 */
1182 BOOL SwapMouseButton(BOOL fSwap)
1183 {
1184         return 0;       /* don't swap */
1185 }
1186
1187 /***********************************************************************
1188 *       FileCDR (KERNEL.130)
1189 */
1190 void FileCDR(FARPROC16 x)
1191 {
1192         printf("FileCDR(%8x)\n", (int) x);
1193 }
1194
1195 /***********************************************************************
1196 *       GetWinDebugInfo (KERNEL.355)
1197 */
1198 BOOL GetWinDebugInfo(WINDEBUGINFO *lpwdi, UINT flags)
1199 {
1200         printf("GetWinDebugInfo(%8lx,%d) stub returning 0\n", (unsigned long)lpwdi, flags);
1201         /* 0 means not in debugging mode/version */
1202         /* Can this type of debugging be used in wine ? */
1203         /* Constants: WDI_OPTIONS WDI_FILTER WDI_ALLOCBREAK */
1204         return 0;
1205 }
1206
1207 /***********************************************************************
1208 *       GetWinDebugInfo (KERNEL.355)
1209 */
1210 BOOL SetWinDebugInfo(WINDEBUGINFO *lpwdi)
1211 {
1212         printf("SetWinDebugInfo(%8lx) stub returning 0\n", (unsigned long)lpwdi);
1213         /* 0 means not in debugging mode/version */
1214         /* Can this type of debugging be used in wine ? */
1215         /* Constants: WDI_OPTIONS WDI_FILTER WDI_ALLOCBREAK */
1216         return 0;
1217 }