static bool saveMainWindow(HWND hwnd, bool quiting, CString* cmdLineOut = NULL) { DWORD errorID = 0; CString arg; CString cmdLine; // save dialog state bool isClient = isClientChecked(hwnd); HKEY key = CArchMiscWindows::addKey(HKEY_CURRENT_USER, getSettingsPath()); if (key != NULL) { HWND child; child = getItem(hwnd, IDC_MAIN_CLIENT_SERVER_NAME_EDIT); CArchMiscWindows::setValue(key, "server", getWindowText(child)); child = getItem(hwnd, IDC_MAIN_DEBUG); CArchMiscWindows::setValue(key, "debug", SendMessage(child, CB_GETCURSEL, 0, 0)); CArchMiscWindows::setValue(key, "isServer", isClient ? 0 : 1); CArchMiscWindows::closeKey(key); } // save user's configuration if (!saveConfig(ARG->m_config, false)) { errorID = IDS_SAVE_FAILED; arg = getErrorString(GetLastError()); goto failed; } // save autostart configuration if (CAutoStart::isDaemonInstalled()) { if (!saveConfig(ARG->m_config, true)) { errorID = IDS_AUTOSTART_SAVE_FAILED; arg = getErrorString(GetLastError()); goto failed; } } // get autostart command cmdLine = getCommandLine(hwnd, false, quiting); if (cmdLineOut != NULL) { *cmdLineOut = cmdLine; } if (cmdLine.empty()) { return quiting; } // save autostart command if (CAutoStart::isDaemonInstalled()) { try { CAutoStart::reinstallDaemon(isClient, cmdLine); CAutoStart::uninstallDaemons(!isClient); } catch (XArchDaemon& e) { errorID = IDS_INSTALL_GENERIC_ERROR; arg = e.what(); goto failed; } } return true; failed: CString errorMessage = CStringUtil::format(getString(errorID).c_str(), arg.c_str()); if (quiting) { errorMessage += "\n"; errorMessage += getString(IDS_UNSAVED_DATA_REALLY_QUIT); if (askVerify(hwnd, errorMessage)) { return true; } } else { showError(hwnd, errorMessage); } return false; }
bool KSFLoader::LoadFromKSFFile( const CString &sPath, Steps &out, const Song &song ) { LOG->Trace( "Steps::LoadFromKSFFile( '%s' )", sPath.c_str() ); MsdFile msd; if( !msd.ReadFile( sPath ) ) RageException::Throw( "Error opening file '%s'.", sPath.c_str() ); int iTickCount = -1; // this is the value we read for TICKCOUNT CStringArray asRows; for( unsigned i=0; i<msd.GetNumValues(); i++ ) { const MsdFile::value_t &sParams = msd.GetValue(i); CString sValueName = sParams[0]; // handle the data if( 0==stricmp(sValueName,"TICKCOUNT") ) iTickCount = atoi(sParams[1]); else if( 0==stricmp(sValueName,"STEP") ) { CString step = sParams[1]; TrimLeft(step); split( step, "\n", asRows, true ); } else if( 0==stricmp(sValueName,"DIFFICULTY") ) out.SetMeter(atoi(sParams[1])); } if( iTickCount == -1 ) { iTickCount = 2; LOG->Warn( "\"%s\": TICKCOUNT not found; defaulting to %i", sPath.c_str(), iTickCount ); } NoteData notedata; // read it into here { CString sDir, sFName, sExt; splitpath( sPath, sDir, sFName, sExt ); sFName.MakeLower(); out.SetDescription(sFName); if( sFName.Find("crazy")!=-1 ) { out.SetDifficulty(DIFFICULTY_HARD); if(!out.GetMeter()) out.SetMeter(8); } else if( sFName.Find("hard")!=-1 ) { out.SetDifficulty(DIFFICULTY_MEDIUM); if(!out.GetMeter()) out.SetMeter(5); } else if( sFName.Find("easy")!=-1 ) { out.SetDifficulty(DIFFICULTY_EASY); if(!out.GetMeter()) out.SetMeter(2); } else { out.SetDifficulty(DIFFICULTY_MEDIUM); if(!out.GetMeter()) out.SetMeter(5); } notedata.SetNumTracks( 5 ); out.m_StepsType = STEPS_TYPE_PUMP_SINGLE; /* Check for "halfdouble" before "double". */ if( sFName.Find("halfdouble") != -1 || sFName.Find("h_double") != -1 ) { notedata.SetNumTracks( 6 ); out.m_StepsType = STEPS_TYPE_PUMP_HALFDOUBLE; } else if( sFName.Find("double") != -1 ) { notedata.SetNumTracks( 10 ); out.m_StepsType = STEPS_TYPE_PUMP_DOUBLE; } else if( sFName.Find("_2") != -1 ) { notedata.SetNumTracks( 10 ); out.m_StepsType = STEPS_TYPE_PUMP_COUPLE; } } int iHoldStartRow[13]; int t; for( t=0; t<13; t++ ) iHoldStartRow[t] = -1; for( unsigned r=0; r<asRows.size(); r++ ) { CString& sRowString = asRows[r]; StripCrnl( sRowString ); if( sRowString == "" ) continue; // skip /* All 2s indicates the end of the song. */ if( sRowString == "2222222222222" ) break; if(sRowString.size() != 13) { LOG->Warn("File %s had a RowString with an improper length (\"%s\"); corrupt notes ignored", sPath.c_str(), sRowString.c_str()); return false; } /* Half-doubles is offset; "0011111100000". */ if( out.m_StepsType == STEPS_TYPE_PUMP_HALFDOUBLE ) sRowString.erase( 0, 2 ); // the length of a note in a row depends on TICKCOUNT float fBeatThisRow = r/(float)iTickCount; int row = BeatToNoteRow(fBeatThisRow); for( int t=0; t < notedata.GetNumTracks(); t++ ) { if( sRowString[t] == '4' ) { /* Remember when each hold starts; ignore the middle. */ if( iHoldStartRow[t] == -1 ) iHoldStartRow[t] = r; continue; } if( iHoldStartRow[t] != -1 ) // this ends the hold { HoldNote hn ( t, /* button */ BeatToNoteRow(iHoldStartRow[t]/(float)iTickCount), /* start */ BeatToNoteRow((r-1)/(float)iTickCount) /* end */ ); notedata.AddHoldNote( hn ); iHoldStartRow[t] = -1; } TapNote tap; switch(sRowString[t]) { case '0': tap = TAP_EMPTY; break; case '1': tap = TAP_ORIGINAL_TAP; break; default: ASSERT(0); tap = TAP_EMPTY; break; } notedata.SetTapNote(t, row, tap); } } /* We need to remove holes where the BPM increases. */ // if( song.m_Timing.m_BPMSegments.size() > 1 ) // RemoveHoles( notedata, song ); out.SetNoteData(¬edata); out.TidyUpData(); return true; }
void CDaemonApp::mainLoop(bool logToFile) { try { DAEMON_RUNNING(true); /*while (true) { }*/ if (logToFile) CLOG->insert(new CFileLogOutputter(logPath().c_str())); // create socket multiplexer. this must happen after daemonization // on unix because threads evaporate across a fork(). CSocketMultiplexer multiplexer; // uses event queue, must be created here. m_ipcServer = new CIpcServer(); // send logging to gui via ipc, log system adopts outputter. m_ipcLogOutputter = new CIpcLogOutputter(*m_ipcServer); CLOG->insert(m_ipcLogOutputter); #if SYSAPI_WIN32 m_relauncher = new CMSWindowsRelauncher(false, *m_ipcServer, *m_ipcLogOutputter); #endif EVENTQUEUE->adoptHandler( CIpcServer::getMessageReceivedEvent(), m_ipcServer, new TMethodEventJob<CDaemonApp>(this, &CDaemonApp::handleIpcMessage)); m_ipcServer->listen(); #if SYSAPI_WIN32 // HACK: create a dummy screen, which can handle system events // (such as a stop request from the service controller). CMSWindowsScreen::init(CArchMiscWindows::instanceWin32()); CGameDeviceInfo gameDevice; CScreen dummyScreen(new CMSWindowsScreen(false, true, gameDevice, false)); CString command = ARCH->setting("Command"); bool elevate = ARCH->setting("Elevate") == "1"; if (command != "") { LOG((CLOG_INFO "using last known command: %s", command.c_str())); m_relauncher->command(command, elevate); } m_relauncher->startAsync(); #endif EVENTQUEUE->loop(); #if SYSAPI_WIN32 m_relauncher->stop(); delete m_relauncher; #endif EVENTQUEUE->removeHandler( CIpcServer::getMessageReceivedEvent(), m_ipcServer); CLOG->remove(m_ipcLogOutputter); delete m_ipcLogOutputter; delete m_ipcServer; DAEMON_RUNNING(false); } catch (XArch& e) { LOG((CLOG_ERR "xarch exception: %s", e.what().c_str())); } catch (std::exception& e) { LOG((CLOG_ERR "std exception: %s", e.what())); } catch (...) { LOG((CLOG_ERR "unrecognized error.")); } }
bool CUser::IsHostAllowed(const CString& sHostMask) const { if (m_ssAllowedHosts.empty()) { return true; } for (const CString& sHost : m_ssAllowedHosts) { if (sHostMask.WildCmp(sHost)) { return true; } else { // CIDR notation checker, e.g. "192.0.2.0/24" or "2001:db8::/32" // Try to split the string into an IP and routing prefix VCString vsSplitCIDR; if (sHost.Split("/", vsSplitCIDR, false) != 2) continue; const CString sRoutingPrefix = vsSplitCIDR.back(); const int iRoutingPrefix = sRoutingPrefix.ToInt(); if (iRoutingPrefix < 0 || iRoutingPrefix > 128) continue; // If iRoutingPrefix is 0, it could be due to ToInt() failing, so // sRoutingPrefix needs to be all zeroes if (iRoutingPrefix == 0 && sRoutingPrefix != "0") continue; // Convert each IP from a numeric string to an addrinfo addrinfo aiHints; memset(&aiHints, 0, sizeof(addrinfo)); aiHints.ai_flags = AI_NUMERICHOST; addrinfo* aiHost; int iIsHostValid = getaddrinfo(sHostMask.c_str(), nullptr, &aiHints, &aiHost); if (iIsHostValid != 0) continue; aiHints.ai_family = aiHost->ai_family; // Host and range must be in // the same address family addrinfo* aiRange; int iIsRangeValid = getaddrinfo(vsSplitCIDR.front().c_str(), nullptr, &aiHints, &aiRange); if (iIsRangeValid != 0) { freeaddrinfo(aiHost); continue; } // "/0" allows all IPv[4|6] addresses if (iRoutingPrefix == 0) { freeaddrinfo(aiHost); freeaddrinfo(aiRange); return true; } // If both IPs are valid and of the same type, make a bit field mask // from the routing prefix, AND it to the host and range, and see if // they match bool bIsHostInRange = false; if (aiHost->ai_family == AF_INET) { if (iRoutingPrefix > 32) { freeaddrinfo(aiHost); freeaddrinfo(aiRange); continue; } const sockaddr_in* saHost = (sockaddr_in*)(aiHost->ai_addr); const sockaddr_in* saRange = (sockaddr_in*)(aiRange->ai_addr); // Make IPv4 bitmask const in_addr_t inBitmask = htonl((~0u) << (32 - iRoutingPrefix)); // Compare masked IPv4s bIsHostInRange = ((inBitmask & saHost->sin_addr.s_addr) == (inBitmask & saRange->sin_addr.s_addr)); } else if (aiHost->ai_family == AF_INET6) { // Make IPv6 bitmask in6_addr in6aBitmask; memset(&in6aBitmask, 0, sizeof(in6aBitmask)); for (int i = 0, iBitsLeft = iRoutingPrefix; iBitsLeft > 0; ++i, iBitsLeft -= 8) { if (iBitsLeft >= 8) { in6aBitmask.s6_addr[i] = (uint8_t)(~0u); } else { in6aBitmask.s6_addr[i] = (uint8_t)(~0u) << (8 - iBitsLeft); } } // Compare masked IPv6s bIsHostInRange = true; const sockaddr_in6* sa6Host = (sockaddr_in6*)(aiHost->ai_addr); const sockaddr_in6* sa6Range = (sockaddr_in6*)(aiRange->ai_addr); for (int i = 0; i < 16; ++i) { if ((in6aBitmask.s6_addr[i] & sa6Host->sin6_addr.s6_addr[i]) != (in6aBitmask.s6_addr[i] & sa6Range->sin6_addr.s6_addr[i])) { bIsHostInRange = false; } } } freeaddrinfo(aiHost); freeaddrinfo(aiRange); if (bIsHostInRange) return true; } } return false; }
void MusicWheel::Load( CString sType ) { LOG->Trace( "MusicWheel::Load('%s')", sType.c_str() ); LoadFromMetrics( sType ); LoadVariables(); FOREACH( MusicWheelItem*, m_MusicWheelItems, i ) SAFE_DELETE( *i ); m_MusicWheelItems.clear(); for( int i=0; i<NUM_WHEEL_ITEMS; i++ ) m_MusicWheelItems.push_back( new MusicWheelItem ); LOG->Trace( "MusicWheel::Load('%s')", sType.c_str() ); if (GAMESTATE->m_pCurSong != NULL) LOG->Trace( "Current Song: %s", GAMESTATE->m_pCurSong->GetSongDir().c_str() ); else LOG->Trace( "Current Song: NULL" ); SONGMAN->UpdateRankingCourses(); /* // for debugging. // Whatever Screen uses MusicWheel should set the Style if it needs to be set. if( GAMESTATE->m_CurStyle == NULL ) GAMESTATE->m_CurStyle = GAMEMAN->STYLE_DANCE_SINGLE; */ /* We play a lot of this one, so precache it. */ m_soundChangeSort.Load( THEME->GetPathS(sType,"sort") ); m_soundExpand.Load( THEME->GetPathS(sType,"expand"), true ); m_WheelState = STATE_SELECTING_MUSIC; if( GAMESTATE->IsExtraStage() || GAMESTATE->IsExtraStage2() ) { // make the preferred group the group of the last song played. // if( GAMESTATE->m_sPreferredSongGroup==GROUP_ALL_MUSIC && !PREFSMAN->m_bPickExtraStage ) // { // ASSERT(GAMESTATE->m_pCurSong); // GAMESTATE->m_sPreferredSongGroup = GAMESTATE->m_pCurSong->m_sGroupName; // } Song* pSong; Steps* pSteps; PlayerOptions po; SongOptions so; SONGMAN->GetExtraStageInfo( GAMESTATE->IsExtraStage2(), GAMESTATE->GetCurrentStyle(), pSong, pSteps, po, so ); GAMESTATE->m_pCurSong.Set( pSong ); GAMESTATE->m_pPreferredSong = pSong; FOREACH_HumanPlayer( p ) { GAMESTATE->m_pCurSteps[p].Set( pSteps ); GAMESTATE->m_pPlayerState[p]->m_PlayerOptions = po; GAMESTATE->m_PreferredDifficulty[p].Set( pSteps->GetDifficulty() ); } GAMESTATE->m_SongOptions = so; }
void KModelEditorTagExport::OnBnClickedBatchExport() { HRESULT hr = E_FAIL; IEKG3DClipTable *piClipTable = NULL; DWORD dwCurNumFrames = 0; vector<CString> vecError; CString strText; TCHAR strSouceTani[MAX_PATH]; TCHAR strTargetAni[MAX_PATH]; DWORD dwCount = m_ListBox_Source.GetCount(); KG_PROCESS_ERROR(m_pContainer); KG_PROCESS_ERROR(dwCount>0); hr = g_pEngineManager->GetIEKG3DClipTable(&piClipTable); KG_COM_PROCESS_ERROR(hr); KG_PROCESS_ERROR(MessageBox("如果原有的同名tani文件存在将会被覆盖掉,确定要执行?","提示",MB_OKCANCEL) == IDOK); for(DWORD i=0;i< dwCount;i++) { IEKG3DClip* pClip = NULL; m_ListBox_Source.GetText(i,strText); sprintf_s(strSouceTani,"%s%s\\动作\\%s.tani",m_strPath,m_strSource,strText); int nIndex = strText.Find(m_strSource); if(nIndex != 0) continue; CString strTargetName; strTargetName.Format("%s%s", m_strTarget,strText.Right(strText.GetLength() - m_strSource.GetLength())); sprintf_s(strTargetAni,"%s%s\\动作\\%s.ani",m_strPath,m_strTarget,strTargetName); piClipTable->LoadResourceFromFileInEditor(strTargetAni, 0, 0, (IEKG3DClip **)&pClip); if(pClip) { HRESULT hr =E_FAIL; if(SUCCEEDED(m_pContainer->Load(strSouceTani))) { DWORD dwNumFrames = 0; pClip->GetNumFrames(&dwNumFrames); hr = m_pContainer->ExportTani(strTargetAni,dwNumFrames); } if(FAILED(hr)) vecError.push_back(strTargetAni); } SAFE_RELEASE(pClip); } m_pContainer->Load(m_strTaniName); if (vecError.size()> 0) { std::string strText = "以下文件导出tani失败\n"; for (DWORD i = 0; i<vecError.size();i++) { strText += vecError[i]; strText += "\n"; } MessageBox(strText.c_str()); } else MessageBox("恭喜,导出完成。可以继续你的工作了!!!"); Exit0: ; }
void ScreenUserPacks::HandleScreenMessage( const ScreenMessage SM ) { #if 0 /* Not compatible with FileCopy callback system; was this ever used? -- vyhd */ if ( SM == SM_CancelTransfer ) { Dialog::OK("SM_CancelTransfer"); InterruptCopy(); InputEventArray throwaway; INPUTFILTER->GetInputEvents( throwaway ); LOG->Warn("Cancelled Transfer of user pack."); } #endif if ( SM == SM_LinkedMenuChange ) { m_pCurLOM = m_pCurLOM->SwitchToNextMenu(); return; } if ( SM == SM_ConfirmDeleteZip ) { SCREENMAN->Prompt( SM_AnswerConfirmDeleteZip, "Proceed to delete pack from machine?", PROMPT_YES_NO, ANSWER_NO ); } if ( SM == SM_AnswerConfirmDeleteZip ) { if (ScreenPrompt::s_LastAnswer == ANSWER_NO) return; CString sSelection = m_AddedZips.GetCurrentSelection(); g_CurSelection = sSelection; bool bSuccess = UPACKMAN->Remove( USER_PACK_SAVE_PATH + sSelection ); if (bSuccess) { m_SoundDelete.Play(); ReloadZips(); m_bRestart = true; } else { SCREENMAN->SystemMessage( "Failed to delete zip file from machine. Check your file permissions." ); } } if ( SM == SM_ConfirmAddZip ) { SCREENMAN->Prompt( SM_AnswerConfirmAddZip, "Proceed to add pack to machine?", PROMPT_YES_NO, ANSWER_NO ); } if ( SM == SM_AnswerConfirmAddZip ) { CString sError; m_bPrompt = false; if (ScreenPrompt::s_LastAnswer == ANSWER_NO) return; m_bStopThread = true; m_PlayerSongLoadThread.Wait(); MountMutex.Lock(); #if defined(LINUX) && defined(ITG_ARCADE) system( "mount -o remount,rw /itgdata" ); #endif MEMCARDMAN->LockCards(); MEMCARDMAN->MountCard(m_CurPlayer, 99999); CString sSelection = m_USBZips.GetCurrentSelection(); { //////////////////////// #define XFER_CLEANUP MEMCARDMAN->UnmountCard(m_CurPlayer); \ MEMCARDMAN->UnlockCards(); \ MountMutex.Unlock(); \ m_bStopThread = false; \ m_PlayerSongLoadThread.Create( InitSASSongThread, this ) //////////////////////// g_CurXferFile = MEM_CARD_MOUNT_POINT[m_CurPlayer] + "/" + USER_PACK_TRANSFER_PATH + sSelection; if ( !UPACKMAN->IsPackTransferable( sSelection, g_CurXferFile, sError ) || !UPACKMAN->IsPackMountable( g_CurXferFile, sError ) ) { SCREENMAN->SystemMessage( "Could not add pack to machine:\n" + sError ); XFER_CLEANUP; return; } sError = ""; // ?? RageTimer start; DrawTimer.Touch(); g_iLastCurrentBytes = 0; g_UpdateDuration.Touch(); if (!UPACKMAN->TransferPack( g_CurXferFile, sSelection, UpdateXferProgress, sError ) ) { SCREENMAN->SystemMessage( "Transfer error:\n" + sError ); XFER_CLEANUP; SCREENMAN->HideOverlayMessage(); SCREENMAN->ZeroNextUpdate(); return; } LOG->Debug( "Transferred %s in %f seconds.", g_CurXferFile.c_str(), start.Ago() ); } #if defined(LINUX) && defined(ITG_ARCADE) sync(); system( "mount -o remount,ro /itgdata" ); #endif SCREENMAN->HideOverlayMessage(); SCREENMAN->ZeroNextUpdate(); FILEMAN->FlushDirCache(USER_PACK_SAVE_PATH); m_bRestart = true; m_SoundTransferDone.Play(); ReloadZips(); XFER_CLEANUP; #undef XFER_CLEANUP } switch( SM ) { case SM_GoToNextScreen: case SM_GoToPrevScreen: SCREENMAN->SetNewScreen( PREV_SCREEN ); break; } }
bool CFile::Delete(const CString& sFileName) { return (unlink(sFileName.c_str()) == 0) ? true : false; }
bool CFile::Chmod(const CString& sFile, mode_t mode) { return (chmod(sFile.c_str(), mode) == 0); }
gid_t CFile::GetGID(const CString& sFile) { struct stat st; return (stat(sFile.c_str(), &st) != 0) ? -1 : (int) st.st_gid; }
int CFile::GetInfo(const CString& sFile, struct stat& st) { return stat(sFile.c_str(), &st); }
time_t CFile::GetCTime(const CString& sFile) { struct stat st; return (stat(sFile.c_str(), &st) != 0) ? 0 : st.st_ctime; }
bool CFile::Exists(const CString& sFile) { struct stat st; return (stat(sFile.c_str(), &st) == 0); }
virtual void Load( OptionRowDefinition &defOut, CString sParam ) { ASSERT( sParam.size() ); if( sParam.CompareNoCase("NoteSkins")==0 ) { FillNoteSkins( defOut, sParam ); return; } else if( sParam.CompareNoCase("Steps")==0 ) { FillSteps( defOut, sParam, false ); return; } else if( sParam.CompareNoCase("StepsLocked")==0 ) { FillSteps( defOut, sParam, true ); return; } else if( sParam.CompareNoCase("Characters")==0 ) { FillCharacters( defOut, sParam ); return; } else if( sParam.CompareNoCase("Styles")==0 ) { FillStyles( defOut, sParam ); return; } else if( sParam.CompareNoCase("Groups")==0 ) { FillGroups( defOut, sParam ); return; } else if( sParam.CompareNoCase("Difficulties")==0 ) { FillDifficulties( defOut, sParam ); return; } else if( sParam.CompareNoCase("SongsInCurrentSongGroup")==0 ) { FillSongsInCurrentSongGroup( defOut, sParam ); return; } Init(); defOut.Init(); m_bUseModNameForIcon = true; defOut.name = sParam; Default.Load( -1, ParseCommands(ENTRY_DEFAULT(sParam)) ); /* Parse the basic configuration metric. */ Commands cmds = ParseCommands( ENTRY(sParam) ); if( cmds.v.size() < 1 ) RageException::Throw( "Parse error in ScreenOptionsMaster::%s", sParam.c_str() ); defOut.bOneChoiceForAllPlayers = false; const int NumCols = atoi( cmds.v[0].m_vsArgs[0] ); for( unsigned i=1; i<cmds.v.size(); i++ ) { const Command &cmd = cmds.v[i]; CString sName = cmd.GetName(); if( sName == "together" ) defOut.bOneChoiceForAllPlayers = true; else if( sName == "selectmultiple" ) defOut.selectType = SELECT_MULTIPLE; else if( sName == "selectone" ) defOut.selectType = SELECT_ONE; else if( sName == "selectnone" ) defOut.selectType = SELECT_NONE; else if( sName == "showoneinrow" ) defOut.layoutType = LAYOUT_SHOW_ONE_IN_ROW; else if( sName == "reloadrowmessages" ) { for( unsigned a=1; a<cmd.m_vsArgs.size(); a++ ) m_vsReloadRowMessages.push_back( cmd.m_vsArgs[a] ); } else if( sName == "enabledforplayers" ) { defOut.m_vEnabledForPlayers.clear(); for( unsigned a=1; a<cmd.m_vsArgs.size(); a++ ) { CString sArg = cmd.m_vsArgs[a]; PlayerNumber pn = (PlayerNumber)(atoi(sArg)-1); ASSERT( pn >= 0 && pn < NUM_PLAYERS ); defOut.m_vEnabledForPlayers.insert( pn ); } } else if( sName == "exportonchange" ) defOut.m_bExportOnChange = true; else if( sName == "broadcastonexport" ) { for( unsigned i=1; i<cmd.m_vsArgs.size(); i++ ) m_vsBroadcastOnExport.push_back( cmd.m_vsArgs[i] ); } else RageException::Throw( "Unkown row flag \"%s\"", sName.c_str() ); } for( int col = 0; col < NumCols; ++col ) { GameCommand mc; mc.Load( 0, ParseCommands(ENTRY_MODE(sParam, col)) ); /* If the row has just one entry, use the name of the row as the name of the * entry. If it has more than one, each one must be specified explicitly. */ if( mc.m_sName == "" && NumCols == 1 ) mc.m_sName = sParam; if( mc.m_sName == "" ) RageException::Throw( "List \"%s\", col %i has no name", sParam.c_str(), col ); if( !mc.IsPlayable() ) { LOG->Trace( "\"%s\" is not playable.", sParam.c_str() ); continue; } ListEntries.push_back( mc ); CString sName = mc.m_sName; CString sChoice = mc.m_sName; defOut.choices.push_back( sChoice ); } // OpenITG hack: load player-defined speed mods if (sParam == "Speed") { set<CString> additionalSet; // load anything from the machine profile first Profile *pMProf = PROFILEMAN->GetMachineProfile(); if (pMProf != NULL) { FOREACH_CONST(CString, pMProf->m_sPlayerAdditionalModifiers, mod) additionalSet.insert(*mod); } // then load anything from the players' profiles FOREACH_EnabledPlayer( pn ) { Profile *pProf = PROFILEMAN->GetProfile(pn); if (pProf == NULL) continue; FOREACH_CONST(CString, pProf->m_sPlayerAdditionalModifiers, mod) additionalSet.insert(*mod); } FOREACHS_CONST( CString, additionalSet, addit_mod ) { Regex mult("^[0-9]{1,2}(\\.[0-9]{1,2})?x$"); Regex constmod("^C[0-9]{1,4}$"); Regex mmod("^M[0-9]{1,4}$"); CString sAdditModName; if (mult.Compare(*addit_mod)) { float factor = 1.0f; sscanf(*addit_mod, "%fx", &factor); sAdditModName = ssprintf("x%.1f", factor); } else if (constmod.Compare(*addit_mod)) { unsigned bpm = 300; sscanf(*addit_mod, "C%u", &bpm); sAdditModName = ssprintf("c%u", bpm); } else if (mmod.Compare(*addit_mod)) { unsigned bpm = 600; sscanf(*addit_mod, "M%u", &bpm); sAdditModName = ssprintf("m%u", bpm); } else ASSERT(0); // how'd it get in here in the first place... GameCommand mc; mc.Load( 0, ParseCommands(CString("mod,")+*addit_mod+";name,"+sAdditModName) ); if ( !mc.IsPlayable() ) { LOG->Trace( "Additional mod \"%s\" is not playable.", addit_mod->c_str() ); continue; } ListEntries.push_back(mc); defOut.choices.push_back(mc.m_sName); }
Value DateProtoFuncImp::call(ExecState *exec, Object &thisObj, const List &args) { if ((id == ToString || id == ValueOf || id == GetTime || id == SetTime) && !thisObj.inherits(&DateInstanceImp::info)) { // non-generic function called on non-date object // ToString and ValueOf are generic according to the spec, but the mozilla // tests suggest otherwise... Object err = Error::create(exec,TypeError); exec->setException(err); return err; } Value result; UString s; const int bufsize=100; char timebuffer[bufsize]; CString oldlocale = setlocale(LC_TIME,NULL); if (!oldlocale.c_str()) oldlocale = setlocale(LC_ALL, NULL); Value v = thisObj.internalValue(); double milli = v.toNumber(exec); time_t tv = (time_t) floor(milli / 1000.0); int ms = int(milli - tv * 1000.0); // As long as we're using time_t we need to 'truncate' to avoid 'wrapping'. // Real long term solutions include: writing our own 64-bit-based date/time class, // using wxWindow's datetime.cpp (in wxBase), using QDateTime... or shifting // to a time_t range by substracting a big enough number of years.... if (sizeof(time_t) == 4) { // If time_t is signed, the bigger it can be is 2^31-1 if ( (time_t)-1 < 0 ) { if ( floor(milli / 1000.0) > ((double)((uint)1<<31)-1) ) { #ifdef KJS_VERBOSE fprintf(stderr, "date above time_t limit. Year seems to be %d\n", (int)(milli/(1000.0*365.25*86400)+1970)); #endif tv = ((uint)1<<31)-1; ms = 0; } } else // time_t is unsigned, the bigger it can be is 2^32-1, aka (uint)-1 if ( floor(milli / 1000.0) > ((double)(uint)-1) ) { #ifdef KJS_VERBOSE fprintf(stderr, "date above time_t limit. Year seems to be %d\n", (int)(milli/(1000.0*365.25*86400)+1970)); #endif tv = (uint)-1; ms = 0; } } struct tm *t; if (utc) t = gmtime(&tv); else t = localtime(&tv); switch (id) { case ToString: case ToDateString: case ToTimeString: case ToGMTString: case ToUTCString: setlocale(LC_TIME,"C"); if (id == DateProtoFuncImp::ToDateString) { strftime(timebuffer, bufsize, "%x",t); } else if (id == DateProtoFuncImp::ToTimeString) { strftime(timebuffer, bufsize, "%X",t); } else { // ToString, toGMTString & toUTCString t = (id == ToString ? localtime(&tv) : gmtime(&tv)); strftime(timebuffer, bufsize, "%a, %d %b %Y %H:%M:%S %z", t); } setlocale(LC_TIME,oldlocale.c_str()); result = String(timebuffer); break; case ToLocaleString: strftime(timebuffer, bufsize, "%c", t); result = String(timebuffer); break; case ToLocaleDateString: strftime(timebuffer, bufsize, "%x", t); result = String(timebuffer); break; case ToLocaleTimeString: strftime(timebuffer, bufsize, "%X", t); result = String(timebuffer); break; case ValueOf: result = Number(milli); break; case GetTime: result = Number(milli); break; case GetYear: // IE returns the full year even in getYear. // Let's do that too, it's more sensible. if ( exec->interpreter()->compatMode() == Interpreter::NetscapeCompat ) result = Number(t->tm_year); else result = Number(1900 + t->tm_year); break; case GetFullYear: result = Number(1900 + t->tm_year); break; case GetMonth: result = Number(t->tm_mon); break; case GetDate: result = Number(t->tm_mday); break; case GetDay: result = Number(t->tm_wday); break; case GetHours: result = Number(t->tm_hour); break; case GetMinutes: result = Number(t->tm_min); break; case GetSeconds: result = Number(t->tm_sec); break; case GetMilliSeconds: result = Number(ms); break; case GetTimezoneOffset: #if defined BSD || defined(__APPLE__) result = Number(-(t->tm_gmtoff / 60) + (t->tm_isdst > 0 ? 60 : 0)); #else # if defined(__BORLANDC__) #error please add daylight savings offset here! result = Number(_timezone / 60 - (t->tm_isdst > 0 ? 60 : 0)); # else result = Number((timezone / 60 - (t->tm_isdst > 0 ? 60 : 0 ))); # endif #endif break; case SetTime: milli = roundValue(exec,args[0]); result = Number(milli); thisObj.setInternalValue(result); break; case SetMilliSeconds: ms = args[0].toInt32(exec); break; case SetSeconds: t->tm_sec = args[0].toInt32(exec); break; case SetMinutes: t->tm_min = args[0].toInt32(exec); break; case SetHours: t->tm_hour = args[0].toInt32(exec); break; case SetDate: t->tm_mday = args[0].toInt32(exec); break; case SetMonth: t->tm_mon = args[0].toInt32(exec); break; case SetFullYear: t->tm_year = args[0].toInt32(exec) - 1900; break; case SetYear: t->tm_year = args[0].toInt32(exec) >= 1900 ? args[0].toInt32(exec) - 1900 : args[0].toInt32(exec); break; } if (id == SetYear || id == SetMilliSeconds || id == SetSeconds || id == SetMinutes || id == SetHours || id == SetDate || id == SetMonth || id == SetFullYear ) { result = Number(mktime(t) * 1000.0 + ms); thisObj.setInternalValue(result); } return result; }
bool CXWindowsClipboard::sendReply(CReply* reply) { assert(reply != NULL); // bail out immediately if reply is done if (reply->m_done) { LOG((CLOG_DEBUG1 "clipboard: finished reply to 0x%08x,%d,%d", reply->m_requestor, reply->m_target, reply->m_property)); return true; } // start in failed state if property is None bool failed = (reply->m_property == None); if (!failed) { LOG((CLOG_DEBUG1 "clipboard: setting property on 0x%08x,%d,%d", reply->m_requestor, reply->m_target, reply->m_property)); // send using INCR if already sending incrementally or if reply // is too large, otherwise just send it. const UInt32 maxRequestSize = 3 * XMaxRequestSize(m_display); const bool useINCR = (reply->m_data.size() > maxRequestSize); // send INCR reply if incremental and we haven't replied yet if (useINCR && !reply->m_replied) { UInt32 size = reply->m_data.size(); if (!CXWindowsUtil::setWindowProperty(m_display, reply->m_requestor, reply->m_property, &size, 4, m_atomINCR, 32)) { failed = true; } } // send more INCR reply or entire non-incremental reply else { // how much more data should we send? UInt32 size = reply->m_data.size() - reply->m_ptr; if (size > maxRequestSize) size = maxRequestSize; // send it if (!CXWindowsUtil::setWindowProperty(m_display, reply->m_requestor, reply->m_property, reply->m_data.data() + reply->m_ptr, size, reply->m_type, reply->m_format)) { failed = true; } else { reply->m_ptr += size; // we've finished the reply if we just sent the zero // size incremental chunk or if we're not incremental. reply->m_done = (size == 0 || !useINCR); } } } // if we've failed then delete the property and say we're done. // if we haven't replied yet then we can send a failure notify, // otherwise we've failed in the middle of an incremental // transfer; i don't know how to cancel that so i'll just send // the final zero-length property. // FIXME -- how do you gracefully cancel an incremental transfer? if (failed) { LOG((CLOG_DEBUG1 "clipboard: sending failure to 0x%08x,%d,%d", reply->m_requestor, reply->m_target, reply->m_property)); reply->m_done = true; if (reply->m_property != None) { CXWindowsUtil::CErrorLock lock(m_display); XDeleteProperty(m_display, reply->m_requestor, reply->m_property); } if (!reply->m_replied) { sendNotify(reply->m_requestor, m_selection, reply->m_target, None, reply->m_time); // don't wait for any reply (because we're not expecting one) return true; } else { static const char dummy = 0; CXWindowsUtil::setWindowProperty(m_display, reply->m_requestor, reply->m_property, &dummy, 0, reply->m_type, reply->m_format); // wait for delete notify return false; } } // send notification if we haven't yet if (!reply->m_replied) { LOG((CLOG_DEBUG1 "clipboard: sending notify to 0x%08x,%d,%d", reply->m_requestor, reply->m_target, reply->m_property)); reply->m_replied = true; // dump every property on the requestor window to the debug2 // log. we've seen what appears to be a bug in lesstif and // knowing the properties may help design a workaround, if // it becomes necessary. if (CLOG->getFilter() >= CLog::kDEBUG2) { CXWindowsUtil::CErrorLock lock(m_display); int n; Atom* props = XListProperties(m_display, reply->m_requestor, &n); LOG((CLOG_DEBUG2 "properties of 0x%08x:", reply->m_requestor)); for (int i = 0; i < n; ++i) { Atom target; CString data; char* name = XGetAtomName(m_display, props[i]); if (!CXWindowsUtil::getWindowProperty(m_display, reply->m_requestor, props[i], &data, &target, NULL, False)) { LOG((CLOG_DEBUG2 " %s: <can't read property>", name)); } else { // if there are any non-ascii characters in string // then print the binary data. static const char* hex = "0123456789abcdef"; for (CString::size_type j = 0; j < data.size(); ++j) { if (data[j] < 32 || data[j] > 126) { CString tmp; tmp.reserve(data.size() * 3); for (j = 0; j < data.size(); ++j) { unsigned char v = (unsigned char)data[j]; tmp += hex[v >> 16]; tmp += hex[v & 15]; tmp += ' '; } data = tmp; break; } } char* type = XGetAtomName(m_display, target); LOG((CLOG_DEBUG2 " %s (%s): %s", name, type, data.c_str())); if (type != NULL) { XFree(type); } } if (name != NULL) { XFree(name); } }
int CString::StrCmp(const CString& s, CString::size_type uLen) const { if (uLen != CString::npos) { return strncmp(c_str(), s.c_str(), uLen); } return strcmp(c_str(), s.c_str()); }
CString::CString(const CString &b) { data = new char[b.length()+1]; strcpy(data, b.c_str()); }
void ComboGraph::Load( CString Path, const StageStats &s, PlayerNumber pn ) { ASSERT( m_SubActors.size() == 0 ); /* Find the largest combo. */ int MaxComboSize = 0; unsigned i; for( i = 0; i < s.ComboList[pn].size(); ++i ) MaxComboSize = max( MaxComboSize, s.ComboList[pn][i].GetStageCnt() ); float width = -1; for( i = 0; i < s.ComboList[pn].size(); ++i ) { const StageStats::Combo_t &combo = s.ComboList[pn][i]; if( combo.GetStageCnt() < MinComboSizeToShow ) continue; /* too small */ const bool IsMax = (combo.GetStageCnt() == MaxComboSize); LOG->Trace("combo %i is %f+%f", i, combo.fStartSecond, combo.fSizeSeconds); Sprite *sprite = new Sprite; sprite->SetName( "ComboBar" ); const CString path = ssprintf( "%s %s", Path.c_str(), IsMax? "max":"normal" ); sprite->Load( THEME->GetPathToG(path) ); const float start = SCALE( combo.fStartSecond, s.fFirstSecond[pn], s.fLastSecond[pn], 0.0f, 1.0f ); const float size = SCALE( combo.fSizeSeconds, 0, s.fLastSecond[pn]-s.fFirstSecond[pn], 0.0f, 1.0f ); sprite->SetCropLeft ( SCALE( size, 0.0f, 1.0f, 0.5f, 0.0f ) ); sprite->SetCropRight( SCALE( size, 0.0f, 1.0f, 0.5f, 0.0f ) ); sprite->BeginTweening( .5f ); sprite->SetCropLeft( start ); sprite->SetCropRight( 1 - (size + start) ); if( width < 0 ) width = sprite->GetUnzoomedWidth(); m_Sprites.push_back( sprite ); this->AddChild( sprite ); } for( i = 0; i < s.ComboList[pn].size(); ++i ) { const StageStats::Combo_t &combo = s.ComboList[pn][i]; if( combo.GetStageCnt() < MinComboSizeToShow ) continue; /* too small */ if( !MaxComboSize ) continue; const bool IsMax = (combo.GetStageCnt() == MaxComboSize); if( !IsMax ) continue; BitmapText *text = new BitmapText; text->SetName( "ComboMaxNumber" ); text->LoadFromFont( THEME->GetPathToF(Path) ); const float start = SCALE( combo.fStartSecond, s.fFirstSecond[pn], s.fLastSecond[pn], 0.0f, 1.0f ); const float size = SCALE( combo.fSizeSeconds, 0, s.fLastSecond[pn]-s.fFirstSecond[pn], 0.0f, 1.0f ); const float CenterPercent = start + size/2; const float CenterXPos = SCALE( CenterPercent, 0.0f, 1.0f, -width/2.0f, width/2.0f ); text->SetX( CenterXPos ); text->SetText( ssprintf("%i",combo.GetStageCnt()) ); ON_COMMAND( text ); m_Numbers.push_back( text ); this->AddChild( text ); } }
double UString::toDouble( bool tolerant ) const { double d; if (!is8Bit()) return NaN; CString str = cstring(); const char *c = str.c_str(); // skip leading white space while (isspace(*c)) c++; // empty string ? if (*c == '\0') return tolerant ? NaN : 0.0; // hex number ? if (*c == '0' && (*(c+1) == 'x' || *(c+1) == 'X')) { c++; d = 0.0; while (*(++c)) { if (*c >= '0' && *c <= '9') d = d * 16.0 + *c - '0'; else if ((*c >= 'A' && *c <= 'F') || (*c >= 'a' && *c <= 'f')) d = d * 16.0 + (*c & 0xdf) - 'A' + 10.0; else break; } } else { // regular number ? char *end; d = strtod(c, &end); if ((d != 0.0 || end != c) && d != HUGE_VAL && d != -HUGE_VAL) { c = end; } else { // infinity ? d = 1.0; if (*c == '+') c++; else if (*c == '-') { d = -1.0; c++; } if (strncmp(c, "Infinity", 8) != 0) return NaN; d = d * Inf; c += 8; } } // allow trailing white space while (isspace(*c)) c++; // don't allow anything after - unless tolerant=true if ( !tolerant && *c != '\0') d = NaN; return d; }
bool operator==(const CString& c1, const CString& c2) { size_t len = c1.size(); return len == c2.size() && (len == 0 || memcmp(c1.c_str(), c2.c_str(), len) == 0); }
void CUtils::GenerateCert(FILE* pOut, const CString& sHost) { EVP_PKEY* pKey = nullptr; X509* pCert = nullptr; X509_NAME* pName = nullptr; const int days = 365; const int years = 10; unsigned int uSeed = (unsigned int)time(nullptr); int serial = (rand_r(&uSeed) % 9999); RSA* pRSA = RSA_generate_key(2048, 0x10001, nullptr, nullptr); if ((pKey = EVP_PKEY_new())) { if (!EVP_PKEY_assign_RSA(pKey, pRSA)) { EVP_PKEY_free(pKey); return; } PEM_write_RSAPrivateKey(pOut, pRSA, nullptr, nullptr, 0, nullptr, nullptr); if (!(pCert = X509_new())) { EVP_PKEY_free(pKey); return; } X509_set_version(pCert, 2); ASN1_INTEGER_set(X509_get_serialNumber(pCert), serial); X509_gmtime_adj(X509_get_notBefore(pCert), 0); X509_gmtime_adj(X509_get_notAfter(pCert), (long)60 * 60 * 24 * days * years); X509_set_pubkey(pCert, pKey); pName = X509_get_subject_name(pCert); const char* pLogName = getenv("LOGNAME"); const char* pHostName = nullptr; if (!sHost.empty()) { pHostName = sHost.c_str(); } if (!pHostName) { pHostName = getenv("HOSTNAME"); } if (!pLogName) { pLogName = "Unknown"; } if (!pHostName) { pHostName = "host.unknown"; } CString sEmailAddr = pLogName; sEmailAddr += "@"; sEmailAddr += pHostName; X509_NAME_add_entry_by_txt(pName, "OU", MBSTRING_ASC, (unsigned char*)pLogName, -1, -1, 0); X509_NAME_add_entry_by_txt(pName, "CN", MBSTRING_ASC, (unsigned char*)pHostName, -1, -1, 0); X509_NAME_add_entry_by_txt(pName, "emailAddress", MBSTRING_ASC, (unsigned char*)sEmailAddr.c_str(), -1, -1, 0); X509_set_subject_name(pCert, pName); X509_set_issuer_name(pCert, pName); if (!X509_sign(pCert, pKey, EVP_sha256())) { X509_free(pCert); EVP_PKEY_free(pKey); return; } PEM_write_X509(pOut, pCert); X509_free(pCert); EVP_PKEY_free(pKey); fprintf(pOut, "%s", szDefaultDH2048); } }
static CString CHOICE_NAME( CString s ) { return ssprintf("Choice%s",s.c_str()); }
void OnIvr2Bin(CString strSrcFile, CString strDstFile, BOOL bForce) { CFile in, out; CString strRead; char * pRead; char * pWrite; int iOffset, iInLen, iOutLen, iLeftLen; if (!PromptOverwriteFile(strDstFile, bForce)) return; if (!in.Open(strSrcFile, CFile::modeRead)) { #ifndef __GNUC__ wprintf(_T("Can not open source file %s"), strSrcFile); #else printf("Can not open source file %s", strSrcFile.c_str()); #endif return; } if (!out.Open(strDstFile, CFile::modeCreate|CFile::modeWrite|CFile::typeBinary)) { #ifndef __GNUC__ wprintf(_T("Can not create destination file %s"), strDstFile); #else printf("Can not create destination file %s", strDstFile.c_str()); #endif in.Close(); return; } iInLen = (int)in.GetLength(); pRead = (char *)malloc(iInLen); in.Read(pRead, iInLen); pWrite = (char *)malloc(IVR_FILE_SIZE); memset(pWrite, 0, IVR_FILE_SIZE); iOffset = 0; iOutLen = 0; while (iOffset < iInLen) { iLeftLen = iInLen - iOffset; if (!iLeftLen) break; if (iLeftLen > IVR_PAGE_SIZE) { iLeftLen = IVR_PAGE_SIZE; } if ((iOutLen + iLeftLen) > IVR_FILE_SIZE) { break; } memcpy((char *)(pWrite + iOutLen), (char *)(pRead + iOffset), iLeftLen); iOutLen += FILE_HALF_PAGE_SIZE; iOffset += iLeftLen; } out.Write(pWrite, IVR_FILE_SIZE); free(pRead); free(pWrite); in.Close(); out.Close(); }
bool KSFLoader::LoadGlobalData( const CString &sPath, Song &out ) { MsdFile msd; if( !msd.ReadFile( sPath ) ) RageException::Throw( "Error opening file \"%s\": %s", sPath.c_str(), msd.GetError().c_str() ); float BPMPos2 = -1, BPM2 = -1, BPMPos3 = -1, BPM3 = -1;; for( unsigned i=0; i < msd.GetNumValues(); i++ ) { const MsdFile::value_t &sParams = msd.GetValue(i); CString sValueName = sParams[0]; // handle the data if( 0==stricmp(sValueName,"TITLE") ) LoadTags(sParams[1], out); else if( 0==stricmp(sValueName,"BPM") ) out.AddBPMSegment( BPMSegment(0, strtof(sParams[1], NULL)) ); else if( 0==stricmp(sValueName,"BPM2") ) BPM2 = strtof( sParams[1], NULL ); else if( 0==stricmp(sValueName,"BPM3") ) BPM3 = strtof( sParams[1], NULL ); else if( 0==stricmp(sValueName,"BUNKI") ) BPMPos2 = strtof( sParams[1], NULL ) / 100.0f; else if( 0==stricmp(sValueName,"BUNKI2") ) BPMPos3 = strtof( sParams[1], NULL ) / 100.0f; else if( 0==stricmp(sValueName,"STARTTIME") ) out.m_Timing.m_fBeat0OffsetInSeconds = -strtof( sParams[1], NULL )/100; else if( 0==stricmp(sValueName,"TICKCOUNT") || 0==stricmp(sValueName,"STEP") || 0==stricmp(sValueName,"DIFFICULTY")) ; /* Handled in LoadFromKSFFile; don't warn. */ else LOG->Trace( "Unexpected value named '%s'", sValueName.c_str() ); } /* This doesn't work yet: we also need to move the data around, I think, and * we should handle more than one BPM change. */ if( BPM2 > 0 && BPMPos2 > 0 ) { const float BeatsPerSecond = out.GetBPMAtBeat(0) / 60.0f; const float beat = BPMPos2 * BeatsPerSecond; LOG->Trace("BPM %f, BPS %f, BPMPos2 %f, beat %f", out.GetBPMAtBeat(0), BeatsPerSecond, BPMPos2, beat); out.AddBPMSegment( BPMSegment(beat, BPM2) ); } if( BPM3 > 0 && BPMPos3 > 0 ) { const float BeatsPerSecond = out.GetBPMAtBeat(0) / 60.0f; const float beat = BPMPos3 * BeatsPerSecond; LOG->Trace("BPM %f, BPS %f, BPMPos3 %f, beat %f", out.GetBPMAtBeat(0), BeatsPerSecond, BPMPos3, beat); out.AddBPMSegment( BPMSegment(beat, BPM3) ); } /* Try to fill in missing bits of information from the pathname. */ { CStringArray asBits; split( sPath, "/", asBits, true); ASSERT(asBits.size() > 1); LoadTags(asBits[asBits.size()-2], out); } // search for music with song in the file name CStringArray arrayPossibleMusic; GetDirListing( out.GetSongDir() + CString("song.mp3"), arrayPossibleMusic ); GetDirListing( out.GetSongDir() + CString("song.ogg"), arrayPossibleMusic ); GetDirListing( out.GetSongDir() + CString("song.wav"), arrayPossibleMusic ); if( !arrayPossibleMusic.empty() ) // we found a match out.m_sMusicFile = arrayPossibleMusic[0]; return true; }
void OnPB2Bin(CString strSrcFile, CString strDstFile, BOOL bForce) { CFile out; CStdioFile in; CString strRead; char * p; if (!PromptOverwriteFile(strDstFile, bForce)) return; if (!in.Open(strSrcFile, CFile::modeRead)) { #ifndef __GNUC__ wprintf(_T("Can not open source file %s"), strSrcFile); #else printf("Can not open source file %s", strSrcFile.c_str()); #endif return; } if (!out.Open(strDstFile, CFile::modeCreate|CFile::modeWrite)) { #ifndef __GNUC__ wprintf(_T("Can not create destination file %s"), strDstFile); #else printf("Can not create destination file %s", strDstFile.c_str()); #endif in.Close(); return; } #ifndef __GNUC__ AfxGetApp()->BeginWaitCursor(); #endif p = (char *)malloc(PHONEBOOK_FILE_SIZE); memset(p, 0, PHONEBOOK_FILE_SIZE); #ifndef __GNUC__ while (in.ReadString(strRead)) { #else while (!in.eof()) { std::getline(in, strRead); strRead.TrimRight(); #endif if (!strRead.GetLength()) { continue; } if (strRead.Left(11) == "[phonebook]") { continue; } AR168ComparePB((char *)p, strRead); } out.Write(p, PHONEBOOK_FILE_SIZE); #ifndef __GNUC__ AfxGetApp()->EndWaitCursor(); #endif free(p); in.Close(); out.Close(); } void OnBin2PB(CString strSrcFile, CString strDstFile, BOOL bForce) { CStdioFile in, out; CString cStr; char * p; if (!PromptOverwriteFile(strDstFile, bForce)) return; if (!in.Open(strSrcFile, CFile::modeRead)) { #ifndef __GNUC__ wprintf(_T("Can not open source file %s"), strSrcFile); #else printf("Can not open source file %s", strSrcFile.c_str()); #endif return; } if (!out.Open(strDstFile, CFile::modeCreate|CFile::modeWrite|CFile::typeText)) { #ifndef __GNUC__ wprintf(_T("Can not create destination file %s"), strDstFile); #else printf("Can not create destination file %s", strDstFile.c_str()); #endif in.Close(); return; } #ifndef __GNUC__ AfxGetApp()->BeginWaitCursor(); #endif p = (char *)malloc(PHONEBOOK_FILE_SIZE); in.Read(p, PHONEBOOK_FILE_SIZE); AR168ConvertPB((char *)p, cStr); out.WriteString(cStr); #ifndef __GNUC__ AfxGetApp()->EndWaitCursor(); #endif free(p); in.Close(); out.Close(); }
void Sprite::LoadFromNode( const CString& sDir, const XNode* pNode ) { retry: CString sTextureFile; CString sPath; if( pNode->GetAttrValue( "Texture", sTextureFile ) ) { sPath = sDir + sTextureFile; CollapsePath( sPath ); } if( !sPath.empty() ) { vector<CString> asElementPaths; GetDirListing( sPath + "*", asElementPaths, false, true ); if( asElementPaths.size() == 0 ) { CString sMessage = ssprintf( "The sprite file '%s' points to a texture '%s' which doesn't exist.", m_sSpritePath.c_str(), sPath.c_str() ); switch( Dialog::AbortRetryIgnore(sMessage) ) { case Dialog::abort: RageException::Throw( "Error reading value 'Texture' from %s.", m_sSpritePath.c_str() ); case Dialog::retry: goto retry; case Dialog::ignore: return; default: ASSERT(0); } } if( asElementPaths.size() > 1 ) { CString message = ssprintf( "There is more than one file that matches " "'%s'. Please remove all but one of these matches.", sPath.c_str() ); RageException::Throw( message ); } sPath = asElementPaths[0]; // Load the texture LoadFromTexture( sPath ); // Read in frames and delays from the sprite file, // overwriting the states that LoadFromTexture created. // If the .sprite file doesn't define any states, leave // frames and delays created during LoadFromTexture(). for( int i=0; true; i++ ) { CString sFrameKey = ssprintf( "Frame%04d", i ); CString sDelayKey = ssprintf( "Delay%04d", i ); State newState; if( !pNode->GetAttrValue( sFrameKey, newState.iFrameIndex ) ) break; if( newState.iFrameIndex >= m_pTexture->GetNumFrames() ) RageException::Throw( "In '%s', %s is %d, but the texture %s only has %d frames.", m_sSpritePath.c_str(), sFrameKey.c_str(), newState.iFrameIndex, sPath.c_str(), m_pTexture->GetNumFrames() ); if( !pNode->GetAttrValue( sDelayKey, newState.fDelay ) ) break; if( i == 0 ) // the ini file defines at least one frame m_States.clear(); // clear before adding m_States.push_back( newState ); } } Actor::LoadFromNode( sDir, pNode ); }
void OnCfg2Bin(CString strSrcFile, CString strDstFile, BOOL bForce) { CFile out; CStdioFile in; CString strRead; char * p; BOOL bSettings = TRUE; int iItem; if (!PromptOverwriteFile(strDstFile, bForce)) return; if (!in.Open(strSrcFile, CFile::modeRead)) { #ifndef __GNUC__ wprintf(_T("Can not open source file %s"), strSrcFile); #else printf("Can not open source file %s", strSrcFile.c_str()); #endif return; } if (!out.Open(strDstFile, CFile::modeCreate|CFile::modeWrite)) { #ifndef __GNUC__ wprintf(_T("Can not create destination file %s"), strDstFile); #else printf("Can not create destination file %s", strDstFile.c_str()); #endif in.Close(); return; } #ifndef __GNUC__ AfxGetApp()->BeginWaitCursor(); #endif p = (char *)malloc(SETTINGS_FILE_SIZE); memset(p, 0, SETTINGS_FILE_SIZE); iItem = 0; #ifndef __GNUC__ while (in.ReadString(strRead)) { #else while (!in.eof()) { std::getline(in, strRead); strRead.TrimRight(); #endif if (!strRead.GetLength()) { continue; } if (strRead.GetAt(0) == '[') { strRead.MakeLower(); if (strRead.Left(10) == "[settings]") { bSettings = TRUE; } else if (strRead.Left(10) == "[digitmap]") { bSettings = FALSE; } continue; } else if (strRead.Left(12) == "ENDOFCONFIG=") { break; } else { if (bSettings) { AR168CompareCfg((char *)p, strRead); } else { if (iItem < DIGITMAP_ENTRY_NUM) { if (AR168CompareMap((char *)(p + OPT_DIGIT_MAP), strRead, iItem)) { iItem++; } } } } } out.Write(p, SETTINGS_FILE_SIZE); #ifndef __GNUC__ AfxGetApp()->EndWaitCursor(); #endif free(p); in.Close(); out.Close(); } void OnBin2H(CString strSrcFile, CString strDstFile, BOOL bForce, int iAddressOffset, int iConvertLength) { CFile in; CStdioFile out; CString strAnswer, strName; CString strOut, strItem; TCHAR drive[_MAX_DRIVE], dir[_MAX_DIR], fname[_MAX_FNAME], ext[_MAX_EXT]; char * p; int iLength, i, j; if (!PromptOverwriteFile(strDstFile, bForce)) return; if (!in.Open(strSrcFile, CFile::modeRead)) { #ifndef __GNUC__ wprintf(_T("Can not open source file %s"), strSrcFile); #else printf("Can not open source file %s", strSrcFile.c_str()); #endif return; } if (!out.Open(strDstFile, CFile::modeCreate|CFile::modeWrite)) { #ifndef __GNUC__ wprintf(_T("Can not create destination file %s"), strDstFile); #else printf("Can not create destination file %s", strDstFile.c_str()); #endif in.Close(); return; } iLength = (int)in.GetLength(); p = (char *)malloc(iLength); in.Read(p, iLength); if (iConvertLength == 0) { iConvertLength = iLength; } #ifndef __GNUC__ _wsplitpath(strDstFile, drive, dir, fname, ext); #else strcpy(fname,basename(strDstFile)); #endif strName = fname; strName.MakeUpper(); #ifndef __GNUC__ strOut.Format(_T("#define DATA_%s_SIZE\t\t%d\n"), strName, iConvertLength); #else { char buff[511]; sprintf(buff, _T("#define DATA_%s_SIZE\t\t%d\n"), strName.c_str(), iConvertLength); strOut = buff; } #endif out.WriteString(strOut); #ifndef __GNUC__ strOut.Format(_T("const unsigned char _c_%s[DATA_%s_SIZE] = {\n"), fname, strName); #else { char buff[511]; sprintf(buff, _T("const unsigned char _c_%s[DATA_%s_SIZE] = {\n"), fname, strName.c_str()); strOut = buff; } #endif out.WriteString(strOut); for (i = iAddressOffset; i < iAddressOffset+iConvertLength; i += FRAME_LEN) { strOut = _T(""); for (j = 0; j < FRAME_LEN; j ++) { if (i+j < iAddressOffset+iConvertLength) { #ifndef __GNUC__ strItem.Format(_T("0x%02x"), (unsigned char)p[i+j]); #else { char buff[511]; sprintf(buff, _T("0x%02x"), (unsigned char)p[i+j]); strItem = buff; } #endif strOut += strItem; } if (i+j < ((iAddressOffset+iConvertLength) - 1)) { strOut += _T(", "); } } strOut += _T("\n"); out.WriteString(strOut); } #ifndef __GNUC__ strOut.Format(_T("};\n")); #else { char buff[511]; sprintf(buff, _T("};\n")); strOut = buff; } #endif out.WriteString(strOut); free(p); in.Close(); out.Close(); }
int CDaemonApp::run(int argc, char** argv) { #if SYSAPI_WIN32 // win32 instance needed for threading, etc. CArchMiscWindows::setInstanceWin32(GetModuleHandle(NULL)); #endif CArch arch; arch.init(); CLog log; CEventQueue events; bool uninstall = false; try { #if SYSAPI_WIN32 // sends debug messages to visual studio console window. log.insert(new CMSWindowsDebugOutputter()); #endif // default log level to system setting. string logLevel = arch.setting("LogLevel"); if (logLevel != "") log.setFilter(logLevel.c_str()); bool foreground = false; for (int i = 1; i < argc; ++i) { string arg(argv[i]); if (arg == "/f" || arg == "-f") { foreground = true; } #if SYSAPI_WIN32 else if (arg == "/install") { uninstall = true; arch.installDaemon(); return kExitSuccess; } else if (arg == "/uninstall") { arch.uninstallDaemon(); return kExitSuccess; } #endif else { stringstream ss; ss << "Unrecognized argument: " << arg; foregroundError(ss.str().c_str()); return kExitArgs; } } if (foreground) { // run process in foreground instead of daemonizing. // useful for debugging. mainLoop(false); } else { #if SYSAPI_WIN32 arch.daemonize("Synergy", winMainLoopStatic); #elif SYSAPI_UNIX arch.daemonize("Synergy", unixMainLoopStatic); #endif } return kExitSuccess; } catch (XArch& e) { CString message = e.what(); if (uninstall && (message.find("The service has not been started") != CString::npos)) { // TODO: if we're keeping this use error code instead (what is it?!). // HACK: this message happens intermittently, not sure where from but // it's quite misleading for the user. they thing something has gone // horribly wrong, but it's just the service manager reporting a false // positive (the service has actually shut down in most cases). } else { foregroundError(message.c_str()); } return kExitFailed; } catch (std::exception& e) { foregroundError(e.what()); return kExitFailed; } catch (...) { foregroundError("Unrecognized error."); return kExitFailed; } }
static CString getCommandLine(HWND hwnd, bool testing, bool silent) { CString cmdLine; // add constant testing args if (testing) { cmdLine += " -z --no-restart --no-daemon"; } // can't start as service on NT else if (!CArchMiscWindows::isWindows95Family()) { cmdLine += " --no-daemon"; } // get the server name CString server; bool isClient = isClientChecked(hwnd); if (isClient) { // check server name HWND child = getItem(hwnd, IDC_MAIN_CLIENT_SERVER_NAME_EDIT); server = getWindowText(child); if (!ARG->m_config.isValidScreenName(server)) { if (!silent) { showError(hwnd, CStringUtil::format( getString(IDS_INVALID_SERVER_NAME).c_str(), server.c_str())); } SetFocus(child); return CString(); } // compare server name to local host. a common error // is to provide the client's name for the server. we // don't bother to check the addresses though that'd be // more accurate. if (CStringUtil::CaselessCmp::equal(ARCH->getHostName(), server)) { if (!silent) { showError(hwnd, CStringUtil::format( getString(IDS_SERVER_IS_CLIENT).c_str(), server.c_str())); } SetFocus(child); return CString(); } } // debug level. always include this. if (true) { HWND child = getItem(hwnd, IDC_MAIN_DEBUG); int debug = (int)SendMessage(child, CB_GETCURSEL, 0, 0); // if testing then we force the debug level to be no less than // s_minTestDebug. what's the point of testing if you can't // see the debugging info? if (testing && debug < s_minTestDebug) { debug = s_minTestDebug; } cmdLine += " --debug "; cmdLine += s_debugName[debug][1]; } // add advanced options cmdLine += s_advancedOptions->getCommandLine(isClient, server); return cmdLine; }