Esempio n. 1
0
/**
 * Load topology from a plain file, load the other files from the same
 * directory.
 */
static bool
LoadConfiguredTopologyFile(TopologyStore &store)
{
  TCHAR file[MAX_PATH];
  if (!Profile::GetPath(szProfileTopologyFile, file))
    return false;

  FileLineReaderA reader(file);
  if (reader.error()) {
    LogStartUp(_T("No topology file: %s"), file);
    return false;
  }

  TCHAR buffer[MAX_PATH];
  const TCHAR *directory = DirName(file, buffer);
  if (directory == NULL)
    return false;

  store.Load(reader, directory);
  return true;
}
Esempio n. 2
0
/**
 * Load topology from the map file (ZIP), load the other files from
 * the same ZIP file.
 */
static bool
LoadConfiguredTopologyZip(TopologyStore &store)
{
  TCHAR path[MAX_PATH];
  if (!Profile::GetPath(szProfileMapFile, path))
    return false;

  ZZIP_DIR *dir = zzip_dir_open(NarrowPathName(path), NULL);
  if (dir == NULL)
    return false;

  ZipLineReaderA reader(dir, "topology.tpl");
  if (reader.error()) {
    LogStartUp(_T("No topology in map file: %s"), path);
    return false;
  }

  store.Load(reader, NULL, dir);
  zzip_dir_close(dir);
  return true;
}
Esempio n. 3
0
void
DeviceDescriptor::Open(OperationEnvironment &env)
{
  assert(InMainThread());
  assert(port == NULL);
  assert(device == NULL);
  assert(!ticker);
  assert(!IsBorrowed());

  if (is_simulator() || !config.IsAvailable())
    return;

  CancelAsync();

  assert(!IsOccupied());
  assert(open_job == NULL);

  TCHAR buffer[64];
  LogStartUp(_T("Opening device %s"), config.GetPortName(buffer, 64));

  open_job = new OpenDeviceJob(*this);
  async.Start(open_job, env, this);
}
Esempio n. 4
0
void
BatteryTimer::Process()
{
#ifdef HAVE_BATTERY
  // TODO feature: Trigger a GCE (Glide Computer Event) when
  // switching to battery mode This can be used to warn users that
  // power has been lost and you are now on battery power - ie:
  // something else is wrong

  UpdateBatteryInfo();

  /* Battery status - simulator only - for safety of battery data
     note: Simulator only - more important to keep running in your plane
  */

  // JMW, maybe this should be active always...
  // we don't want the PDA to be completely depleted.

  if (Power::External::Status == Power::External::OFF) {
    if (is_simulator() && Power::Battery::RemainingPercentValid &&
        Power::Battery::RemainingPercent < BATTERY_EXIT) {
      LogStartUp(_T("Battery low exit..."));
      // TODO feature: Warning message on battery shutdown
      XCSoarInterface::SignalShutdown(true);
    } else {
      if (Power::Battery::RemainingPercentValid &&
          Power::Battery::RemainingPercent < BATTERY_WARNING) {
        if (last_warning.check_update(BATTERY_REMINDER))
          // TODO feature: Show the user what the batt status is.
          Message::AddMessage(_("Battery low"));
      } else {
        last_warning.reset();
      }
    }
  }
#endif /* HAVE_BATTERY */
}
void
Profile::Use()
{
  unsigned Temp = 0;

  LogStartUp(_T("Read registry settings"));

  OrderedTaskBehaviour &osettings_task = 
    XCSoarInterface::SetSettingsComputer().ordered_defaults;

  TaskBehaviour &settings_task = 
    XCSoarInterface::SetSettingsComputer();

  Get(szProfileFinishMinHeight,
		  osettings_task.finish_min_height);
  Get(szProfileStartHeightRef,
		  osettings_task.start_max_height_ref);
  Get(szProfileStartMaxHeight,
		  osettings_task.start_max_height);
  Get(szProfileStartMaxSpeed,
		  osettings_task.start_max_speed);

  Get(szProfileStartMaxHeightMargin,
		  settings_task.start_max_height_margin);
  Get(szProfileStartMaxSpeedMargin,
		  settings_task.start_max_speed_margin);

  unsigned sdtemp = 0;
  Get(szProfileStartType, sdtemp);
  settings_task.sector_defaults.start_type =
      (AbstractTaskFactory::LegalPointType_t)sdtemp;
  Get(szProfileStartRadius,
      settings_task.sector_defaults.start_radius);

  Get(szProfileTurnpointType, sdtemp);
      settings_task.sector_defaults.turnpoint_type =
          (AbstractTaskFactory::LegalPointType_t)sdtemp;
  Get(szProfileTurnpointRadius,
      settings_task.sector_defaults.turnpoint_radius);

  Get(szProfileFinishType, sdtemp);
      settings_task.sector_defaults.finish_type =
          (AbstractTaskFactory::LegalPointType_t)sdtemp;
  Get(szProfileFinishRadius,
      settings_task.sector_defaults.finish_radius);

  Get(szProfileTaskType, sdtemp);
      settings_task.task_type_default =
          (TaskBehaviour::Factory_t)sdtemp;

  Get(szProfileAATMinTime,
      osettings_task.aat_min_time);

  Get(szProfileAATTimeMargin,
      settings_task.optimise_targets_margin);

  LoadUnits();
  Profile::GetInfoBoxManagerConfig(infoBoxManagerConfig);

  SETTINGS_MAP &settings_map = XCSoarInterface::SetSettingsMap();

  bool orientation_found = false;

  Temp = NORTHUP;
  if (Get(szProfileOrientationCircling, Temp))
    orientation_found = true;

  switch (Temp) {
  case TRACKUP:
    settings_map.OrientationCircling = TRACKUP;
    break;
  case NORTHUP:
    settings_map.OrientationCircling = NORTHUP;
    break;
  case TARGETUP:
    settings_map.OrientationCircling = TARGETUP;
    break;
  }

  Temp = NORTHUP;
  if (Get(szProfileOrientationCruise, Temp))
    orientation_found = true;

  switch (Temp) {
  case TRACKUP:
    settings_map.OrientationCruise = TRACKUP;
    break;
  case NORTHUP:
    settings_map.OrientationCruise = NORTHUP;
    break;
  case TARGETUP:
    settings_map.OrientationCruise = TARGETUP;
    break;
  }

  if (!orientation_found) {
    Temp = 1;
    Get(szProfileDisplayUpValue, Temp);
    switch (Temp) {
    case 0:
      settings_map.OrientationCruise = TRACKUP;
      settings_map.OrientationCircling = TRACKUP;
      break;
    case 1:
      settings_map.OrientationCruise = NORTHUP;
      settings_map.OrientationCircling = NORTHUP;
      break;
    case 2:
      settings_map.OrientationCruise = TRACKUP;
      settings_map.OrientationCircling = NORTHUP;
      break;
    case 3:
      settings_map.OrientationCruise = TRACKUP;
      settings_map.OrientationCircling = TARGETUP;
      break;
    case 4:
      settings_map.OrientationCruise = NORTHUP;
      settings_map.OrientationCircling = TRACKUP;
      break;
    }
  }

  GetEnum(szProfileMapShiftBias, settings_map.MapShiftBias);

  settings_map.waypoint.LoadFromProfile();

  SETTINGS_COMPUTER &settings_computer =
    XCSoarInterface::SetSettingsComputer();

  Get(szProfileSafetyAltitudeArrival,
      settings_computer.safety_height_arrival);
  Get(szProfileSafetyAltitudeTerrain,
      settings_computer.route_planner.safety_height_terrain);

  LoadAirspaceConfig();

  GetEnum(szProfileSnailTrail, settings_map.trail_length);

  Get(szProfileTrailDrift,
      settings_map.EnableTrailDrift);

  Get(szProfileDetourCostMarker,
      settings_map.EnableDetourCostMarker);

  GetEnum(szProfileDisplayTrackBearing, settings_map.DisplayTrackBearing);

  Get(szProfileDrawTopography,
      settings_map.EnableTopography);

  LoadTerrainRendererSettings(settings_map.terrain);

  GetEnum(szProfileFinalGlideTerrain,
          settings_computer.FinalGlideTerrain);

  Get(szProfileAutoWind,
      settings_computer.AutoWindMode);

  Get(szProfileExternalWind,
      settings_computer.ExternalWind);

  Get(szProfileCircleZoom,
      settings_map.CircleZoom);

  Get(szProfileMaxAutoZoomDistance,
      settings_map.MaxAutoZoomDistance);

  Get(szProfileHomeWaypoint,
      settings_computer.HomeWaypoint);

  settings_computer.HomeLocationAvailable =
    GetGeoPoint(szProfileHomeLocation, settings_computer.HomeLocation);

  Get(szProfileSnailWidthScale,
      settings_map.SnailScaling);

  GetEnum(szProfileSnailType, settings_map.SnailType);

  Get(szProfileTeamcodeRefWaypoint,
      settings_computer.TeamCodeRefWaypoint);

  Get(szProfileSoundVolume,
      settings_computer.SoundVolume);

  Get(szProfileSoundDeadband,
      settings_computer.SoundDeadband);

  Get(szProfileSoundAudioVario,
      settings_computer.EnableSoundVario);

  Get(szProfileSoundTask,
      settings_computer.EnableSoundTask);

  Get(szProfileSoundModes,
      settings_computer.EnableSoundModes);

#ifdef HAVE_BLANK
  Get(szProfileAutoBlank,
      settings_map.EnableAutoBlank);
#endif

  if (Get(szProfileAverEffTime, Temp))
    settings_computer.AverEffTime = Temp;

  Get(szProfileDebounceTimeout, XCSoarInterface::debounceTimeout);

  /* JMW broken
  if (Get(szProfileAccelerometerZero, Temp))
    AccelerometerZero = Temp;
  if (AccelerometerZero==0.0) {
    AccelerometerZero= 100.0;
    Temp = 100;
    Set(szProfileAccelerometerZero, Temp);
  }
  */

  // new appearance variables
 
  Get(szProfileAppInverseInfoBox,
		  Appearance.InverseInfoBox);

  GetEnum(szProfileAppInfoBoxBorder, Appearance.InfoBoxBorder);
  GetEnum(szProfileAppStatusMessageAlignment, Appearance.StateMessageAlign);
  GetEnum(szProfileAppTextInputStyle, Appearance.TextInputStyle);
  GetEnum(szProfileAppDialogTabStyle, Appearance.DialogTabStyle);
  GetEnum(szProfileAppDialogStyle, DialogStyleSetting);

  Get(szProfileAppInfoBoxColors,
		  Appearance.InfoBoxColors);

  Get(szProfileAutoMc, settings_computer.auto_mc);
  GetEnum(szProfileAutoMcMode, settings_computer.auto_mc_mode);

  if (GetEnum(szProfileOLCRules, settings_computer.contest))
  {
      if ( settings_computer.contest == OLC_Sprint )
        settings_computer.contest = OLC_League; // Handle out-dated Sprint rule in profile
  }

  Get(szProfileEnableExternalTriggerCruise,
      settings_computer.EnableExternalTriggerCruise);

  Get(szProfileUTCOffset,
      settings_computer.UTCOffset);
  if (settings_computer.UTCOffset > 12 * 3600)
    settings_computer.UTCOffset -= 24 * 3600;

  Get(szProfileBlockSTF,
      settings_computer.EnableBlockSTF);
  Get(szProfileAutoZoom,
      settings_map.AutoZoom);
  Get(szProfileMenuTimeout,
      XCSoarInterface::MenuTimeoutMax);
  Get(szProfileLoggerShort,
      settings_computer.LoggerShortName);
  Get(szProfileEnableFLARMMap,
      settings_map.EnableFLARMMap);
  Get(szProfileEnableFLARMGauge,
      settings_map.EnableFLARMGauge);
  Get(szProfileAutoCloseFlarmDialog,
      settings_map.AutoCloseFlarmDialog);
  Get(szProfileEnableTAGauge,
      settings_map.EnableTAGauge);
  Get(szProfileEnableThermalProfile,
      settings_map.EnableThermalProfile);

  Get(szProfileGliderScreenPosition,
      settings_map.GliderScreenPosition);
  Get(szProfileSetSystemTimeFromGPS,
      settings_map.SetSystemTimeFromGPS);
  Get(szProfileUseCustomFonts,
      Appearance.UseCustomFonts);
  Get(szProfileVoiceClimbRate,
      settings_computer.EnableVoiceClimbRate);
  Get(szProfileVoiceTerrain,
      settings_computer.EnableVoiceTerrain);
  Get(szProfileVoiceWaypointDistance,
      settings_computer.EnableVoiceWaypointDistance);
  Get(szProfileVoiceTaskAltitudeDifference,
      settings_computer.EnableVoiceTaskAltitudeDifference);
  Get(szProfileVoiceMacCready,
      settings_computer.EnableVoiceMacCready);
  Get(szProfileVoiceNewWaypoint,
      settings_computer.EnableVoiceNewWaypoint);
  Get(szProfileVoiceInSector,
      settings_computer.EnableVoiceInSector);
  Get(szProfileVoiceAirspace,
      settings_computer.EnableVoiceAirspace);
  Get(szProfileEnableNavBaroAltitude,
      settings_computer.EnableNavBaroAltitude);
  Get(szProfileLoggerTimeStepCruise,
      settings_computer.LoggerTimeStepCruise);
  Get(szProfileLoggerTimeStepCircling,
      settings_computer.LoggerTimeStepCircling);

  if (Get(szProfileSafetyMacCready, Temp))
    settings_computer.safety_mc = fixed(Temp) / 10;

  GetEnum(szProfileAbortTaskMode, settings_computer.abort_task_mode);

  GetEnum(szProfileRoutePlannerMode, settings_computer.route_planner.mode);

  Get(szProfileRoutePlannerAllowClimb,
      settings_computer.route_planner.allow_climb);

  Get(szProfileRoutePlannerUseCeiling,
      settings_computer.route_planner.use_ceiling);

  GetEnum(szProfileTurningReach,
          settings_computer.route_planner.reach_calc_mode);

  GetEnum(szProfileReachPolarMode,
          settings_computer.route_planner.reach_polar_mode);

  if (Get(szProfileRiskGamma, Temp))
    settings_computer.risk_gamma = fixed(Temp) / 10;

  if (Get(szProfileWindArrowStyle, Temp))
    settings_map.WindArrowStyle = Temp;

  Get(szProfileDisableAutoLogger,
      settings_computer.DisableAutoLogger);

  GetEnum(szProfileAircraftSymbol, Appearance.AircraftSymbol);
}
Esempio n. 6
0
static Port *
OpenPortInternal(const DeviceConfig &config, DataHandler &handler)
{
  const TCHAR *path = NULL;
  TCHAR buffer[MAX_PATH];

  switch (config.port_type) {
  case DeviceConfig::PortType::DISABLED:
    return NULL;

  case DeviceConfig::PortType::SERIAL:
    if (config.path.empty())
      return NULL;

    path = config.path.c_str();
    break;

  case DeviceConfig::PortType::RFCOMM:
#ifdef ANDROID
    if (config.bluetooth_mac.empty()) {
      LogFormat("No Bluetooth MAC configured");
      return NULL;
    }

    return OpenAndroidBluetoothPort(config.bluetooth_mac, handler);
#else
    LogFormat("Bluetooth not available on this platform");
    return NULL;
#endif

  case DeviceConfig::PortType::RFCOMM_SERVER:
#ifdef ANDROID
    return OpenAndroidBluetoothServerPort(handler);
#else
    LogFormat("Bluetooth not available on this platform");
    return NULL;
#endif

  case DeviceConfig::PortType::IOIOUART:
#if defined(ANDROID) && defined(IOIOLIB)
    if (config.ioio_uart_id >= AndroidIOIOUartPort::getNumberUarts()) {
      LogFormat("No IOIOUart configured in profile");
      return NULL;
    }

    return OpenAndroidIOIOUartPort(config.ioio_uart_id, config.baud_rate,
                                   handler);
#else
    LogFormat("IOIO Uart not available on this platform or version");
    return NULL;
#endif

  case DeviceConfig::PortType::AUTO:
    if (!DetectGPS(buffer, sizeof(buffer))) {
      LogFormat("no GPS detected");
      return NULL;
    }

    LogStartUp(_T("GPS detected: %s"), buffer);

    path = buffer;
    break;

  case DeviceConfig::PortType::INTERNAL:
  case DeviceConfig::PortType::DROIDSOAR_V2:
  case DeviceConfig::PortType::NUNCHUCK:
  case DeviceConfig::PortType::I2CPRESSURESENSOR:
  case DeviceConfig::PortType::IOIOVOLTAGE:
  case DeviceConfig::PortType::ADCAIRSPEED:
    break;

  case DeviceConfig::PortType::TCP_LISTENER: {
    TCPPort *port = new TCPPort(handler);
    if (!port->Open(config.tcp_port)) {
      delete port;
      return NULL;
    }

    return port;
  }

  case DeviceConfig::PortType::UDP_LISTENER: {
    SocketPort *port = new SocketPort(handler);
    if (!port->OpenUDPListener(config.tcp_port)) {
      delete port;
      return NULL;
    }

    return port;
  }

  case DeviceConfig::PortType::PTY: {
#if defined(HAVE_POSIX) && !defined(ANDROID)
    if (config.path.empty())
      return NULL;

    if (unlink(config.path.c_str()) < 0 && errno != ENOENT)
      return NULL;

    TTYPort *port = new TTYPort(handler);
    const char *slave_path = port->OpenPseudo();
    if (slave_path == NULL) {
      delete port;
      return NULL;
    }

    if (symlink(slave_path, config.path.c_str()) < 0) {
      delete port;
      return NULL;
    }

    return port;
#else
    return NULL;
#endif
  }
  }

  if (path == NULL)
    return NULL;

#ifdef HAVE_POSIX
  TTYPort *port = new TTYPort(handler);
#else
  SerialPort *port = new SerialPort(handler);
#endif
  if (!port->Open(path, config.baud_rate)) {
    delete port;
    return NULL;
  }

  return port;
}
Esempio n. 7
0
bool
DumpPort::StartRxThread()
{
  LogStartUp(_T("StartRxThread"));
  return other.StartRxThread();
}
Esempio n. 8
0
  void commit(InputConfig &config, unsigned line) {
    if (empty())
      return;

    TCHAR *token;

    // For each mode
    token = mode.first_token(_T(" "));

    // General errors - these should be true
    assert(location < 1024);

    const TCHAR *new_label = NULL;
    while (token != NULL) {

      // All modes are valid at this point
      int mode_id = config.MakeMode(token);
      assert(mode_id >= 0);

      // Make label event
      // TODO code: Consider Reuse existing entries...
      if (location > 0) {
        // Only copy this once per object - save string space
        if (!new_label) {
          new_label = UnescapeBackslash(label);
        }

        config.AppendMenu(mode_id, new_label, location, event_id);
      }

      // Make key (Keyboard input)
      // key - Hardware key or keyboard
      if (type.equals(_T("key"))) {
        // Get the int key (eg: APP1 vs 'a')
        unsigned key = ParseKeyCode(data);
        if (key > 0)
          config.Key2Event[mode_id][key] = event_id;
        else
          LogStartUp(_T("Invalid key data: %s at %u"), data.c_str(), line);

        // Make gce (Glide Computer Event)
        // GCE - Glide Computer Event
      } else if (type.equals(_T("gce"))) {
        // Get the int key (eg: APP1 vs 'a')
        int key = InputEvents::findGCE(data);
        if (key >= 0)
          config.GC2Event[key] = event_id;
        else
          LogStartUp(_T("Invalid GCE data: %s at %u"), data.c_str(), line);

        // Make gesture (Gesture Event)
        // Key - Key Event
      } else if (type.equals(_T("gesture"))) {
        // Check data for invalid characters:
        bool valid = true;
        for (const TCHAR* c = data; *c; c++)
          if (*c != _T('U') &&
              *c != _T('D') &&
              *c != _T('R') &&
              *c != _T('L'))
            valid = false;
        
        if (valid) {
          // One entry per key: delete old, create new
          config.Gesture2Event.Remove(data.c_str());
          config.Gesture2Event.Add(data.c_str(), event_id);
        } else
          LogStartUp(_T("Invalid gesture data: %s at %u"), data.c_str(), line);

        // Make ne (NMEA Event)
        // NE - NMEA Event
      } else if (type.equals(_T("ne"))) {
        // Get the int key (eg: APP1 vs 'a')
        int key = InputEvents::findNE(data);
        if (key >= 0)
          config.N2Event[key] = event_id;
        else
          LogStartUp(_T("Invalid GCE data: %s at %u"), data.c_str(), line);

        // label only - no key associated (label can still be touch screen)
      } else if (type.equals(_T("label"))) {
        // Nothing to do here...

      } else {
        LogStartUp(_T("Invalid type: %s at %u"), type.c_str(), line);
      }

      token = mode.next_token(_T(" "));
    }
  }
Esempio n. 9
0
static unsigned
AutoDetect()
{
#ifndef HAVE_POSIX

#if defined(_WIN32_WCE)
  /* the GetUserDefaultUILanguage() prototype is missing on
     mingw32ce, we have to look it up dynamically */
  DynamicLibrary coreloc_dll(_T("coredll"));
  if (!coreloc_dll.defined()) {
    LogStartUp(_T("Units: coredll.dll not found"));
    return 0;
  }

  typedef LANGID WINAPI (*GetUserDefaultUILanguage_t)();
  GetUserDefaultUILanguage_t GetUserDefaultUILanguage =
    (GetUserDefaultUILanguage_t)
    coreloc_dll.lookup(_T("GetUserDefaultUILanguage"));
  if (GetUserDefaultUILanguage == NULL) {
    LogStartUp(_T("Units: GetUserDefaultUILanguage() not available"));
    return 0;
  }
#endif

  // Retrieve the default user language identifier from the OS
  LANGID lang_id = GetUserDefaultUILanguage();
  LogStartUp(_T("Units: GetUserDefaultUILanguage() = 0x%x"), (int)lang_id);
  if (lang_id == 0)
    return 0;

  return find_language(lang_id);

#elif defined(ANDROID)
  JNIEnv *env = Java::GetEnv();

  Java::Class cls(env, "java/util/Locale");

  // Call static function Locale.getDefault() that
  // returns the user's default Locale object

  jmethodID cid = env->GetStaticMethodID(cls, "getDefault",
                                         "()Ljava/util/Locale;");
  assert(cid != NULL);

  jobject _obj = env->CallStaticObjectMethod(cls, cid);
  if (_obj == NULL)
    return 0;

  Java::LocalObject obj(env, _obj);

  // Call function Locale.getLanguage() that
  // returns a two-letter language string

  cid = env->GetMethodID(cls, "toString", "()Ljava/lang/String;");
  assert(cid != NULL);

  jstring language = (jstring)env->CallObjectMethod(obj, cid);
  if (language == NULL)
    return 0;

  // Convert the jstring to a char string
  const char *language2 = env->GetStringUTFChars(language, NULL);
  if (language2 == NULL) {
    env->DeleteLocalRef(language);
    return 0;
  }

  unsigned id = find_language(language2);

  // Clean up the memory
  env->ReleaseStringUTFChars(language, language2);
  env->DeleteLocalRef(language);

  // Return e.g. "de.mo"
  return id;

#else
  // Metric default on Linux
  return 0;
#endif
}
Esempio n. 10
0
void
DumpPort::Flush()
{
  LogStartUp(_T("Flush"));
  port->Flush();
}
Esempio n. 11
0
/**
 * "Boots" up XCSoar
 * @param hInstance Instance handle
 * @param lpCmdLine Command line string
 * @return True if bootup successful, False otherwise
 */
bool
XCSoarInterface::Startup(HINSTANCE hInstance)
{
  // Set the application title to "XCSoar"
  TCHAR szTitle[] = _T("XCSoar");

  // Store instance handle in our global variable
#ifdef WIN32
  ResourceLoader::Init(hInstance);
#endif

  //If "XCSoar" is already running, stop this instance
  if (MainWindow::find(szTitle))
    return false;

  // Register window classes
  PaintWindow::register_class(hInstance);
  MainWindow::register_class(hInstance);

  // Creates the main window
  LogStartUp(_T("Create main window"));
  PixelRect WindowSize = SystemWindowSize();
  main_window.set(szTitle,
                  WindowSize.left, WindowSize.top,
                  WindowSize.right, WindowSize.bottom);
  if (!main_window.defined())
    return false;

  main_window.Initialise();

#ifdef SIMULATOR_AVAILABLE
  // prompt for simulator if not set by command line argument "-simulator" or "-fly"
  if (!sim_set_in_cmd_line_flag) {
    SimulatorPromptResult result = dlgSimulatorPromptShowModal();
    switch (result) {
    case SPR_QUIT:
      return false;

    case SPR_FLY:
      global_simulator_flag = false;
      break;

    case SPR_SIMULATOR:
      global_simulator_flag = true;
      break;
    }
  }
#endif

  if (!LoadProfile())
    return false;

  ProgressGlue::Create(_("Initialising"));

  LoadDisplayOrientation();

  main_window.InitialiseConfigured();

  TCHAR path[MAX_PATH];
  LocalPath(path, _T("cache"));
  file_cache = new FileCache(path);

  Graphics::InitialiseConfigured(SettingsMap());

  ReadLanguageFile();

  status_messages.LoadFile();
  InputEvents::readFile();

  // Initialize DeviceBlackboard
  device_blackboard.Initialise();

  // Initialize Marks
  marks = new Marks();

  // Send the SettingsMap to the DeviceBlackboard
  SendSettingsMap();

  // Show the main and map windows
  LogStartUp(_T("Create map window"));
  main_window.show();
  main_window.map.show();

#ifdef HAVE_AYGSHELL_DLL
  const AYGShellDLL &ayg = main_window.ayg_shell_dll;
  ayg.SHSetAppKeyWndAssoc(VK_APP1, main_window);
  ayg.SHSetAppKeyWndAssoc(VK_APP2, main_window);
  ayg.SHSetAppKeyWndAssoc(VK_APP3, main_window);
  ayg.SHSetAppKeyWndAssoc(VK_APP4, main_window);
  // Typical Record Button
  //	Why you can't always get this to work
  //	http://forums.devbuzz.com/m_1185/mpage_1/key_/tm.htm
  //	To do with the fact it is a global hotkey, but you can with code above
  //	Also APPA is record key on some systems
  ayg.SHSetAppKeyWndAssoc(VK_APP5, main_window);
  ayg.SHSetAppKeyWndAssoc(VK_APP6, main_window);
#endif

  // Initialize main blackboard data
  task_manager = new TaskManager(task_events, way_points);
  task_manager->reset();

  protected_task_manager =
    new ProtectedTaskManager(*task_manager,
                             XCSoarInterface::SettingsComputer(),
                             task_events, airspace_database);

  airspace_warning = new AirspaceWarningManager(airspace_database,
                                                *task_manager);
  airspace_warnings = new ProtectedAirspaceWarningManager(*airspace_warning);

  // Read the terrain file
  ProgressGlue::Create(_("Loading Terrain File..."));
  LogStartUp(_T("OpenTerrain"));
  terrain = RasterTerrain::OpenTerrain(file_cache);

  glide_computer = new GlideComputer(way_points, *protected_task_manager,
                                     *airspace_warnings,
                                     task_events);
  glide_computer->set_terrain(terrain);
  glide_computer->SetLogger(&logger);
  glide_computer->Initialise();

  replay = new Replay(*protected_task_manager);

  // Load the EGM96 geoid data
  OpenGeoid();

  GlidePolar &gp = SetSettingsComputer().glide_polar_task;
  gp = GlidePolar(fixed_zero);
  PolarGlue::LoadFromProfile(gp, SetSettingsComputer());
  task_manager->set_glide_polar(gp);

  task_manager->set_contest(SettingsComputer().contest);

  // Read the topography file(s)
  topography = new TopographyStore();
  LoadConfiguredTopography(*topography);

  // Read the waypoint files
  WayPointGlue::LoadWaypoints(way_points, terrain);

  // Read and parse the airfield info file
  ReadAirfieldFile(way_points);

  // Set the home waypoint
  WayPointGlue::SetHome(way_points, terrain, SetSettingsComputer(),
                        false);

  // ReSynchronise the blackboards here since SetHome touches them
  ReadBlackboardBasic(device_blackboard.Basic());

  // Scan for weather forecast
  ProgressGlue::Create(_("Scanning weather forecast"));
  LogStartUp(_T("RASP load"));
  RASP.ScanAll(Basic().Location);

  // Reads the airspace files
  ReadAirspace(airspace_database, terrain, SettingsComputer().pressure);

  const AIRCRAFT_STATE aircraft_state =
    ToAircraftState(device_blackboard.Basic(), device_blackboard.Calculated());
  airspace_warning->reset(aircraft_state);
  airspace_warning->set_config(CommonInterface::SettingsComputer().airspace.warnings);

  // Read the FLARM details file
  FlarmDetails::Load();

#ifndef DISABLEAUDIOVARIO
  /*
  VarioSound_Init();
  VarioSound_EnableSound(EnableSoundVario);
  VarioSound_SetVdead(SoundDeadband);
  VarioSound_SetV(0);
  VarioSound_SetSoundVolume(SoundVolume);
  */
#endif

  // Start the device thread(s)
  ProgressGlue::Create(_("Starting devices"));
  devStartup();

/*
  -- Reset polar in case devices need the data
  LogStartUp(_T("GlidePolar::UpdatePolar"));
  GlidePolar::UpdatePolar(true, SettingsComputer());

  This should be done inside devStartup if it is really required
*/

  ProgressGlue::Create(_("Initialising display"));

  main_window.map.set_way_points(&way_points);
  main_window.map.set_task(protected_task_manager);
  main_window.map.set_airspaces(&airspace_database, airspace_warnings);

  main_window.map.set_topography(topography);
  main_window.map.set_terrain(terrain);
  main_window.map.set_weather(&RASP);
  main_window.map.set_marks(marks);
  main_window.map.SetLogger(&logger);

  // Finally ready to go.. all structures must be present before this.

  // Create the drawing thread
#ifndef ENABLE_OPENGL
  LogStartUp(_T("CreateDrawingThread"));
  draw_thread = new DrawThread(main_window.map, main_window.flarm,
                               main_window.ta);
  draw_thread->start();
#endif

  // Show the infoboxes
  LogStartUp(_T("ShowInfoBoxes"));
  InfoBoxManager::Show();

  // Create the calculation thread
  LogStartUp(_T("CreateCalculationThread"));
  CreateCalculationThread();

  // Find unique ID of this PDA
  ReadAssetNumber();

  LogStartUp(_T("ProgramStarted"));

  // Give focus to the map
  main_window.map.set_focus();

  Pages::LoadFromProfile();

  // Start calculation thread
  calculation_thread->start();

  globalRunningEvent.trigger();

  AfterStartup();

#ifndef ENABLE_OPENGL
  draw_thread->resume();
#endif

  return true;
}
Esempio n. 12
0
Port::WaitResult
DumpPort::WaitRead(unsigned timeout_ms)
{
  LogStartUp(_T("WaitRead %u"), timeout_ms);
  return other.WaitRead(timeout_ms);
}
Esempio n. 13
0
static Port *
OpenPortInternal(const DeviceConfig &config, Port::Handler &handler)
{
  const TCHAR *path = NULL;
  TCHAR buffer[MAX_PATH];

  switch (config.port_type) {
  case DeviceConfig::PortType::DISABLED:
    return NULL;

  case DeviceConfig::PortType::SERIAL:
    if (config.path.empty())
      return NULL;

    path = config.path.c_str();
    break;

  case DeviceConfig::PortType::RFCOMM:
#ifdef ANDROID
    if (config.bluetooth_mac.empty()) {
      LogStartUp(_T("No Bluetooth MAC configured"));
      return NULL;
    }

    return OpenAndroidBluetoothPort(config.bluetooth_mac, handler);
#else
    LogStartUp(_T("Bluetooth not available on this platform"));
    return NULL;
#endif

  case DeviceConfig::PortType::RFCOMM_SERVER:
#ifdef ANDROID
    return OpenAndroidBluetoothServerPort(handler);
#else
    LogStartUp(_T("Bluetooth not available on this platform"));
    return NULL;
#endif

  case DeviceConfig::PortType::IOIOUART:
#if defined(ANDROID) && defined(IOIOLIB)
    if (config.ioio_uart_id >= AndroidIOIOUartPort::getNumberUarts()) {
      LogStartUp(_T("No IOIOUart configured in profile"));
      return NULL;
    }

    return OpenAndroidIOIOUartPort(config.ioio_uart_id, config.baud_rate,
                                   handler);
#else
    LogStartUp(_T("IOIO Uart not available on this platform or version"));
    return NULL;
#endif

  case DeviceConfig::PortType::AUTO:
    if (!detect_gps(buffer, sizeof(buffer))) {
      LogStartUp(_T("no GPS detected"));
      return NULL;
    }

    LogStartUp(_T("GPS detected: %s"), buffer);

    path = buffer;
    break;

  case DeviceConfig::PortType::INTERNAL:
    break;

  case DeviceConfig::PortType::NETWORK_LISTENER: {
    TCPPort *tcp_port;
    UDPPort *udp_port;
    switch(config.network_protocol){
    case DeviceConfig::NetworkProtocolType::NETWORK_TCP:
      tcp_port = new TCPPort(handler);
      if (!tcp_port->Open(config.network_port)) {
        delete tcp_port;
        return NULL;
      }
      return tcp_port;
    case DeviceConfig::NetworkProtocolType::NETWORK_UDP:
      udp_port = new UDPPort(handler);
      if (!udp_port->Open(config.network_port)) {
        delete udp_port;
        return NULL;
      }
      return udp_port;
    }
  }

  case DeviceConfig::PortType::PTY: {
#if defined(HAVE_POSIX) && !defined(ANDROID)
    if (config.path.empty())
      return NULL;

    if (unlink(config.path.c_str()) < 0 && errno != ENOENT)
      return NULL;

    TTYPort *port = new TTYPort(handler);
    const char *slave_path = port->OpenPseudo();
    if (slave_path == NULL) {
      delete port;
      return NULL;
    }

    if (symlink(slave_path, config.path.c_str()) < 0) {
      delete port;
      return NULL;
    }

    return port;
#else
    return NULL;
#endif
  }
  }

  if (path == NULL)
    return NULL;

#ifdef HAVE_POSIX
  TTYPort *port = new TTYPort(handler);
#else
  SerialPort *port = new SerialPort(handler);
#endif
  if (!port->Open(path, config.baud_rate)) {
    delete port;
    return NULL;
  }

  return port;
}
Esempio n. 14
0
Marks::Marks()
{
  LogStartUp(_T("Initialise marks"));
  icon.load_big(IDB_MARK, IDB_MARK_HD);
  Reset();
}
Esempio n. 15
0
bool
DumpPort::StartRxThread()
{
  LogStartUp(_T("StartRxThread"));
  return port->StartRxThread();
}
Esempio n. 16
0
bool
DumpPort::SetBaudrate(unsigned baud_rate)
{
  LogStartUp(_T("SetBaudrate %u"), baud_rate);
  return port->SetBaudrate(baud_rate);
}
Esempio n. 17
0
bool
PCMPlayer::Start(PCMSynthesiser &_synthesiser, unsigned _sample_rate)
{
#ifdef ANDROID

  /* why, oh why is OpenSL/ES so complicated? */

  SLObjectItf _object;
  SLresult result = SLES::CreateEngine(&_object, 0, NULL, 0, NULL, NULL);
  if (result != SL_RESULT_SUCCESS) {
    LogStartUp("PCMPlayer: slCreateEngine() result=%#x", (int)result);
    return false;
  }

  engine_object = SLES::Object(_object);

  result = engine_object.Realize(false);
  if (result != SL_RESULT_SUCCESS) {
    LogStartUp("PCMPlayer: Engine.Realize() result=%#x", (int)result);
    engine_object.Destroy();
    return false;
  }

  SLEngineItf _engine;
  result = engine_object.GetInterface(*SLES::IID_ENGINE, &_engine);
  if (result != SL_RESULT_SUCCESS) {
    LogStartUp("PCMPlayer: Engine.GetInterface(IID_ENGINE) result=%#x",
               (int)result);
    engine_object.Destroy();
    return false;
  }

  SLES::Engine engine(_engine);

  result = engine.CreateOutputMix(&_object, 0, NULL, NULL);
  if (result != SL_RESULT_SUCCESS) {
    LogStartUp("PCMPlayer: CreateOutputMix() result=%#x", (int)result);
    engine_object.Destroy();
    return false;
  }

  mix_object = SLES::Object(_object);

  result = mix_object.Realize(false);
  if (result != SL_RESULT_SUCCESS) {
    LogStartUp("PCMPlayer: Mix.Realize() result=%#x", (int)result);
    mix_object.Destroy();
    engine_object.Destroy();
    return false;
  }

  SLDataLocator_AndroidSimpleBufferQueue loc_bufq = {
    SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE,
    ARRAY_SIZE(buffers) - 1,
  };

  SLDataFormat_PCM format_pcm;
  format_pcm.formatType = SL_DATAFORMAT_PCM;
  format_pcm.numChannels = 1;
  /* from the Android NDK docs: "Note that the field samplesPerSec is
     actually in units of milliHz, despite the misleading name." */
  format_pcm.samplesPerSec = _sample_rate * 1000;
  format_pcm.bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_16;
  format_pcm.containerSize = SL_PCMSAMPLEFORMAT_FIXED_16;
  format_pcm.channelMask = SL_SPEAKER_FRONT_CENTER;
  format_pcm.endianness = SL_BYTEORDER_LITTLEENDIAN; // XXX

  SLDataSource audioSrc = { &loc_bufq, &format_pcm };

  SLDataLocator_OutputMix loc_outmix = {
    SL_DATALOCATOR_OUTPUTMIX,
    mix_object,
  };

  SLDataSink audioSnk = {
    &loc_outmix,
    NULL,
  };

  const SLInterfaceID ids2[] = {
    *SLES::IID_PLAY,
    *SLES::IID_ANDROIDSIMPLEBUFFERQUEUE,
  };
  static constexpr SLboolean req2[] = {
    SL_BOOLEAN_TRUE,
    SL_BOOLEAN_TRUE,
  };
  result = engine.CreateAudioPlayer(&_object, &audioSrc, &audioSnk,
                                    ARRAY_SIZE(ids2), ids2, req2);
  if (result != SL_RESULT_SUCCESS) {
    LogStartUp("PCMPlayer: CreateAudioPlayer() result=%#x", (int)result);
    mix_object.Destroy();
    engine_object.Destroy();
    return false;
  }

  play_object = SLES::Object(_object);

  result = play_object.Realize(false);

  if (result != SL_RESULT_SUCCESS) {
    LogStartUp("PCMPlayer: Play.Realize() result=%#x", (int)result);
    play_object.Destroy();
    mix_object.Destroy();
    engine_object.Destroy();
    return false;
  }

  SLPlayItf _play;
  result = play_object.GetInterface(*SLES::IID_PLAY, &_play);
  if (result != SL_RESULT_SUCCESS) {
    LogStartUp("PCMPlayer: Play.GetInterface(IID_PLAY) result=%#x",
               (int)result);
    play_object.Destroy();
    mix_object.Destroy();
    engine_object.Destroy();
    return false;
  }

  play = SLES::Play(_play);

  SLAndroidSimpleBufferQueueItf _queue;
  result = play_object.GetInterface(*SLES::IID_ANDROIDSIMPLEBUFFERQUEUE,
                                    &_queue);
  if (result != SL_RESULT_SUCCESS) {
    LogStartUp("PCMPlayer: Play.GetInterface(IID_ANDROIDSIMPLEBUFFERQUEUE) result=%#x",
               (int)result);
    play_object.Destroy();
    mix_object.Destroy();
    engine_object.Destroy();
    return false;
  }

  queue = SLES::AndroidSimpleBufferQueue(_queue);
  result = queue.RegisterCallback(PlayedCallback, (void *)this);
  if (result != SL_RESULT_SUCCESS) {
    LogStartUp("PCMPlayer: Play.RegisterCallback() result=%#x", (int)result);
    play_object.Destroy();
    mix_object.Destroy();
    engine_object.Destroy();
    return false;
  }

  synthesiser = &_synthesiser;

  result = play.SetPlayState(SL_PLAYSTATE_PLAYING);
  if (result != SL_RESULT_SUCCESS) {
    LogStartUp("PCMPlayer: Play.SetPlayState(PLAYING) result=%#x",
               (int)result);
    play_object.Destroy();
    mix_object.Destroy();
    engine_object.Destroy();
    synthesiser = NULL;
    return false;
  }

  next = 0;
  filled = false;
  for (unsigned i = 0; i < ARRAY_SIZE(buffers) - 1; ++i)
    Enqueue();

  return true;
#elif defined(WIN32)
#else
  if (synthesiser != NULL) {
    if (_sample_rate == sample_rate) {
      /* already open, just change the synthesiser */
      SDL_LockAudio();
      synthesiser = &_synthesiser;
      SDL_UnlockAudio();
      return true;
    }

    Stop();
  }

  sample_rate = _sample_rate;

  SDL_AudioSpec spec;
  spec.freq = sample_rate;
  spec.format = AUDIO_S16SYS;
  spec.channels = 2;
  spec.samples = 4096;
  spec.callback = ::Synthesise;
  spec.userdata = this;

  if (SDL_OpenAudio(&spec, NULL) < 0)
    return false;

  synthesiser = &_synthesiser;
  SDL_PauseAudio(0);

  return true;
#endif
}
Esempio n. 18
0
void
BlankDisplay(bool doblank)
{
  static bool oldblank = false;

  UpdateBatteryInfo();

  if (!XCSoarInterface::SettingsMap().EnableAutoBlank)
    return;

  if (doblank == oldblank)
    return;

  if (!Display::BlankSupported())
    // can't do it, not supported
    return;

  // TODO feature: Trigger a GCE (Glide Computer Event) when
  // switching to battery mode This can be used to warn users that
  // power has been lost and you are now on battery power - ie:
  // something else is wrong

  if (doblank) {
    /* Battery status - simulator only - for safety of battery data
       note: Simulator only - more important to keep running in your plane
    */

    // JMW, maybe this should be active always...
    // we don't want the PDA to be completely depleted.

    if (Power::External::Status == Power::External::OFF) {
      if (is_simulator() && Power::Battery::RemainingPercentValid &&
          Power::Battery::RemainingPercent < BATTERY_EXIT) {
        LogStartUp(TEXT("Battery low exit..."));
        // TODO feature: Warning message on battery shutdown
        XCSoarInterface::SignalShutdown(true);
      } else {
        if (Power::Battery::RemainingPercentValid &&
            Power::Battery::RemainingPercent < BATTERY_WARNING) {
          DWORD LocalWarningTime = ::GetTickCount();
          if ((LocalWarningTime - BatteryWarningTime) > BATTERY_REMINDER) {
            BatteryWarningTime = LocalWarningTime;
            // TODO feature: Show the user what the batt status is.
            Message::AddMessage(_("Organiser Battery Low"));
          }
        } else {
          BatteryWarningTime = 0;
        }
      }
    }

    if (Power::External::Status == Power::External::OFF) {
      // Power off the display
      Display::Blank(true);
      oldblank = true;
      XCSoarInterface::SetSettingsMap().ScreenBlanked = true;
    } else {
      ResetDisplayTimeOut();
    }
  } else if (oldblank) {
    // was blanked
    // Power on the display
    Display::Blank(false);
    oldblank = false;
    XCSoarInterface::SetSettingsMap().ScreenBlanked = false;
  }
}
Esempio n. 19
0
bool
LayoutConfigPanel::Save(bool &requirerestart)
{
  bool changed = false;
  WndProperty *wp;

  bool orientation_changed = false;
  if (Display::RotateSupported()) {
    wp = (WndProperty*)wf->FindByName(_T("prpDisplayOrientation"));
    assert(wp != NULL);

    const DataFieldEnum *dfe = (const DataFieldEnum *)wp->GetDataField();
    Display::orientation orientation =
      (Display::orientation)dfe->GetAsInteger();
    if (orientation != Profile::GetDisplayOrientation()) {
      Profile::SetDisplayOrientation(orientation);
      changed = true;
      orientation_changed = true;
    }
  }

  bool info_box_geometry_changed = false;
  wp = (WndProperty*)wf->FindByName(_T("prpAppInfoBoxGeom"));
  if (wp) {
    if (InfoBoxLayout::InfoBoxGeometry !=
        (InfoBoxLayout::Geometry)wp->GetDataField()->GetAsInteger()) {
      InfoBoxLayout::InfoBoxGeometry =
          (InfoBoxLayout::Geometry)wp->GetDataField()->GetAsInteger();
      Profile::Set(szProfileInfoBoxGeometry,
                   (unsigned)InfoBoxLayout::InfoBoxGeometry);
      changed = true;
      info_box_geometry_changed = true;
    }
  }

  wp = (WndProperty*)wf->FindByName(_T("prpAppStatusMessageAlignment"));
  if (wp) {
    if (Appearance.StateMessageAlign != (StateMessageAlign_t)
        (wp->GetDataField()->GetAsInteger())) {
      Appearance.StateMessageAlign = (StateMessageAlign_t)
        (wp->GetDataField()->GetAsInteger());
      Profile::Set(szProfileAppStatusMessageAlignment,
                    Appearance.StateMessageAlign);
      changed = true;
    }
  }

  wp = (WndProperty*)wf->FindByName(_T("prpDialogStyle"));
  if (wp) {
    if (DialogStyleSetting != (DialogStyle)(wp->GetDataField()->GetAsInteger())) {
      DialogStyleSetting = (DialogStyle)(wp->GetDataField()->GetAsInteger());
      Profile::Set(szProfileAppDialogStyle, DialogStyleSetting);
      changed = true;
    }
  }

  wp = (WndProperty*)wf->FindByName(_T("prpAppInfoBoxBorder"));
  if (wp) {
    if (Appearance.InfoBoxBorder != (InfoBoxBorderAppearance_t)
        (wp->GetDataField()->GetAsInteger())) {
      Appearance.InfoBoxBorder = (InfoBoxBorderAppearance_t)
        (wp->GetDataField()->GetAsInteger());
      Profile::Set(szProfileAppInfoBoxBorder,
                    Appearance.InfoBoxBorder);
      changed = true;
      requirerestart = true;
    }
  }

  changed |= requirerestart |=
    SaveFormProperty(*wf, _T("prpAppInverseInfoBox"),
                     szProfileAppInverseInfoBox, Appearance.InverseInfoBox);

  changed |= requirerestart |=
    SaveFormProperty(*wf, _T("prpAppInfoBoxColors"),
                     szProfileAppInfoBoxColors, Appearance.InfoBoxColors);

  wp = (WndProperty*)wf->FindByName(_T("prpTabDialogStyle"));
  assert(wp != NULL);
  if (Appearance.DialogTabStyle != (DialogTabStyle_t)(wp->GetDataField()->GetAsInteger())) {
    Appearance.DialogTabStyle = (DialogTabStyle_t)(wp->GetDataField()->GetAsInteger());
    Profile::Set(szProfileAppDialogTabStyle, Appearance.DialogTabStyle);
    changed = true;
  }

  if (orientation_changed) {
    assert(Display::RotateSupported());

    Display::orientation orientation = Profile::GetDisplayOrientation();
    if (orientation == Display::ORIENTATION_DEFAULT)
      Display::RotateRestore();
    else {
      if (!Display::Rotate(orientation))
        LogStartUp(_T("Display rotation failed"));
    }
  } else if (info_box_geometry_changed)
    XCSoarInterface::main_window.ReinitialiseLayout();

  return changed;
}
Esempio n. 20
0
void
XCSoarInterface::Shutdown()
{
  VerboseOperationEnvironment operation;
  gcc_unused ScopeBusyIndicator busy;

  // Show progress dialog
  operation.SetText(_("Shutdown, please wait..."));

  // Log shutdown information
  LogStartUp(_T("Entering shutdown..."));
  StartupLogFreeRamAndStorage();

  // Turn off all displays
  globalRunningEvent.Reset();

#ifdef HAVE_TRACKING
  if (tracking != NULL)
    tracking->StopAsync();
#endif

  // Stop logger and save igc file
  operation.SetText(_("Shutdown, saving logs..."));
  logger.GUIStopLogger(Basic(), true);

  delete flight_logger;
  flight_logger = NULL;

  GetLiveBlackboard().RemoveListener(glide_computer_events);

  FlarmFriends::Save();

  // Save settings to profile
  operation.SetText(_("Shutdown, saving profile..."));
  Profile::Save();

  // Stop sound

  AudioVarioGlue::Deinitialise();

  operation.SetText(_("Shutdown, please wait..."));

  // Stop threads
  LogStartUp(_T("Stop threads"));
#ifndef ENABLE_OPENGL
  draw_thread->BeginStop();
#endif
  calculation_thread->BeginStop();
  merge_thread->BeginStop();

  // Wait for the calculations thread to finish
  LogStartUp(_T("Waiting for calculation thread"));

  merge_thread->Join();
  delete merge_thread;
  merge_thread = NULL;

  calculation_thread->Join();
  delete calculation_thread;
  calculation_thread = NULL;

  //  Wait for the drawing thread to finish
#ifndef ENABLE_OPENGL
  LogStartUp(_T("Waiting for draw thread"));

  draw_thread->Join();
  delete draw_thread;
#endif

  LogStartUp(_T("delete MapWindow"));
  main_window.Deinitialise();

  // Save the task for the next time
  operation.SetText(_("Shutdown, saving task..."));

  LogStartUp(_T("Save default task"));
  protected_task_manager->TaskSaveDefault();

  // Clear waypoint database
  LogStartUp(_T("Close waypoints"));
  way_points.Clear();

  operation.SetText(_("Shutdown, please wait..."));

  // Clear weather database
  LogStartUp(_T("CloseRASP"));
  RASP.Close();

  // Clear terrain database
  LogStartUp(_T("CloseTerrain"));

  delete terrain;

  LogStartUp(_T("CloseTopography"));
  delete topography;

  delete protected_marks;
  delete marks;

  // Close any device connections
  devShutdown();

  NMEALogger::Shutdown();

  delete replay;

  DeviceListDeinitialise();

  delete device_blackboard;
  device_blackboard = NULL;

  protected_task_manager->SetRoutePlanner(NULL);

  delete protected_task_manager;
  delete task_manager;

#ifdef HAVE_NET
  delete noaa_store;
#endif

#ifdef HAVE_TRACKING
  if (tracking != NULL) {
    tracking->WaitStopped();
    delete tracking;
  }
#endif

  // Close the progress dialog
  LogStartUp(_T("Close Progress Dialog"));
  operation.Hide();

  // Clear the EGM96 database
  EGM96::Close();

  delete glide_computer;

  // Clear airspace database
  LogStartUp(_T("Close airspace"));
  airspace_database.clear();

  // Destroy FlarmNet records
  FlarmNet::Destroy();

  delete file_cache;

  LogStartUp(_T("Close Windows - main"));
  main_window.reset();

  CloseLanguageFile();

  Display::RestoreOrientation();

  StartupLogFreeRamAndStorage();

  LogStartUp(_T("Finished shutdown"));
}
Esempio n. 21
0
void
XCSoarInterface::Shutdown(void)
{
  gcc_unused ScopeBusyIndicator busy;

  // Show progress dialog
  ProgressGlue::Create(_("Shutdown, please wait..."));

  // Log shutdown information
  LogStartUp(_T("Entering shutdown..."));
  StartupLogFreeRamAndStorage();

  // Turn off all displays
  globalRunningEvent.reset();

  // Stop logger and save igc file
  ProgressGlue::Create(_("Shutdown, saving logs..."));
  logger.guiStopLogger(Basic(), true);

  // Save settings to profile
  ProgressGlue::Create(_("Shutdown, saving profile..."));
  Profile::Save();

  // Stop sound
  LogStartUp(_T("SaveSoundSettings"));
  Profile::SetSoundSettings();

#ifndef DISABLEAUDIOVARIO
  //  VarioSound_EnableSound(false);
  //  VarioSound_Close();
#endif

  ProgressGlue::Create(_("Shutdown, please wait..."));

  // Stop threads
  LogStartUp(_T("Stop threads"));
#ifndef ENABLE_OPENGL
  draw_thread->stop();
#endif
  calculation_thread->stop();

  // Wait for the calculations thread to finish
  LogStartUp(_T("Waiting for calculation thread"));
  calculation_thread->join();
  delete calculation_thread;
  calculation_thread = NULL;

  //  Wait for the drawing thread to finish
#ifndef ENABLE_OPENGL
  LogStartUp(_T("Waiting for draw thread"));

  draw_thread->join();
  delete draw_thread;
#endif

  LogStartUp(_T("delete MapWindow"));
  main_window.map.reset();

  // Save the task for the next time
  ProgressGlue::Create(_("Shutdown, saving task..."));

  LogStartUp(_T("Save default task"));
  protected_task_manager->task_save_default();

  // Clear waypoint database
  LogStartUp(_T("Close waypoints"));
  way_points.clear();

  ProgressGlue::Create(_("Shutdown, please wait..."));

  // Clear weather database
  LogStartUp(_T("CloseRASP"));
  RASP.Close();

  // Clear terrain database
  LogStartUp(_T("CloseTerrain"));

  delete terrain;

  LogStartUp(_T("CloseTopography"));
  delete topography;

  delete marks;

  // Close any device connections
  devShutdown();

  RawLoggerShutdown();

  delete replay;

  // Save everything in the persistent memory file
  SaveCalculationsPersist(Basic(), Calculated(),
                          *protected_task_manager, *glide_computer,
                          logger);

  delete protected_task_manager;
  delete task_manager;

  // Kill windows
  LogStartUp(_T("Destroy Info Boxes"));
  InfoBoxManager::Destroy();

  LogStartUp(_T("Destroy Button Labels"));
  ButtonLabel::Destroy();

  // Close the progress dialog
  LogStartUp(_T("Close Progress Dialog"));
  ProgressGlue::Close();

  // Clear the EGM96 database
  CloseGeoid();

  delete glide_computer;

  // Clear airspace database
  LogStartUp(_T("Close airspace"));
  airspace_warnings->clear();
  airspace_database.clear();

  delete airspace_warnings;
  delete airspace_warning;

  // Destroy FlarmNet records
  FlarmNet::Destroy();

  delete file_cache;

  LogStartUp(_T("Close Windows - main "));
  main_window.reset();

  CloseLanguageFile();

  RestoreDisplayOrientation();

  StartupLogFreeRamAndStorage();

  LogStartUp(_T("Finished shutdown"));
}
Esempio n. 22
0
bool
DumpPort::Drain()
{
  LogStartUp(_T("Drain"));
  return port->Drain();
}
Esempio n. 23
0
/**
 * "Boots" up XCSoar
 * @param hInstance Instance handle
 * @param lpCmdLine Command line string
 * @return True if bootup successful, False otherwise
 */
bool
XCSoarInterface::Startup()
{
  VerboseOperationEnvironment operation;

  // Set the application title to "XCSoar"
  TCHAR szTitle[] = _T("XCSoar");

  //If "XCSoar" is already running, stop this instance
  if (MainWindow::find(szTitle))
    return false;

  LogStartUp(_T("Display dpi=%u,%u"), Display::GetXDPI(), Display::GetYDPI());

  // Creates the main window
  LogStartUp(_T("Create main window"));

  TopWindowStyle style;
  if (CommandLine::full_screen)
    style.FullScreen();
  if (CommandLine::resizable)
    style.Resizable();

  main_window.Set(szTitle, SystemWindowSize(), style);
  if (!main_window.IsDefined())
    return false;

#ifdef ENABLE_OPENGL
  LogStartUp(_T("OpenGL: "
#ifdef HAVE_EGL
                "egl=%d "
#endif
                "npot=%d vbo=%d fbo=%d"),
#ifdef HAVE_EGL
             OpenGL::egl,
#endif
             OpenGL::texture_non_power_of_two,
             OpenGL::vertex_buffer_object,
             OpenGL::frame_buffer_object);
#endif

  main_window.Initialise();

#ifdef SIMULATOR_AVAILABLE
  // prompt for simulator if not set by command line argument "-simulator" or "-fly"
  if (!sim_set_in_cmd_line_flag) {
    DialogLook white_look;
    white_look.Initialise(Fonts::map_bold, Fonts::map, Fonts::map_label,
                          Fonts::map_bold, Fonts::map_bold);
    white_look.SetBackgroundColor(COLOR_WHITE);
    SetXMLDialogLook(white_look);

    SimulatorPromptResult result = dlgSimulatorPromptShowModal();
    switch (result) {
    case SPR_QUIT:
      return false;

    case SPR_FLY:
      global_simulator_flag = false;
      break;

    case SPR_SIMULATOR:
      global_simulator_flag = true;
      break;
    }
  }
#endif

  SetXMLDialogLook(main_window.GetLook().dialog);

  SetSystemSettings().SetDefaults();
  SetComputerSettings().SetDefaults();
  SetUISettings().SetDefaults();
  SetUIState().Clear();

  if (!LoadProfile())
    return false;

  operation.SetText(_("Initialising"));

  /* create XCSoarData on the first start */
  CreateDataPath();

  Display::LoadOrientation(operation);

  main_window.InitialiseConfigured();

  TCHAR path[MAX_PATH];
  LocalPath(path, _T("cache"));
  file_cache = new FileCache(path);

  ReadLanguageFile();

  status_messages.LoadFile();
  InputEvents::readFile();

  // Initialize DeviceBlackboard
  device_blackboard = new DeviceBlackboard();

  DeviceListInitialise();

  // Initialize Markers
  marks = new Markers();
  protected_marks = new ProtectedMarkers(*marks);

#ifdef HAVE_AYGSHELL_DLL
  const AYGShellDLL &ayg = main_window.ayg_shell_dll;
  ayg.SHSetAppKeyWndAssoc(VK_APP1, main_window);
  ayg.SHSetAppKeyWndAssoc(VK_APP2, main_window);
  ayg.SHSetAppKeyWndAssoc(VK_APP3, main_window);
  ayg.SHSetAppKeyWndAssoc(VK_APP4, main_window);
  // Typical Record Button
  //	Why you can't always get this to work
  //	http://forums.devbuzz.com/m_1185/mpage_1/key_/tm.htm
  //	To do with the fact it is a global hotkey, but you can with code above
  //	Also APPA is record key on some systems
  ayg.SHSetAppKeyWndAssoc(VK_APP5, main_window);
  ayg.SHSetAppKeyWndAssoc(VK_APP6, main_window);
#endif

  // Initialize main blackboard data
  task_manager = new TaskManager(GetComputerSettings().task, way_points);
  task_manager->SetTaskEvents(task_events);
  task_manager->Reset();

  protected_task_manager =
    new ProtectedTaskManager(*task_manager,
                             XCSoarInterface::GetComputerSettings().task);

  // Read the terrain file
  operation.SetText(_("Loading Terrain File..."));
  LogStartUp(_T("OpenTerrain"));
  terrain = RasterTerrain::OpenTerrain(file_cache, operation);

  glide_computer = new GlideComputer(way_points, airspace_database,
                                     *protected_task_manager,
                                     task_events);
  glide_computer->ReadComputerSettings(GetComputerSettings());
  glide_computer->SetTerrain(terrain);
  glide_computer->SetLogger(&logger);
  glide_computer->Initialise();

  replay = new Replay(&logger, *protected_task_manager);

  // Load the EGM96 geoid data
  EGM96::Load();

  GlidePolar &gp = SetComputerSettings().polar.glide_polar_task;
  gp = GlidePolar(fixed_zero);
  gp.SetMC(GetComputerSettings().task.safety_mc);
  gp.SetBugs(GetComputerSettings().polar.degradation_factor);
  PlaneGlue::FromProfile(SetComputerSettings().plane);
  PlaneGlue::Synchronize(GetComputerSettings().plane, SetComputerSettings(), gp);
  task_manager->SetGlidePolar(gp);

  // Read the topography file(s)
  topography = new TopographyStore();
  LoadConfiguredTopography(*topography, operation);

  // Read the waypoint files
  WaypointGlue::LoadWaypoints(way_points, terrain, operation);

  // Read and parse the airfield info file
  WaypointDetails::ReadFileFromProfile(way_points, operation);

  // Set the home waypoint
  WaypointGlue::SetHome(way_points, terrain, SetComputerSettings(),
                        device_blackboard, false);

  // ReSynchronise the blackboards here since SetHome touches them
  device_blackboard->Merge();
  ReadBlackboardBasic(device_blackboard->Basic());

  // Scan for weather forecast
  LogStartUp(_T("RASP load"));
  RASP.ScanAll(Basic().location, operation);

  // Reads the airspace files
  ReadAirspace(airspace_database, terrain, GetComputerSettings().pressure,
               operation);

  {
    const AircraftState aircraft_state =
      ToAircraftState(device_blackboard->Basic(),
                      device_blackboard->Calculated());
    ProtectedAirspaceWarningManager::ExclusiveLease lease(glide_computer->GetAirspaceWarnings());
    lease->Reset(aircraft_state);
    lease->SetConfig(CommonInterface::GetComputerSettings().airspace.warnings);
  }

#ifdef HAVE_NET
  noaa_store = new NOAAStore();
  noaa_store->LoadFromProfile();
#endif

  AudioVarioGlue::Initialise();
  AudioVarioGlue::Configure(GetComputerSettings().sound);

  // Start the device thread(s)
  operation.SetText(_("Starting devices"));
  devStartup();

/*
  -- Reset polar in case devices need the data
  LogStartUp(_T("GlidePolar::UpdatePolar"));
  GlidePolar::UpdatePolar(true, GetComputerSettings());

  This should be done inside devStartup if it is really required
*/

  operation.SetText(_("Initialising display"));

  GlueMapWindow *map_window = main_window.GetMap();
  if (map_window != NULL) {
    map_window->SetWaypoints(&way_points);
    map_window->SetTask(protected_task_manager);
    map_window->SetRoutePlanner(&glide_computer->GetProtectedRoutePlanner());
    map_window->SetGlideComputer(glide_computer);
    map_window->SetAirspaces(&airspace_database);

    map_window->SetTopography(topography);
    map_window->SetTerrain(terrain);
    map_window->SetWeather(&RASP);
    map_window->SetMarks(protected_marks);
    map_window->SetLogger(&logger);

    /* show map at home waypoint until GPS fix becomes available */
    if (GetComputerSettings().poi.home_location_available)
      map_window->SetLocation(GetComputerSettings().poi.home_location);
  }

  // Finally ready to go.. all structures must be present before this.

  // Create the drawing thread
#ifndef ENABLE_OPENGL
  LogStartUp(_T("CreateDrawingThread"));
  draw_thread = new DrawThread(*map_window);
  draw_thread->Start(true);
#endif

  // Show the infoboxes
  LogStartUp(_T("ShowInfoBoxes"));
  InfoBoxManager::Show();

  // Create the calculation thread
  LogStartUp(_T("CreateCalculationThread"));
  CreateCalculationThread();

  // Find unique ID of this PDA
  ReadAssetNumber();

  glide_computer_events.Reset();
  GetLiveBlackboard().AddListener(glide_computer_events);

  if (CommonInterface::GetComputerSettings().logger.enable_flight_logger) {
    flight_logger = new GlueFlightLogger(GetLiveBlackboard());
    LocalPath(path, _T("flights.log"));
    flight_logger->SetPath(path);
  }

  if (CommonInterface::GetComputerSettings().logger.enable_nmea_logger)
    NMEALogger::enabled = true;

  LogStartUp(_T("ProgramStarted"));

  // Give focus to the map
  main_window.SetDefaultFocus();

  Pages::Initialise(GetUISettings().pages);

  // Start calculation thread
  merge_thread->Start();
  calculation_thread->Start();

#ifdef HAVE_TRACKING
  tracking = new TrackingGlue();
  tracking->SetSettings(GetComputerSettings().tracking);
#endif

  globalRunningEvent.Signal();

  AfterStartup();

  operation.Hide();

  main_window.ResumeThreads();

  return true;
}
Esempio n. 24
0
void
Graphics::Initialise()
{
  /// @todo enhancement: support red/green color blind pilots with adjusted colour scheme

  LogStartUp(_T("Initialise graphics"));

  LoadUnitSymbols();

  hTerrainWarning.load_big(IDB_TERRAINWARNING, IDB_TERRAINWARNING_HD);
  hGPSStatus1.load_big(IDB_GPSSTATUS1, IDB_GPSSTATUS1_HD, false);
  hGPSStatus2.load_big(IDB_GPSSTATUS2, IDB_GPSSTATUS2_HD, false);
  hLogger.load_big(IDB_LOGGER, IDB_LOGGER_HD);
  hLoggerOff.load_big(IDB_LOGGEROFF, IDB_LOGGEROFF_HD);

  hCruise.load_big(IDB_CRUISE, IDB_CRUISE_HD, false);
  hClimb.load_big(IDB_CLIMB, IDB_CLIMB_HD, false);
  hFinalGlide.load_big(IDB_FINALGLIDE, IDB_FINALGLIDE_HD, false);
  hAbort.load_big(IDB_ABORT, IDB_ABORT_HD, false);

#ifdef HAVE_HATCHED_BRUSH
  hAboveTerrainBitmap.load(IDB_ABOVETERRAIN);

  hAboveTerrainBrush.set(hAboveTerrainBitmap);
#endif

  hpWind.set(Layout::Scale(1), dark_color(COLOR_GRAY));
  hpWindTail.set(Pen::DASH, 1, COLOR_BLACK);
  hbWind.set(COLOR_GRAY);

  hBmpMapScaleLeft.load_big(IDB_MAPSCALE_LEFT, IDB_MAPSCALE_LEFT_HD, false);
  hBmpMapScaleRight.load_big(IDB_MAPSCALE_RIGHT, IDB_MAPSCALE_RIGHT_HD, false);

  hBmpTabTask.load((Layout::scale > 1) ? IDB_TASK_HD : IDB_TASK);
  hBmpTabWrench.load((Layout::scale > 1) ? IDB_WRENCH_HD : IDB_WRENCH);
  hBmpTabSettings.load((Layout::scale > 1) ? IDB_SETTINGS_HD : IDB_SETTINGS);
  hBmpTabCalculator.load((Layout::scale > 1) ? IDB_CALCULATOR_HD : IDB_CALCULATOR);

  hBmpTabFlight.load((Layout::scale > 1) ? IDB_GLOBE_HD : IDB_GLOBE);
  hBmpTabSystem.load((Layout::scale > 1) ? IDB_DEVICE_HD : IDB_DEVICE);
  hBmpTabRules.load((Layout::scale > 1) ? IDB_RULES_HD : IDB_RULES);
  hBmpTabTimes.load((Layout::scale > 1) ? IDB_CLOCK_HD : IDB_CLOCK);

  hBmpThermalSource.load_big(IDB_THERMALSOURCE, IDB_THERMALSOURCE_HD);

  hBmpTrafficSafe.load_big(IDB_TRAFFIC_SAFE, IDB_TRAFFIC_SAFE_HD, false);
  hBmpTrafficWarning.load_big(IDB_TRAFFIC_WARNING, IDB_TRAFFIC_WARNING_HD, false);
  hBmpTrafficAlarm.load_big(IDB_TRAFFIC_ALARM, IDB_TRAFFIC_ALARM_HD, false);

  hbCompass.set(Color(207, 207, 207));

  hbFinalGlideBelow.set(COLOR_RED);
  hpFinalGlideBelow.set(Layout::Scale(1), dark_color(COLOR_RED));

  hbFinalGlideBelowLandable.set(COLOR_ORANGE);
  hpFinalGlideBelowLandable.set(Layout::Scale(1), dark_color(COLOR_ORANGE));

  hbFinalGlideAbove.set(COLOR_GREEN);
  hpFinalGlideAbove.set(Layout::Scale(1), dark_color(COLOR_GREEN));

  hpCompass.set(Layout::Scale(1), COLOR_GRAY);

  hpMapScale.set(Layout::Scale(1), COLOR_BLACK);

  hpTerrainLine.set(Pen::DASH, Layout::Scale(1), clrSepia);
  hpTerrainLineThick.set(Pen::DASH, Layout::Scale(2), clrSepia);

  TracePen.set(2, Color(50, 243, 45));
  ContestPen[0].set(Layout::Scale(1)+2, COLOR_RED);
  ContestPen[1].set(Layout::Scale(1)+1, COLOR_ORANGE);
  ContestPen[2].set(Layout::Scale(1), COLOR_BLUE);

    // used for landable rendering
  hbGreen.set(COLOR_GREEN);
  hbWhite.set(COLOR_WHITE);
  hbOrange.set(COLOR_ORANGE);
  hbLightGray.set(COLOR_LIGHT_GRAY);
  hbNotReachableTerrain.set(light_color(COLOR_RED));

  hbGround.set(GroundColor);

  hpTrackBearingLine.set(3, COLOR_GRAY);
}
Esempio n. 25
0
void
Profile::Use()
{
  unsigned Speed = 0;
  unsigned Distance = 0;
  unsigned TaskSpeed = 0;
  unsigned Lift = 0;
  unsigned Altitude = 0;
  unsigned Temperature = 0;
  unsigned Temp = 0;
  int i;

  LogStartUp(_T("Read registry settings"));

  OrderedTaskBehaviour &osettings_task = 
    XCSoarInterface::SetSettingsComputer().ordered_defaults;

  TaskBehaviour &settings_task = 
    XCSoarInterface::SetSettingsComputer();

  Get(szProfileFinishMinHeight,
		  osettings_task.finish_min_height);
  Get(szProfileStartHeightRef,
		  osettings_task.start_max_height_ref);
  Get(szProfileStartMaxHeight,
		  osettings_task.start_max_height);
  Get(szProfileStartMaxSpeed,
		  osettings_task.start_max_speed);

  Get(szProfileStartMaxHeightMargin,
		  settings_task.start_max_height_margin);
  Get(szProfileStartMaxSpeedMargin,
		  settings_task.start_max_speed_margin);

#ifdef OLD_TASK // airspace priority
  for (i = 0; i < AIRSPACECLASSCOUNT; i++) {
    Get(szProfileAirspacePriority[i], AirspacePriority[i]);
  }
#endif

  if (Get(szProfileLatLonUnits, Temp))
    Units::SetCoordinateFormat((CoordinateFormats_t)Temp);

  Get(szProfileSpeedUnitsValue, Speed);
  switch (Speed) {
  case 0:
    Units::SetUserSpeedUnit(unStatuteMilesPerHour);
    Units::SetUserWindSpeedUnit(unStatuteMilesPerHour);
    break;
  case 1:
    Units::SetUserSpeedUnit(unKnots);
    Units::SetUserWindSpeedUnit(unKnots);
    break;
  case 2:
  default:
    Units::SetUserSpeedUnit(unKiloMeterPerHour);
    Units::SetUserWindSpeedUnit(unKiloMeterPerHour);
    break;
  }

  Get(szProfileTaskSpeedUnitsValue, TaskSpeed);
  switch (TaskSpeed) {
  case 0:
    Units::SetUserTaskSpeedUnit(unStatuteMilesPerHour);
    break;
  case 1:
    Units::SetUserTaskSpeedUnit(unKnots);
    break;
  case 2:
  default:
    Units::SetUserTaskSpeedUnit(unKiloMeterPerHour);
    break;
  }

  Get(szProfileDistanceUnitsValue,Distance);
  switch (Distance) {
  case 0:
    Units::SetUserDistanceUnit(unStatuteMiles);
    break;
  case 1:
    Units::SetUserDistanceUnit(unNauticalMiles);
    break;
  case 2:
  default:
    Units::SetUserDistanceUnit(unKiloMeter);
    break;
  }

  Get(szProfileAltitudeUnitsValue, Altitude);
  switch (Altitude) {
  case 0:
    Units::SetUserAltitudeUnit(unFeet);
    break;
  case 1:
  default:
    Units::SetUserAltitudeUnit(unMeter);
    break;
  }

  Get(szProfileTemperatureUnitsValue, Temperature);
  switch (Temperature) {
  default:
  case 0:
    Units::SetUserTemperatureUnit(unGradCelcius);
    break;
  case 1:
    Units::SetUserTemperatureUnit(unGradFahrenheit);
    break;
  }

  Get(szProfileLiftUnitsValue, Lift);
  switch (Lift) {
  case 0:
    Units::SetUserVerticalSpeedUnit(unKnots);
    break;
  case 1:
  default:
    Units::SetUserVerticalSpeedUnit(unMeterPerSecond);
    break;
  }

  for (i = 0; i < MAXINFOWINDOWS; i++) {
    if (Get(szProfileDisplayType[i], Temp))
      InfoBoxManager::SetTypes(i, Temp);
  }

  // check against V3 infotypes
  CheckInfoTypes();

  SETTINGS_MAP &settings_map = XCSoarInterface::SetSettingsMap();

  Temp = settings_map.DisplayOrientation;
  Get(szProfileDisplayUpValue, Temp);
  switch (Temp) {
  case TRACKUP:
    settings_map.DisplayOrientation = TRACKUP;
    break;
  case NORTHUP:
    settings_map.DisplayOrientation = NORTHUP;
    break;
  case NORTHCIRCLE:
    settings_map.DisplayOrientation = NORTHCIRCLE;
    break;
  case TRACKCIRCLE:
    settings_map.DisplayOrientation = TRACKCIRCLE;
    break;
  case NORTHTRACK:
    settings_map.DisplayOrientation = NORTHTRACK;
    break;
  }

  Temp = settings_map.DisplayTextType;
  Get(szProfileDisplayText, Temp);
  switch (Temp) {
  case 0:
    settings_map.DisplayTextType = DISPLAYNAME;
    break;
  case 1:
    settings_map.DisplayTextType = DISPLAYNUMBER;
    break;
  case 2:
    settings_map.DisplayTextType = DISPLAYFIRSTFIVE;
    break;
  case 3:
    settings_map.DisplayTextType = DISPLAYNONE;
    break;
  case 4:
    settings_map.DisplayTextType = DISPLAYFIRSTTHREE;
    break;
  case 5:
    settings_map.DisplayTextType = DISPLAYNAMEIFINTASK;
    break;
  case 6:
    settings_map.DisplayTextType = DISPLAYUNTILSPACE;
    break;
  }

  SETTINGS_COMPUTER &settings_computer =
    XCSoarInterface::SetSettingsComputer();

  Temp = settings_computer.AltitudeMode;
  Get(szProfileAltMode, Temp);
  settings_computer.AltitudeMode = (AirspaceDisplayMode_t)Temp;

  Get(szProfileClipAlt,
      settings_computer.ClipAltitude);
  Get(szProfileAltMargin,
      settings_computer.AltWarningMargin);

  Get(szProfileSafetyAltitudeArrival,
      settings_computer.safety_height_arrival);
  Get(szProfileSafetyAltitudeTerrain,
      settings_computer.safety_height_terrain);
  Get(szProfileSafteySpeed,
      settings_computer.SafetySpeed);
  Get(szProfilePolarID,
      settings_computer.POLARID);

  for (i = 0; i < AIRSPACECLASSCOUNT; i++) {
    if (Get(szProfileAirspaceMode[i], Temp)) {
      settings_computer.DisplayAirspaces[i] = (Temp & 0x1) != 0;
      settings_computer.airspace_warnings.class_warnings[i] = (Temp & 0x2) != 0;
    }

    Get(szProfileBrush[i],
        settings_map.iAirspaceBrush[i]);
    Get(szProfileColour[i],
        settings_map.iAirspaceColour[i]);
    if (settings_map.iAirspaceColour[i] >= NUMAIRSPACECOLORS)
      settings_map.iAirspaceColour[i] = 0;
    if (settings_map.iAirspaceBrush[i] >= NUMAIRSPACEBRUSHES)
      settings_map.iAirspaceBrush[i] = 0;
  }

  Get(szProfileAirspaceBlackOutline,
      settings_map.bAirspaceBlackOutline);
  Get(szProfileSnailTrail,
      settings_map.TrailActive);

  Get(szProfileTrailDrift,
      settings_map.EnableTrailDrift);

  Get(szProfileDetourCostMarker,
      settings_map.EnableDetourCostMarker);

  Get(szProfileDrawTopology,
      settings_map.EnableTopology);

  Get(szProfileDrawTerrain,
      settings_map.EnableTerrain);

  Get(szProfileFinalGlideTerrain,
      settings_computer.FinalGlideTerrain);

  Get(szProfileAutoWind,
      settings_computer.AutoWindMode);

  Get(szProfileCircleZoom,
      settings_map.CircleZoom);

  Get(szProfileHomeWaypoint,
      settings_computer.HomeWaypoint);

  if (Get(szProfileAlternate1, Temp)) {
    // TODO: for portrait no need to force alternate calculations here.
    // Infobox will trigger them on if visible..
    settings_computer.Alternate1 = Temp;
    settings_computer.EnableAlternate1 = true;
  } else {
    settings_computer.Alternate1 = -1;
    settings_computer.EnableAlternate1 = false;
  }

  if (Get(szProfileAlternate2, Temp)) {
    settings_computer.Alternate2 = Temp;
    settings_computer.EnableAlternate2 = true;
  } else {
    settings_computer.Alternate2 = -1;
    settings_computer.EnableAlternate2 = false;
  }

  Get(szProfileSnailWidthScale,
      settings_map.SnailWidthScale);

  Get(szProfileTeamcodeRefWaypoint,
      settings_computer.TeamCodeRefWaypoint);

  Get(szProfileAirspaceWarning,
      settings_computer.EnableAirspaceWarnings);

  Get(szProfileWarningTime,
      settings_computer.airspace_warnings.WarningTime);

  Get(szProfileAcknowledgementTime,
      settings_computer.airspace_warnings.AcknowledgementTime);

  Get(szProfileSoundVolume,
      settings_computer.SoundVolume);

  Get(szProfileSoundDeadband,
      settings_computer.SoundDeadband);

  Get(szProfileSoundAudioVario,
      settings_computer.EnableSoundVario);

  Get(szProfileSoundTask,
      settings_computer.EnableSoundTask);

  Get(szProfileSoundModes,
      settings_computer.EnableSoundModes);

  settings_map.EnableCDICruise = 0;
  settings_map.EnableCDICircling = 0;

#ifdef HAVE_BLANK
  Get(szProfileAutoBlank,
      settings_map.EnableAutoBlank);
#endif

  Get(szProfileAutoBacklight,
      XCSoarInterface::EnableAutoBacklight);

  Get(szProfileGestures,
      settings_computer.EnableGestures);

  if (Get(szProfileAverEffTime, Temp))
    settings_computer.AverEffTime = Temp;

  if (Get(szProfileDebounceTimeout, Temp))
    XCSoarInterface::debounceTimeout = Temp;

  /* JMW broken
  if (Get(szProfileAccelerometerZero, Temp))
    AccelerometerZero = Temp;
  if (AccelerometerZero==0.0) {
    AccelerometerZero= 100.0;
    Temp = 100;
    Set(szProfileAccelerometerZero, Temp);
  }
  */

  // new appearance variables

  //Temp = Appearance.IndFinalGlide;
  if (Get(szProfileAppIndFinalGlide, Temp))
    Appearance.IndFinalGlide = (IndFinalGlide_t)Temp;

  if (Get(szProfileAppIndLandable, Temp))
    Appearance.IndLandable = (IndLandable_t)Temp;

  Get(szProfileAppInverseInfoBox,
		  Appearance.InverseInfoBox);
  Get(szProfileAppGaugeVarioSpeedToFly,
		  Appearance.GaugeVarioSpeedToFly);
  Get(szProfileAppGaugeVarioAvgText,
		  Appearance.GaugeVarioAvgText);
  Get(szProfileAppGaugeVarioMc,
		  Appearance.GaugeVarioMc);
  Get(szProfileAppGaugeVarioBugs,
		  Appearance.GaugeVarioBugs);
  Get(szProfileAppGaugeVarioBallast,
		  Appearance.GaugeVarioBallast);
  Get(szProfileAppGaugeVarioGross,
		  Appearance.GaugeVarioGross);

  if (Get(szProfileAppCompassAppearance, Temp))
    Appearance.CompassAppearance = (CompassAppearance_t)Temp;

  if (Get(szProfileAppInfoBoxBorder, Temp))
    Appearance.InfoBoxBorder = (InfoBoxBorderAppearance_t)Temp;

  if (Get(szProfileAppStatusMessageAlignment, Temp))
    Appearance.StateMessageAlign = (StateMessageAlign_t)Temp;

  if (Get(szProfileAppTextInputStyle, Temp))
    Appearance.TextInputStyle = (TextInputStyle_t)Temp;

  if (Get(szProfileAppDialogStyle, Temp))
    DialogStyleSetting = (DialogStyle)Temp;

  Get(szProfileAppInfoBoxColors,
		  Appearance.InfoBoxColors);
  Get(szProfileAppAveNeedle,
		  Appearance.GaugeVarioAveNeedle);

  // StateMessageAlign : center, topleft
  // CompassAppearance (north arrow)
  //
  // DontShowLoggerIndicator
  // FlightModeIcon
  // DontShowAutoMacCready
  // MapScale
  // MapScale2
  // BestCruiseTrack
  // Aircraft
  // IndFinalGlide
  // IndLandable


  if (Get(szProfileAutoMcMode, Temp))
    settings_computer.auto_mc_mode =
      (TaskBehaviour::AutoMCMode_t)Temp;

  if (Get(szProfileOLCRules, Temp))
      settings_computer.olc_rules = (OLCRules)Temp;

  Get(szProfileHandicap,
      settings_computer.olc_handicap);
  Get(szProfileEnableExternalTriggerCruise,
      settings_computer.EnableExternalTriggerCruise);

  Get(szProfileUTCOffset,
      settings_computer.UTCOffset);
  if (settings_computer.UTCOffset > 12 * 3600)
    settings_computer.UTCOffset -= 24 * 3600;

  Get(szProfileBlockSTF,
      settings_computer.EnableBlockSTF);
  Get(szProfileAutoZoom,
      settings_map.AutoZoom);
  Get(szProfileMenuTimeout,
      XCSoarInterface::MenuTimeoutMax);
  Get(szProfileLockSettingsInFlight,
      XCSoarInterface::LockSettingsInFlight);
  Get(szProfileLoggerShort,
      settings_computer.LoggerShortName);
  Get(szProfileEnableFLARMMap,
      settings_map.EnableFLARMMap);
  Get(szProfileEnableFLARMGauge,
      settings_map.EnableFLARMGauge);
  Get(szProfileEnableTAGauge,
      settings_map.EnableTAGauge);
  Get(szProfileTerrainContrast,
      settings_map.TerrainContrast);
  Get(szProfileTerrainBrightness,
      settings_map.TerrainBrightness);
  Get(szProfileTerrainRamp,
      settings_map.TerrainRamp);

  Get(szProfileGliderScreenPosition,
      settings_map.GliderScreenPosition);
  Get(szProfileBallastSecsToEmpty,
      settings_computer.BallastSecsToEmpty);
  Get(szProfileSetSystemTimeFromGPS,
      settings_map.SetSystemTimeFromGPS);
  Get(szProfileUseCustomFonts,
      Appearance.UseCustomFonts);
  Get(szProfileVoiceClimbRate,
      settings_computer.EnableVoiceClimbRate);
  Get(szProfileVoiceTerrain,
      settings_computer.EnableVoiceTerrain);
  Get(szProfileVoiceWaypointDistance,
      settings_computer.EnableVoiceWaypointDistance);
  Get(szProfileVoiceTaskAltitudeDifference,
      settings_computer.EnableVoiceTaskAltitudeDifference);
  Get(szProfileVoiceMacCready,
      settings_computer.EnableVoiceMacCready);
  Get(szProfileVoiceNewWaypoint,
      settings_computer.EnableVoiceNewWaypoint);
  Get(szProfileVoiceInSector,
      settings_computer.EnableVoiceInSector);
  Get(szProfileVoiceAirspace,
      settings_computer.EnableVoiceAirspace);
  Get(szProfileEnableNavBaroAltitude,
      settings_computer.EnableNavBaroAltitude);
  Get(szProfileLoggerTimeStepCruise,
      settings_computer.LoggerTimeStepCruise);
  Get(szProfileLoggerTimeStepCircling,
      settings_computer.LoggerTimeStepCircling);
  Get(szProfileAbortSafetyUseCurrent,
      settings_computer.safety_mc_use_current);

  if (Get(szProfileSafetyMacCready, Temp))
    settings_computer.safety_mc = fixed(Temp) / 10;

  Get(szProfileUserLevel, XCSoarInterface::UserLevel);

  if (Get(szProfileRiskGamma, Temp))
    settings_computer.risk_gamma = fixed(Temp) / 10;

  if (Get(szProfileWindArrowStyle, Temp))
    settings_map.WindArrowStyle = Temp;

  Get(szProfileDisableAutoLogger,
      settings_computer.DisableAutoLogger);
}
Esempio n. 26
0
void
ParseInputFile(InputConfig &config, TLineReader &reader)
{
  // TODO code - Safer sizes, strings etc - use C++ (can scanf restrict length?)

  TCHAR *new_label = NULL;

  // Init first entry

  // Did we find some in the last loop...
  bool some_data = false;
  // Multiple modes (so large string)
  TCHAR d_mode[1024] = _T("");
  TCHAR d_type[256] = _T("");
  TCHAR d_data[256] = _T("");
  unsigned event_id = 0;
  TCHAR d_label[256] = _T("");
  int d_location = 0;
  TCHAR d_event[256] = _T("");
  TCHAR d_misc[256] = _T("");

  int line = 0;

  // Read from the file
  // TODO code: What about \r - as in \r\n ?
  // TODO code: Note that ^# does not allow # in key - might be required (probably not)
  //   Better way is to separate the check for # and the scanf
  TCHAR *buffer;
  while ((buffer = reader.read()) != NULL) {
    TrimRight(buffer);
    line++;

    const TCHAR *key, *value;

    // experimental: if the first line is "#CLEAR" then the whole default config is cleared
    //               and can be overwritten by file
    if (line == 1 && _tcscmp(buffer, _T("#CLEAR")) == 0) {
      config.clear_all_events();
    } else if (buffer[0] == _T('\0')) {
      // Check valid line? If not valid, assume next record (primative, but works ok!)
      // General checks before continue...
      if (some_data && (d_mode != NULL) && (_tcscmp(d_mode, _T("")) != 0)) {

        TCHAR *token;

        // For each mode
        token = _tcstok(d_mode, _T(" "));

        // General errors - these should be true
        assert(d_location >= 0);
        assert(d_location < 1024); // Scott arbitrary limit
        assert(d_mode != NULL);
        assert(d_type != NULL);
        assert(d_label != NULL);

        // These could indicate bad data - thus not an ASSERT (debug only)
        // assert(_tcslen(d_mode) < 1024);
        // assert(_tcslen(d_type) < 1024);
        // assert(_tcslen(d_label) < 1024);

        while (token != NULL) {

          // All modes are valid at this point
          int mode_id = config.make_mode(token);
          assert(mode_id >= 0);

          // Make label event
          // TODO code: Consider Reuse existing entries...
          if (d_location > 0) {
            // Only copy this once per object - save string space
            if (!new_label) {
              new_label = StringMallocParse(d_label);
            }

            config.append_menu(mode_id, new_label, d_location, event_id);
          }

          // Make key (Keyboard input)
          // key - Hardware key or keyboard
          if (_tcscmp(d_type, _T("key")) == 0) {
            // Get the int key (eg: APP1 vs 'a')
            unsigned key = InputEvents::findKey(d_data);
            if (key > 0)
              config.Key2Event[mode_id][key] = event_id;
            else
              LogStartUp(_T("Invalid key data: %s at %i"), d_data, line);

          // Make gce (Glide Computer Event)
          // GCE - Glide Computer Event
          } else if (_tcscmp(d_type, _T("gce")) == 0) {
            // Get the int key (eg: APP1 vs 'a')
            int key = InputEvents::findGCE(d_data);
            if (key >= 0)
              config.GC2Event[mode_id][key] = event_id;
            else
              LogStartUp(_T("Invalid GCE data: %s at %i"), d_data, line);

          // Make ne (NMEA Event)
          // NE - NMEA Event
          } else if (_tcscmp(d_type, _T("ne")) == 0) {
            // Get the int key (eg: APP1 vs 'a')
            int key = InputEvents::findNE(d_data);
            if (key >= 0)
              config.N2Event[mode_id][key] = event_id;
            else
              LogStartUp(_T("Invalid GCE data: %s at %i"), d_data, line);

          // label only - no key associated (label can still be touch screen)
          } else if (_tcscmp(d_type, _T("label")) == 0) {
            // Nothing to do here...

          } else {
            LogStartUp(_T("Invalid type: %s at %i"), d_type, line);
          }

          token = _tcstok(NULL, _T(" "));
        }
      }

      // Clear all data.
      some_data = false;
      _tcscpy(d_mode, _T(""));
      _tcscpy(d_type, _T(""));
      _tcscpy(d_data, _T(""));
      event_id = 0;
      _tcscpy(d_label, _T(""));
      d_location = 0;
      new_label = NULL;

    } else if (string_is_empty(buffer) || buffer[0] == _T('#')) {
      // Do nothing - we probably just have a comment line
      // JG removed "void;" - causes warning (void is declaration and needs variable)
      // NOTE: Do NOT display buffer to user as it may contain an invalid stirng !

    } else if (parse_assignment(buffer, key, value)) {
      if (_tcscmp(key, _T("mode")) == 0) {
        if (_tcslen(value) < 1024) {
          some_data = true; // Success, we have a real entry
          _tcscpy(d_mode, value);
        }
      } else if (_tcscmp(key, _T("type")) == 0) {
        if (_tcslen(value) < 256)
          _tcscpy(d_type, value);
      } else if (_tcscmp(key, _T("data")) == 0) {
        if (_tcslen(value) < 256)
          _tcscpy(d_data, value);
      } else if (_tcscmp(key, _T("event")) == 0) {
        if (_tcslen(value) < 256) {
          _tcscpy(d_event, _T(""));
          _tcscpy(d_misc, _T(""));
          int ef;

          #if defined(__BORLANDC__)
          memset(d_event, 0, sizeof(d_event));
          memset(d_misc, 0, sizeof(d_event));
          if (_tcschr(value, ' ') == NULL) {
            _tcscpy(d_event, value);
          } else {
          #endif

          ef = _stscanf(value, _T("%[^ ] %[A-Za-z0-9 \\/().,]"), d_event,
              d_misc);

          #if defined(__BORLANDC__)
          }
          #endif

          // TODO code: Can't use token here - breaks
          // other token - damn C - how about
          // C++ String class ?

          // TCHAR *eventtoken;
          // eventtoken = _tcstok(value, _T(" "));
          // d_event = token;
          // eventtoken = _tcstok(value, _T(" "));

          if ((ef == 1) || (ef == 2)) {

            // TODO code: Consider reusing existing identical events

            pt2Event event = InputEvents::findEvent(d_event);
            if (event) {
              TCHAR *allocated = StringMallocParse(d_misc);
              event_id = config.append_event(event, allocated, event_id);

              /* not freeing the string, because
                 InputConfig::append_event() stores the string point
                 without duplicating it; strictly speaking, this is a
                 memory leak, but the input file is only loaded once
                 at startup, so this is acceptable; in return, we
                 don't have to duplicate the hard-coded defaults,
                 which saves some memory */
              //free(allocated);

            } else {
              LogStartUp(_T("Invalid event type: %s at %i"), d_event, line);
            }
          } else {
            LogStartUp(_T("Invalid event type at %i"), line);
          }
        }
      } else if (_tcscmp(key, _T("label")) == 0) {
        _tcscpy(d_label, value);
      } else if (_tcscmp(key, _T("location")) == 0) {
        d_location = _ttoi(value);

      } else {
        LogStartUp(_T("Invalid key/value pair %s=%s at %i"), key, value, line);
      }
    } else  {
      LogStartUp(_T("Invalid line at %i"), line);
    }

  } // end while
}
Esempio n. 27
0
void
ParseInputFile(InputConfig &config, TLineReader &reader)
{
  // TODO code - Safer sizes, strings etc - use C++ (can scanf restrict length?)

  // Multiple modes (so large string)
  EventBuilder current;
  current.clear();

  int line = 0;

  // Read from the file
  TCHAR *buffer;
  while ((buffer = reader.ReadLine()) != NULL) {
    TrimRight(buffer);
    line++;

    const TCHAR *key, *value;

    // experimental: if the first line is "#CLEAR" then the whole default config is cleared
    //               and can be overwritten by file
    if (line == 1 && StringIsEqual(buffer, _T("#CLEAR"))) {
      config.SetDefaults();
    } else if (buffer[0] == _T('\0')) {
      // Check valid line? If not valid, assume next record (primative, but works ok!)
      // General checks before continue...
      current.commit(config, line);

      // Clear all data.
      current.clear();

    } else if (StringIsEmpty(buffer) || buffer[0] == _T('#')) {
      // Do nothing - we probably just have a comment line
      // NOTE: Do NOT display buffer to user as it may contain an invalid stirng !

    } else if (parse_assignment(buffer, key, value)) {
      if (StringIsEqual(key, _T("mode"))) {
        current.mode = value;
      } else if (StringIsEqual(key, _T("type"))) {
        current.type = value;
      } else if (StringIsEqual(key, _T("data"))) {
        current.data = value;
      } else if (StringIsEqual(key, _T("event"))) {
        if (_tcslen(value) < 256) {
          TCHAR d_event[256] = _T("");
          TCHAR d_misc[256] = _T("");
          int ef;

          #if defined(__BORLANDC__)
          memset(d_event, 0, sizeof(d_event));
          memset(d_misc, 0, sizeof(d_event));
          if (_tcschr(value, ' ') == NULL) {
            _tcscpy(d_event, value);
          } else {
          #endif

          ef = _stscanf(value, _T("%[^ ] %[A-Za-z0-9 \\/().,]"), d_event,
              d_misc);

          #if defined(__BORLANDC__)
          }
          #endif

          if ((ef == 1) || (ef == 2)) {

            // TODO code: Consider reusing existing identical events

            pt2Event event = InputEvents::findEvent(d_event);
            if (event) {
              TCHAR *allocated = UnescapeBackslash(d_misc);
              current.event_id = config.AppendEvent(event, allocated,
                                                    current.event_id);

              /* not freeing the string, because
                 InputConfig::AppendEvent() stores the string point
                 without duplicating it; strictly speaking, this is a
                 memory leak, but the input file is only loaded once
                 at startup, so this is acceptable; in return, we
                 don't have to duplicate the hard-coded defaults,
                 which saves some memory */
              //free(allocated);

            } else {
              LogStartUp(_T("Invalid event type: %s at %i"), d_event, line);
            }
          } else {
            LogFormat("Invalid event type at %i", line);
          }
        }
      } else if (StringIsEqual(key, _T("label"))) {
        current.label = value;
      } else if (StringIsEqual(key, _T("location"))) {
        current.location = ParseUnsigned(value);

      } else {
        LogStartUp(_T("Invalid key/value pair %s=%s at %i"), key, value, line);
      }
    } else  {
      LogFormat("Invalid line at %i", line);
    }

  }

  current.commit(config, line);
}
static const TCHAR *
detect_language()
{
#ifdef ANDROID

  JNIEnv *env = Java::GetEnv();

  Java::Class cls(env, "java/util/Locale");

  // Call static function Locale.getDefault() that
  // returns the user's default Locale object

  jmethodID cid = env->GetStaticMethodID(cls, "getDefault",
                                         "()Ljava/util/Locale;");
  assert(cid != NULL);

  jobject _obj = env->CallStaticObjectMethod(cls, cid);
  if (_obj == NULL)
    return NULL;

  Java::LocalObject obj(env, _obj);

  // Call function Locale.getLanguage() that
  // returns a two-letter language string

  cid = env->GetMethodID(cls, "getLanguage", "()Ljava/lang/String;");
  assert(cid != NULL);

  jstring language = (jstring)env->CallObjectMethod(obj, cid);
  if (language == NULL)
    return NULL;

  // Convert the jstring to a char string
  const char *language2 = env->GetStringUTFChars(language, NULL);
  if (language2 == NULL) {
    env->DeleteLocalRef(language);
    return NULL;
  }

  /* generate the resource name */

  const char *language3 = language2;
  if (strcmp(language3, "pt") == 0)
    /* hack */
    language3 = "pt_BR";

  // Attach .mo to the language identifier
  static char language_buffer[16];
  snprintf(language_buffer, sizeof(language_buffer), "%s.mo", language3);

  // Clean up the memory
  env->ReleaseStringUTFChars(language, language2);
  env->DeleteLocalRef(language);

  // Return e.g. "de.mo"
  return language_buffer;

#else /* !ANDROID */

#if defined(_WIN32_WCE)
  /* the GetUserDefaultUILanguage() prototype is missing on
     mingw32ce, we have to look it up dynamically */
  DynamicLibrary coreloc_dll(_T("coredll"));
  if (!coreloc_dll.defined()) {
    LogStartUp(_T("Language: coredll.dll not found"));
    return NULL;
  }

  typedef LANGID WINAPI (*GetUserDefaultUILanguage_t)();
  GetUserDefaultUILanguage_t GetUserDefaultUILanguage =
    (GetUserDefaultUILanguage_t)
    coreloc_dll.lookup(_T("GetUserDefaultUILanguage"));
  if (GetUserDefaultUILanguage == NULL) {
    LogStartUp(_T("Language: GetUserDefaultUILanguage() not available"));
    return NULL;
  }
#endif

  // Retrieve the default user language identifier from the OS
  LANGID lang_id = GetUserDefaultUILanguage();
  LogStartUp(_T("Language: GetUserDefaultUILanguage()=0x%x"), (int)lang_id);
  if (lang_id == 0)
    return NULL;

  // Try to convert the primary language part of the language identifier
  // to a MO file name in the language table
  return find_language(PRIMARYLANGID(lang_id));

#endif /* !ANDROID */
}
Esempio n. 29
0
int WINAPI
WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
#ifdef _WIN32_WCE
        gcc_unused LPWSTR lpCmdLine,
#else
        gcc_unused LPSTR lpCmdLine2,
#endif
        int nCmdShow)
#endif
{
#ifdef WIN32
  ResourceLoader::Init(hInstance);
#endif

  Net::Initialise();

  InitialiseDataPath();
  StartupLogFreeRamAndStorage();

  // Write startup note + version to logfile
  LogStartUp(_T("Starting XCSoar %s"), XCSoar_ProductToken);

  // Read options from the command line
#ifndef WIN32
  CommandLine::Parse(Args(argc, argv, Usage));
#else
  CommandLine::Parse(Args(GetCommandLine(), Usage));
#endif

  ScreenGlobalInit screen_init;

  // Write initialization note to logfile
  LogStartUp(_T("Initialise application instance"));

#ifdef WIN32
  /* try to make the UI most responsive */
  SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
#endif

  // Register window classes
#ifdef USE_GDI
  MainWindow::register_class(hInstance);
#endif

  AllowLanguage();

  InitialiseIOThread();

  // Perform application initialization and run loop
  int ret = EXIT_FAILURE;
  if (XCSoarInterface::Startup())
    ret = CommonInterface::main_window.RunEventLoop();

  CommonInterface::main_window.reset();

  DeinitialiseIOThread();

  DisallowLanguage();

  Fonts::Deinitialize();

  DeinitialiseDataPath();
  Net::Deinitialise();

  assert(!ExistsAnyThread());

  return ret;
}
Esempio n. 30
0
Port *
OpenPort(const DeviceConfig &config, Port::Handler &handler)
{
  if (is_simulator())
    return new NullPort(handler);

  const TCHAR *path = NULL;
  TCHAR buffer[MAX_PATH];

  switch (config.port_type) {
  case DeviceConfig::PortType::DISABLED:
    return NULL;

  case DeviceConfig::PortType::SERIAL:
    if (config.path.empty())
      return NULL;

    path = config.path.c_str();
    break;

  case DeviceConfig::PortType::RFCOMM:
#ifdef ANDROID
    if (config.bluetooth_mac.empty()) {
      LogStartUp(_T("No Bluetooth MAC configured"));
      return NULL;
    }

    {
      AndroidBluetoothPort *port =
        new AndroidBluetoothPort(config.bluetooth_mac, handler);
      if (!port->Open()) {
        delete port;
        return NULL;
      }

      return port;
    }
#else
    LogStartUp(_T("Bluetooth not available on this platform"));
    return NULL;
#endif

  case DeviceConfig::PortType::IOIOUART:
#if defined(ANDROID) && defined(IOIOLIB)
    {
      if (config.ioio_uart_id >= AndroidIOIOUartPort::getNumberUarts()) {
        LogStartUp(_T("No IOIOUart configured in profile"));
        return NULL;
      }

      {
        AndroidIOIOUartPort *port =
          new AndroidIOIOUartPort(config.ioio_uart_id, config.baud_rate, handler);

        if (!port->Open()) {
          delete port;
          return NULL;
        }

        return port;
      }
    }
#else
    LogStartUp(_T("IOIO Uart not available on this platform or version"));
    return NULL;
#endif

  case DeviceConfig::PortType::AUTO:
    if (!detect_gps(buffer, sizeof(buffer))) {
      LogStartUp(_T("no GPS detected"));
      return NULL;
    }

    LogStartUp(_T("GPS detected: %s"), buffer);

    path = buffer;
    break;

  case DeviceConfig::PortType::INTERNAL:
    break;

  case DeviceConfig::PortType::TCP_LISTENER: {
    TCPPort *port = new TCPPort(config.tcp_port, handler);
    if (!port->Open()) {
      delete port;
      return NULL;
    }

    return port;
  }
  }

  if (path == NULL)
    return NULL;

#ifdef HAVE_POSIX
  TTYPort *Com = new TTYPort(path, config.baud_rate, handler);
#else
  SerialPort *Com = new SerialPort(path, config.baud_rate, handler);
#endif
  if (!Com->Open()) {
    delete Com;
    return NULL;
  }

  return Com;
}