Beispiel #1
0
static NTSTATUS DOKAN_CALLBACK MirrorSetAllocationSize(
    LPCWSTR FileName, LONGLONG AllocSize, PDOKAN_FILE_INFO DokanFileInfo) {
  WCHAR filePath[MAX_PATH];
  HANDLE handle;
  LARGE_INTEGER fileSize;

  GetFilePath(filePath, MAX_PATH, FileName);

  DbgPrint(L"SetAllocationSize %s, %I64d\n", filePath, AllocSize);

  handle = (HANDLE)DokanFileInfo->Context;
  if (!handle || handle == INVALID_HANDLE_VALUE) {
    DbgPrint(L"\tinvalid handle\n\n");
    return STATUS_INVALID_HANDLE;
  }

  if (GetFileSizeEx(handle, &fileSize)) {
    if (AllocSize < fileSize.QuadPart) {
      fileSize.QuadPart = AllocSize;
      if (!SetFilePointerEx(handle, fileSize, NULL, FILE_BEGIN)) {
        DWORD error = GetLastError();
        DbgPrint(L"\tSetAllocationSize: SetFilePointer eror: %d, "
                 L"offset = %I64d\n\n",
                 error, AllocSize);
        return ToNtStatus(error);
      }
      if (!SetEndOfFile(handle)) {
        DWORD error = GetLastError();
        DbgPrint(L"\tSetEndOfFile error code = %d\n\n", error);
        return ToNtStatus(error);
      }
    }
  } else {
    DWORD error = GetLastError();
    DbgPrint(L"\terror code = %d\n\n", error);
    return ToNtStatus(error);
  }
  return STATUS_SUCCESS;
}
Beispiel #2
0
bool emAvFileModel::TryContinueLoading() throw(emString)
{
	switch (GetStreamState()) {
	case STREAM_CLOSED:
		OpenStream("none","none",GetFilePath());
		return false;
	case STREAM_OPENED:
		CloseStream();
		PlayPos=0;
		AudioVolume=100;
		AudioMute=false;
		LoadAudioVolume();
		LoadAudioVisu();
		LoadFileState();
		return true;
	case STREAM_ERRORED:
		throw emString(GetStreamErrorText());
	default:
		emSleepMS(10);
		return false;
	}
}
Beispiel #3
0
static NTSTATUS DOKAN_CALLBACK
MirrorFlushFileBuffers(LPCWSTR FileName, PDOKAN_FILE_INFO DokanFileInfo) {
  WCHAR filePath[MAX_PATH];
  HANDLE handle = (HANDLE)DokanFileInfo->Context;

  GetFilePath(filePath, MAX_PATH, FileName);

  DbgPrint(L"FlushFileBuffers : %s\n", filePath);

  if (!handle || handle == INVALID_HANDLE_VALUE) {
    DbgPrint(L"\tinvalid handle\n\n");
    return STATUS_SUCCESS;
  }

  if (FlushFileBuffers(handle)) {
    return STATUS_SUCCESS;
  } else {
    DWORD error = GetLastError();
    DbgPrint(L"\tflush error code = %d\n", error);
    return ToNtStatus(error);
  }
}
/*----------------------------------------------------------------------
|   PLT_FileMediaServer::OnBrowseMetadata
+---------------------------------------------------------------------*/
NPT_Result
PLT_FileMediaServer::OnBrowseMetadata(PLT_ActionReference& action, 
                                      const char*          object_id, 
                                      NPT_SocketInfo*      info /* = NULL */)
{
    NPT_String didl;

    /* locate the file from the object ID */
    NPT_String filepath;
    if (NPT_FAILED(GetFilePath(object_id, filepath))) {
        /* error */
        NPT_LOG_WARNING("PLT_FileMediaServer::OnBrowse - ObjectID not found.");
        action->SetError(701, "No Such Object.");
        return NPT_FAILURE;
    }

    NPT_Reference<PLT_MediaObject> item(BuildFromFilePath(filepath, true, info));
    if (item.IsNull()) return NPT_FAILURE;

    NPT_String filter;
    NPT_CHECK_SEVERE(action->GetArgumentValue("Filter", filter));

    NPT_String tmp;    
    NPT_CHECK_SEVERE(PLT_Didl::ToDidl(*item.AsPointer(), filter, tmp));

    /* add didl header and footer */
    didl = didl_header + tmp + didl_footer;

    NPT_CHECK_SEVERE(action->SetArgumentValue("Result", didl));
    NPT_CHECK_SEVERE(action->SetArgumentValue("NumberReturned", "1"));
    NPT_CHECK_SEVERE(action->SetArgumentValue("TotalMatches", "1"));

    // update ID may be wrong here, it should be the one of the container?
    NPT_CHECK_SEVERE(action->SetArgumentValue("UpdateId", "1"));
    // TODO: We need to keep track of the overall updateID of the CDS

    return NPT_SUCCESS;
}
Beispiel #5
0
static int DOKAN_CALLBACK
MirrorSetFileAttributes(
	LPCWSTR				FileName,
	DWORD				FileAttributes,
	PDOKAN_FILE_INFO	DokanFileInfo)
{
    UNREFERENCED_PARAMETER(DokanFileInfo);

	WCHAR	filePath[MAX_PATH];
	
	GetFilePath(filePath, MAX_PATH, FileName);

	DbgPrint(L"SetFileAttributes %s\n", filePath);

	if (!SetFileAttributes(filePath, FileAttributes)) {
		DWORD error = GetLastError();
		DbgPrint(L"\terror code = %d\n\n", error);
		return error * -1;
	}

	DbgPrint(L"\n");
	return 0;
}
Beispiel #6
0
QVariant ConfigAPI::Read(QString file, QString section, QString key, const QVariant &defaultValue) const
{
    if (configFolder_.isEmpty())
    {
        LogError("ConfigAPI::Read: Config folder has not been prepared, returning null QVariant.");
        return "";
    }

    PrepareString(file);
    PrepareString(section);
    PrepareString(key);

    // Don't return 'defaultValue' but null QVariant
    // as this is an error situation.
    if (!IsFilePathSecure(file))
        return QVariant();

    QSettings config(GetFilePath(file), QSettings::IniFormat);
    if (section.isEmpty())
        return config.value(key, defaultValue);
    else
        return config.value(section + "/" + key, defaultValue);
}
Beispiel #7
0
BOOL CBrowserView::RefreshView()
{
	CBonfireDoc* pDoc = (CBonfireDoc*)GetDocument();
	CString docPath = pDoc->GetPathName();
	if (!pDoc->IsModified())
	{
		// display the file in the browser viewer
		Navigate(docPath);
	}
	else
	{
		CString	strAbsPath	= theApp.m_pszHelpFilePath;
		DWORD	nSize		= 128;
		char*	lpValue		= (char*)malloc( nSize );
		int		retVal		= GetEnvironmentVariable("TEMP", lpValue, nSize);
		if (retVal <= (int)nSize)
			strAbsPath = lpValue;
		else if (retVal == 0)
		{
			// try TMP
			retVal			= GetEnvironmentVariable("TMP", lpValue, nSize);
			if (retVal <= (int)nSize)
				strAbsPath = lpValue;
		}
		// generate a temp file
		CString navPath = GetFilePath( AddSlash(strAbsPath) ) + "btmp_" + GetFileTitle( docPath );
		pDoc->m_xTextBuffer.SaveToFile(navPath, CRLF_STYLE_AUTOMATIC, FALSE);

		// mark the file as temporary for later deletion
		theApp.AddTempFile( navPath );

		// display the file in the browser viewer
		Navigate(navPath);
	}

	return TRUE;
}
Beispiel #8
0
static int
MirrorUnlockFile(
	LPCWSTR				FileName,
	LONGLONG			ByteOffset,
	LONGLONG			Length,
	PDOKAN_FILE_INFO	DokanFileInfo)
{
	WCHAR	filePath[MAX_PATH+1];
	HANDLE	handle;
	LARGE_INTEGER	length;
	LARGE_INTEGER	offset;

	GetFilePath(filePath, FileName);

	DbgPrint(L"UnlockFile %s\n", filePath);

    /*
	handle = (HANDLE)DokanFileInfo->Context;
	if (!handle || handle == INVALID_HANDLE_VALUE) {
		DbgPrint(L"\tinvalid handle\n\n");
		return -1;
	}

	length.QuadPart = Length;
	offset.QuadPart = ByteOffset;

	if (UnlockFile(handle, offset.HighPart, offset.LowPart, length.HighPart, length.LowPart)) {
		DbgPrint(L"\tsuccess\n\n");
		return 0;
	} else {
		DbgPrint(L"\tfail\n\n");
		return -1;
	}
    */
    return 0;
}
nsresult nsNntpUrl::ParseNewsURL()
{
  // The path here is the group/msgid portion
  nsAutoCString path;
  nsresult rv = GetFilePath(path);
  NS_ENSURE_SUCCESS(rv, rv);

  // Drop the potential beginning from the path
  if (path.Length() && path[0] == '/')
    path = Substring(path, 1);

  // The presence of an `@' is a sign we have a msgid
  if (path.Find("@") != -1 || path.Find("%40") != -1)
  {
    MsgUnescapeString(path, 0, m_messageID);

    // Set group, key for ?group=foo&key=123 uris
    nsAutoCString spec;
    GetSpec(spec);
    int32_t groupPos = spec.Find(kNewsURIGroupQuery); // find ?group=
    int32_t keyPos   = spec.Find(kNewsURIKeyQuery);   // find &key=
    if (groupPos != kNotFound && keyPos != kNotFound)
    {
      // get group name and message key
      m_group = Substring(spec, groupPos + kNewsURIGroupQueryLen,
                          keyPos - groupPos - kNewsURIGroupQueryLen);
      nsCString keyStr(Substring(spec, keyPos + kNewsURIKeyQueryLen));
      m_key = keyStr.ToInteger(&rv, 10);
      NS_ENSURE_SUCCESS(rv, NS_ERROR_MALFORMED_URI);
    }
  }
  else
    MsgUnescapeString(path, 0, m_group);

  return NS_OK;
}
Beispiel #10
0
static NTSTATUS DOKAN_CALLBACK
MirrorSetEndOfFile(
	LPCWSTR				FileName,
	LONGLONG			ByteOffset,
	PDOKAN_FILE_INFO	DokanFileInfo)
{
	WCHAR			filePath[MAX_PATH];
	HANDLE			handle;
	LARGE_INTEGER	offset;

	GetFilePath(filePath, MAX_PATH, FileName);

	DbgPrint(L"SetEndOfFile %s, %I64d\n", filePath, ByteOffset);

	handle = (HANDLE)DokanFileInfo->Context;
	if (!handle || handle == INVALID_HANDLE_VALUE) {
		DbgPrint(L"\tinvalid handle\n\n");
		return STATUS_INVALID_HANDLE;
	}

	offset.QuadPart = ByteOffset;
	if (!SetFilePointerEx(handle, offset, NULL, FILE_BEGIN)) {
		DWORD error = GetLastError();
		DbgPrint(L"\tSetFilePointer error: %d, offset = %I64d\n\n",
			error, ByteOffset);
		return ToNtStatus(error);
	}

	if (!SetEndOfFile(handle)) {
		DWORD error = GetLastError();
		DbgPrint(L"\tSetEndOfFile error code = %d\n\n", error);
		return ToNtStatus(error);
	}

	return STATUS_SUCCESS;
}
Beispiel #11
0
static void DOKAN_CALLBACK
MirrorCleanup(
	LPCWSTR					FileName,
	PDOKAN_FILE_INFO		DokanFileInfo)
{
	WCHAR filePath[MAX_PATH];
	GetFilePath(filePath, MAX_PATH, FileName);

	if (DokanFileInfo->Context) {
		DbgPrint(L"Cleanup: %s\n\n", filePath);
		CloseHandle((HANDLE)DokanFileInfo->Context);
		DokanFileInfo->Context = 0;

		if (DokanFileInfo->DeleteOnClose) {
			DbgPrint(L"\tDeleteOnClose\n");
			if (DokanFileInfo->IsDirectory) {
				DbgPrint(L"  DeleteDirectory ");
				if (!RemoveDirectory(filePath)) {
					DbgPrint(L"error code = %d\n\n", GetLastError());
				} else {
					DbgPrint(L"success\n\n");
				}
			} else {
				DbgPrint(L"  DeleteFile ");
				if (DeleteFile(filePath) == 0) {
					DbgPrint(L" error code = %d\n\n", GetLastError());
				} else {
					DbgPrint(L"success\n\n");
				}
			}
		}

	} else {
		DbgPrint(L"Cleanup: %s\n\tinvalid handle\n\n", filePath);
	}
}
Beispiel #12
0
void ConfigAPI::Write(QString file, QString section, QString key, const QVariant &value)
{
    if (configFolder_.isEmpty())
    {
        LogError("ConfigAPI::Write: Config folder has not been prepared, can not write value to config.");
        return;
    }

    PrepareString(file);
    PrepareString(section);
    PrepareString(key);

    if (!IsFilePathSecure(file))
        return;

    QSettings config(GetFilePath(file), QSettings::IniFormat);
    if (!config.isWritable())
        return;
    if (section.isEmpty())
        config.setValue(key, value);
    else
        config.setValue(section + "/" + key, value);
    config.sync();
}
Beispiel #13
0
static int DOKAN_CALLBACK
MirrorEnumerateNamedStreams(
	LPCWSTR					FileName,
	PVOID*					EnumContext,
	LPWSTR					StreamName,
	PULONG					StreamNameLength,
	PLONGLONG				StreamSize,
	PDOKAN_FILE_INFO		DokanFileInfo)
{
	HANDLE	handle;
	WCHAR	filePath[MAX_PATH];

	GetFilePath(filePath, MAX_PATH, FileName);

	DbgPrint(L"EnumerateNamedStreams %s\n", filePath);

	handle = (HANDLE)DokanFileInfo->Context;
	if (!handle || handle == INVALID_HANDLE_VALUE) {
		DbgPrint(L"\tinvalid handle\n\n");
		return -1;
	}

	// As we are requested one by one, it would be better to use FindFirstStream / FindNextStream instead of requesting all streams each time
	// But this doesn't really matter on mirror sample
	BYTE InfoBlock[64 * 1024];
	PFILE_STREAM_INFORMATION pStreamInfo = (PFILE_STREAM_INFORMATION)InfoBlock;
	IO_STATUS_BLOCK ioStatus;
	ZeroMemory(InfoBlock, sizeof(InfoBlock));

	NTSTATUS status = NtQueryInformationFile(handle, &ioStatus, InfoBlock, sizeof(InfoBlock), FileStreamInformation);
	if (status != STATUS_SUCCESS) {
		DbgPrint(L"\tNtQueryInformationFile failed with %d.\n", status);
		return -1;
	}

	if (pStreamInfo->StreamNameLength == 0) {
		DbgPrint(L"\tNo stream found.\n");
		return -1;
	}

	UINT index = (UINT)*EnumContext;
	DbgPrint(L"\tStream #%d requested.\n", index);
	
	for (UINT i = 0; i != index; ++i) {
		if (pStreamInfo->NextEntryOffset == 0) {
			DbgPrint(L"\tNo more stream.\n");
			return -1;
		}
		pStreamInfo = (PFILE_STREAM_INFORMATION) ((LPBYTE)pStreamInfo + pStreamInfo->NextEntryOffset);   // Next stream record
	}

	wcscpy_s(StreamName, SHRT_MAX + 1, pStreamInfo->StreamName);
	*StreamNameLength = pStreamInfo->StreamNameLength;
	*StreamSize = pStreamInfo->StreamSize.QuadPart;

	DbgPrint(L"\t Stream %ws\n", pStreamInfo->StreamName);

	// Remember next stream entry index
	*EnumContext = (PVOID)++index;

	return 0;
}
Beispiel #14
0
static int DOKAN_CALLBACK
MirrorCreateFile(
	LPCWSTR					FileName,
	DWORD					AccessMode,
	DWORD					ShareMode,
	DWORD					CreationDisposition,
	DWORD					FlagsAndAttributes,
	PDOKAN_FILE_INFO		DokanFileInfo)
{
	WCHAR filePath[MAX_PATH];
	HANDLE handle;
	DWORD fileAttr;

	GetFilePath(filePath, MAX_PATH, FileName);

	DbgPrint(L"CreateFile : %s\n", filePath);

	PrintUserName(DokanFileInfo);

	if (CreationDisposition == CREATE_NEW)
		DbgPrint(L"\tCREATE_NEW\n");
	if (CreationDisposition == OPEN_ALWAYS)
		DbgPrint(L"\tOPEN_ALWAYS\n");
	if (CreationDisposition == CREATE_ALWAYS)
		DbgPrint(L"\tCREATE_ALWAYS\n");
	if (CreationDisposition == OPEN_EXISTING)
		DbgPrint(L"\tOPEN_EXISTING\n");
	if (CreationDisposition == TRUNCATE_EXISTING)
		DbgPrint(L"\tTRUNCATE_EXISTING\n");

	/*
	if (ShareMode == 0 && AccessMode & FILE_WRITE_DATA)
		ShareMode = FILE_SHARE_WRITE;
	else if (ShareMode == 0)
		ShareMode = FILE_SHARE_READ;
	*/

	DbgPrint(L"\tShareMode = 0x%x\n", ShareMode);

	MirrorCheckFlag(ShareMode, FILE_SHARE_READ);
	MirrorCheckFlag(ShareMode, FILE_SHARE_WRITE);
	MirrorCheckFlag(ShareMode, FILE_SHARE_DELETE);

	DbgPrint(L"\tAccessMode = 0x%x\n", AccessMode);

	MirrorCheckFlag(AccessMode, GENERIC_READ);
	MirrorCheckFlag(AccessMode, GENERIC_WRITE);
	MirrorCheckFlag(AccessMode, GENERIC_EXECUTE);
	
	MirrorCheckFlag(AccessMode, DELETE);
	MirrorCheckFlag(AccessMode, FILE_READ_DATA);
	MirrorCheckFlag(AccessMode, FILE_READ_ATTRIBUTES);
	MirrorCheckFlag(AccessMode, FILE_READ_EA);
	MirrorCheckFlag(AccessMode, READ_CONTROL);
	MirrorCheckFlag(AccessMode, FILE_WRITE_DATA);
	MirrorCheckFlag(AccessMode, FILE_WRITE_ATTRIBUTES);
	MirrorCheckFlag(AccessMode, FILE_WRITE_EA);
	MirrorCheckFlag(AccessMode, FILE_APPEND_DATA);
	MirrorCheckFlag(AccessMode, WRITE_DAC);
	MirrorCheckFlag(AccessMode, WRITE_OWNER);
	MirrorCheckFlag(AccessMode, SYNCHRONIZE);
	MirrorCheckFlag(AccessMode, FILE_EXECUTE);
	MirrorCheckFlag(AccessMode, STANDARD_RIGHTS_READ);
	MirrorCheckFlag(AccessMode, STANDARD_RIGHTS_WRITE);
	MirrorCheckFlag(AccessMode, STANDARD_RIGHTS_EXECUTE);
	
	// When filePath is a directory, needs to change the flag so that the file can be opened.
	fileAttr = GetFileAttributes(filePath);
	if (fileAttr != INVALID_FILE_ATTRIBUTES && fileAttr & FILE_ATTRIBUTE_DIRECTORY) {
		FlagsAndAttributes |= FILE_FLAG_BACKUP_SEMANTICS;
		//AccessMode = 0;
	}
	DbgPrint(L"\tFlagsAndAttributes = 0x%x\n", FlagsAndAttributes);

	MirrorCheckFlag(FlagsAndAttributes, FILE_ATTRIBUTE_ARCHIVE);
	MirrorCheckFlag(FlagsAndAttributes, FILE_ATTRIBUTE_ENCRYPTED);
	MirrorCheckFlag(FlagsAndAttributes, FILE_ATTRIBUTE_HIDDEN);
	MirrorCheckFlag(FlagsAndAttributes, FILE_ATTRIBUTE_NORMAL);
	MirrorCheckFlag(FlagsAndAttributes, FILE_ATTRIBUTE_NOT_CONTENT_INDEXED);
	MirrorCheckFlag(FlagsAndAttributes, FILE_ATTRIBUTE_OFFLINE);
	MirrorCheckFlag(FlagsAndAttributes, FILE_ATTRIBUTE_READONLY);
	MirrorCheckFlag(FlagsAndAttributes, FILE_ATTRIBUTE_SYSTEM);
	MirrorCheckFlag(FlagsAndAttributes, FILE_ATTRIBUTE_TEMPORARY);
	MirrorCheckFlag(FlagsAndAttributes, FILE_FLAG_WRITE_THROUGH);
	MirrorCheckFlag(FlagsAndAttributes, FILE_FLAG_OVERLAPPED);
	MirrorCheckFlag(FlagsAndAttributes, FILE_FLAG_NO_BUFFERING);
	MirrorCheckFlag(FlagsAndAttributes, FILE_FLAG_RANDOM_ACCESS);
	MirrorCheckFlag(FlagsAndAttributes, FILE_FLAG_SEQUENTIAL_SCAN);
	MirrorCheckFlag(FlagsAndAttributes, FILE_FLAG_DELETE_ON_CLOSE);
	MirrorCheckFlag(FlagsAndAttributes, FILE_FLAG_BACKUP_SEMANTICS);
	MirrorCheckFlag(FlagsAndAttributes, FILE_FLAG_POSIX_SEMANTICS);
	MirrorCheckFlag(FlagsAndAttributes, FILE_FLAG_OPEN_REPARSE_POINT);
	MirrorCheckFlag(FlagsAndAttributes, FILE_FLAG_OPEN_NO_RECALL);
	MirrorCheckFlag(FlagsAndAttributes, SECURITY_ANONYMOUS);
	MirrorCheckFlag(FlagsAndAttributes, SECURITY_IDENTIFICATION);
	MirrorCheckFlag(FlagsAndAttributes, SECURITY_IMPERSONATION);
	MirrorCheckFlag(FlagsAndAttributes, SECURITY_DELEGATION);
	MirrorCheckFlag(FlagsAndAttributes, SECURITY_CONTEXT_TRACKING);
	MirrorCheckFlag(FlagsAndAttributes, SECURITY_EFFECTIVE_ONLY);
	MirrorCheckFlag(FlagsAndAttributes, SECURITY_SQOS_PRESENT);

	handle = CreateFile(
		filePath,
		AccessMode,//GENERIC_READ|GENERIC_WRITE|GENERIC_EXECUTE,
		ShareMode,
		NULL, // security attribute
		CreationDisposition,
		FlagsAndAttributes,// |FILE_FLAG_NO_BUFFERING,
		NULL); // template file handle

	if (handle == INVALID_HANDLE_VALUE) {
		DWORD error = GetLastError();
		DbgPrint(L"\terror code = %d\n\n", error);
		return error * -1; // error codes are negated value of Windows System Error codes
	}

	DbgPrint(L"\n");

	// save the file handle in Context
	DokanFileInfo->Context = (ULONG64)handle;
	return 0;
}
Beispiel #15
0
Int64 GetFreeDisk(const char *FileName)
{
#ifdef _WIN_32
  char Root[NM];
  GetPathRoot(FileName,Root);

  typedef BOOL (WINAPI *GETDISKFREESPACEEX)(
    LPCTSTR,PULARGE_INTEGER,PULARGE_INTEGER,PULARGE_INTEGER
   );
  static GETDISKFREESPACEEX pGetDiskFreeSpaceEx=NULL;

  if (pGetDiskFreeSpaceEx==NULL)
  {
    HMODULE hKernel=GetModuleHandle("kernel32.dll");
    if (hKernel!=NULL)
      pGetDiskFreeSpaceEx=(GETDISKFREESPACEEX)GetProcAddress(hKernel,"GetDiskFreeSpaceExA");
  }
  if (pGetDiskFreeSpaceEx!=NULL)
  {
    GetFilePath(FileName,Root);
    ULARGE_INTEGER uiTotalSize,uiTotalFree,uiUserFree;
    uiUserFree.u.LowPart=uiUserFree.u.HighPart=0;
    if (pGetDiskFreeSpaceEx(*Root ? Root:NULL,&uiUserFree,&uiTotalSize,&uiTotalFree) &&
        uiUserFree.u.HighPart<=uiTotalFree.u.HighPart)
      return(int32to64(uiUserFree.u.HighPart,uiUserFree.u.LowPart));
  }

  DWORD SectorsPerCluster,BytesPerSector,FreeClusters,TotalClusters;
  if (!GetDiskFreeSpace(*Root ? Root:NULL,&SectorsPerCluster,&BytesPerSector,&FreeClusters,&TotalClusters))
    return(1457664);
  Int64 FreeSize=SectorsPerCluster*BytesPerSector;
  FreeSize=FreeSize*FreeClusters;
  return(FreeSize);
#elif defined(_BEOS)
  char Root[NM];
  GetFilePath(FileName,Root);
  dev_t Dev=dev_for_path(*Root ? Root:".");
  if (Dev<0)
    return(1457664);
  fs_info Info;
  if (fs_stat_dev(Dev,&Info)!=0)
    return(1457664);
  Int64 FreeSize=Info.block_size;
  FreeSize=FreeSize*Info.free_blocks;
  return(FreeSize);
#elif defined(_UNIX)
  return(1457664);
#elif defined(_EMX)
  int Drive=(!isalpha(FileName[0]) || FileName[1]!=':') ? 0:toupper(FileName[0])-'A'+1;
  if (_osmode == OS2_MODE)
  {
    FSALLOCATE fsa;
    if (DosQueryFSInfo(Drive,1,&fsa,sizeof(fsa))!=0)
      return(1457664);
    Int64 FreeSize=fsa.cSectorUnit*fsa.cbSector;
    FreeSize=FreeSize*fsa.cUnitAvail;
    return(FreeSize);
  }
  else
  {
    union REGS regs,outregs;
    memset(&regs,0,sizeof(regs));
    regs.h.ah=0x36;
    regs.h.dl=Drive;
    _int86 (0x21,&regs,&outregs);
    if (outregs.x.ax==0xffff)
      return(1457664);
    Int64 FreeSize=outregs.x.ax*outregs.x.cx;
    FreeSize=FreeSize*outregs.x.bx;
    return(FreeSize);
  }
#else
  #define DISABLEAUTODETECT
  return(1457664);
#endif
}
int svlFilterVideoFileWriter::GetFilePath(std::string &filepath, unsigned int videoch) const
{
    filepath = GetFilePath(videoch);
    if (filepath.empty()) return SVL_FAIL;
    return SVL_OK;
}
Beispiel #17
0
static int DOKAN_CALLBACK
MirrorGetFileInformation(
	LPCWSTR							FileName,
	LPBY_HANDLE_FILE_INFORMATION	HandleFileInformation,
	PDOKAN_FILE_INFO				DokanFileInfo)
{
	WCHAR	filePath[MAX_PATH];
	HANDLE	handle = (HANDLE)DokanFileInfo->Context;
	BOOL	opened = FALSE;

	GetFilePath(filePath, MAX_PATH, FileName);

	DbgPrint(L"GetFileInfo : %s\n", filePath);

	if (!handle || handle == INVALID_HANDLE_VALUE) {
		DbgPrint(L"\tinvalid handle\n\n");

		// If CreateDirectory returned FILE_ALREADY_EXISTS and 
		// it is called with FILE_OPEN_IF, that handle must be opened.
		handle = CreateFile(filePath, 0, FILE_SHARE_READ, NULL, OPEN_EXISTING,
			FILE_FLAG_BACKUP_SEMANTICS, NULL);
		if (handle == INVALID_HANDLE_VALUE)
			return -1;
		opened = TRUE;
	}

	if (!GetFileInformationByHandle(handle,HandleFileInformation)) {
		DbgPrint(L"\terror code = %d\n", GetLastError());

		// FileName is a root directory
		// in this case, FindFirstFile can't get directory information
		if (wcslen(FileName) == 1) {
			DbgPrint(L"  root dir\n");
			HandleFileInformation->dwFileAttributes = GetFileAttributes(filePath);

		} else {
			WIN32_FIND_DATAW find;
			ZeroMemory(&find, sizeof(WIN32_FIND_DATAW));
			handle = FindFirstFile(filePath, &find);
			if (handle == INVALID_HANDLE_VALUE) {
				DbgPrint(L"\tFindFirstFile error code = %d\n\n", GetLastError());
				return -1;
			}
			HandleFileInformation->dwFileAttributes = find.dwFileAttributes;
			HandleFileInformation->ftCreationTime = find.ftCreationTime;
			HandleFileInformation->ftLastAccessTime = find.ftLastAccessTime;
			HandleFileInformation->ftLastWriteTime = find.ftLastWriteTime;
			HandleFileInformation->nFileSizeHigh = find.nFileSizeHigh;
			HandleFileInformation->nFileSizeLow = find.nFileSizeLow;
			DbgPrint(L"\tFindFiles OK, file size = %d\n", find.nFileSizeLow);
			FindClose(handle);
		}
	} else {
		DbgPrint(L"\tGetFileInformationByHandle success, file size = %d\n",
			HandleFileInformation->nFileSizeLow);
	}

	DbgPrint(L"\n");

	if (opened) {
		CloseHandle(handle);
	}

	return 0;
}
Beispiel #18
0
GDALDataset *TSXDataset::Open( GDALOpenInfo *poOpenInfo ) {
/* -------------------------------------------------------------------- */
/*      Is this a TerraSAR-X product file?                              */
/* -------------------------------------------------------------------- */
    if (!TSXDataset::Identify( poOpenInfo ))
    {
        return NULL; /* nope */
    }

/* -------------------------------------------------------------------- */
/*      Confirm the requested access is supported.                      */
/* -------------------------------------------------------------------- */
    if( poOpenInfo->eAccess == GA_Update )
    {
        CPLError( CE_Failure, CPLE_NotSupported,
                  "The TSX driver does not support update access to existing"
                  " datasets.\n" );
        return NULL;
    }

    CPLString osFilename;

    if( poOpenInfo->bIsDirectory )
    {
        osFilename =
            CPLFormCIFilename( poOpenInfo->pszFilename,
                               CPLGetFilename( poOpenInfo->pszFilename ),
                               "xml" );
    }
    else
        osFilename = poOpenInfo->pszFilename;

    /* Ingest the XML */
    CPLXMLNode *psData = CPLParseXMLFile( osFilename );
    if (psData == NULL)
        return NULL;

    /* find the product components */
    CPLXMLNode *psComponents
        = CPLGetXMLNode( psData, "=level1Product.productComponents" );
    if (psComponents == NULL) {
        CPLError( CE_Failure, CPLE_OpenFailed,
            "Unable to find <productComponents> tag in file.\n" );
        CPLDestroyXMLNode(psData);
        return NULL;
    }

    /* find the product info tag */
    CPLXMLNode *psProductInfo
        = CPLGetXMLNode( psData, "=level1Product.productInfo" );
    if (psProductInfo == NULL) {
        CPLError( CE_Failure, CPLE_OpenFailed,
            "Unable to find <productInfo> tag in file.\n" );
        CPLDestroyXMLNode(psData);
        return NULL;
    }

/* -------------------------------------------------------------------- */
/*      Create the dataset.                                             */
/* -------------------------------------------------------------------- */

    TSXDataset *poDS = new TSXDataset();

/* -------------------------------------------------------------------- */
/*      Read in product info.                                           */
/* -------------------------------------------------------------------- */

    poDS->SetMetadataItem( "SCENE_CENTRE_TIME", CPLGetXMLValue( psProductInfo,
        "sceneInfo.sceneCenterCoord.azimuthTimeUTC", "unknown" ) );
    poDS->SetMetadataItem( "OPERATIONAL_MODE", CPLGetXMLValue( psProductInfo,
        "generationInfo.groundOperationsType", "unknown" ) );
    poDS->SetMetadataItem( "ORBIT_CYCLE", CPLGetXMLValue( psProductInfo,
        "missionInfo.orbitCycle", "unknown" ) );
    poDS->SetMetadataItem( "ABSOLUTE_ORBIT", CPLGetXMLValue( psProductInfo,
        "missionInfo.absOrbit", "unknown" ) );
    poDS->SetMetadataItem( "ORBIT_DIRECTION", CPLGetXMLValue( psProductInfo,
        "missionInfo.orbitDirection", "unknown" ) );
    poDS->SetMetadataItem( "IMAGING_MODE", CPLGetXMLValue( psProductInfo,
        "acquisitionInfo.imagingMode", "unknown" ) );
    poDS->SetMetadataItem( "PRODUCT_VARIANT", CPLGetXMLValue( psProductInfo,
        "productVariantInfo.productVariant", "unknown" ) );
    char *pszDataType = CPLStrdup( CPLGetXMLValue( psProductInfo,
        "imageDataInfo.imageDataType", "unknown" ) );
    poDS->SetMetadataItem( "IMAGE_TYPE", pszDataType );

    /* Get raster information */
    int nRows = atoi( CPLGetXMLValue( psProductInfo,
        "imageDataInfo.imageRaster.numberOfRows", "" ) );
    int nCols = atoi( CPLGetXMLValue( psProductInfo,
        "imageDataInfo.imageRaster.numberOfColumns", "" ) );

    poDS->nRasterXSize = nCols;
    poDS->nRasterYSize = nRows;

    poDS->SetMetadataItem( "ROW_SPACING", CPLGetXMLValue( psProductInfo,
        "imageDataInfo.imageRaster.rowSpacing", "unknown" ) );
    poDS->SetMetadataItem( "COL_SPACING", CPLGetXMLValue( psProductInfo,
        "imageDataInfo.imageRaster.columnSpacing", "unknown" ) );
    poDS->SetMetadataItem( "COL_SPACING_UNITS", CPLGetXMLValue( psProductInfo,
        "imageDataInfo.imageRaster.columnSpacing.units", "unknown" ) );

    /* Get equivalent number of looks */
    poDS->SetMetadataItem( "AZIMUTH_LOOKS", CPLGetXMLValue( psProductInfo,
        "imageDataInfo.imageRaster.azimuthLooks", "unknown" ) );
    poDS->SetMetadataItem( "RANGE_LOOKS", CPLGetXMLValue( psProductInfo,
        "imageDataInfo.imageRaster.rangeLooks", "unknown" ) );

    const char *pszProductVariant = CPLGetXMLValue( psProductInfo,
        "productVariantInfo.productVariant", "unknown" );

    poDS->SetMetadataItem( "PRODUCT_VARIANT", pszProductVariant );

    /* Determine what product variant this is */
    if (STARTS_WITH_CI(pszProductVariant, "SSC"))
        poDS->nProduct = eSSC;
    else if (STARTS_WITH_CI(pszProductVariant, "MGD"))
        poDS->nProduct = eMGD;
    else if (STARTS_WITH_CI(pszProductVariant, "EEC"))
        poDS->nProduct = eEEC;
    else if (STARTS_WITH_CI(pszProductVariant, "GEC"))
        poDS->nProduct = eGEC;
    else
        poDS->nProduct = eUnknown;

    /* Start reading in the product components */
    char *pszGeorefFile = NULL;
    CPLErr geoTransformErr=CE_Failure;
    for ( CPLXMLNode *psComponent = psComponents->psChild;
          psComponent != NULL;
          psComponent = psComponent->psNext)
    {
        const char *pszType = NULL;
        const char *pszPath = CPLFormFilename(
                CPLGetDirname( osFilename ),
                GetFilePath(psComponent, &pszType),
                "" );
        const char *pszPolLayer = CPLGetXMLValue(psComponent, "polLayer", " ");

        if ( !STARTS_WITH_CI(pszType, " ") ) {
            if (STARTS_WITH_CI(pszType, "MAPPING_GRID") ) {
                /* the mapping grid... save as a metadata item this path */
                poDS->SetMetadataItem( "MAPPING_GRID", pszPath );
            }
            else if (STARTS_WITH_CI(pszType, "GEOREF")) {
                /* save the path to the georef data for later use */
                CPLFree( pszGeorefFile );
                pszGeorefFile = CPLStrdup( pszPath );
            }
        }
        else if( !STARTS_WITH_CI(pszPolLayer, " ") &&
            STARTS_WITH_CI(psComponent->pszValue, "imageData") ) {
            /* determine the polarization of this band */
            ePolarization ePol;
            if ( STARTS_WITH_CI(pszPolLayer, "HH") ) {
                ePol = HH;
            }
            else if ( STARTS_WITH_CI(pszPolLayer, "HV") ) {
                ePol = HV;
            }
            else if ( STARTS_WITH_CI(pszPolLayer, "VH") ) {
                ePol = VH;
            }
            else {
                ePol = VV;
            }

            GDALDataType eDataType = STARTS_WITH_CI(pszDataType, "COMPLEX") ?
                GDT_CInt16 : GDT_UInt16;

            /* try opening the file that represents that band */
            GDALDataset *poBandData = reinterpret_cast<GDALDataset *>(
                GDALOpen( pszPath, GA_ReadOnly ) );
            if ( poBandData != NULL ) {
                TSXRasterBand *poBand
                    = new TSXRasterBand( poDS, eDataType, ePol, poBandData );
                poDS->SetBand( poDS->GetRasterCount() + 1, poBand );

                //copy georeferencing info from the band
                //need error checking??
                //it will just save the info from the last band
                CPLFree( poDS->pszProjection );
                poDS->pszProjection = CPLStrdup(poBandData->GetProjectionRef());
                geoTransformErr = poBandData->GetGeoTransform(poDS->adfGeoTransform);
            }
        }
    }

    //now check if there is a geotransform
    if ( strcmp(poDS->pszProjection, "") && geoTransformErr==CE_None)
    {
        poDS->bHaveGeoTransform = TRUE;
    }
    else
    {
        poDS->bHaveGeoTransform = FALSE;
        CPLFree( poDS->pszProjection );
        poDS->pszProjection = CPLStrdup("");
        poDS->adfGeoTransform[0] = 0.0;
        poDS->adfGeoTransform[1] = 1.0;
        poDS->adfGeoTransform[2] = 0.0;
        poDS->adfGeoTransform[3] = 0.0;
        poDS->adfGeoTransform[4] = 0.0;
        poDS->adfGeoTransform[5] = 1.0;
    }

    CPLFree(pszDataType);

/* -------------------------------------------------------------------- */
/*      Check and set matrix representation.                            */
/* -------------------------------------------------------------------- */

    if (poDS->GetRasterCount() == 4) {
        poDS->SetMetadataItem( "MATRIX_REPRESENTATION", "SCATTERING" );
    }

/* -------------------------------------------------------------------- */
/*      Read the four corners and centre GCPs in                        */
/* -------------------------------------------------------------------- */

    CPLXMLNode *psSceneInfo = CPLGetXMLNode( psData,
        "=level1Product.productInfo.sceneInfo" );
    if (psSceneInfo != NULL)
    {
        /* extract the GCPs from the provided file */
        bool success = false;
        if (pszGeorefFile != NULL)
            success = poDS->getGCPsFromGEOREF_XML(pszGeorefFile);

        //if the gcp's cannot be extracted from the georef file, try to get the corner coordinates
        //for now just SSC because the others don't have refColumn and refRow
        if (!success && poDS->nProduct == eSSC)
        {
            int nGCP = 0;
            double dfAvgHeight = CPLAtof(CPLGetXMLValue(psSceneInfo,
                "sceneAverageHeight", "0.0"));

            //count and allocate gcps - there should be five - 4 corners and a centre
            poDS->nGCPCount = 0;
            CPLXMLNode *psNode = psSceneInfo->psChild;
            for ( ; psNode != NULL; psNode = psNode->psNext )
            {
                if (!EQUAL(psNode->pszValue, "sceneCenterCoord") &&
                    !EQUAL(psNode->pszValue, "sceneCornerCoord"))
                    continue;

                poDS->nGCPCount++;
            }
            if (poDS->nGCPCount > 0)
            {
                poDS->pasGCPList = (GDAL_GCP *)CPLCalloc(sizeof(GDAL_GCP), poDS->nGCPCount);

                /* iterate over GCPs */
                for (psNode = psSceneInfo->psChild; psNode != NULL; psNode = psNode->psNext )
                {
                    GDAL_GCP *psGCP = poDS->pasGCPList + nGCP;

                    if (!EQUAL(psNode->pszValue, "sceneCenterCoord") &&
                        !EQUAL(psNode->pszValue, "sceneCornerCoord"))
                        continue;

                    psGCP->dfGCPPixel = CPLAtof(CPLGetXMLValue(psNode, "refColumn",
                        "0.0"));
                    psGCP->dfGCPLine = CPLAtof(CPLGetXMLValue(psNode, "refRow", "0.0"));
                    psGCP->dfGCPX = CPLAtof(CPLGetXMLValue(psNode, "lon", "0.0"));
                    psGCP->dfGCPY = CPLAtof(CPLGetXMLValue(psNode, "lat", "0.0"));
                    psGCP->dfGCPZ = dfAvgHeight;
                    psGCP->pszId = CPLStrdup( CPLSPrintf( "%d", nGCP ) );
                    psGCP->pszInfo = CPLStrdup("");

                    nGCP++;
                }

                //set the projection string - the fields are lat/long - seems to be WGS84 datum
                OGRSpatialReference osr;
                osr.SetWellKnownGeogCS( "WGS84" );
                CPLFree(poDS->pszGCPProjection);
                osr.exportToWkt( &(poDS->pszGCPProjection) );
            }
        }

        //gcps override geotransform - does it make sense to have both??
        if (poDS->nGCPCount>0)
        {
            poDS->bHaveGeoTransform = FALSE;
            CPLFree( poDS->pszProjection );
            poDS->pszProjection = CPLStrdup("");
            poDS->adfGeoTransform[0] = 0.0;
            poDS->adfGeoTransform[1] = 1.0;
            poDS->adfGeoTransform[2] = 0.0;
            poDS->adfGeoTransform[3] = 0.0;
            poDS->adfGeoTransform[4] = 0.0;
            poDS->adfGeoTransform[5] = 1.0;
        }

    }
    else {
        CPLError(CE_Warning, CPLE_AppDefined,
            "Unable to find sceneInfo tag in XML document. "
            "Proceeding with caution.");
    }

    CPLFree(pszGeorefFile);

/* -------------------------------------------------------------------- */
/*      Initialize any PAM information.                                 */
/* -------------------------------------------------------------------- */
    poDS->SetDescription( poOpenInfo->pszFilename );
    poDS->TryLoadXML();

/* -------------------------------------------------------------------- */
/*      Check for overviews.                                            */
/* -------------------------------------------------------------------- */
    poDS->oOvManager.Initialize( poDS, poOpenInfo->pszFilename );

    CPLDestroyXMLNode(psData);

    return poDS;
}
Beispiel #19
0
GDALDataset *TSXDataset::Open( GDALOpenInfo *poOpenInfo ) {
/* -------------------------------------------------------------------- */
/*      Is this a TerraSAR-X product file?                              */
/* -------------------------------------------------------------------- */
	if (!TSXDataset::Identify( poOpenInfo )) {
		return NULL; /* nope */
	}
    
/* -------------------------------------------------------------------- */
/*      Confirm the requested access is supported.                      */
/* -------------------------------------------------------------------- */
    if( poOpenInfo->eAccess == GA_Update )
    {
        CPLError( CE_Failure, CPLE_NotSupported, 
                  "The TSX driver does not support update access to existing"
                  " datasets.\n" );
        return NULL;
    }
    
	/* Ingest the XML */
	CPLXMLNode *psData, *psComponents, *psProductInfo;
	psData = CPLParseXMLFile( poOpenInfo->pszFilename );

	/* find the product components */
	psComponents = CPLGetXMLNode( psData, "=level1Product.productComponents" );
	if (psComponents == NULL) {
		CPLError( CE_Failure, CPLE_OpenFailed, 
			"Unable to find <productComponents> tag in file.\n" );
		return NULL;
	}

	/* find the product info tag */
	psProductInfo = CPLGetXMLNode( psData, "=level1Product.productInfo" );
	if (psComponents == NULL) {
		CPLError( CE_Failure, CPLE_OpenFailed,
			"Unable to find <productInfo> tag in file.\n" );
		return NULL;
	}

/* -------------------------------------------------------------------- */
/*      Create the dataset.                                             */
/* -------------------------------------------------------------------- */
	
    TSXDataset *poDS = new TSXDataset();
	poDS->fp = poOpenInfo->fp;
	poOpenInfo->fp = NULL;

/* -------------------------------------------------------------------- */
/*      Read in product info.                                           */
/* -------------------------------------------------------------------- */

    poDS->SetMetadataItem( "SCENE_CENTRE_TIME", CPLGetXMLValue( psProductInfo,
        "sceneInfo.sceneCenterCoord.azimuthTimeUTC", "unknown" ) );
	poDS->SetMetadataItem( "OPERATIONAL_MODE", CPLGetXMLValue( psProductInfo, 
		"generationInfo.groundOperationsType", "unknown" ) );
	poDS->SetMetadataItem( "ORBIT_CYCLE", CPLGetXMLValue( psProductInfo,
		"missionInfo.orbitCycle", "unknown" ) );
	poDS->SetMetadataItem( "ABSOLUTE_ORBIT", CPLGetXMLValue( psProductInfo,
		"missionInfo.absOrbit", "unknown" ) );
	poDS->SetMetadataItem( "ORBIT_DIRECTION", CPLGetXMLValue( psProductInfo,
		"missionInfo.orbitDirection", "unknown" ) );
	poDS->SetMetadataItem( "IMAGING_MODE", CPLGetXMLValue( psProductInfo,
		"acquisitionInfo.imagingMode", "unknown" ) );
	poDS->SetMetadataItem( "PRODUCT_VARIANT", CPLGetXMLValue( psProductInfo,
		"productVariantInfo.productVariant", "unknown" ) ); 
	char *pszDataType = strdup( CPLGetXMLValue( psProductInfo,
		"imageDataInfo.imageDataType", "unknown" ) );
	poDS->SetMetadataItem( "IMAGE_TYPE", pszDataType ); 
	
	/* Get raster information */
	int nRows = atoi( CPLGetXMLValue( psProductInfo,
		"imageDataInfo.imageRaster.numberOfRows", "" ) );
	int nCols = atoi( CPLGetXMLValue( psProductInfo,
		"imageDataInfo.imageRaster.numberOfColumns", "" ) );

	poDS->nRasterXSize = nCols;
	poDS->nRasterYSize = nRows;

	poDS->SetMetadataItem( "ROW_SPACING", CPLGetXMLValue( psProductInfo,
		"imageDataInfo.imageRaster.rowSpacing", "unknown" ) );
	poDS->SetMetadataItem( "COL_SPACING", CPLGetXMLValue( psProductInfo,
		"imageDataInfo.imageRaster.columnSpacing", "unknown" ) );
    poDS->SetMetadataItem( "COL_SPACING_UNITS", CPLGetXMLValue( psProductInfo,
        "imageDataInfo.imageRaster.columnSpacing.units", "unknown" ) );

	/* Get equivalent number of looks */
	poDS->SetMetadataItem( "AZIMUTH_LOOKS", CPLGetXMLValue( psProductInfo,
		"imageDataInfo.imageRaster.azimuthLooks", "unknown" ) );
	poDS->SetMetadataItem( "RANGE_LOOKS", CPLGetXMLValue( psProductInfo,
		"imageDataInfo.imageRaster.rangeLooks", "unknown" ) );

    const char *pszProductVariant;
    pszProductVariant = CPLGetXMLValue( psProductInfo, 
        "productVariantInfo.productVariant", "unknown" );

    poDS->SetMetadataItem( "PRODUCT_VARIANT", pszProductVariant );

    /* Determine what product variant this is */
    if (EQUALN(pszProductVariant,"SSC",3))
        poDS->nProduct = eSSC;
    else if (EQUALN(pszProductVariant,"MGD",3))
        poDS->nProduct = eMGD;
    else if (EQUALN(pszProductVariant,"EEC",3))
        poDS->nProduct = eEEC;
    else if (EQUALN(pszProductVariant,"GEC",3))
        poDS->nProduct = eGEC;
    else
        poDS->nProduct = eUnknown;

	/* Start reading in the product components */
	const char *pszPath;
	char *pszGeorefFile = NULL;
	CPLXMLNode *psComponent;
	for (psComponent = psComponents->psChild; psComponent != NULL;
		 psComponent = psComponent->psNext)
	{
		char *pszType;
		pszPath = CPLFormFilename( 
				CPLGetDirname( poOpenInfo->pszFilename ),
				GetFilePath(psComponent, &pszType), 
				"" );
		const char *pszPolLayer = CPLGetXMLValue(psComponent, "polLayer", " ");

		if ( !EQUALN(pszType," ",1) ) {
			if (EQUALN(pszType, "MAPPING_GRID", 12) ) {
				/* the mapping grid... save as a metadata item this path */
				poDS->SetMetadataItem( "MAPPING_GRID", pszPath );	
			}
			else if (EQUALN(pszType, "GEOREF", 6)) {
				/* save the path to the georef data for later use */
				pszGeorefFile = strdup( pszPath );
			}
			CPLFree(pszType);
		}
		else if( !EQUALN(pszPolLayer, " ", 1) && 
			EQUALN(psComponent->pszValue, "imageData", 9) ) {
			/* determine the polarization of this band */
			ePolarization ePol;
			if ( EQUALN(pszPolLayer, "HH", 2) ) {
				ePol = HH;
			}
			else if ( EQUALN(pszPolLayer, "HV" , 2) ) {
				ePol = HV;
			}
			else if ( EQUALN(pszPolLayer, "VH", 2) ) {
				ePol = VH;
			}
			else {
				ePol = VV;
			}

			GDALDataType eDataType = EQUALN(pszDataType, "COMPLEX", 7) ?
				GDT_CInt16 : GDT_UInt16;

			/* try opening the file that represents that band */
			TSXRasterBand *poBand;
			GDALDataset *poBandData;

			poBandData = (GDALDataset *) GDALOpen( pszPath, GA_ReadOnly );
			if ( poBandData != NULL ) {
				poBand = new TSXRasterBand( poDS, eDataType, ePol, 
					poBandData );
				poDS->SetBand( poDS->GetRasterCount() + 1, poBand );
			}
		}
	}

	CPLFree(pszDataType);


/* -------------------------------------------------------------------- */
/*      Check and set matrix representation.                            */
/* -------------------------------------------------------------------- */

	if (poDS->GetRasterCount() == 4) {
		poDS->SetMetadataItem( "MATRIX_REPRESENTATION", "SCATTERING" );
	}

/* -------------------------------------------------------------------- */
/*      Read the four corners and centre GCPs in                        */
/* -------------------------------------------------------------------- */

    CPLXMLNode *psSceneInfo = CPLGetXMLNode( psData, 
        "=level1Product.productInfo.sceneInfo" );
    /* for SSC products */
    if (poDS->nProduct == eSSC && psSceneInfo != NULL) {
        CPLXMLNode *psNode;
        int nGCP = 0;
        double dfAvgHeight = atof(CPLGetXMLValue(psSceneInfo, 
            "sceneAverageHeight", "0.0"));
        char szID[3];

        poDS->nGCPCount = 5; /* 5 GCPs provided */
        poDS->pasGCPList = (GDAL_GCP *)CPLCalloc(sizeof(GDAL_GCP), 
            poDS->nGCPCount);

        /* iterate over GCPs */
        for (psNode = psSceneInfo->psChild; psNode != NULL; 
             psNode = psNode->psNext )
        {
            GDAL_GCP *psGCP = poDS->pasGCPList + nGCP;

            if (!EQUAL(psNode->pszValue, "sceneCenterCoord") && 
                !EQUAL(psNode->pszValue, "sceneCornerCoord"))
                continue;

            CPLSPrintf( szID, "%d", nGCP );
            
            psGCP->dfGCPPixel = atof(CPLGetXMLValue(psNode, "refColumn", 
                "0.0"));
            psGCP->dfGCPLine = atof(CPLGetXMLValue(psNode, "refRow", "0.0"));
            psGCP->dfGCPX = atof(CPLGetXMLValue(psNode, "lon", "0.0"));
            psGCP->dfGCPY = atof(CPLGetXMLValue(psNode, "lat", "0.0"));
            psGCP->dfGCPZ = dfAvgHeight;
            psGCP->pszId = CPLStrdup( szID );
            psGCP->pszInfo = CPLStrdup("");

            nGCP++;
        }
    }
    else if (psSceneInfo != NULL) {
        /* extract the GCPs from the provided file */

        /* TODO */
    }
    else {
        CPLError(CE_Warning, CPLE_AppDefined, 
            "Unable to find sceneInfo tag in XML document. " 
            "Proceeding with caution.");
    }

/* -------------------------------------------------------------------- */
/*      Initialize any PAM information.                                 */
/* -------------------------------------------------------------------- */
    poDS->SetDescription( poOpenInfo->pszFilename );
    poDS->TryLoadXML();

/* -------------------------------------------------------------------- */
/*      Check for overviews.                                            */
/* -------------------------------------------------------------------- */
    poDS->oOvManager.Initialize( poDS, poOpenInfo->pszFilename );

    CPLDestroyXMLNode(psData);

    return poDS;
}
Beispiel #20
0
static int DOKAN_CALLBACK
MirrorReadFile(
	LPCWSTR				FileName,
	LPVOID				Buffer,
	DWORD				BufferLength,
	LPDWORD				ReadLength,
	LONGLONG			Offset,
	PDOKAN_FILE_INFO	DokanFileInfo)
{
	WCHAR	filePath[MAX_PATH];
	HANDLE	handle = (HANDLE)DokanFileInfo->Context;
	ULONG	offset = (ULONG)Offset;
	BOOL	opened = FALSE;

	GetFilePath(filePath, MAX_PATH, FileName);

	DbgPrint(L"ReadFile : %s\n", filePath);

	if (!handle || handle == INVALID_HANDLE_VALUE) {
		DbgPrint(L"\tinvalid handle, cleanuped?\n");
		handle = CreateFile(
			filePath,
			GENERIC_READ,
			FILE_SHARE_READ,
			NULL,
			OPEN_EXISTING,
			0,
			NULL);
		if (handle == INVALID_HANDLE_VALUE) {
			DbgPrint(L"\tCreateFile error : %d\n\n", GetLastError());
			return -1;
		}
		opened = TRUE;
	}
	
    LARGE_INTEGER distanceToMove;
    distanceToMove.QuadPart = Offset;
    if (!SetFilePointerEx(handle, distanceToMove, NULL, FILE_BEGIN)) {
		DbgPrint(L"\tseek error, offset = %d\n\n", offset);
		if (opened)
			CloseHandle(handle);
		return -1;
	}

		
	if (!ReadFile(handle, Buffer, BufferLength, ReadLength,NULL)) {
		DbgPrint(L"\tread error = %u, buffer length = %d, read length = %d\n\n",
			GetLastError(), BufferLength, *ReadLength);
		if (opened)
			CloseHandle(handle);
		return -1;

	} else {
		DbgPrint(L"\tread %d, offset %d\n\n", *ReadLength, offset);
	}

	if (opened)
		CloseHandle(handle);

	return 0;
}
Beispiel #21
0
static int DOKAN_CALLBACK
MirrorWriteFile(
	LPCWSTR		FileName,
	LPCVOID		Buffer,
	DWORD		NumberOfBytesToWrite,
	LPDWORD		NumberOfBytesWritten,
	LONGLONG			Offset,
	PDOKAN_FILE_INFO	DokanFileInfo)
{
	WCHAR	filePath[MAX_PATH];
	HANDLE	handle = (HANDLE)DokanFileInfo->Context;
	ULONG	offset = (ULONG)Offset;
	BOOL	opened = FALSE;

	GetFilePath(filePath, MAX_PATH, FileName);

	DbgPrint(L"WriteFile : %s, offset %I64d, length %d\n", filePath, Offset, NumberOfBytesToWrite);

	// reopen the file
	if (!handle || handle == INVALID_HANDLE_VALUE) {
		DbgPrint(L"\tinvalid handle, cleanuped?\n");
		handle = CreateFile(
			filePath,
			GENERIC_WRITE,
			FILE_SHARE_WRITE,
			NULL,
			OPEN_EXISTING,
			0,
			NULL);
		if (handle == INVALID_HANDLE_VALUE) {
			DbgPrint(L"\tCreateFile error : %d\n\n", GetLastError());
			return -1;
		}
		opened = TRUE;
	}

    LARGE_INTEGER distanceToMove;
    distanceToMove.QuadPart = Offset;

	if (DokanFileInfo->WriteToEndOfFile) {
        LARGE_INTEGER z;
        z.QuadPart = 0;
		if (!SetFilePointerEx(handle, z, NULL, FILE_END)) {
			DbgPrint(L"\tseek error, offset = EOF, error = %d\n", GetLastError());
			return -1;
		}
    }
    else if (!SetFilePointerEx(handle, distanceToMove, NULL, FILE_BEGIN)) {
		DbgPrint(L"\tseek error, offset = %d, error = %d\n", offset, GetLastError());
		return -1;
	}

		
	if (!WriteFile(handle, Buffer, NumberOfBytesToWrite, NumberOfBytesWritten, NULL)) {
		DbgPrint(L"\twrite error = %u, buffer length = %d, write length = %d\n",
			GetLastError(), NumberOfBytesToWrite, *NumberOfBytesWritten);
		return -1;

	} else {
		DbgPrint(L"\twrite %d, offset %d\n\n", *NumberOfBytesWritten, offset);
	}

	// close the file when it is reopened
	if (opened)
		CloseHandle(handle);

	return 0;
}
Beispiel #22
0
//--------------------------------------------------------------------------------------
void FBXScene::ProcessMaterials(FbxScene* pScene)
{
	for( int i = 0; i < pScene->GetMaterialCount(); ++i )
	{
		Material* pMaterial = new Material(i);

		FbxSurfaceMaterial* pFBXMaterial = pScene->GetMaterial(i);

		FbxProperty diffuseTextureProperty = pFBXMaterial->FindProperty(FbxSurfaceMaterial::sDiffuse);
		if( diffuseTextureProperty.IsValid() )
		{
			FbxFileTexture* pDiffuseTexture = diffuseTextureProperty.GetSrcObject<FbxFileTexture>(0);

			if( pDiffuseTexture )
			{
				std::string strFileName = pDiffuseTexture->GetFileName();

				if( strFileName.length() == 0 )
					strFileName = pDiffuseTexture->GetRelativeFileName();

				strFileName = GetFileFromPath(strFileName);

				pMaterial->SetDiffuseTextureName(strFileName);
			}
		}
		
		FbxProperty normalTextureProperty = pFBXMaterial->FindProperty(FbxSurfaceMaterial::sNormalMap);
		if( normalTextureProperty.IsValid() )
		{
				FbxFileTexture* pNormalTexture = normalTextureProperty.GetSrcObject<FbxFileTexture>(0);

				if( pNormalTexture )
				{
					std::string strFileName = pNormalTexture->GetFileName();

					if( strFileName.length() == 0 )
						strFileName = pNormalTexture->GetRelativeFileName();
					
					strFileName = GetFileFromPath(strFileName);

					pMaterial->SetNormalTextureName(strFileName);
				}
		}

		FbxSurfaceLambert* pLambert = FbxCast<FbxSurfaceLambert>(pFBXMaterial);
		FbxSurfacePhong* pPhong = FbxCast<FbxSurfacePhong>(pFBXMaterial); 

		BTHFBX_VEC3 AmbientColor2;
		BTHFBX_VEC3 EmissiveColor2;
		BTHFBX_VEC3 DiffuseColor2;
		BTHFBX_VEC3 SpecularColor2;

		float fSpecularPower = 1.0f;
		float fTransparency = 1.0f;

		if( pLambert )
		{
			AmbientColor2 = GetMaterialColor2(pLambert->Ambient, pLambert->AmbientFactor);
			EmissiveColor2 = GetMaterialColor2(pLambert->Emissive, pLambert->EmissiveFactor);
			DiffuseColor2 = GetMaterialColor2(pLambert->Diffuse, pLambert->DiffuseFactor);

			FbxPropertyT<FbxDouble> FBXTransparencyProperty = pLambert->TransparencyFactor;

			if( FBXTransparencyProperty.IsValid() )
				fTransparency = (float)FBXTransparencyProperty.Get();
		}

		if( pPhong )
		{
			SpecularColor2 = GetMaterialColor2(pPhong->Specular, pPhong->SpecularFactor);

			FbxPropertyT<FbxDouble> FBXSpecularPowerProperty = pPhong->Shininess;

			if( FBXSpecularPowerProperty.IsValid() )
				fSpecularPower = (float)FBXSpecularPowerProperty.Get();
		}

		pMaterial->SetAmbientColor2(AmbientColor2);
		pMaterial->SetEmissiveColor2(EmissiveColor2);
		pMaterial->SetDiffuseColor2(DiffuseColor2);
		pMaterial->SetSpecularColor2(SpecularColor2);

		pMaterial->SetSpecularPower(fSpecularPower);
		pMaterial->SetTransparency(fTransparency);

		pMaterial->AddTexturePath( GetFilePath(this->mFilename) + "/" );

		m_Materials.push_back(pMaterial);
		m_FBXMaterials.push_back(pFBXMaterial);
	}
}
Beispiel #23
0
bool GetExePath(char *path)
{
	TCHAR buf[MAX_PATH+1];
	GetModuleFileName(NULL,buf,MAX_PATH);
	return GetFilePath(buf,path,MAX_PATH);
}
	__time64_t CDirectoryManagerBase::GetLastUpdate(const std::string& fileName, const std::string& fileExt, bool bVerifyAllFiles)const
	{
		std::string filePath = GetFilePath(fileName, fileExt);
		return GetFileStamp(fileName);
	}
Beispiel #25
0
void CImagePack::SaveConfig( const tagHistoryInfo& _info )
{
	CString strConfig = GetFilePath()+"\\Config.ini";
	CString strTemp;
	tagHistoryInfo tempInfo;
	bool    bFindSame = false;
	int     curUpdateIndex;
	m_nSwitchOption = 0;
	m_nSwitchOption|=((CButton*)GetDlgItem(IDC_SUBITEMUSE))->GetCheck()?SWITCH_OPTION_SAME:0;
	m_nSwitchOption|=((CButton*)GetDlgItem(IDC_OPTIMIZE))->GetCheck()?SWITCH_OPTION_AUTO:0;
	m_nSwitchOption|=((CButton*)GetDlgItem(IDC_2MI))->GetCheck()?SWITCH_OPTION_TOWMI:0;
	m_nSwitchOption|=((CButton*)GetDlgItem(IDC_LUACORE))->GetCheck()?SWITCH_OPTION_LUA:0;
	strTemp.Format("%d",m_nSwitchOption);
	WritePrivateProfileString("Info","switchOption",strTemp.GetString(),strConfig);
	for (int i=0;i<m_vecHistory.size();i++)
	{
		if(m_vecHistory[i].strFilePath == _info.strFilePath){
			bFindSame = true;
			m_vecHistory[i].nSpace = _info.nSpace;
			m_vecHistory[i].nMaxHeight = _info.nMaxHeight;
			m_vecHistory[i].nMaxWidth = _info.nMaxWidth;
			m_vecHistory[i].strFileName = _info.strFileName;

			tempInfo.nSpace = _info.nSpace;
			tempInfo.nMaxHeight = _info.nMaxHeight;
			tempInfo.nMaxWidth = _info.nMaxWidth;
			tempInfo.strFileName = _info.strFileName;
			tempInfo.strFilePath = _info.strFilePath;
			tempInfo.nDataType = _info.nDataType;
			curUpdateIndex = i+1;
			break;
		}
	}

	
	if(!bFindSame)
	{
		if(m_nLoopIndex>=m_nMaxSize)
			m_nLoopIndex = 0;
		
		if(m_nLoopIndex>=m_vecHistory.size())
		{

			tempInfo.nSpace = _info.nSpace;
			tempInfo.nMaxHeight = _info.nMaxHeight;
			tempInfo.nMaxWidth = _info.nMaxWidth;
			tempInfo.strFileName = _info.strFileName;
			tempInfo.strFilePath = _info.strFilePath;
			tempInfo.nDataType = _info.nDataType;
			m_vecHistory.push_back(tempInfo);
			m_nLoopIndex++;
			m_nSize = m_vecHistory.size();
			insertComboBox(tempInfo.strFilePath);
			
			curUpdateIndex = m_nLoopIndex;
		}else
		{
			tagHistoryInfo &tempInfo = m_vecHistory[m_nLoopIndex];
			tempInfo.nSpace = _info.nSpace;
			tempInfo.nMaxHeight = _info.nMaxHeight;
			tempInfo.nMaxWidth = _info.nMaxWidth;
			tempInfo.strFileName = _info.strFileName;
			tempInfo.strFilePath = _info.strFilePath;
			tempInfo.nDataType = _info.nDataType;
			
			insertComboBox(tempInfo.strFilePath);
			m_nLoopIndex++;
			curUpdateIndex = m_nLoopIndex;
		}
	}
	
	CString strHistory;
	strHistory.Format("History%d",curUpdateIndex);
	strTemp.Format("%d",tempInfo.nSpace);
	WritePrivateProfileString(strHistory,"space",strTemp.GetString(),strConfig); 
	strTemp.Format("%d",tempInfo.nMaxHeight);
	WritePrivateProfileString(strHistory,"maxWidth",strTemp.GetString(),strConfig);
	strTemp.Format("%d",tempInfo.nMaxWidth);
	WritePrivateProfileString(strHistory,"maxHeight",strTemp.GetString(),strConfig);
	strTemp.Format("%d",tempInfo.nDataType);
	WritePrivateProfileString(strHistory,"dataType",strTemp.GetString(),strConfig);
	WritePrivateProfileString(strHistory,"fileName",tempInfo.strFileName.GetString(),strConfig);
	WritePrivateProfileString(strHistory,"filePath",tempInfo.strFilePath.GetString(),strConfig);

	strTemp.Format("%d",m_nSize);
	WritePrivateProfileString("Info","Size",strTemp.GetString(),strConfig); 
	strTemp.Format("%d",m_nMaxSize);
	WritePrivateProfileString("Info","MaxSize",strTemp.GetString(),strConfig);
	strTemp.Format("%d",m_nCurIndex);
	WritePrivateProfileString("Info","CurIndex",strTemp.GetString(),strConfig);
	strTemp.Format("%d",m_nLoopIndex);
	WritePrivateProfileString("Info","LoopIndex",strTemp.GetString(),strConfig);

	

	
}
Beispiel #26
0
/**
 * @brief recover the database and check the tuples
 */
void DoRecovery(std::string file_name) {
  std::chrono::time_point<std::chrono::system_clock> start, end;
  std::chrono::duration<double, std::milli> elapsed_milliseconds;

  auto file_path = GetFilePath(state.log_file_dir, file_name);

  std::ifstream log_file(file_path);

  // Reset the log file if exists
  log_file.close();

  CreateDatabaseAndTable(LOGGING_TESTS_DATABASE_OID, LOGGING_TESTS_TABLE_OID);

  // start a thread for logging
  auto& log_manager = logging::LogManager::GetInstance();
  if (log_manager.ActiveFrontendLoggerCount() > 0) {
    LOG_ERROR("another logging thread is running now");
    return;
  }

  //===--------------------------------------------------------------------===//
  // RECOVERY
  //===--------------------------------------------------------------------===//

  start = std::chrono::system_clock::now();

  // set log file and logging type
  log_manager.SetLogFileName(file_path);

  // start off the frontend logger of appropriate type in STANDBY mode
  std::thread thread(&logging::LogManager::StartStandbyMode, &log_manager);

  // wait for the frontend logger to enter STANDBY mode
  log_manager.WaitForMode(LOGGING_STATUS_TYPE_STANDBY, true);

  // STANDBY -> RECOVERY mode
  log_manager.StartRecoveryMode();

  // Wait for the frontend logger to enter LOGGING mode after recovery
  log_manager.WaitForMode(LOGGING_STATUS_TYPE_LOGGING, true);

  end = std::chrono::system_clock::now();
  elapsed_milliseconds = end - start;

  // Recovery time
  if (state.experiment_type == EXPERIMENT_TYPE_RECOVERY)
    WriteOutput(elapsed_milliseconds.count());

  // Check the tuple count if needed
  if (state.check_tuple_count) {
    oid_t total_expected = 0;
    CheckTupleCount(LOGGING_TESTS_DATABASE_OID, LOGGING_TESTS_TABLE_OID,
                    total_expected);
  }

  // Check the next oid
  // CheckNextOid();

  if (log_manager.EndLogging()) {
    thread.join();
  } else {
    LOG_ERROR("Failed to terminate logging thread");
  }
  DropDatabaseAndTable(LOGGING_TESTS_DATABASE_OID, LOGGING_TESTS_TABLE_OID);
}
Beispiel #27
0
/**
 *  Hauptfunktion von Siedler II.5 Return to the Roots
 *
 *  @param[in] argc Anzahl übergebener Argumente
 *  @param[in] argv Array der übergebenen Argumente
 *
 *  @return Exit Status, 0 bei Erfolg, > 0 bei Fehler
 *
 *  @author FloSoft
 *  @author OLiver
 */
int main(int argc, char* argv[])
{
#if defined _WIN32 && defined _DEBUG && defined _MSC_VER && !defined NOHWETRANS
    _set_se_translator(ExceptionHandler);
#endif // _WIN32 && _DEBUG && !NOHWETRANS

#if defined _WIN32 && defined _DEBUG && defined _MSC_VER && !defined NOCRTDBG
    // Enable Memory-Leak-Detection
    _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_CHECK_ALWAYS_DF | _CRTDBG_LEAK_CHECK_DF /*| _CRTDBG_CHECK_CRT_DF*/);
#endif // _WIN32 && _DEBUG && !NOCRTDBG

    // Signal-Handler setzen
#ifdef _WIN32
    SetConsoleCtrlHandler(HandlerRoutine, TRUE);

    // set console window icon
    SendMessage(GetConsoleWindow(), WM_SETICON, (WPARAM)TRUE, (LPARAM)LoadIcon(GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_SYMBOL)));

    // Set UTF-8 console charset
    SetConsoleOutputCP(CP_UTF8);

#ifndef _MSC_VER
    signal(SIGSEGV, WinExceptionHandler);
#else
    SetUnhandledExceptionFilter(WinExceptionHandler);
#endif
    //AddVectoredExceptionHandler(1, WinExceptionHandler);
#else
    struct sigaction sa;
    sa.sa_handler = HandlerRoutine;
    sa.sa_flags = 0; //SA_RESTART would not allow to interrupt connect call;
    sigemptyset(&sa.sa_mask);

    sigaction(SIGINT, &sa, NULL);
    sigaction(SIGPIPE, &sa, NULL);
    sigaction(SIGALRM, &sa, NULL);

    signal(SIGSEGV, LinExceptionHandler);
#endif // _WIN32

    // diverse dirs anlegen
    const unsigned int dir_count = 7;
    unsigned int dirs[dir_count] = { 94, 47, 48, 51, 85, 98, 99 }; // settingsdir muss zuerst angelegt werden (94)

#ifdef _WIN32
    if(IsDir(GetFilePath("~/Siedler II.5 RttR")))
        MoveFileA(GetFilePath("~/Siedler II.5 RttR").c_str(), GetFilePath(FILE_PATHS[94]).c_str());
#endif

#ifdef __APPLE__
    if(IsDir(GetFilePath("~/.s25rttr")))
        rename(GetFilePath("~/.s25rttr").c_str(), GetFilePath(FILE_PATHS[94]).c_str());
#endif

    for(unsigned int i = 0; i < dir_count; ++i)
    {
        std::string dir = GetFilePath(FILE_PATHS[dirs[i]]);

        if(mkdir_p(dir) < 0)
        {
            error("Verzeichnis %s konnte nicht erstellt werden: ", dir.c_str());
            error("Das Spiel konnte nicht gestartet werden");
            return 1;
        }
    }

    libsiedler2::setTextureFormat(libsiedler2::FORMAT_RGBA);
    libsiedler2::setAllocator(glAllocator);

    // Zufallsgenerator initialisieren (Achtung: nur für Animationens-Offsets interessant, für alles andere (spielentscheidende) wird unser Generator verwendet)
    srand(static_cast<unsigned int>(std::time(NULL)));

    // Exit-Handler initialisieren
    atexit(&ExitHandler);

    // Socketzeug initialisieren
    if(!Socket::Initialize())
    {
        error("Konnte Sockets nicht initialisieren!");
        return 1;
    }

    // Spiel starten
    if(!GAMEMANAGER.Start())
    {
        error("Das Spiel konnte nicht gestartet werden");
        return 1;
    }

#ifndef NDEBUG
    if (argc > 1)
    {
        CreateServerInfo csi;
        csi.gamename = _("Unlimited Play");
        csi.password = "******";
        csi.port = 3665;
        csi.type = NP_LOCAL;
        csi.ipv6 = false;
        csi.use_upnp = false;

        printf("loading game!\n");

        WINDOWMANAGER.Switch(new dskSelectMap(csi));

        if(!GAMESERVER.TryToStart(csi, argv[1], MAPTYPE_SAVEGAME))
        {
            if(!GAMESERVER.TryToStart(csi, argv[1], MAPTYPE_OLDMAP))
            {
                GameWorldViewer* gwv;
                unsigned int error = GAMECLIENT.StartReplay(argv[1], gwv);

                std::string replay_errors[] =
                {
                    _("Error while playing replay!"),
                    _("Error while opening file!"),
                    _("Invalid Replay!"),
                    _("Error: Replay is too old!"),
                    _("Program version is too old to play that replay!"),
                    "",
                    _("Temporary map file was not found!")
                };

                if (error)
                {
                    printf("ERROR: %s\n", replay_errors[error].c_str());
                }
                else
                {
                    WINDOWMANAGER.Switch(new dskGameLoader(gwv));
                }
            }
            else
            {
                WINDOWMANAGER.Draw();
                WINDOWMANAGER.Show(new iwPleaseWait);
            }
        }
        else
        {
            WINDOWMANAGER.Draw();
            WINDOWMANAGER.Show(new iwPleaseWait);
        }
    }
#endif

    // Hauptschleife
    while(GAMEMANAGER.Run())
    {
#ifndef _WIN32
        extern bool killme;
        killme = false;
#endif // !_WIN32
    }

    // Spiel beenden
    GAMEMANAGER.Stop();

    return 0;
}
Beispiel #28
0
// 実行ファイルのパスを返す(末尾に\が付く)
std::string GetExePath()
{
	char buf[MAX_PATH+1];
	GetModuleFileName(NULL, buf, MAX_PATH);
	return GetFilePath(buf);
}
	bool CDirectoryManager::FileExists(const std::string& fileName)const
	{
		std::string tmp = GetFilePath(fileName);
		return !tmp.empty();
	}
void emPngImageFileModel::TryStartLoading() throw(emString)
{
	emString colTypeStr;
	int rowbytes,originalPixelSize;

	L=new emPngLoadingState;
	memset(L,0,sizeof(emPngLoadingState));

	L->file=fopen(GetFilePath(),"rb");
	if (!L->file) throw emGetErrorText(errno);

	if (setjmp(L->jmpbuffer)) throw emString(L->errorText);

	L->png_ptr=png_create_read_struct(
		PNG_LIBPNG_VER_STRING,
		(png_voidp)L,
		emPng_error_fn,
		emPng_warning_fn
	);
	if (!L->png_ptr) throw emString("PNG lib failed.");

	L->info_ptr=png_create_info_struct(L->png_ptr);
	if (!L->info_ptr) throw emString("PNG lib failed.");

	L->end_info_ptr=png_create_info_struct(L->png_ptr);
	if (!L->end_info_ptr) throw emString("PNG lib failed.");

	png_init_io(L->png_ptr, L->file);

	png_read_info(L->png_ptr, L->info_ptr);

	png_get_IHDR(
		L->png_ptr,
		L->info_ptr,
		&L->width,
		&L->height,
		&L->bit_depth,
		&L->color_type,
		&L->interlace_type,
		NULL,
		NULL
	);

	originalPixelSize=L->bit_depth;
	if ((L->color_type&PNG_COLOR_MASK_PALETTE)==0) {
		originalPixelSize*=png_get_channels(L->png_ptr,L->info_ptr);
	}

	if ((L->color_type&PNG_COLOR_MASK_COLOR)!=0) {
		colTypeStr="color";
	}
	else {
		colTypeStr="grayscale";
	}
	if ((L->color_type&PNG_COLOR_MASK_ALPHA)!=0) {
		colTypeStr+="-alpha";
	}
	if ((L->color_type&PNG_COLOR_MASK_PALETTE)!=0) {
		colTypeStr+="-palette";
	}

	png_set_expand(L->png_ptr);
	png_set_strip_16(L->png_ptr);
	png_set_packing(L->png_ptr);
	L->number_of_passes=png_set_interlace_handling(L->png_ptr);
	png_read_update_info(L->png_ptr, L->info_ptr);
	rowbytes=png_get_rowbytes(L->png_ptr,L->info_ptr);
	L->bytes_per_pixel=rowbytes/L->width;
	if (rowbytes%L->width!=0 || L->bytes_per_pixel<1 || L->bytes_per_pixel>4) {
		throw emString("Unsupported PNG format.");
	}

	FileFormatInfo=emString::Format(
		"PNG %d-bit %s (%d channels extracted)",
		originalPixelSize,
		colTypeStr.Get(),
		(int)L->bytes_per_pixel
	);
	Signal(ChangeSignal);
}