std::string GetMediaFolder() { if (DirectoryExists("Media/")) { return GetWorkingDirectory() + std::string("/Media/"); } if (DirectoryExists("../Media")) { return GetWorkingDirectory() + std::string("/../Media/"); } throw std::runtime_error("Failed to find media folder"); }
LPCWSTR GetWorkingPath(LPWSTR buffer, size_t bufferSize, LPCWSTR relatedPath) { WCHAR dir[MAX_PATH + 1] = { 0 }; GetWorkingDirectory(dir, MAX_PATH); _snwprintf(buffer, bufferSize, L"%s%s", dir, relatedPath); return buffer; }
/* * OpenMidiFile: Open midi file for playing. * Returns 0 if successful; MCI error code otherwise. */ DWORD OpenMidiFile(LPSTR lpszMIDIFileName) { DWORD dwReturn; MCI_OPEN_PARMS mciOpenParms; //char current_dir[MAX_PATH], filename[MAX_PATH]; char current_dir[MAX_PATH]; // Seems not to work in Windows 95 sometimes without full pathname if (!GetWorkingDirectory(current_dir, MAX_PATH)) debug(("Unable to get current directory!\n")); sprintf(filename, "%s%s", current_dir, lpszMIDIFileName); debug(("music filename = %s\n", filename)); memset(&mciOpenParms, 0, sizeof(MCI_OPEN_PARMS)); mciOpenParms.lpstrDeviceType = "MPEGVideo"; mciOpenParms.lpstrElementName = filename; if (dwReturn = mciSendCommand(0, MCI_OPEN, MCI_OPEN_ELEMENT | MCI_OPEN_TYPE, (DWORD)(LPVOID) &mciOpenParms)) return dwReturn; midi_element = mciOpenParms.wDeviceID; debug(("midi element = %d\n", midi_element)); return 0; }
static int RunFile(const char * filename, bool checkOnly) { C4Group File; if (!File.Open(GetWorkingDirectory())) { fprintf(stderr, "Open failed: %s\n", File.GetError()); return 1; } // get scripts StdStrBuf fn; File.ResetSearch(); if (!File.FindNextEntry(filename, &fn)) { fprintf(stderr, "FindNextEntry failed: %s\n", File.GetError()); return 1; } InitializeC4Script(); GameScript.Load(File, fn.getData(), nullptr, nullptr); if (!checkOnly) RunLoadedC4Script(); ClearC4Script(); return ScriptEngine.errCnt; }
void Item::Execute (ICoreProxy_ptr proxy) const { auto command = GetCommand (); if (GetType () == Type::Application) { command.remove ("%c"); command.remove ("%f"); command.remove ("%F"); command.remove ("%u"); command.remove ("%U"); command.remove ("%i"); auto items = command.split (' ', QString::SkipEmptyParts); auto removePred = [] (const QString& str) { return str.size () == 2 && str.at (0) == '%'; }; items.erase (std::remove_if (items.begin (), items.end (), removePred), items.end ()); if (items.isEmpty ()) return; QProcess::startDetached (items.at (0), items.mid (1), GetWorkingDirectory ()); } else if (GetType () == Type::URL) { const auto& e = Util::MakeEntity (QUrl (command), QString (), FromUserInitiated | OnlyHandle); proxy->GetEntityManager ()->HandleEntity (e); } else { qWarning () << Q_FUNC_INFO << "don't know how to execute this type of app"; } }
status_t SVNSourceControl::GetChangeStatus(BString &out) { BString command; command << "svn status --non-interactive '" << GetWorkingDirectory() << "'"; RunCommand(command, out); return B_OK; }
FText FProvider::GetStatusText() const { FFormatNamedArguments Args; Args.Add(TEXT("ProviderName"), LOCTEXT("Mercurial", "Mercurial")); Args.Add(TEXT("YesOrNo"), IsEnabled() ? LOCTEXT("Yes", "Yes") : LOCTEXT("No", "No")); Args.Add(TEXT("LocalPath"), FText::FromString(GetWorkingDirectory())); return FText::Format( LOCTEXT("Status", "Provider: {ProviderName}\nEnabled: {YesOrNo}\nRepository: {LocalPath}"), Args ); }
status_t SVNSourceControl::GetHistory(BString &out, const char *file) { BPath path(file); if (path.InitCheck() != B_OK) return path.InitCheck(); BString command; command << "cd '" << GetWorkingDirectory() << "'; "; command << "svn log --non-interactive '" << file << "'"; RunCommand(command,out); return B_OK; }
status_t SVNSourceControl::Commit(const char *msg) { if (!msg) return B_ERROR; BString command; command << "cd '" << GetWorkingDirectory() << "'; "; command << "svn update --non-interactive; svn ci --non-interactive -m '" << msg << "'"; BString out; RunCommand(command,out); return B_OK; }
// Untested status_t SVNSourceControl::Diff(const char *filename, const char *revision) { BString command; command << "cd '" << GetWorkingDirectory() << "'; svn "; command << "diff --non-interactive '" << filename << "' "; if (revision) command << "-r " << revision; BString out; RunCommand(command, out); return B_OK; }
void QuickDebugDlg::OnButtonBrowseWD(wxCommandEvent& event) { wxUnusedVar(event); wxString ans, path(GetWorkingDirectory()); if(!wxFileName::DirExists(path)) { path = wxGetCwd(); } ans = wxDirSelector(_("Select working directory:"), path); if(!ans.empty()) { m_WD->Insert(ans, 0); m_WD->SetSelection(0); } }
void DebugCoreDumpDlg::OnButtonDebug(wxCommandEvent& event) { wxUnusedVar(event); // save values const size_t MAX_NO_ITEMS = 10; DebugCoreDumpInfo info; info.SetCoreFilepaths(ReturnWithStringPrepended(m_Core->GetStrings(), GetCore(), MAX_NO_ITEMS)); info.SetExeFilepaths(ReturnWithStringPrepended(m_ExeFilepath->GetStrings(), GetExe(), MAX_NO_ITEMS)); info.SetWDs(ReturnWithStringPrepended(m_WD->GetStrings(), GetWorkingDirectory(), MAX_NO_ITEMS)); info.SetSelectedDbg(m_choiceDebuggers->GetSelection()); EditorConfigST::Get()->WriteObject(wxT("DebugCoreDumpDlg"), &info); EndModal(wxID_OK); }
void QuickDebugDlg::OnButtonDebug(wxCommandEvent& event) { wxUnusedVar(event); // save values const size_t MAX_NO_ITEMS = 10; QuickDebugInfo info; info.SetSelectedDbg(m_choiceDebuggers->GetSelection()); info.SetExeFilepaths(ReturnWithStringPrepended(m_ExeFilepath->GetStrings(), GetExe(), MAX_NO_ITEMS)); info.SetWDs(ReturnWithStringPrepended(m_WD->GetStrings(), GetWorkingDirectory(), MAX_NO_ITEMS)); info.SetStartCmds(GetStartupCmds()); info.SetArguments(m_textCtrlArgs->GetValue()); EditorConfigST::Get()->WriteObject(wxT("QuickDebugDlg"), &info); EndModal(wxID_OK); }
//============================================================================== char* GoToDirectory( const char* DirectoryPath ) ///< path to a directory { // save current working directory char *WorkingDirectory = GetWorkingDirectory(); // go to directory int retval = chdir(DirectoryPath); if ( retval != 0 ) { free(WorkingDirectory); WorkingDirectory = NULL; } return WorkingDirectory; }
status_t SVNSourceControl::Revert(const char *relPath) { BPath path(relPath); if (path.InitCheck() != B_OK) return path.InitCheck(); BString command; command << "cd '" << GetWorkingDirectory() << "'; "; command << "svn revert --non-interactive "; if (relPath) command << " '" << relPath << "'"; BString out; RunCommand(command,out); return B_OK; }
// Returns a file path which is relative to the engine's executable string FileSystem::GetRelativeFilePath(const string& absoluteFilePath) { // create absolute paths path p = absolute(absoluteFilePath); path r = absolute(GetWorkingDirectory()); // if root paths are different, return absolute path if( p.root_path() != r.root_path()) return p.generic_string(); // initialize relative path path result; // find out where the two paths diverge path::const_iterator itr_path = p.begin(); path::const_iterator itr_relative_to = r.begin(); while( *itr_path == *itr_relative_to && itr_path != p.end() && itr_relative_to != r.end() ) { ++itr_path; ++itr_relative_to; } // add "../" for each remaining token in relative_to if( itr_relative_to != r.end() ) { ++itr_relative_to; while( itr_relative_to != r.end() ) { result /= ".."; ++itr_relative_to; } } // add remaining path while( itr_path != p.end() ) { result /= *itr_path; ++itr_path; } return result.generic_string(); }
void QuickDebugDlg::OnButtonBrowseExe(wxCommandEvent& event) { wxUnusedVar(event); wxString path, ans; wxFileName fn(GetExe()); if(fn.FileExists()) { // Use the serialised path as the wxFileSelector default path path = fn.GetPath(); } else { // Otherwise use any working dir entry, which might just have been altered path = GetWorkingDirectory(); } ans = wxFileSelector(_("Select file:"), path); if(!ans.empty()) { m_ExeFilepath->Insert(ans, 0); m_ExeFilepath->SetSelection(0); } }
//============================================================================== char* GetAbsolutePath( char* path ) ///< a path { // check we have a relative path, i.e. that starts with '/' // otherwise return the path itself if ( path[0] == '/' ) { path = StringDuplicate(path); return path; } // get working directory char *AbsolutePath = GetWorkingDirectory(); // append relative path to it StringAppend(&AbsolutePath, "/"); StringAppend(&AbsolutePath, path); return AbsolutePath; }
status_t SVNSourceControl::RemoveFromRepository(const char *path) { // File patterns are not internally supported by SVN. They have to be // expanded by bash. Meh. bool escape = true; BString pattern(path); if (pattern.FindFirst("*.") == 0 || pattern.FindFirst("*") == 0 || pattern.FindLast("*") == pattern.CountChars() - 1) escape = false; BString command; command << "cd '" << GetWorkingDirectory() << "'; "; command << "svn delete --non-interactive --keep-local "; if (escape) command << "'" << path << "'"; else command << path; BString out; RunCommand(command,out); return B_OK; }
int c4s_runfile(const char * filename) { C4Group File; if (!File.Open(GetWorkingDirectory())) { fprintf(stderr, "Open failed: %s\n", File.GetError()); return 1; } // get scripts StdStrBuf fn; File.ResetSearch(); if (!File.FindNextEntry(filename, &fn)) { fprintf(stderr, "FindNextEntry failed: %s\n", File.GetError()); return 1; } InitializeC4Script(); GameScript.Load(File, fn.getData(), NULL, NULL); RunLoadedC4Script(); return 0; }
void C4Application::ParseCommandLine(int argc, char * argv[]) { StdStrBuf CmdLine("Command line:"); for(int i = 0; i < argc; ++i) { CmdLine.Append(" "); CmdLine.Append(argv[i]); } Log(CmdLine.getData()); ClearCommandLine(); Game.NetworkActive = false; isEditor = 2; int c; while (1) { static struct option long_options[] = { // option, w/ argument?, set directly, set to... {"editor", no_argument, &isEditor, 1}, {"fullscreen", no_argument, &isEditor, 0}, {"debugwait", no_argument, &Game.DebugWait, 1}, {"update", no_argument, &CheckForUpdates, 1}, {"noruntimejoin", no_argument, &Config.Network.NoRuntimeJoin, 1}, {"runtimejoin", no_argument, &Config.Network.NoRuntimeJoin, 0}, {"noleague", no_argument, &Config.Network.LeagueServerSignUp, 0}, {"league", no_argument, &Config.Network.LeagueServerSignUp, 1}, {"nosignup", no_argument, &Config.Network.MasterServerSignUp, 0}, {"signup", no_argument, &Config.Network.MasterServerSignUp, 1}, {"debugrecread", required_argument, 0, 'K'}, {"debugrecwrite", required_argument, 0, 'w'}, {"client", required_argument, 0, 'c'}, {"host", no_argument, 0, 'h'}, {"debughost", required_argument, 0, 'H'}, {"debugpass", required_argument, 0, 'P'}, {"debug", required_argument, 0, 'D'}, {"data", required_argument, 0, 'd'}, {"startup", required_argument, 0, 's'}, {"stream", required_argument, 0, 'e'}, {"recdump", required_argument, 0, 'R'}, {"comment", required_argument, 0, 'm'}, {"pass", required_argument, 0, 'p'}, {"udpport", required_argument, 0, 'u'}, {"tcpport", required_argument, 0, 't'}, {"join", required_argument, 0, 'j'}, {"language", required_argument, 0, 'L'}, {"scenpar", required_argument, 0, 'S'}, {"observe", no_argument, 0, 'o'}, {"nonetwork", no_argument, 0, 'N'}, {"network", no_argument, 0, 'n'}, {"record", no_argument, 0, 'r'}, {"lobby", required_argument, 0, 'l'}, {"debug-opengl", no_argument, &Config.Graphics.DebugOpenGL, 1}, {0, 0, 0, 0} }; int option_index = 0; c = getopt_long (argc, argv, "abc:d:f:", long_options, &option_index); // no more options if (c == -1) break; switch (c) { case 0: // Signup if (SEqualNoCase(long_options[option_index].name, "signup")) { Game.NetworkActive = true; } // League if (SEqualNoCase(long_options[option_index].name, "league")) { Game.NetworkActive = true; Config.Network.MasterServerSignUp = true; } break; // Lobby case 'l': Game.fLobby = true; // lobby timeout specified? (e.g. --lobby=120) if (optarg) { Game.iLobbyTimeout = atoi(optarg); if (Game.iLobbyTimeout < 0) Game.iLobbyTimeout = 0; } break; case 'o': Game.fObserve = true; break; // Direct join case 'j': Game.NetworkActive = true; SCopy(optarg, Game.DirectJoinAddress, _MAX_PATH); break; case 'K': if (optarg && optarg[0]) { LogF("Reading from DebugRec file '%s'", optarg); SCopy(optarg, Config.General.DebugRecExternalFile, _MAX_PATH); } else Log("Reading DebugRec from CtrlRec file in scenario record"); Config.General.DebugRec = 1; Config.General.DebugRecWrite = 0; break; case 'w': if (optarg && optarg[0]) { LogF("Writing to DebugRec file '%s'", optarg); SCopy(optarg, Config.General.DebugRecExternalFile, _MAX_PATH); } else Log("Writing DebugRec to CtrlRec file in scenario record"); Config.General.DebugRec = 1; Config.General.DebugRecWrite = 1; break; case 'r': Game.Record = true; break; case 'n': Game.NetworkActive = true; break; case 'N': Game.NetworkActive = false; break; // Language override by parameter case 'L': SCopy(optarg, Config.General.LanguageEx, CFG_MaxString); // port overrides case 't': Config.Network.PortTCP = atoi(optarg); break; case 'u': Config.Network.PortUDP = atoi(optarg); break; // network game password case 'p': Network.SetPassword(optarg); break; // network game comment case 'm': Config.Network.Comment.CopyValidated(optarg); break; // record dump case 'R': Game.RecordDumpFile.Copy(optarg); break; // record stream case 'e': Game.RecordStream.Copy(optarg); break; // startup start screen case 's': C4Startup::SetStartScreen(optarg); break; // additional read-only data path case 'd': Reloc.AddPath(optarg); break; // debug options case 'D': Game.DebugPort = atoi(optarg); break; case 'P': Game.DebugPassword = optarg; break; case 'H': Game.DebugHost = optarg; break; // set custom scenario parameter by command line case 'S': { StdStrBuf sopt, soptval; sopt.Copy(optarg); int32_t val=1; if (sopt.SplitAtChar('=', &soptval)) val=atoi(soptval.getData()); Game.StartupScenarioParameters.SetValue(sopt.getData(), val, false); } break; // debug configs case 'h': Game.NetworkActive = true; Game.fLobby = true; Config.Network.PortTCP = 11112; Config.Network.PortUDP = 11113; Config.Network.MasterServerSignUp = Config.Network.LeagueServerSignUp = false; break; case 'c': Game.NetworkActive = true; SCopy("localhost", Game.DirectJoinAddress, _MAX_PATH); Game.fLobby = true; Config.Network.PortTCP = 11112 + 2*(atoi(optarg)+1); Config.Network.PortUDP = 11113 + 2*(atoi(optarg)+1); break; case '?': /* getopt_long already printed an error message. */ break; default: assert(!"unexpected getopt_long return value"); } } if (!Config.Network.MasterServerSignUp) Config.Network.LeagueServerSignUp = false; if (Game.fObserve || Game.fLobby) Game.NetworkActive = true; while (optind < argc) { char * szParameter = argv[optind++]; { // Strip trailing / that result from tab-completing unpacked c4groups int iLen = SLen(szParameter); if (iLen > 5 && szParameter[iLen-1] == '/' && szParameter[iLen-5] == '.' && szParameter[iLen-4] == 'o' && szParameter[iLen-3] == 'c') { szParameter[iLen-1] = '\0'; } } // Scenario file if (SEqualNoCase(GetExtension(szParameter),"ocs")) { if(IsGlobalPath(szParameter)) Game.SetScenarioFilename(szParameter); else Game.SetScenarioFilename((std::string(GetWorkingDirectory()) + DirSep + szParameter).c_str()); continue; } if (SEqualNoCase(GetFilename(szParameter),"scenario.txt")) { Game.SetScenarioFilename(szParameter); continue; } // Player file if (SEqualNoCase(GetExtension(szParameter),"ocp")) { if(IsGlobalPath(szParameter)) SAddModule(Game.PlayerFilenames, szParameter); else SAddModule(Game.PlayerFilenames, (std::string(GetWorkingDirectory()) + DirSep + szParameter).c_str()); continue; } // Definition file if (SEqualNoCase(GetExtension(szParameter),"ocd")) { SAddModule(Game.DefinitionFilenames,szParameter); continue; } // Key file if (SEqualNoCase(GetExtension(szParameter),"c4k")) { Application.IncomingKeyfile.Copy(szParameter); continue; } // Update file if (SEqualNoCase(GetExtension(szParameter),"ocu")) { Application.IncomingUpdate.Copy(szParameter); continue; } // record stream if (SEqualNoCase(GetExtension(szParameter),"c4r")) { Game.RecordStream.Copy(szParameter); } // Direct join by URL if (SEqual2NoCase(szParameter, "clonk:")) { // Store address SCopy(szParameter + 6, Game.DirectJoinAddress, _MAX_PATH); SClearFrontBack(Game.DirectJoinAddress, '/'); // Special case: if the target address is "update" then this is used for update initiation by url if (SEqualNoCase(Game.DirectJoinAddress, "update")) { Application.CheckForUpdates = true; Game.DirectJoinAddress[0] = 0; continue; } // Self-enable network Game.NetworkActive = true; continue; } } #ifdef _WIN32 // Clean up some forward/backward slach confusion since many internal OC file functions cannot handle both SReplaceChar(Game.ScenarioFilename, AltDirectorySeparator, DirectorySeparator); SReplaceChar(Game.PlayerFilenames, AltDirectorySeparator, DirectorySeparator); SReplaceChar(Game.DefinitionFilenames, AltDirectorySeparator, DirectorySeparator); Application.IncomingKeyfile.ReplaceChar(AltDirectorySeparator, DirectorySeparator); Application.IncomingUpdate.ReplaceChar(AltDirectorySeparator, DirectorySeparator); Game.RecordStream.ReplaceChar(AltDirectorySeparator, DirectorySeparator); #endif // Default to editor if scenario given, player mode otherwise if (isEditor == 2) isEditor = !!*Game.ScenarioFilename && !Config.General.OpenScenarioInGameMode; // record? Game.Record = Game.Record || (Config.Network.LeagueServerSignUp && Game.NetworkActive); // startup dialog required? QuitAfterGame = !isEditor && Game.HasScenario(); }
/* This function loads the newlib footprints into the Library. * It examines all directories pointed to by Settings.LibraryTree. * In each directory specified there, it looks both in that directory, * as well as *one* level down. It calls the subfunction * LoadNewlibFootprintsFromDir to put the footprints into PCB's internal * datastructures. */ static int ParseLibraryTree (void) { char toppath[MAXPATHLEN + 1]; /* String holding abs path to top level library dir */ char working[MAXPATHLEN + 1]; /* String holding abs path to working dir */ char *libpaths; /* String holding list of library paths to search */ char *p; /* Helper string used in iteration */ DIR *dirobj; /* Iterable directory object */ struct dirent *direntry = NULL; /* Object holding individual directory entries */ struct stat buffer; /* buffer used in stat */ int n_footprints = 0; /* Running count of footprints found */ /* Initialize path, working by writing 0 into every byte. */ memset (toppath, 0, sizeof toppath); memset (working, 0, sizeof working); /* Save the current working directory as an absolute path. * This fcn writes the abs path into the memory pointed to by the input arg. */ if (GetWorkingDirectory (working) == NULL) { Message (_("ParseLibraryTree: Could not determine initial working directory\n")); return 0; } /* Additional loop to allow for multiple 'newlib' style library directories * called out in Settings.LibraryTree */ libpaths = strdup (Settings.LibraryTree); for (p = strtok (libpaths, PCB_PATH_DELIMETER); p && *p; p = strtok (NULL, PCB_PATH_DELIMETER)) { /* remove trailing path delimeter */ strncpy (toppath, p, sizeof (toppath) - 1); /* start out in the working directory in case the path is a * relative path */ if (chdir (working)) { ChdirErrorMessage (working); free (libpaths); return 0; } /* * Next change to the directory which is the top of the library tree * and extract its abs path. */ if (chdir (toppath)) { ChdirErrorMessage (toppath); continue; } if (GetWorkingDirectory (toppath) == NULL) { Message (_("ParseLibraryTree: Could not determine new working directory\n")); continue; } #ifdef DEBUG printf("In ParseLibraryTree, looking for newlib footprints inside top level directory %s ... \n", toppath); #endif /* Next read in any footprints in the top level dir */ n_footprints += LoadNewlibFootprintsFromDir("(local)", toppath); /* Then open this dir so we can loop over its contents. */ if ((dirobj = opendir (toppath)) == NULL) { OpendirErrorMessage (toppath); continue; } /* Now loop over files in this directory looking for subdirs. * For each direntry which is a valid subdirectory, * try to load newlib footprints inside it. */ while ((direntry = readdir (dirobj)) != NULL) { #ifdef DEBUG printf("In ParseLibraryTree loop examining 2nd level direntry %s ... \n", direntry->d_name); #endif /* Find subdirectories. Ignore entries beginning with "." and CVS * directories. */ if (!stat (direntry->d_name, &buffer) && S_ISDIR (buffer.st_mode) && direntry->d_name[0] != '.' && NSTRCMP (direntry->d_name, "CVS") != 0) { /* Found a valid subdirectory. Try to load footprints from it. */ n_footprints += LoadNewlibFootprintsFromDir(direntry->d_name, toppath); } } closedir (dirobj); } /* restore the original working directory */ if (chdir (working)) ChdirErrorMessage (working); #ifdef DEBUG printf("Leaving ParseLibraryTree, found %d footprints.\n", n_footprints); #endif free (libpaths); return n_footprints; }
/* This is a helper function for ParseLibrary Tree. Given a char *path, * it finds all newlib footprints in that dir and sticks them into the * library menu structure named entry. */ static int LoadNewlibFootprintsFromDir(char *libpath, char *toppath) { char olddir[MAXPATHLEN + 1]; /* The directory we start out in (cwd) */ char subdir[MAXPATHLEN + 1]; /* The directory holding footprints to load */ DIR *subdirobj; /* Interable object holding all subdir entries */ struct dirent *subdirentry; /* Individual subdir entry */ struct stat buffer; /* Buffer used in stat */ LibraryMenuType *menu = NULL; /* Pointer to PCB's library menu structure */ LibraryEntryType *entry; /* Pointer to individual menu entry */ size_t l; size_t len; int n_footprints = 0; /* Running count of footprints found in this subdir */ /* Cache old dir, then cd into subdir because stat is given relative file names. */ memset (subdir, 0, sizeof subdir); memset (olddir, 0, sizeof olddir); if (GetWorkingDirectory (olddir) == NULL) { Message (_("LoadNewlibFootprintsFromDir: Could not determine initial working directory\n")); return 0; } if (strcmp (libpath, "(local)") == 0) strcpy (subdir, "."); else strcpy (subdir, libpath); if (chdir (subdir)) { ChdirErrorMessage (subdir); return 0; } /* Determine subdir is abs path */ if (GetWorkingDirectory (subdir) == NULL) { Message (_("LoadNewlibFootprintsFromDir: Could not determine new working directory\n")); if (chdir (olddir)) ChdirErrorMessage (olddir); return 0; } /* First try opening the directory specified by path */ if ( (subdirobj = opendir (subdir)) == NULL ) { OpendirErrorMessage (subdir); if (chdir (olddir)) ChdirErrorMessage (olddir); return 0; } /* Get pointer to memory holding menu */ menu = GetLibraryMenuMemory (&Library); /* Populate menuname and path vars */ menu->Name = strdup (pcb_basename(subdir)); menu->directory = strdup (pcb_basename(toppath)); /* Now loop over files in this directory looking for files. * We ignore certain files which are not footprints. */ while ((subdirentry = readdir (subdirobj)) != NULL) { #ifdef DEBUG /* printf("... Examining file %s ... \n", subdirentry->d_name); */ #endif /* Ignore non-footprint files found in this directory * We're skipping .png and .html because those * may exist in a library tree to provide an html browsable * index of the library. */ l = strlen (subdirentry->d_name); if (!stat (subdirentry->d_name, &buffer) && S_ISREG (buffer.st_mode) && subdirentry->d_name[0] != '.' && NSTRCMP (subdirentry->d_name, "CVS") != 0 && NSTRCMP (subdirentry->d_name, "Makefile") != 0 && NSTRCMP (subdirentry->d_name, "Makefile.am") != 0 && NSTRCMP (subdirentry->d_name, "Makefile.in") != 0 && (l < 4 || NSTRCMP(subdirentry->d_name + (l - 4), ".png") != 0) && (l < 5 || NSTRCMP(subdirentry->d_name + (l - 5), ".html") != 0) && (l < 4 || NSTRCMP(subdirentry->d_name + (l - 4), ".pcb") != 0) ) { #ifdef DEBUG /* printf("... Found a footprint %s ... \n", subdirentry->d_name); */ #endif n_footprints++; entry = GetLibraryEntryMemory (menu); /* * entry->AllocatedMemory points to abs path to the footprint. * entry->ListEntry points to fp name itself. */ len = strlen(subdir) + strlen("/") + strlen(subdirentry->d_name) + 1; entry->AllocatedMemory = (char *)calloc (1, len); strcat (entry->AllocatedMemory, subdir); strcat (entry->AllocatedMemory, PCB_DIR_SEPARATOR_S); /* store pointer to start of footprint name */ entry->ListEntry = entry->AllocatedMemory + strlen (entry->AllocatedMemory); /* Now place footprint name into AllocatedMemory */ strcat (entry->AllocatedMemory, subdirentry->d_name); /* mark as directory tree (newlib) library */ entry->Template = (char *) -1; } } /* Done. Clean up, cd back into old dir, and return */ closedir (subdirobj); if (chdir (olddir)) ChdirErrorMessage (olddir); return n_footprints; }
BOOL CALLBACK PreferencesDialogProc(HWND hDlg, UINT message, UINT wParam, LONG lParam) { static HWND hBrowser; static Bool browser_changed; Bool toolbar_changed, lagbox_changed, temp; CommSettings *comm = &config.comm; OPENFILENAME ofn; static char *dir; // Working directory before dialog (OpenFile may change it) int new_val; switch (message) { case WM_INITDIALOG: CenterWindow(hDlg, GetParent(hDlg)); if (hPreferencesDialog != NULL) { EndDialog(hDlg, IDCANCEL); return FALSE; } hPreferencesDialog = hDlg; hBrowser = GetDlgItem(hDlg, IDC_BROWSER); Edit_LimitText(hBrowser, MAX_PATH); SetWindowFont(hBrowser, GetFont(FONT_INPUT), FALSE); SetWindowText(hBrowser, config.browser); CheckDlgButton(hDlg, IDC_SCROLLLOCK, config.scroll_lock); CheckDlgButton(hDlg, IDC_DRAWNAMES, config.draw_names); CheckDlgButton(hDlg, IDC_TOOLTIPS, config.tooltips); CheckDlgButton(hDlg, IDC_PAIN, config.pain); CheckDlgButton(hDlg, IDC_INVNUM, config.inventory_num); CheckDlgButton(hDlg, IDC_SAFETY, config.aggressive); CheckDlgButton(hDlg, IDC_BOUNCE, config.bounce); CheckDlgButton(hDlg, IDC_TOOLBAR, config.toolbar); CheckDlgButton(hDlg, IDS_LATENCY0, config.lagbox); CheckDlgButton(hDlg, IDC_PROFANE, config.antiprofane); CheckDlgButton(hDlg, IDC_DRAWMAP, config.drawmap); CheckDlgButton(hDlg, IDC_MAP_ANNOTATIONS, config.map_annotations); CheckDlgButton(hDlg, IDC_MUSIC, config.play_music); CheckDlgButton(hDlg, IDC_SOUNDFX, config.play_sound); CheckDlgButton(hDlg, IDC_LOOPSOUNDS, config.play_loop_sounds); CheckDlgButton(hDlg, IDC_RANDSOUNDS, config.play_random_sounds); EnableWindow(GetDlgItem(hDlg, IDC_LOOPSOUNDS), IsDlgButtonChecked(hDlg, IDC_SOUNDFX)); EnableWindow(GetDlgItem(hDlg, IDC_RANDSOUNDS), IsDlgButtonChecked(hDlg, IDC_SOUNDFX)); CheckRadioButton(hDlg, IDC_TARGETHALO1, IDC_TARGETHALO3, config.halocolor + IDC_TARGETHALO1); CheckDlgButton(hDlg, IDC_COLORCODES, config.colorcodes); Trackbar_SetRange(GetDlgItem(hDlg, IDC_SOUND_VOLUME), 0, CONFIG_MAX_VOLUME, FALSE); Trackbar_SetRange(GetDlgItem(hDlg, IDC_MUSIC_VOLUME), 0, CONFIG_MAX_VOLUME, FALSE); Trackbar_SetPos(GetDlgItem(hDlg, IDC_SOUND_VOLUME), config.sound_volume); Trackbar_SetPos(GetDlgItem(hDlg, IDC_MUSIC_VOLUME), config.music_volume); dir = (char *) SafeMalloc(MAX_PATH + 1); GetWorkingDirectory(dir, MAX_PATH); browser_changed = False; return TRUE; case WM_COMMAND: switch(GET_WM_COMMAND_ID(wParam, lParam)) { case IDC_BROWSER: if (GET_WM_COMMAND_CMD(wParam, lParam) != EN_CHANGE) break; browser_changed = True; return TRUE; case IDC_FIND: memset(&ofn, 0, sizeof(OPENFILENAME)); ofn.lStructSize = sizeof(OPENFILENAME); ofn.hwndOwner = hDlg; ofn.lpstrFilter = EXE_filter; ofn.lpstrFile = config.browser; ofn.nMaxFile = MAX_PATH; ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY; if (GetOpenFileName(&ofn)) { SetWindowText(hBrowser, config.browser); browser_changed = True; } else debug(("GetOpenFileName failed, error = %d\n", CommDlgExtendedError())); return TRUE; case IDCANCEL: EndDialog(hDlg, IDCANCEL); return TRUE; case IDC_SOUNDFX: EnableWindow(GetDlgItem(hDlg, IDC_LOOPSOUNDS), IsDlgButtonChecked(hDlg, IDC_SOUNDFX)); EnableWindow(GetDlgItem(hDlg, IDC_RANDSOUNDS), IsDlgButtonChecked(hDlg, IDC_SOUNDFX)); return TRUE; case IDC_PROFANESETTINGS: if (IDOK == DialogBox(hInst, MAKEINTRESOURCE(IDC_PROFANESETTINGS), hDlg, ProfanityDialogProc)) CheckDlgButton(hDlg, IDC_PROFANE, TRUE); return TRUE; case IDOK: Edit_GetText(hBrowser, config.browser, MAX_PATH); if (browser_changed) config.default_browser = False; config.scroll_lock = IsDlgButtonChecked(hDlg, IDC_SCROLLLOCK); config.draw_names = IsDlgButtonChecked(hDlg, IDC_DRAWNAMES); config.tooltips = IsDlgButtonChecked(hDlg, IDC_TOOLTIPS); config.pain = IsDlgButtonChecked(hDlg, IDC_PAIN); config.inventory_num = IsDlgButtonChecked(hDlg, IDC_INVNUM); config.aggressive = IsDlgButtonChecked(hDlg, IDC_SAFETY); config.bounce = IsDlgButtonChecked(hDlg, IDC_BOUNCE); config.antiprofane = IsDlgButtonChecked(hDlg, IDC_PROFANE); config.drawmap = IsDlgButtonChecked(hDlg, IDC_DRAWMAP); config.map_annotations = IsDlgButtonChecked(hDlg, IDC_MAP_ANNOTATIONS); temp = IsDlgButtonChecked(hDlg, IDC_TOOLBAR); toolbar_changed = (temp != config.toolbar); config.toolbar = temp; temp = IsDlgButtonChecked(hDlg, IDS_LATENCY0); lagbox_changed = (temp != config.lagbox); config.lagbox = temp; if (IsDlgButtonChecked(hDlg, IDC_MUSIC) != config.play_music) UserToggleMusic(config.play_music); config.play_music = IsDlgButtonChecked(hDlg, IDC_MUSIC); config.play_sound = IsDlgButtonChecked(hDlg, IDC_SOUNDFX); config.play_loop_sounds = IsDlgButtonChecked(hDlg, IDC_LOOPSOUNDS); config.play_random_sounds = IsDlgButtonChecked(hDlg, IDC_RANDSOUNDS); if (!config.play_sound) SoundAbort(); new_val = Trackbar_GetPos(GetDlgItem(hDlg, IDC_MUSIC_VOLUME)); if (new_val != config.music_volume) { config.music_volume = new_val; ResetMusicVolume(); } // Don't need to dynamically update sound volume, because // looping sounds are updated as player moves around. config.sound_volume = Trackbar_GetPos(GetDlgItem(hDlg, IDC_SOUND_VOLUME)); if( IsDlgButtonChecked( hDlg, IDC_TARGETHALO1 ) == BST_CHECKED ) config.halocolor = 0; else if( IsDlgButtonChecked( hDlg, IDC_TARGETHALO2 ) == BST_CHECKED ) config.halocolor = 1; else config.halocolor = 2; config.colorcodes = IsDlgButtonChecked(hDlg, IDC_COLORCODES); // Redraw main window to reflect new settings if (toolbar_changed || lagbox_changed) { ResizeAll(); } else { InvalidateRect(hMain, NULL, TRUE); RedrawAll(); } EditBoxSetNormalFormat(); EndDialog(hDlg, IDOK); return TRUE; } break; case WM_DESTROY: // Restore working drive and directory if (chdir(dir) != 0) debug(("chdir failed to %s\n", dir)); SafeFree(dir); hPreferencesDialog = NULL; return TRUE; } return FALSE; }
BOOL CBitmapControl::LoadBitmapResource(void) { BOOL fResult = TRUE; if (m_pDDB == NULL) { fResult = FALSE; CString csName; CString csFileName; CString csFullName; TRY { // Get the resource name from the window title. GetWindowText(csName); CWindowDC dcWindow(this); /* See if we need to split the name from "resource;filename". */ int nIndex = csName.Find(';'); if (nIndex != -1) { /* We have a split point. Split it. */ csFileName = csName.Mid(nIndex+1); csName = csName.Left(nIndex); /* Construct the full filename using the working directory. */ LPCSTR pszWorkingDirectory = GetWorkingDirectory(); if (pszWorkingDirectory == NULL) { /* No working directory. Take it as is. */ csFullName = csFileName; } else { /* Construct it. */ Util::ConstructPath(csFullName, pszWorkingDirectory, csFileName); } /* Create the DDB using this file name. */ m_pDDB = new CDDB(csFullName, dcWindow.GetSafeHdc(), TRUE); /* If we failed, delete the created DDB. */ if (m_pDDB != NULL && !m_pDDB->IsValid()) { delete m_pDDB; m_pDDB = NULL; } } /* If we don't have a DDB yet, try and get one from the resource. */ if (m_pDDB == NULL) { m_pDDB = new CDDB( AfxGetInstanceHandle(), csName, RT_BITMAP, dcWindow.GetSafeHdc(), TRUE); } if ((m_pDDB != NULL) && (m_pDDB->IsValid())) { // Get size of bitmap. BITMAP Bitmap; if (CBitmap::FromHandle(m_pDDB->GetBitmap())->GetObject(sizeof(Bitmap), &Bitmap) != 0) { m_nBitmapWidth = Bitmap.bmWidth; m_nBitmapHeight = Bitmap.bmHeight; fResult = TRUE; } } } END_TRY }
/* This function loads the newlib footprints into the Library. * It examines all directories pointed to by Settings.LibraryTree. * It calls the subfunction LoadNewlibFootprintsFromDir to put the * footprints into PCB's internal datastructures. */ static int ParseLibraryTree (void) { char toppath[MAXPATHLEN + 1]; /* String holding abs path to top level library dir */ char working[MAXPATHLEN + 1]; /* String holding abs path to working dir */ char *libpaths; /* String holding list of library paths to search */ char *p; /* Helper string used in iteration */ int n_footprints = 0; /* Running count of footprints found */ /* Initialize path, working by writing 0 into every byte. */ memset (toppath, 0, sizeof toppath); memset (working, 0, sizeof working); /* Save the current working directory as an absolute path. * This fcn writes the abs path into the memory pointed to by the input arg. */ if (GetWorkingDirectory (working) == NULL) { Message (_("ParseLibraryTree: Could not determine initial working directory\n")); return 0; } /* Additional loop to allow for multiple 'newlib' style library directories * called out in Settings.LibraryTree */ libpaths = strdup (Settings.LibraryTree); for (p = strtok (libpaths, PCB_PATH_DELIMETER); p && *p; p = strtok (NULL, PCB_PATH_DELIMETER)) { /* remove trailing path delimeter */ strncpy (toppath, p, sizeof (toppath) - 1); /* start out in the working directory in case the path is a * relative path */ if (chdir (working)) { ChdirErrorMessage (working); free (libpaths); return 0; } /* * Next change to the directory which is the top of the library tree * and extract its abs path. */ if (chdir (toppath)) { ChdirErrorMessage (toppath); continue; } if (GetWorkingDirectory (toppath) == NULL) { Message (_("ParseLibraryTree: Could not determine new working directory\n")); continue; } #ifdef DEBUG printf("In ParseLibraryTree, looking for newlib footprints inside top level directory %s ... \n", toppath); #endif /* Next read in any footprints in the top level dir and below */ n_footprints += LoadNewlibFootprintsFromDir("(local)", toppath, *p == '/'); } /* restore the original working directory */ if (chdir (working)) ChdirErrorMessage (working); #ifdef DEBUG printf("Leaving ParseLibraryTree, found %d footprints.\n", n_footprints); #endif free (libpaths); return n_footprints; }
bool SessionImpl::FindFileInternal (/*[in]*/ const char * lpszFileName, /*[in]*/ const PathNameArray & directoryPatterns, /*[in]*/ bool firstMatchOnly, /*[in]*/ bool useFndb, /*[in]*/ bool searchFileSystem, /*[out]*/ vector<PathName> & result) { AutoTraceTime att ("find file", lpszFileName); MIKTEX_ASSERT (useFndb || searchFileSystem); bool found = false; // if a fully qualified path name is given, then don't look out any // further if (Utils::IsAbsolutePath(lpszFileName)) { PathName path (lpszFileName); found = CheckCandidate(path, 0); if (found) { result.push_back (path); } return (found); } // if an explicitly relative path name is given, then don't look out // any further if (IsExplicitlyRelativePath(lpszFileName)) { PathName pathWD; for (unsigned idx = 0; ! (found && firstMatchOnly) && GetWorkingDirectory(idx, pathWD); ++ idx) { PathName path (pathWD); path += lpszFileName; path.MakeAbsolute (); if (CheckCandidate(path, 0)) { found = true; #if FIND_FILE_PREFER_RELATIVE_PATH_NAMES // 2015-01-15 if (idx == 0) { MIKTEX_ASSERT(PathName::Compare(pathWD, PathName().SetToCurrentDirectory()) == 0); path = lpszFileName; } #endif result.push_back (path); } } return (found); } // make use of the file name database if (useFndb) { for (PathNameArray::const_iterator it = directoryPatterns.begin(); ! (found && firstMatchOnly) && it != directoryPatterns.end(); ++ it) { if (found && ! firstMatchOnly && IsMpmFile(it->Get())) { // don't trigger the package installer continue; } FileNameDatabase * pFndb = GetFileNameDatabase(it->Get()); if (pFndb != 0) { // search fndb AutoFndbRelease autoRelease (pFndb); vector<PathName> paths; vector<string> fileNameInfo; bool foundInFndb = pFndb->Search(lpszFileName, it->Get(), firstMatchOnly, paths, fileNameInfo); // we must release the FNDB handle since CheckCandidate() might request an unload of the FNDB autoRelease.Reset (); if (foundInFndb) { for (int idx = 0; idx < paths.size(); ++ idx) { if (CheckCandidate(paths[idx], fileNameInfo[idx].c_str())) { found = true; result.push_back (paths[idx]); } } } } else { // search the file system because the file name database does not exist vector<PathName> paths; if (SearchFileSystem(lpszFileName, it->Get(), firstMatchOnly, paths)) { found = true; result.insert (result.end(), paths.begin(), paths.end()); } } } } if (found || ! searchFileSystem) { return (found); } // search the file system for (PathNameArray::const_iterator it = directoryPatterns.begin(); ! (found && firstMatchOnly) && it != directoryPatterns.end(); ++ it) { if (found && ! firstMatchOnly && IsMpmFile(it->Get())) { // don't search the virtual MPM directory tree continue; } FileNameDatabase * pFndb = GetFileNameDatabase(it->Get()); if (pFndb == 0) { // fndb does not exist => we already searched the file system (see above) continue; } pFndb->Release (); vector<PathName> paths; if (SearchFileSystem(lpszFileName, it->Get(), firstMatchOnly, paths)) { found = true; result.insert (result.end(), paths.begin(), paths.end()); } } return (found); }
/* * GetGamePath: Get pathname to game directory (including trailing \\ ) from registry and return it -- AJM. * Defaults to current directory if not found. Does not currently set registry. */ void GetGamePath( char *szGamePath ) { if (!GetWorkingDirectory(szGamePath, MAX_PATH)) debug(("Unable to get current directory!\n")); }
char *getwd(char *buf) { GetWorkingDirectory(buf); return buf; }
ECommandResult::Type FProvider::Execute( const TSharedRef<ISourceControlOperation, ESPMode::ThreadSafe>& InOperation, const TArray<FString>& InFiles, EConcurrency::Type InConcurrency, const FSourceControlOperationComplete& InOperationCompleteDelegate ) { // the "Connect" operation is the only operation that can be performed while the // provider is disabled, if the operation is successful the provider will be enabled if (!IsEnabled() && (InOperation->GetName() != OperationNames::Connect)) { return ECommandResult::Failed; } // attempt to create a worker to perform the requested operation FWorkerPtr WorkerPtr = CreateWorker(InOperation->GetName()); if (!WorkerPtr.IsValid()) { // apparently we don't support this particular operation FFormatNamedArguments Arguments; Arguments.Add(TEXT("OperationName"), FText::FromName(InOperation->GetName())); Arguments.Add(TEXT("ProviderName"), FText::FromName(GetName())); LogError( FText::Format( LOCTEXT( "UnsupportedOperation", "Operation '{OperationName}' not supported by source control provider '{ProviderName}'" ), Arguments ) ); return ECommandResult::Failed; } auto* Command = new FCommand( GetWorkingDirectory(), AbsoluteContentDirectory, InOperation, WorkerPtr.ToSharedRef(), InOperationCompleteDelegate ); TArray<FString> AbsoluteFiles; if (InOperation->GetName() == OperationNames::Connect) { AbsoluteFiles.Add(Settings.GetMercurialPath()); } else if (InOperation->GetName() == OperationNames::MarkForAdd) { TArray<FString> AbsoluteLargeFiles; PrepareFilenamesForAddCommand(InFiles, AbsoluteFiles, AbsoluteLargeFiles); if (AbsoluteLargeFiles.Num() > 0) { Command->SetAbsoluteLargeFiles(AbsoluteLargeFiles); } } else { for (const auto& Filename : InFiles) { AbsoluteFiles.Add(FPaths::ConvertRelativePathToFull(Filename)); } } if (AbsoluteFiles.Num() > 0) { Command->SetAbsoluteFiles(AbsoluteFiles); } if (InConcurrency == EConcurrency::Synchronous) { auto Result = ExecuteSynchronousCommand(Command, InOperation->GetInProgressString()); delete Command; return Result; } else { return ExecuteCommand(Command, true); } }