Skip to content

Commit

Permalink
Fixed (?) bug where notepad windows might load garbage
Browse files Browse the repository at this point in the history
  • Loading branch information
nickgammon committed Sep 26, 2010
1 parent 0665664 commit 24e3b52
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 3 deletions.
2 changes: 1 addition & 1 deletion TextDocument.cpp
Expand Up @@ -115,7 +115,7 @@ void CTextDocument::Dump(CDumpContext& dc) const
void CTextDocument::Serialize(CArchive& ar)
{
// CEditView contains an edit control which handles all serialization
((CEditView*)m_viewList.GetHead())->SerializeRaw(ar);
((CTextView*)m_viewList.GetHead())->SerializeRaw(ar);

if (ar.IsLoading ())
CreateMonitoringThread (ar.GetFile ()->GetFilePath ());
Expand Down
37 changes: 35 additions & 2 deletions TextView.cpp
Expand Up @@ -238,9 +238,42 @@ void CTextView::SerializeRaw(CArchive& ar)
{
CFile* pFile = ar.GetFile();
ASSERT(pFile->GetPosition() == 0);
DWORD nFileSize = pFile->GetLength();
DWORD nLen = pFile->GetLength();
// ReadFromArchive takes the number of characters as argument
ReadFromArchive(ar, (UINT)nFileSize/sizeof(TCHAR));

// REPLACING: ReadFromArchive(ar, (UINT)nFileSize/sizeof(TCHAR));

// with this (we got garbage at times):

LPVOID hText = LocalAlloc(LMEM_MOVEABLE, (nLen+1)*sizeof(TCHAR));
if (hText == NULL)
AfxThrowMemoryException();

LPTSTR lpszText = (LPTSTR)LocalLock(hText);
ASSERT(lpszText != NULL);
if (ar.Read(lpszText, nLen*sizeof(TCHAR)) != nLen*sizeof(TCHAR))
{
LocalUnlock(hText);
LocalFree(hText);
AfxThrowArchiveException(CArchiveException::endOfFile);
}
// Replace the editing edit buffer with the newly loaded data
lpszText[nLen] = '\0';

// set the text with SetWindowText, then free
BOOL bResult = ::SetWindowText(m_hWnd, lpszText);
LocalUnlock(hText);
LocalFree(hText);

// make sure that SetWindowText was successful
if (!bResult || ::GetWindowTextLength(m_hWnd) < (int)nLen)
AfxThrowMemoryException();

// remove old shadow buffer
delete[] m_pShadowBuffer;
m_pShadowBuffer = NULL;
m_nShadowSize = 0;

}
ASSERT_VALID(this);
} /* end of CTextView::SerializeRaw */
Expand Down

0 comments on commit 24e3b52

Please sign in to comment.