bool PopulateDayFolder::putPhotosInTarget()
	{
		for (auto it = pPhotosPerName.cbegin(), end = pPhotosPerName.cend(); it != end; ++it)
		{
			YString newIncompleteName(pTargetFolder);
			newIncompleteName << IO::Separator << it->first; // without index or extension
			const auto& photos = it->second;

			unsigned int size = static_cast<unsigned int>(photos.size());

			if (size == 1u)
			{
				auto& photoPtr = photos[0];
				assert(!(!photoPtr));
				YString name(newIncompleteName);
				name << ".jpg";

				YString originalPath = photoPtr->originalPath();

				// Yuni doesn't seem to have any move function...
				if (!moveFile(logs, originalPath, name))
					return false;
			}
			else
			{
				::GenericTools::Numeration numeration(size + 1u);

				for (unsigned int i = 0u; i < size; ++i)
				{
					auto& photoPtr = photos[i];
					assert(!(!photoPtr));

					YString name(newIncompleteName);
					name << '_' << numeration.next() << ".jpg";

					YString originalPath = photoPtr->originalPath();

					if (originalPath != name)
					{
						if (!moveFile(logs, originalPath, name))
							return false;
					}
				}
			}
		}

		return true;
	}
Example #2
0
LogFile* ArchiveByNumberStrategy::archive(LogFile* pFile)
{
	std::string basePath = pFile->path();
	delete pFile;
	int n = -1;
	std::string path;
	do
	{
		path = basePath;
		path.append(".");
		NumberFormatter::append(path, ++n);
	}
	while (exists(path));
	
	while (n >= 0)
	{
		std::string oldPath = basePath;
		if (n > 0)
		{
			oldPath.append(".");
			NumberFormatter::append(oldPath, n - 1);
		}
		std::string newPath = basePath;
		newPath.append(".");
		NumberFormatter::append(newPath, n);
		moveFile(oldPath, newPath);
		--n;
	}
	return new LogFile(basePath);
}
bool TestCase_Core_File_File::MoveFileTest()
{
    LLBC_PrintLine("Move file test:");

    const LLBC_String moveFileName = _testFileName + ".move";
    LLBC_File file(_testFileName, LLBC_FileMode::BinaryReadWrite);
    if (!file.IsOpened())
    {
        LLBC_PrintLine("Open test file[%s] failed, error: %s", _testFileName.c_str(), LLBC_FormatLastError());
        return false;
    }

    LLBC_PrintLine("test file[name: %s, will move] opened, write line string: Hello World!", _testFileName.c_str());
    file.WriteLine("Hello World");

    LLBC_PrintLine("Begin move(overlapped): %s ---> %s", _testFileName.c_str(), moveFileName.c_str());
    if (file.MoveFile(moveFileName, true) != LLBC_OK)
    {
        LLBC_PrintLine("Move file failed, error: %s", LLBC_FormatLastError());
        return false;
    }

    LLBC_PrintLine("Open the move file:");
    LLBC_File moveFile(moveFileName, LLBC_FileMode::BinaryRead);
    if (!moveFile.IsOpened())
    {
        LLBC_PrintLine("Failed to open move file, error: %s", LLBC_FormatLastError());
        return false;
    }

    LLBC_PrintLine("Move file opened, content: %s", moveFile.ReadToEnd().c_str());
    moveFile.Close();

    const LLBC_String copyFileName = _testFileName + ".copy";
    LLBC_File::CopyFile(moveFileName, copyFileName, true);
    LLBC_PrintLine("Copy move file and move again(don't overlapped): %s ---> %s", copyFileName.c_str(), copyFileName.c_str());
    if (LLBC_File::MoveFile(copyFileName, moveFileName, false) == LLBC_OK)
    {
        LLBC_PrintLine("Move success, failed. check your code!");
        LLBC_File::DeleteFile(copyFileName);
        LLBC_File::DeleteFile(moveFileName);

        return false;
    }
    else
    {
        LLBC_PrintLine("Move failed, error: %s, right!", LLBC_FormatLastError());
    }

    LLBC_PrintLine("Delete copy file and move file");
    LLBC_File::DeleteFile(copyFileName);
    LLBC_File::DeleteFile(moveFileName);

    LLBC_PrintLine("");

    return true;
}
Example #4
0
void
backupfsExit (bkupInfo* info, int exitStatus)
{
    assert(info);

    closeFiles(info);
    removeFiles(info);
    moveFile(info->oldJpath, info->jpath);
    exit(exitStatus);
}
Example #5
0
static int archiveLog (LOGGER *p_logger, char *archiveDate) {

	int		retval	= SUCCESS;
	char		archivePath[LOG_MAX_PATH_LEN+1];
	char		*fname;
	char		*ext;
	char		timeStr[64];	/* .HH.MM.SS */
	char		newName[LOG_MAX_FILENAME_LEN+1];
	struct tm	*lt;

	if (p_logger == NULL) {
		fprintf (stderr, "ERROR: %s - NULL logger provided\n", __FUNCTION__);
		return ERROR;
	}

	if (!(p_logger->optionMask & NODE_IN_USE)) {
		fprintf (stderr, "ERROR: %s - Logger not in use\n", __FUNCTION__);
		return ERROR;
	}

	sprintf (archivePath, "%s/%s", p_logger->archivePath, archiveDate);
	if (!fileExists (archivePath)) {
		if (makeDirectory (archivePath, YES, DIRECTORY_CREATE_PERMS)) {
			fprintf (stderr, "ERROR: %s - could not create directory %s\n", __FUNCTION__, archivePath);
			retval = ERROR;
		}
	}

	fname = strdup (p_logger->logName);
	splitFilenameExt (fname, &ext);		/* Remove the extension, if there is one */

	lt = localtime (&p_logger->lastLogTime);
	sprintf (timeStr, "%02d.%02d.%02d", lt->tm_hour, lt->tm_min, lt->tm_sec);

	sprintf (newName, "%s/%s.%s", archivePath, fname, timeStr);
	free (fname);

	if (p_logger->optionMask & O_LOG_INIT) {
		p_logger->amArchiving = TRUE;
		logMsg (p_logger, V_ALWAYS, S_STATUS, "%s ARCHIVED TO %s", p_logger->name, newName);
		p_logger->amArchiving = FALSE;
	}

	logClose (p_logger);

	if (moveFile (p_logger->fullLogName, newName, NO)) {
		fprintf (stderr, "ERROR: %s - could not move %s to %s\n", __FUNCTION__, p_logger->fullLogName, archivePath);
		retval = ERROR;
	}

	return retval;
}
Example #6
0
int main()
{
    Tree * testTree;
	int (*compare)(void *, void *, void*, void*);
    void (*destroy)(void *);
    compare = &comparePointer;
    destroy = &destroyPointer;
    printDirectory("testdir/");
    deleteFile("testdir/", "text.txt");
    renameFile("testdir/b/", "6.txt", "7.txt");
    moveFile("testdir/a/aa/", "testdir/a/", "3.txt");
	return(0);
}
Example #7
0
int main(int argc, char* argv[]){
	int c;
	int fcounter = 0, hcounter = 0, rcounter = 0;
	int fileArgPos = argc-1; //position of file to be removed in arguments should be last
	
	//get all options
	while((c = getopt(argc, argv, ":fhr")) != -1){
		switch(c) {
		
			case 'h' :
				hcounter = 1;
				break;
			
			case '?' :
				perror("Getopt error.");
				break;
			
		}
	}


	
		if(hcounter){
			printUseMessage();
		}
		char* filename = argv[fileArgPos];
		struct stat  buf;
		
		struct utimbuf  puttime;
		char* bin = getTrash(); 	//Confirm TRASH variable is set, and place it in a string
		if(access(bin, F_OK)){		//Confirm TRASH variable doesn't point to nothing
			perror("TRASH does not point to anything.");
			exit(1);
		}
		char* endZone = getcwd(NULL, 0);
		chdir(bin);
		//confirm file exists
		moveFile(filename, endZone, 0, 1);
	
		
	

}
Example #8
0
void FileUtils::removeFile(const char* src) throw (IOException)
{
#ifdef PLATFORM_UNIX
	if (unlink(src) != 0)
	{
		if (errno != ENOENT)
		{
			throw IOException("Unable to remove file " + std::string(src));
		}
	}
#else
	if (!DeleteFile(src))
	{
		if (GetLastError() == ERROR_ACCESS_DENIED)
		{
			// if another process is using the file, try moving it to
			// a temporary directory and then
			// scheduling it for deletion on reboot
			std::string tempDeletePathBase = tempPath();
			tempDeletePathBase += '/';
			tempDeletePathBase += fileName(src);

			int suffix = 0;
			std::string tempDeletePath = tempDeletePathBase;
			while (fileExists(tempDeletePath.c_str()))
			{
				++suffix;
				tempDeletePath = tempDeletePathBase + '_' + intToStr(suffix);
			}

			LOG(Warn,"Unable to remove file " + std::string(src) + " - it may be in use.  Moving to "
			         + tempDeletePath + " and scheduling delete on reboot.");
			moveFile(src,tempDeletePath.c_str());
			MoveFileEx(tempDeletePath.c_str(),0,MOVEFILE_DELAY_UNTIL_REBOOT);
		}
		else if (GetLastError() != ERROR_FILE_NOT_FOUND)
		{
			throw IOException("Unable to remove file " + std::string(src));
		}
	}
#endif
}
Example #9
0
/**
  @return 0 if the file was saved, 1 if cancled, or -1 if an error occured
*/
int GData::saveFile(SoundFile *s, QString newFilename)
{
  if(newFilename.isNull()) { /*printf("cancled\n");*/ return 1; }
  QString oldFilename(s->filename);
//#ifdef WINDOWS
//  oldFilename.replace(QChar('/'), QChar('\\'));
//#endif
  oldFilename = QDir::convertSeparators(oldFilename);
  int pos = s->stream->pos();
  s->stream->close();
  
  //printf("moveFile(%s, %s);\n", oldFilename.latin1(), newFilename.latin1());
  int ret = (moveFile(oldFilename.latin1(), newFilename.latin1())) ? 0 : -1;
  if(ret == 0) {
	s->stream->open_read(newFilename.latin1());
    s->stream->jump_to_frame(pos);
	s->setSaved(true);
    s->setFilename(newFilename.latin1());
  } else {
    s->stream->open_read(oldFilename.latin1());
	s->stream->jump_to_frame(pos);
  }
  return ret;
}
Example #10
0
static void checkLogRollover (LOGGER *p_logger) {

	char		archiveDate[LOG_SIZE_ARCHIVE_DATE+1];
	time_t		now;

	if (p_logger == NULL) {
		fprintf (stderr, "ERROR: %s - NULL logger provided\n", __FUNCTION__);
		return;
	}

	if (!(p_logger->optionMask & NODE_IN_USE)) {
		fprintf (stderr, "ERROR: %s - Logger not in use\n", __FUNCTION__);
		return;
	}

	if ((p_logger->lastLogTime == 0) || (p_logger->logSize == 0))
		return;

	if ((p_logger->optionMask & O_ARCHIVE)) {
		now = time (NULL);
		/* Check if date changed since last run or log reached rollover size and archive it if so */
		if (((now / 86400) != p_logger->lastLogDay) ||
		   (p_logger->rollOverSize && (p_logger->logSize >= p_logger->rollOverSize))) {
			strftime (archiveDate, LOG_SIZE_ARCHIVE_DATE+1, "%b%d", localtime (&p_logger->lastLogTime));
			if (archiveLog(p_logger, archiveDate) == 0) {
				p_logger->lastLogDay = p_logger->lastLogTime = 0;
				p_logger->logSize = 0;
			}

			if (p_logger->optionMask & O_KEEP_OPEN) {
				logOpen (p_logger);
			}
		}
	} else {
		if (p_logger->rollOverSize && (p_logger->logSize >= p_logger->rollOverSize)) {
			char	*oldExt = ".old";
			char	*fname = strdup (p_logger->logName);
			char	*newName = malloc (strlen (p_logger->fullLogName) + strlen (oldExt) + 1);	/* Reserve characters for old extension */
			char	*ext;

			splitFilenameExt (fname, &ext);
			sprintf (newName, "%s/%s.%s", p_logger->logPath, fname, oldExt);

			if (p_logger->optionMask & O_LOG_INIT) {
				p_logger->amArchiving = TRUE;
				logMsg (p_logger, V_ALWAYS, S_STATUS, "%s TERMINATED %s FILE SIZE %d RENAMED TO %s",
					p_logger->name, p_logger->fullLogName, p_logger->logSize, newName);
				p_logger->amArchiving = FALSE;
			}

			logClose (p_logger);
			if (moveFile (p_logger->fullLogName, newName, TRUE)) {
				fprintf (stderr, "ERROR: %s - could not move %s to %s\n", __FUNCTION__, p_logger->fullLogName, newName);
			}
			p_logger->lastLogDay = p_logger->lastLogTime = 0;
			p_logger->logSize = 0;

			if (p_logger->optionMask & O_KEEP_OPEN) {
				logOpen (p_logger);
			}

			free (newName);
			free (fname);
		}
	}
}
int main() {
	char command[1024];

	printf("------------------\n<<<  Commands >>>\nclf\ncontf\ncof\ncrf\ndef\nmof\nrname\ntappend\ntinsert\nexit()\n");
	printf("\n* Be careful, the program is case sensitive.\n** To get information about how command works, add \\h next to the command (command\\h). \nFor example: clf\\h\n------------------\n\nEnter a command:\n");
	scanf("%s", command);
	while(strcmp("exit()",command)!=0)
	{

		if (strcmp("clf",command)==0)
		{
			clearFile();
		}
		else if (strcmp("contf",command)==0)
		{
			contentFile();
		}
		else if (strcmp("cof",command)==0)
		{
			copyFile();
		}
		else if (strcmp("crf",command)==0)
		{
			createFile();
		}
		else if (strcmp("def",command)==0)
		{
			deleteFile();
		}
		else if (strcmp("mof",command)==0)
		{
			moveFile();
		}
		else if (strcmp("rname",command)==0)
		{
			rnameFile();
		}
		else if (strcmp("tappend",command)==0)
		{
			tappendFile();
		}
		else if (strcmp("tinsert",command)==0)
		{
			tinsertFile();
		}
		else if(strcmp(command,"clf\\h")==0){
			printf("\n> This function removes all text in a file.\nWhen function asks, You should just enter the file path. \n\n");
		}

		else if(strcmp(command,"contf\\h")==0){
			printf("\n> This function shows the content of a text file, with the ability to pause per page. The number of lines per page can be specified by the user.\nWhen function asks, You should enter the file path and enter a number to specify number of lines per page.\n\n");
		}

		else if(strcmp(command,"cof\\h")==0){
			printf("\n> This function copies the given file to specific path.\nWhen function asks, You should enter the file path and a path you want to copy file in.\n\n");
		}

		else if(strcmp(command,"crf\\h")==0){
			printf("\n> This function creates a file in given path.\nWhen function asks, You should just enter the file path and it will create the file if there is no\nfile with same filename.\n\n");
		}

		else if(strcmp(command,"def\\h")==0){
			printf("\n> This function deletes the given file.\nWhen function asks, You should just enter the file path and it will delete the file if file exists.\n\n");
		}

		else if(strcmp(command,"mof\\h")==0){
			printf("\n> This function moves the given file to specific pat.\nWhen function asks, You should enter the file path and a path you want to move file in.\n\n");
		}

		else if(strcmp(command,"rname\\h")==0){
			printf("\n> This function change name of the given file.\nWhen function asks, You should just enter the file path and it will change the file name if there is no file with same filename.\n\n");
		}

		else if(strcmp(command,"tappend\\h")==0){
			printf("\n> This function appends given text to the end of the given file.\nWhen function asks, You should enter a text and file path.\n\n");
		}

		else if(strcmp(command,"tinsert\\h")==0){
			printf("\n> This function inserts given text in a specific position (counted in characters) of the file.\nWhen function asks, You should enter file path, text and the position you want to insert text in.\n\n");
		}
		else{
			printf("\n!!! Command is not valid. Please enter a from the menu. !!!\n\n");
		}
		scanf("%s", command);

	}
}
Example #12
0
bool BaseInFileStream::ResolveCompleteMetadata(Variant &metaData) {
	if ((bool)metaData[CONF_APPLICATION_EXTERNSEEKGENERATOR])
		return false;
	//1. Create the document
	BaseMediaDocument *pDocument = NULL;
	if (false) {

	}
#ifdef HAS_MEDIA_FLV
	else if (metaData[META_MEDIA_TYPE] == MEDIA_TYPE_FLV ||
			metaData[META_MEDIA_TYPE] == MEDIA_TYPE_LIVE_OR_FLV) {
		pDocument = new FLVDocument(metaData);
	}
#endif /* HAS_MEDIA_FLV */
#ifdef HAS_MEDIA_MP3
	else if (metaData[META_MEDIA_TYPE] == MEDIA_TYPE_MP3) {
		pDocument = new MP3Document(metaData);
	}
#endif /* HAS_MEDIA_MP3 */
#ifdef HAS_MEDIA_MP4
	else if (metaData[META_MEDIA_TYPE] == MEDIA_TYPE_MP4
			|| metaData[META_MEDIA_TYPE] == MEDIA_TYPE_M4A
			|| metaData[META_MEDIA_TYPE] == MEDIA_TYPE_M4V
			|| metaData[META_MEDIA_TYPE] == MEDIA_TYPE_MOV
			|| metaData[META_MEDIA_TYPE] == MEDIA_TYPE_F4V) {
		pDocument = new MP4Document(metaData);
	}
#endif /* HAS_MEDIA_MP4 */
#ifdef HAS_MEDIA_NSV
	else if (metaData[META_MEDIA_TYPE] == MEDIA_TYPE_NSV) {
		pDocument = new NSVDocument(metaData);
	}
#endif /* HAS_MEDIA_NSV */

	else {
		FATAL("File type not supported yet. Partial metadata:\n%s",
				STR(metaData.ToString()));
		return false;
	}

	//2. Process the document
	FINEST("Processing file %s", STR(metaData[META_SERVER_FULL_PATH]));
	if (!pDocument->Process()) {
		FATAL("Unable to process document");
		delete pDocument;
		if ((bool)metaData[CONF_APPLICATION_RENAMEBADFILES]) {
			moveFile(metaData[META_SERVER_FULL_PATH],
					(string) metaData[META_SERVER_FULL_PATH] + ".bad");
		} else {
			WARN("File %s will not be renamed",
					STR(metaData[META_SERVER_FULL_PATH]));
		}
		return false;
	}

	//3. Get the medatada
	metaData = pDocument->GetMetadata();

	//4. cleanup
	delete pDocument;

	//5. Done
	return true;
}
Example #13
0
int process(int fd, char* watch_dir)
{
	struct inotify_event* event;
	int length = 0;
	char buffer[BUF_SIZE];

	length = read(fd, buffer, BUF_SIZE);
	for (int i = 0; i < length;)
	{
		event = (struct inotify_event*)(buffer + i);
		printf("\n");
		printEvent(event);
		char* extension;

		if (event->mask & IN_DELETE_SELF)
		{
			writeWarning("Watch directory was deleted");
			return 1;
		}
		else if ((extension = strstr(event->name, ".")) != NULL)
		{
			size_t name_len = strlen(watch_dir) + strlen(event->name) + 1;
			char* fullname = malloc(name_len);
			snprintf(fullname, name_len, "%s%s", watch_dir, event->name);

			int file_size = getFileSize(fullname);
			printf("File size: %d\n", file_size);

			if (file_size > 0) // firefox likes to create empty files for the temp files to be renamed to
			{
				printf("Extension: %s\n", extension);
				if (strend(extension, ".txt") || strend(extension, ".pdf"))
				{
					moveFile(fullname, "/home/calcifer/Documents");
				}
				else if (strend(extension, ".tar.gz") || strend(extension, ".tar") || strend(extension, ".tar.bz2") ||
				         strend(extension, ".zip") || strend(extension, ".7z") || strend(extension, ".ar") ||
				         strend(extension, ".ace"))
				{
					moveFile(fullname, "/home/calcifer/Documents/archives");
				}
				else if (strend(extension, ".deb") || strend(extension, ".rpm") ||
				         strend(extension, ".msi") ||
				         strend(extension, ".apk") ||
				         strend(extension, ".app"))
				{
					moveFile(fullname, "/home/calcifer/Documents/installers");
				}
				else if (strend(extension, ".torrent"))
				{
					moveFile(fullname, "/home/calcifer/Downloads/torrents");
				}
				else if (strend(extension, ".mp4") || strend(extension, ".video") || strend(extension, ".mkv") || strend(extension, ".avi"))
				{
					moveFile(fullname, "/home/calcifer/Videos");
				}
				else if (strend(extension, ".odt") || strend(extension, ".ods") || strend(extension, ".odp") ||
				         strend(extension, ".doc") || strend(extension, ".xls") || strend(extension, ".ppt") ||
				         strend(extension, ".docx") || strend(extension, ".xlsx") || strend(extension, ".pptx"))
				{
					moveFile(fullname, "/home/calcifer/Documents/office");
				}
				else if (strend(extension, ".ovpn"))
				{
					moveFile(fullname, "/home/calcifer/Web");
				}
				else if (strend(extension, ".mp3"))
				{
					moveFile(fullname, "/home/calcifer/Music");
				}
				else if (strend(extension, ".gif"))
				{
					moveFile(fullname, "/home/calcifer/Pictures/gifs");
				}
				else if (strend(extension, ".jpg") || strend(extension, ".jpeg") ||
				         strend(extension, ".png") || strend(extension, ".bmp") ||
				         strend(extension, ".svg") ||
				         strend(extension, ".tif") || strend(extension, ".tiff"))
				{
					moveFile(fullname, "/home/calcifer/Pictures");
				}
				else if (strend(extension, ".c") || strend(extension, ".h") ||
				         strend(extension, ".cpp") || strend(extension, ".hpp") ||
				         strend(extension, ".py") || strend(extension, ".py3") ||
				         strend(extension, ".rb") ||
				         strend(extension, ".cs") ||
				         strend(extension, ".php") || strend(extension, ".js") || strend(extension, ".html") ||
				         strend(extension, ".java"))
				{
					moveFile(fullname, "/home/calcifer/Documents/code/unorganized");
				}
				else if (strend(extension, ".iso") || strend(extension, ".vbox") || strend(extension, ".vdi"))
				{
					moveFile(fullname, "/home/calcifer/Documents/disc-images");
				}
				else if (strend(extension, ".desktop"))
				{
					moveFile(fullname, "/home/calcifer/Desktop");
				}
			}
			free(fullname);
		}

		i += sizeof(struct inotify_event) + event->len;
	}

	return 0; // shouldn't ever be possible, infinite loop
}
Example #14
0
File: main.c Project: liuch/tags
int main(int argc, char *argv[])
{
	setlocale(LC_ALL, "");
	if (argc == 1)
	{
		showWarning(WarnOptions);
		return EXIT_FAILURE;
	}

	int res = EXIT_SUCCESS;
	int opt, oi = -1;
	flags = NoneFlag;
	while (res == EXIT_SUCCESS && (opt = getopt_long(argc, argv, "a:cd:f:hilprs:vw:", long_options, &oi)) != -1)
	{
		switch (opt)
		{
			case 'a':
				addOptArg = makeWideCharString(optarg, 0);
				break;
			case 'c':
				flags |= InitFlag;
				break;
			case 'd':
				delOptArg = makeWideCharString(optarg, 0);
				break;
			case 'f':
				fieldsList = makeWideCharString(optarg, 0);
				break;
			case 'h':
				showHelp();
				return EXIT_SUCCESS;
			case 'i':
				flags |= InfoFlag;
				break;
			case 'l':
				flags |= ListFlag;
				break;
			case 'p':
				flags |= PropFlag;
				break;
			case 'r':
				flags |= RecurFlag;
				break;
			case 's':
				setOptArg = makeWideCharString(optarg, 0);
				break;
			case 'v':
				flags |= VersionFlag;
				break;
			case 'w':
				whrOptArg = makeWideCharString(optarg, 0);
				break;
			case MoveFileOption:
				flags |= MoveFileFlag;
				break;
			default:
				showWarning(WarnOther);
				res = EXIT_FAILURE;
				break;
		}
	}
	if (res != EXIT_SUCCESS)
		return res;

	res = EXIT_FAILURE;
	enum WarnMode warn = WarnOptions;
	if (addOptArg == NULL && delOptArg == NULL && setOptArg == NULL)
	{
		int filesCnt = argc - optind;
		if (flags == InitFlag) // -c option
		{
			if (filesCnt == 0 && whrOptArg == NULL && fieldsList == NULL)
			{
				res = tagsCreateIndex();
				warn = WarnNone;
			}
		}
		else if (flags == InfoFlag) // -i option
		{
			if (filesCnt > 0)
			{
				if (whrOptArg == NULL && fieldsList == NULL)
				{
					res = tagsStatus(&argv[optind], filesCnt);
					warn = WarnNone;
				}
			}
			else
				warn = WarnFiles;
		}
		else if ((flags & ListFlag) != 0) // -l option
		{
			if ((flags & ~(ListFlag | RecurFlag)) == 0 && filesCnt == 0)
			{
				res = tagsList(fieldsList, whrOptArg);
				warn = WarnNone;
			}
		}
		else if ((flags & PropFlag) != 0) // -p option
		{
			if ((flags & ~(PropFlag | RecurFlag)) == 0 && filesCnt == 0 && whrOptArg == NULL && fieldsList == NULL)
			{
				res = tagsShowProps();
				warn = WarnNone;
			}
		}
		else if (flags == VersionFlag) // -v option
		{
			if (filesCnt == 0 && whrOptArg == NULL && fieldsList == NULL)
			{
				showVersion();
				res = EXIT_SUCCESS;
				warn = WarnNone;
			}
		}
		else if (flags == MoveFileFlag) // --rename-file option
		{
			if (filesCnt == 2 && whrOptArg == NULL && fieldsList == NULL)
			{
				res = moveFile(&argv[optind]);
				warn = WarnNone;
			}
		}
	}
	else  // -a -d -s options
	{
		if (flags == NoneFlag)
		{
			warn = WarnFiles;
			int filesCnt = argc - optind;
			if (filesCnt > 0)
			{
				res = tagsUpdateFileInfo(&argv[optind], filesCnt, addOptArg, delOptArg, setOptArg, whrOptArg);
				warn = WarnNone;
			}
		}
	}

	freeResources();
	if (warn != WarnNone)
		showWarning(warn);
	return res;
}
Example #15
0
int openportWrite(unsigned char *buf, unsigned short nbytes, int isHk)
{
  static unsigned int dataCounter=0;
  static unsigned int hkCounter=0;
  static unsigned int eventCounter=0;
  static int first=1;
  static struct timeval lastTime;
  struct timeval newTime;
  static FILE *fp=NULL;
  static int openedFile=0;
  static int bytesToFile=0;
  static char fileName[FILENAME_MAX];

  static int openportRun=-1;
  if(openportRun<0) openportRun=getOpenportRunNumber();
  short numWrapBytes=0;
  float timeDiff;
  int retVal=0;
  if(first) {
    gettimeofday(&lastTime,0);
    first=0;
  }

  
  unsigned short *openportBuffer=openport_wrap_buffer(buf,nbytes,&numWrapBytes);

  //  const int maxBytesToFile=1000000;
  
  if(!openedFile) {
    sprintf(fileName,"%s/%05d",OPENPORT_STAGE_DIR,openportRun);
    makeDirectories(fileName);
    sprintf(currentOpenportDir,"%s/%05d",OPENPORT_OUTPUT_DIR,openportRun);
    makeDirectories(currentOpenportDir);
    sprintf(fileName,"%s/%05d/%06d",OPENPORT_STAGE_DIR,openportRun,getOpenportFileNumber());
    printf("Openport file: %s\n",fileName);
    fp=fopen(fileName,"wb");
    openedFile=1;
  }

  if(fp) {
    fwrite(openportBuffer,numWrapBytes,1,fp);
    bytesToFile+=numWrapBytes;


    //Now some accounting
    dataCounter+=nbytes;
    if(isHk) hkCounter+=nbytes;
    else eventCounter+=nbytes;
    printf("openportWrite %d bytes, file %d, hk %d, event %d\n",nbytes,bytesToFile,hkCounter,eventCounter);

    if(bytesToFile>maxFileSize) {
      printf("Finished file %s -- with %d bytes\n",fileName,bytesToFile);
      fclose(fp);
      //      zipFileInPlace(fileName);
      moveFile(fileName,currentOpenportDir);
      fp=NULL;
      openedFile=0;
      bytesToFile=0;

   
      gettimeofday(&newTime,0);
      timeDiff=getTimeDiff(lastTime,newTime);
      printf("Transferred %u bytes (%u hk, %u event) in %2.2f seconds (%3.4f bytes/sec)\n",dataCounter,hkCounter,eventCounter,timeDiff,((float)dataCounter)/timeDiff);
      //      sleep(5);
      dataCounter=0;
      hkCounter=0;
      eventCounter=0;
      lastTime=newTime;
    
    }
  }
  
  return retVal;
}
Example #16
0
static void MainLoop(void)
{
	uint ip = 0;

	if(!DoLock())
		return;

	removeFileIfExist(ParamsFile);
	removeFileIfExist(AnswerFile);

	mutexRelease(MutexHandle);

	SockStartup();
	cout("START\n");

	while(!collectEvents(StopAppEventHandle, 0))
	{
		collectEvents(StartEventHandle, 3000);

		if(!DoLock())
			break;

		if(existFile(ParamsFile))
		{
			char *ansFile;

			if(Serializer)
			{
				char *wrkFile = makeTempFile(NULL);

				Serializer(ParamsFile, wrkFile);
				removeFile(ParamsFile);
				moveFile(wrkFile, ParamsFile);
				memFree(wrkFile);
			}
			removeFileIfExist(AnswerFile); // Cleanup
			mutexRelease(MutexHandle);

			cout("REQUEST START %I64u\n", getFileSize(ParamsFile));
			ansFile = sockClient((uchar *)&ip, ServerDomain, ServerPort, ParamsFile, Idle);
			cout("REQUEST END %08x\n", ansFile);

			if(StopAppEventCaught || !DoLock())
			{
				if(ansFile)
				{
					removeFile(ansFile);
					memFree(ansFile);
				}
				break;
			}
			removeFileIfExist(AnswerFile); // Cleanup (2bs)

			if(ansFile)
			{
				if(Deserializer)
				{
					Deserializer(ansFile, AnswerFile);
					removeFile(ansFile);
				}
				else
					moveFile(ansFile, AnswerFile);

				memFree(ansFile);
				cout("ANSWER %I64u\n", getFileSize(AnswerFile));
			}
			removeFileIfExist(ParamsFile); // Cleanup
			eventSet(AnswerEventHandle); // リクエストの完了(応答)を通知
		}
		mutexRelease(MutexHandle);
	}
	cout("END\n");
	SockCleanup();

	if(handleWaitForMillis(MutexHandle, 2000))
	{
		// Cleanup
		removeFileIfExist(ParamsFile);
		removeFileIfExist(AnswerFile);

		mutexRelease(MutexHandle);
	}
}
Example #17
0
/*
	srcFile
		読み込み元ファイル

	destFile
		出力先ファイル
		srcFile と同じパスであっても良い。

	textMode
		真のとき -> テキストモード
		偽のとき -> バイナリーモード

	uint readElement(FILE *fp)
		1レコード読み込む。
		これ以上レコードが無いときは 0 を返すこと。

	void writeElement_x(FILE *fp, uint element)
		1レコード書き込む。
		必要であれば element を開放すること。

	sint compElement(uint element1, uint element2)
		element1 と element2 を比較した結果を strcmp() 的に返す。

	partSize
		メモリに一度期に読み込める「レコードの合計バイト数」の最大値の目安
		srcFile のシーク位置の変化をバイトに換算しているだけ。
		0 のときは常に1レコードずつになる。
		各パートのレコード数が partSize / 100 を超えないようにする。
*/
void MergeSort(
	char *srcFile,
	char *destFile,
	int textMode,
	uint (*readElement)(FILE *fp),
	void (*writeElement_x)(FILE *fp, uint element),
	sint (*compElement)(uint element1, uint element2),
	uint partSize
	)
{
	autoList_t *partFiles = newList();
	autoList_t *elements = NULL;
	char *rMode;
	char *wMode;
	FILE *fp;
	uint64 startPos = 0;

	if(textMode)
	{
		rMode = "rt";
		wMode = "wt";
	}
	else
	{
		rMode = "rb";
		wMode = "wb";
	}
	fp = fileOpen(srcFile, rMode);

	for(; ; )
	{
		uint element = readElement(fp);
		uint64 currPos;

		if(!element)
			break;

		if(!elements)
			elements = createAutoList(partSize / 100 + 1);

		addElement(elements, element);

		currPos = _ftelli64(fp);
		errorCase(currPos < 0);

		if(startPos + partSize <= currPos || partSize / 100 < getCount(elements))
		{
			CommitPart(partFiles, wMode, writeElement_x, compElement, elements);
			elements = NULL;
			startPos = currPos;

			// メモリのデフラグ?
			{
				char *wkFile = makeTempPath("work");

				writeLines_cx(wkFile, partFiles);
				partFiles = readLines(wkFile);

				removeFile(wkFile);
				memFree(wkFile);
			}
		}
	}
	if(elements)
		CommitPart(partFiles, wMode, writeElement_x, compElement, elements);

	fileClose(fp);

	while(2 < getCount(partFiles))
	{
		char *partFile1 = (char *)unaddElement(partFiles);
		char *partFile2 = (char *)unaddElement(partFiles);
		char *partFile3 = makeTempPath("part");

		MergePart(partFile1, partFile2, partFile3, rMode, wMode, readElement, writeElement_x, compElement);

		memFree(partFile1);
		memFree(partFile2);

		insertElement(partFiles, 0, (uint)partFile3);
	}
	switch(getCount(partFiles))
	{
	case 2:
		MergePart(getLine(partFiles, 0), getLine(partFiles, 1), destFile, rMode, wMode, readElement, writeElement_x, compElement);
		break;

	case 1:
		removeFileIfExist(destFile);
		moveFile(getLine(partFiles, 0), destFile);
		break;

	case 0:
		createFile(destFile);
		break;

	default:
		error();
	}
	releaseDim(partFiles, 1);
}
Example #18
0
bool FileSystem::saveFile()
{
    QString file = getCurrentAbsoluteFileName();
    return moveFile(file,
                    Config::tempLocation + fileName(file));
}
Example #19
0
int main(int argc, char *argv[]){
    int i;
    direction hv = HORIZONTAL;

    /*
     * print help & exit
     */
    if(argc<=1){
        printf("%s version %s\n  divide JPG image files into a directory according to landscape/portrait types\n"
               "usage:  %s <option> file..\n"
               "option: -h, -l, --horizontal, --landscape (default)\n"
               "                move horizontally-long images to 'landscape' sub directory.\n"
               "        -v, -p, --vertical, --portrait\n"
               "                move vertically-long images to 'portrait' sub directory.\n"
               "supported: ", PROGNAME, PROGVERSION, PROGNAME);
        for(i=0; i<sizeof(g_suffix)/sizeof(g_suffix[0]); i++)
            fprintf(stderr, "%s ", g_suffix[i]);
        printf("\n");
        fflush(stdout);
        exit(1);
    }

    /*
     * argument handling
     */
    for(i=1; i<argc; i++){
        size_type size;
        int ftype;

        if((strcmp(argv[i],"-h")==0) ||
           (strcmp(argv[i],"-l")==0) ||
           (strcmp(argv[i],"--horizontal")==0) ||
           (strcmp(argv[i],"--landscape")==0)){
            hv = HORIZONTAL;
            continue;
        }else if((strcmp(argv[i],"-v")==0) ||
                 (strcmp(argv[i],"-p")==0) ||
                 (strcmp(argv[i],"--vertical")==0) ||
                 (strcmp(argv[i],"--portrait")==0)){
            hv = VERTICAL;
            continue;
        }

        /*
         * filename check
         */
        if(getSuffix(argv[i]) >= 0){
            size = jpgGetSize(argv[i]); //jpg
        }else{
            size.width = -1;
        }

        /*
         * output result
         */
        if(size.width <= -1){
            fprintf(stdout, "Warning: '%s' is not an image file ?\n", argv[i]);
        }else{
            if(hv == HORIZONTAL && size.width > size.height){
                moveFile(argv[i], "landscape");
#ifdef DEBUG
            fprintf(stderr, "%s w=%d, h=%d (landscape)\n", argv[i], size.width, size.height);
#endif /* DEBUG */
            }else if (hv == VERTICAL && size.width < size.height){
                moveFile(argv[i], "portrait");
#ifdef DEBUG
            fprintf(stderr, "%s w=%d, h=%d (portrait)\n", argv[i], size.width, size.height);
#endif /* DEBUG */
            }
        }
    }//for(i
    exit(0);
}
Example #20
0
bool psCheckReadyUpdate() {
    QString readyPath = cWorkingDir() + qsl("tupdates/ready");
	if (!QDir(readyPath).exists()) {
		return false;
	}

	// check ready version
	QString versionPath = readyPath + qsl("/tdata/version");
	{
		QFile fVersion(versionPath);
		if (!fVersion.open(QIODevice::ReadOnly)) {
			LOG(("Update Error: cant read version file '%1'").arg(versionPath));
			PsUpdateDownloader::clearAll();
			return false;
		}
		VerInt versionNum;
		if (fVersion.read((char*)&versionNum, sizeof(VerInt)) != sizeof(VerInt)) {
			LOG(("Update Error: cant read version from file '%1'").arg(versionPath));
			PsUpdateDownloader::clearAll();
			return false;
		}
		fVersion.close();
		if (versionNum <= AppVersion) {
			LOG(("Update Error: cant install version %1 having version %2").arg(versionNum).arg(AppVersion));
			PsUpdateDownloader::clearAll();
			return false;
		}
	}

#ifdef Q_OS_WIN
	QString curUpdater = (cExeDir() + "Updater.exe");
	QFileInfo updater(cWorkingDir() + "tupdates/ready/Updater.exe");
#elif defined Q_OS_MAC
	QString curUpdater = (cExeDir() + "Telegram.app/Contents/Frameworks/Updater");
	QFileInfo updater(cWorkingDir() + "tupdates/ready/Telegram.app/Contents/Frameworks/Updater");
#elif defined Q_OS_LINUX
    QString curUpdater = (cExeDir() + "Updater");
    QFileInfo updater(cWorkingDir() + "tupdates/ready/Updater");
#endif
	if (!updater.exists()) {
		QFileInfo current(curUpdater);
		if (!current.exists()) {
			PsUpdateDownloader::clearAll();
			return false;
		}
		if (!QFile(current.absoluteFilePath()).copy(updater.absoluteFilePath())) {
			PsUpdateDownloader::clearAll();
			return false;
		}
	}
#ifdef Q_OS_WIN
	if (CopyFile(updater.absoluteFilePath().toStdWString().c_str(), curUpdater.toStdWString().c_str(), FALSE) == FALSE) {
		PsUpdateDownloader::clearAll();
		return false;
	}
	if (DeleteFile(updater.absoluteFilePath().toStdWString().c_str()) == FALSE) {
		PsUpdateDownloader::clearAll();
		return false;
    }
#elif defined Q_OS_MAC
	QFileInfo to(curUpdater);
	QDir().mkpath(to.absolutePath());
	if (!objc_moveFile(updater.absoluteFilePath(), curUpdater)) {
		PsUpdateDownloader::clearAll();
		return false;
	}
#elif defined Q_OS_LINUX
    if (!moveFile(updater.absoluteFilePath().toUtf8().constData(), curUpdater.toUtf8().constData())) {
        PsUpdateDownloader::clearAll();
        return false;
    }
#endif
    return true;
}
Example #21
0
bool ScPrintEngine_PS::print(ScribusDoc& doc, PrintOptions& options)
{
	bool retw = false;
	ColorList usedColors;
	QMap<QString, QMap<uint, FPointArray> > usedFonts;
	QString filename(options.filename);
	doc.getUsedFonts(usedFonts);
	doc.getUsedColors(usedColors);
	PrefsManager *prefsManager = PrefsManager::instance();
	PSLib *dd = new PSLib(options, true, prefsManager->appPrefs.AvailFonts, usedFonts, usedColors, options.includePDFMarks, options.useSpotColors);
	if (dd != NULL)
	{
		if (!options.toFile)
			filename = prefsManager->preferencesLocation()+"/tmp.ps";
		bool PSfile = dd->PS_set_file(filename);
		filename = QDir::toNativeSeparators(filename);
		if (PSfile)
		{
			// Write the PS to a file
			int psCreationRetVal=dd->CreatePS(&doc, options);
			if (psCreationRetVal!=0)
			{
				QFile::remove(filename);
				if (psCreationRetVal==2)
					return true;
				else
				{
					m_errorMessage = dd->errorMessage();
					return false;
				}
			}
			if (options.prnEngine != PostScript3 && ScCore->haveGS())
			{
				// use gs to convert our PS to a lower version
				QString tmp;
				QStringList opts;
				opts.append( QString("-dDEVICEWIDTHPOINTS=%1").arg(tmp.setNum(doc.pageWidth)) );
				opts.append( QString("-dDEVICEHEIGHTPOINTS=%1").arg(tmp.setNum(doc.pageHeight)) );
				convertPS2PS(filename, filename + ".tmp", opts, options.prnEngine);
				moveFile( filename + ".tmp", filename );
			}
			if (!options.toFile)
			{
				// print and delete the PS file
				QByteArray cmd;
				if (options.useAltPrintCommand)
				{
					cmd += options.printerCommand;
					cmd += " ";
					cmd += filename;
					system(cmd.data());
				}
				else
				{
					QByteArray cc;
					cmd += "lpr -P '";
					cmd += options.printer;
					cmd += "'";
					if (options.copies > 1)
						cmd += " -#" + cc.setNum(options.copies);
					cmd += options.printerOptions;
					cmd += " "+filename;
					system(cmd.data());
				}
// Disabled that for now, as kprinter won't work otherwise
// leaving that file around doesn't harm, as it will be overwritten the next time.
//				unlink(filename);
			}
			retw = true;
		}
		else
			retw = false;
		delete dd;
	}
	return retw;
}
bool BaseMediaDocument::Process() {
	double startTime = 0;
	double endTime = 0;
	GETCLOCKS(startTime);

	//1. Compute the names
	_mediaFilePath = (string) _metadata[META_SERVER_FULL_PATH];
	_metaFilePath = _mediaFilePath + "."MEDIA_TYPE_META;
	_seekFilePath = _mediaFilePath + "."MEDIA_TYPE_SEEK;
	_keyframeSeek = (bool)_metadata[CONF_APPLICATION_KEYFRAMESEEK];
	_seekGranularity = (uint32_t) _metadata[CONF_APPLICATION_SEEKGRANULARITY];

	//1. Open the media file
#ifdef HAS_MMAP
	if (!_mediaFile.Initialize(_mediaFilePath, 4 * 1024 * 1024, true)) {
		FATAL("Unable to open media file: %s", STR(_mediaFilePath));
		return false;
	}
#else
	if (!_mediaFile.Initialize(_mediaFilePath)) {
		FATAL("Unable to open media file: %s", STR(_mediaFilePath));
		return false;
	}
#endif

	//4. Read the document
	if (!ParseDocument()) {
		FATAL("Unable to parse document");
		return false;
	}

	//5. Build the frames
	if (!BuildFrames()) {
		FATAL("Unable to build frames");
		return false;
	}

	//6. Save the seek file
	if (!SaveSeekFile()) {
		FATAL("Unable to save seeking file");
		return false;
	}

	//7. Build the meta
	if (!SaveMetaFile()) {
		FATAL("Unable to save meta file");
		return false;
	}

	GETCLOCKS(endTime);

	INFO("%"PRIz"u frames computed in %.2f seconds at a speed of %.2f FPS",
			_frames.size(),
			(endTime - startTime) / (double) CLOCKS_PER_SECOND,
			(double) _frames.size() / ((endTime - startTime) / (double) CLOCKS_PER_SECOND));
	if (_frames.size() != 0) {
		uint32_t totalSeconds = (uint32_t) (((uint32_t) _frames[_frames.size() - 1].absoluteTime) / 1000);
		uint32_t hours = totalSeconds / 3600;
		uint32_t minutes = (totalSeconds - hours * 3600) / 60;
		uint32_t seconds = (totalSeconds - hours * 3600 - minutes * 60);
		INFO("File size: %"PRIu64" bytes; Duration: %u:%u:%u (%u sec); Optimal bandwidth: %.2f kb/s",
				_mediaFile.Size(),
				hours, minutes, seconds,
				totalSeconds,
				(double) _streamCapabilities.bandwidthHint);
	}

	moveFile(_seekFilePath + ".tmp", _seekFilePath);
	moveFile(_metaFilePath + ".tmp", _metaFilePath);

	chmod(STR(_seekFilePath), S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
	chmod(STR(_metaFilePath), S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);

	return true;
}
Example #23
0
// Here we actually print
static PyObject *Printer_print(Printer *self)
{
	if (!checkHaveDocument()) {
		return NULL;
	}
// copied from void ScribusMainWindow::slotFilePrint() in file scribus.cpp
	QString fna, prn, cmd, cc, SepName;
	QString printcomm;
	bool fil, PSfile;
	PSfile = false;

//    ReOrderText(ScCore->primaryMainWindow()->doc, ScCore->primaryMainWindow()->view);
	prn = QString(PyString_AsString(self->printer));
	fna = QString(PyString_AsString(self->file));
	fil = (QString(PyString_AsString(self->printer)) == QString("File")) ? true : false;
	std::vector<int> pageNs;
	PrintOptions options;
	for (int i = 0; i < PyList_Size(self->pages); ++i) {
		options.pageNumbers.push_back((int)PyInt_AsLong(PyList_GetItem(self->pages, i)));
	}
	int Nr = (self->copies < 1) ? 1 : self->copies;
	SepName = QString(PyString_AsString(self->separation));
	options.printer   = prn;
	options.prnEngine = (PrintEngine) self->pslevel;
	options.toFile    = fil;
	options.separationName = SepName;
	options.outputSeparations = (SepName == QString("No")) ?  false : true;
	options.useColor = self->color;
	options.mirrorH  = self->mph;
	options.mirrorV  = self->mpv;
	options.doGCR    = self->ucr;
	options.cropMarks  = false;
	options.bleedMarks = false;
	options.registrationMarks = false;
	options.colorMarks = false;
	options.markOffset = 0.0;
	options.bleeds.set(0, 0, 0, 0);
	if (!PrinterUtil::checkPrintEngineSupport(options.printer, options.prnEngine, options.toFile))
		options.prnEngine = PrinterUtil::getDefaultPrintEngine(options.printer, options.toFile);
	printcomm = QString(PyString_AsString(self->cmd));
	QMap<QString, QMap<uint, FPointArray> > ReallyUsed;
	ReallyUsed.clear();
	ScCore->primaryMainWindow()->doc->getUsedFonts(ReallyUsed);
	PrefsManager *prefsManager=PrefsManager::instance();

#if defined(_WIN32)
	if (!options.toFile)
	{
		QByteArray devMode;
		bool printDone = false;
		if ( PrinterUtil::getDefaultSettings(prn, options.devMode) )
		{
			ScPrintEngine_GDI winPrint;
			printDone = winPrint.print( *ScCore->primaryMainWindow()->doc, options );
		}
		if (!printDone)
			PyErr_SetString(PyExc_SystemError, "Printing failed");
		Py_RETURN_NONE;
	}
#endif

	PSLib *dd = new PSLib(options, true, prefsManager->appPrefs.fontPrefs.AvailFonts, ReallyUsed, ScCore->primaryMainWindow()->doc->PageColors, false, true);
	if (dd != NULL)
	{
		if (!fil)
			fna = QDir::toNativeSeparators(ScPaths::tempFileDir()+"/tmp.ps");
		PSfile = dd->PS_set_file(fna);
		fna = QDir::toNativeSeparators(fna);
		if (PSfile)
		{
			options.setDevParam = false;
			options.doClip = false;
			dd->CreatePS(ScCore->primaryMainWindow()->doc, options);
			if (options.prnEngine == PostScript1 || options.prnEngine == PostScript2)
			{
				if (ScCore->haveGS())
				{
					QString tmp;
					QStringList opts;
					opts.append( QString("-dDEVICEWIDTHPOINTS=%1").arg(tmp.setNum(ScCore->primaryMainWindow()->doc->pageWidth())) );
					opts.append( QString("-dDEVICEHEIGHTPOINTS=%1").arg(tmp.setNum(ScCore->primaryMainWindow()->doc->pageHeight())) );
					convertPS2PS(fna, fna+".tmp", opts, options.prnEngine);
					moveFile( fna + ".tmp", fna );
				}
				else
				{
					PyErr_SetString(PyExc_SystemError, "Printing failed : GhostScript is needed to print to PostScript Level 1 or Level 2");
					Py_RETURN_NONE;
				}
			}

			if (!fil)
			{
				if (!printcomm.isEmpty())
					cmd = printcomm + " "+fna;
				else
				{
					cmd = "lpr -P" + prn;
					if (Nr > 1)
						cmd += " -#" + cc.setNum(Nr);
					cmd += " "+fna;
				}
				system(cmd.toLocal8Bit().constData());
				unlink(fna.toLocal8Bit().constData());
			}
		}
		else {
			delete dd;
			PyErr_SetString(PyExc_SystemError, "Printing failed");
			return NULL;
		}
		delete dd;
	}
//	Py_INCREF(Py_None);
//	return Py_None;
	Py_RETURN_NONE;
}
Example #24
0
void PrinterAPI::doPrint()
{
// copied from void ScribusMainWindow::slotFilePrint() in file scribus.cpp
	QString fna, prn, cmd, scmd, cc, data, SepName;
	QString printcomm;
	bool fil, PSfile;
	PSfile = false;

//    ReOrderText(ScCore->primaryMainWindow()->doc, ScCore->primaryMainWindow()->view);
	prn = printer;
	fna = file;
	fil = (printer == QString("File")) ? true : false;
	std::vector<int> pageNs;
	PrintOptions options;
	for (int i = 0; i < pages.size(); ++i) {
		options.pageNumbers.push_back(pages[i]);
	}
	int Nr = (copies < 1) ? 1 : copies;
	SepName = separation;
	options.printer   = prn;
	options.prnEngine = (PrintEngine) pslevel;
	options.toFile    = fil;
	options.separationName = SepName;
	options.outputSeparations = (SepName == QString("No")) ?  false : true;
	options.useColor = color;
	options.mirrorH  = mph;
	options.mirrorV  = mpv;
	options.useICC   = useICC;
	options.doGCR    = ucr;
	options.cropMarks  = false;
	options.bleedMarks = false;
	options.registrationMarks = false;
	options.colorMarks = false;
	options.markOffset = 0.0;
	options.bleeds.setTop(0.0);
	options.bleeds.setLeft(0.0);
	options.bleeds.setRight(0.0);
	options.bleeds.setBottom(0.0);
	if (!PrinterUtil::checkPrintEngineSupport(options.printer, options.prnEngine, options.toFile))
		options.prnEngine = PrinterUtil::getDefaultPrintEngine(options.printer, options.toFile);
	printcomm = cmd;
	QMap<QString, QMap<uint, FPointArray> > ReallyUsed;
	ReallyUsed.clear();
	ScCore->primaryMainWindow()->doc->getUsedFonts(ReallyUsed);
	PrefsManager *prefsManager=PrefsManager::instance();

#if defined(_WIN32)
	if (!options.toFile)
	{
		QByteArray devMode;
		bool printDone = false;
		if ( PrinterUtil::getDefaultSettings(prn, options.devMode) )
		{
			ScPrintEngine_GDI winPrint;
			printDone = winPrint.print( *ScCore->primaryMainWindow()->doc, options );
		}
		if (!printDone)
			RAISE("Printing failed");
	}
#endif

	PSLib *dd = new PSLib(options, true, prefsManager->appPrefs.fontPrefs.AvailFonts, ReallyUsed, ScCore->primaryMainWindow()->doc->PageColors, false, true);
	if (dd != NULL)
	{
		if (!fil)
			fna = QDir::toNativeSeparators(ScPaths::getTempFileDir()+"/tmp.ps");
		PSfile = dd->PS_set_file(fna);
		fna = QDir::toNativeSeparators(fna);
		if (PSfile)
		{
			options.setDevParam = false;
			options.doClip = false;
			dd->CreatePS(ScCore->primaryMainWindow()->doc, options);
			if (options.prnEngine == PostScript1 || options.prnEngine == PostScript2)
			{
				if (ScCore->haveGS())
				{
					QString tmp;
					QStringList opts;
					opts.append( QString("-dDEVICEWIDTHPOINTS=%1").arg(tmp.setNum(ScCore->primaryMainWindow()->doc->pageWidth())) );
					opts.append( QString("-dDEVICEHEIGHTPOINTS=%1").arg(tmp.setNum(ScCore->primaryMainWindow()->doc->pageHeight())) );
					convertPS2PS(fna, fna+".tmp", opts, options.prnEngine);
					moveFile( fna + ".tmp", fna );
				}
				else
				{
					RAISE("Printing failed : GhostScript is needed to print to PostScript Level 1 or Level 2");
				}
			}

			if (!fil)
			{
				if (!printcomm.isEmpty())
					cmd = printcomm + " "+fna;
				else
				{
					cmd = "lpr -P" + prn;
					if (Nr > 1)
						cmd += " -#" + cc.setNum(Nr);
#ifdef HAVE_CUPS
// This need yet to be implemented by object Printer
//					cmd += printer->PrinterOpts;
#endif
					cmd += " "+fna;
				}
				system(cmd.toLocal8Bit().constData());
				unlink(fna.toLocal8Bit().constData());
			}
		}
		else {
			delete dd;
			RAISE("Printing failed");
		}
		delete dd;
	}
}
Example #25
0
bool BaseMediaDocument::Process() {
	double startTime = 0;
	double endTime = 0;
	GETCLOCKS(startTime, double);

	//1. Compute the names
	_mediaFilePath = _metadata.mediaFullPath();
	_metaFilePath = _metadata.metaFileFullPath();
	_seekFilePath = _metadata.seekFileFullPath();
	_keyframeSeek = _metadata.storage().keyframeSeek();
	_seekGranularity = _metadata.storage().seekGranularity();

	//1. Open the media file
	if (!GetFile(_mediaFilePath, 4 * 1024 * 1024, _mediaFile)) {
		FATAL("Unable to open media file: %s", STR(_mediaFilePath));
		return false;
	}

	//4. Read the document
	if (!ParseDocument()) {
		FATAL("Unable to parse document");
		return false;
	}

	//5. Build the frames
	if (!BuildFrames()) {
		FATAL("Unable to build frames");
		return false;
	}

	//6. Save the seek file
	if (!SaveSeekFile()) {
		FATAL("Unable to save seeking file");
		return false;
	}

	//7. Build the meta
	if (!SaveMetaFile()) {
		FATAL("Unable to save meta file");
		return false;
	}

	GETCLOCKS(endTime, double);

	uint64_t framesCount = _audioSamplesCount + _videoSamplesCount;
	if (framesCount == 0)
		framesCount = (uint64_t) _frames.size();

	INFO("%"PRIu64" frames computed in %.2f seconds at a speed of %.2f FPS",
			framesCount,
			(endTime - startTime) / (double) CLOCKS_PER_SECOND,
			(double) framesCount / ((endTime - startTime) / (double) CLOCKS_PER_SECOND));
	if (_frames.size() != 0) {
		uint32_t totalSeconds = (uint32_t) (((uint32_t) _frames[_frames.size() - 1].dts) / 1000);
		uint32_t hours = totalSeconds / 3600;
		uint32_t minutes = (totalSeconds - hours * 3600) / 60;
		uint32_t seconds = (totalSeconds - hours * 3600 - minutes * 60);
		INFO("File size: %"PRIu64" bytes; Duration: %u:%u:%u (%u sec); Optimal bandwidth: %.2f kB/s",
				_mediaFile.Size(),
				hours, minutes, seconds,
				totalSeconds,
				(double) _streamCapabilities.GetTransferRate() / 8192);
	}

	moveFile(_seekFilePath + ".tmp", _seekFilePath);
	moveFile(_metaFilePath + ".tmp", _metaFilePath);

	chmod(STR(_seekFilePath), S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
	chmod(STR(_metaFilePath), S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);

	return true;
}