示例#1
0
void FileManager::LoadContent(const char *filename, std::vector<std::vector<std::string>> &attributes, std::vector<std::vector<std::string>> &contents, std::string identifier)
{
	int lines = 0;
	std::ifstream openFile(filename);
	std::string line, newLine;

	if(openFile.is_open())
	{
		while(std::getline(openFile, line))
		{
			std::stringstream str;
			std::cout << "Line: " << line << std::endl;

			if(line.find("EndLoad=") != std::string::npos && line.find(identifier) != std::string::npos)
			{
				identifierFound = false;
				break;
			}
			else if(line.find("Load=") != std::string::npos && line.find(identifier) != std::string::npos)
			{
				identifierFound = true;
				continue;
			}

			if(identifierFound)
			{

				if(line.find("Load=") != std::string::npos)
				{
					type = LoadType::Attributes;
					line = line.erase(0, line.find("=") + 1);
					tempAttributes.clear();
					std::cout << "Line Attribute: " << line << std::endl;
				}
				else
				{
					type = LoadType::Contents;
					tempContents.clear();
					std::cout << "Line Content: " << line << std::endl;
				}

				str << line;
				std::cout << "Line Str: " << line << std::endl;

				while(std::getline(str, newLine, ']'))
				{

					newLine.erase(std::remove(newLine.begin(), newLine.end(), '['), newLine.end());

					std::string erase = " \t\n\r"; 

					newLine.erase(newLine.find_last_not_of(erase) + 1);

					if(type == LoadType::Attributes)
						tempAttributes.push_back(newLine);
					else
						tempContents.push_back(newLine);

					//std::cout << "Post: "<< newLine << std::endl;
				}

				if(type == LoadType::Contents && tempContents.size() > 0)
				{
					attributes.push_back(tempAttributes);
					contents.push_back(tempContents);
				}
			}
		}
	}
	else
	{

	}
}
示例#2
0
文件: gvmap.c 项目: emdenrg/graphviz
static void 
init(int argc, char **argv, params_t* pm)
{
  char* cmd = argv[0];
  unsigned int c;
  real s;
  int v, r;
  char stmp[3];  /* two character string plus '\0' */

  pm->outfile = NULL;
  pm->opacity = NULL;
  pm->nrandom = -1;
  pm->dim = 2;
  pm->shore_depth_tol = 0;
  pm->highlight_cluster = 0;
  pm->useClusters = 0;
  pm->plotedges = 0;
  pm->whatout = 0;
  pm->show_points = 0;
  pm->color_scheme = COLOR_SCHEME_PASTEL; 
  pm->line_width = 0;
  pm->plot_label = NULL;
  pm->bg_color = NULL;
  pm->improve_contiguity_n = 0;
  pm->whatout = OUT_DOT;
  pm->nart = -1;
  pm->color_optimize = 1;
  pm->maxcluster = 0;
  pm->nedgep = 0;

  pm->cmd = cmd;
  pm->infiles = NULL;
  pm->line_color = N_NEW(10,char);
  strcpy(pm->line_color,"#000000");
  pm->include_OK_points = FALSE;
  pm->seed = 123;

  /*  bbox_margin[0] =  bbox_margin[1] = -0.2;*/
  pm->bbox_margin[0] =  pm->bbox_margin[1] = 0;

  opterr = 0;
  while ((c = getopt(argc, argv, ":evODko:m:s:r:p:c:C:l:b:g:t:a:h:z:d:")) != -1) {
    switch (c) {
    case 'm':
      if ((sscanf(optarg,"%lf",&s) > 0) && (s != 0)){
	    pm->bbox_margin[0] =  pm->bbox_margin[1] = s;
      } else {
        usage(cmd, 1);
      }
      break;
#if 0
    case 'q':
      if ((sscanf(optarg,"%d",&r) > 0) && r >=0 && r <=OUT_PROCESSING){
        pm->whatout = r;
      } else {
        usage(cmd,1);
      }
      break;
#endif
    case 's':
      if ((sscanf(optarg,"%lf",&s) > 0)){
        pm->shore_depth_tol = s;
      } else {
        usage(cmd,1);
      }
      break;
    case 'h':
      if ((sscanf(optarg,"%d",&v) > 0)){
        pm->nedgep = MAX(0, v);
      } else if (!strncmp(optarg, HLPFX, N_HLPFX) && (sscanf(optarg+N_HLPFX,"%d",&v) > 0)) {
        pm->highlight_cluster = MAX(0, v);
      } else {
        usage(cmd,1);
      }
      break;
     case 'r':
      if ((sscanf(optarg,"%d",&r) > 0)){
        pm->nrandom = r;
      }
      break;
    case 't':
      if ((sscanf(optarg,"%d",&r) > 0) && r > 0){
        pm->improve_contiguity_n = r;
      }
      break;
    case 'p':
      pm->show_points = 1;
      if ((sscanf(optarg,"%d",&r) > 0)){
        pm->show_points = MIN(3, r);
      }
      break;
    case 'k':
      pm->include_OK_points = TRUE;
      break;
    case 'v':
      Verbose = 1;
      break;
    case 'D':
      pm->useClusters = 1;
      break;
    case 'e':
      pm->plotedges = 1;
      break;
    case 'o':
	  pm->outfile = openFile(optarg, "w", pm->cmd);
      break;
    case 'O':
      pm->color_optimize = 0;
      break;
    case 'a':
      if ((sscanf(optarg,"%d",&r) > 0)){
	    pm->nart = r;
      } else {
	    usage(cmd,1);
      }
      break;
    case 'c':
      if (sscanf(optarg,"_opacity=%2s", stmp) > 0 && strlen(stmp) == 2){
        pm->opacity = strdup(stmp);
      } else if ((sscanf(optarg,"%d",&r) > 0) && r >= COLOR_SCHEME_NONE && r <= COLOR_SCHEME_GREY){
        pm->color_scheme = r;
      } else {
        usage(cmd,1);
      }
      break;
    case 'd':
      if (sscanf(optarg,"%d",&v) <= 0){
        usage(cmd,1);
      }
      else
        pm->seed = v;
      break;
    case 'C':
      if (!((sscanf(optarg,"%d",&v) > 0) && v >= 0)){
        usage(cmd,1);
      }
      else
        pm->maxcluster = v;
      break;
    case 'g': {
      gvcolor_t color;
      if (colorxlate(optarg, &color, RGBA_DOUBLE) == COLOR_OK) {
        if (!pm->bg_color) pm->bg_color = N_NEW(3,real);
        pm->bg_color[0] = color.u.RGBA[0];
        pm->bg_color[1] = color.u.RGBA[1];
        pm->bg_color[2] = color.u.RGBA[2];
      }
      break;
    }
    case 'z': {
      FREE (pm->line_color);
      pm->line_color = strdup (optarg);
      break;
    }
    case 'b':
      if (sscanf(optarg,"%lf",&s) > 0) {
        pm->line_width = s;
      } else {
        fprintf (stderr, "%s: unexpected argument \"%s\" for -b flag\n", cmd, optarg);
      }
      break;
    case 'l':
      if (pm->plot_label) free (pm->plot_label);
      pm->plot_label = strdup (optarg);
      break;
    case ':':
      fprintf(stderr, "gvpack: option -%c missing argument - ignored\n", optopt);
      break;
    case '?':
      if (optopt == '?')
        usage(cmd, 0);
      else {
        fprintf(stderr, " option -%c unrecognized - ignored\n", optopt);
        usage(cmd, 0);
      }
      break;
    }
  }

  argv += optind;
  argc -= optind;
  if (argc)
    pm->infiles = argv;
  if (!pm->outfile)
    pm->outfile = stdout;
}
示例#3
0
void huffman(FILE** file, FILE** ptFileOutput, char* fileInputName) {
	char c;
	int i = 0;
	int positionChar = 0;
	int tailleTab = 0;
	int tailleCode = 0;
	int currentChar = 0;
	float longueurTotaleCode = 0;
	char* tabChar;
	char* fileOutputName;
	int* intTab;
	char* charTab;
	char* bufferCode;
	char charTemp[7];
	elementListe* elemL = NULL;
	elementListe** ptListe = &elemL;

	/* temps de traitement */
	clock_t start_time, end_time;
	start_time = clock();

	intTab = calloc(1, sizeof(int));
	charTab = calloc(1, sizeof(char));

	if ((intTab == NULL) || (charTab == NULL)) {
		printf("Erreur d'allocation intTab ou  charTab.\n");
		exit(-1);
	}

	/* parcours du fichier source et remplissage des tableaux de frequence*/
	while ((c = fgetc(*file)) != EOF) {

		/*printf("%c", c);*/
		if (isInTab(c, charTab) == -1) {
			intTab = realloc(intTab, sizeof(int) * tailleTab + 1);
			charTab = realloc(charTab, sizeof(char) * tailleTab + 1);
			if ((intTab == NULL) || (charTab == NULL)) {
				printf("Erreur REALLOC intTab ou  charTab.\n");
				exit(-1);
			}

			intTab[tailleTab] = 1;
			charTab[tailleTab] = c;
			tailleTab++;

		} else {
			positionChar = isInTab(c, charTab);
			intTab[positionChar]++;
		}
	}

	/* Affichage tableau */
	/*for (i = 0; i < tailleTab; i++) {
	 printf("1-%c   %d\n", charTab[i], intTab[i]);
	 }*/

	tri(charTab, intTab, tailleTab);

	/* Affichage tableaux triés */
	/*for (i = 0; i < tailleTab; i++) {
	 printf("2-%c   %d\n", charTab[i], intTab[i]);
	 }*/

	for (i = 0; i < tailleTab; i++) {
		createChainedList(ptListe, charTab[i], intTab[i]);
	}
	/* Affichage liste chainee triée*/
	/*for (a = *ptListe;a->suivant!=NULL;a = a->suivant) {
	 printf("3-%c   %d\n", a->caractere, a->frequence);
	 }*/

	printf("\n");

	while ((*ptListe)->suivant != NULL) {
		insertNewNodeInChainedList(ptListe);
	}

	/* La liste ne contient plus qu'un seul element qui contiend l'arbre entier */
	tabChar = calloc(1, sizeof(char*));
	if (tabChar == NULL) {
		printf("Erreur d'allocation tabChar.\n");
		exit(-1);
	}

	/* Parcours d'arbre*/
	prefixeHuffmanTree(elemL->noeudIntermediaire, tabChar, 0);

	/* affichage caractères codés */
	for (i = 0; i < 256; i++) {
		if (code[i]) {
			printf("'%c': %s\n", i, code[i]);
			longueurTotaleCode += strlen(code[i]);
		}
	}

	printf("Longueur moyenne d'un symbole : %.2f bits\n",
			longueurTotaleCode / tailleTab);
	printf("Compression en cours, veuillez patienter . . .\n");

	/*Ecriture de la taille de la table des fréquences */
	fileOutputName = calloc((8 + strlen(fileInputName)), sizeof(char));
	if (fileOutputName == NULL) {
		printf("Erreur d'allocation fileOutputName.\n");
		exit(-1);
	}

	fileOutputName = createBinaryFile(fileInputName, ptFileOutput, ".huffman");

	openFile(fileOutputName, ptFileOutput, "wb");

	/*ECRITURE DANS LE FICHIER CIBLE*/
	/*------------------------------------------------------------*/

	/* on écrit la taille du dictionnaire  */
	fwrite(&tailleTab, sizeof(int), 1, *ptFileOutput);

	/* Ecriture du dictionnaire de donnees */
	for (i = 0; i < tailleTab; i++) {

		fwrite(&charTab[i], sizeof(char), 1, *ptFileOutput);
		tailleFileOutput++;
		fwrite(&intTab[i], sizeof(int), 1, *ptFileOutput);
		tailleFileOutput += 4;
	}
	/*------------------------------------------------------------*/

	bufferCode = calloc(1, sizeof(char));
	if (bufferCode == NULL) {
		printf("Erreur d'allocation bufferCode.\n");
		exit(-1);
	}
	/*pointeur sur le fichier initial pour un nouveau parcours (creation du code)*/
	fseek(*file, 0, SEEK_SET);

	while ((c = fgetc(*file)) != EOF) {
		tailleFileInput++;
		for (i = 0; i < 256; i++) {
			if (c == (char) i) {

				tailleCode = strlen(code[i]) + strlen(bufferCode) + 1;
				bufferCode = realloc(bufferCode, tailleCode * sizeof(char));
				if (bufferCode == NULL) {
					printf("Erreur reallocation bufferCode.\n");
				}
				strcat(bufferCode, code[i]);
			}
		}
	}
	printf("\n");
	/* Affichage du buffer */
	/*printf("%s\n", bufferCode);*/

	tailleCode = strlen(bufferCode);
	int nboctet = tailleCode / 7;
	tailleFileOutput += nboctet;
	for (i = 0; i < nboctet; i++) {
		strncpy(charTemp, bufferCode, 7);
		currentChar = binaryToDecimal(charTemp);
		fwrite(&currentChar, 1, 1, *ptFileOutput);
		bufferCode += 7;
	}

	i = nboctet * 7;

	/* si il reste des octets */
	if (i != tailleCode) {
		tailleFileOutput++;

		strcpy(charTemp, bufferCode);
		if (strlen(charTemp) != 7) {
			for (i = 0; i < 7; i++) {
				if (charTemp[i] == '\0') {
					charTemp[i + 1] = '\0';
					charTemp[i] = '0';
				}
			}
			currentChar = binaryToDecimal(charTemp);
			fwrite(&currentChar, 1, 1, *ptFileOutput);
		}
	}
	closeFile(ptFileOutput);

	printf("Taux de compression : %.2llu %% \n",
			100 -((tailleFileOutput) * 100 / tailleFileInput));
	freeHuffmanTree(elemL->noeudIntermediaire);

	free(elemL);
	free(intTab);
	intTab = NULL;
	free(charTab);
	charTab = NULL;
	free(fileOutputName);
	fileOutputName = NULL;
	free(tabChar);
	tabChar = NULL;

	end_time = clock();
	printf("Compression effectuee en %lu s.",
			(long) ((end_time - start_time) / CLOCKS_PER_SEC));
}
示例#4
0
void eDVRPlayerThread::readMore(int what)
{
	(void)what;
	if ((state != statePlaying) && (state != stateBuffering))
	{
		eDebug("wrong state (%d)", state);
		return;
	}

	int flushbuffer=0;

	if (curBufferFullness < maxBufferFullness)
	{
		int rd = buffer.fromfile(sourcefd, maxBufferFullness);
		int next=0;
		if ( rd < maxBufferFullness)
		{
			next=1;
			if (playingPermanentTimeshift)
			{
				int nextslice = permanentTimeshift.setNextPlayingSlice();
				if (nextslice == -1)
				{
					eDebug("no next file, stateFileEnd (previous state %d)", state);
					flushbuffer=1;
					if (inputsn)
						inputsn->stop();
					next = 0;
				}
				if (next && openFile(nextslice)) // if no next part found, else continue there...
					flushbuffer=1;
			}
			else
			{
				if (livemode)
				{
					struct stat64 s;
					eString tfilename=filename;
					tfilename += eString().sprintf(".%03d", slice+1);
	
					if (::stat64(tfilename.c_str(), &s) < 0)
					{
						eDebug("no next file, stateFileEnd (previous state %d)", state);
						flushbuffer=1;
						if (inputsn)
							inputsn->stop();
						next=0;
					}
				}
				if (next && openFile(slice+1)) // if no next part found, else continue there...
					flushbuffer=1;
			}
		}

		int newbuffsize = curBufferFullness + rd;
		curBufferFullness = newbuffsize;
		if (!next)
		{
			off64_t newpos = position + rd;
			position = newpos;
		}
	}

	int bla = eSystemInfo::getInstance()->getHwType() < 3 ? 100000 : 16384;

	if ( (state == stateBuffering && curBufferFullness > bla) || flushbuffer )
	{
		state=statePlaying;
		outputsn->start();
	}

	if (flushbuffer)
	{
		state=stateFileEnd;
		if (inputsn)
			inputsn->stop();
	}

	if ((state == statePlaying) && (curBufferFullness >= maxBufferFullness))
	{
		state=stateBufferFull;
		if (inputsn)
			inputsn->stop();
	}
}
void TranslatorView::openMorseCodeTextFile()
{
    QString fileContent;
    fileContent = openFile();
    textEditMorseCode->setPlainText(fileContent);
}
示例#6
0
void CardReader::openLogFile(char* name)
{
  logging = true;
  openFile(name, false);
}
示例#7
0
InfoFile::InfoFile(string id)
{
  stringstream fileName; 
  fileName << INF_FILE_NAME << "." << id; 
  fh =  openFile(fileName.str(), "w"); 
}
示例#8
0
文件: dwriter.cpp 项目: KDE/umbrello
/**
 * Call this method to generate d code for a UMLClassifier.
 * @param c   the class to generate code for
 */
void DWriter::writeClass(UMLClassifier *c)
{
    if (!c) {
        uDebug() << "Cannot write class of NULL concept!";
        return;
    }

    isInterface = c->isInterface();

    QString fileName = cleanName(c->name().toLower());

    //find an appropriate name for our file
    fileName = findFileName(c, QLatin1String(".d"));
    if (fileName.isEmpty()) {
        emit codeGenerated(c, false);
        return;
    }

    // check that we may open that file for writing
    QFile file;
    if (!openFile(file, fileName)) {
        emit codeGenerated(c, false);
        return;
    }

    // open text stream to file
    QTextStream d(&file);

    //try to find a heading file (license, coments, etc)
    QString str;
    str = getHeadingFile(QLatin1String(".d"));
    if (!str.isEmpty()) {
        str.replace(QRegExp(QLatin1String("%filename%")), fileName);
        str.replace(QRegExp(QLatin1String("%filepath%")), file.fileName());
        d<<str<<m_endl;
    }

    // source file begins with the module declaration
    writeModuleDecl(c, d);

    // imports
    writeModuleImports(c, d);

    // write the opening declaration for the class incl any documentation,
    // interfaces and/or inheritence issues we have
    writeClassDecl(c, d);

    // start body of class
    d << " {" << m_endl;

    // Preparations
    //

    // sort attributes by Scope
    UMLAttributeList  atl;
    UMLAttributeList  atpub, atprot, atpriv, atpkg, atexport;
    UMLAttributeList  final_atpub, final_atprot, final_atpriv, final_atpkg, final_atexport;

    if (!isInterface) {
        UMLAttributeList atl = c->getAttributeList();
        foreach (UMLAttribute* at, atl) {
            switch(at->visibility())
            {
                case Uml::Visibility::Public:
                    if (at->isStatic())
                        final_atpub.append(at);
                    else
                        atpub.append(at);
                    break;
                case Uml::Visibility::Protected:
                    if (at->isStatic())
                        final_atprot.append(at);
                    else
                        atprot.append(at);
                    break;
                case Uml::Visibility::Private:
                    if (at->isStatic())
                        final_atpriv.append(at);
                    else
                        atpriv.append(at);
                    break;/* TODO: requires support from the gui & other structures
                case Uml::Visibility::Package:
                    if (at->getStatic())
                    final_atpkg.append(at);
                    else
                    atpkg.append(at);
                    break;
                case Uml::Visibility::Export:
                    if (at->getStatic())
                    final_atexport.append(at);
                    else
                    atexport.append(at);
                    break;*/
                default:
                    break;
            }
        }
    }
示例#9
0
Cnv* DosDisk_ns::loadCnv(const char *filename) {
	Common::SeekableReadStream *stream = openFile(filename);
	assert(stream);
	return makeCnv(stream);
}
示例#10
0
void BlitzMainWindow::slotOpen()
{
    QString filename(QFileDialog::getOpenFileName(this));
    if(!filename.isEmpty())
        openFile(filename);
}
示例#11
0
void BlitzMainWindow::slotRevert()
{
    if(!fn.isEmpty())
        openFile(fn);
}
/*
This function initializes the IFSOperationViewer and gets the inherited main window ready.
*/
IFSOperationViewer::IFSOperationViewer()
{
loadedIFSImage = NULL;
setupUi(this);

//Setup IFSImageLabels
leftImageLabel = new IFSImageLabel(imageFrame);
leftImageLabel->setObjectName(QString::fromUtf8("leftImageLabel"));
leftImageLabel->setScaledContents(false);
leftImageLabel->setAlignment(Qt::AlignCenter);

horizontalLayout_2->addWidget(leftImageLabel);

rightImageLabel = new IFSImageLabel(imageFrame);
rightImageLabel->setObjectName(QString::fromUtf8("rightImageLabel"));
rightImageLabel->setAlignment(Qt::AlignCenter);

horizontalLayout_2->addWidget(rightImageLabel);

//Set the slider for 3D images invisible until it is needed
threeDFramePositionLabel->setHidden(true);
threeDFramePositionSlider->setHidden(true);





//Initialize the file open action
action_Open->setShortcut(QKeySequence::Open);
action_Open->setStatusTip(tr("Load a IFS image for processing and viewing"));

//Initialize the save action
action_Save->setShortcut(QKeySequence::Save);
action_Save->setStatusTip(tr("Save the result of processing"));

//Connect the image labels to the values for the position
connect(leftImageLabel, SIGNAL(imageCursorRow(int)), rowPositionLabel, SLOT(setNum(int)));
connect(rightImageLabel, SIGNAL(imageCursorRow(int)), rowPositionLabel, SLOT(setNum(int)));

connect(leftImageLabel, SIGNAL(imageCursorColumn(int)), columnPositionLabel, SLOT(setNum(int)));
connect(rightImageLabel, SIGNAL(imageCursorColumn(int)), columnPositionLabel, SLOT(setNum(int)));

connect(leftImageLabel, SIGNAL(imageCursorValue(double)), imageValueLabel, SLOT(setNum(double)));
connect(rightImageLabel, SIGNAL(imageCursorValue(double)), imageValueLabel, SLOT(setNum(double)));

//Add action signals
connect(action_Open, SIGNAL(triggered()), this, SLOT(openFile()));
connect(action_Save, SIGNAL(triggered()), this, SLOT(saveFile()));

//Connect buttons
connect(applyButton, SIGNAL(clicked()), this, SLOT(applyOperation()));
connect(swapButton, SIGNAL(clicked()), this, SLOT(swap()));

//Connect slider
connect(threeDFramePositionSlider, SIGNAL(valueChanged(int)), this, SLOT(setFrame(int)));
connect(threeDFramePositionSlider, SIGNAL(valueChanged(int)), threeDFramePositionLabel, SLOT(setNum(int)));

//Set up function details and the function list
populateFunctionDetailsAndList();

//Connect list to parameters
connect(operationListBox, SIGNAL(currentTextChanged(const QString &)), this, SLOT(setupParameterWidgets(const QString&)));

//Set the function list to the first item
if(operationListBox->count() > 0)
{
operationListBox->setCurrentRow(0);
}

}
void RemoteDatabase::gotReply(QNetworkReply* reply)
{
    // Check if request was successful
    if(reply->error() != QNetworkReply::NoError)
    {
        QMessageBox::warning(nullptr, qApp->applicationName(),
                             tr("Error when connecting to %1.\n%2").arg(reply->url().toString()).arg(reply->errorString()));
        reply->deleteLater();
        return;
    }

    // Check for redirect
    QString redirectUrl = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toString();
    if(!redirectUrl.isEmpty())
    {
        // Avoid redirect loop
        if(reply->url() == redirectUrl)
        {
            reply->deleteLater();
            return;
        }
        fetch(redirectUrl, static_cast<RequestType>(reply->property("type").toInt()), reply->property("certfile").toString(), reply->property("userdata"));
        reply->deleteLater();
        return;
    }

    // What type of data is this?
    RequestType type = static_cast<RequestType>(reply->property("type").toInt());

    // Hide progress dialog before opening a file dialog to make sure the progress dialog doesn't interfer with the file dialog
    if(type == RequestTypeDatabase || type == RequestTypePush)
        m_progress->reset();

    // Handle the reply data
    switch(type)
    {
    case RequestTypeDatabase:
        {
            // It's a database file.

            // Add cloned database to list of local databases
            QString saveFileAs = localAdd(reply->url().fileName(), reply->property("certfile").toString(),
                                          reply->url(), QUrlQuery(reply->url()).queryItemValue("commit").toStdString());

            // Save the downloaded data under the generated file name
            QFile file(saveFileAs);
            file.open(QIODevice::WriteOnly);
            file.write(reply->readAll());

            // Set last modified data of the new file to the one provided by the server
            // Before version 5.10, Qt didn't offer any option to set this attribute, so we're not setting it at the moment
#if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0)
            QString last_modified = reply->rawHeader("Content-Disposition");
            QRegExp regex("^.*modification-date=\"(.+)\";.*$");
            regex.setMinimal(true); // Set to non-greedy matching
            if(regex.indexIn(last_modified) != -1)
            {
                last_modified = regex.cap(1);
                bool success = file.setFileTime(QDateTime::fromString(last_modified, Qt::ISODate), QFileDevice::FileModificationTime);
                if(!success)
                    qWarning() << file.errorString();
            }
#endif

            file.close();

            // Tell the application to open this file
            emit openFile(saveFileAs);
        }
        break;
    case RequestTypeDirectory:
        emit gotDirList(reply->readAll(), reply->property("userdata"));
        break;
    case RequestTypeNewVersionCheck:
        {
            QString version = reply->readLine().trimmed();
            QString url = reply->readLine().trimmed();
            emit gotCurrentVersion(version, url);
            break;
        }
    case RequestTypeLicenceList:
        {
            // Read and check results
            json obj = json::parse(reply->readAll(), nullptr, false);
            if(obj.is_discarded() || !obj.is_object())
                break;

            // Parse data and build ordered licence map: order -> (short name, long name)
            std::map<int, std::pair<std::string, std::string>> licences;
            for(auto it=obj.cbegin();it!=obj.cend();++it)
                licences.insert({it.value()["order"], {it.key(), it.value()["full_name"]}});

            // Convert the map into an ordered vector and send it to anyone who's interested
            std::vector<std::pair<std::string, std::string>> licence_list;
            std::transform(licences.begin(), licences.end(), std::back_inserter(licence_list), [](const std::pair<int, std::pair<std::string, std::string>>& it) {
                return it.second;
            });
            emit gotLicenceList(licence_list);
            break;
        }
    case RequestTypeBranchList:
        {
            // Read and check results
            json obj = json::parse(reply->readAll(), nullptr, false);
            if(obj.is_discarded() || !obj.is_object())
                break;
            json obj_branches = obj["branches"];

            // Parse data and assemble branch list
            std::vector<std::string> branches;
            for(auto it=obj_branches.cbegin();it!=obj_branches.cend();++it)
                branches.push_back(it.key());

            // Get default branch
            std::string default_branch = (obj.contains("default_branch") && !obj["default_branch"].empty()) ? obj["default_branch"] : "master";

            // Send branch list to anyone who is interested
            emit gotBranchList(branches, default_branch);
            break;
        }
    case RequestTypePush:
        {
            // Read and check results
            json obj = json::parse(reply->readAll(), nullptr, false);
            if(obj.is_discarded() || !obj.is_object())
                break;

            // Create or update the record in our local checkout database
            QString saveFileAs = localAdd(reply->url().fileName(), reply->property("certfile").toString(), QString::fromStdString(obj["url"]), obj["commit_id"]);

            // If the name of the source file and the name we're saving as differ, we're doing an initial push. In this case, copy the source file to
            // the destination path to avoid redownloading it when it's first used.
            if(saveFileAs != reply->property("source_file").toString())
                QFile::copy(reply->property("source_file").toString(), saveFileAs);

            emit uploadFinished(obj["url"]);
            break;
        }
    }

    // Delete reply later, i.e. after returning from this slot function
    reply->deleteLater();
}
示例#14
0
//
// WadDirectory::addFile
//
// All files are optional, but at least one file must be found (PWAD, if all
// required lumps are present).
// Files with a .wad extension are wadlink files with multiple lumps.
// Other files are single lumps with the base filename for the lump name.
//
// Reload hack removed by Lee Killough
// killough 1/31/98: static, const
//
bool WadDirectory::addFile(wfileadd_t &addInfo)
{
    // Directory file addition callback type
    typedef bool (WadDirectory::* AddFileCB)(openwad_t &, wfileadd_t &, int);

    static AddFileCB fileadders[W_FORMAT_MAX] =
    {
        &WadDirectory::addWadFile,   // W_FORMAT_WAD
        &WadDirectory::addZipFile,   // W_FORMAT_ZIP
        &WadDirectory::addSingleFile // W_FORMAT_FILE
    };

    openwad_t openData;

    // When loading a subfile, the physical file is already open.
    if(addInfo.flags & WFA_SUBFILE)
    {
        openData.filename = addInfo.filename;
        openData.handle   = addInfo.f;

        // Only WAD files are currently supported as subfiles.
        if(W_DetermineFileFormat(openData.handle,
                                 static_cast<long>(addInfo.baseoffset)) != W_FORMAT_WAD)
        {
            addInfo.flags |= WFA_OPENFAILFATAL;
            handleOpenError(openData, addInfo, openData.filename);
            return false; // it'll actually I_Error, but whatever.
        }
        openData.format = W_FORMAT_WAD;
    }
    else if(addInfo.flags & WFA_INMEMORY)
    {
        openData.base     = addInfo.memory;
        openData.size     = addInfo.size;
        openData.filename = "memory";
        openData.format   = W_FORMAT_WAD; // wad handler will deal with this.
    }
    else
    {
        // Open the physical archive file and determine its format
        openData = openFile(addInfo);
        if(openData.error)
            return false;
    }

    // Show adding message if at startup and not a private directory or
    // in-memory wad
    /*
    if(!(addInfo.flags & (WFA_PRIVATE|WFA_INMEMORY)) && this->ispublic)
    {
       printf(" adding %s\n", openData.filename);   // killough 8/8/98
    }
    */

    // Call the appropriate file directory addition routine for this format
#ifdef RANGECHECK
    if(openData.format < 0 || openData.format >= W_FORMAT_MAX)
        I_Error("WadDirectory::addFile: invalid file format %d\n", openData.format);
#endif

    if(!(this->*fileadders[openData.format])(openData, addInfo, numlumps))
    {
        handleOpenError(openData, addInfo, openData.filename);
        return false;
    }

    return true; // no error
}
示例#15
0
文件: Input.C 项目: svalinn/ALARA
/** This constructor creates a new Input object to contain the
      problem input and connects it to an input stream.  If called with
      no arguments, the input is read from stdin, otherwise it is read
      from the filename specified in the argument.  The constructor
      initializes all the different members, with the list tails
      pointing to the list heads. */
Input::Input(char* inputFname)
{
  if (inputFname != NULL)
    {
      debug(1,"Openning %s for input.",inputFname);
      input = openFile(inputFname);
      if (!*input)
	error(102,"Unable to open main input file: '%s'.",inputFname);

      verbose(1,"Openned %s for input.",inputFname);
    }
  else
    {
      debug(1,"Openning stdin for input.");
      input = &cin;
      verbose(1,"Opened stdin for input.");
    }
      
  inGeom = NULL;

  mixListHead = new Mixture(IN_HEAD);
  memCheck(mixListHead,"Input::Input() constructor: mixListHead");
  mixList = mixListHead;

  fluxListHead = new Flux(FLUX_HEAD);
  memCheck(fluxListHead,"Input::Input() constructor: fluxListHead");
  fluxList = fluxListHead;

  historyListHead = new History(IN_HEAD);
  memCheck(historyListHead,"Input::Input() constructor: historyListHead");
  historyList = historyListHead;

  schedListHead = new Schedule(IN_HEAD);
  memCheck(schedListHead,"Input::Input() constructor: schedListHead");
  schedList = schedListHead;

  dimListHead = new Dimension(DIM_HEAD);
  memCheck(dimListHead,"Input::Input() constructor: dimListHead");
  dimList = dimListHead;

  coolList = new CoolingTime(COOL_HEAD);
  memCheck(coolList,"Input::Input() constructor: coolList");

  volList = new Volume(VOL_HEAD);
  memCheck(volList,"Input::Input() constructor: volList");

  normList = new Norm(NORM_HEAD);
  memCheck(normList,"Input::Input() constructor: normList");
  
  loadList = new Loading(IN_HEAD);
  memCheck(loadList,"Input::Input() constructor: loadList");
  
  solveList = new Loading(IN_HEAD);
  memCheck(loadList,"Input::Input() constructor: solveList");
  
  skipList = new Loading(IN_HEAD);
  memCheck(loadList,"Input::Input() constructor: skipList");
  
  outListHead = new OutputFormat(OUTRES_HEAD);
  memCheck(outListHead,"Input::Input() constructor: outListHead");

}
示例#16
0
Table* DosDisk_ns::loadTable(const char* name) {
	char path[PATH_LEN];
	sprintf(path, "%s.tab", name);
	return createTableFromStream(100, openFile(path));
}
示例#17
0
AWavefrontDecoder::AWavefrontDecoder(const char *fname) : AMeshDecoder(fname)
{
  init();
  openFile(fname);
  readObjects();
}
示例#18
0
Common::SeekableReadStream* DosDisk_ns::loadMusic(const char* name) {
	char path[PATH_LEN];
	sprintf(path, "%s.mid", name);
	return openFile(path);
}
示例#19
0
void RecordNode::setParameter(int parameterIndex, float newValue)
{
    //editor->updateParameterButtons(parameterIndex);

    // 0 = stop recording
    // 1 = start recording
    // 2 = toggle individual channel (0.0f = OFF, anything else = ON)

    if (parameterIndex == 1)
    {

        isRecording = true;
       // std::cout << "START RECORDING." << std::endl;

        if (newDirectoryNeeded)
        {
            createNewDirectory();
            recordingNumber = 0;
        }
        else
        {
            recordingNumber++; // increment recording number within this directory
        }

        if (!rootFolder.exists())
        {
            rootFolder.createDirectory();
            String settingsFileName = rootFolder.getFullPathName() + File::separator + "settings.xml";
            getEditorViewport()->saveState(File(settingsFileName));
        }

        createNewFiles();
        
        openFile(eventChannel);

        blockIndex = 0; // reset index


        // create / open necessary files
        for (int i = 0; i < channelPointers.size(); i++)
        {
           // std::cout << "Checking channel " << i << std::endl;

            if (channelPointers[i]->getRecordState())
            {
                openFile(channelPointers[i]);
            }
        }

    }
    else if (parameterIndex == 0)
    {


       // std::cout << "STOP RECORDING." << std::endl;

        if (isRecording)
        {

            // close necessary files
            signalFilesShouldClose = true;

        }

        isRecording = false;


    }
    else if (parameterIndex == 2)
    {

        if (isProcessing)
        {

            std::cout << "Toggling channel " << currentChannel << std::endl;

            if (newValue == 0.0f)
            {
                channelPointers[currentChannel]->setRecordState(false);

                if (isRecording)
                {

                    if (blockIndex < BLOCK_LENGTH)
                    {
                        // fill out the rest of the current buffer
                        writeContinuousBuffer(zeroBuffer.getSampleData(0), BLOCK_LENGTH - blockIndex, currentChannel);
                    }

                    closeFile(channelPointers[currentChannel]);
                }

            }
            else
            {
                channelPointers[currentChannel]->setRecordState(true);

                if (isRecording)
                {

                    openFile(channelPointers[currentChannel]);

                    if (blockIndex > 0)
                    {
                        writeTimestampAndSampleCount(channelPointers[currentChannel]->file);
                        // fill up the first data block up to sample count
                        writeContinuousBuffer(zeroBuffer.getSampleData(0), blockIndex, currentChannel);
                    }

                }
            }
        }
    }
}
示例#20
0
FileBrowser::FileBrowser(LiteApi::IApplication *app, QObject *parent) :
    QObject(parent),
    m_liteApp(app)
{
    m_widget = new QWidget;
    QVBoxLayout *mainLayout = new QVBoxLayout;
    mainLayout->setMargin(0);
    mainLayout->setSpacing(0);

    m_fileModel = new QFileSystemModel(this);
    m_fileModel->setFilter(QDir::AllEntries | QDir::NoDotAndDotDot);

    m_proxyModel = new QSortFileSystemProxyModel(this);
    m_proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive);
    m_proxyModel->setDynamicSortFilter(true);
    m_proxyModel->setSourceModel(m_fileModel);
    m_proxyModel->sort(0);

    //create filter toolbar
    m_filterToolBar = new QToolBar(m_widget);
    m_filterToolBar->setIconSize(QSize(16,16));

    m_syncAct = new QAction(QIcon("icon:filebrowser/images/sync.png"),tr("Synchronize with editor"),this);
    m_syncAct->setCheckable(true);

    m_filterCombo = new QComboBox;
    m_filterCombo->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Preferred);
    m_filterCombo->setSizeAdjustPolicy(QComboBox::AdjustToMinimumContentsLength);
    m_filterCombo->setEditable(true);
    m_filterCombo->addItem("*");
    m_filterCombo->addItem("Makefile;*.go;*.cgo;*.s;*.goc;*.y;*.e64;*.pro");
    m_filterCombo->addItem("*.sh;Makefile;*.go;*.cgo;*.s;*.goc;*.y;*.*.c;*.cpp;*.h;*.hpp;*.e64;*.pro");

    m_filterToolBar->addAction(m_syncAct);
    m_filterToolBar->addSeparator();
    m_filterToolBar->addWidget(m_filterCombo);

    //create root toolbar
    m_rootToolBar = new QToolBar(m_widget);
    m_rootToolBar->setIconSize(QSize(16,16));

    m_cdupAct = new QAction(QIcon("icon:filebrowser/images/cdup.png"),tr("Open to Parent"),this);

    m_rootCombo = new QComboBox;
    m_rootCombo->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Preferred);
    m_rootCombo->setSizeAdjustPolicy(QComboBox::AdjustToMinimumContentsLength);
    m_rootCombo->setEditable(false);
    m_rootCombo->addItem(m_fileModel->myComputer().toString());

    m_rootToolBar->addAction(m_cdupAct);
    m_rootToolBar->addSeparator();
    m_rootToolBar->addWidget(m_rootCombo);

    //create treeview
    m_treeView = new QTreeView;
    m_treeView->setContextMenuPolicy(Qt::CustomContextMenu);
    m_treeView->setModel(m_proxyModel);

    m_treeView->setRootIsDecorated(true);
    m_treeView->setUniformRowHeights(true);
    m_treeView->setTextElideMode(Qt::ElideNone);
    m_treeView->setAttribute(Qt::WA_MacShowFocusRect, false);

    m_treeView->setHeaderHidden(true);
    m_treeView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    // show horizontal scrollbar
    m_treeView->header()->setResizeMode(QHeaderView::ResizeToContents);
    m_treeView->header()->setStretchLastSection(false);
    //hide
    int count = m_treeView->header()->count();
    for (int i = 1; i < count; i++) {
        m_treeView->setColumnHidden(i,true);
    }
    QHBoxLayout *cmdLayout = new QHBoxLayout;
    cmdLayout->setMargin(0);
    QLabel *label = new QLabel("Exec:");
    label->setToolTip("Execute\tCtrl+`, Alt+`");
    QAction *q = new QAction(this);
    q->setShortcuts(QList<QKeySequence>()
                    << QKeySequence("Ctrl+`")
                    << QKeySequence("Alt+`"));
    m_liteApp->mainWindow()->addAction(q);
    connect(q,SIGNAL(triggered()),this,SLOT(requestCommand()));
    cmdLayout->addWidget(label);
    m_commandEdit = new QLineEdit;
    m_commandEdit->setText("go ");
    cmdLayout->addWidget(m_commandEdit);

    mainLayout->addWidget(m_filterToolBar);
    mainLayout->addWidget(m_rootToolBar);
    mainLayout->addWidget(m_treeView);
    mainLayout->addLayout(cmdLayout);
    m_widget->setLayout(mainLayout);

    //create menu
    m_fileMenu = new QMenu;
    m_folderMenu = new QMenu;
    m_rootMenu = new QMenu;

    m_openFileAct = new QAction(tr("Open File"),this);
    m_openEditorAct = new QAction(tr("Open Editor"),this);
    m_newFileAct = new QAction(tr("New File"),this);
    m_newFileWizardAct = new QAction(tr("New File Wizard"),this);
    m_renameFileAct = new QAction(tr("Rename File"),this);
    m_removeFileAct = new QAction(tr("Remove File"),this);

    m_setRootAct = new QAction(tr("Set Folder To Root"),this);
    m_newFolderAct = new QAction(tr("New Folder"),this);
    m_renameFolderAct = new QAction(tr("Rename Folder"),this);
    m_removeFolderAct = new QAction(tr("Remove Folder"),this);

    m_openShellAct = new QAction(tr("Open Terminal Here"),this);
    m_openExplorerAct = new QAction(tr("Open Explorer Here"),this);

    m_viewGodocAct = new QAction(tr("View Godoc Here"),this);

    m_loadFolderAct = new QAction(tr("Load Folder Project"),this);

    m_fileMenu->addAction(m_openFileAct);
    m_fileMenu->addAction(m_openEditorAct);
    m_fileMenu->addSeparator();
    m_fileMenu->addAction(m_newFileAct);
    m_fileMenu->addAction(m_newFileWizardAct);
    m_fileMenu->addAction(m_renameFileAct);
    m_fileMenu->addAction(m_removeFileAct);
    m_fileMenu->addSeparator();
    m_fileMenu->addAction(m_loadFolderAct);
    m_fileMenu->addAction(m_viewGodocAct);
    m_fileMenu->addSeparator();
    m_fileMenu->addAction(m_openShellAct);
    m_fileMenu->addAction(m_openExplorerAct);

    m_folderMenu->addAction(m_setRootAct);
    m_folderMenu->addSeparator();
    m_folderMenu->addAction(m_newFileAct);
    m_folderMenu->addAction(m_newFileWizardAct);
    m_folderMenu->addAction(m_newFolderAct);
    m_folderMenu->addAction(m_renameFolderAct);
    m_folderMenu->addAction(m_removeFolderAct);
    m_folderMenu->addSeparator();
    m_folderMenu->addAction(m_loadFolderAct);
    m_folderMenu->addAction(m_viewGodocAct);
    m_folderMenu->addSeparator();
    m_folderMenu->addAction(m_openShellAct);
    m_folderMenu->addAction(m_openExplorerAct);

    m_rootMenu->addAction(m_cdupAct);
    m_rootMenu->addSeparator();
    m_rootMenu->addAction(m_newFileAct);
    m_rootMenu->addAction(m_newFileWizardAct);
    m_rootMenu->addAction(m_newFolderAct);
    m_rootMenu->addSeparator();
    m_rootMenu->addAction(m_loadFolderAct);
    m_rootMenu->addSeparator();
    m_rootMenu->addAction(m_openShellAct);
    m_rootMenu->addAction(m_openExplorerAct);

    connect(m_openFileAct,SIGNAL(triggered()),this,SLOT(openFile()));
    connect(m_openEditorAct,SIGNAL(triggered()),this,SLOT(openEditor()));    
    connect(m_newFileAct,SIGNAL(triggered()),this,SLOT(newFile()));
    connect(m_newFileWizardAct,SIGNAL(triggered()),this,SLOT(newFileWizard()));
    connect(m_renameFileAct,SIGNAL(triggered()),this,SLOT(renameFile()));
    connect(m_removeFileAct,SIGNAL(triggered()),this,SLOT(removeFile()));
    connect(m_newFolderAct,SIGNAL(triggered()),this,SLOT(newFolder()));
    connect(m_renameFolderAct,SIGNAL(triggered()),this,SLOT(renameFolder()));
    connect(m_removeFolderAct,SIGNAL(triggered()),this,SLOT(removeFolder()));
    connect(m_openShellAct,SIGNAL(triggered()),this,SLOT(openShell()));
    connect(m_setRootAct,SIGNAL(triggered()),this,SLOT(setFolderToRoot()));
    connect(m_cdupAct,SIGNAL(triggered()),this,SLOT(cdUp()));
    connect(m_openExplorerAct,SIGNAL(triggered()),this,SLOT(openExplorer()));
    connect(m_viewGodocAct,SIGNAL(triggered()),this,SLOT(viewGodoc()));
    connect(m_loadFolderAct,SIGNAL(triggered()),this,SLOT(loadFolderProject()));

    //QDockWidget *dock = m_liteApp->dockManager()->addDock(m_widget,tr("File Browser"));
    //connect(dock,SIGNAL(visibilityChanged(bool)),this,SLOT(visibilityChanged(bool)));
    m_toolWindowAct = m_liteApp->toolWindowManager()->addToolWindow(Qt::LeftDockWidgetArea,m_widget,"filesystem",tr("File System"),true);
    connect(m_toolWindowAct,SIGNAL(toggled(bool)),this,SLOT(visibilityChanged(bool)));
    connect(m_treeView,SIGNAL(doubleClicked(QModelIndex)),this,SLOT(doubleClickedTreeView(QModelIndex)));
    connect(m_filterCombo,SIGNAL(activated(QString)),this,SLOT(activatedFilter(QString)));
    connect(m_rootCombo,SIGNAL(activated(QString)),this,SLOT(activatedRoot(QString)));
    connect(m_syncAct,SIGNAL(triggered(bool)),this,SLOT(syncFileModel(bool)));
    connect(m_liteApp->editorManager(),SIGNAL(currentEditorChanged(LiteApi::IEditor*)),this,SLOT(currentEditorChanged(LiteApi::IEditor*)));
    connect(m_treeView,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(treeViewContextMenuRequested(QPoint)));
    connect(m_commandEdit,SIGNAL(returnPressed()),this,SLOT(commandReturn()));

    QString root = m_liteApp->settings()->value("FileBrowser/root",m_fileModel->myComputer().toString()).toString();
    addFolderToRoot(root);
    bool b = m_liteApp->settings()->value("FileBrowser/synceditor",true).toBool();
    if (b) {
        m_syncAct->setChecked(true);
    }
}
示例#21
0
void eDVRPlayerThread::init_eDVRPlayerThread(const char *_filename)
{
	state=stateInit;
	int nodetect=0;
	eConfig::getInstance()->getKey("/enigma/notimestampdetect", nodetect );
	timestampParser = nodetect ? 0 : new eTimeStampParserTS(_filename);
		

	int count=0;
	seekbusy=0;
	seeking=0;
#if HAVE_DVB_API_VERSION < 3
	do
	{
		dvrfd=::open("/dev/pvr", O_WRONLY|O_NONBLOCK); // TODO: change to /dev/dvb/dvr0 (but only when drivers support this!)
		if (dvrfd < 0)
		{
			if ( errno == EBUSY )
			{
				eDebug("pvr device busy try %d", count++);
				if ( count < 40 )
				{
					usleep(20000);
					continue;
				}
			}
			eDebug("couldn't open /dev/pvr - buy the new $$$ box and load pvr.o! (%m)");
			state=stateError;
		}
		break;
	}
	while( dvrfd < 0 );
#else
	if ((dvrfd = ::open("/dev/dvb/adapter0/dvr0", O_WRONLY|O_NONBLOCK)) == -1) 
	{
		eDebug("couldn't open /dev/dvb/adapter0/dvr0 (%m)");
		state=stateError;
	}
#endif
	outputsn=new eSocketNotifier(this, dvrfd, eSocketNotifier::Write, 0);
	CONNECT(outputsn->activated, eDVRPlayerThread::outputReady);

	CONNECT(liveupdatetimer.timeout, eDVRPlayerThread::updatePosition);

	filename=_filename;

	sourcefd=-1;
	inputsn=0;

	slice=0;
	audiotracks=1;

	if (playingPermanentTimeshift)
	{
		filelength = permanentTimeshift.getCurrentLength (-1)/1880;
	}
	else
	{
		filelength = FillSliceSizes();
	}

	if (openFile(0))
	{
		state=stateError;
		eDebug("error opening %s (%m)", filename.c_str());
	}

	CONNECT(messages.recv_msg, eDVRPlayerThread::gotMessage);

	if ( eSystemInfo::getInstance()->getHwType() < 3 ) // dbox2
		maxBufferFullness=128*1024;
	else
		maxBufferFullness=256*1024;

	speed=1;

	run();

	if (livemode)
	{
		int fileend;
		if (filelength > (TIMESHIFT_GUARD/1880))
			fileend = filelength - (TIMESHIFT_GUARD/1880);
		else
			fileend = 0;
		if ( livemode == 1 )
			messages.send(eDVRPlayerThread::eDVRPlayerThreadMessage(eDVRPlayerThread::eDVRPlayerThreadMessage::seekreal, fileend));
	}

	FILE *bitstream=fopen("/proc/bus/bitstream", "rt");
	if (bitstream)
	{
		char buf[100];
		while (fgets(buf, 100, bitstream))
		{
			if (strstr(buf, "AUDIO_STC:"))
			{
				needasyncworkaround=1;
				break;
			}
		}
		fclose(bitstream);
	}
}
示例#22
0
void MainWindow::createActions()
{
	openAction = new QAction("Open", this);
	connect(openAction, SIGNAL(triggered()), this, SLOT(openFile()));
	exitAction = new QAction("Exit", this);
	connect(exitAction, SIGNAL(triggered()), this, SLOT(close()));

	signalModeMapper = new QSignalMapper(this);
	modePointAction = new QAction("Point", this);
	modeLineAction = new QAction("Line", this);
	modeFillAction = new QAction("Fill", this);
	modePointAction->setCheckable(true);
	modeLineAction->setCheckable(true);
	modeFillAction->setCheckable(true);
	connect(modePointAction, SIGNAL(triggered()), signalModeMapper, SLOT(map()));
	connect(modeLineAction, SIGNAL(triggered()), signalModeMapper, SLOT(map()));
	connect(modeFillAction, SIGNAL(triggered()), signalModeMapper, SLOT(map()));
	signalModeMapper->setMapping(modePointAction, 0);
	signalModeMapper->setMapping(modeLineAction, 1);
	signalModeMapper->setMapping(modeFillAction, 2);
	connect(signalModeMapper, SIGNAL(mapped(int)), this, SLOT(setMeshMode(int)));
	modeGroup = new QActionGroup(this);
	modeGroup->addAction(modePointAction);
	modeGroup->addAction(modeLineAction);
	modeGroup->addAction(modeFillAction);
	modeFillAction->setChecked(true);

	signalShadeMapper = new QSignalMapper(this);
	shadeSmoothAction = new QAction("Smooth", this);
	shadeFlatAction = new QAction("Flat", this);
	shadeSmoothAction->setCheckable(true);
	shadeFlatAction->setCheckable(true);
	connect(shadeSmoothAction, SIGNAL(triggered()), signalShadeMapper, SLOT(map()));
	connect(shadeFlatAction, SIGNAL(triggered()), signalShadeMapper, SLOT(map()));
	signalShadeMapper->setMapping(shadeSmoothAction, 0);
	signalShadeMapper->setMapping(shadeFlatAction, 1);
	connect(signalShadeMapper, SIGNAL(mapped(int)), this, SLOT(setMeshShade(int)));
	shadeGroup = new QActionGroup(this);
	shadeGroup->addAction(shadeSmoothAction);
	shadeGroup->addAction(shadeFlatAction);
	shadeSmoothAction->setChecked(true);

	signalColorMapper = new QSignalMapper(this);
	redAction = new QAction("Red", this);
	greenAction = new QAction("Green", this);
	blueAction = new QAction("Blue", this);
	yellowAction = new QAction("Yellow", this);
	purpleAction = new QAction("Purple", this);
	whiteAction = new QAction("White", this);
	redAction->setCheckable(true);
	greenAction->setCheckable(true);
	blueAction->setCheckable(true);
	yellowAction->setCheckable(true);
	purpleAction->setCheckable(true);
	whiteAction->setCheckable(true);
	connect(redAction, SIGNAL(triggered()), signalColorMapper, SLOT(map()));
	connect(greenAction, SIGNAL(triggered()), signalColorMapper, SLOT(map()));
	connect(blueAction, SIGNAL(triggered()), signalColorMapper, SLOT(map()));
	connect(yellowAction, SIGNAL(triggered()), signalColorMapper, SLOT(map()));
	connect(purpleAction, SIGNAL(triggered()), signalColorMapper, SLOT(map()));
	connect(whiteAction, SIGNAL(triggered()), signalColorMapper, SLOT(map()));
	signalColorMapper->setMapping(redAction, 0);
	signalColorMapper->setMapping(greenAction, 1);
	signalColorMapper->setMapping(blueAction, 2);
	signalColorMapper->setMapping(yellowAction, 3);
	signalColorMapper->setMapping(purpleAction, 4);
	signalColorMapper->setMapping(whiteAction, 5);
	connect(signalColorMapper, SIGNAL(mapped(int)), this, SLOT(setMeshColor(int)));
	colorGroup = new QActionGroup(this);
	colorGroup->addAction(redAction);
	colorGroup->addAction(greenAction);
	colorGroup->addAction(blueAction);
	colorGroup->addAction(yellowAction);
	colorGroup->addAction(purpleAction);
	colorGroup->addAction(whiteAction);
	greenAction->setChecked(true);

	aboutAction = new QAction("About", this);
	connect(aboutAction, SIGNAL(triggered()), this, SLOT(about()));
}
示例#23
0
void eDVRPlayerThread::seekTo(off64_t offset)
{
	off64_t newoffset = 0;
	if (playingPermanentTimeshift)
	{
		permanentTimeshift.lock.lock();
		newoffset = permanentTimeshift.seekTo(offset);
		int newslice = permanentTimeshift.getCurrentPlayingSlice();
		permanentTimeshift.lock.unlock();

		if (newslice != slice)
		{
			if (openFile(newslice))
			{
				if (livemode)
				{
					// end of timeshifted recording reached
					state=stateFileEnd;
					return;
				}
				eDebug("open slice %d failed\n", newslice);
				state=stateError;
			}
		}
		eDebug("[PERM]newoffset:%lld,%d,%d",newoffset,slice, state == stateError);
	}
	else
	{
		off64_t sliceoffset = 0;
		int newslice = 0;
		while  (newslice < (int)slicesizes.size())
		{
			if (offset > (sliceoffset + slicesizes[newslice]))
			{
				sliceoffset += slicesizes[newslice];
				newslice++;
			}
			else
				break;
		}			
		if (slice != newslice)
		{
			if (openFile(newslice))
			{
				if (livemode)
				{
					// end of timeshifted recording reached
					state=stateFileEnd;
					return;
				}
				eDebug("open slice %d failed\n", newslice);
				state=stateError;
			}
		}
		newoffset = offset-sliceoffset;
	}

	if (state != stateError)
	{
		off64_t newpos=::lseek64(sourcefd, newoffset, SEEK_SET);
		dvrFlush();
		position=newpos;
	}
}
示例#24
0
void SingleApplication::slotOpenFile(QString path)
{
    emit openFile(path);
}
void TranslatorView::openNormalTextFile()
{
    QString fileContent;
    fileContent = openFile();
    textEditNormalText->setPlainText(fileContent);
}
示例#26
0
void PluginDatabase::loadPersistentMetadataCache()
{
    if (!isPersistentMetadataCacheEnabled() || persistentMetadataCachePath().isEmpty())
        return;

    PlatformFileHandle file;
    String absoluteCachePath = pathByAppendingComponent(persistentMetadataCachePath(), persistentPluginMetadataCacheFilename);
    file = openFile(absoluteCachePath, OpenForRead);

    if (!isHandleValid(file))
        return;

    // Mark cache as loaded regardless of success or failure. If
    // there's error in the cache, we won't try to load it anymore.
    m_persistentMetadataCacheIsLoaded = true;

    Vector<char> fileContents;
    fillBufferWithContentsOfFile(file, fileContents);
    closeFile(file);

    if (fileContents.size() < 2 || fileContents.first() != schemaVersion || fileContents.last() != '\0') {
        LOG_ERROR("Unable to read plugin metadata cache: corrupt schema");
        deleteFile(absoluteCachePath);
        return;
    }

    char* bufferPos = fileContents.data() + 1;
    char* end = fileContents.data() + fileContents.size();

    PluginSet cachedPlugins;
    HashMap<String, time_t> cachedPluginPathsWithTimes;
    HashMap<String, RefPtr<PluginPackage> > cachedPluginsByPath;

    while (bufferPos < end) {
        String path;
        time_t lastModified;
        String name;
        String desc;
        String mimeDesc;
        if (!(readUTF8String(path, bufferPos, end)
              && readTime(lastModified, bufferPos, end)
              && readUTF8String(name, bufferPos, end)
              && readUTF8String(desc, bufferPos, end)
              && readUTF8String(mimeDesc, bufferPos, end))) {
            LOG_ERROR("Unable to read plugin metadata cache: corrupt data");
            deleteFile(absoluteCachePath);
            return;
        }

        // Skip metadata that points to plugins from directories that
        // are not part of plugin directory list anymore.
        String pluginDirectoryName = directoryName(path);
        if (m_pluginDirectories.find(pluginDirectoryName) == WTF::notFound)
            continue;

        RefPtr<PluginPackage> package = PluginPackage::createPackageFromCache(path, lastModified, name, desc, mimeDesc);

        if (package && cachedPlugins.add(package).isNewEntry) {
            cachedPluginPathsWithTimes.add(package->path(), package->lastModified());
            cachedPluginsByPath.add(package->path(), package);
        }
    }

    m_plugins.swap(cachedPlugins);
    m_pluginsByPath.swap(cachedPluginsByPath);
    m_pluginPathsWithTimes.swap(cachedPluginPathsWithTimes);
}
示例#27
0
//文件自检功能
bool PackFile::selfCheck(SELFCHECK_CALLBACK callBack)
{
	if(0==m_hPakFile) 
	{
		setLastError(AXP_ERR_PARAM);
		return false;
	}

	//编辑模式错误
	if(m_fileHead.nEditFlag != 0)
	{
		setLastError(AXP_ERR_FILE_EDITMODE);
		return false;
	}

	//打开List文件
	IStream* pListStream = openFile(LIST_FILENAME);
	if(!pListStream) return false;

	//skip first line
	pListStream->skipLine();

	//read second line
	char szTempLine[MAX_PATH*4] = {0};
	int nLineSize = pListStream->readLine(szTempLine, MAX_PATH*4);
	int nFileCount = atoi(szTempLine);

	//记录已经检查过的HashNode索引
	std::set< unsigned int > setHashNode;
	//记录已经检查过的BlockNode索引
	std::set< unsigned int > setBlockNode;

	//逐行读文件
	int nFileListSize = 0;
	while (!pListStream->eof())
	{
		int nLineLength = pListStream->readLine(szTempLine, MAX_PATH*4);
		if(0 == nLineLength) 
		{
			pListStream->close();
			setLastError(AXP_ERR_FILE_FORMAT, "list file second line=0");
			return false;
		}

		//分析文件描述
		std::vector< std::string > vStringVec;
		convertStringToVector(szTempLine, vStringVec, "|", true, false);
		if(vStringVec.size() != 3) 
		{
			pListStream->close();
			setLastError(AXP_ERR_FILE_FORMAT, "list file=%s", szTempLine);
			return false;
		}

		//获得文件信息
		std::string& strFileName = vStringVec[0];
		unsigned int nFileSize, nFileCRC;
		sscanf(vStringVec[1].c_str(), "%08X", &(nFileSize));
		sscanf(vStringVec[2].c_str(), "%08X", &(nFileCRC));

		//读入文件
		IStream* pFileStream = openFile(strFileName.c_str());	//打开文件
		if(!pFileStream)
		{
			pListStream->close();
			return false;
		}

		unsigned int nStreamSize = pFileStream->size();
		if(nStreamSize != nFileSize)
		{
			pFileStream->close();
			pListStream->close();
			setLastError(AXP_ERR_FILE_FORMAT, "file=%s, sizedif(%d!=%d)", 
				strFileName.c_str(), nStreamSize, nFileSize);
			return false;
		}

		char* pTempBuf = new char[nStreamSize];
		if(nStreamSize != pFileStream->read(pTempBuf, nStreamSize))
		{
			pFileStream->close();
			pListStream->close();
			setLastError(AXP_ERR_FILE_READ, "file=%s", strFileName.c_str());
		}
		pFileStream->close(); pFileStream=0;

		//计算文件实际crc
		unsigned int  nStreamCRC;
		crcMemory32(pTempBuf, nStreamSize, nStreamCRC);
		delete[] pTempBuf; pTempBuf=0;

		if(nStreamCRC != nFileCRC)
		{
//			pFileStream->close();
			pListStream->close();
			setLastError(AXP_ERR_FILE_FORMAT, "file=%s, crcdif(%d!=%d)", 
				strFileName.c_str(), nStreamCRC, nFileCRC);
			return false;
		}

		//保存分析过的文件Hash和Block数据

		//得到Hash数据
		int nHashPos = getStringPosInHashTable(normaliseName(strFileName).c_str());
		setHashNode.insert(nHashPos);

		//得到Block数据
		unsigned int nBlockIndex = getHashNodeBlockIndex(m_hashTable[nHashPos]);
		setBlockNode.insert(nBlockIndex);

		nFileListSize++;
	};
	pListStream->close(); pListStream=0;

	//文件个数检查
	if(nFileListSize != nFileCount)
	{
		setLastError(AXP_ERR_FILE_FORMAT, "file countdif(%d!=%d)", nFileListSize, nFileCount);
		return false;
	}

	//得到(list)的Hash数据
	int nListFileHashPos = getStringPosInHashTable(LIST_FILENAME);
	//得到(list)的Block数据
	unsigned int nListFileBlockIndex = getHashNodeBlockIndex(m_hashTable[nListFileHashPos]);

	//检查是否有未引用的Hash数据
	for(int i=0; i<HASH_TABLE_SIZE; i++)
	{
		const FILE_HASHNODE& hashNode = m_hashTable[i];
		if(!getHashNodeExists(hashNode)) continue;

		if(setHashNode.find(i) != setHashNode.end()) continue;
		if(i==nListFileHashPos) continue;

		//未引用的Hash数据
		setLastError(AXP_ERR_FILE_FORMAT, "unref hashnode(%d)", i);
		return false;
	}

	//检查是否有未引用的BlockNode数据
	for(int i=0; i<(int)m_blockTable.size(); i++)
	{
		const FILE_BLOCKNODE& blockNode = m_blockTable[i];
		if(!getBlockNodeUsed(blockNode)) continue;
		if(setBlockNode.find(i) != setBlockNode.end()) continue;
		if(i==nListFileBlockIndex) continue;

		//未引用的Hash数据
		setLastError(AXP_ERR_FILE_FORMAT, "unref blocknode(%d)", i);
		return false;
	}

	return true;
}
示例#28
0
TorrentDetails::TorrentDetails(QWidget* me, TorrentDownload* obj)
	: m_download(obj), m_bFilled(false)
{
	connect(obj, SIGNAL(destroyed(QObject*)), this, SLOT(deleteLater()));
	setupUi(me);
	TorrentDownload::m_worker->setDetailsObject(this);
	
	m_pPiecesModel = new TorrentPiecesModel(treePieces, obj);
	treePieces->setModel(m_pPiecesModel);
	treePieces->setItemDelegate(new BlockDelegate(treePieces));
	
	m_pPeersModel = new TorrentPeersModel(treePeers, obj);
	treePeers->setModel(m_pPeersModel);
	
	m_pFilesModel = new TorrentFilesModel(treeFiles, obj);
	treeFiles->setModel(m_pFilesModel);
	treeFiles->setItemDelegate(new TorrentProgressDelegate(treeFiles));
	
	QHeaderView* hdr = treePeers->header();
	hdr->resizeSection(1, 110);
	hdr->resizeSection(3, 50);
	hdr->resizeSection(4, 70);
	
	for(int i=5;i<9;i++)
		hdr->resizeSection(i, 70);
	
	hdr->resizeSection(9, 300);
	
	hdr = treeFiles->header();
	hdr->resizeSection(0, 500);
	
	QAction* act;
	QMenu* submenu;
	
	m_pMenuFiles = new QMenu(me);
	submenu = new QMenu(tr("Priority"), m_pMenuFiles);
	
	act = submenu->addAction( tr("Do not download") );
	connect(act, SIGNAL(triggered()), this, SLOT(setPriority0()));
	act = submenu->addAction( tr("Normal") );
	connect(act, SIGNAL(triggered()), this, SLOT(setPriority1()));
	act = submenu->addAction( tr("Increased") );
	connect(act, SIGNAL(triggered()), this, SLOT(setPriority4()));
	act = submenu->addAction( tr("Maximum") );
	connect(act, SIGNAL(triggered()), this, SLOT(setPriority7()));
	
	m_pMenuFiles->addAction(actionOpenFile);
	m_pMenuFiles->addMenu(submenu);
	
	connect(treeFiles, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(fileContext(const QPoint&)));
	connect(treeFiles, SIGNAL(doubleClicked(const QModelIndex &)), this, SLOT(openFile()));
	
	m_pMenuPeers = new QMenu(me);
	act = m_pMenuPeers->addAction( tr("Ban") );
	act = m_pMenuPeers->addAction( tr("Information") );
	connect(act, SIGNAL(triggered()), this, SLOT(peerInfo()));
	
	connect(treePeers, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(peerContext(const QPoint&)));
	connect(actionOpenFile, SIGNAL(triggered()), this, SLOT(openFile()));
	
	refresh();
}
示例#29
0
void decompressHuffman(FILE** file, FILE** ptFileOutput, char* fileInputName) {
	char c;
	char* bufferCode;
	char currentOctet[7];
	int i = 0, tailleBuf;
	int valueChar;
	int tailleDico = 0, tailleTab;
	int* intTab;
	char* charTab;
	char* tabChar;
	char* decodedFileName;
	elementListe* elemL = NULL;
	elementListe** ptListe = &elemL;

	/* temps de traitement */
	clock_t start_time, end_time;
	start_time = clock();

	bufferCode = calloc(1, sizeof(char));
	if (bufferCode == NULL) {
		printf("Erreur d'allocation bufferCode.\n");
		exit(-1);
	}

	/* Lire la taille des structures au début du fichier */
	fread(&tailleDico, sizeof(int), 1, *file);
	/*printf("%d\n", tailleDico);*/

	charTab = calloc(1, sizeof(char));
	intTab = calloc(1, sizeof(int));
	if ((intTab == NULL) || (charTab == NULL)) {
		printf("Erreur d'allocation intTab ou  charTab.\n");
		exit(-1);
	}
	i = 0;

	/* Extraction du dictionnaire */
	while (i < tailleDico) {
		charTab = realloc(charTab, sizeof(char) * i + 1);
		intTab = realloc(intTab, sizeof(int) * i + 1);
		if ((intTab == NULL) || (charTab == NULL)) {
			printf("Erreur reallocation intTab ou  charTab.\n");
			exit(-1);
		}

		fread(&charTab[i], sizeof(char), 1, *file);
		fread(&intTab[i], sizeof(int), 1, *file);
		i++;
	}

	/* Affichage des caractères */
	/*for (i = 0; i < tailleDico; i++) {
	 printf("1- %c %d\n", charTab[i], intTab[i]);
	 }*/

	tailleTab = tailleDico;

	/* Creation de liste chainee */
	for (i = 0; i < tailleTab; i++) {
		createChainedList(ptListe, charTab[i], intTab[i]);
	}

	printf("\n");

	while ((*ptListe)->suivant != NULL) {
		insertNewNodeInChainedList(ptListe);
	}

	/* La liste ne contient plus qu'un seul element qui contiend l'arbre entier */
	tabChar = calloc(1, sizeof(char*));
	if (tabChar == NULL) {
		printf("Erreur d'allocation tabChar.\n");
		exit(-1);
	}

	/* Parcours d'arbre*/
	prefixeHuffmanTree(elemL->noeudIntermediaire, tabChar, 0);

	/* affichage caractères codés */
	for (i = 0; i < 256; i++) {
		if (code[i])
			printf("'%c': %s\n", i, code[i]);
	}

	printf("Decompression en cours, veuillez patienter . . .\n");

	/* on parcours le fichier compresse */
	bufferCode = calloc(1, sizeof(char));
	if(bufferCode == NULL){
		printf("Erreur d'allocation bufferCode.\n");
		exit(-1);
	}
	while (!feof(*file)) {
		c = fgetc(*file);
		bufferCode = realloc(bufferCode, 7 * (i + 2) * sizeof(char));
		if(bufferCode == NULL){
			printf("Erreur d'allocation bufferCode.\n");
			exit(-1);
		}
		valueChar = c;
		decimalToBinary(valueChar, currentOctet);
		strcat(bufferCode, currentOctet);
		i++;

		/*printf("%c", c);*/
	}

	/* on supprime les 8 derniers caracteres = \0 */
	tailleBuf = strlen(bufferCode);
	for (i = (tailleBuf - 8); i < tailleBuf; i++) {
		bufferCode[i] = '\0';
	}

	/* Affichage du buffer */
	/*printf("%s\n", bufferCode);*/

	/*Ecriture de la taille de la table des fréquences */
	decodedFileName = calloc((8 + strlen(fileInputName)), sizeof(char));
	if (decodedFileName == NULL) {
		printf("Erreur d'allocation fileOutputName.\n");
		exit(-1);
	}

	strcat(fileInputName, ".decoded");
	*ptFileOutput = createFile(fileInputName);
	closeFile(ptFileOutput);
	openFile(fileInputName, ptFileOutput, "wb+");

	decodeHuffmanTree(bufferCode, elemL->noeudIntermediaire, ptFileOutput);

	closeFile(ptFileOutput);

	free(decodedFileName);
	decodedFileName = NULL;
	free(bufferCode);
	free(elemL);
	elemL = NULL;
	free(intTab);
	intTab = NULL;
	free(charTab);
	charTab = NULL;
	free(tabChar);
	tabChar = NULL;

	end_time = clock();
	printf("Decompression effectuee en %lu s.\n",
			(long) ((end_time - start_time) / CLOCKS_PER_SEC));

}
示例#30
0
    void Workspace<EncodingT>::loadXML(DOMElement* xml_wrks)
    {
        DOMElement*  xml_file       = NULL;
        DOMText*     xml_text       = NULL;
        DOMNodeList* xml_list       = NULL;

        if (!xml_wrks || string("Workspace") != A(xml_wrks->getTagName()))
        {
            m_logger->fatalStream() << "Workspace::loadXML() : XML workspace element expected";
            //throw BadXmlFormatException("XML entity element expected");
        }
        else {
            m_name = C(xml_wrks->getAttribute( AX("Name") ));
            m_author = C(xml_wrks->getAttribute( AX("Author") ));
            m_brief = C(xml_wrks->getAttribute( AX("Brief") ));
            m_version = C(xml_wrks->getAttribute( AX("Version") ));
            m_type = (A(xml_wrks->getAttribute( AX("Type") ))==string("File"))?WRK_FILE:WRK_PROJECT;
            m_option = ToInt::parse(A(xml_wrks->getAttribute( AX("Option") )));
            m_comment = EncodingT::EMPTY;
            m_files.clear();
            if (xml_wrks->hasChildNodes())
            {
                 xml_list = xml_wrks->getChildNodes();
                 for (unsigned int i=0; i<xml_list->getLength(); ++i)
                 {
                     xml_file = (DOMElement*) xml_list->item(i);
                     if (xml_file && string("File") == A(xml_file->getTagName()))
                     {
                         File<EncodingT> fi;
                         fi.loadXML(xml_file);
                         m_files.push_back(fi);
                     }

                     if (xml_file && string("Comments") == A(xml_file->getTagName()))
                     {
                        try 
                        {
                            xml_text = (DOMText*) xml_file->getFirstChild();
                            if (xml_text)
                            {
                                m_comment = C(xml_text->getData());
                            }
                        } 
                        catch(DOMException & e) 
                        {
                            m_logger->fatalStream() << "Workspace::loadXML() : XML wrk comments element error: " 
                                                    << A(e.getMessage());
                            //throw e;
                        }
                     }
                 }
            }
            // Add wokspace file if it is not defined.
            if (m_type==WRK_FILE && 
                (m_files.empty()  || 
                 sizeFiles() != 1 || 
                 beginFiles()->getName() != getName()))
            {
                openFile(getName(), true);
            }
            m_logger->debugStream() << "set workspace : "
                                    << encode<EncodingT,ansi>(m_name) << ", "
                                    << encode<EncodingT,ansi>(m_comment);
            m_logger->debug("Workspace::loadXML() : XML workspace loaded");
        }
    }