std::string Shell::absPath(std::string path) { if(path.size() < 1) return ""; std::string tpath; size_t start = 0, end = 0; if(path == "..") { tpath = parentPath(basePath); return tpath; } if(path == ".") return basePath; if(path == "/") return "/"; if(path[0] == '/') { start = 1; tpath = ""; } else if(basePath == "/") tpath = ""; else tpath = basePath; for(end = start; end < path.size(); ++end) { if(path[end] == '/') { if(start == end) tpath = ""; else if(end - start == 2 && path[start] == '.' && path[start + 1] == '.') tpath = parentPath(tpath); else if(end - start == 1 && path[start] == '.'); else { tpath += '/'; tpath += path.substr(start, end - start); } start = end + 1; } } if(path[path.size() - 1] != '/') { tpath += '/'; tpath += path.substr(start, path.size() - start); } return tpath; }
std::string ZLDir::itemPath(const std::string &itemName) const { if (itemName == "..") { return parentPath(); } else { return isRoot() ? myPath + itemName : myPath + delimiter() + itemName; } }
bool FilesPageHandler::listDirectory(Common::String path, Common::String &content, const Common::String &itemTemplate) { if (path == "" || path == "/") { if (ConfMan.hasKey("rootpath", "cloud")) addItem(content, itemTemplate, IT_DIRECTORY, "/root/", _("File system root")); addItem(content, itemTemplate, IT_DIRECTORY, "/saves/", _("Saved games")); return true; } if (HandlerUtils::hasForbiddenCombinations(path)) return false; Common::String prefixToRemove = "", prefixToAdd = ""; if (!transformPath(path, prefixToRemove, prefixToAdd)) return false; Common::FSNode node = Common::FSNode(path); if (path == "/") node = node.getParent(); // absolute root if (!HandlerUtils::permittedPath(node.getPath())) return false; if (!node.isDirectory()) return false; // list directory Common::FSList _nodeContent; if (!node.getChildren(_nodeContent, Common::FSNode::kListAll, false)) // do not show hidden files _nodeContent.clear(); else Common::sort(_nodeContent.begin(), _nodeContent.end()); // add parent directory link { Common::String filePath = path; if (filePath.hasPrefix(prefixToRemove)) filePath.erase(0, prefixToRemove.size()); if (filePath == "" || filePath == "/" || filePath == "\\") filePath = "/"; else filePath = parentPath(prefixToAdd + filePath); addItem(content, itemTemplate, IT_PARENT_DIRECTORY, filePath, _("Parent directory")); } // fill the content for (Common::FSList::iterator i = _nodeContent.begin(); i != _nodeContent.end(); ++i) { Common::String name = i->getDisplayName(); if (i->isDirectory()) name += "/"; Common::String filePath = i->getPath(); if (filePath.hasPrefix(prefixToRemove)) filePath.erase(0, prefixToRemove.size()); filePath = prefixToAdd + filePath; addItem(content, itemTemplate, detectType(i->isDirectory(), name), filePath, name); } return true; }
pugi::xml_node Config::buildXmlNode(pugi::xml_node& rootNode, const UnicodeString& path) const { unsigned int indexOfSlash = path.lastIndexOf('/'); UnicodeString parentPath(path, 0, indexOfSlash); UnicodeString selfName(path, indexOfSlash + 1); //LOGARG_DEBUG(LOGTYPE_MAIN, "buildxmlnode parentPath: %s selfName: %s", StringConverter::toUtf8String(parentPath).c_str(), StringConverter::toUtf8String(selfName).c_str()); pugi::xml_node parentNode; if (indexOfSlash == 0) { parentNode = rootNode; } if (!parentNode) { std::string utf8ParentPath = StringConverter::toUtf8String(parentPath); parentNode = rootNode.first_element_by_path(utf8ParentPath.c_str(), '/'); } if (!parentNode) { parentNode = buildXmlNode(rootNode, parentPath); } pugi::xml_node ret = parentNode.append_child(pugi::node_element); ret.set_name(StringConverter::toUtf8String(selfName).c_str()); return ret; }
/*! * Adds the necessary paths to the file system watcher * \param filePath Path (including name) of the file to watch. * \param watcher The file system watcher. */ static void addPathsToWatcher(const QString &filePath, QScopedPointer<QFileSystemWatcher>& watcher) { QFileInfo fileInfo(filePath); QString directory; bool fileExists = fileInfo.exists(); if (fileExists) { // If the file exists, we can take the canonical path directly directory = fileInfo.canonicalPath(); } else { // If the file doesn't exist, canonicalPath would return an empty string. That's why // we need to get the parent directory first. QFileInfo parentPath(fileInfo.absolutePath()); if (parentPath.exists()) { directory = parentPath.canonicalFilePath(); } } if (!directory.isEmpty()) { // Watch the directory if it's not being watched yet if (!watcher->directories().contains(directory)) { watcher->addPath(directory); } } // Watch the file itself if it's not being watched yet if (fileExists && !watcher->files().contains(filePath)) { watcher->addPath(filePath); } }
const Env::file_path Env::rootPath() const { Env::file_path parentPath("."); std::size_t pos; pos = server.confPath.rfind('/'); if (pos != std::string::npos) parentPath = server.confPath.substr(0, pos); return (parentPath); }
std::string getBootstrap() { std::string modulePath(BrowserManager::Instance()->GetModulePath()); std::string parentPath(modulePath.substr(0, modulePath.find_last_of('/') + 1)); #ifdef _WIN32 return parentPath + "/cef-bootstrap.exe"; #else return parentPath + "/cef-bootstrap"; #endif }
String extractPath(const String& path) { try { boost::filesystem::wpath parentPath(path.c_str()); return parentPath.parent_path().wstring().c_str(); } catch (...) { return path; } }
CString topLevelPath() { if (const char* topLevelDirectory = g_getenv("WEBKIT_TOP_LEVEL")) return topLevelDirectory; // If the environment variable wasn't provided then assume we were built into // WebKitBuild/Debug or WebKitBuild/Release. Obviously this will fail if the build // directory is non-standard, but we can't do much more about this. GUniquePtr<char> parentPath(g_path_get_dirname(getCurrentExecutablePath().data())); GUniquePtr<char> layoutTestsPath(g_build_filename(parentPath.get(), "..", "..", "..", nullptr)); GUniquePtr<char> absoluteTopLevelPath(realpath(layoutTestsPath.get(), 0)); return absoluteTopLevelPath.get(); }
bool PlexHierarchicalCache::CacheData (const void* data, size_t size, const char* path) { size_t writeCacheIndex = (size_t)~0; for (size_t i = 0; i < caches.GetSize(); i++) { if (caches[i].cache->IsCacheWriteable()) { writeCacheIndex = i; break; } } if (writeCacheIndex == (size_t)~0) return false; bool doWrite = true; if (redundantRemove) { csRef<iDataBuffer> nextData; for (size_t i = writeCacheIndex+1; i < caches.GetSize(); i++) { nextData = caches[i].cache->ReadCache (path); if (nextData.IsValid()) break; } if (nextData.IsValid() && (nextData->GetSize() == size) && (memcmp (data, nextData->GetData(), size) == 0)) { /* The item to cache matches what's cached in some lower cache, * so we don't have to cache it in the higher cache. Instead, * remove it */ doWrite = false; caches[writeCacheIndex].cache->ClearCache (path); // The containing directory may be empty, so try to tidy up later csString parentPath (GetParentDir (path)); if (!parentPath.IsEmpty()) caches[writeCacheIndex].delayedClearDirs.Add (parentPath); } } if (doWrite) return caches[writeCacheIndex].cache->CacheData (data, size, path); else return true; }
String PBXFile::getFullPath() const { if (m_sourceTree == "<group>") { String parentPath("$(SOURCE_ROOT)"); if (m_parent) parentPath = m_parent->getFullPath(); if (m_path.empty()) return parentPath; else return joinPaths(parentPath, m_path, false); } else if (m_sourceTree == "<absolute>") { return m_path; } else { return joinPaths("$(" + m_sourceTree + ")", m_path, false); } }
void BundleFile::list(const std::string& path, std::vector<std::string>& files) const { poco_assert (_pArchive); files.clear(); int depth = 0; std::string parent; if (!path.empty()) { // ensure parent ends with a slash Path parentPath(path, Path::PATH_UNIX); parentPath.makeDirectory(); parent = parentPath.toString(Path::PATH_UNIX); } ZipArchive::FileHeaders::const_iterator it; ZipArchive::FileHeaders::const_iterator end(_pArchive->headerEnd()); if (path.empty()) { it = _pArchive->headerBegin(); } else { it = _pArchive->findHeader(parent); if (it != end) ++it; depth = Path(parent).depth(); } std::set<std::string> fileSet; while (it != end && isSubdirectoryOf(it->first, parent)) { Path p(it->first, Path::PATH_UNIX); p.makeFile(); if (p.depth() == depth) { std::string name = p.getFileName(); if (fileSet.find(name) == fileSet.end()) { files.push_back(name); fileSet.insert(name); } } ++it; } }
bool AssimpAssetLoader::open(const std::string& path) { mScene = mImporter.ReadFile( path, aiProcess_CalcTangentSpace | aiProcess_Triangulate | aiProcess_JoinIdenticalVertices | aiProcess_SortByPType | aiProcess_GenNormals); if(mScene == NULL) { // Assimp couldnt read the file std::cout << "Error AssimpAssetLoader Could not open file " << mImporter.GetErrorString() << std::endl; std::cout << "supported extension " << mImporter.IsExtensionSupported(".mesh.xml") << std::endl; return false; } mOpenFile = path; mParentPath = parentPath(mOpenFile); return true; }
void Shell::mkfile(size_t argc, const std::string* argv) { if(argc < 1) { printError(ERR_ARGS_INVALID); return; } std::string abspth, parent, name; abspth = absPath(argv[0]); parent = parentPath(abspth); if(parent == "/") name = abspth.substr(1, abspth.size() - 1); else name = abspth.substr(parent.size() + 1, abspth.size() - (parent.size() + 1)); if(parent == "" || name == "") { printError(ERR_ARGS_INVALID); return; } if(!session->createFile(parent.c_str(), name.c_str())) printError(session->getErrno()); }
void ParticleDumperPlugin::handshake() { auto req = waitData(); MPI_Check( MPI_Wait(&req, MPI_STATUS_IGNORE) ); recv(); std::vector<int> sizes; std::vector<std::string> names; SimpleSerializer::deserialize(data, sizes, names); auto init_channel = [] (XDMF::Channel::DataForm dataForm, int sz, const std::string& str, XDMF::Channel::NumberType numberType = XDMF::Channel::NumberType::Float, TypeDescriptor datatype = DataTypeWrapper<float>()) { return XDMF::Channel(str, nullptr, dataForm, numberType, datatype); }; // Velocity and id are special channels which are always present std::string allNames = "velocity, id"; channels.push_back(init_channel(XDMF::Channel::DataForm::Vector, 3, "velocity", XDMF::Channel::NumberType::Float, DataTypeWrapper<float>())); channels.push_back(init_channel(XDMF::Channel::DataForm::Scalar, 1, "id", XDMF::Channel::NumberType::Int64, DataTypeWrapper<int64_t>())); for (int i = 0; i<sizes.size(); i++) { allNames += ", " + names[i]; switch (sizes[i]) { case 1: channels.push_back(init_channel(XDMF::Channel::DataForm::Scalar, sizes[i], names[i])); break; case 3: channels.push_back(init_channel(XDMF::Channel::DataForm::Vector, sizes[i], names[i])); break; case 6: channels.push_back(init_channel(XDMF::Channel::DataForm::Tensor6, sizes[i], names[i])); break; default: die("Plugin '%s' got %d as a channel '%s' size, expected 1, 3 or 6", name.c_str(), sizes[i], names[i].c_str()); } } // Create the required folder createFoldersCollective(comm, parentPath(path)); debug2("Plugin '%s' was set up to dump channels %s. Path is %s", name.c_str(), allNames.c_str(), path.c_str()); }
std::string ZLUnixFSManager::resolveSymlink(const std::string &path) const { std::set<std::string> names; std::string current = path; for (int i = 0; i < 256; ++i) { names.insert(current); std::string buffer(2048, '\0'); int len = readlink(current.c_str(), (char*)buffer.data(), 2048); if ((len == 2048) || (len <= 0)) { return current; } buffer.erase(len); if (buffer[0] != '/') { buffer = parentPath(current) + '/' + buffer; } normalizeRealPath(buffer); if (names.find(buffer) != names.end()) { return buffer; } current = buffer; } return ""; }
void PlexHierarchicalCache::DelayClearDirs (SubCache& cache) { while (cache.delayedClearDirs.GetSize() > 0) { csSet<csString> newClearDirs; csSet<csString>::GlobalIterator it (cache.delayedClearDirs.GetIterator()); while (it.HasNext()) { csString dir (it.Next()); csRef<iStringArray> subitems = cache.cache->GetSubItems (dir); if (subitems->GetSize() == 0) { cache.cache->ClearCache (dir); // Now the parent may be empty ... check on next cycle csString parentPath (GetParentDir (dir)); if (!parentPath.IsEmpty()) newClearDirs.Add (parentPath); } } cache.delayedClearDirs = newClearDirs; } }
bool Effect::loadFromFile( const std::string& filename ) { // Define DEBUG_VS and/or DEBUG_PS to debug vertex and/or pixel shaders with the // shader debugger. Debugging vertex shaders requires either REF or software vertex // processing, and debugging pixel shaders requires REF. The // D3DXSHADER_FORCE_*_SOFTWARE_NOOPT flag improves the debug experience in the // shader debugger. It enables source level debugging, prevents instruction // reordering, prevents dead code elimination, and forces the compiler to compile // against the next higher available software target, which ensures that the // unoptimized shaders do not exceed the shader model limitations. Setting these // flags will cause slower rendering since the shaders will be unoptimized and // forced into software. See the DirectX documentation for more information about // using the shader debugger. DWORD dwShaderFlags = D3DXFX_NOT_CLONEABLE; #if defined( DEBUG ) || defined( _DEBUG ) // Set the D3DXSHADER_DEBUG flag to embed debug information in the shaders. // Setting this flag improves the shader debugging experience, but still allows // the shaders to be optimized and to run exactly the way they will run in // the release configuration of this program. dwShaderFlags |= D3DXSHADER_DEBUG; #endif #ifdef DEBUG_VS dwShaderFlags |= D3DXSHADER_FORCE_VS_SOFTWARE_NOOPT; #endif #ifdef DEBUG_PS dwShaderFlags |= D3DXSHADER_FORCE_PS_SOFTWARE_NOOPT; #endif // Preshaders are parts of the shader that the effect system pulls out of the // shader and runs on the host CPU. They should be used if you are GPU limited. // The D3DXSHADER_NO_PRESHADER flag disables preshaders. //if( !g_bEnablePreshader ) // dwShaderFlags |= D3DXSHADER_NO_PRESHADER; // Create an effect from an ASCII or binary effect description // std::string data = filename; HRESULT hr; if (FAILED(hr = D3DXCreateEffectFromFile(Paras::getInstancePtr()->_device, data.c_str(), NULL, NULL, dwShaderFlags, NULL, &_effect, NULL))) { data.clear(); Buddha::FileSystem::getInstancePtr()->getDataDirectory(data); data += filename; if (FAILED(hr = D3DXCreateEffectFromFile(Paras::getInstancePtr()->_device, data.c_str(), NULL, NULL, dwShaderFlags, NULL, &_effect, NULL))) { data.clear(); // char path[257]; static const std::string tMaxProgramName("MaxPreview.exe"); GetModuleFileName(GetModuleHandle(tMaxProgramName.c_str()), path, 256); std::string parentPath(path); parentPath.erase(parentPath.size() - tMaxProgramName.size(), tMaxProgramName.size()); std::string previewProgramPath(parentPath); // data = previewProgramPath + filename; if (FAILED(hr = D3DXCreateEffectFromFile(Paras::getInstancePtr()->_device, data.c_str(), NULL, NULL, dwShaderFlags, NULL, &_effect, NULL))) { std::ostringstream buf; buf<<"D3DXCreateTextureFromFile "<<filename<<" Error Code : "<<(hr); Error(buf.str()); return false; } } } return true; }
int loadPlaylist(FILE * fp, char * utf8file) { FILE * fileP; char s[MAXPATHLEN+1]; int slength = 0; char * temp = strdup(utf8ToFsCharset(utf8file)); char * rfile = malloc(strlen(temp)+strlen(".")+ strlen(PLAYLIST_FILE_SUFFIX)+1); char * actualFile; char * parent = parentPath(temp); int parentlen = strlen(parent); char * erroredFile = NULL; int tempInt; int commentCharFound = 0; strcpy(rfile,temp); strcat(rfile,"."); strcat(rfile,PLAYLIST_FILE_SUFFIX); free(temp); if((actualFile = rpp2app(rfile)) && isPlaylist(actualFile)) free(rfile); else { free(rfile); commandError(fp, ACK_ERROR_NO_EXIST, "playlist \"%s\" not found", utf8file); return -1; } while(!(fileP = fopen(actualFile,"r")) && errno==EINTR); if(fileP==NULL) { commandError(fp, ACK_ERROR_SYSTEM, "problems opening file \"%s\"", utf8file); return -1; } while((tempInt = fgetc(fileP))!=EOF) { s[slength] = tempInt; if(s[slength]=='\n' || s[slength]=='\0') { commentCharFound = 0; s[slength] = '\0'; if(s[0]==PLAYLIST_COMMENT) { commentCharFound = 1; } if(strncmp(s,musicDir,strlen(musicDir))==0) { strcpy(s,&(s[strlen(musicDir)])); } else if(parentlen) { temp = strdup(s); memset(s,0,MAXPATHLEN+1); strcpy(s,parent); strncat(s,"/",MAXPATHLEN-parentlen); strncat(s,temp,MAXPATHLEN-parentlen-1); if(strlen(s)>=MAXPATHLEN) { commandError(fp, ACK_ERROR_PLAYLIST_LOAD, "\"%s\" too long", temp); free(temp); while(fclose(fileP) && errno==EINTR); if(erroredFile) free(erroredFile); return -1; } free(temp); } slength = 0; temp = fsCharsetToUtf8(s); if(!temp) continue; temp = strdup(temp); if(commentCharFound && !getSongFromDB(temp) && !isRemoteUrl(temp)) { free(temp); continue; } if((addToPlaylist(stderr,temp))<0) { if(!erroredFile) erroredFile = strdup(temp); } free(temp); } else if(slength==MAXPATHLEN) { s[slength] = '\0'; commandError(fp, ACK_ERROR_PLAYLIST_LOAD, "line in \"%s\" is too long", utf8file); ERROR("line \"%s\" in playlist \"%s\" is too long\n", s, utf8file); while(fclose(fileP) && errno==EINTR); if(erroredFile) free(erroredFile); return -1; } else if(s[slength]!='\r') slength++; } while(fclose(fileP) && errno==EINTR); if(erroredFile) { commandError(fp, ACK_ERROR_PLAYLIST_LOAD, "can't add file \"%s\"", erroredFile); free(erroredFile); return -1; } return 0; }
MStatus preview(const MArgList& args,bool useVertexColor) { //单实例先清除 if(MaterialSet::getSingletonPtr()) MaterialSet::getSingletonPtr()->clear(); char tempPath[MAX_PATH]; GetTempPath(MAX_PATH, tempPath); std::string tempFileName(tempPath); ExportOptions::instance().m_outFilePath = tempFileName.c_str(); tempFileName += "\\"; tempFileName += _T("maya.mz"); ExportOptions::instance().m_outFile = tempFileName.c_str(); ExportOptions::instance().clipList.clear(); MTime kTimeMin = MAnimControl::animationStartTime(); //整个场景的起始帧 MTime kTimeMax = MAnimControl::animationEndTime(); //整个场景的结束帧 clipInfo clip; clip.name = "Animation"; clip.startFrame = (int)kTimeMin.value(); clip.endFrame = (int)kTimeMax.value(); clip.stepFrame = 1; ExportOptions::instance().clipList.push_back(clip); ExportOptions::instance().exportAnims = true; ExportOptions::instance().exportVertexColour = useVertexColor; /*BindPoseTool bindPoseTool; bindPoseTool.GoIntoBindPose();*/ MWriter writer; writer.read(); MStatus status = writer.write(); #ifdef RELEASEDEBUG #define DLL_NAME "MayaPreview_rd.exe" #elif _DEBUG #define DLL_NAME "MayaPreview_d.exe" #else #define DLL_NAME "MayaPreview.exe" #endif if(status == MS::kSuccess) { HWND hWnd = FindWindowEx(0,0,0,"MayaPreview"); //if(hWnd) //{ // SendMessage(hWnd,WM_CLOSE,0,0); // hWnd = 0; //} if(!hWnd) { static const std::string tMaxProgramName("Maya.exe"); char path[257]; GetModuleFileName(GetModuleHandle(tMaxProgramName.c_str()),path,256); std::string parentPath(path); parentPath.erase(parentPath.size() - tMaxProgramName.size(), tMaxProgramName.size()); std::string previewProgramPath(parentPath + "preview\\" + DLL_NAME); if(!ShellExecute(0,"open",previewProgramPath.c_str(),"","",SW_SHOW)) { MessageBox(0,previewProgramPath.c_str(),"Can't Find MayaPreview Program",0); return MS::kFailure; } hWnd = FindWindowEx(0,0,0,"MayaPreview"); DWORD tick = GetTickCount(); while(!hWnd) { DWORD tickNow = GetTickCount(); if(tickNow - tick > 3000)break; Sleep(1); hWnd = FindWindowEx(0,0,0,"MayaPreview"); } } if(hWnd) { SendMessage(hWnd,WM_USER + 128,0,0); SetActiveWindow(hWnd); SetForegroundWindow(hWnd); BringWindowToTop(hWnd); } } /*bindPoseTool .UndoGoIntoBindPose();*/ return MS::kSuccess; }
// ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- int32_t LosAlamosFFTWriter::writeFile() { setErrorCondition(0); dataCheck(); if(getErrorCondition() < 0) { return getErrorCondition(); } DataContainer::Pointer m = getDataContainerArray()->getDataContainer(getFeatureIdsArrayPath().getDataContainerName()); int32_t err = 0; size_t dims[3] = { 0, 0, 0 }; m->getGeometryAs<ImageGeom>()->getDimensions(dims); float res[3] = { 0.0f, 0.0f, 0.0f }; m->getGeometryAs<ImageGeom>()->getResolution(res); float origin[3] = { 0.0f, 0.0f, 0.0f }; m->getGeometryAs<ImageGeom>()->getOrigin(origin); // Make sure any directory path is also available as the user may have just typed // in a path without actually creating the full path QFileInfo fi(getOutputFile()); QDir parentPath(fi.path()); if (!parentPath.mkpath(".")) { QString ss = QObject::tr("Error creating parent path '%1'").arg(parentPath.absolutePath()); notifyErrorMessage(getHumanLabel(), ss, -1); setErrorCondition(-1); return -1; } FILE* f = fopen(getOutputFile().toLatin1().data(), "wb"); if (NULL == f) { QString ss = QObject::tr("Error opening output file '%1'").arg(getOutputFile()); notifyErrorMessage(getHumanLabel(), ss, -1); setErrorCondition(-1); return -1; } float phi1 = 0.0f, phi = 0.0f, phi2 = 0.0f; int32_t featureId = 0; int32_t phaseId = 0; size_t index = 0; for (size_t z = 0; z < dims[2]; ++z) { for (size_t y = 0; y < dims[1]; ++y) { for (size_t x = 0; x < dims[0]; ++x) { index = (z * dims[0] * dims[1]) + (dims[0] * y) + x; phi1 = m_CellEulerAngles[index * 3] * 180.0 * DREAM3D::Constants::k_1OverPi; phi = m_CellEulerAngles[index * 3 + 1] * 180.0 * DREAM3D::Constants::k_1OverPi; phi2 = m_CellEulerAngles[index * 3 + 2] * 180.0 * DREAM3D::Constants::k_1OverPi; featureId = m_FeatureIds[index]; phaseId = m_CellPhases[index]; fprintf(f, "%.3f %.3f %.3f %lu %lu %lu %d %d\n", phi1, phi, phi2, x + 1, y + 1, z + 1, featureId, phaseId); } } } fclose(f); notifyStatusMessage(getHumanLabel(), "Complete"); return err; }
bool ConfigOptionsDialog::ParseConfigOptions(const ConfigToken &setProfile) { wxStandardPaths stdPaths; // Reset any grid values gridValues.childHeaderArray.clear(); gridValues.childSelectArray.clear(); // Get the directory that contains the main options wxFileName mainConfigDef; mainConfigDef.AssignDir(stdPaths.GetDataDir()); mainConfigDef.AppendDir("MainLib"); mainConfigDef.SetFullName(wxT("gliConfig_Definition.ini")); // Parse the main config file if(!ParseConfigFile(mainConfigDef, false)) { return false; } // Get the plugin directory wxFileName pluginDir; pluginDir.AssignDir(stdPaths.GetDataDir()); pluginDir.AppendDir("Plugins"); wxDir searchDir(pluginDir.GetFullPath()); // Search for all directories under the "Plugins" directory wxArrayString foundDirs; DirListTraverse dirTraverse(foundDirs); searchDir.Traverse(dirTraverse); // Loop for all plugins directories and get any plugin options for(uint i=0; i<foundDirs.size(); i++) { wxFileName pluginConfigDef; pluginConfigDef.AssignDir(foundDirs[i]); pluginConfigDef.SetFullName(wxT("config_Definition.ini")); // If the file exists if(pluginConfigDef.FileExists()) { // Parse the main config file if(!ParseConfigFile(pluginConfigDef, true)) { return false; } } else { wxLogWarning("Unable to find plugin config definition (%s) - file does not exist", pluginConfigDef.GetFullPath().c_str()); } } // Set the defualts from the passed config options if(!SetProfileData(setProfile, gridValues)) { wxLogError("Unable to set selected config options"); return false; } // Lock and clear the property grid propGrid->Freeze(); // Add the options to the property grid string parentPath(""); if(!AddPropGridHeader(gridValues, 0, true, parentPath)) { propGrid->Thaw(); return false; } // Release the property grid propGrid->Thaw(); return true; }
bool ZLUnixFSManager::canRemoveFile(const std::string &path) const { return access(parentPath(path).c_str(), W_OK) == 0; }
void MltRuntime::add_runtime_entry(const JsonPath& path, json_t* script_serialed, int give) throw(Exception) { if ( path.path.size() == 0) { throw_error_v(ErrorRuntimeUuidPathInvalid, "root path not allowed for add entry"); } JsonPath parentPath(path); parentPath.path.pop_back(); json_t* parent_je = json_serialize; JsonPath::PathCompIter it = parentPath.path.begin(); for (; it != parentPath.path.end(); it++) { json_t* je = json_object_get(parent_je, it->name.c_str()); if (!je) { throw_error_v(ErrorRuntimeUuidPathInvalid, "parent path invalid for add entry"); } if ( it->type == JsonPathComponent::PathObject ) { if ( !json_is_object(je) ) { throw_error_v(ErrorRuntimeUuidPathInvalid, "parent path invalid for add entry"); } parent_je = je; } else if (it->type == JsonPathComponent::PathArray ) { if (!json_is_array(je)) { throw_error_v(ErrorRuntimeUuidPathInvalid, "parent path invalid for add entry"); } int sz = json_array_size(je); if (sz == 0) { throw_error_v(ErrorRuntimeUuidPathInvalid, "parent path invalid for add entry"); } int idx = it->arr_idx; if (idx < 0) idx = sz + idx; if (idx < 0 || idx >= sz ) { throw_error_v(ErrorRuntimeUuidPathInvalid, "parent path invalid for add entry"); } parent_je = json_array_get(je, idx); } } if (!json_is_object(parent_je)) { throw_error_v(ErrorRuntimeUuidPathInvalid, "parent path invalid for add entry"); } const JsonPathComponent& lastPath = *(path.path.rbegin()); if (lastPath.type == JsonPathComponent::PathArray) { json_t* cur = json_object_get(parent_je, lastPath.name.c_str()); if ( !cur ) { cur = json_array(); json_object_set_new(parent_je, lastPath.name.c_str(), cur); } if (!json_is_array(cur)) { throw_error_v(ErrorRuntimeUuidPathInvalid, " path invalid for add entry"); } else { int idx = lastPath.arr_idx; int sz = json_array_size(cur); if (idx < 0) { idx = sz + idx + 1; } if (idx > sz) idx = sz; if (idx < 0) idx = 0; if ( idx == sz ) { JsonPath curPath(parentPath); curPath.push_back(lastPath.name.c_str(), idx); parse_struct(script_serialed, curPath, uuid_pathmap); if (give) json_array_append_new(cur, script_serialed); else json_array_append(cur, script_serialed); } else { JsonPath curPath(parentPath); curPath.push_back(lastPath.name.c_str(), idx); parse_struct(script_serialed, curPath, uuid_pathmap); if (give) json_array_insert_new(cur, idx, script_serialed); else json_array_insert(cur, idx, script_serialed); } } } else if (lastPath.type == JsonPathComponent::PathObject) { json_t* cur = json_object_get(parent_je, lastPath.name.c_str()); if (cur) { throw_error_v(ErrorRuntimeUuidPathInvalid, " path invalid for add entry"); } JsonPath curPath(parentPath); curPath.push_back(lastPath.name.c_str()); parse_struct(script_serialed, curPath, uuid_pathmap); if (give) { json_object_set_new(parent_je, lastPath.name.c_str(), script_serialed); } else { json_object_set(parent_je, lastPath.name.c_str(), script_serialed); } } json_version++; return; }
void testObj::test<2>(void) { ensure_equals("invalid parent path", parentPath("/some/path/myFile"), "/some/path"); }
void Shell::ocp(size_t argc, const std::string* argv) { class _FDGuard { SessionClient* session; public: _FDGuard(SessionClient* _ss) : session(_ss) {} void operator () (int fd) { session->closeFile(fd); } }; class _OFDGuard { public: void operator () (FILE* fd) { fclose(fd); } }; if(argc < 2) { printError(ERR_ARGS_INVALID); return; } FILE* ofd = fopen(argv[0].c_str(), "r"); if(ofd == nullptr) { printError(ERR_OFILE_OPEN_FAIL); return; } Guard<FILE*, _OFDGuard> ogd(ofd, _OFDGuard()); std::string abspth, parent, name; abspth = absPath(argv[1]); parent = parentPath(abspth); if(parent == "/") name = abspth.substr(1, abspth.size() - 1); else name = abspth.substr(parent.size() + 1, abspth.size() - (parent.size() + 1)); if(parent == "" || name == "") { printError(ERR_ARGS_INVALID); return; } if(!session->createFile(parent.c_str(), name.c_str())) { printError(session->getErrno()); return; } int fd = session->openFile(absPath(argv[1]).c_str(), OPTYPE_WRITE); if(fd <= 0) { printError(session->getErrno()); return; } Guard<int, _FDGuard> gd(fd, _FDGuard(session)); size_t start = 0; const size_t BUFSIZE = 64; std::unique_ptr<char> buf(new char[BUFSIZE]); while(true) { int len = fread(buf.get(), sizeof(char), BUFSIZE, ofd); if(len < 0) { printError(ERR_OFILE_READ_FAIL); return; } else if(len == 0) break; else { start += len; int has = 0; while(has != len) { int cl = session->writeFile(fd, buf.get() + has, len - has); if(cl < 0) { printError(session->getErrno()); return; } if(cl == 0) { printError(ERR_UNKNOW); return; } has += cl; } } } }
void testObj::test<3>(void) { parentPath( Path("/a/b/c") ); }
void TypeInference::inferTypes( ValueDef& valueDef, StaticContextPtr& pMemberCtx, const LogPtr& pLog) { switch (valueDef.getValueType()) { case OBJECT_INIT: { const ObjectInitValueDef& objectInitDef = static_cast<const ObjectInitValueDef&>(valueDef); TypePtr pType = TypePtr( new ReferenceType(OBJECT_REF_TYPE, objectInitDef.getClassName())); valueDef.setInferredType(pType); const map<const wstring, ActualParamDefPtr>& actualParamsMap = objectInitDef.getActualParamsMap(); map<const wstring, ActualParamDefPtr>::const_iterator it; for (it = actualParamsMap.begin(); it != actualParamsMap.end(); it++) { const ActualParamDefPtr& pActualParamDef = (*it).second; const ValueDefPtr& pParamValueDef = pActualParamDef->getValue(); inferTypes(*pParamValueDef, pMemberCtx, pLog); } } break; case ARRAY_INIT: { const ArrayInitValueDef& arrayInitDef = static_cast<const ArrayInitValueDef&>(valueDef); valueDef.setInferredType(arrayInitDef.getDeclaredType()); const list<ValueDefPtr>& arrayValues = arrayInitDef.getValues(); list<ValueDefPtr>::const_iterator it; for (it = arrayValues.begin(); it != arrayValues.end(); it++) { const ValueDefPtr& pArrayValue = *it; inferTypes(*pArrayValue, pMemberCtx, pLog); } } break; case LITERAL: { const LiteralValueDef& literalDef = static_cast<const LiteralValueDef&>(valueDef); switch (literalDef.getLiteralType()) { case INTEGER_LITERAL: valueDef.setInferredType(P_INTEGER_TYPE); break; case FLOAT_LITERAL: valueDef.setInferredType(P_FLOAT_TYPE); break; case STRING_LITERAL: valueDef.setInferredType(P_STRING_TYPE); break; default: assert(false); break; } } break; case REFERENCE_PATH: { const ReferencePathValueDef& referencePathDef = static_cast<const ReferencePathValueDef&>(valueDef); const list<const wstring>& path = referencePathDef.getReferencePath(); StaticContextEntryPtr pEntry; TypePtr pCurrentType; list<const wstring>::const_iterator it; wstring parentPath(L""); for (it = path.begin(); it != path.end(); it++) { const wstring& pathElement = *it; if (it == path.begin()) { CStaticContextEntryPtr pEntry; if (!pMemberCtx->lookup(pathElement, pEntry)) { boost::wformat f(L"Unable to resolve name %1%"); f % pathElement; pLog->log(referencePathDef, msg::ErrAnaTypeInfer_NameNotInContext, f.str()); return; } else { switch (pEntry->getStaticEntryType()) { case CLASS_DEF_CTX_ENTRY: { TypePtr pType(new ReferenceType(CLASS_REF_TYPE, pEntry->getName())); pCurrentType = pType; } break; case INTERFACE_DEF_CTX_ENTRY: { TypePtr pType(new ReferenceType(CLASS_REF_TYPE, pEntry->getName())); pCurrentType = pType; } break; case VARIABLE_DEF_CTX_ENTRY: { VariableDeclDefPtr pVariableDef; pEntry->getVariable(pVariableDef); if (pMemberCtx->isStatic() && !pVariableDef->isStatic()) { boost::wformat f(L"Cannot refer to a non static variable from an static context: %1%"); f % pathElement; pLog->log(referencePathDef, msg::ErrAnaTypeInfer_NonStaticVarRef, f.str()); return; } else { pCurrentType = pVariableDef->getDeclaredType(); } } break; case FORMAL_PARAM_DEF_CTX_ENTRY: { if (pMemberCtx->isStatic()) { boost::wformat f(L"Cannot refer to a class parameter from an static context: %1%"); f % pathElement; pLog->log(referencePathDef, msg::ErrAnaTypeInfer_NonStaticParamRef, f.str()); return; } FormalParamDefPtr pFormalParamDef; pEntry->getFormalParam(pFormalParamDef); pCurrentType = pFormalParamDef->getType(); } break; default: assert(false); return; } } } else { assert(pCurrentType.get() != NULL); StaticContextPtr pRootCtx; pMemberCtx->getRootContext(pRootCtx); if (!followPathElement( *pCurrentType, *pRootCtx, pathElement, pCurrentType)) { boost::wformat f(L"%1% is not a member of %2%"); f % pathElement % parentPath; pLog->log(referencePathDef, msg::ErrAnaTypeInfer_NotAMember, f.str()); return; } } if (parentPath.size()) { parentPath.append(L"."); } parentPath.append(pathElement); } assert(pCurrentType.get() != NULL); valueDef.setInferredType(pCurrentType); } break; default: assert(false); break; } }