void ScriptsVectorController::directoryChanged(const QString &t_path) { StringVector extsToIgnore; extsToIgnore.push_back("osp"); extsToIgnore.push_back("osp-journal"); extsToIgnore.push_back("db"); extsToIgnore.push_back("db-journal"); StringVector::const_iterator extsToIgnoreBegin = extsToIgnore.begin(); StringVector::const_iterator extsToIgnoreEnd = extsToIgnore.end(); openstudio::path path = openstudio::toPath(t_path); if (!m_fswatcher->directories().contains(toQString(m_path)) && boost::filesystem::exists(m_path)) { m_fswatcher->addPath(openstudio::toQString(m_path)); } if (!m_fswatcher->directories().contains(toQString(m_path.parent_path())) && boost::filesystem::exists(m_path.parent_path())) { m_fswatcher->addPath(openstudio::toQString(m_path.parent_path())); } if (path == m_path) { // ooh, it was us. QStringList files = QDir(openstudio::toQString(m_path)).entryList(QDir::Files, QDir::Name); std::vector<OSItemId> items; for (QStringList::const_iterator itr = files.begin(); itr != files.end(); ++itr) { openstudio::path filePath = openstudio::toPath(*itr); std::string ext = getFileExtension(filePath); if (std::find(extsToIgnoreBegin,extsToIgnoreEnd,ext) == extsToIgnoreEnd) { items.push_back(scriptToItemId(m_path / filePath)); } } m_items = items; std::reverse(m_items.begin(), m_items.end()); emit itemIds(m_items); } else { LOG(Debug, "No match for FS Path: " << openstudio::toString(path) << " " << openstudio::toString(m_path)); } }
//============================================================================== bool File::moveToTrash() const { if (! exists()) return true; File trashCan ("~/.Trash"); if (! trashCan.isDirectory()) trashCan = "~/.local/share/Trash/files"; if (! trashCan.isDirectory()) return false; return moveFileTo (trashCan.getNonexistentChildFile (getFileNameWithoutExtension(), getFileExtension())); }
int wxOpenCommanderListCtrl::getIcon(long itemPos, long itemCol) const { wxString actualFileDir = m_cCommander->getFileDirActualPath(itemPos, itemCol); if (m_cCommander->getListDevices()) return getIconDevice(itemPos, itemCol); if (wxDir::Exists(actualFileDir)) return ICON_DIRECTORY; else { wxString ext = getFileExtension(actualFileDir); ext.UpperCase(); if (ext != "EXE" && ext != "BAT" && ext != "COM") return ICON_NORMAL_FILE; else return ICON_EXEC_FILE; } }
SampleSourceType sampleSourceGuess(const CharString sampleSourceTypeString) { if(!charStringIsEmpty(sampleSourceTypeString)) { // Look for stdin/stdout if(strlen(sampleSourceTypeString->data) == 1 && sampleSourceTypeString->data[0] == '-') { return SAMPLE_SOURCE_TYPE_PCM; } else { const char* fileExtension = getFileExtension(sampleSourceTypeString->data); // If there is no file extension, then automatically assume raw PCM data. Deal with it! if(fileExtension == NULL) { return SAMPLE_SOURCE_TYPE_PCM; } // Possible file extensions for raw PCM data else if(!strcasecmp(fileExtension, "pcm") || !strcasecmp(fileExtension, "raw") || !strcasecmp(fileExtension, "dat")) { return SAMPLE_SOURCE_TYPE_PCM; } else if(!strcasecmp(fileExtension, "aif") || !strcasecmp(fileExtension, "aiff")) { return SAMPLE_SOURCE_TYPE_AIFF; } #if HAVE_LIBFLAC else if(!strcasecmp(fileExtension, "flac")) { return SAMPLE_SOURCE_TYPE_FLAC; } #endif #if HAVE_LIBLAME else if(!strcasecmp(fileExtension, "mp3")) { return SAMPLE_SOURCE_TYPE_MP3; } #endif #if HAVE_LIBVORBIS else if(!strcasecmp(fileExtension, "ogg")) { return SAMPLE_SOURCE_TYPE_OGG; } #endif else if(!strcasecmp(fileExtension, "wav") || !strcasecmp(fileExtension, "wave")) { return SAMPLE_SOURCE_TYPE_WAVE; } else { logCritical("Sample source '%s' does not match any supported type", sampleSourceTypeString->data); return SAMPLE_SOURCE_TYPE_INVALID; } } } else { return SAMPLE_SOURCE_TYPE_INVALID; } }
FREEIMAGE_BMP* FREEIMAGE_LoadImage(const UString& filePath, BYTE* raw_data, int len) { if (!raw_data) return NULL; FREEIMAGE_BMP* vix_bmp = new FREEIMAGE_BMP; vix_bmp->path = filePath; vix_bmp->name = getFileName(filePath); vix_bmp->format = FREEIMAGE_FormatFromExtension(getFileExtension(filePath, false)); vix_bmp->data = NULL; vix_bmp->bitmap = NULL; switch (vix_bmp->format) { case FIF_PNG: FREEIMAGE_LoadPNGHeader(&vix_bmp->header, raw_data); break; case FIF_TARGA: FREEIMAGE_LoadTGAHeader(&vix_bmp->header, vix_bmp->data); break; case FIF_JPEG: FREEIMAGE_LoadJPGHeader(&vix_bmp->header, vix_bmp->data); break; } //Check if FreeImage has reading capabilities if (FreeImage_FIFSupportsReading(vix_bmp->format)) { int pitch = ((vix_bmp->header.bitdepth * vix_bmp->header.width + 31) / 32) * 4; vix_bmp->bitmap = FreeImage_ConvertFromRawBits(raw_data, vix_bmp->header.width, vix_bmp->header.height, pitch, vix_bmp->header.bitdepth * 4, FI_RGBA_RED_MASK, FI_RGBA_GREEN_MASK, FI_RGBA_BLUE_MASK); } //If image failed to load, return NULL if (!vix_bmp->bitmap) return NULL; FreeImage_FlipVertical(vix_bmp->bitmap); //return bitmap return vix_bmp; }
void FileListAdapter::drawItem(int item, int x, int y, int w, int h, bool selected) const { int icon = -1; if ((*items_)[item].isDirectory) { icon = options_.folderIcon; } else { std::string extension = getFileExtension((*items_)[item].name); auto iter = options_.iconMapping.find(extension); if (iter != options_.iconMapping.end()) icon = iter->second; } int iconSpace = this->itemHeight(item); ui_draw2d.DrawImage2GridH(selected ? I_BUTTON_SELECTED: I_BUTTON, x, y, x + w); ui_draw2d.DrawTextShadow(UBUNTU24, (*items_)[item].name.c_str(), x + UI_SPACE + iconSpace, y + 25, 0xFFFFFFFF, ALIGN_LEFT | ALIGN_VCENTER); if (icon != -1) ui_draw2d.DrawImage(icon, x + UI_SPACE, y + 25, 1.0f, 0xFFFFFFFF, ALIGN_VCENTER | ALIGN_LEFT); }
QStringList Configuration::getFileOpenFilters( FileType firstType ) { QStringList exts = getFileExtension(); QStringList filterList; for ( int i = 0; i < FileTypeNum && i < exts.length(); i++ ) { QString filter = QString::fromLatin1( "%1 (%2)" ).arg( fileTypeToString( i ) ).arg( exts.value( i ).split( "|" ).join( " " ) ); if ( firstType == i ) { filterList.prepend( filter ); } else { filterList.append( filter ); } } return filterList; }
FileReference::FileReference(const openstudio::path& p) : m_uuid(createUUID()), m_versionUUID(createUUID()), m_name(toString(p)), m_displayName(toString(p.filename())), m_path(completeAndNormalize(p)), m_timestampLast(), m_checksumCreate(checksum(m_path)), m_checksumLast(m_checksumCreate) { try { m_fileType = FileReferenceType(getFileExtension(p)); } catch (...) { m_fileType = FileReferenceType::Unknown; } update(openstudio::path()); }
/** * Deletes the oldest video and it's thumbnail */ void deleteOldestVideo() { DIR *dir; struct dirent *ent; time_t oldest = time(NULL); //all files will be older then now if ((dir = opendir(config.VideoSaveDirectory)) != NULL) { //For every file in the videos directory while ((ent = readdir(dir)) != NULL) { //If the file is a mp4 const char* extensao = getFileExtension(ent->d_name); if (extensao != NULL) { if (strcmp(extensao, "mp4") == 0) { //Converting the timestamp to time_t time_t timestamp = atol(ent->d_name); //If it's older then the oldest one until now, set this as oldest if (timestamp < oldest) { oldest = timestamp; } } } } closedir(dir); //Removing the video char temp[256]; snprintf(temp, 256, "%s/%d.mp4", config.VideoSaveDirectory, oldest); int status = remove(temp); if (status == 0) { syslog(LOG_INFO, "Video %s removed.", temp); } else { syslog(LOG_ERR, "Failed to remove video %s: %d.", temp, status); } //And it's thumbnail snprintf(temp, 256, "%s/%d.%s", config.ThumbnailSaveDirectory, oldest, config.ThumbnailFormat); status = remove(temp); if (status == 0) { syslog(LOG_INFO, "Thumbnail %s removed.", temp); } else { syslog(LOG_ERR, "Failed to remove thumbnail %s: %d.", temp, status); } } }
bool BZFSHTTP::handleRequest(const HTTPRequest &request, HTTPReply &reply) { if (serviceMimeResources && resourceRootPath.size() && mimeTypes.size()) { // parse out the resource and see if we know what it is std::string ext; tolower(getFileExtension(request.resource),ext); if (ext.size()) { if ( mimeTypes.find(ext) != mimeTypes.end() ) { // it's one we do, try and find it std::string filepath = concatPaths(resourceRootPath.c_str(),request.resource.c_str()); FILE *fp = fopen(filepath.c_str(),"rb"); if (fp) { char buffer[1024]; bool done = false; while (!done) { size_t read = fread(buffer,1,1024,fp); if (read) reply.addBody(buffer,read); if (read != 1024) done = true; } fclose(fp); reply.docType = HTTPReply::eOther; reply.otherMimeType = mimeTypes[ext]; reply.returnCode = HTTPReply::e200OK; return true; } } } } return generatePage(request,reply); }
GLuint CGLSLProgram::getShaderType(const string fileName){ string fileExtension = getFileExtension(fileName); GLuint numberOfExtensions, shaderType; shaderType = nGLSLProgram::GLSLShader::VERTEX; numberOfExtensions = sizeof(nGLSLProgram::Extensions) / sizeof(nGLSLProgram::GLSLShaderFileExtension); for (int k = 0; k < static_cast<GLint>(numberOfExtensions); ++k) if (fileExtension == nGLSLProgram::Extensions[k].mExtension){ shaderType = nGLSLProgram::Extensions[k].mType; break; } return shaderType; }
void FileListAdapter::drawItem(int item, int x, int y, int w, int h, bool selected) const { int icon = -1; if ((*items_)[item].isDirectory) { icon = options_.folderIcon; } else { std::string extension = getFileExtension((*items_)[item].name); auto iter = options_.iconMapping.find(extension); if (iter != options_.iconMapping.end()) icon = iter->second; } float scaled_h = ui_atlas.images[I_BUTTON].h; float scaled_w = scaled_h * (144.f / 80.f); int iconSpace = scaled_w + 10; ui_draw2d.DrawImage2GridH(selected ? I_BUTTON_SELECTED: I_BUTTON, x, y, x + w); ui_draw2d.DrawTextShadow(UBUNTU24, (*items_)[item].name.c_str(), x + UI_SPACE + iconSpace, y + 25, 0xFFFFFFFF, ALIGN_LEFT | ALIGN_VCENTER); // This might create a texture so we must flush first. UIFlush(); GameInfo *ginfo = 0; if (!(*items_)[item].isDirectory) { ginfo = g_gameInfoCache.GetInfo((*items_)[item].fullName, false); if (!ginfo) { ELOG("No ginfo :( %s", (*items_)[item].fullName.c_str()); } } if (ginfo) { if (ginfo->iconTexture) { uint32_t color = whiteAlpha(ease((time_now_d() - ginfo->timeIconWasLoaded) * 2)); UIFlush(); ginfo->iconTexture->Bind(0); ui_draw2d.DrawTexRect(x + 10, y, x + 10 + scaled_w, y + scaled_h, 0, 0, 1, 1, color); ui_draw2d.Flush(); ctx_->RebindTexture(); } } else { if (icon != -1) ui_draw2d.DrawImage(icon, x + UI_SPACE, y + 25, 1.0f, 0xFFFFFFFF, ALIGN_VCENTER | ALIGN_LEFT); } }
void *image_search(void *arg) { Search_Arg *arg1 = (Search_Arg *)arg; char *dir = arg1->dir; char *extension = arg1->extension; DIR *dp = opendir(dir); if(dp == NULL) { printf("Cannot open directory: %s\n", dir); return NULL; } //scan through everything in current directory struct dirent *entry; while((entry = readdir(dp)) != NULL) { //ignore . and .. directories if(strcmp(".",entry->d_name) == 0 ||strcmp("..",entry->d_name) == 0) {continue;} char curName[strlen(dir) + strlen(entry->d_name) + 3]; strcpy(curName, dir); strcat(curName, "/"); strcat(curName, entry->d_name); //see if the entry is a directory by attempting to open it DIR *dp2 = opendir(curName); if(dp2 != NULL); // if directory, do nothing else if(getFileExtension(entry->d_name) == extension) //file is not a directory, check extension { //get information about file pthread_mutex_lock(&FilePrinting); getFileInfo(curName); pthread_mutex_unlock(&FilePrinting); //printf("%s\n",curName); pthread_mutex_lock(&CountMutex); count++; pthread_mutex_unlock(&CountMutex); } } closedir(dp); //close directory return NULL; }
bool ResourceManager::store(const std::string & filename, T * resource) const { // Get file extension std::string ext = getFileExtension(filename); // Find suitable storer for (AbstractStorer * storer : m_storers) { // Check storer type Storer<T> * concreteStorer = dynamic_cast<Storer<T> *>(storer); if (concreteStorer) { // Check if filetype is supported if (concreteStorer->canStore(ext)) { // Use store return concreteStorer->store(filename, resource); } } } // No suitable loader found return false; }
unsigned int devil_loadImage(const std::string &fileName) { unsigned int imageName = 0; ilGenImages(1, &imageName); ilBindImage(imageName); ilLoadImage(fileName); ILenum error = ilGetError(); if (error != IL_NO_ERROR) { std::cerr << "DevIL error: " << iluErrorString(error) << std::endl; return 0; } else { if (ilGetInteger(IL_ORIGIN_MODE) == IL_ORIGIN_LOWER_LEFT && getFileExtension(fileName) != ".tif") { iluFlipImage(); } return imageName; } }
T * ResourceManager::load(const std::string & filename) const { // Get file extension std::string ext = getFileExtension(filename); // Find suitable loader for (AbstractLoader * loader : m_loaders) { // Check loader type Loader<T> * concreteLoader = dynamic_cast<Loader<T> *>(loader); if (concreteLoader) { // Check if filetype is supported if (concreteLoader->canLoad(ext)) { // Use loader return concreteLoader->load(filename); } } } // No suitable loader found return nullptr; }
std::vector<std::string> getFilesOnDirectory(const std::string& directoryPath, const std::vector<std::string>& extensions) { try { // Check folder exits if (!existDir(directoryPath)) error("Folder " + directoryPath + " does not exist.", __LINE__, __FUNCTION__, __FILE__); // Read images std::vector<std::string> filePaths; for (const auto& file : boost::make_iterator_range(boost::filesystem::directory_iterator{directoryPath}, {})) if (!boost::filesystem::is_directory(file.status())) // Skip directories filePaths.emplace_back(file.path().string()); // Check #files > 0 if (filePaths.empty()) error("No files were found on " + directoryPath, __LINE__, __FUNCTION__, __FILE__); // If specific extensions specified if (!extensions.empty()) { // Read images std::vector<std::string> specificExtensionPaths; specificExtensionPaths.reserve(filePaths.size()); for (const auto& filePath : filePaths) if (extensionIsDesired(getFileExtension(filePath), extensions)) specificExtensionPaths.emplace_back(filePath); std::swap(filePaths, specificExtensionPaths); } // Sort alphabetically std::sort(filePaths.begin(), filePaths.end()); return filePaths; } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); return {}; } }
void Image::write(std::string filepath){ ASSERT(loaded, "You didn't load the image!"); ASSERT(path != INVALID_PATH, "You didn't provide a path for the Image"); INFO("Writing image " << filepath << "..."); std::string ext = getFileExtension(filepath); bool success = false; if(ext == BMP_EXT){ unsigned int rc = writeBMP(filepath); if(!rc) success = true; } else if (ext == PNG_EXT){ unsigned int rc = writePNG(filepath); if(!rc) success = true; } ASSERT(success, "Failed to write image " << filepath << "!"); INFO("Image wrote " << filepath << "!"); }
void buildAbsolutePath(const CharString directory, const CharString file, const char* fileExtension, CharString outString) { const char* extension; CharString absoluteDirectory; if(directory == NULL || charStringIsEmpty(directory)) { logWarn("Attempt to build absolute path with empty directory"); return; } if(file == NULL || charStringIsEmpty(file)) { logWarn("Attempt to build absolute path with empty file"); return; } absoluteDirectory = newCharString(); if(isAbsolutePath(directory)) { charStringCopy(absoluteDirectory, directory); } else { convertRelativePathToAbsolute(directory, absoluteDirectory); } if(fileExtension != NULL) { // Ignore attempts to append the same extension as is already on the file extension = getFileExtension(file->data); if(extension != NULL && !strncasecmp(extension, fileExtension, strlen(extension))) { buildAbsolutePath(absoluteDirectory, file, NULL, outString); } else { snprintf(outString->data, outString->length, "%s%c%s.%s", absoluteDirectory->data, PATH_DELIMITER, file->data, fileExtension); } } else { snprintf(outString->data, outString->length, "%s%c%s", absoluteDirectory->data, PATH_DELIMITER, file->data); } freeCharString(absoluteDirectory); }
void Image::load(){ ASSERT(path != INVALID_PATH, "You didn't provide a path for the Image"); ASSERT(path != GENERATED_MANUALLY, "This image was generated manually. " << "You can't load it"); INFO("Loading image " << path << "..."); std::string ext = getFileExtension(path); if(ext == BMP_EXT){ unsigned int rc = loadBMP(); if(!rc) loaded = true; } else if (ext == PNG_EXT){ unsigned int rc = loadPNG(); if(!rc) loaded = true; } ASSERT(loaded, "Failed to load image " << path << "!"); INFO("Image " << path << " loaded!"); INFO("\tWidth: " << width); INFO("\tHeight: " << height); }
openstudio::path saveModel(openstudio::model::Model model, const openstudio::path& osmPath, const openstudio::path& modelTempDir) { openstudio::path modelPath = osmPath; if (getFileExtension(osmPath).empty()) { modelPath = setFileExtension(osmPath,modelFileExtension(),false,true); } // save osm to temp directory, saveModelTempDir will copy to real location openstudio::path tempModelPath = modelTempDir / toPath("in.osm"); Workspace(model).save(tempModelPath,true); LOG_FREE(Debug, "saveModel", "Saved model to '" << toString(tempModelPath) << "'"); // DLM: eventually put saveRunManagerDatabase here, needs to happen before saveModelTempDir // DLM: eventually add this back in too // DLM: for now this is accomplished by calling saveModelTempDir after saveModel in all cases //saveModelTempDir(modelTempDir, modelPath); return modelPath; }
/* Returns Assimp's format description to filename */ const char * findFormatDescription(Assimp::Exporter &exporter, const std::string &filename) { if (!exporter.GetExportFormatCount()) { LOGE("Unexpected failure! Missing number of supported formats."); return 0; } auto const extension = getFileExtension(filename); std::string supported_extensions; for (int i = 0; i < exporter.GetExportFormatCount(); i++) { if (!strcmp(extension.c_str(), exporter.GetExportFormatDescription(i)->fileExtension)) return exporter.GetExportFormatDescription(i)->fileExtension; // List of supported extensions to a better log supported_extensions.append(exporter.GetExportFormatDescription(i)->fileExtension); supported_extensions.append(" "); } LOGW("Format '%s' is not supported! Please use some of the following format(s): %s", extension.c_str(), supported_extensions.c_str()); return 0; }
std::string createIntermediateSource(const std::string &filename, const std::string &cachedBinary, const kernelInfo &info){ std::string prefix, name; getFilePrefixAndName(cachedBinary, prefix, name); std::string extension = getFileExtension(filename); const std::string iCachedBinary = prefix + "i_" + name; if(extension == "okl"){ const std::string pCachedBinary = prefix + "p_" + name; parser fileParser; std::ofstream fs; fs.open(pCachedBinary.c_str()); fs << info.header << readFile(filename); fs.close(); fs.open(iCachedBinary.c_str()); fs << info.occaKeywords << fileParser.parseFile(pCachedBinary); fs.close(); } else{ std::ofstream fs; fs.open(iCachedBinary.c_str()); fs << info.occaKeywords << info.header << readFile(filename); fs.close(); } return iCachedBinary; }
QString KFileTools::scaleImageAndSave(QString path, qreal maxArea) { QImageReader reader(path); if(!reader.canRead()) return path; auto sz = reader.size(); int64_t originArea = (int64_t)sz.width()*sz.height(); float scale = float(maxArea/originArea); if(scale >= 1){ if(getFileExtension(path).toLower() != ".jpg"){ path = QKit::instance()->runTimeCachePath() + "/" + QKit::instance()->randString(8) + ".jpg"; reader.read().save(path, "JPG", 90); } return path; } qDebug() << "##### originArea:" << originArea << " maxArea:" << maxArea << " scale:" << scale ; scale = sqrtf(scale); qDebug() << "scale:" << scale; int sw = int(sz.width()*scale); int sh = int(sz.height()*scale); QSize ssz(sw, sh); qDebug() << "sw:" << sw <<" sh:" << sh << " rt:" << ssz; reader.setScaledSize(ssz); QImage img = reader.read(); if(img.isNull()) return path; //path = QKit::instance()->runTimeCachePath() + "/" + QKit::instance()->randString(8) + getFileExtension(path); //img.save(path); path = QKit::instance()->runTimeCachePath() + "/" + QKit::instance()->randString(8) + ".jpg"; img.save(path, "JPG", 90); return path; }
osg::ref_ptr<const NifOsg::KeyframeHolder> SceneManager::getKeyframes(const std::string &name) { std::string normalized = name; mVFS->normalizeFilename(normalized); KeyframeIndex::iterator it = mKeyframeIndex.find(normalized); if (it == mKeyframeIndex.end()) { Files::IStreamPtr file = mVFS->get(normalized); std::string ext = getFileExtension(normalized); if (ext != "nif" && ext != "kf") return NULL; osg::ref_ptr<NifOsg::KeyframeHolder> loaded (new NifOsg::KeyframeHolder); NifOsg::Loader::loadKf(Nif::NIFFilePtr(new Nif::NIFFile(file, normalized)), *loaded.get()); mKeyframeIndex[normalized] = loaded; return loaded; } else return it->second; }
// ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void QDataContainerReaderWidget::on_InputFileBtn_clicked() { QObject* whoSent = sender(); // for QButtons we prepended "btn_" to the end of the property name so strip that off QString propName = whoSent->objectName(); propName = propName.remove(0, 4); QString Ftype = getFileType(propName.toStdString()); QString ext = getFileExtension(propName.toStdString()); QString s = Ftype + QString("DREAM3D Files (*.dream3d *.h5 *.hdf5);;All Files(*.*)"); QString defaultName = getOpenDialogLastDirectory(); QString inputFile = QFileDialog::getOpenFileName(this, tr("Select Input File"), defaultName, s); if(true == inputFile.isEmpty()) { return; } // Store the last used directory into the private instance variable inputFile = QDir::toNativeSeparators(inputFile); if (!inputFile.isNull()) { setInputFile(inputFile); setOpenDialogLastDirectory(inputFile); } }
bool AkaiFileHandler::writePgmFileMPC1000( QStringList sampleNames, const QString fileBaseName, const QString outputDirPath, const QString tempDirPath, const SamplerAudioSource::EnvelopeSettings& envelopes, const bool isOverwriteEnabled ) { const QString fileName = fileBaseName + getFileExtension(); if ( QDir( outputDirPath ).exists( fileName ) && ! isOverwriteEnabled ) { return false; } while ( sampleNames.size() > MPC1000_Profile::NUM_PADS ) { sampleNames.removeLast(); } QByteArray pgmData( MPC1000_PGM::FILE_SIZE, PADDING ); bool isSuccessful = getTemplateDataMPC1000( pgmData ); if ( isSuccessful ) { quint8 noteNum = Midi::MIDDLE_C; for ( quint8 padNum = 0; padNum < sampleNames.size(); padNum++ ) { // Add sample name to PGM data { QByteArray sampleName = sampleNames.at( padNum ).toLatin1().leftJustified( MPC1000_PGM::SAMPLE_NAME_SIZE, PADDING, true ); const int pos = MPC1000_PGM::PAD_DATA_START + ( padNum * MPC1000_PGM::PAD_DATA_SIZE ); pgmData.replace( pos, MPC1000_PGM::SAMPLE_NAME_SIZE, sampleName ); } // Add sample volume level { const int pos = MPC1000_PGM::PAD_DATA_START + ( padNum * MPC1000_PGM::PAD_DATA_SIZE ) + MPC1000_PGM::LEVEL_OFFSET; QByteArray level; level += quint8( 100 ); pgmData.replace( pos, 1, level ); } // Add play mode { const int pos = MPC1000_PGM::PAD_DATA_START + ( padNum * MPC1000_PGM::PAD_DATA_SIZE ) + MPC1000_PGM::PLAY_MODE_OFFSET; QByteArray playMode; playMode += envelopes.oneShotSettings.at( padNum ) ? (char) 0x0 // 0 - One shot is set : quint8( 1 ); // 1 - One shot is not set pgmData.replace( pos, 1, playMode ); } // Add attack { const int pos = MPC1000_PGM::PAD_DATA_START + ( padNum * MPC1000_PGM::PAD_DATA_SIZE ) + MPC1000_PGM::ATTACK_OFFSET; QByteArray attack; attack += quint8( envelopes.attackValues.at( padNum ) * 100 ); pgmData.replace( pos, 1, attack ); } // Add decay { const int pos = MPC1000_PGM::PAD_DATA_START + ( padNum * MPC1000_PGM::PAD_DATA_SIZE ) + MPC1000_PGM::DECAY_OFFSET; QByteArray decay; decay += quint8( envelopes.releaseValues.at( padNum ) * 100 ); pgmData.replace( pos, 1, decay ); } // Add decay mode { const int pos = MPC1000_PGM::PAD_DATA_START + ( padNum * MPC1000_PGM::PAD_DATA_SIZE ) + MPC1000_PGM::DECAY_MODE_OFFSET; QByteArray decayMode; decayMode += (char) 0x0; pgmData.replace( pos, 1, decayMode ); } // Add "pad" -> "MIDI note" mapping { const int pos = MPC1000_PGM::PAD_MIDI_DATA_START + padNum; QByteArray value; value += noteNum; pgmData.replace( pos, 1, value ); } // Add "MIDI note" -> "pad" mapping { const int pos = MPC1000_PGM::MIDI_NOTE_DATA_START + noteNum; QByteArray value; value += padNum; pgmData.replace( pos, 1, value ); } noteNum++; } // Write PGM data to file const QString tempFilePath = QDir( tempDirPath ).absoluteFilePath( fileName ); QFile tempFile( tempFilePath ); isSuccessful = tempFile.open( QIODevice::WriteOnly ); if ( isSuccessful ) { QDataStream outStream( &tempFile ); const int numBytesWritten = outStream.writeRawData( pgmData.data(), MPC1000_PGM::FILE_SIZE ); if ( numBytesWritten != MPC1000_PGM::FILE_SIZE ) { isSuccessful = false; } else { const QString outputFilePath = QDir( outputDirPath ).absoluteFilePath( fileName ); QFile::remove( outputFilePath ); tempFile.copy( outputFilePath ); } tempFile.remove(); } } return isSuccessful; }
size_t getFilesInDir(const char *directory, std::vector<FileInfo> *files, const char *filter) { size_t foundEntries = 0; std::set<std::string> filters; std::string tmp; if (filter) { while (*filter) { if (*filter == ':') { filters.insert(tmp); tmp = ""; } else { tmp.push_back(*filter); } filter++; } } if (tmp.size()) filters.insert(tmp); #ifdef _WIN32 // Find the first file in the directory. WIN32_FIND_DATA ffd; #ifdef UNICODE HANDLE hFind = FindFirstFile((ConvertUTF8ToWString(directory) + L"\\*").c_str(), &ffd); #else HANDLE hFind = FindFirstFile((std::string(directory) + "\\*").c_str(), &ffd); #endif if (hFind == INVALID_HANDLE_VALUE) { FindClose(hFind); return 0; } // windows loop do { const std::string virtualName = ConvertWStringToUTF8(ffd.cFileName); #else struct dirent_large { struct dirent entry; char padding[FILENAME_MAX+1]; }; struct dirent_large diren; struct dirent *result = NULL; //std::string directoryWithSlash = directory; //if (directoryWithSlash.back() != '/') // directoryWithSlash += "/"; DIR *dirp = opendir(directory); if (!dirp) return 0; // non windows loop while (!readdir_r(dirp, (dirent*) &diren, &result) && result) { const std::string virtualName(result->d_name); #endif // check for "." and ".." if (((virtualName[0] == '.') && (virtualName[1] == '\0')) || ((virtualName[0] == '.') && (virtualName[1] == '.') && (virtualName[2] == '\0'))) continue; // Remove dotfiles (should be made optional?) if (virtualName[0] == '.') continue; FileInfo info; info.name = virtualName; std::string dir = directory; // Only append a slash if there isn't one on the end. size_t lastSlash = dir.find_last_of("/"); if (lastSlash != (dir.length() - 1)) dir.append("/"); info.fullName = dir + virtualName; info.isDirectory = isDirectory(info.fullName); info.exists = true; info.size = 0; if (!info.isDirectory) { std::string ext = getFileExtension(info.fullName); if (filter) { if (filters.find(ext) == filters.end()) continue; } } if (files) files->push_back(info); foundEntries++; #ifdef _WIN32 } while (FindNextFile(hFind, &ffd) != 0); FindClose(hFind); #else } closedir(dirp); #endif if (files) std::sort(files->begin(), files->end()); return foundEntries; }
size_t getFilesInDir(const char *directory, std::vector<FileInfo> *files, const char *filter) { size_t foundEntries = 0; std::set<std::string> filters; std::string tmp; if (filter) { while (*filter) { if (*filter == ':') { filters.insert(tmp); tmp = ""; } else { tmp.push_back(*filter); } filter++; } } #ifdef _WIN32 // Find the first file in the directory. WIN32_FIND_DATA ffd; #ifdef UNICODE HANDLE hFind = FindFirstFile((std::wstring(directory) + "\\*").c_str(), &ffd); #else HANDLE hFind = FindFirstFile((std::string(directory) + "\\*").c_str(), &ffd); #endif if (hFind == INVALID_HANDLE_VALUE) { FindClose(hFind); return 0; } // windows loop do { const std::string virtualName(ffd.cFileName); #else struct dirent_large { struct dirent entry; char padding[FILENAME_MAX+1]; }; struct dirent_large diren; struct dirent *result = NULL; DIR *dirp = opendir(directory); if (!dirp) return 0; // non windows loop while (!readdir_r(dirp, (dirent*) &diren, &result) && result) { const std::string virtualName(result->d_name); #endif // check for "." and ".." if (((virtualName[0] == '.') && (virtualName[1] == '\0')) || ((virtualName[0] == '.') && (virtualName[1] == '.') && (virtualName[2] == '\0'))) continue; // Remove dotfiles (should be made optional?) if (virtualName[0] == '.') continue; FileInfo info; info.name = virtualName; info.fullName = std::string(directory) + "/" + virtualName; info.isDirectory = isDirectory(info.fullName); info.exists = true; if (!info.isDirectory) { std::string ext = getFileExtension(info.fullName); if (filter) { if (filters.find(ext) == filters.end()) continue; } } files->push_back(info); #ifdef _WIN32 } while (FindNextFile(hFind, &ffd) != 0); FindClose(hFind); #else } closedir(dirp); #endif std::sort(files->begin(), files->end()); return foundEntries; }
int main(int argc, char *argv[ ]) { int i; FILE *infile, *outfile; if (argc < 3) { printf("XGMTool %s - Stephane Dallongeville - copyright 2016\n", version); printf("\n"); printf("Usage: xgmtool inputFile outputFile <options>\n"); printf("XGMTool can do the following operations:\n"); printf(" - Optimize and reduce size of Sega Megadrive VGM file\n"); printf(" Note that it won't work correctly on VGM file which require sub frame accurate timing.\n"); printf(" - Convert a Sega Megadrive VGM file to XGM file\n"); printf(" - Convert a XGM file to Sega Megadrive VGM file\n"); printf(" - Compile a XGM file into a binary file (XGC) ready to played by the Z80 XGM driver\n"); printf(" - Convert a XGC binary file to XGM file (experimental)\n"); printf(" - Convert a XGC binary file to Sega Megadrive VGM file (experimental)\n"); printf("\n"); printf("Optimize VGM:\n"); printf(" xgmtool input.vgm output.vgm\n"); printf("\n"); printf("Convert VGM to XGM:\n"); printf(" xgmtool input.vgm output.xgm\n"); printf("\n"); printf("Convert and compile VGM to binary/XGC:\n"); printf(" xgmtool input.vgm output.bin\n"); printf(" xgmtool input.vgm output.xgc\n"); printf("\n"); printf("Convert XGM to VGM:\n"); printf(" xgmtool input.xgm output.vgm\n"); printf("\n"); printf("Compile XGM to binary/XGC:\n"); printf(" xgmtool input.xgm output.bin\n"); printf(" xgmtool input.xgm output.xgc\n"); printf("\n"); printf("Convert XGC to XGM (experimental):\n"); printf(" xgmtool input.xgc output.xgm\n"); printf("\n"); printf("Compile XGC to VGM (experimental):\n"); printf(" xgmtool input.xgc output.vgm\n"); printf("\n"); printf("The action xmgtool performs is dependant from the input and output file extension.\n"); printf("Supported options:\n"); printf("-s\tenable silent mode (no message except error and warning).\n"); printf("-v\tenable verbose mode.\n"); printf("-n\tforce NTSC timing (only meaningful for VGM to XGM conversion).\n"); printf("-p\tforce PAL timing (only meaningful for VGM to XGM conversion).\n"); printf("-di\tdisable PCM sample auto ignore (it can help when PCM are not properly extracted).\n"); printf("-dr\tdisable PCM sample rate auto fix (it can help when PCM are not properly extracted).\n"); printf("-kf\tenable delayed KEY OFF event when we have KEY ON/OFF in a single frame (it can fix incorrect instrument sound).\n"); exit(1); } sys = SYSTEM_AUTO; silent = false; verbose = false; sampleIgnore = true; sampleRateFix = true; delayKeyOff = false; // Open source for binary read (will fail if file does not exist) if ((infile = fopen(argv[1], "rb")) == NULL) { printf("Error: the source file %s could not be opened\n", argv[1]); exit(2); } // test open output for write if ((outfile = fopen(argv[2], "wb")) == NULL) { printf("Error: the output file %s could not be opened\n", argv[2]); exit(3); } // can close fclose(outfile); // options for(i = 3; i < argc; i++) { if (!strcasecmp(argv[i], "-s")) { silent = true; verbose = false; } else if (!strcasecmp(argv[i], "-v")) { verbose = true; silent = false; } else if (!strcasecmp(argv[i], "-di")) sampleIgnore = false; else if (!strcasecmp(argv[i], "-dr")) sampleRateFix = false; else if (!strcasecmp(argv[i], "-kf")) delayKeyOff = true; else if (!strcasecmp(argv[i], "-n")) sys = SYSTEM_NTSC; else if (!strcasecmp(argv[i], "-p")) sys = SYSTEM_PAL; else printf("Warning: option %s not recognized (ignored)\n", argv[i]); } // silent mode has priority if (silent) verbose = false; char* inExt = getFileExtension(argv[1]); char* outExt = getFileExtension(argv[2]); int errCode = 0; if (!strcasecmp(inExt, "VGM")) { if ((!strcasecmp(outExt, "VGM")) || (!strcasecmp(outExt, "XGM")) || (!strcasecmp(outExt, "BIN")) || (!strcasecmp(outExt, "XGC"))) { // VGM optimization int inDataSize; unsigned char* inData; int outDataSize; unsigned char* outData; VGM* vgm; VGM* optVgm; // load file inData = readBinaryFile(argv[1], &inDataSize); if (inData == NULL) exit(1); // load VGM if (sys == SYSTEM_NTSC) inData[0x24] = 60; else if (sys == SYSTEM_PAL) inData[0x24] = 50; vgm = VGM_create1(inData, inDataSize, 0); if (vgm == NULL) exit(1); // optimize optVgm = VGM_createFromVGM(vgm, true); if (optVgm == NULL) exit(1); VGM_convertWaits(optVgm); VGM_cleanCommands(optVgm); VGM_cleanSamples(optVgm); VGM_fixKeyCommands(optVgm); // VGM output if (!strcasecmp(outExt, "VGM")) { // get byte array outData = VGM_asByteArray(optVgm, &outDataSize); if (outData == NULL) exit(1); // write to file writeBinaryFile(outData, outDataSize, argv[2]); } else { XGM* xgm; // convert to XGM xgm = XGM_createFromVGM(optVgm); if (xgm == NULL) exit(1); // XGM output if (!strcasecmp(outExt, "XGM")) { // get byte array outData = XGM_asByteArray(xgm, &outDataSize); } else { XGM* xgc; // convert to XGC (compiled XGM) xgc = XGC_create(xgm); if (xgc == NULL) exit(1); // get byte array outData = XGC_asByteArray(xgc, &outDataSize); } if (outData == NULL) exit(1); // write to file writeBinaryFile(outData, outDataSize, argv[2]); } } else { printf("Error: the output file %s is incorrect (should be a VGM, XGM or BIN/XGC file)\n", argv[2]); errCode = 4; } } else if (!strcasecmp(inExt, "XGM")) { if ((!strcasecmp(outExt, "VGM")) || (!strcasecmp(outExt, "BIN")) || (!strcasecmp(outExt, "XGC"))) { // XGM to VGM int inDataSize; unsigned char* inData; int outDataSize; unsigned char* outData; XGM* xgm; // load file inData = readBinaryFile(argv[1], &inDataSize); if (inData == NULL) exit(1); // load XGM xgm = XGM_createFromData(inData, inDataSize); if (xgm == NULL) exit(1); // VGM conversion if (!strcasecmp(outExt, "VGM")) { VGM* vgm; // convert to VGM vgm = VGM_createFromXGM(xgm); if (vgm == NULL) exit(1); // get byte array outData = VGM_asByteArray(vgm, &outDataSize); } else { XGM* xgc; // convert to XGC (compiled XGM) xgc = XGC_create(xgm); if (xgc == NULL) exit(1); // get byte array outData = XGC_asByteArray(xgc, &outDataSize); } if (outData == NULL) exit(1); // write to file writeBinaryFile(outData, outDataSize, argv[2]); } else { printf("Error: the output file %s is incorrect (should be a VGM or BIN/XGC file)\n", argv[2]); errCode = 4; } } else if (!strcasecmp(inExt, "XGC")) { if ((!strcasecmp(outExt, "VGM")) || (!strcasecmp(outExt, "XGM"))) { // XGC to XGM int inDataSize; unsigned char* inData; int outDataSize; unsigned char* outData; XGM* xgm; // load file inData = readBinaryFile(argv[1], &inDataSize); if (inData == NULL) exit(1); // load XGM xgm = XGM_createFromXGCData(inData, inDataSize); if (xgm == NULL) exit(1); // VGM conversion if (!strcasecmp(outExt, "VGM")) { VGM* vgm; // convert to VGM vgm = VGM_createFromXGM(xgm); if (vgm == NULL) exit(1); // get byte array outData = VGM_asByteArray(vgm, &outDataSize); } else { // get byte array outData = XGM_asByteArray(xgm, &outDataSize); } if (outData == NULL) exit(1); // write to file writeBinaryFile(outData, outDataSize, argv[2]); } else { printf("Error: the output file %s is incorrect (should be a XGM or VGM file)\n", argv[2]); errCode = 4; } } else { printf("Error: the input file %s is incorrect (should be a VGM, XGM or XGC file)\n", argv[1]); errCode = 4; } fclose(infile); remove("tmp.bin"); return errCode; }