Example #1
0
void ClientServer::handleFileFormatsResponse(FileFormats *response)
{
    QSettings settings;

    QStringList filters;
    for (int i=0; i<response->formats_size(); i++)
    {
        FileFormat format = response->formats(i);
        QString filter = tr("%1 (").arg(QString::fromStdString(format.name()));
        for (int j=0; j<format.extension_size(); j++)
        {
            filter += tr("*.%1").arg(QString::fromStdString(format.extension(j)));

            if (j != format.extension_size()-1)
                filter += " ";
        }

        filter += ")";
        filters << filter;
    }

    qDebug() << filters.join(";;");

    QString dir = settings.value(lastOpenDirSettingPath()).toString();
    FileDialog *remoteFileDialog = new FileDialog(m_channel, NULL,
            QString("Remote File Dialog"), dir, filters.join(";;"));

    connect(remoteFileDialog, SIGNAL(accepted()), this, SLOT(onAccepted()));
    connect(remoteFileDialog, SIGNAL(finished(int)), this, SLOT(onFinished(int)));

    remoteFileDialog->show();

    delete response;
}
Example #2
0
Defaults::Defaults(void)
{
FileFormat *filef;
FSSpec fspec;
McoStatus status;
int		magic_num;
int		version;
Str255  def = MONACO_DEFAULT;
Str255  fold = MONACO_FOLDER;

// set factory defaults
printer_type = 1;
input_type = DT_None;
patch_format = 1;
port = 1;

// now try to load in the user defults
filef = new FileFormat;

ptocstr(def);
ptocstr(fold);

status = filef->openFilefromPref(&fspec,(char*)def,(char*)fold);
if (status != MCO_SUCCESS) goto bail;

status = filef->relRead(sizeof(int),(char*)&magic_num);
if (status != MCO_SUCCESS) goto bail;

if (magic_num != DEFAULTS_MAGIC_NUM) goto bail;

status = filef->relRead(sizeof(int),(char*)&version);
if (status != MCO_SUCCESS) goto bail;

if (version > DEFAULTS_VERSION) goto bail;

status = filef->relRead(sizeof(int),(char*)&printer_type);
if (status != MCO_SUCCESS) goto bail;

status = filef->relRead(sizeof(int),(char*)&input_type);
if (status != MCO_SUCCESS) goto bail;

status = filef->relRead(sizeof(int),(char*)&patch_format);
if (status != MCO_SUCCESS) goto bail;

status = filef->relRead(sizeof(int),(char*)&port);
if (status != MCO_SUCCESS) goto bail;

filef->closeFile();

bail:
delete filef;

}
TEST(FileFormatManagerTest, readFile)
{
  FileFormat *format =
    FileFormatManager::instance().newFormatFromIdentifier("Avogadro: CML");
  EXPECT_TRUE(format != NULL);
  if (!format)
    return;
  Molecule molecule;
  format->readFile(std::string(AVOGADRO_DATA) + "/data/ethane.cml", molecule);
  delete format;
  format = NULL;

  EXPECT_EQ(molecule.data("name").type(), Variant::String);
  EXPECT_EQ(molecule.data("name").toString(), "Ethane");

  EXPECT_EQ(molecule.data("inchi").type(), Variant::String);
  EXPECT_EQ(molecule.data("inchi").toString(), "1/C2H6/c1-2/h1-2H3");
}
 void BuildFileOps(OpRcPtrVec & ops,
                   const Config& config,
                   const ConstContextRcPtr & context,
                   const FileTransform& fileTransform,
                   TransformDirection dir)
 {
     std::string src = fileTransform.getSrc();
     if(src.empty())
     {
         std::ostringstream os;
         os << "The transform file has not been specified.";
         throw Exception(os.str().c_str());
     }
     
     std::string filepath = context->resolveFileLocation(src.c_str());
     CreateFileNoOp(ops, filepath);
     
     FileFormat* format = NULL;
     CachedFileRcPtr cachedFile;
     
     GetCachedFileAndFormat(format, cachedFile, filepath);
     if(!format)
     {
         std::ostringstream os;
         os << "The specified file load ";
         os << filepath << " appeared to succeed, but no format ";
         os << "was returned.";
         throw Exception(os.str().c_str());
     }
     
     if(!cachedFile.get())
     {
         std::ostringstream os;
         os << "The specified file load ";
         os << filepath << " appeared to succeed, but no cachedFile ";
         os << "was returned.";
         throw Exception(os.str().c_str());
     }
     
     format->BuildFileOps(ops,
                          config, context,
                          cachedFile, fileTransform,
                          dir);
 }
Example #5
0
    bool
SimpleReadWriter::writeHeader(
    const ReaderContext& context,
    bool sorted,
    int argc,
    const char **argv,
    const char *version,
    const char *rgLine,
	bool omitSQLines)
{
    char* buffer;
    size_t size;
    size_t used;

    char *localBuffer = NULL;

	writer->inHeader(true);
    if (! writer->getBuffer(&buffer, &size)) {
        return false;
    }

    char *writerBuffer = buffer;
    size_t writerBufferSize = size;

	while (!format->writeHeader(context, buffer, size, &used, sorted, argc, argv, version, rgLine, omitSQLines)) {
        delete[] localBuffer;
        size = 2 * size;
        localBuffer = new char[size];
        buffer = localBuffer;
    }

    if (NULL == localBuffer) {
        _ASSERT(writerBuffer == buffer);
        writer->advance((unsigned)used, 0);
        writer->nextBatch();
    } else {
        size_t bytesRemainingToWrite = used;
        size_t bytesWritten = 0;
        while (bytesRemainingToWrite > 0) {
            size_t bytesToWrite = __min(bytesRemainingToWrite, writerBufferSize);
            memcpy(writerBuffer, localBuffer + bytesWritten, bytesToWrite);
            writer->advance(bytesToWrite);
            writer->nextBatch();
            if (!writer->getBuffer(&writerBuffer, &writerBufferSize)) {
                return false;
            }
            bytesWritten += bytesToWrite;
            bytesRemainingToWrite -= bytesToWrite;
        }

        delete[] localBuffer;
    }

	writer->inHeader(false);
    return true;
}
Example #6
0
Palette* load_palette(const char *filename)
{
  std::string ext = base::string_to_lower(base::get_file_extension(filename));
  Palette* pal = NULL;

  if (ext == "col") {
    pal = doc::file::load_col_file(filename);
  }
  else if (ext == "gpl") {
    pal = doc::file::load_gpl_file(filename);
  }
  else {
    FileFormat* ff = FileFormatsManager::instance()->getFileFormatByExtension(ext.c_str());
    if (ff->support(FILE_SUPPORT_LOAD)) {
      FileOp* fop = fop_to_load_document(NULL, filename,
        FILE_LOAD_SEQUENCE_NONE |
        FILE_LOAD_ONE_FRAME);
      if (fop && !fop->has_error()) {
        fop_operate(fop, NULL);
        fop_post_load(fop);

        if (fop->document &&
            fop->document->sprite() &&
            fop->document->sprite()->getPalette(FrameNumber(0))) {
          pal = new Palette(
            *fop->document->sprite()->getPalette(FrameNumber(0)));

          // TODO remove this line when support for palettes with less
          // than 256 colors is added.
          pal->resize(Palette::MaxColors);
        }

        delete fop->document;
        fop_done(fop);
      }
    }
  }

  if (pal)
    pal->setFilename(filename);

  return pal;
}
Example #7
0
/********************************************************************************************

>	FormatEntry* FilterManager::FindFormatEntryFromName(const StringBase& FormatName) const

	Author:		Colin_Barfoot (Xara Group Ltd) <*****@*****.**>
	Created:	10/12/96
	Inputs:		FormatName:	The name of a FileFormat given in the FileFormat's constructor
							which has subsequently been Added to this FilterManager.
	Returns:	A pointer to the FileFormat with the name given or NULL if none was found
	Purpose:	Finds the one & only FileFormat with the given FormatName
				Used by Xtra's mainly

********************************************************************************************/
FormatEntry* FilterManager::FindFormatEntryFromName(const StringBase& FormatName) const
{
	for (UINT32 index = 0; index < GetLastFormatID(); ++index)
	{
		FormatEntry* pFormatEntry = GetFormats()[index];
		if (pFormatEntry != NULL)
		{
			FileFormat* pFormat = pFormatEntry->GetFormat();
			if (pFormat->GetName() == FormatName)
			{
				return pFormatEntry;
			}
		}
		else
		{
			// we'll ignore this one
		}
	}

	return NULL;
}
Example #8
0
bool save_palette(const char *filename, Palette* pal)
{
  std::string ext = base::string_to_lower(base::get_file_extension(filename));
  bool success = false;

  if (ext == "col") {
    success = doc::file::save_col_file(pal, filename);
  }
  else if (ext == "gpl") {
    success = doc::file::save_gpl_file(pal, filename);
  }
  else {
    FileFormat* ff = FileFormatsManager::instance()->getFileFormatByExtension(ext.c_str());
    if (ff->support(FILE_SUPPORT_SAVE)) {
      app::Context tmpContext;
      doc::Document* doc = tmpContext.documents().add(
        16, 16, doc::ColorMode::INDEXED,
        Palette::MaxColors);

      Sprite* sprite = doc->sprite();
      doc->sprite()->setPalette(pal, false);

      LayerImage* layer = dynamic_cast<LayerImage*>(sprite->folder()->getFirstLayer());
      Image* image = layer->getCel(FrameNumber(0))->image();

      int x, y, c;
      for (y=c=0; y<16; y++)
        for (x=0; x<16; x++)
          image->putPixel(x, y, c++);

      doc->setFilename(filename);
      success = (save_document(&tmpContext, doc) == 0);

      doc->close();
      delete doc;
    }
  }

  return success;
}
Example #9
0
 void Baker::bake(std::ostream & os) const
 {
     FileFormat* fmt = FormatRegistry::GetInstance().getFileFormatByName(getImpl()->formatName_);
     
     if(!fmt)
     {
         std::ostringstream err;
         err << "The format named '" << getImpl()->formatName_;
         err << "' could not be found. ";
         throw Exception(err.str().c_str());
     }
     
     try
     {
         fmt->Write(*this, getImpl()->formatName_, os);
     }
     catch(std::exception & e)
     {
         std::ostringstream err;
         err << "Error baking " << getImpl()->formatName_ << ":";
         err << e.what();
         throw Exception(err.str().c_str());
     }
     
     // 
     // TODO:
     // 
     // - throw exception when we don't have inputSpace and targetSpace
     //   at least set
     // - check limits of shaper and target, throw exception if we can't
     //   write that much data in x format
     // - check that the shaper is 1D transform only, throw excpetion
     // - check the file format supports shapers, 1D and 3D
     // - add some checks to make sure we are monotonic
     // - deal with the case of writing out non cube formats (1D only)
     // - do a compare between ocio transform and output lut transform
     //   throw error if we going beyond tolerance
     //
 }
Example #10
0
bool sameEncoding(const FileFormat & src, const FileFormat & tgt)
{
    if (src.equals(tgt))
        return true;
    switch (src.type)
    {
    case FFTutf8n:
        return (tgt.type == FFTutf8);
    case FFTutf16be:
        return (tgt.type == FFTutf16);
    case FFTutf32be:
        return (tgt.type == FFTutf32);
    }
    return false;
}
bool FileFormatManager::removeFormat(const std::string &identifier)
{
  FormatIdVector ids = m_identifiers[identifier];
  m_identifiers.erase(identifier);

  if (ids.empty())
    return false;

  for (FormatIdVector::const_iterator it = ids.begin(), itEnd = ids.end();
       it != itEnd; ++it) {
    FileFormat *fmt = m_formats[*it];

    if (fmt == NULL)
      continue;

    removeFromMap(m_mimeTypes, fmt->mimeTypes(), *it);
    removeFromMap(m_fileExtensions, fmt->fileExtensions(), *it);

    m_formats[*it] = NULL;
    delete fmt;
  }

  return true;
}
Example #12
0
bool processPartitionCommand(ISocket * masterSocket, MemoryBuffer & msg, MemoryBuffer & results)
{
    FileFormat srcFormat;
    FileFormat tgtFormat;
    unsigned whichInput;
    RemoteFilename fullPath;
    offset_t totalSize;
    offset_t thisOffset;
    offset_t thisSize;
    unsigned thisHeaderSize;
    unsigned numParts;
    bool compressedInput = false;
    unsigned compatflags = 0;  

    srcFormat.deserialize(msg);
    tgtFormat.deserialize(msg);
    msg.read(whichInput);
    fullPath.deserialize(msg);
    msg.read(totalSize);
    msg.read(thisOffset);
    msg.read(thisSize);
    msg.read(thisHeaderSize);
    msg.read(numParts);
    if (msg.remaining())
        msg.read(compressedInput);
    if (msg.remaining())
        msg.read(compatflags); // not yet used
    StringAttr decryptkey;
    if (msg.remaining())
        msg.read(decryptkey);
    if (msg.remaining())
    {
        srcFormat.deserializeExtra(msg, 1);
        tgtFormat.deserializeExtra(msg, 1);
    }

    StringBuffer text;
    fullPath.getRemotePath(text);
    LOG(MCdebugProgress, unknownJob, "Process partition %d(%s)", whichInput, text.str());
    Owned<IFormatProcessor> processor = createFormatProcessor(srcFormat, tgtFormat, true);
    Owned<IOutputProcessor> target = createOutputProcessor(tgtFormat);
    processor->setTarget(target);

    processor->setPartitionRange(totalSize, thisOffset, thisSize, thisHeaderSize, numParts);
    processor->setSource(whichInput, fullPath, compressedInput, decryptkey);
    processor->calcPartitions(NULL);

    PartitionPointArray partition;
    processor->getResults(partition);

    serialize(partition, results);
    return true;
}
Example #13
0
    bool
SimpleReadWriter::writePairs(
    const ReaderContext& context, 
    Read **reads /* array of size NUM_READS_PER_PAIR */, 
    PairedAlignmentResult *result, 
    int nResults,
    SingleAlignmentResult **singleResults /* array of size NUM_READS_PER_PAIR*/, 
    int *nSingleResults /* array of size NUM_READS_PER_PAIR*/, 
    bool firstIsPrimary)
{
    bool retVal = false;
    //
    // We need to write all alignments for the pair into the same buffer, so that a write from
    // some other thread doesn't separate them.  We make two passes, trying to write into the 
    // existing buffer, and then into a clean one.  If that doesn't work, abort the alignment
    // run and ask for a bigger write buffer.
    //
    const int staticUsedBufferSize = 2000;
    size_t staticUsedBuffer[NUM_READS_PER_PAIR][staticUsedBufferSize];
    GenomeLocation staticLocationBuffer[NUM_READS_PER_PAIR][staticUsedBufferSize];

    GenomeLocation *finalLocations[NUM_READS_PER_PAIR];
    size_t *usedBuffer[NUM_READS_PER_PAIR];
    if (nResults + nSingleResults[0] <= staticUsedBufferSize && nResults + nSingleResults[1] <= staticUsedBufferSize) {
        usedBuffer[0] = staticUsedBuffer[0];
        usedBuffer[1] = staticUsedBuffer[1];
        finalLocations[0] = staticLocationBuffer[0];
        finalLocations[1] = staticLocationBuffer[1];
    } else {
        usedBuffer[0] = new size_t[nResults * NUM_READS_PER_PAIR + nSingleResults[0] + nSingleResults[1]];
        usedBuffer[1] = usedBuffer[0] + nResults + nSingleResults[0];
        finalLocations[0] = new GenomeLocation[nResults * NUM_READS_PER_PAIR + nSingleResults[0] + nSingleResults[1]];
        finalLocations[1] = finalLocations[0] + nResults + nSingleResults[0];
    }


    //
    // For paired reads, we need to have the same QNAME for both of them, and it needs to be unique among all other
    // reads in the dataset.  For now, all we do is see if the read names end in /1 and /2, and if so truncate them.
    //
    size_t idLengths[NUM_READS_PER_PAIR];
    idLengths[0] = reads[0]->getIdLength();
    idLengths[1] = reads[1]->getIdLength();
    if (idLengths[0] == idLengths[1] && idLengths[0] > 2 && reads[0]->getId()[idLengths[0]-2] == '/' && reads[1]->getId()[idLengths[0]-2] == '/') {
        char lastChar0, lastChar1;
        lastChar0 = reads[0]->getId()[idLengths[0] - 1];
        lastChar1 = reads[1]->getId()[idLengths[1] - 1];
        if ((lastChar0 == '1' || lastChar0 == '2') && (lastChar1 == '1' || lastChar1 == '2') && 
            lastChar0 != lastChar1) {
                idLengths[0] -= 2;
                idLengths[1] -= 2;
        }
    }

    for (int pass = 0; pass < 2; pass++) {

        char* buffer;
        size_t size;
        size_t used = 0;

        bool fitInBuffer = true;

        if (!writer->getBuffer(&buffer, &size)) {
            goto done;
        }

        //
        // Write all of the pair alignments into the buffer.
        //
        for (int whichAlignmentPair = 0; whichAlignmentPair < nResults; whichAlignmentPair++) {
            reads[0]->setAdditionalFrontClipping(0);
            reads[1]->setAdditionalFrontClipping(0);

            GenomeLocation locations[2];
            locations[0] = result[whichAlignmentPair].status[0] != NotFound ? result[whichAlignmentPair].location[0] : InvalidGenomeLocation;
            locations[1] = result[whichAlignmentPair].status[1] != NotFound ? result[whichAlignmentPair].location[1] : InvalidGenomeLocation;

            int writeOrder[2];  // The order in which we write the reads, which is just numerical by genome location.  SO writeOrder[0] gets written first, and writeOrder[1] second.

            if (locations[0] <= locations[1]) {
                writeOrder[0] = 0;
                writeOrder[1] = 1;
            } else {
                writeOrder[0] = 1;
                writeOrder[1] = 0;
            }

            bool secondReadLocationChanged;
            int cumulativePositiveAddFrontClipping[NUM_READS_PER_PAIR] = { 0, 0 };

            do {
                size_t tentativeUsed = 0;
                secondReadLocationChanged = false;

                for (int firstOrSecond = 0; firstOrSecond < NUM_READS_PER_PAIR; firstOrSecond++) {  // looping over the order in which the reads are written, not the order in which they arrived
                    int whichRead = writeOrder[firstOrSecond];
                    //
                    // Loop until we get a write with no additional front clipping.
                    //
                    int addFrontClipping = 0;

                    while (!format->writeRead(context, &lvc, buffer + used + tentativeUsed, size - used - tentativeUsed, &usedBuffer[firstOrSecond][whichAlignmentPair],
                        idLengths[whichRead], reads[whichRead], result[whichAlignmentPair].status[whichRead], result[whichAlignmentPair].mapq[whichRead], locations[whichRead], result[whichAlignmentPair].direction[whichRead],
                        whichAlignmentPair != 0 || !firstIsPrimary, &addFrontClipping, true, writeOrder[firstOrSecond] == 0,
                        reads[1 - whichRead], result[whichAlignmentPair].status[1 - whichRead], locations[1 - whichRead], result[whichAlignmentPair].direction[1 - whichRead],
                        result[whichAlignmentPair].alignedAsPair)) {

                        if (0 == addFrontClipping || locations[whichRead] == InvalidGenomeLocation) {
                            //
                            // We failed because we ran out of buffer.
                            //
                            goto blownBuffer;
                        }

                        if (1 == firstOrSecond) {
                            //
                            // If the location of the second read changed, we need to redo the first one as well, because it includes an offset to the second read
                            //
                            secondReadLocationChanged = true;
                        }

                        const Genome::Contig *originalContig = genome->getContigAtLocation(locations[whichRead]);
                        const Genome::Contig *newContig = genome->getContigAtLocation(locations[whichRead] + addFrontClipping);
                        if (newContig != originalContig || NULL == newContig || locations[whichRead] + addFrontClipping > originalContig->beginningLocation + originalContig->length - genome->getChromosomePadding()) {
                            //
                            // Altering this would push us over a contig boundary.  Just give up on the read.
                            //
                            result[whichAlignmentPair].status[whichRead] = NotFound;
                            result[whichAlignmentPair].location[whichRead] = InvalidGenomeLocation;
                            locations[whichRead] = InvalidGenomeLocation;
                        } else {
                            if (addFrontClipping > 0) {
                                cumulativePositiveAddFrontClipping[firstOrSecond] += addFrontClipping;
                                reads[whichRead]->setAdditionalFrontClipping(cumulativePositiveAddFrontClipping[firstOrSecond]);
                            }
                            locations[whichRead] += addFrontClipping;
                        }
                    } // While formatting didn't work
                    tentativeUsed += usedBuffer[firstOrSecond][whichAlignmentPair];
                } // for first or second read

            } while (secondReadLocationChanged);
            used += usedBuffer[0][whichAlignmentPair] + usedBuffer[1][whichAlignmentPair];

            //
            // Both reads are written into the buffer.  Save the final locations we used for when we commit.
            //
            for (int whichRead = 0; whichRead < NUM_READS_PER_PAIR; whichRead++) {
                finalLocations[whichRead][whichAlignmentPair] = locations[whichRead];
            }
        } // for each pair.

        //
        // Now write the single alignments.
        //
        for (int whichRead = 0; whichRead < NUM_READS_PER_PAIR; whichRead++) {
            for (int whichAlignment = 0; whichAlignment < nSingleResults[whichRead]; whichAlignment++) {
                int addFrontClipping;
                reads[whichRead]->setAdditionalFrontClipping(0);
                GenomeLocation location = singleResults[whichRead][whichAlignment].status != NotFound ? singleResults[whichRead][whichAlignment].location : InvalidGenomeLocation;
                int cumulativePositiveAddFrontClipping = 0;

                while (!format->writeRead(context, &lvc, buffer + used, size - used, &usedBuffer[whichRead][nResults + whichAlignment], reads[whichRead]->getIdLength(),
                    reads[whichRead], singleResults[whichRead][whichAlignment].status, singleResults[whichRead][whichAlignment].mapq, location, singleResults[whichRead][whichAlignment].direction,
                    true, &addFrontClipping)) {

                    if (0 == addFrontClipping) {
                        goto blownBuffer;
                    }

                    const Genome::Contig *originalContig = genome->getContigAtLocation(location);
                    const Genome::Contig *newContig = genome->getContigAtLocation(location + addFrontClipping);
                    if (newContig != originalContig || NULL == newContig || location + addFrontClipping > originalContig->beginningLocation + originalContig->length - genome->getChromosomePadding()) {
                        //
                        // Altering this would push us over a contig boundary.  Just give up on the read.
                        //
                        singleResults[whichRead][whichAlignment].status = NotFound;
                        location = InvalidGenomeLocation;
                    } else {
                        if (addFrontClipping > 0) {
                            cumulativePositiveAddFrontClipping += addFrontClipping;
                            reads[whichRead]->setAdditionalFrontClipping(cumulativePositiveAddFrontClipping);
                        }
                        location += addFrontClipping;
                    }
                } 

                finalLocations[whichRead][nResults + whichAlignment] = location;
                used += usedBuffer[whichRead][nResults + whichAlignment];
            } // For each single alignment of a read
        } // For each read

        //
        // They all fit into the buffer.
        //

        //
        // Commit the updates for the pairs.
        //
        for (int whichReadPair = 0; whichReadPair < nResults; whichReadPair++) {
            for (int firstOrSecond = 0; firstOrSecond < NUM_READS_PER_PAIR; firstOrSecond++) {
                // adjust for write order
                int writeFirstOrSecond = (!!firstOrSecond) ^ (finalLocations[0][whichReadPair] > finalLocations[1][whichReadPair]); // goofy looking !! converts int to bool
                writer->advance((unsigned)usedBuffer[firstOrSecond][whichReadPair],
                    finalLocations[writeFirstOrSecond][whichReadPair] == InvalidGenomeLocation ? finalLocations[1 - writeFirstOrSecond][whichReadPair] : finalLocations[writeFirstOrSecond][whichReadPair]);
            }
        }

        //
        // Now commit the updates for the single reads.
        //
        for (int whichRead = 0; whichRead < NUM_READS_PER_PAIR; whichRead++) {
            for (int whichAlignment = 0; whichAlignment < nSingleResults[whichRead]; whichAlignment++) {
                writer->advance((unsigned)usedBuffer[whichRead][nResults + whichAlignment], finalLocations[whichRead][nResults + whichAlignment]);
            }
        }

        retVal = true;
        break;

blownBuffer:
        if (pass > 0) {
            WriteErrorMessage("Unable to fit all alignments for one read pair into a single write buffer.  Increase the size of the write buffer with -wbs, or reduce the number of alignments with -om or -omax\n");
            WriteErrorMessage("Read id: '%.*s'\n", reads[0]->getIdLength(), reads[0]->getId());
            soft_exit(1);
        }

        if (!writer->nextBatch()) {
            goto done;
        }
            
    } // For each buffer full pass



done:
    if (usedBuffer[0] != staticUsedBuffer[0]) {
        delete[] usedBuffer[0];
        usedBuffer[0] = usedBuffer[1] = NULL;

        delete[] finalLocations[0];
        finalLocations[0] = finalLocations[1] = NULL;
    }

    reads[0]->setAdditionalFrontClipping(0);
    reads[1]->setAdditionalFrontClipping(0);

    return retVal;
}
Example #14
0
McoStatus PrinterType::Save(FSSpec *fspec)
{
	int i;
	McoStatus status = MCO_SUCCESS;
	FileFormat *filef;
	int   magic_num = PRINTERTYPE_MAGICNUM;
	int   version = PRINTERTYPE_VERSION;
	
	filef = new FileFormat;

//	status = filef->createFilewithtype(fspec,smSystemScript,'Mprn','MCO6');
//	if (status != MCO_SUCCESS) goto bail;

	status = filef->openFile(fspec);
	if (status != MCO_SUCCESS) goto bail;

	status = filef->relWrite(sizeof(int),(char*)&magic_num);
	if (status != MCO_SUCCESS) goto bailclose;

	status = filef->relWrite(sizeof(int),(char*)&version);
	if (status != MCO_SUCCESS) goto bailclose;

	status = filef->relWrite(sizeof(ConData),(char*)&data);
	if (status != MCO_SUCCESS) goto bailclose;

	status = filef->relWrite(sizeof(int),(char*)&num_hands);
	if (status != MCO_SUCCESS) goto bailclose;

	status = filef->relWrite(sizeof(double)*31,(char*)x_hands);
	if (status != MCO_SUCCESS) goto bailclose;

	status = filef->relWrite(sizeof(double)*31,(char*)y_hands);
	if (status != MCO_SUCCESS) goto bailclose;
	
	status = filef->relWrite(sizeof(int),(char*)&sim_num);
	if (status != MCO_SUCCESS) goto bailclose;

	status = filef->relWrite(sizeof(int),(char*)&num_tweaks);
	if (status != MCO_SUCCESS) goto bailclose;

	for (i=0; i<num_tweaks; i++)
		{
		status = filef->relWrite(sizeof(Tweak_Element),(char*)tweaks[i]);
		if (status != MCO_SUCCESS) goto bailclose;
		}

	filef->setInfo(fspec,MONACO_SIG,'MCO6');

	bailclose:
	filef->closeFile();
	bail:
	delete filef;
	return status;
}
Example #15
0
FileFormatInstance::FileFormatInstance( const FileFormat& fmt ) :
   UIObject( (*API->FileFormat->CreateFileFormatInstance)( ModuleHandle(), fmt.Handle() ) )
{
   if ( IsNull() )
      throw APIFunctionError( "CreateFileFormatInstance" );
}
Example #16
0
    bool
SimpleReadWriter::writeReads(
    const ReaderContext& context, 
    Read *read, 
    SingleAlignmentResult *results, 
    int nResults,
    bool firstIsPrimary)
{
    char* buffer;
    size_t size;
    size_t used;
    bool result = false;

    for (int i = 0; i < nResults; i++) {
        if (results[i].status == NotFound) {
            results[i].location = InvalidGenomeLocation;
        }
    }

    //
    // We need to keep track of the offsets of all of the alignments in the output buffer so we can commit them.  However,
    // we want to avoid dynamic memory allocation as much as possible.  So, we have a static buffer on the stack that's big enough
    // for the great majority of cases, and then allocate dynamically if that's too small.  Makes for annoying, but efficient
    // code.
    //

    const int staticUsedBufferSize = 2000;
    size_t staticUsedBuffer[staticUsedBufferSize];

    GenomeLocation staticFinalLocationsBuffer[staticUsedBufferSize];

    size_t *usedBuffer;
    GenomeLocation *finalLocations;
    if (nResults <= staticUsedBufferSize) {
        usedBuffer = staticUsedBuffer;
        finalLocations = staticFinalLocationsBuffer;
    } else {
        usedBuffer = new size_t[nResults];
        finalLocations = new GenomeLocation[nResults];
    }


    for (int pass = 0; pass < 2; pass++) { // Make two passes, one with whatever buffer space is left and one with a clean buffer.
        bool blewBuffer = false;

        if (!writer->getBuffer(&buffer, &size)) {
            goto done;
        }

        used = 0;

        for (int whichResult = 0; whichResult < nResults; whichResult++) {
            int addFrontClipping = 0;
            read->setAdditionalFrontClipping(0);
            int cumulativeAddFrontClipping = 0;
            finalLocations[whichResult] = results[whichResult].location;

            while (!format->writeRead(context, &lvc, buffer + used, size - used, &usedBuffer[whichResult], read->getIdLength(), read, results[whichResult].status,
                results[whichResult].mapq, finalLocations[whichResult], results[whichResult].direction, (whichResult > 0) || !firstIsPrimary, &addFrontClipping)) {

                if (0 == addFrontClipping) {
                    blewBuffer = true;
                    break;
                }

                // redo if read modified (e.g. to add soft clipping, or move alignment for a leading I.
                const Genome::Contig *originalContig = results[whichResult].status == NotFound ? NULL
                    : genome->getContigAtLocation(results[whichResult].location);
                const Genome::Contig *newContig = results[whichResult].status == NotFound ? NULL
                    : genome->getContigAtLocation(results[whichResult].location + addFrontClipping);
                if (newContig == NULL || newContig != originalContig || finalLocations[whichResult] + addFrontClipping > originalContig->beginningLocation + originalContig->length - genome->getChromosomePadding()) {
                    //
                    // Altering this would push us over a contig boundary.  Just give up on the read.
                    //
                    results[whichResult].status = NotFound;
                    results[whichResult].location = InvalidGenomeLocation;
                    finalLocations[whichResult] = InvalidGenomeLocation;
                } else {
                    cumulativeAddFrontClipping += addFrontClipping;
                    if (addFrontClipping > 0) {
                        read->setAdditionalFrontClipping(cumulativeAddFrontClipping);
                    }
                    finalLocations[whichResult] = results[whichResult].location + cumulativeAddFrontClipping;
                }
            } // while formatting doesn't work

            if (blewBuffer) {
                break;
            }

            used += usedBuffer[whichResult];
            _ASSERT(used <= size);

            if (used > 0xffffffff) {
                 WriteErrorMessage("SimpleReadWriter:writeReads: used too big\n");
                 soft_exit(1);
            }
        } // for each result.

        if (!blewBuffer) {
            //
            // Everything worked OK.
            //
            for (int whichResult = 0; whichResult < nResults; whichResult++) {
                writer->advance((unsigned)usedBuffer[whichResult], finalLocations[whichResult]);
            }
            result = true;
            goto done;
        }

        if (pass == 1) {
            WriteErrorMessage("Failed to write into fresh buffer; trying providing the -wbs switch with a larger value\n");
            soft_exit(1);
        }

        if (!writer->nextBatch()) {
            goto done;
        }
    } // for each pass (i.e., not empty, empty buffer)
    
done:
    if (usedBuffer != staticUsedBuffer) {
        delete[] usedBuffer;
        usedBuffer = NULL;

        delete[] finalLocations;
        finalLocations = NULL;
    }

    read->setAdditionalFrontClipping(0);

    return result;
}
Example #17
0
void FileDialog_import(EditorState *state)
{
	std::string path = getSaveLoadDirectory(state->settings->get("save_directory"),
			state->isInstalled);

	const char* filters[] = {"*.nbe"};
	const char *cfile = tinyfd_openFileDialog("Import Nodes",
			path.c_str(), 1, filters, 0);

	if (!cfile)
		return;

	std::string file = cfile;

	if (file == "")
		return;


	std::cerr << file.c_str() << std::endl;

	// Get file parser
	FileFormat *parser = getFromType(FILE_FORMAT_NBE, state);
	if (!parser) {
		state->device->getGUIEnvironment()->addMessageBox(L"Unable to open",
		L"File format does not exist.");
		return;
	}

	// Get directory, and load
	std::cerr << "Reading from " << file << std::endl;
	Project *tmp = parser->read(file, state->project);
	if (tmp) {
		state->project->remesh();
	} else {
		switch(parser->error_code) {
		case EFFE_IO_ERROR:
			state->device->getGUIEnvironment()->addMessageBox(L"Unable to open",
					L"Failed to open the file\n\t(Does it not exist, or is it readonly?)");
			break;
		case EFFE_READ_OLD_VERSION:
			state->device->getGUIEnvironment()->addMessageBox(L"Unable to open",
				L"This file is outdated and is not supported");
			break;
		case EFFE_READ_NEW_VERSION:
			state->device->getGUIEnvironment()->addMessageBox(L"Unable to open",
				L"This file was created with a new version of NBE\n\t(Update your copy)");
			break;
		case EFFE_READ_PARSE_ERROR:
			state->device->getGUIEnvironment()->addMessageBox(L"Unable to open",
				L"An error occurred while reading the file - it may be corrupted\n\t(This should never happen)");
			break;
		case EFFE_READ_WRONG_TYPE:
			state->device->getGUIEnvironment()->addMessageBox(L"Unable to open",
				L"The file is not in the correct format\n\t(Are you opening the wrong type of file?)");
			break;
		default:
			state->device->getGUIEnvironment()->addMessageBox(L"Unable to open",
				L"Unknown error");
			break;
		}
		delete parser;
		parser = NULL;
	}
}
Example #18
0
// The event handler for the main menu
McoStatus	ToneTab::DoEvents(short item, Point clickPoint, WindowCode *wc, int32 *numwc, void **data,Boolean &changed)
{
int					didit = 0;
int		i,j;
McoStatus 			status = MCO_SUCCESS;	
short 				item2 = item - startNum;
Str255				prompt;
StandardFileReply 	soutReply,sinReply;
Str255				outname = "\p";
SFTypeList			filelist;
Str255				inname;
Rect r1;
short	iType;
Handle	iHandle;
WindowPtr	oldP;

GetPort(&oldP);
SetPort( dp ) ;

	// no codes passed back
	*numwc = 0;
	
	for (i=0; i<numControls; i++) 
		{
		status = controls[i]->DoEvents(item,clickPoint,wc,numwc,data,changed,&didit);
		if (status) return status;
		if (changed) 
			{
			doc->changedLinearTone = 1;
			last_changed = 1;
			CopyOutofControl(i);
			CopyIntoControl(i);
			}
		else last_changed = 0;		
		if (didit) return status;
		}

	if (item2 == EXPORT)
		{
		if (doc->calCurves)
			{
			GetIndString(prompt,PROMPT_STRINGS,STANDARD_PROMPT);
			StandardPutFile(prompt, outname, &soutReply);
			if(soutReply.sfGood)
				{
				memcpy(outname, soutReply.sfFile.name, *(soutReply.sfFile.name)+1);	
				PathNameFromDirID(soutReply.sfFile.parID, soutReply.sfFile.vRefNum, outname);
				ptocstr(outname);
				status = doc->calCurves->exportTone((char*)outname);
				if (status) McoErrorAlert(status);
				else 
					{
					FileFormat ff;
	
					ff.setInfo(&soutReply.sfFile,MONACO_SIG,'TEXT');
					}
				}
			}
		}
	else if (item2 == IMPORT)
		{
		if (doc->calCurves)
			{	
			filelist[0] = 'TEXT';
			StandardGetFile(0L, 1, filelist, &sinReply);
			if(sinReply.sfGood)	
				{
				memcpy(inname, sinReply.sfFile.name, *(sinReply.sfFile.name)+1);
				PathNameFromDirID(sinReply.sfFile.parID, sinReply.sfFile.vRefNum, inname);
				ptocstr(inname);	
				status = doc->calCurves->importTone((char*)inname);
				if (status) McoErrorAlert(status);
				else 
					{
					CopyIntoControl(-1);
					doc->changedLinearTone = 1;
					}
				status = MCO_SUCCESS;
				}
			}
		}
	else
		{
		GetDItem (dp, DESCRIPTION+startNum, &iType, (Handle*)&iHandle, &r1);
		GetIText(iHandle,inname);
		if (inname[0] > 100) inname[0] = 100;
		ptocstr(inname);
		strcpy(doc->printData->setting.toneDesc,(char*)inname);
		}
	SetPort(oldP);		
	return status;
}
Example #19
0
McoStatus PrinterType::Save(void)
{
	int i;
	StandardFileReply 	soutReply;
	Str255				prompt;
	Str255				outname = "\p";
	McoStatus status = MCO_SUCCESS;
	FileFormat *filef;
	int   magic_num = PRINTERTYPE_MAGICNUM;
	int   version = PRINTERTYPE_VERSION;
	
	GetIndString(prompt,PROMPT_STRINGS,SETTINGS_PROMPT);
	
	StandardPutFile(prompt, outname, &soutReply);
	if(!soutReply.sfGood) return MCO_CANCEL;



	filef = new FileFormat;

	status = filef->createFilewithtype(&soutReply.sfFile,soutReply.sfScript,MONACO_SIG,'MCO6');
	if (status != MCO_SUCCESS) goto bail;

	status = filef->relWrite(sizeof(int),(char*)&magic_num);
	if (status != MCO_SUCCESS) goto bailclose;

	status = filef->relWrite(sizeof(int),(char*)&version);
	if (status != MCO_SUCCESS) goto bailclose;

	status = filef->relWrite(sizeof(ConData),(char*)&data);
	if (status != MCO_SUCCESS) goto bailclose;

	status = filef->relWrite(sizeof(int),(char*)&num_hands);
	if (status != MCO_SUCCESS) goto bailclose;

	status = filef->relWrite(sizeof(double)*31,(char*)x_hands);
	if (status != MCO_SUCCESS) goto bailclose;

	status = filef->relWrite(sizeof(double)*31,(char*)y_hands);
	if (status != MCO_SUCCESS) goto bailclose;
	
	status = filef->relWrite(sizeof(int),(char*)&sim_num);
	if (status != MCO_SUCCESS) goto bailclose;

	status = filef->relWrite(sizeof(int),(char*)&num_tweaks);
	if (status != MCO_SUCCESS) goto bailclose;

	for (i=0; i<num_tweaks; i++)
		{
		status = filef->relWrite(sizeof(Tweak_Element),(char*)tweaks[i]);
		if (status != MCO_SUCCESS) goto bailclose;
		}

	bailclose:
	filef->closeFile();
	bail:
	delete filef;
	return status;
}
Example #20
0
Defaults::~Defaults(void)
{
FileFormat *filef;
FSSpec fspec;
McoStatus status;
int		magic_num = DEFAULTS_MAGIC_NUM;
int		version = DEFAULTS_VERSION;
Str255  def = MONACO_DEFAULT;
Str255  fold = MONACO_FOLDER;

// now try to load in the user defults
filef = new FileFormat;

ptocstr(def);
ptocstr(fold);

status = filef->createFileinPref(&fspec,(char*)def,(char*)fold);
if (status != MCO_SUCCESS) return;

status = filef->openFile(&fspec);
if (status != MCO_SUCCESS) return;

status = filef->relWrite(sizeof(int),(char*)&magic_num);
if (status != MCO_SUCCESS) return;

status = filef->relWrite(sizeof(int),(char*)&version);
if (status != MCO_SUCCESS) return;

status = filef->relWrite(sizeof(int),(char*)&printer_type);
if (status != MCO_SUCCESS) return;

status = filef->relWrite(sizeof(int),(char*)&input_type);
if (status != MCO_SUCCESS) return;

status = filef->relWrite(sizeof(int),(char*)&patch_format);
if (status != MCO_SUCCESS) return;

status = filef->relWrite(sizeof(int),(char*)&port);
if (status != MCO_SUCCESS) return;

filef->setInfo(&fspec,MONACO_SIG,'MCO7');

filef->closeFile();
delete filef;
}
Example #21
0
bool PlotIO::write(const QString& path, const ros::Time& start, const ros::Time& end)
{
	FileFormat* io = 0;

	if(path.endsWith(".bag"))
		io = new BagFormat;
	else if(path.endsWith(".csv"))
		io = new CSVFormat;

	if(!io)
	{
		fprintf(stderr, "Could not find output format\n");
		return false;
	}

	if(!io->init(path, start))
		return false;

	QLinkedList<Plot::LinkedBufferIterator> its = m_rootPlot->iterators(io->defaultFlags());

	io->writeHeader(its);

	QVector<Plot::LinkedBufferIterator*> to_write(its.size(), 0);

	while(1)
	{
		ros::Time stamp = ros::Time(0);
		qFill(to_write, (Plot::LinkedBufferIterator*)0);

		// Get a list of iterators with the next timestamp
		int i = 0;
		for(QLinkedList<Plot::LinkedBufferIterator>::iterator it = its.begin(); it != its.end(); ++it, ++i)
		{
			Plot::LinkedBufferIterator& buf_it = *it;
			if(!buf_it.isValid())
				continue;

			const Plot::DataPoint& point = *buf_it;

			if(point.time < stamp || stamp == ros::Time(0))
			{
				qFill(to_write, (Plot::LinkedBufferIterator*)0);
				to_write[i] = &buf_it;
				stamp = point.time;
			}
			else if(point.time == stamp)
				to_write[i] = &buf_it;
		}

		if(stamp == ros::Time(0))
			break;

		if(end != ros::Time(0) && stamp > end)
			break;

		if(stamp >= start)
			io->writeData(stamp, to_write);

		// Advance all used iterators
		Q_FOREACH(Plot::LinkedBufferIterator* it, to_write)
		{
			if(!it)
				continue;

			++(*it);
		}
	}

	delete io;
	return true;
}
Example #22
0
int main (int commands, char *control [])
{
	FileFormat *exe = new FileFormat ();

	return (exe->Start_Execution (commands, control));
}
Example #23
0
McoStatus PrinterType::Load(FSSpec *fspec)
{
int i;
McoStatus status = MCO_SUCCESS;
FileFormat *filef;
int   magic_num;
int   version;


filef = new FileFormat;

status = filef->openFile(fspec);
if (status != MCO_SUCCESS) goto bail;

status = filef->relRead(sizeof(int),(char*)&magic_num);
if (status != MCO_SUCCESS) goto bailclose;

status = filef->relRead(sizeof(int),(char*)&version);
if (status != MCO_SUCCESS) goto bailclose;
if (version != PRINTERTYPE_VERSION) goto bailclose;

status = filef->relRead(sizeof(ConData),(char*)&data);
if (status != MCO_SUCCESS) goto bailclose;

status = filef->relRead(sizeof(int),(char*)&num_hands);
if (status != MCO_SUCCESS) goto bailclose;

status = filef->relRead(sizeof(double)*31,(char*)x_hands);
if (status != MCO_SUCCESS) goto bailclose;

status = filef->relRead(sizeof(double)*31,(char*)y_hands);
if (status != MCO_SUCCESS) goto bailclose;

status = filef->relRead(sizeof(int),(char*)&sim_num);
if (status != MCO_SUCCESS) goto bailclose;

status = filef->relRead(sizeof(int),(char*)&num_tweaks);
if (status != MCO_SUCCESS) goto bailclose;

for (i=0; i<num_tweaks; i++)
	{
	if (!tweaks[i]) 
	tweaks[i] = new Tweak_Element(0L);
	if (!tweaks[i]) goto bailclose;
	status = filef->relRead(sizeof(Tweak_Element),(char*)tweaks[i]);
	if (status != MCO_SUCCESS) goto bailclose;
	}
	


bailclose:
filef->closeFile();
bail:
delete filef;
return status;
}