]> git.mxchange.org Git - flightgear.git/blob - src/Main/options.cxx
Log options to INFO level when processing
[flightgear.git] / src / Main / options.cxx
1 // options.cxx -- class to handle command line options
2 //
3 // Written by Curtis Olson, started April 1998.
4 //
5 // Copyright (C) 1998  Curtis L. Olson  - http://www.flightgear.org/~curt
6 //
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
11 //
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 // General Public License for more details.
16 //
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
20 //
21 // $Id$
22
23
24 #ifdef HAVE_CONFIG_H
25 #  include <config.h>
26 #endif
27
28 #include <simgear/compiler.h>
29 #include <simgear/structure/exception.hxx>
30 #include <simgear/debug/logstream.hxx>
31 #include <simgear/timing/sg_time.hxx>
32 #include <simgear/misc/sg_dir.hxx>
33
34 #include <boost/foreach.hpp>
35
36 #include <cmath>        // rint()
37 #include <stdio.h>
38 #include <stdlib.h>     // atof(), atoi()
39 #include <string.h>     // strcmp()
40 #include <algorithm>
41
42 #include <iostream>
43 #include <string>
44 #include <sstream>
45
46 #include <simgear/math/sg_random.h>
47 #include <simgear/props/props_io.hxx>
48 #include <simgear/misc/sgstream.hxx>
49 #include <simgear/misc/sg_path.hxx>
50 #include <simgear/scene/material/mat.hxx>
51 #include <simgear/sound/soundmgr_openal.hxx>
52 #include <simgear/misc/strutils.hxx>
53 #include <Autopilot/route_mgr.hxx>
54 #include <Aircraft/replay.hxx>
55
56 #include <GUI/gui.h>
57 #include <GUI/MessageBox.hxx>
58 #if defined(HAVE_QT)
59 #include <GUI/QtLauncher.hxx>
60 #include <GUI/SetupRootDialog.hxx>
61 #endif
62
63 #include <Main/locale.hxx>
64 #include "globals.hxx"
65 #include "fg_init.hxx"
66 #include "fg_props.hxx"
67 #include "options.hxx"
68 #include "util.hxx"
69 #include "main.hxx"
70 #include "locale.hxx"
71 #include <Viewer/viewer.hxx>
72 #include <Viewer/viewmgr.hxx>
73 #include <Environment/presets.hxx>
74 #include <Network/http/httpd.hxx>
75 #include "AircraftDirVisitorBase.hxx"
76
77 #include <osg/Version>
78 #include <Include/version.h>
79 #include <simgear/version.h>
80
81 using std::string;
82 using std::sort;
83 using std::cout;
84 using std::cerr;
85 using std::endl;
86 using std::vector;
87 using std::cin;
88
89 using namespace flightgear;
90
91 #define NEW_DEFAULT_MODEL_HZ 120
92
93 static flightgear::Options* shared_instance = NULL;
94
95 static double
96 atof( const string& str )
97 {
98     return ::atof( str.c_str() );
99 }
100
101 static int
102 atoi( const string& str )
103 {
104     return ::atoi( str.c_str() );
105 }
106
107 static int fgSetupProxy( const char *arg );
108
109 /**
110  * Set a few fail-safe default property values.
111  *
112  * These should all be set in $FG_ROOT/preferences.xml, but just
113  * in case, we provide some initial sane values here. This method
114  * should be invoked *before* reading any init files.
115  */
116 void fgSetDefaults ()
117 {
118
119                                 // Position (deliberately out of range)
120     fgSetDouble("/position/longitude-deg", 9999.0);
121     fgSetDouble("/position/latitude-deg", 9999.0);
122     fgSetDouble("/position/altitude-ft", -9999.0);
123
124                                 // Orientation
125     fgSetDouble("/orientation/heading-deg", 9999.0);
126     fgSetDouble("/orientation/roll-deg", 0.0);
127     fgSetDouble("/orientation/pitch-deg", 0.424);
128
129                                 // Velocities
130     fgSetDouble("/velocities/uBody-fps", 0.0);
131     fgSetDouble("/velocities/vBody-fps", 0.0);
132     fgSetDouble("/velocities/wBody-fps", 0.0);
133     fgSetDouble("/velocities/speed-north-fps", 0.0);
134     fgSetDouble("/velocities/speed-east-fps", 0.0);
135     fgSetDouble("/velocities/speed-down-fps", 0.0);
136     fgSetDouble("/velocities/airspeed-kt", 0.0);
137     fgSetDouble("/velocities/mach", 0.0);
138
139                                 // Presets
140     fgSetDouble("/sim/presets/longitude-deg", 9999.0);
141     fgSetDouble("/sim/presets/latitude-deg", 9999.0);
142     fgSetDouble("/sim/presets/altitude-ft", -9999.0);
143
144     fgSetDouble("/sim/presets/heading-deg", 9999.0);
145     fgSetDouble("/sim/presets/roll-deg", 0.0);
146     fgSetDouble("/sim/presets/pitch-deg", 0.424);
147
148     fgSetString("/sim/presets/speed-set", "knots");
149     fgSetDouble("/sim/presets/airspeed-kt", 0.0);
150     fgSetDouble("/sim/presets/mach", 0.0);
151     fgSetDouble("/sim/presets/uBody-fps", 0.0);
152     fgSetDouble("/sim/presets/vBody-fps", 0.0);
153     fgSetDouble("/sim/presets/wBody-fps", 0.0);
154     fgSetDouble("/sim/presets/speed-north-fps", 0.0);
155     fgSetDouble("/sim/presets/speed-east-fps", 0.0);
156     fgSetDouble("/sim/presets/speed-down-fps", 0.0);
157
158     fgSetBool("/sim/presets/onground", true);
159     fgSetBool("/sim/presets/trim", false);
160
161                                 // Miscellaneous
162     fgSetBool("/sim/startup/splash-screen", true);
163     // we want mouse-pointer to have an undefined value if nothing is
164     // specified so we can do the right thing for voodoo-1/2 cards.
165     // fgSetString("/sim/startup/mouse-pointer", "disabled");
166     fgSetBool("/controls/flight/auto-coordination", false);
167     fgSetString("/sim/logging/priority", "alert");
168
169                                 // Features
170     fgSetBool("/sim/hud/color/antialiased", false);
171     fgSetBool("/sim/hud/enable3d[1]", true);
172     fgSetBool("/sim/hud/visibility[1]", false);
173     fgSetBool("/sim/panel/visibility", true);
174     fgSetBool("/sim/sound/enabled", true);
175     fgSetBool("/sim/sound/working", true);
176     fgSetBool("/sim/fgcom/enabled", false);
177
178                                 // Flight Model options
179     fgSetString("/sim/flight-model", "jsb");
180     fgSetString("/sim/aero", "c172");
181     fgSetInt("/sim/model-hz", NEW_DEFAULT_MODEL_HZ);
182     fgSetDouble("/sim/speed-up", 1.0);
183
184                                 // Rendering options
185     fgSetString("/sim/rendering/fog", "nicest");
186     fgSetBool("/environment/clouds/status", true);
187     fgSetBool("/sim/startup/fullscreen", false);
188     fgSetBool("/sim/rendering/shading", true);
189     fgTie( "/sim/rendering/filtering", SGGetTextureFilter, SGSetTextureFilter, false);
190     fgSetInt("/sim/rendering/filtering", 1);
191     fgSetBool("/sim/rendering/wireframe", false);
192     fgSetBool("/sim/rendering/horizon-effect", false);
193     fgSetBool("/sim/rendering/enhanced-lighting", false);
194     fgSetBool("/sim/rendering/distance-attenuation", false);
195     fgSetBool("/sim/rendering/specular-highlight", true);
196     fgSetString("/sim/rendering/materials-file", "materials.xml");
197     fgSetInt("/sim/startup/xsize", 1024);
198     fgSetInt("/sim/startup/ysize", 768);
199     fgSetInt("/sim/rendering/bits-per-pixel", 32);
200     fgSetString("/sim/view-mode", "pilot");
201     fgSetDouble("/sim/current-view/heading-offset-deg", 0);
202
203                                 // HUD options
204     fgSetString("/sim/startup/units", "feet");
205     fgSetString("/sim/hud/frame-stat-type", "tris");
206
207                                 // Time options
208     fgSetInt("/sim/startup/time-offset", 0);
209     fgSetString("/sim/startup/time-offset-type", "system-offset");
210     fgSetLong("/sim/time/cur-time-override", 0);
211
212                                 // Freeze options
213     fgSetBool("/sim/freeze/master", false);
214     fgSetBool("/sim/freeze/position", false);
215     fgSetBool("/sim/freeze/clock", false);
216     fgSetBool("/sim/freeze/fuel", false);
217
218     fgSetString("/sim/multiplay/callsign", "callsign");
219     fgSetString("/sim/multiplay/rxhost", "");
220     fgSetString("/sim/multiplay/txhost", "");
221     fgSetInt("/sim/multiplay/rxport", 0);
222     fgSetInt("/sim/multiplay/txport", 0);
223     
224     SGPropertyNode* v = globals->get_props()->getNode("/sim/version", true);
225     v->setValueReadOnly("flightgear", FLIGHTGEAR_VERSION);
226     v->setValueReadOnly("simgear", SG_STRINGIZE(SIMGEAR_VERSION));
227     v->setValueReadOnly("openscenegraph", osgGetVersion());
228     v->setValueReadOnly("openscenegraph-thread-safe-reference-counting",
229                          osg::Referenced::getThreadSafeReferenceCounting());
230     v->setValueReadOnly("revision", REVISION);
231     v->setValueReadOnly("build-number", HUDSON_BUILD_NUMBER);
232     v->setValueReadOnly("build-id", HUDSON_BUILD_ID);
233     v->setValueReadOnly("hla-support", bool(FG_HAVE_HLA));
234 #if defined(FG_NIGHTLY)
235     v->setValueReadOnly("nightly-build", true);
236 #else
237     v->setValueReadOnly("nightly-build", false);
238 #endif
239     
240     char* envp = ::getenv( "http_proxy" );
241     if( envp != NULL )
242       fgSetupProxy( envp );
243 }
244
245 ///////////////////////////////////////////////////////////////////////////////
246 // helper object to implement the --show-aircraft command.
247 // resides here so we can share the fgFindAircraftInDir template above,
248 // and hence ensure this command lists exectly the same aircraft as the normal
249 // loading path.
250 class ShowAircraft : public AircraftDirVistorBase
251 {
252 public:
253     ShowAircraft()
254     {
255         _minStatus = getNumMaturity(fgGetString("/sim/aircraft-min-status", "all"));
256     }
257     
258     
259     void show(const vector<SGPath> & path_list)
260     {
261                 for (vector<SGPath>::const_iterator p = path_list.begin();
262                          p != path_list.end(); ++p)
263                         visitDir(*p, 0);
264         
265         simgear::requestConsole(); // ensure console is shown on Windows
266         
267         std::sort(_aircraft.begin(), _aircraft.end(), ciLessLibC());
268         cout << "Available aircraft:" << endl;
269         for ( unsigned int i = 0; i < _aircraft.size(); i++ ) {
270             cout << _aircraft[i] << endl;
271         }
272     }
273     
274 private:
275     virtual VisitResult visit(const SGPath& path)
276     {
277         SGPropertyNode root;
278         try {
279             readProperties(path.str(), &root);
280         } catch (sg_exception& ) {
281             return VISIT_CONTINUE;
282         }
283         
284         int maturity = 0;
285         string descStr("   ");
286         descStr += path.file();
287         // trim common suffix from file names
288         int nPos = descStr.rfind("-set.xml");
289         if (nPos == (int)(descStr.size() - 8)) {
290             descStr.resize(nPos);
291         }
292         
293         SGPropertyNode *node = root.getNode("sim");
294         if (node) {
295             SGPropertyNode* desc = node->getNode("description");
296             // if a status tag is found, read it in
297             if (node->hasValue("status")) {
298                 maturity = getNumMaturity(node->getStringValue("status"));
299             }
300             
301             if (desc) {
302                 if (descStr.size() <= 27+3) {
303                     descStr.append(29+3-descStr.size(), ' ');
304                 } else {
305                     descStr += '\n';
306                     descStr.append( 32, ' ');
307                 }
308                 descStr += desc->getStringValue();
309             }
310         } // of have 'sim' node
311         
312         if (maturity >= _minStatus) {
313             _aircraft.push_back(descStr);
314         }
315         
316         return VISIT_CONTINUE;
317     }
318     
319     
320     int getNumMaturity(const char * str)
321     {
322         // changes should also be reflected in $FG_ROOT/data/options.xml &
323         // $FG_ROOT/data/Translations/string-default.xml
324         const char* levels[] = {"alpha","beta","early-production","production"};
325         
326         if (!strcmp(str, "all")) {
327             return 0;
328         }
329         
330         for (size_t i=0; i<(sizeof(levels)/sizeof(levels[0]));i++)
331             if (strcmp(str,levels[i])==0)
332                 return i;
333         
334         return 0;
335     }
336     
337     // recommended in Meyers, Effective STL when internationalization and embedded
338     // NULLs aren't an issue.  Much faster than the STL or Boost lex versions.
339     struct ciLessLibC : public std::binary_function<string, string, bool>
340     {
341         bool operator()(const std::string &lhs, const std::string &rhs) const
342         {
343             return strcasecmp(lhs.c_str(), rhs.c_str()) < 0 ? 1 : 0;
344         }
345     };
346     
347     int _minStatus;
348     string_list _aircraft;
349 };
350
351 /*
352  * Search in the current directory, and in on directory deeper
353  * for <aircraft>-set.xml configuration files and show the aircaft name
354  * and the contents of the<description> tag in a sorted manner.
355  *
356  * @parampath the directory to search for configuration files
357  */
358 void fgShowAircraft(const vector<SGPath> &path_list)
359 {
360     ShowAircraft s;
361     s.show(path_list);
362     
363 #ifdef _MSC_VER
364     cout << "Hit a key to continue..." << endl;
365     std::cin.get();
366 #endif
367 }
368
369
370 static bool
371 parse_wind (const string &wind, double * min_hdg, double * max_hdg,
372             double * speed, double * gust)
373 {
374   string::size_type pos = wind.find('@');
375   if (pos == string::npos)
376     return false;
377   string dir = wind.substr(0, pos);
378   string spd = wind.substr(pos+1);
379   pos = dir.find(':');
380   if (pos == string::npos) {
381     *min_hdg = *max_hdg = atof(dir.c_str());
382   } else {
383     *min_hdg = atof(dir.substr(0,pos).c_str());
384     *max_hdg = atof(dir.substr(pos+1).c_str());
385   }
386   pos = spd.find(':');
387   if (pos == string::npos) {
388     *speed = *gust = atof(spd.c_str());
389   } else {
390     *speed = atof(spd.substr(0,pos).c_str());
391     *gust = atof(spd.substr(pos+1).c_str());
392   }
393   return true;
394 }
395
396 static bool
397 parseIntValue(char** ppParserPos, int* pValue,int min, int max, const char* field, const char* argument)
398 {
399     if ( !strlen(*ppParserPos) )
400         return true;
401
402     char num[256];
403     int i = 0;
404
405     while ( isdigit((*ppParserPos)[0]) && (i<255) )
406     {
407         num[i] = (*ppParserPos)[0];
408         (*ppParserPos)++;
409         i++;
410     }
411     num[i] = '\0';
412
413     switch ((*ppParserPos)[0])
414     {
415         case 0:
416             break;
417         case ':':
418             (*ppParserPos)++;
419             break;
420         default:
421             SG_LOG(SG_GENERAL, SG_ALERT, "Illegal character in time string for " << field << ": '" <<
422                     (*ppParserPos)[0] << "'.");
423             // invalid field - skip rest of string to avoid further errors
424             while ((*ppParserPos)[0])
425                 (*ppParserPos)++;
426             return false;
427     }
428
429     if (i<=0)
430         return true;
431
432     int value = atoi(num);
433     if ((value < min)||(value > max))
434     {
435         SG_LOG(SG_GENERAL, SG_ALERT, "Invalid " << field << " in '" << argument <<
436                "'. Valid range is " << min << "-" << max << ".");
437         return false;
438     }
439     else
440     {
441         *pValue = value;
442         return true;
443     }
444 }
445
446 // parse a time string ([+/-]%f[:%f[:%f]]) into hours
447 static double
448 parse_time(const string& time_in) {
449     char *time_str, num[256];
450     double hours, minutes, seconds;
451     double result = 0.0;
452     int sign = 1;
453     int i;
454
455     time_str = (char *)time_in.c_str();
456
457     // printf("parse_time(): %s\n", time_str);
458
459     // check for sign
460     if ( strlen(time_str) ) {
461         if ( time_str[0] == '+' ) {
462             sign = 1;
463             time_str++;
464         } else if ( time_str[0] == '-' ) {
465             sign = -1;
466             time_str++;
467         }
468     }
469     // printf("sign = %d\n", sign);
470
471     // get hours
472     if ( strlen(time_str) ) {
473         i = 0;
474         while ( (time_str[0] != ':') && (time_str[0] != '\0') ) {
475             num[i] = time_str[0];
476             time_str++;
477             i++;
478         }
479         if ( time_str[0] == ':' ) {
480             time_str++;
481         }
482         num[i] = '\0';
483         hours = atof(num);
484         // printf("hours = %.2lf\n", hours);
485
486         result += hours;
487     }
488
489     // get minutes
490     if ( strlen(time_str) ) {
491         i = 0;
492         while ( (time_str[0] != ':') && (time_str[0] != '\0') ) {
493             num[i] = time_str[0];
494             time_str++;
495             i++;
496         }
497         if ( time_str[0] == ':' ) {
498             time_str++;
499         }
500         num[i] = '\0';
501         minutes = atof(num);
502         // printf("minutes = %.2lf\n", minutes);
503
504         result += minutes / 60.0;
505     }
506
507     // get seconds
508     if ( strlen(time_str) ) {
509         i = 0;
510         while ( (time_str[0] != ':') && (time_str[0] != '\0') ) {
511             num[i] = time_str[0];
512             time_str++;
513             i++;
514         }
515         num[i] = '\0';
516         seconds = atof(num);
517         // printf("seconds = %.2lf\n", seconds);
518
519         result += seconds / 3600.0;
520     }
521
522     SG_LOG( SG_GENERAL, SG_INFO, " parse_time() = " << sign * result );
523
524     return(sign * result);
525 }
526
527 // parse a date string (yyyy:mm:dd:hh:mm:ss) into a time_t (seconds)
528 static long int
529 parse_date( const string& date, const char* timeType)
530 {
531     struct tm gmt,*pCurrentTime;
532     int year,month,day,hour,minute,second;
533     char *argument, *date_str;
534
535     SGTime CurrentTime;
536     CurrentTime.update(SGGeod(),0,0);
537
538     // FIXME This should obtain system/aircraft/GMT time depending on timeType
539     pCurrentTime = CurrentTime.getGmt();
540
541     // initialize all fields with current time
542     year   = pCurrentTime->tm_year + 1900;
543     month  = pCurrentTime->tm_mon + 1;
544     day    = pCurrentTime->tm_mday;
545     hour   = pCurrentTime->tm_hour;
546     minute = pCurrentTime->tm_min;
547     second = pCurrentTime->tm_sec;
548
549     argument = (char *)date.c_str();
550     date_str = argument;
551
552     // start with parsing year
553     if (!strlen(date_str) ||
554         !parseIntValue(&date_str,&year,0,9999,"year",argument))
555     {
556         return -1;
557     }
558
559     if (year < 1970)
560     {
561         SG_LOG(SG_GENERAL, SG_ALERT, "Invalid year '" << year << "'. Use 1970 or later.");
562         return -1;
563     }
564
565     parseIntValue(&date_str, &month,  1, 12, "month",  argument);
566     parseIntValue(&date_str, &day,    1, 31, "day",    argument);
567     parseIntValue(&date_str, &hour,   0, 23, "hour",   argument);
568     parseIntValue(&date_str, &minute, 0, 59, "minute", argument);
569     parseIntValue(&date_str, &second, 0, 59, "second", argument);
570
571     gmt.tm_sec  = second;
572     gmt.tm_min  = minute;
573     gmt.tm_hour = hour;
574     gmt.tm_mday = day;
575     gmt.tm_mon  = month - 1;
576     gmt.tm_year = year -1900;
577     gmt.tm_isdst = 0; // ignore daylight savings time for the moment
578
579     time_t theTime = sgTimeGetGMT( gmt.tm_year, gmt.tm_mon, gmt.tm_mday,
580                                    gmt.tm_hour, gmt.tm_min, gmt.tm_sec );
581
582     SG_LOG(SG_GENERAL, SG_INFO, "Configuring startup time to " << ctime(&theTime));
583
584     return (theTime);
585 }
586
587
588 // parse angle in the form of [+/-]ddd:mm:ss into degrees
589 static double
590 parse_degree( const string& degree_str) {
591     double result = parse_time( degree_str );
592
593     // printf("Degree = %.4f\n", result);
594
595     return(result);
596 }
597
598
599 // parse time offset string into seconds
600 static long int
601 parse_time_offset( const string& time_str) {
602    long int result;
603
604     // printf("time offset = %s\n", time_str);
605
606 #ifdef HAVE_RINT
607     result = (int)rint(parse_time(time_str) * 3600.0);
608 #else
609     result = (int)(parse_time(time_str) * 3600.0);
610 #endif
611
612     // printf("parse_time_offset(): %d\n", result);
613
614     return( result );
615 }
616
617
618 // Parse --fov=x.xx type option
619 static double
620 parse_fov( const string& arg ) {
621     double fov = atof(arg);
622
623     if ( fov < FG_FOV_MIN ) { fov = FG_FOV_MIN; }
624     if ( fov > FG_FOV_MAX ) { fov = FG_FOV_MAX; }
625
626     fgSetDouble("/sim/view[0]/config/default-field-of-view-deg", fov);
627
628     // printf("parse_fov(): result = %.4f\n", fov);
629
630     return fov;
631 }
632
633
634 // Parse I/O channel option
635 //
636 // Format is "--protocol=medium,direction,hz,medium_options,..."
637 //
638 //   protocol = { native, nmea, garmin, AV400, AV400Sim, fgfs, rul, pve, etc. }
639 //   medium = { serial, socket, file, etc. }
640 //   direction = { in, out, bi }
641 //   hz = number of times to process channel per second (floating
642 //        point values are ok.
643 //
644 // Serial example "--nmea=serial,dir,hz,device,baud" where
645 //
646 //  device = OS device name of serial line to be open()'ed
647 //  baud = {300, 1200, 2400, ..., 230400}
648 //
649 // Socket exacmple "--native=socket,dir,hz,machine,port,style" where
650 //
651 //  machine = machine name or ip address if client (leave empty if server)
652 //  port = port, leave empty to let system choose
653 //  style = tcp or udp
654 //
655 // File example "--garmin=file,dir,hz,filename" where
656 //
657 //  filename = file system file name
658
659 static bool
660 add_channel( const string& type, const string& channel_str ) {
661     // This check is neccessary to prevent fgviewer from segfaulting when given
662     // weird options. (It doesn't run the full initailization)
663     if(!globals->get_channel_options_list())
664     {
665         SG_LOG(SG_GENERAL, SG_ALERT, "Option " << type << "=" << channel_str
666                                      << " ignored.");
667         return false;
668     }
669     SG_LOG(SG_GENERAL, SG_INFO, "Channel string = " << channel_str );
670     globals->get_channel_options_list()->push_back( type + "," + channel_str );
671     return true;
672 }
673
674 static void
675 clearLocation ()
676 {
677     fgSetString("/sim/presets/airport-id", "");
678     fgSetString("/sim/presets/vor-id", "");
679     fgSetString("/sim/presets/ndb-id", "");
680     fgSetString("/sim/presets/carrier", "");
681     fgSetString("/sim/presets/parkpos", "");
682     fgSetString("/sim/presets/fix", "");
683 }
684
685 static int
686 fgOptVOR( const char * arg )
687 {
688     clearLocation();
689     fgSetString("/sim/presets/vor-id", arg);
690     return FG_OPTIONS_OK;
691 }
692
693 static int
694 fgOptNDB( const char * arg )
695 {
696     clearLocation();
697     fgSetString("/sim/presets/ndb-id", arg);
698     return FG_OPTIONS_OK;
699 }
700
701 static int
702 fgOptCarrier( const char * arg )
703 {
704     clearLocation();
705     fgSetString("/sim/presets/carrier", arg);
706     return FG_OPTIONS_OK;
707 }
708
709 static int
710 fgOptParkpos( const char * arg )
711 {
712     fgSetString("/sim/presets/parkpos", arg);
713     return FG_OPTIONS_OK;
714 }
715
716 static int
717 fgOptFIX( const char * arg )
718 {
719     clearLocation();
720     fgSetString("/sim/presets/fix", arg);
721     return FG_OPTIONS_OK;
722 }
723
724 static int
725 fgOptLon( const char *arg )
726 {
727     clearLocation();
728     fgSetDouble("/sim/presets/longitude-deg", parse_degree( arg ));
729     fgSetDouble("/position/longitude-deg", parse_degree( arg ));
730     return FG_OPTIONS_OK;
731 }
732
733 static int
734 fgOptLat( const char *arg )
735 {
736     clearLocation();
737     fgSetDouble("/sim/presets/latitude-deg", parse_degree( arg ));
738     fgSetDouble("/position/latitude-deg", parse_degree( arg ));
739     return FG_OPTIONS_OK;
740 }
741
742 static int
743 fgOptAltitude( const char *arg )
744 {
745     fgSetBool("/sim/presets/onground", false);
746     if ( !strcmp(fgGetString("/sim/startup/units"), "feet") )
747         fgSetDouble("/sim/presets/altitude-ft", atof( arg ));
748     else
749         fgSetDouble("/sim/presets/altitude-ft",
750                     atof( arg ) * SG_METER_TO_FEET);
751     return FG_OPTIONS_OK;
752 }
753
754 static int
755 fgOptUBody( const char *arg )
756 {
757     fgSetString("/sim/presets/speed-set", "UVW");
758     if ( !strcmp(fgGetString("/sim/startup/units"), "feet") )
759         fgSetDouble("/sim/presets/uBody-fps", atof( arg ));
760     else
761         fgSetDouble("/sim/presets/uBody-fps",
762                     atof( arg ) * SG_METER_TO_FEET);
763     return FG_OPTIONS_OK;
764 }
765
766 static int
767 fgOptVBody( const char *arg )
768 {
769     fgSetString("/sim/presets/speed-set", "UVW");
770     if ( !strcmp(fgGetString("/sim/startup/units"), "feet") )
771         fgSetDouble("/sim/presets/vBody-fps", atof( arg ));
772     else
773         fgSetDouble("/sim/presets/vBody-fps",
774                             atof( arg ) * SG_METER_TO_FEET);
775     return FG_OPTIONS_OK;
776 }
777
778 static int
779 fgOptWBody( const char *arg )
780 {
781     fgSetString("/sim/presets/speed-set", "UVW");
782     if ( !strcmp(fgGetString("/sim/startup/units"), "feet") )
783         fgSetDouble("/sim/presets/wBody-fps", atof(arg));
784     else
785         fgSetDouble("/sim/presets/wBody-fps",
786                             atof(arg) * SG_METER_TO_FEET);
787     return FG_OPTIONS_OK;
788 }
789
790 static int
791 fgOptVNorth( const char *arg )
792 {
793     fgSetString("/sim/presets/speed-set", "NED");
794     if ( !strcmp(fgGetString("/sim/startup/units"), "feet") )
795         fgSetDouble("/sim/presets/speed-north-fps", atof( arg ));
796     else
797         fgSetDouble("/sim/presets/speed-north-fps",
798                             atof( arg ) * SG_METER_TO_FEET);
799     return FG_OPTIONS_OK;
800 }
801
802 static int
803 fgOptVEast( const char *arg )
804 {
805     fgSetString("/sim/presets/speed-set", "NED");
806     if ( !strcmp(fgGetString("/sim/startup/units"), "feet") )
807         fgSetDouble("/sim/presets/speed-east-fps", atof(arg));
808     else
809         fgSetDouble("/sim/presets/speed-east-fps",
810                     atof(arg) * SG_METER_TO_FEET);
811     return FG_OPTIONS_OK;
812 }
813
814 static int
815 fgOptVDown( const char *arg )
816 {
817     fgSetString("/sim/presets/speed-set", "NED");
818     if ( !strcmp(fgGetString("/sim/startup/units"), "feet") )
819         fgSetDouble("/sim/presets/speed-down-fps", atof(arg));
820     else
821         fgSetDouble("/sim/presets/speed-down-fps",
822                             atof(arg) * SG_METER_TO_FEET);
823     return FG_OPTIONS_OK;
824 }
825
826 static int
827 fgOptVc( const char *arg )
828 {
829     // fgSetString("/sim/presets/speed-set", "knots");
830     // fgSetDouble("/velocities/airspeed-kt", atof(arg.substr(5)));
831     fgSetString("/sim/presets/speed-set", "knots");
832     fgSetDouble("/sim/presets/airspeed-kt", atof(arg));
833     return FG_OPTIONS_OK;
834 }
835
836 static int
837 fgOptMach( const char *arg )
838 {
839     fgSetString("/sim/presets/speed-set", "mach");
840     fgSetDouble("/sim/presets/mach", atof(arg));
841     return FG_OPTIONS_OK;
842 }
843
844 static int
845 fgOptRoc( const char *arg )
846 {
847     fgSetDouble("/sim/presets/vertical-speed-fps", atof(arg)/60);
848     return FG_OPTIONS_OK;
849 }
850
851 static int
852 fgOptFgScenery( const char *arg )
853 {
854     globals->append_fg_scenery(arg, true);
855     return FG_OPTIONS_OK;
856 }
857
858 static int
859 fgOptFov( const char *arg )
860 {
861     parse_fov( arg );
862     return FG_OPTIONS_OK;
863 }
864
865 static int
866 fgOptGeometry( const char *arg )
867 {
868     bool geometry_ok = true;
869     int xsize = 0, ysize = 0;
870     string geometry = arg;
871     string::size_type i = geometry.find('x');
872
873     if (i != string::npos) {
874         xsize = atoi(geometry.substr(0, i));
875         ysize = atoi(geometry.substr(i+1));
876     } else {
877         geometry_ok = false;
878     }
879
880     if ( xsize <= 0 || ysize <= 0 ) {
881         xsize = 640;
882         ysize = 480;
883         geometry_ok = false;
884     }
885
886     if ( !geometry_ok ) {
887         SG_LOG( SG_GENERAL, SG_ALERT, "Unknown geometry: " << geometry );
888         SG_LOG( SG_GENERAL, SG_ALERT,
889                 "Setting geometry to " << xsize << 'x' << ysize << '\n');
890     } else {
891         SG_LOG( SG_GENERAL, SG_INFO,
892                 "Setting geometry to " << xsize << 'x' << ysize << '\n');
893         fgSetInt("/sim/startup/xsize", xsize);
894         fgSetInt("/sim/startup/ysize", ysize);
895     }
896     return FG_OPTIONS_OK;
897 }
898
899 static int
900 fgOptBpp( const char *arg )
901 {
902     string bits_per_pix = arg;
903     if ( bits_per_pix == "16" ) {
904         fgSetInt("/sim/rendering/bits-per-pixel", 16);
905     } else if ( bits_per_pix == "24" ) {
906         fgSetInt("/sim/rendering/bits-per-pixel", 24);
907     } else if ( bits_per_pix == "32" ) {
908         fgSetInt("/sim/rendering/bits-per-pixel", 32);
909     } else {
910         SG_LOG(SG_GENERAL, SG_ALERT, "Unsupported bpp " << bits_per_pix);
911     }
912     return FG_OPTIONS_OK;
913 }
914
915 static int
916 fgOptTimeOffset( const char *arg )
917 {
918     fgSetLong("/sim/startup/time-offset",
919                 parse_time_offset( arg ));
920     fgSetString("/sim/startup/time-offset-type", "system-offset");
921     return FG_OPTIONS_OK;
922 }
923
924 static int
925 fgOptStartDateSys( const char *arg )
926 {
927     long int theTime = parse_date( arg, "system" );
928     if (theTime>=0)
929     {
930         fgSetLong("/sim/startup/time-offset",  theTime);
931         fgSetString("/sim/startup/time-offset-type", "system");
932     }
933     return FG_OPTIONS_OK;
934 }
935
936 static int
937 fgOptStartDateLat( const char *arg )
938 {
939     long int theTime = parse_date( arg, "latitude" );
940     if (theTime>=0)
941     {
942         fgSetLong("/sim/startup/time-offset", theTime);
943         fgSetString("/sim/startup/time-offset-type", "latitude");
944     }
945     return FG_OPTIONS_OK;
946 }
947
948 static int
949 fgOptStartDateGmt( const char *arg )
950 {
951     long int theTime = parse_date( arg, "gmt" );
952     if (theTime>=0)
953     {
954         fgSetLong("/sim/startup/time-offset", theTime);
955         fgSetString("/sim/startup/time-offset-type", "gmt");
956     }
957     return FG_OPTIONS_OK;
958 }
959
960 static int
961 fgOptJpgHttpd( const char * arg )
962 {
963   SG_LOG(SG_ALL,SG_ALERT,
964    "the option --jpg-httpd is no longer supported! Please use --httpd instead."
965    " URL for the screenshot within the new httpd is http://YourFgServer:xxxx/screenshot");
966   return FG_OPTIONS_EXIT;
967 }
968
969 static int
970 fgOptHttpd( const char * arg )
971 {
972     // port may be any valid address:port notation
973     // like 127.0.0.1:8080
974     // or just the port 8080
975     string port = simgear::strutils::strip(string(arg));
976     if( port.empty() ) return FG_OPTIONS_ERROR;
977     fgSetString( string(flightgear::http::PROPERTY_ROOT).append("/options/listening-port").c_str(), port );
978     return FG_OPTIONS_OK;
979 }
980
981 static int
982 fgSetupProxy( const char *arg )
983 {
984     string options = simgear::strutils::strip( arg );
985     string host, port, auth;
986     string::size_type pos;
987
988     // this is NURLP - NURLP is not an url parser
989     if( simgear::strutils::starts_with( options, "http://" ) )
990         options = options.substr( 7 );
991     if( simgear::strutils::ends_with( options, "/" ) )
992         options = options.substr( 0, options.length() - 1 );
993
994     host = port = auth = "";
995     if ((pos = options.find("@")) != string::npos)
996         auth = options.substr(0, pos++);
997     else
998         pos = 0;
999
1000     host = options.substr(pos, options.size());
1001     if ((pos = host.find(":")) != string::npos) {
1002         port = host.substr(++pos, host.size());
1003         host.erase(--pos, host.size());
1004     }
1005
1006     fgSetString("/sim/presets/proxy/host", host.c_str());
1007     fgSetString("/sim/presets/proxy/port", port.c_str());
1008     fgSetString("/sim/presets/proxy/authentication", auth.c_str());
1009
1010     return FG_OPTIONS_OK;
1011 }
1012
1013 static int
1014 fgOptTraceRead( const char *arg )
1015 {
1016     string name = arg;
1017     SG_LOG(SG_GENERAL, SG_INFO, "Tracing reads for property " << name);
1018     fgGetNode(name.c_str(), true)
1019         ->setAttribute(SGPropertyNode::TRACE_READ, true);
1020     return FG_OPTIONS_OK;
1021 }
1022
1023 static int
1024 fgOptLogLevel( const char *arg )
1025 {
1026     fgSetString("/sim/logging/priority", arg);
1027     setLoggingPriority(arg);
1028
1029     return FG_OPTIONS_OK;
1030 }
1031
1032 static int
1033 fgOptLogClasses( const char *arg )
1034 {
1035     fgSetString("/sim/logging/classes", arg);
1036     setLoggingClasses (arg);
1037
1038     return FG_OPTIONS_OK;
1039 }
1040
1041 static int
1042 fgOptTraceWrite( const char *arg )
1043 {
1044     string name = arg;
1045     SG_LOG(SG_GENERAL, SG_INFO, "Tracing writes for property " << name);
1046     fgGetNode(name.c_str(), true)
1047         ->setAttribute(SGPropertyNode::TRACE_WRITE, true);
1048     return FG_OPTIONS_OK;
1049 }
1050
1051 static int
1052 fgOptViewOffset( const char *arg )
1053 {
1054     // $$$ begin - added VS Renganathan, 14 Oct 2K
1055     // for multi-window outside window imagery
1056     string woffset = arg;
1057     double default_view_offset = 0.0;
1058     if ( woffset == "LEFT" ) {
1059             default_view_offset = SGD_PI * 0.25;
1060     } else if ( woffset == "RIGHT" ) {
1061         default_view_offset = SGD_PI * 1.75;
1062     } else if ( woffset == "CENTER" ) {
1063         default_view_offset = 0.00;
1064     } else {
1065         default_view_offset = atof( woffset.c_str() ) * SGD_DEGREES_TO_RADIANS;
1066     }
1067     /* apparently not used (CLO, 11 Jun 2002)
1068         FGViewer *pilot_view =
1069             (FGViewer *)globals->get_viewmgr()->get_view( 0 ); */
1070     // this will work without calls to the viewer...
1071     fgSetDouble( "/sim/current-view/heading-offset-deg",
1072                     default_view_offset  * SGD_RADIANS_TO_DEGREES );
1073     // $$$ end - added VS Renganathan, 14 Oct 2K
1074     return FG_OPTIONS_OK;
1075 }
1076
1077 static int
1078 fgOptVisibilityMeters( const char *arg )
1079 {
1080     Environment::Presets::VisibilitySingleton::instance()->preset( atof( arg ) );
1081     return FG_OPTIONS_OK;
1082 }
1083
1084 static int
1085 fgOptVisibilityMiles( const char *arg )
1086 {
1087     Environment::Presets::VisibilitySingleton::instance()->preset( atof( arg ) * 5280.0 * SG_FEET_TO_METER );
1088     return FG_OPTIONS_OK;
1089 }
1090
1091 static int
1092 fgOptRandomWind( const char *arg )
1093 {
1094     double min_hdg = sg_random() * 360.0;
1095     double max_hdg = min_hdg + (20 - sqrt(sg_random() * 400));
1096     double speed = sg_random() * sg_random() * 40;
1097     double gust = speed + (10 - sqrt(sg_random() * 100));
1098     Environment::Presets::WindSingleton::instance()->preset(min_hdg, max_hdg, speed, gust);
1099     return FG_OPTIONS_OK;
1100 }
1101
1102 static int
1103 fgOptWind( const char *arg )
1104 {
1105     double min_hdg = 0.0, max_hdg = 0.0, speed = 0.0, gust = 0.0;
1106     if (!parse_wind( arg, &min_hdg, &max_hdg, &speed, &gust)) {
1107         SG_LOG( SG_GENERAL, SG_ALERT, "bad wind value " << arg );
1108         return FG_OPTIONS_ERROR;
1109     }
1110     Environment::Presets::WindSingleton::instance()->preset(min_hdg, max_hdg, speed, gust);
1111     return FG_OPTIONS_OK;
1112 }
1113
1114 static int
1115 fgOptTurbulence( const char *arg )
1116 {
1117     Environment::Presets::TurbulenceSingleton::instance()->preset( atof(arg) );
1118     return FG_OPTIONS_OK;
1119 }
1120
1121 static int
1122 fgOptCeiling( const char *arg )
1123 {
1124     double elevation, thickness;
1125     string spec = arg;
1126     string::size_type pos = spec.find(':');
1127     if (pos == string::npos) {
1128         elevation = atof(spec.c_str());
1129         thickness = 2000;
1130     } else {
1131         elevation = atof(spec.substr(0, pos).c_str());
1132         thickness = atof(spec.substr(pos + 1).c_str());
1133     }
1134     Environment::Presets::CeilingSingleton::instance()->preset( elevation, thickness );
1135     return FG_OPTIONS_OK;
1136 }
1137
1138 static int
1139 fgOptWp( const char *arg )
1140 {
1141     string_list *waypoints = globals->get_initial_waypoints();
1142     if (!waypoints) {
1143         waypoints = new string_list;
1144         globals->set_initial_waypoints(waypoints);
1145     }
1146     waypoints->push_back(arg);
1147     return FG_OPTIONS_OK;
1148 }
1149
1150 static int
1151 fgOptConfig( const char *arg )
1152 {
1153     string file = arg;
1154     try {
1155         readProperties(file, globals->get_props());
1156     } catch (const sg_exception &e) {
1157         string message = "Error loading config file: ";
1158         message += e.getFormattedMessage() + e.getOrigin();
1159         SG_LOG(SG_INPUT, SG_ALERT, message);
1160         return FG_OPTIONS_ERROR;
1161     }
1162     return FG_OPTIONS_OK;
1163 }
1164
1165 static bool
1166 parse_colon (const string &s, double * val1, double * val2)
1167 {
1168     string::size_type pos = s.find(':');
1169     if (pos == string::npos) {
1170         *val2 = atof(s);
1171         return false;
1172     } else {
1173         *val1 = atof(s.substr(0, pos).c_str());
1174         *val2 = atof(s.substr(pos+1).c_str());
1175         return true;
1176     }
1177 }
1178
1179
1180 static int
1181 fgOptFailure( const char * arg )
1182 {
1183     string a = arg;
1184     if (a == "pitot") {
1185         fgSetBool("/systems/pitot/serviceable", false);
1186     } else if (a == "static") {
1187         fgSetBool("/systems/static/serviceable", false);
1188     } else if (a == "vacuum") {
1189         fgSetBool("/systems/vacuum/serviceable", false);
1190     } else if (a == "electrical") {
1191         fgSetBool("/systems/electrical/serviceable", false);
1192     } else {
1193         SG_LOG(SG_INPUT, SG_ALERT, "Unknown failure mode: " << a);
1194         return FG_OPTIONS_ERROR;
1195     }
1196
1197     return FG_OPTIONS_OK;
1198 }
1199
1200
1201 static int
1202 fgOptNAV1( const char * arg )
1203 {
1204     double radial, freq;
1205     if (parse_colon(arg, &radial, &freq))
1206         fgSetDouble("/instrumentation/nav[0]/radials/selected-deg", radial);
1207     fgSetDouble("/instrumentation/nav[0]/frequencies/selected-mhz", freq);
1208     return FG_OPTIONS_OK;
1209 }
1210
1211 static int
1212 fgOptNAV2( const char * arg )
1213 {
1214     double radial, freq;
1215     if (parse_colon(arg, &radial, &freq))
1216         fgSetDouble("/instrumentation/nav[1]/radials/selected-deg", radial);
1217     fgSetDouble("/instrumentation/nav[1]/frequencies/selected-mhz", freq);
1218     return FG_OPTIONS_OK;
1219 }
1220
1221 static int
1222 fgOptADF1( const char * arg )
1223 {
1224     double rot, freq;
1225     if (parse_colon(arg, &rot, &freq))
1226         fgSetDouble("/instrumentation/adf[0]/rotation-deg", rot);
1227     fgSetDouble("/instrumentation/adf[0]/frequencies/selected-khz", freq);
1228     return FG_OPTIONS_OK;
1229 }
1230
1231 static int
1232 fgOptADF2( const char * arg )
1233 {
1234     double rot, freq;
1235     if (parse_colon(arg, &rot, &freq))
1236         fgSetDouble("/instrumentation/adf[1]/rotation-deg", rot);
1237     fgSetDouble("/instrumentation/adf[1]/frequencies/selected-khz", freq);
1238     return FG_OPTIONS_OK;
1239 }
1240
1241 static int
1242 fgOptDME( const char *arg )
1243 {
1244     string opt = arg;
1245     if (opt == "nav1") {
1246         fgSetInt("/instrumentation/dme/switch-position", 1);
1247         fgSetString("/instrumentation/dme/frequencies/source",
1248                     "/instrumentation/nav[0]/frequencies/selected-mhz");
1249     } else if (opt == "nav2") {
1250         fgSetInt("/instrumentation/dme/switch-position", 3);
1251         fgSetString("/instrumentation/dme/frequencies/source",
1252                     "/instrumentation/nav[1]/frequencies/selected-mhz");
1253     } else {
1254         double frequency = atof(arg);
1255         if (frequency==0.0)
1256         {
1257             SG_LOG(SG_INPUT, SG_ALERT, "Invalid DME frequency: '" << arg << "'.");
1258             return FG_OPTIONS_ERROR;
1259         }
1260         fgSetInt("/instrumentation/dme/switch-position", 2);
1261         fgSetString("/instrumentation/dme/frequencies/source",
1262                     "/instrumentation/dme/frequencies/selected-mhz");
1263         fgSetDouble("/instrumentation/dme/frequencies/selected-mhz", frequency);
1264     }
1265     return FG_OPTIONS_OK;
1266 }
1267
1268 static int
1269 fgOptLivery( const char *arg )
1270 {
1271     string opt = arg;
1272     string livery_path = "livery/" + opt;
1273     fgSetString("/sim/model/texture-path", livery_path.c_str() );
1274     return FG_OPTIONS_OK;
1275 }
1276
1277 static int
1278 fgOptScenario( const char *arg )
1279 {
1280     SGPropertyNode_ptr ai_node = fgGetNode( "/sim/ai", true );
1281     vector<SGPropertyNode_ptr> scenarii = ai_node->getChildren( "scenario" );
1282     int index = -1;
1283     for ( size_t i = 0; i < scenarii.size(); ++i ) {
1284         int ind = scenarii[i]->getIndex();
1285         if ( index < ind ) {
1286             index = ind;
1287         }
1288     }
1289     SGPropertyNode_ptr scenario = ai_node->getNode( "scenario", index + 1, true );
1290     scenario->setStringValue( arg );
1291     return FG_OPTIONS_OK;
1292 }
1293
1294 static int
1295 fgOptRunway( const char *arg )
1296 {
1297     fgSetString("/sim/presets/runway", arg );
1298     fgSetBool("/sim/presets/runway-requested", true );
1299     return FG_OPTIONS_OK;
1300 }
1301
1302 static int
1303 fgOptParking( const char *arg )
1304 {
1305     cerr << "Processing argument " << arg << endl;
1306     fgSetString("/sim/presets/parking", arg );
1307     fgSetBool  ("/sim/presets/parking-requested", true );
1308     return FG_OPTIONS_OK;
1309 }
1310
1311 static int
1312 fgOptVersion( const char *arg )
1313 {
1314     cerr << "FlightGear version: " << FLIGHTGEAR_VERSION << endl;
1315     cerr << "Revision: " << REVISION << endl;
1316     cerr << "Build-Id: " << HUDSON_BUILD_ID << endl;
1317     cerr << "FG_ROOT=" << globals->get_fg_root() << endl;
1318     cerr << "FG_HOME=" << globals->get_fg_home() << endl;
1319     cerr << "FG_SCENERY=";
1320
1321     int didsome = 0;
1322     string_list scn = globals->get_fg_scenery();
1323     for (string_list::const_iterator it = scn.begin(); it != scn.end(); it++)
1324     {
1325         if (didsome) cerr << ":";
1326         didsome++;
1327         cerr << *it;
1328     }
1329     cerr << endl;
1330     cerr << "SimGear version: " << SG_STRINGIZE(SIMGEAR_VERSION) << endl;
1331     cerr << "OSG version: " << osgGetVersion() << endl;
1332     cerr << "PLIB version: " << PLIB_VERSION << endl;
1333     return FG_OPTIONS_EXIT;
1334 }
1335
1336 static int
1337 fgOptCallSign(const char * arg)
1338 {
1339     int i;
1340     char callsign[11];
1341     strncpy(callsign,arg,10);
1342     callsign[10]=0;
1343     for (i=0;callsign[i];i++)
1344     {
1345         char c = callsign[i];
1346         if (c >= 'A' && c <= 'Z') continue;
1347         if (c >= 'a' && c <= 'z') continue;
1348         if (c >= '0' && c <= '9') continue;
1349         if (c == '-' || c == '_') continue;
1350         // convert any other illegal characters
1351         callsign[i]='-';
1352     }
1353     fgSetString("sim/multiplay/callsign", callsign );
1354     return FG_OPTIONS_OK;
1355 }
1356
1357 static int
1358 fgOptIgnoreAutosave(const char* arg)
1359 {
1360     fgSetBool("/sim/startup/ignore-autosave", true);
1361     // don't overwrite autosave on exit
1362     fgSetBool("/sim/startup/save-on-exit", false);
1363     return FG_OPTIONS_OK;
1364 }
1365
1366 static int
1367 fgOptEnableFreeze(const char* arg)
1368 {
1369     fgSetBool("/sim/freeze/master", true);
1370     fgSetBool("/sim/freeze/clock", true);
1371     return FG_OPTIONS_OK;
1372 }
1373
1374 static int
1375 fgOptDisableFreeze(const char* arg)
1376 {
1377     fgSetBool("/sim/freeze/master", false);
1378     fgSetBool("/sim/freeze/clock", false);
1379     return FG_OPTIONS_OK;
1380 }
1381
1382 // Set a property for the --prop: option. Syntax: --prop:[<type>:]<name>=<value>
1383 // <type> can be "double" etc. but also only the first letter "d".
1384 // Examples:  --prop:alpha=1  --prop:bool:beta=true  --prop:d:gamma=0.123
1385 static int
1386 fgOptSetProperty(const char* raw)
1387 {
1388   string arg(raw);
1389   string::size_type pos = arg.find('=');
1390   if (pos == arg.npos || pos == 0 || pos + 1 == arg.size())
1391     return FG_OPTIONS_ERROR;
1392   
1393   string name = arg.substr(0, pos);
1394   string value = arg.substr(pos + 1);
1395   string type;
1396   pos = name.find(':');
1397   
1398   if (pos != name.npos && pos != 0 && pos + 1 != name.size()) {
1399     type = name.substr(0, pos);
1400     name = name.substr(pos + 1);
1401   }
1402   SGPropertyNode *n = fgGetNode(name.c_str(), true);
1403   
1404   bool writable = n->getAttribute(SGPropertyNode::WRITE);
1405   if (!writable)
1406     n->setAttribute(SGPropertyNode::WRITE, true);
1407   
1408   bool ret = false;
1409   if (type.empty())
1410     ret = n->setUnspecifiedValue(value.c_str());
1411   else if (type == "s" || type == "string")
1412     ret = n->setStringValue(value.c_str());
1413   else if (type == "d" || type == "double")
1414     ret = n->setDoubleValue(strtod(value.c_str(), 0));
1415   else if (type == "f" || type == "float")
1416     ret = n->setFloatValue(atof(value.c_str()));
1417   else if (type == "l" || type == "long")
1418     ret =  n->setLongValue(strtol(value.c_str(), 0, 0));
1419   else if (type == "i" || type == "int")
1420     ret =  n->setIntValue(atoi(value.c_str()));
1421   else if (type == "b" || type == "bool")
1422     ret =  n->setBoolValue(value == "true" || atoi(value.c_str()) != 0);
1423   
1424   if (!writable)
1425     n->setAttribute(SGPropertyNode::WRITE, false);
1426   return ret ? FG_OPTIONS_OK : FG_OPTIONS_ERROR;
1427 }
1428
1429 static int
1430 fgOptLoadTape(const char* arg)
1431 {
1432   // load a flight recorder tape but wait until the fdm is initialized
1433   class DelayedTapeLoader : SGPropertyChangeListener {
1434   public:
1435     DelayedTapeLoader( const char * tape ) :
1436       _tape(tape)
1437     {
1438       SGPropertyNode_ptr n = fgGetNode("/sim/signals/fdm-initialized", true);
1439       n->addChangeListener( this );
1440     }
1441
1442     virtual ~ DelayedTapeLoader() {}
1443
1444     virtual void valueChanged(SGPropertyNode * node)
1445     {
1446       node->removeChangeListener( this );
1447
1448       // tell the replay subsystem to load the tape
1449       FGReplay* replay = (FGReplay*) globals->get_subsystem("replay");
1450       SGPropertyNode_ptr arg = new SGPropertyNode();
1451       arg->setStringValue("tape", _tape );
1452       arg->setBoolValue( "same-aircraft", 0 );
1453       replay->loadTape(arg);
1454
1455       delete this; // commence suicide
1456     }
1457   private:
1458     std::string _tape;
1459
1460   };
1461
1462   new DelayedTapeLoader(arg);
1463   return FG_OPTIONS_OK;
1464 }
1465
1466
1467
1468 /*
1469    option       has_param type        property         b_param s_param  func
1470
1471 where:
1472  option    : name of the option
1473  has_param : option is --name=value if true or --name if false
1474  type      : OPTION_BOOL    - property is a boolean
1475              OPTION_STRING  - property is a string
1476              OPTION_DOUBLE  - property is a double
1477              OPTION_INT     - property is an integer
1478              OPTION_CHANNEL - name of option is the name of a channel
1479              OPTION_FUNC    - the option trigger a function
1480  b_param   : if type==OPTION_BOOL,
1481              value set to the property (has_param is false for boolean)
1482  s_param   : if type==OPTION_STRING,
1483              value set to the property if has_param is false
1484  func      : function called if type==OPTION_FUNC. if has_param is true,
1485              the value is passed to the function as a string, otherwise,
1486              s_param is passed.
1487
1488     For OPTION_DOUBLE and OPTION_INT, the parameter value is converted into a
1489     double or an integer and set to the property.
1490
1491     For OPTION_CHANNEL, add_channel is called with the parameter value as the
1492     argument.
1493 */
1494
1495 enum OptionType { OPTION_BOOL = 0, OPTION_STRING, OPTION_DOUBLE, OPTION_INT, OPTION_CHANNEL, OPTION_FUNC, OPTION_IGNORE };
1496 const int OPTION_MULTI = 1 << 17;
1497
1498 struct OptionDesc {
1499     const char *option;
1500     bool has_param;
1501     int type;
1502     const char *property;
1503     bool b_param;
1504     const char *s_param;
1505     int (*func)( const char * );
1506     } fgOptionArray[] = {
1507
1508     {"language",                     true,  OPTION_IGNORE, "", false, "", 0 },
1509         {"console",                      false, OPTION_IGNORE,   "", false, "", 0 },
1510     {"launcher",                     false, OPTION_IGNORE,   "", false, "", 0 },
1511     {"disable-rembrandt",            false, OPTION_BOOL,   "/sim/rendering/rembrandt/enabled", false, "", 0 },
1512     {"enable-rembrandt",             false, OPTION_BOOL,   "/sim/rendering/rembrandt/enabled", true, "", 0 },
1513     {"renderer",                     true,  OPTION_STRING, "/sim/rendering/rembrandt/renderer", false, "", 0 },
1514     {"disable-splash-screen",        false, OPTION_BOOL,   "/sim/startup/splash-screen", false, "", 0 },
1515     {"enable-splash-screen",         false, OPTION_BOOL,   "/sim/startup/splash-screen", true, "", 0 },
1516     {"disable-mouse-pointer",        false, OPTION_STRING, "/sim/startup/mouse-pointer", false, "disabled", 0 },
1517     {"enable-mouse-pointer",         false, OPTION_STRING, "/sim/startup/mouse-pointer", false, "enabled", 0 },
1518     {"disable-random-objects",       false, OPTION_BOOL,   "/sim/rendering/random-objects", false, "", 0 },
1519     {"enable-random-objects",        false, OPTION_BOOL,   "/sim/rendering/random-objects", true, "", 0 },
1520     {"disable-random-vegetation",    false, OPTION_BOOL,   "/sim/rendering/random-vegetation", false, "", 0 },
1521     {"enable-random-vegetation",     false, OPTION_BOOL,   "/sim/rendering/random-vegetation", true, "", 0 },
1522     {"disable-random-buildings",     false, OPTION_BOOL,   "/sim/rendering/random-buildings", false, "", 0 },
1523     {"enable-random-buildings",      false, OPTION_BOOL,   "/sim/rendering/random-buildings", true, "", 0 },
1524     {"disable-real-weather-fetch",   false, OPTION_BOOL,   "/environment/realwx/enabled", false, "", 0 },
1525     {"enable-real-weather-fetch",    false, OPTION_BOOL,   "/environment/realwx/enabled", true,  "", 0 },
1526     {"metar",                        true,  OPTION_STRING, "/environment/metar/data", false, "", 0 },
1527     {"disable-ai-models",            false, OPTION_BOOL,   "/sim/ai/enabled", false, "", 0 },
1528     {"enable-ai-models",             false, OPTION_BOOL,   "/sim/ai/enabled", true, "", 0 },
1529     {"disable-ai-traffic",           false, OPTION_BOOL,   "/sim/traffic-manager/enabled", false, "", 0 },
1530     {"enable-ai-traffic",            false, OPTION_BOOL,   "/sim/traffic-manager/enabled", true,  "", 0 },
1531     {"disable-freeze",               false, OPTION_FUNC,   "", false, "", fgOptDisableFreeze },
1532     {"enable-freeze",                false, OPTION_FUNC,   "", true, "", fgOptEnableFreeze },
1533     {"disable-fuel-freeze",          false, OPTION_BOOL,   "/sim/freeze/fuel", false, "", 0 },
1534     {"enable-fuel-freeze",           false, OPTION_BOOL,   "/sim/freeze/fuel", true, "", 0 },
1535     {"disable-clock-freeze",         false, OPTION_BOOL,   "/sim/freeze/clock", false, "", 0 },
1536     {"enable-clock-freeze",          false, OPTION_BOOL,   "/sim/freeze/clock", true, "", 0 },
1537     {"disable-hud-3d",               false, OPTION_BOOL,   "/sim/hud/enable3d[1]", false, "", 0 },
1538     {"enable-hud-3d",                false, OPTION_BOOL,   "/sim/hud/enable3d[1]", true, "", 0 },
1539     {"disable-anti-alias-hud",       false, OPTION_BOOL,   "/sim/hud/color/antialiased", false, "", 0 },
1540     {"enable-anti-alias-hud",        false, OPTION_BOOL,   "/sim/hud/color/antialiased", true, "", 0 },
1541     {"disable-auto-coordination",    false, OPTION_BOOL,   "/controls/flight/auto-coordination", false, "", 0 },
1542     {"enable-auto-coordination",     false, OPTION_BOOL,   "/controls/flight/auto-coordination", true, "", 0 },
1543     {"browser-app",                  true,  OPTION_STRING, "/sim/startup/browser-app", false, "", 0 },
1544     {"disable-hud",                  false, OPTION_BOOL,   "/sim/hud/visibility[1]", false, "", 0 },
1545     {"enable-hud",                   false, OPTION_BOOL,   "/sim/hud/visibility[1]", true, "", 0 },
1546     {"disable-panel",                false, OPTION_BOOL,   "/sim/panel/visibility", false, "", 0 },
1547     {"enable-panel",                 false, OPTION_BOOL,   "/sim/panel/visibility", true, "", 0 },
1548     {"disable-sound",                false, OPTION_BOOL,   "/sim/sound/working", false, "", 0 },
1549     {"enable-sound",                 false, OPTION_BOOL,   "/sim/sound/working", true, "", 0 },
1550     {"sound-device",                 true,  OPTION_STRING, "/sim/sound/device-name", false, "", 0 },
1551     {"airport",                      true,  OPTION_STRING, "/sim/presets/airport-id", false, "", 0 },
1552     {"runway",                       true,  OPTION_FUNC,   "", false, "", fgOptRunway },
1553     {"vor",                          true,  OPTION_FUNC,   "", false, "", fgOptVOR },
1554     {"vor-frequency",                true,  OPTION_DOUBLE, "/sim/presets/vor-freq", false, "", fgOptVOR },
1555     {"ndb",                          true,  OPTION_FUNC,   "", false, "", fgOptNDB },
1556     {"ndb-frequency",                true,  OPTION_DOUBLE, "/sim/presets/ndb-freq", false, "", fgOptVOR },
1557     {"carrier",                      true,  OPTION_FUNC,   "", false, "", fgOptCarrier },
1558     {"parkpos",                      true,  OPTION_FUNC,   "", false, "", fgOptParkpos },
1559     {"fix",                          true,  OPTION_FUNC,   "", false, "", fgOptFIX },
1560     {"offset-distance",              true,  OPTION_DOUBLE, "/sim/presets/offset-distance-nm", false, "", 0 },
1561     {"offset-azimuth",               true,  OPTION_DOUBLE, "/sim/presets/offset-azimuth-deg", false, "", 0 },
1562     {"lon",                          true,  OPTION_FUNC,   "", false, "", fgOptLon },
1563     {"lat",                          true,  OPTION_FUNC,   "", false, "", fgOptLat },
1564     {"altitude",                     true,  OPTION_FUNC,   "", false, "", fgOptAltitude },
1565     {"uBody",                        true,  OPTION_FUNC,   "", false, "", fgOptUBody },
1566     {"vBody",                        true,  OPTION_FUNC,   "", false, "", fgOptVBody },
1567     {"wBody",                        true,  OPTION_FUNC,   "", false, "", fgOptWBody },
1568     {"vNorth",                       true,  OPTION_FUNC,   "", false, "", fgOptVNorth },
1569     {"vEast",                        true,  OPTION_FUNC,   "", false, "", fgOptVEast },
1570     {"vDown",                        true,  OPTION_FUNC,   "", false, "", fgOptVDown },
1571     {"vc",                           true,  OPTION_FUNC,   "", false, "", fgOptVc },
1572     {"mach",                         true,  OPTION_FUNC,   "", false, "", fgOptMach },
1573     {"heading",                      true,  OPTION_DOUBLE, "/sim/presets/heading-deg", false, "", 0 },
1574     {"roll",                         true,  OPTION_DOUBLE, "/sim/presets/roll-deg", false, "", 0 },
1575     {"pitch",                        true,  OPTION_DOUBLE, "/sim/presets/pitch-deg", false, "", 0 },
1576     {"glideslope",                   true,  OPTION_DOUBLE, "/sim/presets/glideslope-deg", false, "", 0 },
1577     {"roc",                          true,  OPTION_FUNC,   "", false, "", fgOptRoc },
1578     {"fg-root",                      true,  OPTION_IGNORE,   "", false, "", 0 },
1579     {"fg-scenery",                   true,  OPTION_FUNC | OPTION_MULTI,   "", false, "", fgOptFgScenery },
1580     {"fg-aircraft",                  true,  OPTION_IGNORE | OPTION_MULTI,   "", false, "", 0 },
1581     {"fdm",                          true,  OPTION_STRING, "/sim/flight-model", false, "", 0 },
1582     {"aero",                         true,  OPTION_STRING, "/sim/aero", false, "", 0 },
1583     {"aircraft-dir",                 true,  OPTION_IGNORE,   "", false, "", 0 },
1584     {"model-hz",                     true,  OPTION_INT,    "/sim/model-hz", false, "", 0 },
1585     {"max-fps",                      true,  OPTION_DOUBLE, "/sim/frame-rate-throttle-hz", false, "", 0 },
1586     {"speed",                        true,  OPTION_DOUBLE, "/sim/speed-up", false, "", 0 },
1587     {"trim",                         false, OPTION_BOOL,   "/sim/presets/trim", true, "", 0 },
1588     {"notrim",                       false, OPTION_BOOL,   "/sim/presets/trim", false, "", 0 },
1589     {"on-ground",                    false, OPTION_BOOL,   "/sim/presets/onground", true, "", 0 },
1590     {"in-air",                       false, OPTION_BOOL,   "/sim/presets/onground", false, "", 0 },
1591     {"fog-disable",                  false, OPTION_STRING, "/sim/rendering/fog", false, "disabled", 0 },
1592     {"fog-fastest",                  false, OPTION_STRING, "/sim/rendering/fog", false, "fastest", 0 },
1593     {"fog-nicest",                   false, OPTION_STRING, "/sim/rendering/fog", false, "nicest", 0 },
1594     {"disable-horizon-effect",       false, OPTION_BOOL,   "/sim/rendering/horizon-effect", false, "", 0 },
1595     {"enable-horizon-effect",        false, OPTION_BOOL,   "/sim/rendering/horizon-effect", true, "", 0 },
1596     {"disable-enhanced-lighting",    false, OPTION_BOOL,   "/sim/rendering/enhanced-lighting", false, "", 0 },
1597     {"enable-enhanced-lighting",     false, OPTION_BOOL,   "/sim/rendering/enhanced-lighting", true, "", 0 },
1598     {"disable-distance-attenuation", false, OPTION_BOOL,   "/sim/rendering/distance-attenuation", false, "", 0 },
1599     {"enable-distance-attenuation",  false, OPTION_BOOL,   "/sim/rendering/distance-attenuation", true, "", 0 },
1600     {"disable-specular-highlight",   false, OPTION_BOOL,   "/sim/rendering/specular-highlight", false, "", 0 },
1601     {"enable-specular-highlight",    false, OPTION_BOOL,   "/sim/rendering/specular-highlight", true, "", 0 },
1602     {"disable-clouds",               false, OPTION_BOOL,   "/environment/clouds/status", false, "", 0 },
1603     {"enable-clouds",                false, OPTION_BOOL,   "/environment/clouds/status", true, "", 0 },
1604     {"disable-clouds3d",             false, OPTION_BOOL,   "/sim/rendering/clouds3d-enable", false, "", 0 },
1605     {"enable-clouds3d",              false, OPTION_BOOL,   "/sim/rendering/clouds3d-enable", true, "", 0 },
1606     {"fov",                          true,  OPTION_FUNC,   "", false, "", fgOptFov },
1607     {"aspect-ratio-multiplier",      true,  OPTION_DOUBLE, "/sim/current-view/aspect-ratio-multiplier", false, "", 0 },
1608     {"disable-fullscreen",           false, OPTION_BOOL,   "/sim/startup/fullscreen", false, "", 0 },
1609     {"enable-fullscreen",            false, OPTION_BOOL,   "/sim/startup/fullscreen", true, "", 0 },
1610     {"disable-save-on-exit",         false, OPTION_BOOL,   "/sim/startup/save-on-exit", false, "", 0 },
1611     {"enable-save-on-exit",          false, OPTION_BOOL,   "/sim/startup/save-on-exit", true, "", 0 },
1612     {"read-only",                    false, OPTION_BOOL,   "/sim/fghome-readonly", true, "", 0 },
1613     {"ignore-autosave",              false, OPTION_FUNC,   "", false, "", fgOptIgnoreAutosave },
1614     {"restore-defaults",             false, OPTION_BOOL,   "/sim/startup/restore-defaults", true, "", 0 },
1615     {"shading-flat",                 false, OPTION_BOOL,   "/sim/rendering/shading", false, "", 0 },
1616     {"shading-smooth",               false, OPTION_BOOL,   "/sim/rendering/shading", true, "", 0 },
1617     {"texture-filtering",            false, OPTION_INT,    "/sim/rendering/filtering", 1, "", 0 },
1618     {"disable-wireframe",            false, OPTION_BOOL,   "/sim/rendering/wireframe", false, "", 0 },
1619     {"enable-wireframe",             false, OPTION_BOOL,   "/sim/rendering/wireframe", true, "", 0 },
1620     {"materials-file",               true,  OPTION_STRING, "/sim/rendering/materials-file", false, "", 0 },
1621     {"disable-terrasync",            false, OPTION_BOOL,   "/sim/terrasync/enabled", false, "", 0 },
1622     {"enable-terrasync",             false, OPTION_BOOL,   "/sim/terrasync/enabled", true, "", 0 },
1623     {"terrasync-dir",                true,  OPTION_STRING, "/sim/terrasync/scenery-dir", false, "", 0 },
1624     {"download-dir",                 true,  OPTION_STRING, "/sim/paths/download-dir", false, "", 0 },
1625     {"geometry",                     true,  OPTION_FUNC,   "", false, "", fgOptGeometry },
1626     {"bpp",                          true,  OPTION_FUNC,   "", false, "", fgOptBpp },
1627     {"units-feet",                   false, OPTION_STRING, "/sim/startup/units", false, "feet", 0 },
1628     {"units-meters",                 false, OPTION_STRING, "/sim/startup/units", false, "meters", 0 },
1629     {"timeofday",                    true,  OPTION_STRING, "/sim/startup/time-offset-type", false, "noon", 0 },
1630     {"season",                       true,  OPTION_STRING, "/sim/startup/season", false, "summer", 0 },
1631     {"time-offset",                  true,  OPTION_FUNC,   "", false, "", fgOptTimeOffset },
1632     {"time-match-real",              false, OPTION_STRING, "/sim/startup/time-offset-type", false, "system-offset", 0 },
1633     {"time-match-local",             false, OPTION_STRING, "/sim/startup/time-offset-type", false, "latitude-offset", 0 },
1634     {"start-date-sys",               true,  OPTION_FUNC,   "", false, "", fgOptStartDateSys },
1635     {"start-date-lat",               true,  OPTION_FUNC,   "", false, "", fgOptStartDateLat },
1636     {"start-date-gmt",               true,  OPTION_FUNC,   "", false, "", fgOptStartDateGmt },
1637     {"hud-tris",                     false, OPTION_STRING, "/sim/hud/frame-stat-type", false, "tris", 0 },
1638     {"hud-culled",                   false, OPTION_STRING, "/sim/hud/frame-stat-type", false, "culled", 0 },
1639     {"atcsim",                       true,  OPTION_CHANNEL, "", false, "dummy", 0 },
1640     {"atlas",                        true,  OPTION_CHANNEL | OPTION_MULTI, "", false, "", 0 },
1641     {"httpd",                        true,  OPTION_FUNC   , "", false, "", fgOptHttpd },
1642     {"jpg-httpd",                    true,  OPTION_FUNC,    "", false, "", fgOptJpgHttpd },
1643     {"native",                       true,  OPTION_CHANNEL | OPTION_MULTI, "", false, "", 0 },
1644     {"native-ctrls",                 true,  OPTION_CHANNEL | OPTION_MULTI, "", false, "", 0 },
1645     {"native-fdm",                   true,  OPTION_CHANNEL | OPTION_MULTI, "", false, "", 0 },
1646     {"native-gui",                   true,  OPTION_CHANNEL | OPTION_MULTI, "", false, "", 0 },
1647     {"opengc",                       true,  OPTION_CHANNEL | OPTION_MULTI, "", false, "", 0 },
1648     {"AV400",                        true,  OPTION_CHANNEL | OPTION_MULTI, "", false, "", 0 },
1649     {"AV400Sim",                     true,  OPTION_CHANNEL | OPTION_MULTI, "", false, "", 0 },
1650     {"AV400WSimA",                   true,  OPTION_CHANNEL | OPTION_MULTI, "", false, "", 0 },
1651     {"AV400WSimB",                   true,  OPTION_CHANNEL | OPTION_MULTI, "", false, "", 0 },
1652     {"garmin",                       true,  OPTION_CHANNEL | OPTION_MULTI, "", false, "", 0 },
1653     {"igc",                          true,  OPTION_CHANNEL | OPTION_MULTI, "", false, "", 0 },
1654     {"nmea",                         true,  OPTION_CHANNEL | OPTION_MULTI, "", false, "", 0 },
1655     {"generic",                      true,  OPTION_CHANNEL | OPTION_MULTI, "", false, "", 0 },
1656     {"props",                        true,  OPTION_CHANNEL | OPTION_MULTI, "", false, "", 0 },
1657     {"telnet",                       true,  OPTION_CHANNEL | OPTION_MULTI, "", false, "", 0 },
1658     {"pve",                          true,  OPTION_CHANNEL, "", false, "", 0 },
1659     {"ray",                          true,  OPTION_CHANNEL, "", false, "", 0 },
1660     {"rul",                          true,  OPTION_CHANNEL, "", false, "", 0 },
1661     {"joyclient",                    true,  OPTION_CHANNEL, "", false, "", 0 },
1662     {"jsclient",                     true,  OPTION_CHANNEL, "", false, "", 0 },
1663     {"proxy",                        true,  OPTION_FUNC,    "", false, "", fgSetupProxy },
1664     {"callsign",                     true,  OPTION_FUNC,    "", false, "", fgOptCallSign},
1665     {"multiplay",                    true,  OPTION_CHANNEL | OPTION_MULTI, "", false, "", 0 },
1666 #if FG_HAVE_HLA
1667     {"hla",                          true,  OPTION_CHANNEL, "", false, "", 0 },
1668     {"hla-local",                    true,  OPTION_CHANNEL, "", false, "", 0 },
1669 #endif
1670     {"trace-read",                   true,  OPTION_FUNC | OPTION_MULTI,   "", false, "", fgOptTraceRead },
1671     {"trace-write",                  true,  OPTION_FUNC | OPTION_MULTI,   "", false, "", fgOptTraceWrite },
1672     {"log-level",                    true,  OPTION_FUNC,   "", false, "", fgOptLogLevel },
1673     {"log-class",                    true,  OPTION_FUNC,   "", false, "", fgOptLogClasses },
1674     {"view-offset",                  true,  OPTION_FUNC | OPTION_MULTI,   "", false, "", fgOptViewOffset },
1675     {"visibility",                   true,  OPTION_FUNC,   "", false, "", fgOptVisibilityMeters },
1676     {"visibility-miles",             true,  OPTION_FUNC,   "", false, "", fgOptVisibilityMiles },
1677     {"random-wind",                  false, OPTION_FUNC,   "", false, "", fgOptRandomWind },
1678     {"wind",                         true,  OPTION_FUNC | OPTION_MULTI,   "", false, "", fgOptWind },
1679     {"turbulence",                   true,  OPTION_FUNC,   "", false, "", fgOptTurbulence },
1680     {"ceiling",                      true,  OPTION_FUNC,   "", false, "", fgOptCeiling },
1681     {"wp",                           true,  OPTION_FUNC | OPTION_MULTI,   "", false, "", fgOptWp },
1682     {"flight-plan",                  true,  OPTION_STRING,   "/autopilot/route-manager/file-path", false, "", NULL },
1683     {"config",                       true,  OPTION_FUNC | OPTION_MULTI,   "", false, "", fgOptConfig },
1684     {"aircraft",                     true,  OPTION_STRING, "/sim/aircraft", false, "", 0 },
1685     {"vehicle",                      true,  OPTION_STRING, "/sim/aircraft", false, "", 0 },
1686     {"failure",                      true,  OPTION_FUNC | OPTION_MULTI,   "", false, "", fgOptFailure },
1687 #ifdef ENABLE_IAX
1688     {"enable-fgcom",                 false, OPTION_BOOL,   "/sim/fgcom/enabled", true, "", 0 },
1689     {"disable-fgcom",                false, OPTION_BOOL,   "/sim/fgcom/enabled", false, "", 0 },
1690 #endif
1691     {"com1",                         true,  OPTION_DOUBLE, "/instrumentation/comm[0]/frequencies/selected-mhz", false, "", 0 },
1692     {"com2",                         true,  OPTION_DOUBLE, "/instrumentation/comm[1]/frequencies/selected-mhz", false, "", 0 },
1693     {"nav1",                         true,  OPTION_FUNC,   "", false, "", fgOptNAV1 },
1694     {"nav2",                         true,  OPTION_FUNC,   "", false, "", fgOptNAV2 },
1695     {"adf", /*legacy*/               true,  OPTION_FUNC,   "", false, "", fgOptADF1 },
1696     {"adf1",                         true,  OPTION_FUNC,   "", false, "", fgOptADF1 },
1697     {"adf2",                         true,  OPTION_FUNC,   "", false, "", fgOptADF2 },
1698     {"dme",                          true,  OPTION_FUNC,   "", false, "", fgOptDME },
1699     {"min-status",                   true,  OPTION_STRING,  "/sim/aircraft-min-status", false, "all", 0 },
1700     {"livery",                       true,  OPTION_FUNC,   "", false, "", fgOptLivery },
1701     {"ai-scenario",                  true,  OPTION_FUNC | OPTION_MULTI,   "", false, "", fgOptScenario },
1702     {"parking-id",                   true,  OPTION_FUNC,   "", false, "", fgOptParking  },
1703     {"version",                      false, OPTION_FUNC,   "", false, "", fgOptVersion },
1704     {"enable-fpe",                   false, OPTION_IGNORE,   "", false, "", 0},
1705     {"fgviewer",                     false, OPTION_IGNORE,   "", false, "", 0},
1706     {"no-default-config",            false, OPTION_IGNORE, "", false, "", 0},
1707     {"prop",                         true,  OPTION_FUNC | OPTION_MULTI,   "", false, "", fgOptSetProperty},
1708     {"load-tape",                    true,  OPTION_FUNC,   "", false, "", fgOptLoadTape },
1709     {0}
1710 };
1711
1712
1713 namespace flightgear
1714 {
1715
1716 /**
1717  * internal storage of a value->option binding
1718  */
1719 class OptionValue 
1720 {
1721 public:
1722   OptionValue(OptionDesc* d, const string& v) :
1723     desc(d), value(v)
1724   {;}
1725   
1726   OptionDesc* desc;
1727   string value;
1728 };
1729
1730 typedef std::vector<OptionValue> OptionValueVec;
1731 typedef std::map<string, OptionDesc*> OptionDescDict;
1732   
1733 class Options::OptionsPrivate
1734 {
1735 public:
1736   
1737   OptionValueVec::const_iterator findValue(const string& key) const
1738   {
1739     OptionValueVec::const_iterator it = values.begin();
1740     for (; it != values.end(); ++it) {
1741       if (!it->desc) {
1742         continue; // ignore markers
1743       }
1744       
1745       if (it->desc->option == key) {
1746         return it;
1747       }
1748     } // of set values iteration
1749     
1750     return it; // not found
1751   }
1752   
1753   OptionDesc* findOption(const string& key) const
1754   {
1755     OptionDescDict::const_iterator it = options.find(key);
1756     if (it == options.end()) {
1757       return NULL;
1758     }
1759     
1760     return it->second;
1761   }
1762   
1763   int processOption(OptionDesc* desc, const string& arg_value)
1764   {
1765     if (!desc) {
1766       return FG_OPTIONS_OK; // tolerate marker options
1767     }
1768     
1769     switch ( desc->type & 0xffff ) {
1770       case OPTION_BOOL:
1771         fgSetBool( desc->property, desc->b_param );
1772         break;
1773       case OPTION_STRING:
1774         if ( desc->has_param && !arg_value.empty() ) {
1775           fgSetString( desc->property, arg_value.c_str() );
1776         } else if ( !desc->has_param && arg_value.empty() ) {
1777           fgSetString( desc->property, desc->s_param );
1778         } else if ( desc->has_param ) {
1779           SG_LOG( SG_GENERAL, SG_ALERT, "Option '" << desc->option << "' needs a parameter" );
1780           return FG_OPTIONS_ERROR;
1781         } else {
1782           SG_LOG( SG_GENERAL, SG_ALERT, "Option '" << desc->option << "' does not have a parameter" );
1783           return FG_OPTIONS_ERROR;
1784         }
1785         break;
1786       case OPTION_DOUBLE:
1787         if ( !arg_value.empty() ) {
1788           fgSetDouble( desc->property, atof( arg_value ) );
1789         } else {
1790           SG_LOG( SG_GENERAL, SG_ALERT, "Option '" << desc->option << "' needs a parameter" );
1791           return FG_OPTIONS_ERROR;
1792         }
1793         break;
1794       case OPTION_INT:
1795         if ( !arg_value.empty() ) {
1796           fgSetInt( desc->property, atoi( arg_value ) );
1797         } else {
1798           SG_LOG( SG_GENERAL, SG_ALERT, "Option '" << desc->option << "' needs a parameter" );
1799           return FG_OPTIONS_ERROR;
1800         }
1801         break;
1802       case OPTION_CHANNEL:
1803         // XXX return value of add_channel should be checked?
1804         if ( desc->has_param && !arg_value.empty() ) {
1805           add_channel( desc->option, arg_value );
1806         } else if ( !desc->has_param && arg_value.empty() ) {
1807           add_channel( desc->option, desc->s_param );
1808         } else if ( desc->has_param ) {
1809           SG_LOG( SG_GENERAL, SG_ALERT, "Option '" << desc->option << "' needs a parameter" );
1810           return FG_OPTIONS_ERROR;
1811         } else {
1812           SG_LOG( SG_GENERAL, SG_ALERT, "Option '" << desc->option << "' does not have a parameter" );
1813           return FG_OPTIONS_ERROR;
1814         }
1815         break;
1816       case OPTION_FUNC:
1817         if ( desc->has_param && !arg_value.empty() ) {
1818           return desc->func( arg_value.c_str() );
1819         } else if ( !desc->has_param && arg_value.empty() ) {
1820           return desc->func( desc->s_param );
1821         } else if ( desc->has_param ) {
1822           SG_LOG( SG_GENERAL, SG_ALERT, "Option '" << desc->option << "' needs a parameter" );
1823           return FG_OPTIONS_ERROR;
1824         } else {
1825           SG_LOG( SG_GENERAL, SG_ALERT, "Option '" << desc->option << "' does not have a parameter" );
1826           return FG_OPTIONS_ERROR;
1827         }
1828         break;
1829         
1830       case OPTION_IGNORE:
1831         break;
1832     }
1833     
1834     return FG_OPTIONS_OK;
1835   }
1836     
1837   /**
1838    * insert a marker value into the values vector. This is necessary
1839    * when processing options, to ensure the correct ordering, where we scan
1840    * for marker values in reverse, and then forwards within each group.
1841    */
1842   void insertGroupMarker()
1843   {
1844     values.push_back(OptionValue(NULL, "-"));
1845   }
1846   
1847   /**
1848    * given a current iterator into the values, find the preceding group marker,
1849    * or return the beginning of the value vector.
1850    */
1851   OptionValueVec::const_iterator rfindGroup(OptionValueVec::const_iterator pos) const
1852   {
1853     while (--pos != values.begin()) {
1854       if (pos->desc == NULL) {
1855         return pos; // found a marker, we're done
1856       }
1857     }
1858     
1859     return pos;
1860   }
1861   
1862   bool showHelp,
1863     verbose,
1864     showAircraft,
1865     shouldLoadDefaultConfig;
1866     
1867   OptionDescDict options;
1868   OptionValueVec values;
1869   simgear::PathList propertyFiles;
1870 };
1871   
1872 Options* Options::sharedInstance()
1873 {
1874   if (shared_instance == NULL) {
1875     shared_instance = new Options;
1876   }
1877   
1878   return shared_instance;
1879 }
1880   
1881 Options::Options() :
1882   p(new OptionsPrivate())
1883 {
1884   p->showHelp = false;
1885   p->verbose = false;
1886   p->showAircraft = false;
1887   p->shouldLoadDefaultConfig = true;
1888   
1889 // build option map
1890   OptionDesc *desc = &fgOptionArray[ 0 ];
1891   while ( desc->option != 0 ) {
1892     p->options[ desc->option ] = desc;
1893     ++desc;
1894   }
1895 }
1896   
1897 Options::~Options()
1898 {
1899 }
1900   
1901 void Options::init(int argc, char **argv, const SGPath& appDataPath)
1902 {
1903 // first, process the command line
1904   bool inOptions = true;
1905   for (int i=1; i<argc; ++i) {
1906     if (inOptions && (argv[i][0] == '-')) {
1907       if (strcmp(argv[i], "--") == 0) { // end of options delimiter
1908         inOptions = true;
1909         continue;
1910       }
1911       
1912       int result = parseOption(argv[i]);
1913       processArgResult(result);
1914     } else {
1915     // XML properties file
1916       SGPath f(argv[i]);
1917       if (!f.exists()) {
1918         SG_LOG(SG_GENERAL, SG_ALERT, "config file not found:" << f.str());
1919       } else {
1920         p->propertyFiles.push_back(f);
1921       }
1922     }
1923   } // of arguments iteration
1924   p->insertGroupMarker(); // command line is one group
1925   
1926   // establish log-level before anything else - otherwise it is not possible
1927   // to show extra (debug/info/warning) messages for the start-up phase.
1928   fgOptLogLevel(valueForOption("log-level", "alert").c_str());
1929
1930   if (!p->shouldLoadDefaultConfig) {
1931     setupRoot(argc, argv);
1932     return;
1933   }
1934   
1935 // then config files
1936   SGPath config;
1937   std::string homedir;
1938   if (getenv("HOME")) {
1939     homedir = getenv("HOME");
1940   }
1941     
1942   if( !homedir.empty() && !hostname.empty() ) {
1943     // Check for ~/.fgfsrc.hostname
1944     config.set(homedir);
1945     config.append(".fgfsrc");
1946     config.concat( "." );
1947     config.concat( hostname );
1948     readConfig(config);
1949   }
1950   
1951 // Check for ~/.fgfsrc
1952   if( !homedir.empty() ) {
1953     config.set(homedir);
1954     config.append(".fgfsrc");
1955     readConfig(config);
1956   }
1957   
1958 // check for a config file in app data
1959   SGPath appDataConfig(appDataPath);
1960   appDataConfig.append("fgfsrc");
1961   if (appDataConfig.exists()) {
1962     readConfig(appDataConfig);
1963   }
1964   
1965 // setup FG_ROOT
1966   setupRoot(argc, argv);
1967   
1968 // system.fgfsrc is disabled, as we no longer allow anything in fgdata to set
1969 // fg-root/fg-home/fg-aircraft and hence control what files Nasal can access
1970   std::string name_for_error = homedir.empty() ? appDataConfig.str() : config.str();
1971   if( ! hostname.empty() ) {
1972     config.set(globals->get_fg_root());
1973     config.append( "system.fgfsrc" );
1974     config.concat( "." );
1975     config.concat( hostname );
1976     if (config.exists()) {
1977       flightgear::fatalMessageBox("Unsupported configuration",
1978         "You have a " + config.str() + " file, which is no longer processed for security reasons",
1979         "If you created this file intentionally, please move it to " + name_for_error);
1980     }
1981   }
1982
1983   config.set(globals->get_fg_root());
1984   config.append( "system.fgfsrc" );
1985   if (config.exists()) {
1986     flightgear::fatalMessageBox("Unsupported configuration",
1987       "You have a " + config.str() + " file, which is no longer processed for security reasons",
1988       "If you created this file intentionally, please move it to " + name_for_error);
1989   }
1990 }
1991
1992 void Options::initPaths()
1993 {
1994     BOOST_FOREACH(const string& paths, valuesForOption("fg-aircraft")) {
1995         globals->append_aircraft_paths(paths);
1996     }
1997
1998     const char* envp = ::getenv("FG_AIRCRAFT");
1999     if (envp) {
2000         globals->append_aircraft_paths(envp);
2001     }
2002
2003 }
2004
2005 void Options::initAircraft()
2006 {
2007   string aircraft;
2008   if (isOptionSet("aircraft")) {
2009     aircraft = valueForOption("aircraft");
2010   } else if (isOptionSet("vehicle")) {
2011     aircraft = valueForOption("vehicle");
2012   }
2013     
2014   if (!aircraft.empty()) {
2015     SG_LOG(SG_INPUT, SG_INFO, "aircraft = " << aircraft );
2016     fgSetString("/sim/aircraft", aircraft.c_str() );
2017   } else {
2018     SG_LOG(SG_INPUT, SG_INFO, "No user specified aircraft, using default" );
2019   }
2020     
2021   if (p->showAircraft) {
2022         vector<SGPath> path_list;
2023
2024     fgOptLogLevel( "alert" );
2025
2026     // First place to check is the 'Aircraft' sub-directory in $FG_ROOT
2027
2028         path_list.push_back( SGPath( globals->get_fg_root() ) );
2029         path_list.back().append("Aircraft");
2030
2031     // Additionally, aircraft may also be found in user-defined places
2032         // (via $FG_AIRCRAFT or with the '--fg-aircraft' option)
2033
2034         string_list aircraft_paths = globals->get_aircraft_paths();
2035         for (string_list::iterator it = aircraft_paths.begin();
2036                  it != aircraft_paths.end(); ++it)
2037           path_list.push_back( SGPath(*it));
2038
2039     fgShowAircraft(path_list);
2040     exit(0);
2041   }
2042   
2043   if (isOptionSet("aircraft-dir")) {
2044     SGPath aircraftDirPath(valueForOption("aircraft-dir"));
2045
2046     // Set this now, so it's available in FindAndCacheAircraft. Use realpath()
2047     // as in FGGlobals::append_aircraft_path(), otherwise fgValidatePath()
2048     // will deny access to resources under this path if one of its components
2049     // is a symlink (which is not a problem, since it was given as is by the
2050     // user---this is very different from a symlink *under* the aircraft dir
2051     // or a scenery dir).
2052     fgSetString("/sim/aircraft-dir", aircraftDirPath.realpath().c_str());
2053   }
2054 }
2055   
2056 void Options::processArgResult(int result)
2057 {
2058   if ((result == FG_OPTIONS_HELP) || (result == FG_OPTIONS_ERROR))
2059     p->showHelp = true;
2060   else if (result == FG_OPTIONS_VERBOSE_HELP)
2061     p->verbose = true;
2062   else if (result == FG_OPTIONS_SHOW_AIRCRAFT) {
2063     p->showAircraft = true;
2064   } else if (result == FG_OPTIONS_NO_DEFAULT_CONFIG) {
2065     p->shouldLoadDefaultConfig = false;
2066   } else if (result == FG_OPTIONS_SHOW_SOUND_DEVICES) {
2067     SGSoundMgr smgr;
2068     
2069     smgr.init();
2070     string vendor = smgr.get_vendor();
2071     string renderer = smgr.get_renderer();
2072     cout << renderer << " provided by " << vendor << endl;
2073     cout << endl << "No. Device" << endl;
2074     
2075     vector <const char*>devices = smgr.get_available_devices();
2076     for (vector <const char*>::size_type i=0; i<devices.size(); i++) {
2077       cout << i << ".  \"" << devices[i] << "\"" << endl;
2078     }
2079     devices.clear();
2080     smgr.stop();
2081     exit(0);
2082   } else if (result == FG_OPTIONS_EXIT) {
2083     exit(0);
2084   }
2085 }
2086   
2087 void Options::readConfig(const SGPath& path)
2088 {
2089   sg_gzifstream in( path.str() );
2090   if ( !in.is_open() ) {
2091     return;
2092   }
2093   
2094   SG_LOG( SG_GENERAL, SG_INFO, "Processing config file: " << path.str() );
2095   
2096   in >> skipcomment;
2097   while ( ! in.eof() ) {
2098     string line;
2099     getline( in, line, '\n' );
2100     
2101     // catch extraneous (DOS) line ending character
2102     int i;
2103     for (i = line.length(); i > 0; i--)
2104       if (line[i - 1] > 32)
2105         break;
2106     line = line.substr( 0, i );
2107     
2108     if ( parseOption( line ) == FG_OPTIONS_ERROR ) {
2109       cerr << endl << "Config file parse error: " << path.str() << " '"
2110       << line << "'" << endl;
2111             p->showHelp = true;
2112     }
2113     in >> skipcomment;
2114   }
2115
2116   p->insertGroupMarker(); // each config file is a group
2117 }
2118   
2119 int Options::parseOption(const string& s)
2120 {
2121   if ((s == "--help") || (s=="-h")) {
2122     return FG_OPTIONS_HELP;
2123   } else if ( (s == "--verbose") || (s == "-v") ) {
2124     // verbose help/usage request
2125     return FG_OPTIONS_VERBOSE_HELP;
2126   } else if ((s == "--console") || (s == "-c")) {
2127           simgear::requestConsole();
2128           return FG_OPTIONS_OK;
2129   } else if (s.find("-psn") == 0) {
2130     // on Mac, when launched from the GUI, we are passed the ProcessSerialNumber
2131     // as an argument (and no others). Silently ignore the argument here.
2132     return FG_OPTIONS_OK;
2133   } else if ( s.find( "--show-aircraft") == 0) {
2134     return(FG_OPTIONS_SHOW_AIRCRAFT);
2135   } else if ( s.find( "--show-sound-devices") == 0) {
2136     return(FG_OPTIONS_SHOW_SOUND_DEVICES);
2137   } else if ( s.find( "--no-default-config") == 0) {
2138     return FG_OPTIONS_NO_DEFAULT_CONFIG;
2139   } else if ( s.find( "--prop:") == 0) {
2140     // property setting has a slightly different syntax, so fudge things
2141     OptionDesc* desc = p->findOption("prop");
2142     if (s.find("=", 7) == string::npos) { // no equals token
2143       SG_LOG(SG_GENERAL, SG_ALERT, "malformed property option:" << s);
2144       return FG_OPTIONS_ERROR;
2145     }
2146     
2147     p->values.push_back(OptionValue(desc, s.substr(7)));
2148     return FG_OPTIONS_OK;
2149   } else if ( s.find( "--" ) == 0 ) {
2150     size_t eqPos = s.find( '=' );
2151     string key, value;
2152     if (eqPos == string::npos) {
2153       key = s.substr(2);
2154     } else {
2155       key = s.substr( 2, eqPos - 2 );
2156       value = s.substr( eqPos + 1);
2157     }
2158     
2159     return addOption(key, value);
2160   } else {
2161       flightgear::modalMessageBox("Unknown option", "Unknown command-line option: " + s);
2162     return FG_OPTIONS_ERROR;
2163   }
2164 }
2165   
2166 int Options::addOption(const string &key, const string &value)
2167 {
2168   OptionDesc* desc = p->findOption(key);
2169   if (!desc) {
2170     flightgear::modalMessageBox("Unknown option", "Unknown command-line option: " + key);
2171     return FG_OPTIONS_ERROR;
2172   }
2173   
2174   if (!(desc->type & OPTION_MULTI)) {
2175     OptionValueVec::const_iterator it = p->findValue(key);
2176     if (it != p->values.end()) {
2177       SG_LOG(SG_GENERAL, SG_WARN, "multiple values forbidden for option:" << key << ", ignoring:" << value);
2178       return FG_OPTIONS_OK;
2179     }
2180   }
2181   
2182   p->values.push_back(OptionValue(desc, value));
2183   return FG_OPTIONS_OK;
2184 }
2185   
2186 bool Options::isOptionSet(const string &key) const
2187 {
2188   OptionValueVec::const_iterator it = p->findValue(key);
2189   return (it != p->values.end());
2190 }
2191   
2192 string Options::valueForOption(const string& key, const string& defValue) const
2193 {
2194   OptionValueVec::const_iterator it = p->findValue(key);
2195   if (it == p->values.end()) {
2196     return defValue;
2197   }
2198   
2199   return it->value;
2200 }
2201
2202 string_list Options::valuesForOption(const std::string& key) const
2203 {
2204   string_list result;
2205   OptionValueVec::const_iterator it = p->values.begin();
2206   for (; it != p->values.end(); ++it) {
2207     if (!it->desc) {
2208       continue; // ignore marker values
2209     }
2210     
2211     if (it->desc->option == key) {
2212       result.push_back(it->value);
2213     }
2214   }
2215   
2216   return result;
2217 }
2218
2219 string defaultDownloadDir()
2220 {
2221 #if defined(SG_WINDOWS)
2222     SGPath p(SGPath::documents());
2223     p.append("FlightGear");
2224 #else
2225     SGPath p(globals->get_fg_home());
2226 #endif
2227     return p.str();
2228 }
2229
2230 OptionResult Options::processOptions()
2231 {
2232   // establish locale before showing help (this selects the default locale,
2233   // when no explicit option was set)
2234   globals->get_locale()->selectLanguage(valueForOption("language").c_str());
2235
2236   // now FG_ROOT is setup, process various command line options that bail us
2237   // out quickly, but rely on aircraft / root settings
2238   if (p->showHelp) {
2239     showUsage();
2240       return FG_OPTIONS_EXIT;
2241   }
2242   
2243   // processing order is complicated. We must process groups LIFO, but the
2244   // values *within* each group in FIFO order, to retain consistency with
2245   // older versions of FG, and existing user configs.
2246   // in practice this means system.fgfsrc must be *processed* before
2247   // .fgfsrc, which must be processed before the command line args, and so on.
2248   OptionValueVec::const_iterator groupEnd = p->values.end();
2249
2250   while (groupEnd != p->values.begin()) {
2251     OptionValueVec::const_iterator groupBegin = p->rfindGroup(groupEnd);
2252   // run over the group in FIFO order
2253     OptionValueVec::const_iterator it;
2254     for (it = groupBegin; it != groupEnd; ++it) {      
2255       int result = p->processOption(it->desc, it->value);
2256       switch(result)
2257       {
2258           case FG_OPTIONS_ERROR:
2259               showUsage();
2260               return FG_OPTIONS_ERROR;
2261               
2262           case FG_OPTIONS_EXIT:
2263               return FG_OPTIONS_EXIT;
2264               
2265           default:
2266               break;
2267       }
2268         if (it->desc) {
2269             SG_LOG(SG_GENERAL, SG_INFO, "\toption:" << it->desc->option << " = " << it->value);
2270         }
2271     }
2272     
2273     groupEnd = groupBegin;
2274   }
2275
2276   BOOST_FOREACH(const SGPath& file, p->propertyFiles) {
2277     SG_LOG(SG_GENERAL, SG_INFO,
2278            "Reading command-line property file " << file.str());
2279           readProperties(file.str(), globals->get_props());
2280   }
2281
2282 // now options are process, do supplemental fixup
2283   const char *envp = ::getenv( "FG_SCENERY" );
2284   if (envp) {
2285     globals->append_fg_scenery(envp, true);
2286   }
2287
2288 // download dir fix-up
2289     string downloadDir = simgear::strutils::strip(fgGetString("/sim/paths/download-dir"));
2290     if (downloadDir.empty()) {
2291         downloadDir = defaultDownloadDir();
2292         SG_LOG(SG_GENERAL, SG_INFO, "Using default download dir: " << downloadDir);
2293     } else {
2294         simgear::Dir d(downloadDir);
2295         if (!d.exists()) {
2296             SG_LOG(SG_GENERAL, SG_INFO, "Creating requested download dir: " << downloadDir);
2297             d.create(0755);
2298         }
2299     }
2300
2301 // terrasync directory fixup
2302     string terrasyncDir = simgear::strutils::strip(fgGetString("/sim/terrasync/scenery-dir"));
2303   if (terrasyncDir.empty()) {
2304       SGPath p(downloadDir);
2305       p.append("TerraSync");
2306       terrasyncDir = p.str();
2307
2308       simgear::Dir d(terrasyncDir);
2309       if (!d.exists()) {
2310           d.create(0755);
2311       }
2312
2313           SG_LOG(SG_GENERAL, SG_INFO, "Using default TerraSync: " << terrasyncDir);
2314       fgSetString("/sim/terrasync/scenery-dir", p.str());
2315   } else {
2316       SG_LOG(SG_GENERAL, SG_INFO, "Using explicit TerraSync dir: " << terrasyncDir);
2317   }
2318
2319     // check if we setup a scenery path so far
2320     bool addFGDataScenery = globals->get_fg_scenery().empty();
2321
2322     // always add the terrasync location, regardless of whether terrasync
2323     // is enabled or not. This allows us to toggle terrasync on/off at
2324     // runtime and have things work as expected
2325     const string_list& scenery_paths(globals->get_fg_scenery());
2326     if (std::find(scenery_paths.begin(), scenery_paths.end(), terrasyncDir) == scenery_paths.end()) {
2327         // terrasync dir is not in the scenery paths, add it
2328         globals->append_fg_scenery(terrasyncDir);
2329     }
2330
2331     if (addFGDataScenery) {
2332         // no scenery paths set at all, use the data in FG_ROOT
2333         // ensure this path is added last
2334         SGPath root(globals->get_fg_root());
2335         root.append("Scenery");
2336         globals->append_fg_scenery(root.str());
2337     }
2338
2339   return FG_OPTIONS_OK;
2340 }
2341   
2342 void Options::showUsage() const
2343 {
2344   fgOptLogLevel( "alert" );
2345   
2346   FGLocale *locale = globals->get_locale();
2347   SGPropertyNode options_root;
2348   
2349   simgear::requestConsole(); // ensure console is shown on Windows
2350   cout << endl;
2351
2352   try {
2353     fgLoadProps("options.xml", &options_root);
2354   } catch (const sg_exception &) {
2355     cout << "Unable to read the help file." << endl;
2356     cout << "Make sure the file options.xml is located in the FlightGear base directory," << endl;
2357     cout << "and the location of the base directory is specified by setting $FG_ROOT or" << endl;
2358     cout << "by adding --fg-root=path as a program argument." << endl;
2359     
2360     exit(-1);
2361   }
2362
2363   SGPropertyNode *options = options_root.getNode("options");
2364   if (!options) {
2365     SG_LOG( SG_GENERAL, SG_ALERT,
2366            "Error reading options.xml: <options> directive not found." );
2367     exit(-1);
2368   }
2369
2370   if (!locale->loadResource("options"))
2371   {
2372       cout << "Unable to read the language resource." << endl;
2373       exit(-1);
2374   }
2375
2376   const char* usage = locale->getLocalizedString(options->getStringValue("usage"), "options");
2377   if (usage) {
2378     cout << usage << endl;
2379   }
2380   
2381   vector<SGPropertyNode_ptr>section = options->getChildren("section");
2382   for (unsigned int j = 0; j < section.size(); j++) {
2383     string msg = "";
2384     
2385     vector<SGPropertyNode_ptr>option = section[j]->getChildren("option");
2386     for (unsigned int k = 0; k < option.size(); k++) {
2387       
2388       SGPropertyNode *name = option[k]->getNode("name");
2389       SGPropertyNode *short_name = option[k]->getNode("short");
2390       SGPropertyNode *key = option[k]->getNode("key");
2391       SGPropertyNode *arg = option[k]->getNode("arg");
2392       bool brief = option[k]->getNode("brief") != 0;
2393       
2394       if ((brief || p->verbose) && name) {
2395         string tmp = name->getStringValue();
2396         
2397         if (key){
2398           tmp.append(":");
2399           tmp.append(key->getStringValue());
2400         }
2401         if (arg) {
2402           tmp.append("=");
2403           tmp.append(arg->getStringValue());
2404         }
2405         if (short_name) {
2406           tmp.append(", -");
2407           tmp.append(short_name->getStringValue());
2408         }
2409         
2410         if (tmp.size() <= 25) {
2411           msg+= "   --";
2412           msg += tmp;
2413           msg.append( 27-tmp.size(), ' ');
2414         } else {
2415           msg += "\n   --";
2416           msg += tmp + '\n';
2417           msg.append(32, ' ');
2418         }
2419         // There may be more than one <description> tag associated
2420         // with one option
2421         
2422         vector<SGPropertyNode_ptr> desc;
2423         desc = option[k]->getChildren("description");
2424         if (! desc.empty()) {
2425           for ( unsigned int l = 0; l < desc.size(); l++) {
2426             string t = desc[l]->getStringValue();
2427
2428             // There may be more than one translation line.
2429             vector<SGPropertyNode_ptr>trans_desc = locale->getLocalizedStrings(t.c_str(),"options");
2430             for ( unsigned int m = 0; m < trans_desc.size(); m++ ) {
2431               string t_str = trans_desc[m]->getStringValue();
2432               
2433               if ((m > 0) || ((l > 0) && m == 0)) {
2434                 msg.append( 32, ' ');
2435               }
2436               
2437               // If the string is too large to fit on the screen,
2438               // then split it up in several pieces.
2439               
2440               while ( t_str.size() > 47 ) {
2441                 
2442                 string::size_type m = t_str.rfind(' ', 47);
2443                 msg += t_str.substr(0, m) + '\n';
2444                 msg.append( 32, ' ');
2445                 
2446                 t_str.erase(t_str.begin(), t_str.begin() + m + 1);
2447               }
2448               msg += t_str + '\n';
2449             }
2450           }
2451         }
2452       }
2453     }
2454     
2455     const char* name = locale->getLocalizedString(section[j]->getStringValue("name"),"options");
2456     if (!msg.empty() && name) {
2457       cout << endl << name << ":" << endl;
2458       cout << msg;
2459       msg.erase();
2460     }
2461   }
2462   
2463   if ( !p->verbose ) {
2464     const char* verbose_help = locale->getLocalizedString(options->getStringValue("verbose-help"),"options");
2465     if (verbose_help)
2466         cout << endl << verbose_help << endl;
2467   }
2468 #ifdef _MSC_VER
2469   std::cout << "Hit a key to continue..." << std::endl;
2470   std::cin.get();
2471 #endif
2472 }
2473   
2474 #if defined(__CYGWIN__)
2475 string Options::platformDefaultRoot() const
2476 {
2477   return "../data";
2478 }
2479
2480 #elif defined(SG_WINDOWS)
2481 string Options::platformDefaultRoot() const
2482 {
2483   return "..\\data";
2484 }
2485 #elif defined(SG_MAC)
2486 // platformDefaultRoot defined in CocoaHelpers.mm
2487 #else
2488 string Options::platformDefaultRoot() const
2489 {
2490   return PKGLIBDIR;
2491 }
2492 #endif
2493   
2494 void Options::setupRoot(int argc, char **argv)
2495 {
2496   string root;
2497     bool usingDefaultRoot = false;
2498
2499   if (isOptionSet("fg-root")) {
2500     root = valueForOption("fg-root"); // easy!
2501   } else {
2502   // Next check if fg-root is set as an env variable
2503     char *envp = ::getenv( "FG_ROOT" );
2504     if ( envp != NULL ) {
2505       root = envp;
2506     } else {
2507         usingDefaultRoot = true;
2508       root = platformDefaultRoot();
2509     }
2510   } 
2511   
2512   SG_LOG(SG_GENERAL, SG_INFO, "fg_root = " << root );
2513   globals->set_fg_root(root);
2514     static char required_version[] = FLIGHTGEAR_VERSION;
2515     string base_version = fgBasePackageVersion(root);
2516
2517 #if defined(HAVE_QT)
2518     if (base_version != required_version) {
2519         flightgear::initApp(argc, argv);
2520         if (SetupRootDialog::restoreUserSelectedRoot()) {
2521             SG_LOG(SG_GENERAL, SG_INFO, "restored user selected fg_root = " << globals->get_fg_root() );
2522             return;
2523         }
2524
2525         SetupRootDialog dlg(usingDefaultRoot);
2526         dlg.exec();
2527         if (dlg.result() != QDialog::Accepted) {
2528             exit(-1);
2529         }
2530     }
2531 #else
2532     // validate it
2533     if (base_version.empty()) {
2534         flightgear::fatalMessageBox("Base package not found",
2535                                     "Required data files not found, check your installation.",
2536                                     "Looking for base-package files at: '" + root + "'");
2537
2538         exit(-1);
2539     }
2540     
2541     if (base_version != required_version) {
2542       flightgear::fatalMessageBox("Base package version mismatch",
2543                                   "Version check failed: please check your installation.",
2544                                   "Found data files for version '" + base_version +
2545                                   "' at '" + globals->get_fg_root() + "', version '"
2546                                   + required_version + "' is required.");
2547
2548     exit(-1);
2549   }
2550 #endif
2551 }
2552   
2553 bool Options::shouldLoadDefaultConfig() const
2554 {
2555   return p->shouldLoadDefaultConfig;
2556 }
2557
2558 bool Options::checkForArg(int argc, char* argv[], const char* checkArg)
2559 {
2560     for (int i = 0; i < argc; ++i) {
2561         char* arg = argv[i];
2562         if (!strncmp("--", arg, 2) && !strcmp(arg + 2, checkArg)) {
2563             return true;
2564         }
2565         
2566         if ((arg[0] == '-') && !strcmp(arg + 1, checkArg)) {
2567             return true;
2568         }
2569     }
2570     
2571     return false;
2572 }
2573     
2574 } // of namespace flightgear
2575