コード例 #1
0
NS_IMETHODIMP nsMsgMaildirStore::ChangeKeywords(nsIArray *aHdrArray,
                                             const nsACString &aKeywords,
                                             bool aAdd)
{
  NS_ENSURE_ARG_POINTER(aHdrArray);
  NS_ENSURE_ARG_POINTER(aHdrArray);
  nsCOMPtr<nsIOutputStream> outputStream;
  nsCOMPtr<nsISeekableStream> seekableStream;

  uint32_t messageCount;
  nsresult rv = aHdrArray->GetLength(&messageCount);
  NS_ENSURE_SUCCESS(rv, rv);
  if (!messageCount)
    return NS_ERROR_INVALID_ARG;

  nsAutoPtr<nsLineBuffer<char> > lineBuffer(new nsLineBuffer<char>);
  NS_ENSURE_TRUE(lineBuffer, NS_ERROR_OUT_OF_MEMORY);

  nsTArray<nsCString> keywordArray;
  ParseString(aKeywords, ' ', keywordArray);

  for (uint32_t i = 0; i < messageCount; ++i) // for each message
  {
    nsCOMPtr<nsIMsgDBHdr> message = do_QueryElementAt(aHdrArray, i, &rv);
    NS_ENSURE_SUCCESS(rv, rv);
    // get output stream for header
    nsCOMPtr<nsIOutputStream> outputStream;
    rv = GetOutputStream(message, outputStream);
    NS_ENSURE_SUCCESS(rv, rv);
    nsCOMPtr <nsIInputStream> inputStream = do_QueryInterface(outputStream, &rv);
    NS_ENSURE_SUCCESS(rv, rv);
    nsCOMPtr <nsISeekableStream> seekableStream(do_QueryInterface(inputStream, &rv));
    NS_ENSURE_SUCCESS(rv, rv);
    uint32_t statusOffset = 0;
    (void)message->GetStatusOffset(&statusOffset);
    uint64_t desiredOffset = statusOffset;

    ChangeKeywordsHelper(message, desiredOffset, lineBuffer, keywordArray,
                         aAdd, outputStream, seekableStream, inputStream);
    if (inputStream)
      inputStream->Close();
    // ### TODO - if growKeywords property is set on the message header,
    // we need to rewrite the message file with extra room for the keywords,
    // or schedule some sort of background task to do this.
  }
  lineBuffer = nullptr;
  return NS_OK;
}
コード例 #2
0
void LineBufferCPU(int inH, int inW, int padH, int padW, int kH, int kW, int stride, float *kernel, float *dataIn, float *dataOut){
  int paddedH = inH+2*padH;
  int paddedW = inW+2*padW;
  float *padded = malloc(paddedH*paddedW*sizeof(float));
  pad(inH,inW,padH,padW,dataIn,padded); 
  int outH = (paddedH-kH) + 1;
  int outW = (paddedW-kW) + 1;
  float **lb = malloc(outH*outW*sizeof(float*));
  for (int i=0; i<outH*outW; i++) lb[i] = malloc(kH*kW*sizeof(float));
  lineBuffer(paddedH,paddedW,kH,kW,stride,padded,lb);
  print_2d_data(padded, "PADDED",paddedH,paddedW);
  free(padded);
  for (int i=0; i<outH*outW; i++) {
    dataOut[i] = 0;
    for(int j=0; j<kH*kW;j++) {
      dataOut[i] += kernel[j] *lb[i][j];
    }
  }
  for (int i=0; i<outH*outW; i++) free(lb[i]);
  free(lb);
  
}
コード例 #3
0
NS_IMETHODIMP nsMsgBrkMBoxStore::ChangeKeywords(nsIArray *aHdrArray,
                                             const nsACString &aKeywords,
                                             bool aAdd)
{
  NS_ENSURE_ARG_POINTER(aHdrArray);
  nsCOMPtr<nsIOutputStream> outputStream;
  nsCOMPtr<nsISeekableStream> seekableStream;
  int64_t restoreStreamPos;

  uint32_t messageCount;
  nsresult rv = aHdrArray->GetLength(&messageCount);
  NS_ENSURE_SUCCESS(rv, rv);
  if (!messageCount)
    return NS_ERROR_INVALID_ARG;

  rv = GetOutputStream(aHdrArray, outputStream, seekableStream,
                       restoreStreamPos);
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr<nsIInputStream> inputStream = do_QueryInterface(outputStream, &rv);
  NS_ENSURE_SUCCESS(rv, rv);

  nsAutoPtr<nsLineBuffer<char> > lineBuffer(new nsLineBuffer<char>);
  NS_ENSURE_TRUE(lineBuffer, NS_ERROR_OUT_OF_MEMORY);

  // For each message, we seek to the beginning of the x-mozilla-status header,
  // and start reading lines, looking for x-mozilla-keys: headers; If we're
  // adding the keyword and we find
  // a header with the desired keyword already in it, we don't need to
  // do anything. Likewise, if removing keyword and we don't find it,
  // we don't need to do anything. Otherwise, if adding, we need to
  // see if there's an x-mozilla-keys
  // header with room for the new keyword. If so, we replace the
  // corresponding number of spaces with the keyword. If no room,
  // we can't do anything until the folder is compacted and another
  // x-mozilla-keys header is added. In that case, we set a property
  // on the header, which the compaction code will check.

  nsTArray<nsCString> keywordArray;
  ParseString(aKeywords, ' ', keywordArray);

  nsCOMPtr<nsIMsgDBHdr> msgHdr;
  for (uint32_t i = 0; i < messageCount; ++i) // for each message
  {
    msgHdr = do_QueryElementAt(aHdrArray, i, &rv);
    NS_ENSURE_SUCCESS(rv, rv);
    uint64_t messageOffset;
    msgHdr->GetMessageOffset(&messageOffset);
    uint32_t statusOffset = 0;
    (void)msgHdr->GetStatusOffset(&statusOffset);
    uint64_t desiredOffset = messageOffset + statusOffset;

    ChangeKeywordsHelper(msgHdr, desiredOffset, lineBuffer, keywordArray,
                         aAdd, outputStream, seekableStream, inputStream);
  }
  lineBuffer = nullptr;
  if (restoreStreamPos != -1)
    seekableStream->Seek(nsISeekableStream::NS_SEEK_SET, restoreStreamPos);
  else if (outputStream)
    outputStream->Close();
  if (messageCount > 0)
  {
    msgHdr = do_QueryElementAt(aHdrArray, 0);
    SetDBValid(msgHdr);
  }
  return NS_OK;
}
コード例 #4
0
CResourceCompilerHelper::ERcCallResult CResourceCompilerHelper::CallResourceCompiler(
	const char* szFileName, 
	const char* szAdditionalSettings, 
	IResourceCompilerListener* listener, 
	bool bMayShowWindow, 
	CResourceCompilerHelper::ERcExePath rcExePath, 
	bool bSilent,
	bool bNoUserDialog,
	const wchar_t* szWorkingDirectory,
	const wchar_t* szRootPath)
{
	// make command for execution
	SettingsManagerHelpers::CFixedString<wchar_t, MAX_PATH * 3> wRemoteCmdLine;
	CSettingsManagerTools smTools = CSettingsManagerTools();

	if (!szAdditionalSettings)
	{
		szAdditionalSettings = "";
	}

	wchar_t szRcDirectory[512];
	{
		wchar_t pathBuffer[512];
		switch (rcExePath)
		{
		case eRcExePath_registry:
			smTools.GetRootPathUtf16(true, SettingsManagerHelpers::CWCharBuffer(pathBuffer, sizeof(pathBuffer)));
			break;
		case eRcExePath_settingsManager:
			smTools.GetRootPathUtf16(false, SettingsManagerHelpers::CWCharBuffer(pathBuffer, sizeof(pathBuffer)));
			break;
		case eRcExePath_currentFolder:
			wcscpy(pathBuffer, L".");
			break;
		case eRcExePath_customPath:
			wcscpy(pathBuffer, szRootPath);
			break;
		default:
			return eRcCallResult_notFound;
		}

		if (!pathBuffer[0])
		{
			wcscpy(pathBuffer, L".");
		}

		if (smTools.Is64bitWindows() && (DirectoryExists(pathBuffer, L"/Bin64/rc") || !DirectoryExists(pathBuffer, L"/Bin32/rc")))
		{
			swprintf_s(szRcDirectory, L"%s/Bin64/rc", pathBuffer);
		}
		else
		{
			swprintf_s(szRcDirectory, L"%s/Bin32/rc", pathBuffer);
		}
	}

	wchar_t szRegSettingsBuffer[1024];
	smTools.GetEngineSettingsManager()->GetValueByRef("RC_Parameters", SettingsManagerHelpers::CWCharBuffer(szRegSettingsBuffer, sizeof(szRegSettingsBuffer)));

	wRemoteCmdLine.appendAscii("\"");
	wRemoteCmdLine.append(szRcDirectory);
	wRemoteCmdLine.appendAscii("/");
	wRemoteCmdLine.appendAscii(RC_EXECUTABLE);	
	wRemoteCmdLine.appendAscii("\"");

	if (!szFileName)
	{
		wRemoteCmdLine.appendAscii(" /userdialog=0 ");
		wRemoteCmdLine.appendAscii(szAdditionalSettings);
		wRemoteCmdLine.appendAscii(" ");
		wRemoteCmdLine.append(szRegSettingsBuffer);
	}
	else
	{
		wRemoteCmdLine.appendAscii(" \"");
		wRemoteCmdLine.appendAscii(szFileName);
		wRemoteCmdLine.appendAscii("\"");
		wRemoteCmdLine.appendAscii(bNoUserDialog ? " /userdialog=0 " : " /userdialog=1 ");
		wRemoteCmdLine.appendAscii(szAdditionalSettings);
		wRemoteCmdLine.appendAscii(" ");
		wRemoteCmdLine.append(szRegSettingsBuffer);
	}

	// Create a pipe to read the stdout of the RC.
	SECURITY_ATTRIBUTES saAttr;
	HANDLE hChildStdOutRd, hChildStdOutWr;
	HANDLE hChildStdInRd, hChildStdInWr;
	if (listener)
	{
		ZeroMemory(&saAttr, sizeof(saAttr));
		saAttr.bInheritHandle = TRUE;
		saAttr.lpSecurityDescriptor = 0;
		CreatePipe(&hChildStdOutRd, &hChildStdOutWr, &saAttr, 0);
		SetHandleInformation(hChildStdOutRd, HANDLE_FLAG_INHERIT, 0); // Need to do this according to MSDN
		CreatePipe(&hChildStdInRd, &hChildStdInWr, &saAttr, 0);
		SetHandleInformation(hChildStdInWr, HANDLE_FLAG_INHERIT, 0); // Need to do this according to MSDN
	}

	STARTUPINFOW si;
	ZeroMemory(&si, sizeof(si));
	si.cb = sizeof(si);
	si.dwX = 100;
	si.dwY = 100;
	if (listener)
	{
		si.hStdError = hChildStdOutWr;
		si.hStdOutput = hChildStdOutWr;
		si.hStdInput = hChildStdInRd;
		si.dwFlags = STARTF_USEPOSITION | STARTF_USESTDHANDLES;
	}
	else
	{
		si.dwFlags = STARTF_USEPOSITION;
	}

	PROCESS_INFORMATION pi;
	ZeroMemory(&pi, sizeof(pi));

	bool bShowWindow;
	if (bMayShowWindow)
	{
		wchar_t buffer[20];
		smTools.GetEngineSettingsManager()->GetValueByRef("ShowWindow", SettingsManagerHelpers::CWCharBuffer(buffer, sizeof(buffer)));
		bShowWindow = (wcscmp(buffer, L"true") == 0);
	}
	else
	{
		bShowWindow = false;
	}

	const wchar_t* const szStartingDirectory = szWorkingDirectory ? szWorkingDirectory : szRcDirectory;

	if (!CreateProcessW(
		NULL,                   // No module name (use command line).
		const_cast<wchar_t*>(wRemoteCmdLine.c_str()), // Command line.
		NULL,                   // Process handle not inheritable.
		NULL,                   // Thread handle not inheritable.
		TRUE,                   // Set handle inheritance to TRUE.
		bShowWindow ? 0 : CREATE_NO_WINDOW, // creation flags.
		NULL,                   // Use parent's environment block.
		szStartingDirectory,    // Set starting directory.
		&si,                    // Pointer to STARTUPINFO structure.
		&pi))                   // Pointer to PROCESS_INFORMATION structure.
	{
		// The following  code block is commented out instead of being deleted 
		// because it's good to have at hand for a debugging session.







		if (!bSilent)
		{
			ShowMessageBoxRcNotFound(wRemoteCmdLine.c_str(), szStartingDirectory);
		}

		return eRcCallResult_notFound;
	}

	bool bFailedToReadOutput = false;

	if (listener)
	{
		// Close the pipe that writes to the child process, since we don't actually have any input for it.
		CloseHandle(hChildStdInWr);

		// Read all the output from the child process.
		CloseHandle(hChildStdOutWr);
		ResourceCompilerLineHandler lineHandler(listener);
		LineStreamBuffer lineBuffer(&lineHandler, &ResourceCompilerLineHandler::HandleLine);
		for (;;)
		{
			char buffer[2048];
			DWORD bytesRead;
			if (!ReadFile(hChildStdOutRd, buffer, sizeof(buffer), &bytesRead, NULL) || (bytesRead == 0))
			{
				break;
			}
			lineBuffer.HandleText(buffer, bytesRead);
		} 

		bFailedToReadOutput = lineBuffer.IsTruncated();
	}

	// Wait until child process exits.
	WaitForSingleObject(pi.hProcess, INFINITE);

	DWORD exitCode = eRcExitCode_Error;
	if (bFailedToReadOutput || GetExitCodeProcess(pi.hProcess, &exitCode) == 0)
	{
		exitCode = eRcExitCode_Error;
	}

	// Close process and thread handles. 
	CloseHandle(pi.hProcess);
	CloseHandle(pi.hThread);

	switch (exitCode)
	{
	case eRcExitCode_Success:
	case eRcExitCode_UserFixing:
		return eRcCallResult_success;
	case eRcExitCode_Crash:
		return eRcCallResult_crash;
	default:
		return eRcCallResult_error;
	}
}
コード例 #5
0
CResourceCompilerHelper::ERcCallResult CResourceCompilerHelper::CallResourceCompiler(
	const TCHAR* szFileName, 
	const TCHAR* szAdditionalSettings, 
	IResourceCompilerListener* listener, 
	bool bMayShowWindow, 
	bool bUseQuota, 
	CResourceCompilerHelper::ERcExePath rcExePath, 
	bool bSilent,
	bool bNoUserDialog,
	const TCHAR *szWorkingDirectory)
{
	// make command for execution
	TCHAR szRemoteCmdLine[MAX_PATH*3];

	if (!szAdditionalSettings)
	{
		szAdditionalSettings = _T("");
	}

	tstring path;
	switch (rcExePath)
	{
	case eRcExePath_registry:
		path = GetRootPath(true);
		break;
	case eRcExePath_settingsManager:
		path = GetRootPath(false);
		break;
	case eRcExePath_currentFolder:
		path = _T(".");
		break;
	default:
		return eRcCallResult_notFound;
	}

	if (path.empty())
	{
		path = _T(".");
	}

	TCHAR szRemoteDirectory[512];
	_stprintf_s(szRemoteDirectory, _T("%s/Bin32/rc"), path.c_str());

	const TCHAR* const szHideCustom = ((g_pSettingsManager->GetValue<tstring>(_T("HideCustom"))==_T("true")) || bNoUserDialog) 
		? _T("") 
		: _T(" /userdialogcustom=0");

	if (!szFileName)
	{
		_stprintf_s(szRemoteCmdLine, _T("%s/rc.exe /userdialog=0 %s"), szRemoteDirectory, szAdditionalSettings);
	}
	else
	{
		const TCHAR* const szFormat = bUseQuota
			? _T("%s/rc.exe \"%s\" %s %s %s")
			: _T("%s/rc.exe %s %s %s %s");
		const TCHAR* const szUserDialog = bNoUserDialog
			? _T("/userdialog=0")
			: _T("/userdialog=1");
		_stprintf_s(szRemoteCmdLine, szFormat, szRemoteDirectory, szFileName, szUserDialog, szAdditionalSettings, szHideCustom);
	}

	// Create a pipe to read the stdout of the RC.
	SECURITY_ATTRIBUTES saAttr;
	std::memset(&saAttr, 0, sizeof(saAttr));
	saAttr.bInheritHandle = TRUE;
	saAttr.lpSecurityDescriptor = 0;
	HANDLE hChildStdOutRd, hChildStdOutWr;
	CreatePipe(&hChildStdOutRd, &hChildStdOutWr, &saAttr, 0);
	SetHandleInformation(hChildStdOutRd, HANDLE_FLAG_INHERIT, 0); // Need to do this according to MSDN
	HANDLE hChildStdInRd, hChildStdInWr;
	CreatePipe(&hChildStdInRd, &hChildStdInWr, &saAttr, 0);
	SetHandleInformation(hChildStdInWr, HANDLE_FLAG_INHERIT, 0); // Need to do this according to MSDN

	STARTUPINFO si;
	ZeroMemory(&si, sizeof(si));
	si.cb = sizeof(si);
	si.dwX = 100;
	si.dwY = 100;
	si.hStdError = hChildStdOutWr;
	si.hStdOutput = hChildStdOutWr;
	si.hStdInput = hChildStdInRd;
	si.dwFlags = STARTF_USEPOSITION | STARTF_USESTDHANDLES;

	PROCESS_INFORMATION pi;
	ZeroMemory(&pi, sizeof(pi));

	if (!CreateProcess(
		NULL,                   // No module name (use command line).
		szRemoteCmdLine,        // Command line.
		NULL,                   // Process handle not inheritable.
		NULL,                   // Thread handle not inheritable.
		TRUE,                   // Set handle inheritance to TRUE.
		bMayShowWindow && (g_pSettingsManager->GetValue<tstring>(_T("ShowWindow"))==_T("true"))?0:CREATE_NO_WINDOW, // creation flags.
		NULL,                   // Use parent's environment block.
		szWorkingDirectory?szWorkingDirectory:szRemoteDirectory,  // Set starting directory.
		&si,                    // Pointer to STARTUPINFO structure.
		&pi ))                  // Pointer to PROCESS_INFORMATION structure.
	{
		TCHAR szMessage[65535] = _T("");
		FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), 0, szMessage, 65354, NULL);
		GetCurrentDirectory(65534, szMessage);
		if (!bSilent)
		{
			MessageBox(0,_T("ResourceCompiler was not found.\n\nPlease verify CryENGINE RootPath."),_T("Error"),MB_ICONERROR|MB_OK);
		}
		return eRcCallResult_notFound;
	}

	// Close the pipe that writes to the child process, since we don't actually have any input for it.
	CloseHandle(hChildStdInWr);

	// Read all the output from the child process.
	CloseHandle(hChildStdOutWr);
	ResourceCompilerLineHandler lineHandler(listener);
	LineStreamBuffer lineBuffer(&lineHandler, &ResourceCompilerLineHandler::HandleLine);
	for (;;)
	{
		char buffer[2048];
		DWORD bytesRead;
		if (!ReadFile(hChildStdOutRd, buffer, sizeof(buffer), &bytesRead, NULL) || (bytesRead == 0))
		{
			break;
		}
		lineBuffer.HandleText(buffer, bytesRead);
	} 

	// Wait until child process exits.
	WaitForSingleObject(pi.hProcess, INFINITE);

	bool ok = true;
	{
		DWORD exitCode = 1;
		if ((GetExitCodeProcess(pi.hProcess, &exitCode) == 0) || (exitCode != 0))
		{
			ok = false;
		}	
	}

	// Close process and thread handles. 
	CloseHandle(pi.hProcess);
	CloseHandle(pi.hThread);

	return ok ? eRcCallResult_success : eRcCallResult_error;
}
コード例 #6
0
static nsresult __AddNewMessageToFolder(nsIMsgFolder * dstFolder,
                                        ews_msg_item * msg_item,
                                        nsIMsgDBHdr* messageToReplace,
                                        nsIFile * pSrc,
                                        nsIMsgDBHdr ** _msgHdr) {
    nsCOMPtr<nsIOutputStream> outputStream;
    nsCOMPtr<nsIMsgPluggableStore> msgStore;
    nsresult rv;
    
    nsCOMPtr<nsIMsgDatabase> destDB;
    rv = dstFolder->GetMsgDatabase(getter_AddRefs(destDB));
    
    rv = dstFolder->GetMsgStore(getter_AddRefs(msgStore));
    NS_ENSURE_SUCCESS(rv, rv);
    
    nsCOMPtr<nsIMsgDBHdr> msgHdr;
    bool reusable;

    rv = msgStore->GetNewMsgOutputStream(dstFolder,
                                         getter_AddRefs(msgHdr),
                                         &reusable,
                                         getter_AddRefs(outputStream));
    NS_ENSURE_SUCCESS(rv, rv);

    nsCOMPtr <nsIInputStream> pInputStream;
    rv = NS_NewLocalFileInputStream(getter_AddRefs(pInputStream), pSrc);
    NS_ENSURE_SUCCESS(rv, rv);

    nsAutoPtr<nsLineBuffer<char> > lineBuffer(new nsLineBuffer<char>);
    NS_ENSURE_TRUE(lineBuffer, NS_ERROR_OUT_OF_MEMORY);

    nsCOMPtr <nsIMsgParseMailMsgState> msgParser = do_CreateInstance(NS_PARSEMAILMSGSTATE_CONTRACTID, &rv);
    msgParser->SetMailDB(destDB);
    msgParser->SetState(nsIMsgParseMailMsgState::ParseHeadersState);
    msgParser->SetNewMsgHdr(msgHdr);
    
    nsCString line;
    bool more = false;
    uint32_t write_count = 0;
    uint32_t msg_size = 0;

    //Need to write Local message header
    //From
    nsAutoCString result;
    time_t now = time ((time_t*) 0);
    char *ct = ctime(&now);
    ct[24] = 0;
    result = "From - ";
    result += ct;
    result += MSG_LINEBREAK;

    outputStream->Write(result.get(),
                        result.Length(),
                        &write_count);
    msg_size += write_count;
    
    //Status
    NS_NAMED_LITERAL_CSTRING(MozillaStatus,
                             "X-Mozilla-Status: 0001" MSG_LINEBREAK);
    outputStream->Write(MozillaStatus.get(),
                        MozillaStatus.Length(),
                        &write_count);
    msg_size += write_count;

    //Status2
    NS_NAMED_LITERAL_CSTRING(MozillaStatus2,
                             "X-Mozilla-Status2: 00000000" MSG_LINEBREAK);
    outputStream->Write(MozillaStatus2.get(),
                        MozillaStatus2.Length(),
                        &write_count);
    msg_size += write_count;

    do {
        rv = NS_ReadLine(pInputStream.get(),
                         lineBuffer.get(),
                         line,
                         &more);
        if (NS_FAILED(rv))
            break;

        nsCString newLine(line);
        newLine.AppendLiteral("\x0D\x0A");
        msgParser->ParseAFolderLine(newLine.get(), newLine.Length());

        //Need to replace Date: Header with received time
        if (!strncmp(line.get(), "Date:", strlen("Date:")) &&
            msg_item &&
            msg_item->item.received_time > 0) {
            char buf[256] = {0};
            size_t len = strftime(buf, 255, "%a, %d %b %Y %H:%M:%S %z", localtime(&msg_item->item.received_time));

            outputStream->Write("Date: ", strlen("Date: "), &write_count);
            msg_size += write_count;
            outputStream->Write(buf, len, &write_count);
            msg_size += write_count;
            outputStream->Write("\x0D\x0A", 2, &write_count);
            msg_size += write_count;
        } else if (!strncmp(line.get(), "Subject:", strlen("Subject:"))) {
            const char * key = line.get() + strlen("Subject:");
            uint32_t l = strlen(key);
            
            nsCString newSubject("Subject: ");

            /* strip "Re: " */
            nsCString modifiedSubject;
            if (mailews::NS_MsgStripRE((const char **) &key,
                              &l,
                              modifiedSubject)) {
                nsString utf16LocalizedRe;
                mailews::NS_GetLocalizedUnicharPreferenceWithDefault(nullptr,
                                                            "mailnews.localizedRe",
                                                            EmptyString(),
                                                            utf16LocalizedRe);
                NS_ConvertUTF16toUTF8 localizedRe(utf16LocalizedRe);

                if (localizedRe.IsEmpty()) {
                    newSubject.Append("Re");
                } else {
                    newSubject.Append(localizedRe);
                }
                newSubject.Append(": ");
            }

            if (!modifiedSubject.IsEmpty()) {
                newSubject.Append(modifiedSubject);
            } else {
                newSubject.AppendLiteral(key);
            }
            outputStream->Write(newSubject.get(), newSubject.Length(), &write_count);
            msg_size += write_count;
            outputStream->Write("\x0D\x0A", 2, &write_count);
            msg_size += write_count;
        } else {
            outputStream->Write(line.get(), line.Length(), &write_count);
            msg_size += write_count;
            outputStream->Write("\x0D\x0A", 2, &write_count);
            msg_size += write_count;
        }
    } while(more);

    pInputStream->Close();

    msgParser->FinishHeader();

    msgParser->GetNewMsgHdr(getter_AddRefs(msgHdr));
    
    if (NS_SUCCEEDED(rv)) {
        if (msg_item)
            UpdateMsgHdr(msg_item, msgHdr);
        else if (messageToReplace) {
            CopyPropertiesToMsgHdr(msgHdr, messageToReplace, true);
        }

        msgHdr->SetMessageSize(msg_size);
        
        destDB->AddNewHdrToDB(msgHdr, true /* notify */);
        msgStore->FinishNewMessage(outputStream, msgHdr);
        dstFolder->UpdateSummaryTotals(true);
    }
    else {
        msgStore->DiscardNewMessage(outputStream, msgHdr);
        IMPORT_LOG0( "*** Error importing message\n");
    }

    if (!reusable)
        outputStream->Close();

    destDB->Commit(nsMsgDBCommitType::kLargeCommit);

    if (_msgHdr)
        msgHdr.swap(*_msgHdr);
    return rv;
}
コード例 #7
0
ファイル: ossimCodecFactory.cpp プロジェクト: Dukeke/ossim
bool ossimCodecFactory::decodeJpeg( const std::vector<ossim_uint8>& in,
                                    ossimRefPtr<ossimImageData>& out ) const
{
   bool result = false;

   // Note: This is public and can be called directly; hence, the signature check
   // Check for jpeg signature:
   if ( in.size() > 3 )
   {
      if ( (in[0] == 0xff) &&
           (in[1] == 0xd8) &&
           (in[2] == 0xff) &&
           (in[3] == 0xe0) )
      {
         /* This struct contains the JPEG decompression parameters and pointers
          * to working space (which is allocated as needed by the JPEG library).
          */
         jpeg_decompress_struct cinfo;
         
         /* We use our private extension JPEG error handler.
          * Note that this struct must live as long as the main JPEG parameter
          * struct, to avoid dangling-pointer problems.
          */
         ossimJpegErrorMgr jerr;
         
         /* Step 1: allocate and initialize JPEG decompression object */
         
         /* We set up the normal JPEG error routines, then override error_exit. */
         cinfo.err = jpeg_std_error(&jerr.pub);
         
         jerr.pub.error_exit = ossimJpegErrorExit;
         
         /* Establish the setjmp return context for my_error_exit to use. */
         if (setjmp(jerr.setjmp_buffer) == 0)
         {
            result = true;
            
            /* Now we can initialize the JPEG decompression object. */
            jpeg_CreateDecompress(&cinfo, JPEG_LIB_VERSION, sizeof(cinfo));
            
            //---
            // Step 2: specify data source.  In this case we will uncompress from
            // memory so we will use "ossimJpegMemorySrc" in place of " jpeg_stdio_src".
            //---
            ossimJpegMemorySrc ( &cinfo,
                                 &(in.front()),
                                 (size_t)(in.size()) );
            
            /* Step 3: read file parameters with jpeg_read_header() */
            jpeg_read_header(&cinfo, TRUE);
            
            /* Step 4: set parameters for decompression */
            
            /* In this example, we don't need to change any of the defaults set by
             * jpeg_read_header(), so we do nothing here.
             */
            
            /* Step 5: Start decompressor */
            jpeg_start_decompress(&cinfo);
            
#if 0       /* Please leave for debug. (drb) */
            if ( traceDebug() )
            {
               ossimNotify(ossimNotifyLevel_DEBUG)
                  << "jpeg cinfo.output_width:  " << cinfo.output_width
                  << "\njpeg cinfo.output_height: " << cinfo.output_height
                  << "\n";
            }
#endif
            
            const ossim_uint32 SAMPLES    = cinfo.output_width;
            const ossim_uint32 LINES      = cinfo.output_height;
            const ossim_uint32 BANDS      = cinfo.output_components;

            if ( out.valid() )
            {
               // This will resize tile if not correct.
               out->setImageRectangleAndBands(
                  ossimIrect(0,0,(ossim_int32)SAMPLES-1,(ossim_int32)LINES-1), BANDS );
            }
            else
            {
               out = new ossimU8ImageData( 0, BANDS, SAMPLES, LINES );
               out->initialize();
            }
            
            // Get pointers to the cache tile buffers.
            std::vector<ossim_uint8*> destinationBuffer(BANDS);
            for (ossim_uint32 band = 0; band < BANDS; ++band)
            {
               destinationBuffer[band] = out->getUcharBuf(band);
            }
            
            std::vector<ossim_uint8> lineBuffer(SAMPLES * cinfo.output_components);
            JSAMPROW jbuf[1];
            jbuf[0] = (JSAMPROW) &(lineBuffer.front());
            
            while (cinfo.output_scanline < LINES)
            {
               // Read a line from the jpeg file.
               jpeg_read_scanlines(&cinfo, jbuf, 1);
               
               //---
               // Copy the line which if band interleaved by pixel the the band
               // separate buffers.
               //---
               ossim_uint32 index = 0;
               for (ossim_uint32 sample = 0; sample < SAMPLES; ++sample)         
               {
                  for (ossim_uint32 band = 0; band < BANDS; ++band)
                  {
                     destinationBuffer[band][sample] = lineBuffer[index];
                     ++index;
                  }
               }
               
               for (ossim_uint32 band = 0; band < BANDS; ++band)
               {
                  destinationBuffer[band] += SAMPLES;
               }
            }

            // Set the tile status:
            out->validate();
   
            // clean up...
            
            jpeg_finish_decompress(&cinfo);
            
         } // Matches: if (setjmp(jerr.setjmp_buffer) == 0)

         jpeg_destroy_decompress(&cinfo);
         
      } // Matches: if ( (in[0] == 0xff) ... )
      
   } // Matches: if ( in.size() > 3 )
   
   return result;
}
コード例 #8
0
ファイル: add_noise.cpp プロジェクト: shadedev/pluginsdk
///ja @breif 「ノイズを追加する」イメージへの描画処理 
///ja \relates add_noise_stream
void draw_noise(sxsdk::image_interface* image, const add_noise_stream& settings, const sx::rectangle_class& bounds, unsigned int seed, sxsdk::rendering_context_interface *rendering_context = 0)
{
	boost::scoped_array<sxsdk::vec4> lineBuffer(new sxsdk::vec4[bounds.max.x-bounds.min.x]);

	//initializing random seed
	srand(seed);
	const float rand_max1 = 1.0f/(RAND_MAX + 1.0f);	// RAND_MAX = 32767 (Macintosh) , 2147483647 (Linux)

	int weight_add = 1;
	int weight_mul = 0;
	if(settings.apply_to == add_noise_stream::Background_only) {
		weight_add = 1;
		weight_mul = -1;
	}
	else if(settings.apply_to == add_noise_stream::Foreground_only)	{
		weight_add = 0;
		weight_mul = 1;
	}

	if(settings.z_depth_effect <= 0.0f || !image->has_z()) {
		for (int line = bounds.min.y ; line < bounds.max.y ; ++line) {
			image->get_pixels_rgba_float(bounds.min.x, line, (bounds.max.x-bounds.min.x), 1, (sxsdk::rgba_class*)lineBuffer.get()); 
			for (int i = 0; i < (bounds.max.x-bounds.min.x) ; ++i) {
				const float weight = settings.opacity * (weight_add + weight_mul * lineBuffer[i].w);

				if(weight <= 0.0f) continue;
				const float value = rand() * rand_max1;
				const sxsdk::vec4 noise_rand = settings.color_noise ? sxsdk::vec4(rand(), rand(), rand(), rand()) * rand_max1 : sxsdk::vec4(value, value, value, value);
				lineBuffer[i] = lineBuffer[i] * (1.0f - weight) + sxsdk::mul(noise_rand, settings.color) * weight;
			}
			image->set_pixels_rgba_float(bounds.min.x, line, (bounds.max.x-bounds.min.x), 1, (sxsdk::rgba_class*)lineBuffer.get()); 
			if (rendering_context) rendering_context->yield();
		}
	}
	else {
		boost::scoped_array<float> zlineBuffer(new float[(bounds.max.x-bounds.min.x)]);
		const std::pair<float, float> z_range = get_zdepth_range(image, bounds, zlineBuffer.get());
		const float extract_ratio = 1.0f / (z_range.second - z_range.first);

		const int revert_z_mul = ((settings.revert_z_depth) ? -1 : 1);
		const int revert_z_add = ((settings.revert_z_depth) ? 1 : 0);

		for (int line = bounds.min.y ; line < bounds.max.y ; ++line) {
			image->get_pixels_rgba_float(bounds.min.x, line, (bounds.max.x-bounds.min.x), 1, (sxsdk::rgba_class*)lineBuffer.get()); 
			image->get_zs(bounds.min.x, line, (bounds.max.x-bounds.min.x), 1, zlineBuffer.get());

			for (int i = 0; i < (bounds.max.x-bounds.min.x) ; ++i) {
				float weight = settings.opacity * (weight_add + weight_mul * lineBuffer[i].w);
				const float z = (zlineBuffer[i] - z_range.first) * extract_ratio;
				weight *= 1.0f - (revert_z_add + revert_z_mul * z) * settings.z_depth_effect;

				if(weight <= 0.0f) continue;

				const float value = rand() * rand_max1;
				const sxsdk::vec4 noise_rand = settings.color_noise ? sxsdk::vec4(rand(), rand(), rand(), rand()) * rand_max1 : sxsdk::vec4(value, value, value, value);
				lineBuffer[i] = lineBuffer[i] * (1.0f - weight) + sxsdk::mul(noise_rand, settings.color) * weight;
			}
			image->set_pixels_rgba_float(bounds.min.x, line, (bounds.max.x-bounds.min.x), 1, (sxsdk::rgba_class*)lineBuffer.get()); 
			if (rendering_context) rendering_context->yield();
		}
	}
}
コード例 #9
0
CResourceCompilerHelper::ERcCallResult CResourceCompilerHelper::CallResourceCompiler(
	const char* szFileName, 
	const char* szAdditionalSettings, 
	IResourceCompilerListener* listener, 
	bool bMayShowWindow, 
	CResourceCompilerHelper::ERcExePath rcExePath, 
	bool bSilent,
	bool bNoUserDialog,
	const wchar_t* szWorkingDirectory,
	const wchar_t* szRootPath)
{
	// make command for execution
	SettingsManagerHelpers::CFixedString<wchar_t, MAX_PATH*3> wRemoteCmdLine;

	if (!szAdditionalSettings)
	{
		szAdditionalSettings = "";
	}

	wchar_t szRemoteDirectory[512];
	{
		wchar_t pathBuffer[512];
		switch (rcExePath)
		{
		case eRcExePath_registry:
			GetRootPathUtf16(true, SettingsManagerHelpers::CWCharBuffer(pathBuffer, sizeof(pathBuffer)));
			break;
		case eRcExePath_settingsManager:
			GetRootPathUtf16(false, SettingsManagerHelpers::CWCharBuffer(pathBuffer, sizeof(pathBuffer)));
			break;
		case eRcExePath_currentFolder:
			wcscpy(pathBuffer, L".");
			break;
		case eRcExePath_customPath:
			wcscpy(pathBuffer, szRootPath);
			break;
		default:
			return eRcCallResult_notFound;
		}

		if (!pathBuffer[0])
		{
			wcscpy(pathBuffer, L".");
		}

		swprintf_s(szRemoteDirectory, L"%s/Bin32/rc", pathBuffer);
	}

	if (!szFileName)
	{
		wRemoteCmdLine.appendAscii("\"");
		wRemoteCmdLine.append(szRemoteDirectory);
		wRemoteCmdLine.appendAscii("/rc.exe\" /userdialog=0 ");
		wRemoteCmdLine.appendAscii(szAdditionalSettings);
	}
	else
	{
		wRemoteCmdLine.appendAscii("\"");
		wRemoteCmdLine.append(szRemoteDirectory);
		wRemoteCmdLine.appendAscii("/rc.exe\" \"");
		wRemoteCmdLine.appendAscii(szFileName);
		wRemoteCmdLine.appendAscii("\" ");
		wRemoteCmdLine.appendAscii(bNoUserDialog ? "/userdialog=0 " : "/userdialog=1 ");
		wRemoteCmdLine.appendAscii(szAdditionalSettings);
	}

	// Create a pipe to read the stdout of the RC.
	SECURITY_ATTRIBUTES saAttr;
	::memset(&saAttr, 0, sizeof(saAttr));
	saAttr.bInheritHandle = TRUE;
	saAttr.lpSecurityDescriptor = 0;
	HANDLE hChildStdOutRd, hChildStdOutWr;
	CreatePipe(&hChildStdOutRd, &hChildStdOutWr, &saAttr, 0);
	SetHandleInformation(hChildStdOutRd, HANDLE_FLAG_INHERIT, 0); // Need to do this according to MSDN
	HANDLE hChildStdInRd, hChildStdInWr;
	CreatePipe(&hChildStdInRd, &hChildStdInWr, &saAttr, 0);
	SetHandleInformation(hChildStdInWr, HANDLE_FLAG_INHERIT, 0); // Need to do this according to MSDN

	STARTUPINFOW si;
	ZeroMemory(&si, sizeof(si));
	si.cb = sizeof(si);
	si.dwX = 100;
	si.dwY = 100;
	si.hStdError = hChildStdOutWr;
	si.hStdOutput = hChildStdOutWr;
	si.hStdInput = hChildStdInRd;
	si.dwFlags = STARTF_USEPOSITION | STARTF_USESTDHANDLES;

	PROCESS_INFORMATION pi;
	ZeroMemory(&pi, sizeof(pi));

	bool bShowWindow = false;
	{
		wchar_t buffer[20];
		g_pSettingsManager->GetValueByRef("ShowWindow", SettingsManagerHelpers::CWCharBuffer(buffer, sizeof(buffer)));
		bShowWindow = (wcscmp(buffer, L"true") == 0);
	}

	if (!CreateProcessW(
		NULL,                   // No module name (use command line).
		const_cast<wchar_t*>(wRemoteCmdLine.c_str()), // Command line.
		NULL,                   // Process handle not inheritable.
		NULL,                   // Thread handle not inheritable.
		TRUE,                   // Set handle inheritance to TRUE.
		(bMayShowWindow && bShowWindow) ? 0  : CREATE_NO_WINDOW, // creation flags.
		NULL,                   // Use parent's environment block.
		szWorkingDirectory?szWorkingDirectory:szRemoteDirectory,  // Set starting directory.
		&si,                    // Pointer to STARTUPINFO structure.
		&pi ))                  // Pointer to PROCESS_INFORMATION structure.
	{
		/*
		This code block is commented out instead of being deleted because it's
		good to have at hand for a debugging session.

		const size_t charsInMessageBuffer = 32768;   // msdn about FormatMessage(): "The output buffer cannot be larger than 64K bytes."
		wchar_t szMessageBuffer[charsInMessageBuffer] = L"";   
		FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), 0, szMessageBuffer, charsInMessageBuffer, NULL);
		GetCurrentDirectoryW(charsInMessageBuffer, szMessageBuffer);
		*/

		if (!bSilent)
		{
			MessageBoxA(0, "ResourceCompiler was not found.\n\nPlease verify CryENGINE RootPath.", "Error", MB_ICONERROR|MB_OK);
		}

		return eRcCallResult_notFound;
	}

	// Close the pipe that writes to the child process, since we don't actually have any input for it.
	CloseHandle(hChildStdInWr);

	// Read all the output from the child process.
	CloseHandle(hChildStdOutWr);
	ResourceCompilerLineHandler lineHandler(listener);
	LineStreamBuffer lineBuffer(&lineHandler, &ResourceCompilerLineHandler::HandleLine);
	for (;;)
	{
		char buffer[2048];
		DWORD bytesRead;
		if (!ReadFile(hChildStdOutRd, buffer, sizeof(buffer), &bytesRead, NULL) || (bytesRead == 0))
		{
			break;
		}
		lineBuffer.HandleText(buffer, bytesRead);
	} 

	// Wait until child process exits.
	WaitForSingleObject(pi.hProcess, INFINITE);

	bool ok = true;
	DWORD exitCode = 1;
	{
		if ((GetExitCodeProcess(pi.hProcess, &exitCode) == 0) || (exitCode != 0))
		{
			ok = false;
		}	
	}

	// Close process and thread handles. 
	CloseHandle(pi.hProcess);
	CloseHandle(pi.hThread);

	if (exitCode == eRcExitCode_Crash)
	{
		return eRcCallResult_crash;
	}

	if (lineBuffer.IsTruncated())
	{
		return eRcCallResult_error;
	}

	return ok ? eRcCallResult_success : eRcCallResult_error;
}