bool Customizations::GetBitmap( const wxString& key, wxBitmap& bitmap )
{
	if ( Provides( key ) )
	{
    const auto path = m_customs.getSingleValue(STD_STRING(key));
    wxBitmap icon_bmp;
		if( icon_bmp.IsOk() )
		{
			bitmap = icon_bmp;
			return true;
		}
	}
	return false;//either loaded bmp was kaput or key not found
}
bool abstract_panel::loadValuesIntoMap()
{
	try {
		//special treatment for resolution that'll set proper defaults for res
		wxDisplay display(0);
		//		wxRect display_rect ( display.GetGeometry() );
		//		const int current_x_res = LSL::susynclib().GetSpringConfigInt(RC_TEXT[0].key,display_rect.width);
		//		const int current_y_res = LSL::susynclib().GetSpringConfigInt(RC_TEXT[1].key,display_rect.height);

		for (int i = 0; i < intControls_size; ++i) {
			intSettings[intControls[i].key] = LSL::usync().GetSpringConfigInt(STD_STRING(intControls[i].key), FromwxString(intControls[i].def));
		}
		for (int i = 0; i < floatControls_size; ++i) {
			floatSettings[floatControls[i].key] = LSL::usync().GetSpringConfigFloat(STD_STRING(floatControls[i].key), FromwxString(floatControls[i].def));
		}
	} catch (...) {
		customMessageBox(SS_MAIN_ICON, _("Could not access your settings.\n"), _("Error"), wxOK | wxICON_HAND, 0);
		abstract_panel::settingsChanged = false;
		return false;
	}

	return true; // SUCCESS!
}
Exemple #3
0
template <typename CHAR> void DumpKey( KeyTree<CHAR> &KT, LPCSTR keyPath ) {

   std::vector<STD_STRING(CHAR)> ss;
   char *label = NULL;
   
   KT.EnumSubkeys( keyPath, ss ); label = "subkeys" ; 
   std::cout << keyPath << " " << label << ": ";
   for (size_t i=0; i<ss.size(); i++) { std::cout << ss[i] << " "; } 
   std::cout << "\n";   
   
   KT.EnumValues ( keyPath, ss ); label = "values"  ;  
   std::cout << keyPath << " " << label << ": ";
   for (size_t i=0; i<ss.size(); i++) { std::cout << ss[i] << " "; }
   std::cout << "\n";      
}
void ServerEvents::OnLoginInfoComplete()
{
	slLogDebugFunc("");
	wxString nick = TowxString(m_serv.GetMe().GetNick());
	wxArrayString highlights = sett().GetHighlightedWords();
	if (highlights.Index(nick) == -1) {
		highlights.Add(nick);
		sett().SetHighlightedWords(highlights);
	}
	//m_serv.RequestChannels();
	GlobalEventManager::Instance()->Send(GlobalEventManager::OnLogin);
	std::vector<ChannelJoinInfo> autojoin = sett().GetChannelsJoin();
	for (std::vector<ChannelJoinInfo>::const_iterator itor = autojoin.begin(); itor != autojoin.end(); ++itor) {
		if (itor->name.IsEmpty())
			continue;
		Channel& chan = m_serv._AddChannel(STD_STRING(itor->name));
		chan.SetPassword(STD_STRING(itor->password));
		ui().OnJoinedChannelSuccessful(chan, itor == autojoin.begin());
	}
	for (std::vector<ChannelJoinInfo>::const_iterator itor = autojoin.begin(); itor != autojoin.end(); ++itor)
		m_serv.JoinChannel(STD_STRING(itor->name), STD_STRING(itor->password));

	ui().OnLoggedIn();
}
Exemple #5
0
cli::Error_e cmdVKDump( CLIARGS args, cli::Param_t prm) {

   if (args.size() < 2) {
      printf( "***ERROR: You must enter a file name.\n" );
      return cli::ERR_MISSINGARG; 
   }
   
   STD_STRING(TCHAR) filename = args[1];

   ValStore<TCHAR> vs;
   vs.Deserialize( filename );
   vs.Dump( ConOut );   
   
   return cli::ERR_NOERROR; 
}
void SpringOptionsTab::OnDataDir(wxCommandEvent& /*unused*/)
{
	int result = wxMessageBox(_("Do you want to change spring's datadir location? (select yes only if you know what you're doing)"), _("Data dir wizard"), wxICON_QUESTION | wxYES_NO | wxCANCEL, &ui().mw());

	if (result != wxYES) {
		return;
	}

	const wxString dir = wxDirSelector(_("Choose a folder"), TowxString(SlPaths::GetDataDir()));
	const bool res = SlPaths::CreateSpringDataDir(STD_STRING(dir));
	if (!res) {
		wxMessageBox(wxString::Format(_("Something went wrong when creating the directory: %s"), dir.c_str()));
		return;
	}
}
void BattleRoomTab::OnMapSelect(wxCommandEvent& /*unused*/)
{
	if (!m_battle)
		return;
	if (!m_battle->IsFounderMe()) {
		try {
			const std::string map = STD_STRING(m_map_combo->GetString(m_map_combo->GetCurrentSelection()));
			m_battle->m_autohost_manager->GetAutohostHandler().SetMap(map);
			//m_battle->DoAction( _T( "suggests " ) + TowxString(LSL::usync().GetMap( m_map_combo->GetCurrentSelection() ).name));
		} catch (...) {
		}
		return;
	}
	SetMap(m_map_combo->GetCurrentSelection());
}
void BattleMapTab::OnMapSelect( wxCommandEvent& /*unused*/ )
{
	if ( !m_battle ) return;
	if ( !m_battle->IsFounderMe() )
	{
		try
		{
            m_battle->DoAction("suggests " + STD_STRING(m_map_combo->GetString(m_map_combo->GetCurrentSelection())));
		}
		catch ( ... )
		{
		}
		return;
	}
	SetMap( m_map_combo->GetCurrentSelection() );
}
void BattleOptionsTab::ReloadRestrictions()
{
	if ( !m_battle ) return;
	m_allowed_list->Clear();
	m_restrict_list->Clear();
	if ( m_battle->GetHostModName() == wxEmptyString )
        return;

	try {
        m_allowed_list->InsertItems(LSL::Util::vectorToArrayString(
                                        LSL::usync().GetUnitsList(STD_STRING(m_battle->GetHostModName()))), 0);
	} catch ( ... ) {}
	std::map<wxString, int> units = m_battle->RestrictedUnits();

	for ( std::map<wxString, int>::const_iterator itor = units.begin(); itor != units.end(); ++itor )
		Restrict( itor->first, itor->second );
}
Exemple #10
0
void Battle::LoadMapDefaults( const std::string& mapname )
{
    CustomBattleOptions().setSingleOption( "startpostype",
                                           STD_STRING(sett().GetMapLastStartPosType(TowxString(mapname))),
                                           LSL::OptionsWrapper::EngineOption );
	SendHostInfo( wxFormat( _T("%d_startpostype") ) % LSL::OptionsWrapper::EngineOption );

	for( unsigned int i = 0; i <= GetLastRectIdx(); ++i ) if ( GetStartRect( i ).IsOk() ) RemoveStartRect(i); // remove all rects
	SendHostInfo( IBattle::HI_StartRects );

	std::vector<Settings::SettStartBox> savedrects = sett().GetMapLastRectPreset(TowxString(mapname));
	for ( std::vector<Settings::SettStartBox>::const_iterator itor = savedrects.begin(); itor != savedrects.end(); ++itor )
	{
		AddStartRect( itor->ally, itor->topx, itor->topy, itor->bottomx, itor->bottomy );
	}
	SendHostInfo( IBattle::HI_StartRects );
}
Exemple #11
0
void BattleMapTab::OnMapBrowse(wxCommandEvent& /*unused*/)
{
	if (!m_battle)
		return;
	slLogDebugFunc("");

	wxString mapname = mapSelectDialog();
	if (!mapname.empty()) {
		slLogDebugFunc("");
		if (!m_battle->IsFounderMe()) {
			m_battle->DoAction("suggests " + STD_STRING(mapname));
			return;
		}
		const int idx = m_map_combo->FindString(mapname, true /*case sensitive*/);
		if (idx != wxNOT_FOUND)
			SetMap(idx);
	}
}
Exemple #12
0
void ChatPanelMenu::OnUserMenuKick(wxCommandEvent& /*unused*/)
{
	if (!HasChanserv())
		return;

	const User* user = m_chatpanel->GetSelectedUser();
	if (user == 0)
		return;

	wxString msg;
	if (!ui().AskText(_("Kick User"), _("Reason:"), msg))
		return;

	if (msg != wxEmptyString)
		msg = _T( " " ) + msg;
	SayChanserv("!KICK #" + m_chatpanel->m_channel->GetName() + " " + user->GetNick() + STD_STRING(msg));
	//KICK /<channame>/ <username> [{reason}]
}
Exemple #13
0
void BattleMapTab::Update(const wxString& Tag)
{
	if (!m_battle)
		return;
	long type;
	Tag.BeforeFirst('_').ToLong(&type);
	const std::string key = STD_STRING(Tag.AfterFirst('_'));
	if (type == LSL::Enum::EngineOption) {
		if (key == "startpostype") {
			const long longval = LSL::Util::FromIntString(m_battle->CustomBattleOptions().getSingleValue(key, (LSL::Enum::GameOption)type));
			m_start_radios->SetSelection(longval);
			m_minimap->UpdateMinimap();
		}
	} else if (type == LSL::Enum::PrivateOptions) {
		if (key == "mapname") {
			Update();
		}
	}
}
void BattleroomMMOptionsTab::UpdateOptControls(const wxString& controlName)
{
	if (!m_battle)
		return;
	long gameoption;
	controlName.BeforeFirst(sep).ToLong(&gameoption);
	const auto optKey = STD_STRING(controlName.AfterFirst(sep));

	if (gameoption == LSL::Enum::PrivateOptions) {
		if (optKey == "mapname")
			OnReloadControls(LSL::Enum::MapOption);
		if (optKey == "gamename")
			OnReloadControls(LSL::Enum::ModOption);
		return;
	}

	if (m_chkbox_map.find(controlName) != m_chkbox_map.end()) {
		const long value = LSL::Util::FromIntString(
		    m_battle->CustomBattleOptions().getSingleValue(optKey, (LSL::Enum::GameOption)gameoption));
		wxCheckBox* cur = m_chkbox_map[controlName];
		cur->SetValue(value);
	}

	if (m_combox_map.find(controlName) != m_combox_map.end()) {
		wxComboBox* cur = m_combox_map[controlName];
		cur->SetValue(TowxString((m_battle->CustomBattleOptions()
					      .GetNameListOptValue(optKey, (LSL::Enum::GameOption)gameoption))));
	}

	if (m_textctrl_map.find(controlName) != m_textctrl_map.end()) {
		const wxString value = TowxString(m_battle->CustomBattleOptions()
						      .getSingleValue(optKey, (LSL::Enum::GameOption)gameoption));
		wxTextCtrl* cur = m_textctrl_map[controlName];
		cur->SetValue(value);
	}

	if (m_spinctrl_map.find(controlName) != m_spinctrl_map.end()) {
		const long value = LSL::Util::FromIntString(
		    m_battle->CustomBattleOptions().getSingleValue(optKey, (LSL::Enum::GameOption)gameoption));
		wxSpinCtrlDouble* cur = m_spinctrl_map[controlName];
		cur->SetValue(value);
	}
}
wxString BattleroomListCtrl::GetItemText(long item, long column) const
{
	if ( (item == -1) || (item >= (long)m_data.size()) || (m_battle == NULL))
		return _T("");

	const User& user = *GetDataFromIndex( item );
	bool is_bot = user.BattleStatus().IsBot();
	bool is_spec = user.BattleStatus().spectator;

	if ( column == m_faction_column_index ) {
		try {
            auto sides = LSL::usync().GetSides(STD_STRING(m_battle->GetHostModName()));
            ASSERT_EXCEPTION( user.BattleStatus().side < (long)sides.size(), _T("Side index too high") );
		}
		catch ( ... ) {
			return wxFormat( _T("s%d") ) % (user.BattleStatus().side + 1);
		}
		return _T("");
	}
    if ( column == m_nick_column_index )  {
        if ( is_bot ) {
            wxString botname = user.BattleStatus().aishortname;
            if ( !user.BattleStatus().aiversion.IsEmpty() ) botname += _T(" ") + user.BattleStatus().aiversion;
            if ( !LSL::usync().VersionSupports( LSL::USYNC_GetSkirmishAI ) )
            {
                if ( botname.Find(_T('.')) != wxNOT_FOUND ) botname = botname.BeforeLast(_T('.'));
                if ( botname.Find(_T('/')) != wxNOT_FOUND ) botname = botname.AfterLast(_T('/'));
                if ( botname.Find(_T('\\')) != wxNOT_FOUND ) botname = botname.AfterLast(_T('\\'));
                if ( botname.Find(_T("LuaAI:")) != wxNOT_FOUND ) botname = botname.AfterFirst(_T(':'));
            }
            return (wxFormat(_T("%s - %s (%s)")) % user.GetNick() % botname % user.BattleStatus().owner);
        }
        else
            return user.GetNick();
    }
	if ( column == m_team_column_index ) return is_spec ? _T("") : (wxFormat( _T("%d") ) % ( user.BattleStatus().team + 1 ) ).c_str();
	if ( column == m_ally_column_index ) return is_spec ? _T("") : (wxFormat( _T("%d") ) % ( user.BattleStatus().ally + 1 ) ).c_str();
	if ( column == m_resourcebonus_column_index ) return is_spec ? _T("") : (wxFormat( _T("%d%%") ) % user.BattleStatus().handicap ).c_str();
	if ( column == m_country_column_index ) return _T("");

	return _T("");
}
void BattleOptionsTab::OnAllow( wxCommandEvent& /*unused*/ )
{
	if ( !m_battle ) return;
	wxArrayInt sel;
	wxArrayString names;

	m_restrict_list->GetSelections( sel );
	for ( unsigned int i = 0; i < sel.Count(); i++ ) {
		wxString name = m_restrict_list->GetString( sel.Item( i ) );
		name = name.AfterLast( '(' );
		name = name.BeforeLast( ')' );
		names.Add( name );
	}
	for ( unsigned int i = 0; i < names.Count(); i++ ) {
		const wxString unit =  names.Item( i );
		m_battle->UnrestrictUnit(STD_STRING(unit));
	}
	if ( names.Count() > 0 ) m_battle->SendHostInfo( IBattle::HI_Restrictions );

}
void BattleRoomTab::OnMapBrowse(wxCommandEvent& /*unused*/)
{
	if (!m_battle)
		return;
	slLogDebugFunc("");

	const wxString mapname = mapSelectDialog();
	if (!mapname.empty()) {
		if (!m_battle->IsFounderMe()) {
			m_battle->m_autohost_manager->GetAutohostHandler().SetMap(STD_STRING(mapname));
			//m_battle->DoAction( _T( "suggests " ) + mapname );
			return;
		}

		const int idx = m_map_combo->FindString(mapname, true /*case sensitive*/);
		if (idx != wxNOT_FOUND) {
			SetMap(idx);
		}
	}
}
void AddBotDialog::OnOptionActivate(wxListEvent& event)
{
	long index = event.GetIndex();
	wxString tag;
	for (OptionListMap::const_iterator itor = m_opt_list_map.begin(); itor != m_opt_list_map.end(); ++itor) {
		if (itor->second == index) {
			tag = itor->first;
			break;
		}
	}
	LSL::OptionsWrapper& optWrap = m_battle.CustomBattleOptions();
	const LSL::Enum::GameOption optFlag = (LSL::Enum::GameOption)FromwxString(tag.BeforeFirst('_'));
	const std::string key = STD_STRING(tag.AfterFirst('_'));
	LSL::Enum::OptionType type = optWrap.GetSingleOptionType(key);
	if (!optWrap.keyExists(key, optFlag, false, type))
		return;
	SingleOptionDialog dlg(m_battle, tag);
	dlg.ShowModal();
	UpdateOption(tag);
}
void BattleOptionsTab::OnRestrict( wxCommandEvent& /*unused*/ )
{
	if ( !m_battle ) return;
	wxArrayInt sel;
	wxArrayString names;

	m_allowed_list->GetSelections( sel );
	for ( unsigned int i = 0; i < sel.Count(); i++ ) {
		wxString name = m_allowed_list->GetString( sel.Item( i ) );
		name = name.AfterLast( '(' );
		name = name.BeforeLast( ')' );
		names.Add( name );
	}
	for ( unsigned int i = 0; i < names.Count(); i++ ) {
		wxString unit = names.Item( i );
		int count = wxGetNumberFromUser( _( "How many units of this type do you wish to allow?" ), wxEmptyString, _( "Unit restriction" ), 0, 0, 500000 );
		if ( count >= 0 ) m_battle->RestrictUnit(STD_STRING(unit), count );
	}
	if ( names.Count() > 0 ) m_battle->SendHostInfo( IBattle::HI_Restrictions );
}
Exemple #20
0
//! @brief parses the command line and sets global app options like log verbosity or log target
bool Springsettings::OnCmdLineParsed(wxCmdLineParser& parser)
{
//  #if wxUSE_CMDLINE_PARSER
    if ( !parser.Parse(true) )
    {
#if wxUSE_STD_IOSTREAM
		m_log_console = parser.Found(_T("console-logging"));
#endif
		m_log_file = parser.Found(_T("file-logging"), &m_log_file_path);
        m_log_window_show = parser.Found(_T("gui-logging"));
        m_crash_handle_disable = parser.Found(_T("no-crash-handler"));

		wxString config;;
		const bool userconfig = parser.Found( _T("config-file"), &config);
		if ( userconfig ) {
			 wxFileName fn ( config );
			 if ( ! fn.IsAbsolute() ) {
				 wxLogError ( _T("path for parameter \"config-file\" must be absolute") );
				 return false;
			 }
			 if ( ! fn.IsFileWritable() ) {
				 wxLogError ( _T("path for parameter \"config-file\" must be writeable") );
				 return false;
			 }
			SlPaths::SetUserConfigPath(STD_STRING(config));
		}


		if ( !parser.Found(_T("log-verbosity"), &m_log_verbosity ) )
			m_log_verbosity = m_log_window_show ? 3 : 5;

        return true;
    }
    else
    {
        return false;
    }
//  #else // wxUSE_CMDLINE_PARSER
  return true;
//  #endif
}
void PlaybackTab::OnWatch(wxCommandEvent& /*unused*/)
{
	const StoredGame* storedGame = m_replay_dataview->GetSelectedItem();

	if (storedGame == nullptr) {
		Deselected();
		return;
	}

	const int m_sel_replay_id = storedGame->id;

	wxString type = m_isreplay ? _("replay") : _("savegame");
	wxLogMessage(_T( "Watching %s %d " ), type.c_str(), m_sel_replay_id);
	StoredGame& rep = replaylist().GetPlaybackById(m_sel_replay_id);
	if (ui().NeedsDownload(&rep.battle)) {
		return;
	}

	rep.battle.GetMe().SetNick(STD_STRING(cfg().ReadString("/Spring/DefaultName")));
	rep.battle.StartSpring();
}
void SinglePlayerBattle::SendHostInfo(HostInfo update)
{
	if ((update & HI_StartType) != 0)
		m_sptab.UpdateMinimap();
	if ((update & HI_Restrictions) != 0)
		m_sptab.ReloadRestrictions();
	if ((update & HI_Map_Changed) != 0) {
		LoadMap();
		m_sptab.ReloadMapOptContrls();
	}
	if ((update & HI_Game_Changed) != 0) {
		RemoveUnfittingBots();
		LoadGame();
		wxString presetname = sett().GetModDefaultPresetName(TowxString(GetHostGameName()));
		if (!presetname.IsEmpty()) {
			LoadOptionsPreset(STD_STRING(presetname));
			SendHostInfo(HI_Send_All_opts);
		}
		m_sptab.ReloadModOptContrls();
	}
}
Exemple #23
0
void ReplayList::GetHeaderInfo(wxFile& replay, StoredGame& rep, const int version) const
{
	const int seek = 72 + (version < 5 ? 0 : 240);
	if (replay.Seek(seek) == wxInvalidOffset) {
		return;
	}
	int gametime = 0;
	replay.Read(&gametime, 4);
	rep.duration = gametime;
	rep.size = replay.Length();
	//! \todo don't use long long? (pedantic)
	wxLongLong_t unixtime = 0;
	if (replay.Seek(56) == wxInvalidOffset) {
		return;
	}
	replay.Read(&unixtime, 8);
	wxDateTime dt;
	dt.Set((time_t)unixtime);
	// todo: add 2 strings one for date other for time?
	rep.date_string = STD_STRING(dt.FormatISODate() + _T(" ") + dt.FormatISOTime());
	//  rep.date = (time_t) unixtime ;
}
Exemple #24
0
void BattleRoomTab::RegenerateOptionsList()
{
	long pos = 0;
	m_opts_list->DeleteAllItems();
	m_opts_list->InsertItem( pos, _( "Size" ) );
	m_opt_list_map[ _( "Size" ) ] = pos;
	pos++;
	m_opts_list->InsertItem( pos , _( "Windspeed" ) );
	m_opt_list_map[ _( "Windspeed" ) ] = pos;
	pos++;
	m_opts_list->InsertItem( pos, _( "Tidal strength" ) );
	m_opt_list_map[ _( "Tidal strength" ) ] = pos;
	pos++;
	m_opts_list->InsertItem( pos, wxEmptyString );
	pos++;
	pos = AddMMOptionsToList( pos, LSL::OptionsWrapper::EngineOption );
	// AddMMOptionsToList already increments pos by itself
	m_opts_list->InsertItem( pos, wxEmptyString );
	pos++;
	m_mod_opts_index = pos;
	pos = AddMMOptionsToList( m_mod_opts_index, LSL::OptionsWrapper::ModOption );
	// AddMMOptionsToList already increments pos by itself
	m_opts_list->InsertItem( pos, wxEmptyString );
	pos++;
	m_map_opts_index = pos;
	pos = AddMMOptionsToList( m_map_opts_index, LSL::OptionsWrapper::MapOption );
	m_side_sel->Clear();
	if (m_battle != NULL) {
		try {
			printf("RegenerateOptionsList\n");
			const wxArrayString sides = LSL::Util::vectorToArrayString(LSL::usync().GetSides(STD_STRING(m_battle->GetHostModName())));
			for ( unsigned int i = 0; i < sides.GetCount(); i++ ) {
				m_side_sel->Append(sides[i], icons().GetBitmap( icons().GetSideIcon( m_battle->GetHostModName(), i ) ) );
			printf("RegenerateOptionsList %s\n", (const char*)sides[i].mb_str());
			}
		}
		catch ( ... ) {}
	}
}
Exemple #25
0
void AddBotDialog::ReloadAIList()
{
  try
  {
     m_ais = LSL::Util::vectorToArrayString(
                    LSL::usync().GetAIList(STD_STRING(m_battle.GetHostModName())));
  } catch (...) {}

  m_ai->Clear();
  for ( unsigned int i = 0; i < m_ais.GetCount(); i++ ) m_ai->Append( RefineAIName(m_ais[i]) );
  if ( m_ais.GetCount() > 0 )
  {
    m_ai->SetStringSelection( sett().GetLastAI() );
    if ( m_ai->GetStringSelection() == wxEmptyString ) m_ai->SetSelection( 0 );
  }
  else
  {
    customMessageBox(SL_MAIN_ICON, _("No AI bots found in your Spring installation."), _("No bot-libs found"), wxOK );
  }
  m_add_btn->Enable( m_ai->GetStringSelection() != wxEmptyString );
  ShowAIInfo();
  ShowAIOptions();
}
void BattleListTab::DoJoin(IBattle& battle)
{
	wxString password = wxEmptyString;

	IBattle* curbattle = ui().mw().GetJoinTab().GetCurrentBattle();

	if (curbattle != 0 && curbattle->GetID() == battle.GetID()) {
		ui().mw().ShowTab(MainWindow::PAGE_JOIN);
		return;
	}

	if (curbattle != 0) {
		if (ui().Ask(_("Already in another battle"), _("You are already in a battle.\n\nDo you want to leave your current battle and join this one?"))) {
			curbattle->Leave();
			ui().mw().GetJoinTab().LeaveCurrentBattle();
		} else {
			return;
		}
	}

	if (battle.IsPassworded()) {
		wxPasswordEntryDialog pw(this, _("Battle password"), _("Enter password (spaces will be stripped)"));
		pw.SetFocus();
		if (pw.ShowModal() != wxID_OK) {
			return;
		}
		password = pw.GetValue();
		password.Replace(_T(" "), wxEmptyString);
	}

	if (!ui().DownloadArchives(battle)) {
		return;
	}

	battle.Join(STD_STRING(password));
}
Exemple #27
0
std::string GetBestMatch(const std::vector<std::string>& a, const std::string& s, double* distance  )
{
    auto arr = LSL::Util::vectorToArrayString(a);
    return STD_STRING(GetBestMatch(arr, TowxString(s), distance));
}
void RunHostBattleDialog( wxWindow* parent )
{
	HostBattleDialog dlg( parent );
	if ( dlg.ShowModal() == wxID_OK )
	{
		BattleOptions bo;
		bo.description = sett().GetLastHostDescription();
		bo.port = sett().GetLastHostPort();
		bo.nattype = NatType( sett().GetLastHostNATSetting() );

		if ( bo.nattype == NAT_None && sett().GetTestHostPort() )
		{
			switch ( ui().TestHostPort( bo.port ) )
			{
				case Server::porttest_pass :
					break; // success
				case Server::porttest_pass_WX26 :
					wxLogWarning( _T( "hosting port %d: test aborted (wx26)" ), bo.port  );
					customMessageBoxNoModal( SL_MAIN_ICON, wxFormat( _( "Your using wxWidgets prior to version 2.8,\n "
											 "port testing is not supported.\n Hosting may or may not work." ) ) % bo.port );
					sett().SetTestHostPort( false ); // no need to have it checked anymore
					break;

				case Server::porttest_unreachable :
					wxLogWarning( _T( "hosting port %d: test undetermined" ), bo.port  );
					customMessageBoxNoModal( SL_MAIN_ICON, wxFormat( _( "The server used for testing your port %d "
											 "is unreachable. \nHosting may or may not work with this setting." ) ) % bo.port );
					break; //inconclusive test shouldn't hinder hosting imo (koshi)

				case Server::porttest_timeout :
				case Server::porttest_socketNotOk :
				case Server::porttest_socketError :
					wxLogWarning( _T( "hosting port %d: test unsuccessful, closing battle" ), bo.port  );
					customMessageBoxNoModal( SL_MAIN_ICON, wxFormat( _( "Battle not started because the port you selected (%d) "
											 "is unable to-f /home/kosh/.springlobby/testing.conf recieve incoming packets\n checks your router & firewall configuration again or change port "
											 "in the dialog.\n\nIf everything else fails, enable the Hole Punching NAT Traversal\n "
											 "option in the hosting settings." ) ) % bo.port );
					return;
				default:
					wxLogWarning( _T( "unknonw port forward test result" ) );
					break;

			}
			if ( !ui().TestHostPort( bo.port ) )
			{
				wxLogWarning( _T( "hosting port %d: test unsuccessful, closing battle" ), bo.port  );
				customMessageBoxNoModal( SL_MAIN_ICON, wxFormat( _( "Battle not started because the port you selected (%d) "
										"is unable to recieve incoming packets\n checks your router & firewall configuration "
										"again or change port in the dialog.\n\nIf everything else fails, enable the Hole "
										"Punching NAT Traversal\n option in the hosting settings." ) ) % bo.port );
				return;
			}
		}

		// Get selected mod from unitsync.
		LSL::UnitsyncMod mod;
		try
		{
            mod = LSL::usync().GetMod(STD_STRING(sett().GetLastHostMod()));
            bo.modhash = TowxString(mod.hash);
            bo.modname = TowxString(mod.name);
		}
		catch ( ... )
		{
			wxLogWarning( _T( "can't host: game not found" ) );
			customMessageBoxNoModal( SL_MAIN_ICON, _( "Battle not started beacuse the game you selected could not be found. " ), _( "Error starting battle." ), wxOK );
			return;
		}

		LSL::UnitsyncMap map;
        const auto mname = STD_STRING(sett().GetLastHostMap());
		try {
			if ( LSL::usync().MapExists( mname ) )
				map = LSL::usync().GetMap( mname );
			else if ( LSL::usync().GetNumMaps() <= 0 )
			{
				wxLogWarning( _T( "no maps found" ) );
				customMessageBoxNoModal( SL_MAIN_ICON, _( "Couldn't find any maps in your spring installation. This could happen when you set the Spring settings incorrectly." ), _( "No maps found" ), wxOK );
				return;
			}
			else
			{
				map = LSL::usync().GetMap( 0 );
			}
		}
		catch ( ... )
		{
			wxLogWarning( _T( "no maps found" ) );
			customMessageBoxNoModal( SL_MAIN_ICON, _( "Couldn't find any maps in your spring installation. This could happen when you set the Spring settings incorrectly." ), _( "No maps found" ), wxOK );
			return;
		}
        bo.maphash = TowxString(map.hash);
        bo.mapname = TowxString(map.name);

		bo.rankneeded = sett().GetLastRankLimit();

		bo.maxplayers = sett().GetLastHostPlayerNum();
		bo.userelayhost = sett().GetLastHostRelayedMode();
		if ( bo.userelayhost ) bo.nattype = NAT_None;
		bo.relayhost = sett().GetLastRelayedHost();
		bo.engineName = _T("spring");
		bo.engineVersion = TowxString(LSL::usync().GetSpringVersion());

		serverSelector().GetServer().HostBattle( bo, sett().GetLastHostPassword() );
	}
}
Exemple #29
0
std::string GetDownloadUrl(const std::string& version)
{
	wxString url = cfg().ReadString(_T("/General/DownloadUrl"));
	url.Replace(wxT("%s"), TowxString(version));
	return STD_STRING(url);
}
Exemple #30
0
//! (koshi) don't delete commented things please, they might be need in the future and i'm lazy
void IBattle::GetBattleFromScript( bool loadmapmod )
{

	BattleOptions opts;
	std::stringstream ss (GetScript());
	LSL::TDF::PDataList script( LSL::TDF::ParseTDF(ss) );

	LSL::TDF::PDataList replayNode ( script->Find("GAME") );
	if ( replayNode.ok() ) {

		std::string modname = replayNode->GetString("GameType");
		std::string modhash = replayNode->GetString("ModHash");
		if ( !modhash.empty() ) modhash = STD_STRING(MakeHashUnsigned(TowxString(modhash)));
		SetHostMod( modname, modhash );

		//don't have the maphash, what to do?
		//ui download function works with mapname if hash is empty, so works for now
		std::string mapname    = replayNode->GetString("MapName");
		std::string maphash    = replayNode->GetString("MapHash");
		if ( !maphash.empty() ) maphash = STD_STRING(MakeHashUnsigned(TowxString(maphash)));
		SetHostMap( mapname, maphash );

//        opts.ip         = replayNode->GetString( _T("HostIP") );
//        opts.port       = replayNode->GetInt  ( _T("HostPort"), DEFAULT_EXTERNAL_UDP_SOURCE_PORT );
		opts.spectators = 0;

		int playernum = replayNode->GetInt("NumPlayers", 0);
		int usersnum = replayNode->GetInt("NumUsers", 0);
		if ( usersnum > 0 ) playernum = usersnum;
//        int allynum = replayNode->GetInt  ( _T("NumAllyTeams"), 1);
//        int teamnum = replayNode->GetInt  ( _T("NumTeams"), 1);



		LSL::StringVector sides;
		if ( loadmapmod ) {
			sides = LSL::usync().GetSides(modname);
		}

		IBattle::TeamVec parsed_teams = GetParsedTeamsVec();
		IBattle::AllyVec parsed_allies = GetParsedAlliesVec();

		//[PLAYERX] sections
		for ( int i = 0; i < playernum ; ++i ) {
			LSL::TDF::PDataList player ( replayNode->Find(stdprintf("PLAYER%d", i)));
			LSL::TDF::PDataList bot ( replayNode->Find(stdprintf("AI%d", i )));
			if ( player.ok() || bot.ok() ) {
				if ( bot.ok() ) player = bot;
				User user(player->GetString("Name"), boost::to_upper_copy(player->GetString("CountryCode")), 0);
				UserBattleStatus& status = user.BattleStatus();
				status.isfromdemo = true;
				status.spectator = player->GetInt("Spectator", 0 );
				opts.spectators += user.BattleStatus().spectator;
				status.team = player->GetInt("Team");
				if ( !status.spectator ) {
					PlayerJoinedTeam( status.team );
				}
				status.sync = true;
				status.ready = true;
				if ( status.spectator ) m_opts.spectators++;
				else {
					if ( !bot.ok() ) {
						if ( status.ready) m_players_ready++;
						if ( status.sync ) m_players_sync++;
						if ( status.sync && status.ready ) m_players_ok++;
					}
				}

				//! (koshi) changed this from ServerRankContainer to RankContainer
				user.Status().rank = (UserStatus::RankContainer)player->GetInt("Rank", -1 );

				if ( bot.ok() ) {
					status.aishortname = bot->GetString("ShortName");
					status.aiversion = bot->GetString("Version");
					int ownerindex = bot->GetInt("Host");
					LSL::TDF::PDataList aiowner (replayNode->Find(stdprintf("PLAYER%d", ownerindex)));
					if ( aiowner.ok() ) {
						status.owner = aiowner->GetString("Name");
					}
				}

				IBattle::TeamInfoContainer teaminfos = parsed_teams[user.BattleStatus().team];
				if ( !teaminfos.exist ) {
					LSL::TDF::PDataList team( replayNode->Find( stdprintf("TEAM%d", user.BattleStatus().team) ));
					if ( team.ok() ) {
						teaminfos.exist = true;
						teaminfos.TeamLeader = team->GetInt("TeamLeader", 0 );
						teaminfos.StartPosX = team->GetInt("StartPosX", -1 );
						teaminfos.StartPosY = team->GetInt("StartPosY", -1 );
						teaminfos.AllyTeam = team->GetInt("AllyTeam", 0 );
						teaminfos.RGBColor = GetColorFromFloatStrng(TowxString(team->GetString("RGBColor")));
						teaminfos.SideName = team->GetString("Side", "");
						teaminfos.Handicap = team->GetInt("Handicap", 0 );
						const int sidepos = LSL::Util::IndexInSequence(sides, teaminfos.SideName);
						teaminfos.SideNum = sidepos;
						parsed_teams[ user.BattleStatus().team ] = teaminfos;
					}
				}
				if ( teaminfos.exist ) {
					status.ally = teaminfos.AllyTeam;
					status.pos.x = teaminfos.StartPosX;
					status.pos.y = teaminfos.StartPosY;
					status.colour = teaminfos.RGBColor;
					status.handicap = teaminfos.Handicap;
					if ( !status.spectator ) {
						PlayerJoinedAlly( status.ally );
					}
					if ( teaminfos.SideNum >= 0 ) status.side = teaminfos.SideNum;
					IBattle::AllyInfoContainer allyinfos = parsed_allies[user.BattleStatus().ally];
					if ( !allyinfos.exist ) {
						LSL::TDF::PDataList ally( replayNode->Find(stdprintf("ALLYTEAM%d", user.BattleStatus().ally) ) );
						if ( ally.ok() ) {
							allyinfos.exist = true;
							allyinfos.NumAllies = ally->GetInt("NumAllies", 0 );
							allyinfos.StartRectLeft = ally->GetInt("StartRectLeft", 0 );
							allyinfos.StartRectTop = ally->GetInt("StartRectTop", 0 );
							allyinfos.StartRectRight = ally->GetInt("StartRectRight", 0 );
							allyinfos.StartRectBottom = ally->GetInt("StartRectBottom", 0 );
							parsed_allies[ user.BattleStatus().ally ] = allyinfos;
							AddStartRect( user.BattleStatus().ally, allyinfos.StartRectTop, allyinfos.StartRectTop, allyinfos.StartRectRight, allyinfos.StartRectBottom );
						}
					}
				}

				AddUserFromDemo( user );
			}

		}
		SetParsedTeamsVec( parsed_teams );
		SetParsedAlliesVec( parsed_allies );

		//MMoptions, this'll fail unless loading map/mod into wrapper first
		if ( loadmapmod ) {
			LoadScriptMMOpts("mapoptions", replayNode );
			LoadScriptMMOpts("modoptions", replayNode );
		}

		opts.maxplayers = playernum ;

	}
	SetBattleOptions( opts );
}