home *** CD-ROM | disk | FTP | other *** search
/ Supercompiler 1997 / SUPERCOMPILER97.iso / MS_VC.50 / VC / MFC / SRC / VIEWRICH.CPP < prev    next >
Encoding:
C/C++ Source or Header  |  1996-12-12  |  56.5 KB  |  2,151 lines

  1. // This is a part of the Microsoft Foundation Classes C++ library.
  2. // Copyright (C) 1992-1997 Microsoft Corporation
  3. // All rights reserved.
  4. //
  5. // This source code is only intended as a supplement to the
  6. // Microsoft Foundation Classes Reference and related
  7. // electronic documentation provided with the library.
  8. // See these sources for detailed information regarding the
  9. // Microsoft Foundation Classes product.
  10.  
  11. #include "stdafx.h"
  12.  
  13. #ifdef AFX_CORE4_SEG
  14. #pragma code_seg(AFX_CORE4_SEG)
  15. #endif
  16.  
  17. #ifdef _DEBUG
  18. #undef THIS_FILE
  19. static char THIS_FILE[] = __FILE__;
  20. #endif
  21.  
  22. #define new DEBUG_NEW
  23.  
  24. /////////////////////////////////////////////////////////////////////////////
  25. // CReObject
  26.  
  27. class CReObject : public _reobject
  28. {
  29. public:
  30.     CReObject();
  31.     CReObject(CRichEditCntrItem* pItem);
  32.     ~CReObject();
  33. };
  34.  
  35. CReObject::CReObject()
  36. {
  37.     cbStruct = sizeof(REOBJECT);
  38.     poleobj = NULL;
  39.     pstg = NULL;
  40.     polesite = NULL;
  41. }
  42.  
  43. CReObject::CReObject(CRichEditCntrItem* pItem)
  44. {
  45.     ASSERT(pItem != NULL);
  46.     cbStruct = sizeof(REOBJECT);
  47.  
  48.     pItem->GetClassID(&clsid);
  49.     poleobj = pItem->m_lpObject;
  50.     pstg = pItem->m_lpStorage;
  51.     polesite = pItem->m_lpClientSite;
  52.     ASSERT(poleobj != NULL);
  53.     ASSERT(pstg != NULL);
  54.     ASSERT(polesite != NULL);
  55.     poleobj->AddRef();
  56.     pstg->AddRef();
  57.     polesite->AddRef();
  58.  
  59.     sizel.cx = sizel.cy = 0; // let richedit determine initial size
  60.     dvaspect = pItem->GetDrawAspect();
  61.     dwFlags = REO_RESIZABLE;
  62.     dwUser = 0;
  63. }
  64.  
  65. CReObject::~CReObject()
  66. {
  67.     if (poleobj != NULL)
  68.         poleobj->Release();
  69.     if (pstg != NULL)
  70.         pstg->Release();
  71.     if (polesite != NULL)
  72.         polesite->Release();
  73. }
  74.  
  75. /////////////////////////////////////////////////////////////////////////////
  76. // CRichEditView
  77.  
  78. static const UINT nMsgFindReplace = ::RegisterWindowMessage(FINDMSGSTRING);
  79.  
  80. BEGIN_MESSAGE_MAP(CRichEditView, CCtrlView)
  81.     //{{AFX_MSG_MAP(CRichEditView)
  82.     ON_UPDATE_COMMAND_UI(ID_EDIT_CUT, OnUpdateNeedSel)
  83.     ON_UPDATE_COMMAND_UI(ID_EDIT_PASTE, OnUpdateNeedClip)
  84.     ON_UPDATE_COMMAND_UI(ID_EDIT_FIND, OnUpdateNeedText)
  85.     ON_UPDATE_COMMAND_UI(ID_EDIT_REPEAT, OnUpdateNeedFind)
  86.     ON_UPDATE_COMMAND_UI(ID_EDIT_UNDO, OnUpdateEditUndo)
  87.     ON_UPDATE_COMMAND_UI(ID_EDIT_PASTE_SPECIAL, OnUpdateEditPasteSpecial)
  88.     ON_UPDATE_COMMAND_UI(ID_OLE_EDIT_PROPERTIES, OnUpdateEditProperties)
  89.     ON_UPDATE_COMMAND_UI(ID_EDIT_COPY, OnUpdateNeedSel)
  90.     ON_UPDATE_COMMAND_UI(ID_EDIT_CLEAR, OnUpdateNeedSel)
  91.     ON_UPDATE_COMMAND_UI(ID_EDIT_SELECT_ALL, OnUpdateNeedText)
  92.     ON_UPDATE_COMMAND_UI(ID_EDIT_REPLACE, OnUpdateNeedText)
  93.     ON_COMMAND(ID_EDIT_CUT, OnEditCut)
  94.     ON_COMMAND(ID_EDIT_COPY, OnEditCopy)
  95.     ON_COMMAND(ID_EDIT_PASTE, OnEditPaste)
  96.     ON_COMMAND(ID_EDIT_CLEAR, OnEditClear)
  97.     ON_COMMAND(ID_EDIT_UNDO, OnEditUndo)
  98.     ON_COMMAND(ID_EDIT_SELECT_ALL, OnEditSelectAll)
  99.     ON_COMMAND(ID_EDIT_FIND, OnEditFind)
  100.     ON_COMMAND(ID_EDIT_REPLACE, OnEditReplace)
  101.     ON_COMMAND(ID_EDIT_REPEAT, OnEditRepeat)
  102.     ON_COMMAND(ID_EDIT_PASTE_SPECIAL, OnEditPasteSpecial)
  103.     ON_COMMAND(ID_OLE_EDIT_PROPERTIES, OnEditProperties)
  104.     ON_COMMAND(ID_OLE_INSERT_NEW, OnInsertObject)
  105.     ON_COMMAND(ID_FORMAT_FONT, OnFormatFont)
  106.     ON_WM_SIZE()
  107.     ON_WM_CREATE()
  108.     ON_WM_DESTROY()
  109.     //}}AFX_MSG_MAP
  110.     ON_NOTIFY_REFLECT(EN_SELCHANGE, OnSelChange)
  111.     ON_REGISTERED_MESSAGE(nMsgFindReplace, OnFindReplaceCmd)
  112. END_MESSAGE_MAP()
  113.  
  114. // richedit buffer limit -- let's set it at 16M
  115. AFX_DATADEF ULONG CRichEditView::lMaxSize = 0xffffff;
  116.  
  117. /////////////////////////////////////////////////////////////////////////////
  118. // CRichEditView construction/destruction
  119.  
  120. CRichEditView::CRichEditView() : CCtrlView(_T("RICHEDIT"), AFX_WS_DEFAULT_VIEW |
  121.     WS_HSCROLL | WS_VSCROLL | ES_AUTOHSCROLL | ES_AUTOVSCROLL |
  122.     ES_MULTILINE | ES_NOHIDESEL | ES_SAVESEL | ES_SELECTIONBAR)
  123. {
  124.     m_bSyncCharFormat = m_bSyncParaFormat = TRUE;
  125.     m_lpRichEditOle = NULL;
  126.     m_nBulletIndent = 720; // 1/2 inch
  127.     m_nWordWrap = WrapToWindow;
  128.     m_nPasteType = 0;
  129.     SetPaperSize(CSize(8*1440+720, 11*1440));
  130.     SetMargins(CRect(0,0,0,0));
  131.     m_charformat.cbSize = sizeof(CHARFORMAT);
  132.     m_paraformat.cbSize = sizeof(PARAFORMAT);
  133. }
  134.  
  135. BOOL CRichEditView::PreCreateWindow(CREATESTRUCT& cs)
  136. {
  137.     if (!AfxInitRichEdit())
  138.         return FALSE;
  139.     CCtrlView::PreCreateWindow(cs);
  140.     cs.lpszName = &afxChNil;
  141.  
  142.     cs.cx = cs.cy = 100; // necessary to avoid bug with ES_SELECTIONBAR and zero for cx and cy
  143.     cs.style |= WS_CLIPSIBLINGS;
  144.  
  145.     return TRUE;
  146. }
  147.  
  148. int CRichEditView::OnCreate(LPCREATESTRUCT lpcs)
  149. {
  150.     if (CCtrlView::OnCreate(lpcs) != 0)
  151.         return -1;
  152.     GetRichEditCtrl().LimitText(lMaxSize);
  153.     GetRichEditCtrl().SetEventMask(ENM_SELCHANGE | ENM_CHANGE | ENM_SCROLL);
  154.     VERIFY(GetRichEditCtrl().SetOLECallback(&m_xRichEditOleCallback));
  155.     m_lpRichEditOle = GetRichEditCtrl().GetIRichEditOle();
  156.     DragAcceptFiles();
  157.     GetRichEditCtrl().SetOptions(ECOOP_OR, ECO_AUTOWORDSELECTION);
  158.     WrapChanged();
  159.     ASSERT(m_lpRichEditOle != NULL);
  160.     return 0;
  161. }
  162.  
  163. void CRichEditView::OnInitialUpdate()
  164. {
  165.     CCtrlView::OnInitialUpdate();
  166.     m_bSyncCharFormat = m_bSyncParaFormat = TRUE;
  167. }
  168.  
  169. /////////////////////////////////////////////////////////////////////////////
  170. // CRichEditView document like functions
  171.  
  172. void CRichEditView::DeleteContents()
  173. {
  174.     ASSERT_VALID(this);
  175.     ASSERT(m_hWnd != NULL);
  176.     SetWindowText(_T(""));
  177.     GetRichEditCtrl().EmptyUndoBuffer();
  178.     m_bSyncCharFormat = m_bSyncParaFormat = TRUE;
  179.     ASSERT_VALID(this);
  180. }
  181.  
  182. void CRichEditView::WrapChanged()
  183. {
  184.     CWaitCursor wait;
  185.     CRichEditCtrl& ctrl = GetRichEditCtrl();
  186.     if (m_nWordWrap == WrapNone)
  187.         ctrl.SetTargetDevice(NULL, 1);
  188.     else if (m_nWordWrap == WrapToWindow)
  189.         ctrl.SetTargetDevice(NULL, 0);
  190.     else if (m_nWordWrap == WrapToTargetDevice) // wrap to ruler
  191.     {
  192.         AfxGetApp()->CreatePrinterDC(m_dcTarget);
  193.         if (m_dcTarget.m_hDC == NULL)
  194.             m_dcTarget.CreateDC(_T("DISPLAY"), NULL, NULL, NULL);
  195.         ctrl.SetTargetDevice(m_dcTarget, GetPrintWidth());
  196.     }
  197. }
  198.  
  199. /////////////////////////////////////////////////////////////////////////////
  200. // CRichEditView serialization support
  201.  
  202. class _afxRichEditCookie
  203. {
  204. public:
  205.     CArchive& m_ar;
  206.     DWORD m_dwError;
  207.     _afxRichEditCookie(CArchive& ar) : m_ar(ar) {m_dwError=0;}
  208. };
  209.  
  210. void CRichEditView::Serialize(CArchive& ar)
  211.     // Read and write CRichEditView object to archive, with length prefix.
  212. {
  213.     ASSERT_VALID(this);
  214.     ASSERT(m_hWnd != NULL);
  215.     Stream(ar, FALSE);
  216.     ASSERT_VALID(this);
  217. }
  218.  
  219. void CRichEditView::Stream(CArchive& ar, BOOL bSelection)
  220. {
  221.     EDITSTREAM es = {0, 0, EditStreamCallBack};
  222.     _afxRichEditCookie cookie(ar);
  223.     es.dwCookie = (DWORD)&cookie;
  224.     int nFormat = GetDocument()->GetStreamFormat();
  225.     if (bSelection)
  226.         nFormat |= SFF_SELECTION;
  227.     if (ar.IsStoring())
  228.         GetRichEditCtrl().StreamOut(nFormat, es);
  229.     else
  230.     {
  231.         GetRichEditCtrl().StreamIn(nFormat, es);
  232.         Invalidate();
  233.     }
  234.     if (cookie.m_dwError != 0)
  235.         AfxThrowFileException(cookie.m_dwError);
  236. }
  237.  
  238. // return 0 for no error, otherwise return error code
  239. DWORD CALLBACK CRichEditView::EditStreamCallBack(DWORD dwCookie, LPBYTE pbBuff, LONG cb, LONG *pcb)
  240. {
  241.     _afxRichEditCookie* pCookie = (_afxRichEditCookie*)dwCookie;
  242.     CArchive& ar = pCookie->m_ar;
  243.     ar.Flush();
  244.     DWORD dw = 0;
  245.     *pcb = cb;
  246.     TRY
  247.     {
  248.         if (ar.IsStoring())
  249.             ar.GetFile()->WriteHuge(pbBuff, cb);
  250.         else
  251.             *pcb = ar.GetFile()->ReadHuge(pbBuff, cb);
  252.     }
  253.     CATCH(CFileException, e)
  254.     {
  255.         *pcb = 0;
  256.         pCookie->m_dwError = (DWORD)e->m_cause;
  257.         dw = 1;
  258.         DELETE_EXCEPTION(e);
  259.     }
  260.     AND_CATCH_ALL(e)
  261.     {
  262.         *pcb = 0;
  263.         pCookie->m_dwError = (DWORD)CFileException::generic;
  264.         dw = 1;
  265.         DELETE_EXCEPTION(e);
  266.     }
  267.     END_CATCH_ALL
  268.     return dw;
  269. }
  270.  
  271. /////////////////////////////////////////////////////////////////////////////
  272. // CRichEditView Printing support
  273.  
  274. void CRichEditView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo*)
  275. {
  276.     ASSERT_VALID(this);
  277. //  ASSERT_VALID(pDC);
  278.     // initialize page start vector
  279.     ASSERT(m_aPageStart.GetSize() == 0);
  280.     m_aPageStart.Add(0);
  281.     ASSERT(m_aPageStart.GetSize() > 0);
  282.     GetRichEditCtrl().FormatRange(NULL, FALSE); // required by RichEdit to clear out cache
  283.  
  284.     ASSERT_VALID(this);
  285. }
  286.  
  287. BOOL CRichEditView::PaginateTo(CDC* pDC, CPrintInfo* pInfo)
  288.     // attempts pagination to pInfo->m_nCurPage, TRUE == success
  289. {
  290.     ASSERT_VALID(this);
  291.     ASSERT_VALID(pDC);
  292.  
  293.     CRect rectSave = pInfo->m_rectDraw;
  294.     UINT nPageSave = pInfo->m_nCurPage;
  295.     ASSERT(nPageSave > 1);
  296.     ASSERT(nPageSave >= (UINT)m_aPageStart.GetSize());
  297.     VERIFY(pDC->SaveDC() != 0);
  298.     pDC->IntersectClipRect(0, 0, 0, 0);
  299.     pInfo->m_nCurPage = m_aPageStart.GetSize();
  300.     while (pInfo->m_nCurPage < nPageSave)
  301.     {
  302.         ASSERT(pInfo->m_nCurPage == (UINT)m_aPageStart.GetSize());
  303.         OnPrepareDC(pDC, pInfo);
  304.         ASSERT(pInfo->m_bContinuePrinting);
  305.         pInfo->m_rectDraw.SetRect(0, 0,
  306.             pDC->GetDeviceCaps(HORZRES), pDC->GetDeviceCaps(VERTRES));
  307.         pDC->DPtoLP(&pInfo->m_rectDraw);
  308.         OnPrint(pDC, pInfo);
  309.         if (pInfo->m_nCurPage == (UINT)m_aPageStart.GetSize())
  310.             break;
  311.         ++pInfo->m_nCurPage;
  312.     }
  313.     BOOL bResult = pInfo->m_nCurPage == nPageSave;
  314.     pDC->RestoreDC(-1);
  315.     pInfo->m_nCurPage = nPageSave;
  316.     pInfo->m_rectDraw = rectSave;
  317.     ASSERT_VALID(this);
  318.     return bResult;
  319. }
  320.  
  321. void CRichEditView::OnPrepareDC(CDC* pDC, CPrintInfo* pInfo)
  322. {
  323.     ASSERT_VALID(this);
  324.     ASSERT_VALID(pDC);
  325.     ASSERT(pInfo != NULL);  // overriding OnPaint -- never get this.
  326.  
  327.     pDC->SetMapMode(MM_TEXT);
  328.  
  329.     if (pInfo->m_nCurPage > (UINT)m_aPageStart.GetSize() &&
  330.         !PaginateTo(pDC, pInfo))
  331.     {
  332.         // can't paginate to that page, thus cannot print it.
  333.         pInfo->m_bContinuePrinting = FALSE;
  334.     }
  335.     ASSERT_VALID(this);
  336. }
  337.  
  338. long CRichEditView::PrintPage(CDC* pDC, long nIndexStart, long nIndexStop)
  339.     // worker function for laying out text in a rectangle.
  340. {
  341.     ASSERT_VALID(this);
  342.     ASSERT_VALID(pDC);
  343.     FORMATRANGE fr;
  344.  
  345.     // offset by printing offset
  346.     pDC->SetViewportOrg(-pDC->GetDeviceCaps(PHYSICALOFFSETX),
  347.         -pDC->GetDeviceCaps(PHYSICALOFFSETY));
  348.     // adjust DC because richedit doesn't do things like MFC
  349.     if (::GetDeviceCaps(pDC->m_hDC, TECHNOLOGY) != DT_METAFILE && pDC->m_hAttribDC != NULL)
  350.     {
  351.         ::ScaleWindowExtEx(pDC->m_hDC,
  352.             ::GetDeviceCaps(pDC->m_hDC, LOGPIXELSX),
  353.             ::GetDeviceCaps(pDC->m_hAttribDC, LOGPIXELSX),
  354.             ::GetDeviceCaps(pDC->m_hDC, LOGPIXELSY),
  355.             ::GetDeviceCaps(pDC->m_hAttribDC, LOGPIXELSY), NULL);
  356.     }
  357.  
  358.     fr.hdcTarget = pDC->m_hAttribDC;
  359.     fr.hdc = pDC->m_hDC;
  360.     fr.rcPage = GetPageRect();
  361.     fr.rc = GetPrintRect();
  362.  
  363.     fr.chrg.cpMin = nIndexStart;
  364.     fr.chrg.cpMax = nIndexStop;
  365.     long lRes = GetRichEditCtrl().FormatRange(&fr,TRUE);
  366.     return lRes;
  367. }
  368.  
  369. long CRichEditView::PrintInsideRect(CDC* pDC, RECT& rectLayout,
  370.     long nIndexStart, long nIndexStop, BOOL bOutput)
  371. {
  372.     ASSERT_VALID(this);
  373.     ASSERT_VALID(pDC);
  374.     FORMATRANGE fr;
  375.  
  376.     // adjust DC because richedit doesn't do things like MFC
  377.     if (::GetDeviceCaps(pDC->m_hDC, TECHNOLOGY) != DT_METAFILE && pDC->m_hAttribDC != NULL)
  378.     {
  379.         ::ScaleWindowExtEx(pDC->m_hDC,
  380.             ::GetDeviceCaps(pDC->m_hDC, LOGPIXELSX),
  381.             ::GetDeviceCaps(pDC->m_hAttribDC, LOGPIXELSX),
  382.             ::GetDeviceCaps(pDC->m_hDC, LOGPIXELSY),
  383.             ::GetDeviceCaps(pDC->m_hAttribDC, LOGPIXELSY), NULL);
  384.     }
  385.  
  386.     fr.hdcTarget = pDC->m_hAttribDC;
  387.     fr.hdc = pDC->m_hDC;
  388.     // convert rect to twips
  389.     fr.rcPage = rectLayout;
  390.     fr.rc = rectLayout;
  391.  
  392.     fr.chrg.cpMin = nIndexStart;
  393.     fr.chrg.cpMax = nIndexStop;
  394.     GetRichEditCtrl().FormatRange(NULL, FALSE); // required by RichEdit to clear out cache
  395.     // if bOutput is FALSE, we only measure
  396.     long lres = GetRichEditCtrl().FormatRange(&fr, bOutput);
  397.     GetRichEditCtrl().FormatRange(NULL, FALSE); // required by RichEdit to clear out cache
  398.  
  399.     rectLayout = fr.rc;
  400.     return lres;
  401. }
  402.  
  403. void CRichEditView::OnPrint(CDC* pDC, CPrintInfo* pInfo)
  404. {
  405.     ASSERT_VALID(this);
  406.     ASSERT_VALID(pDC);
  407.     ASSERT(pInfo != NULL);
  408.     ASSERT(pInfo->m_bContinuePrinting);
  409.  
  410.     UINT nPage = pInfo->m_nCurPage;
  411.     ASSERT(nPage <= (UINT)m_aPageStart.GetSize());
  412.     long nIndex = (long) m_aPageStart[nPage-1];
  413.  
  414.     // print as much as possible in the current page.
  415.     nIndex = PrintPage(pDC, nIndex, 0xFFFFFFFF);
  416.  
  417.     if (nIndex >= GetTextLength())
  418.     {
  419.         TRACE0("End of Document\n");
  420.         pInfo->SetMaxPage(nPage);
  421.     }
  422.  
  423.     // update pagination information for page just printed
  424.     if (nPage == (UINT)m_aPageStart.GetSize())
  425.     {
  426.         if (nIndex < GetTextLength())
  427.             m_aPageStart.Add(nIndex);
  428.     }
  429.     else
  430.     {
  431.         ASSERT(nPage+1 <= (UINT)m_aPageStart.GetSize());
  432.         ASSERT(nIndex == (long)m_aPageStart[nPage+1-1]);
  433.     }
  434. }
  435.  
  436.  
  437. void CRichEditView::OnEndPrinting(CDC*, CPrintInfo*)
  438. {
  439.     ASSERT_VALID(this);
  440.     GetRichEditCtrl().FormatRange(NULL, FALSE); // required by RichEdit to clear out cache
  441.     m_aPageStart.RemoveAll();
  442. }
  443.  
  444. /////////////////////////////////////////////////////////////////////////////
  445. // CRichEditView::XRichEditOleCallback
  446.  
  447. BEGIN_INTERFACE_MAP(CRichEditView, CCtrlView)
  448.     // we use IID_IUnknown because richedit doesn't define an IID
  449.     INTERFACE_PART(CRichEditView, IID_IUnknown, RichEditOleCallback)
  450. END_INTERFACE_MAP()
  451.  
  452. STDMETHODIMP_(ULONG) CRichEditView::XRichEditOleCallback::AddRef()
  453. {
  454.     METHOD_PROLOGUE_EX_(CRichEditView, RichEditOleCallback)
  455.     return (ULONG)pThis->InternalAddRef();
  456. }
  457.  
  458. STDMETHODIMP_(ULONG) CRichEditView::XRichEditOleCallback::Release()
  459. {
  460.     METHOD_PROLOGUE_EX_(CRichEditView, RichEditOleCallback)
  461.     return (ULONG)pThis->InternalRelease();
  462. }
  463.  
  464. STDMETHODIMP CRichEditView::XRichEditOleCallback::QueryInterface(
  465.     REFIID iid, LPVOID* ppvObj)
  466. {
  467.     METHOD_PROLOGUE_EX_(CRichEditView, RichEditOleCallback)
  468.     return (HRESULT)pThis->InternalQueryInterface(&iid, ppvObj);
  469. }
  470.  
  471. STDMETHODIMP CRichEditView::XRichEditOleCallback::GetNewStorage(LPSTORAGE* ppstg)
  472. {
  473.     METHOD_PROLOGUE_EX_(CRichEditView, RichEditOleCallback)
  474.  
  475.     // Create a flat storage and steal it from the client item
  476.     // the client item is only used for creating the storage
  477.     COleClientItem item;
  478.     item.GetItemStorageFlat();
  479.     *ppstg = item.m_lpStorage;
  480.     HRESULT hRes = E_OUTOFMEMORY;
  481.     if (item.m_lpStorage != NULL)
  482.     {
  483.         item.m_lpStorage = NULL;
  484.         hRes = S_OK;
  485.     }
  486.     pThis->GetDocument()->InvalidateObjectCache();
  487.     return hRes;
  488. }
  489.  
  490. STDMETHODIMP CRichEditView::XRichEditOleCallback::GetInPlaceContext(
  491.     LPOLEINPLACEFRAME* lplpFrame, LPOLEINPLACEUIWINDOW* lplpDoc,
  492.     LPOLEINPLACEFRAMEINFO lpFrameInfo)
  493. {
  494.     METHOD_PROLOGUE_EX(CRichEditView, RichEditOleCallback)
  495.     return pThis->GetWindowContext(lplpFrame, lplpDoc, lpFrameInfo);
  496. }
  497.  
  498. STDMETHODIMP CRichEditView::XRichEditOleCallback::ShowContainerUI(BOOL fShow)
  499. {
  500.     METHOD_PROLOGUE_EX(CRichEditView, RichEditOleCallback)
  501.     return pThis->ShowContainerUI(fShow);
  502. }
  503.  
  504. STDMETHODIMP CRichEditView::XRichEditOleCallback::QueryInsertObject(
  505.     LPCLSID /*lpclsid*/, LPSTORAGE /*pstg*/, LONG /*cp*/)
  506. {
  507.     METHOD_PROLOGUE_EX(CRichEditView, RichEditOleCallback)
  508.     pThis->GetDocument()->InvalidateObjectCache();
  509.     return S_OK;
  510. }
  511.  
  512. STDMETHODIMP CRichEditView::XRichEditOleCallback::DeleteObject(LPOLEOBJECT /*lpoleobj*/)
  513. {
  514.     METHOD_PROLOGUE_EX_(CRichEditView, RichEditOleCallback)
  515.     pThis->GetDocument()->InvalidateObjectCache();
  516.     return S_OK;
  517. }
  518.  
  519. STDMETHODIMP CRichEditView::XRichEditOleCallback::QueryAcceptData(
  520.     LPDATAOBJECT lpdataobj, CLIPFORMAT* lpcfFormat, DWORD reco,
  521.     BOOL fReally, HGLOBAL hMetaPict)
  522. {
  523.     METHOD_PROLOGUE_EX(CRichEditView, RichEditOleCallback)
  524.     return pThis->QueryAcceptData(lpdataobj, lpcfFormat, reco,
  525.         fReally, hMetaPict);
  526. }
  527.  
  528. STDMETHODIMP CRichEditView::XRichEditOleCallback::ContextSensitiveHelp(BOOL /*fEnterMode*/)
  529. {
  530.     return E_NOTIMPL;
  531. }
  532.  
  533. STDMETHODIMP CRichEditView::XRichEditOleCallback::GetClipboardData(
  534.     CHARRANGE* lpchrg, DWORD reco, LPDATAOBJECT* lplpdataobj)
  535. {
  536.     METHOD_PROLOGUE_EX(CRichEditView, RichEditOleCallback)
  537.     LPDATAOBJECT lpOrigDataObject = NULL;
  538.  
  539.     // get richedit's data object
  540.     if (FAILED(pThis->m_lpRichEditOle->GetClipboardData(lpchrg, reco,
  541.         &lpOrigDataObject)))
  542.     {
  543.         return E_NOTIMPL;
  544.     }
  545.  
  546.     // allow changes
  547.     HRESULT hRes = pThis->GetClipboardData(lpchrg, reco, lpOrigDataObject,
  548.         lplpdataobj);
  549.  
  550.     // if changed then free original object
  551.     if (SUCCEEDED(hRes))
  552.     {
  553.         if (lpOrigDataObject!=NULL)
  554.             lpOrigDataObject->Release();
  555.         return hRes;
  556.     }
  557.     else
  558.     {
  559.         // use richedit's data object
  560.         *lplpdataobj = lpOrigDataObject;
  561.         return S_OK;
  562.     }
  563. }
  564.  
  565. STDMETHODIMP CRichEditView::XRichEditOleCallback::GetDragDropEffect(
  566.     BOOL fDrag, DWORD grfKeyState, LPDWORD pdwEffect)
  567. {
  568.     if (!fDrag) // allowable dest effects
  569.     {
  570.         DWORD dwEffect;
  571.         // check for force link
  572. #ifndef _MAC
  573.         if ((grfKeyState & (MK_CONTROL|MK_SHIFT)) == (MK_CONTROL|MK_SHIFT))
  574. #else
  575.         if ((grfKeyState & (MK_OPTION|MK_SHIFT)) == (MK_OPTION|MK_SHIFT))
  576. #endif
  577.             dwEffect = DROPEFFECT_LINK;
  578.         // check for force copy
  579. #ifndef _MAC
  580.         else if ((grfKeyState & MK_CONTROL) == MK_CONTROL)
  581. #else
  582.         else if ((grfKeyState & MK_OPTION) == MK_OPTION)
  583. #endif
  584.             dwEffect = DROPEFFECT_COPY;
  585.         // check for force move
  586.         else if ((grfKeyState & MK_ALT) == MK_ALT)
  587.             dwEffect = DROPEFFECT_MOVE;
  588.         // default -- recommended action is move
  589.         else
  590.             dwEffect = DROPEFFECT_MOVE;
  591.         if (dwEffect & *pdwEffect) // make sure allowed type
  592.             *pdwEffect = dwEffect;
  593.     }
  594.     return S_OK;
  595. }
  596.  
  597. STDMETHODIMP CRichEditView::XRichEditOleCallback::GetContextMenu(
  598.     WORD seltype, LPOLEOBJECT lpoleobj, CHARRANGE* lpchrg,
  599.     HMENU* lphmenu)
  600. {
  601.     METHOD_PROLOGUE_EX(CRichEditView, RichEditOleCallback)
  602.     HMENU hMenu = pThis->GetContextMenu(seltype, lpoleobj, lpchrg);
  603.     if (hMenu == NULL)
  604.         return E_NOTIMPL;
  605.     *lphmenu = hMenu;
  606.     return S_OK;
  607. }
  608.  
  609. /////////////////////////////////////////////////////////////////////////////
  610. // CRichEditView command helpers
  611.  
  612. void CRichEditView::OnCharEffect(DWORD dwMask, DWORD dwEffect)
  613. {
  614.     GetCharFormatSelection();
  615.     if (m_charformat.dwMask & dwMask) // selection is all the same
  616.         m_charformat.dwEffects ^= dwEffect;
  617.     else
  618.         m_charformat.dwEffects |= dwEffect;
  619.     m_charformat.dwMask = dwMask;
  620.     SetCharFormat(m_charformat);
  621. }
  622.  
  623. void CRichEditView::OnUpdateCharEffect(CCmdUI* pCmdUI, DWORD dwMask, DWORD dwEffect)
  624. {
  625.     GetCharFormatSelection();
  626.     pCmdUI->SetCheck((m_charformat.dwMask & dwMask) ?
  627.         ((m_charformat.dwEffects & dwEffect) ? 1 : 0) : 2);
  628. }
  629.  
  630. void CRichEditView::OnParaAlign(WORD wAlign)
  631. {
  632.     GetParaFormatSelection();
  633.     m_paraformat.dwMask = PFM_ALIGNMENT;
  634.     m_paraformat.wAlignment = wAlign;
  635.     SetParaFormat(m_paraformat);
  636. }
  637.  
  638. void CRichEditView::OnUpdateParaAlign(CCmdUI* pCmdUI, WORD wAlign)
  639. {
  640.     GetParaFormatSelection();
  641.     // disable if no word wrap since alignment is meaningless
  642.     pCmdUI->Enable( (m_nWordWrap == WrapNone) ?
  643.         FALSE : TRUE);
  644.     pCmdUI->SetCheck( (m_paraformat.dwMask & PFM_ALIGNMENT) ?
  645.         ((m_paraformat.wAlignment == wAlign) ? 1 : 0) : 2);
  646. }
  647.  
  648. /////////////////////////////////////////////////////////////////////////////
  649. // CRichEditView commands
  650.  
  651. void CRichEditView::OnUpdateNeedSel(CCmdUI* pCmdUI)
  652. {
  653.     ASSERT_VALID(this);
  654.     long nStartChar, nEndChar;
  655.     GetRichEditCtrl().GetSel(nStartChar, nEndChar);
  656.     pCmdUI->Enable(nStartChar != nEndChar);
  657.     ASSERT_VALID(this);
  658. }
  659.  
  660. void CRichEditView::OnUpdateNeedClip(CCmdUI* pCmdUI)
  661. {
  662.     ASSERT_VALID(this);
  663.     pCmdUI->Enable(CanPaste());
  664. }
  665.  
  666. void CRichEditView::OnUpdateNeedText(CCmdUI* pCmdUI)
  667. {
  668.     ASSERT_VALID(this);
  669.     pCmdUI->Enable(GetTextLength() != 0);
  670. }
  671.  
  672. void CRichEditView::OnUpdateNeedFind(CCmdUI* pCmdUI)
  673. {
  674.     ASSERT_VALID(this);
  675.     _AFX_RICHEDIT_STATE* pEditState = _afxRichEditState;
  676.     pCmdUI->Enable(GetTextLength() != 0 &&
  677.         !pEditState->strFind.IsEmpty());
  678. }
  679.  
  680. void CRichEditView::OnUpdateEditUndo(CCmdUI* pCmdUI)
  681. {
  682.     ASSERT_VALID(this);
  683.     pCmdUI->Enable(GetRichEditCtrl().CanUndo());
  684. }
  685.  
  686. void CRichEditView::OnEditCut()
  687. {
  688.     ASSERT_VALID(this);
  689.     GetRichEditCtrl().Cut();
  690. }
  691.  
  692. void CRichEditView::OnEditCopy()
  693. {
  694.     ASSERT_VALID(this);
  695.     GetRichEditCtrl().Copy();
  696. }
  697.  
  698. void CRichEditView::OnEditPaste()
  699. {
  700.     ASSERT_VALID(this);
  701.     m_nPasteType = 0;
  702.     GetRichEditCtrl().Paste();
  703. }
  704.  
  705. void CRichEditView::OnEditClear()
  706. {
  707.     ASSERT_VALID(this);
  708.     GetRichEditCtrl().Clear();
  709. }
  710.  
  711. void CRichEditView::OnEditUndo()
  712. {
  713.     ASSERT_VALID(this);
  714.     GetRichEditCtrl().Undo();
  715.     m_bSyncCharFormat = m_bSyncParaFormat = TRUE;
  716. }
  717.  
  718. void CRichEditView::OnEditSelectAll()
  719. {
  720.     ASSERT_VALID(this);
  721.     GetRichEditCtrl().SetSel(0, -1);
  722. }
  723.  
  724. void CRichEditView::OnEditFind()
  725. {
  726.     ASSERT_VALID(this);
  727.     OnEditFindReplace(TRUE);
  728. }
  729.  
  730. void CRichEditView::OnEditReplace()
  731. {
  732.     ASSERT_VALID(this);
  733.     OnEditFindReplace(FALSE);
  734. }
  735.  
  736. void CRichEditView::OnEditRepeat()
  737. {
  738.     ASSERT_VALID(this);
  739.     _AFX_RICHEDIT_STATE* pEditState = _afxRichEditState;
  740.     if (!FindText(pEditState))
  741.         TextNotFound(pEditState->strFind);
  742. }
  743.  
  744. void CRichEditView::OnCancelEditCntr()
  745. {
  746.     m_lpRichEditOle->InPlaceDeactivate();
  747. }
  748.  
  749. void CRichEditView::OnInsertObject()
  750. {
  751.     // Invoke the standard Insert Object dialog box to obtain information
  752.     COleInsertDialog dlg;
  753.     if (dlg.DoModal() != IDOK)
  754.         return;
  755.  
  756.     CWaitCursor wait;
  757.  
  758.     CRichEditCntrItem* pItem = NULL;
  759.     TRY
  760.     {
  761.         // create item from dialog results
  762.         pItem = GetDocument()->CreateClientItem();
  763.         pItem->m_bLock = TRUE;
  764.         if (!dlg.CreateItem(pItem))
  765.         {
  766.             pItem->m_bLock = FALSE;
  767.             AfxThrowMemoryException();  // any exception will do
  768.         }
  769.  
  770.         HRESULT hr = InsertItem(pItem);
  771.         pItem->UpdateItemType();
  772.  
  773.         pItem->m_bLock = FALSE;
  774.  
  775.         if (hr != NOERROR)
  776.             AfxThrowOleException(hr);
  777.  
  778.         // if insert new object -- initially show the object
  779.         if (dlg.GetSelectionType() == COleInsertDialog::createNewItem)
  780.             pItem->DoVerb(OLEIVERB_SHOW, this);
  781.     }
  782.     CATCH(CException, e)
  783.     {
  784.         if (pItem != NULL)
  785.         {
  786.             ASSERT_VALID(pItem);
  787.             pItem->Delete();
  788.         }
  789.         AfxMessageBox(AFX_IDP_FAILED_TO_CREATE);
  790.     }
  791.     END_CATCH
  792. }
  793.  
  794. void CRichEditView::OnSelChange(NMHDR* pNMHDR, LRESULT* pResult)
  795. {
  796.     ASSERT(pNMHDR->code == EN_SELCHANGE);
  797.     UNUSED(pNMHDR); // not used in release builds
  798.  
  799.     m_bSyncCharFormat = m_bSyncParaFormat = TRUE;
  800.     *pResult = 0;
  801. }
  802.  
  803. void CRichEditView::OnDestroy()
  804. {
  805.     if (m_lpRichEditOle != NULL)
  806.         m_lpRichEditOle->Release();
  807.     CCtrlView::OnDestroy();
  808. }
  809.  
  810. void CRichEditView::OnEditProperties()
  811. {
  812.     ASSERT(m_lpRichEditOle != NULL);
  813.     CRichEditCntrItem* pSelection = GetSelectedItem();
  814.     // make sure item is in sync with richedit's item
  815.     CReObject reo;
  816.     HRESULT hr = m_lpRichEditOle->GetObject(REO_IOB_SELECTION, &reo,
  817.         REO_GETOBJ_NO_INTERFACES);
  818.     pSelection->SyncToRichEditObject(reo);
  819.     COlePropertiesDialog dlg(pSelection);
  820.     dlg.DoModal();
  821. }
  822.  
  823. void CRichEditView::OnUpdateEditProperties(CCmdUI* pCmdUI)
  824. {
  825.     pCmdUI->Enable(GetSelectedItem() != NULL);
  826. }
  827.  
  828. void CRichEditView::OnCharBold()
  829. {
  830.     OnCharEffect(CFM_BOLD, CFE_BOLD);
  831. }
  832.  
  833. void CRichEditView::OnUpdateCharBold(CCmdUI* pCmdUI)
  834. {
  835.     OnUpdateCharEffect(pCmdUI, CFM_BOLD, CFE_BOLD);
  836. }
  837.  
  838. void CRichEditView::OnCharItalic()
  839. {
  840.     OnCharEffect(CFM_ITALIC, CFE_ITALIC);
  841. }
  842.  
  843. void CRichEditView::OnUpdateCharItalic(CCmdUI* pCmdUI)
  844. {
  845.     OnUpdateCharEffect(pCmdUI, CFM_ITALIC, CFE_ITALIC);
  846. }
  847.  
  848. void CRichEditView::OnCharUnderline()
  849. {
  850.     OnCharEffect(CFM_UNDERLINE, CFE_UNDERLINE);
  851. }
  852.  
  853. void CRichEditView::OnUpdateCharUnderline(CCmdUI* pCmdUI)
  854. {
  855.     OnUpdateCharEffect(pCmdUI, CFM_UNDERLINE, CFE_UNDERLINE);
  856. }
  857.  
  858. void CRichEditView::OnParaCenter()
  859. {
  860.     OnParaAlign(PFA_CENTER);
  861. }
  862.  
  863. void CRichEditView::OnUpdateParaCenter(CCmdUI* pCmdUI)
  864. {
  865.     OnUpdateParaAlign(pCmdUI, PFA_CENTER);
  866. }
  867.  
  868. void CRichEditView::OnParaLeft()
  869. {
  870.     OnParaAlign(PFA_LEFT);
  871. }
  872.  
  873. void CRichEditView::OnUpdateParaLeft(CCmdUI* pCmdUI)
  874. {
  875.     OnUpdateParaAlign(pCmdUI, PFA_LEFT);
  876. }
  877.  
  878. void CRichEditView::OnParaRight()
  879. {
  880.     OnParaAlign(PFA_RIGHT);
  881. }
  882.  
  883. void CRichEditView::OnUpdateParaRight(CCmdUI* pCmdUI)
  884. {
  885.     OnUpdateParaAlign(pCmdUI, PFA_RIGHT);
  886. }
  887.  
  888. void CRichEditView::OnBullet()
  889. {
  890.     GetParaFormatSelection();
  891.     if (m_paraformat.dwMask & PFM_NUMBERING && m_paraformat.wNumbering == PFN_BULLET)
  892.     {
  893.         m_paraformat.wNumbering = 0;
  894.         m_paraformat.dxOffset = 0;
  895.         m_paraformat.dxStartIndent = 0;
  896.         m_paraformat.dwMask = PFM_NUMBERING | PFM_STARTINDENT | PFM_OFFSET;
  897.     }
  898.     else
  899.     {
  900.         m_paraformat.wNumbering = PFN_BULLET;
  901.         m_paraformat.dwMask = PFM_NUMBERING;
  902.         if (m_paraformat.dxOffset == 0)
  903.         {
  904.             m_paraformat.dxOffset = m_nBulletIndent;
  905.             m_paraformat.dwMask = PFM_NUMBERING | PFM_STARTINDENT | PFM_OFFSET;
  906.         }
  907.     }
  908.     SetParaFormat(m_paraformat);
  909. }
  910.  
  911. void CRichEditView::OnUpdateBullet(CCmdUI* pCmdUI)
  912. {
  913.     GetParaFormatSelection();
  914.     pCmdUI->SetCheck( (m_paraformat.dwMask & PFM_NUMBERING) ? ((m_paraformat.wNumbering & PFN_BULLET) ? 1 : 0) : 2);
  915. }
  916.  
  917. void CRichEditView::OnFormatFont()
  918. {
  919.     GetCharFormatSelection();
  920.     CFontDialog dlg(m_charformat, CF_BOTH|CF_NOOEMFONTS);
  921.     if (dlg.DoModal() == IDOK)
  922.     {
  923.         dlg.GetCharFormat(m_charformat);
  924.         SetCharFormat(m_charformat);
  925.     }
  926. }
  927.  
  928. void CRichEditView::OnColorPick(COLORREF cr)
  929. {
  930.     GetCharFormatSelection();
  931.     m_charformat.dwMask = CFM_COLOR;
  932.     m_charformat.dwEffects = NULL;
  933.     m_charformat.crTextColor = cr;
  934.     SetCharFormat(m_charformat);
  935. }
  936.  
  937. void CRichEditView::OnColorDefault()
  938. {
  939.     GetCharFormatSelection();
  940.     m_charformat.dwMask = CFM_COLOR;
  941.     m_charformat.dwEffects = CFE_AUTOCOLOR;
  942.     SetCharFormat(m_charformat);
  943. }
  944.  
  945. void CRichEditView::OnEditPasteSpecial()
  946. {
  947.     COlePasteSpecialDialog dlg;
  948.     dlg.AddStandardFormats();
  949.     dlg.AddFormat(_oleData.cfRichTextFormat, TYMED_HGLOBAL, AFX_IDS_RTF_FORMAT, FALSE, FALSE);
  950.     dlg.AddFormat(CF_TEXT, TYMED_HGLOBAL, AFX_IDS_TEXT_FORMAT, FALSE, FALSE);
  951.  
  952.     if (dlg.DoModal() != IDOK)
  953.         return;
  954.  
  955.     DVASPECT dv = dlg.GetDrawAspect();
  956.     HMETAFILE hMF = (HMETAFILE)dlg.GetIconicMetafile();
  957.     CLIPFORMAT cf =
  958.         dlg.m_ps.arrPasteEntries[dlg.m_ps.nSelectedIndex].fmtetc.cfFormat;
  959.  
  960.     CWaitCursor wait;
  961.     SetCapture();
  962.  
  963.     // we set the target type so that QueryAcceptData know what to paste
  964.     m_nPasteType = dlg.GetSelectionType();
  965.     GetRichEditCtrl().PasteSpecial(cf, dv, hMF);
  966.     m_nPasteType = 0;
  967.  
  968.     ReleaseCapture();
  969. }
  970.  
  971. void CRichEditView::OnUpdateEditPasteSpecial(CCmdUI* pCmdUI)
  972. {
  973.     pCmdUI->Enable(CanPaste());
  974. }
  975.  
  976. void CRichEditView::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags)
  977. {
  978.     if (nChar == VK_F10 && GetKeyState(VK_SHIFT) < 0)
  979.     {
  980.         CRect rect;
  981.         GetClientRect(rect);
  982.         CPoint pt = rect.CenterPoint();
  983.         SendMessage(WM_CONTEXTMENU, (WPARAM)m_hWnd, MAKELPARAM(pt.x, pt.y));
  984.     }
  985.     else
  986.         CCtrlView::OnKeyDown(nChar, nRepCnt, nFlags);
  987. }
  988.  
  989. void CRichEditView::OnDropFiles(HDROP hDropInfo)
  990. {
  991.     TCHAR szFileName[_MAX_PATH];
  992.     UINT nFileCount = ::DragQueryFile(hDropInfo, 0xFFFFFFFF, NULL, 0);
  993.     ASSERT(nFileCount != 0);
  994.     CHARRANGE cr;
  995.     GetRichEditCtrl().GetSel(cr);
  996.     int nMin = cr.cpMin;
  997.     for (UINT i=0;i<nFileCount;i++)
  998.     {
  999.         ::DragQueryFile(hDropInfo, i, szFileName, _MAX_PATH);
  1000.         InsertFileAsObject(szFileName);
  1001.         GetRichEditCtrl().GetSel(cr);
  1002.         cr.cpMin = cr.cpMax;
  1003.         GetRichEditCtrl().SetSel(cr);
  1004.         UpdateWindow();
  1005.     }
  1006.     cr.cpMin = nMin;
  1007.     GetRichEditCtrl().SetSel(cr);
  1008.     ::DragFinish(hDropInfo);
  1009. }
  1010.  
  1011. void CRichEditView::OnDevModeChange(LPTSTR /*lpDeviceName*/)
  1012. {
  1013.     // WM_DEVMODECHANGE forwarded by the main window of the app
  1014.     CDC dc;
  1015.     AfxGetApp()->CreatePrinterDC(dc);
  1016.     OnPrinterChanged(dc);
  1017. }
  1018.  
  1019. /////////////////////////////////////////////////////////////////////////////
  1020. // CRichEditView attributes
  1021.  
  1022. BOOL AFX_CDECL CRichEditView::IsRichEditFormat(CLIPFORMAT cf)
  1023. {
  1024.     return ((cf == _oleData.cfRichTextFormat) ||
  1025.         (cf == _oleData.cfRichTextAndObjects) || (cf == CF_TEXT));
  1026. }
  1027.  
  1028. BOOL CRichEditView::CanPaste() const
  1029. {
  1030.     return (CountClipboardFormats() != 0) &&
  1031.         (IsClipboardFormatAvailable(CF_TEXT) ||
  1032.         IsClipboardFormatAvailable(_oleData.cfRichTextFormat) ||
  1033.         IsClipboardFormatAvailable(_oleData.cfEmbedSource) ||
  1034.         IsClipboardFormatAvailable(_oleData.cfEmbeddedObject) ||
  1035.         IsClipboardFormatAvailable(_oleData.cfFileName) ||
  1036.         IsClipboardFormatAvailable(_oleData.cfFileNameW) ||
  1037.         IsClipboardFormatAvailable(CF_METAFILEPICT) ||
  1038.         IsClipboardFormatAvailable(CF_DIB) ||
  1039.         IsClipboardFormatAvailable(CF_BITMAP) ||
  1040.         GetRichEditCtrl().CanPaste());
  1041. }
  1042.  
  1043. CHARFORMAT& CRichEditView::GetCharFormatSelection()
  1044. {
  1045.     if (m_bSyncCharFormat)
  1046.     {
  1047.         GetRichEditCtrl().GetSelectionCharFormat(m_charformat);
  1048.         m_bSyncCharFormat = FALSE;
  1049.     }
  1050.     return m_charformat;
  1051. }
  1052.  
  1053. PARAFORMAT& CRichEditView::GetParaFormatSelection()
  1054. {
  1055.     if (m_bSyncParaFormat)
  1056.     {
  1057.         GetRichEditCtrl().GetParaFormat(m_paraformat);
  1058.         m_bSyncParaFormat = FALSE;
  1059.     }
  1060.     return m_paraformat;
  1061. }
  1062.  
  1063. void CRichEditView::SetCharFormat(CHARFORMAT cf)
  1064. {
  1065.     CWaitCursor wait;
  1066.     GetRichEditCtrl().SetSelectionCharFormat(cf);
  1067.     m_bSyncCharFormat = TRUE;
  1068. }
  1069.  
  1070. void CRichEditView::SetParaFormat(PARAFORMAT& pf)
  1071. {
  1072.     CWaitCursor wait;
  1073.     GetRichEditCtrl().SetParaFormat(pf);
  1074.     m_bSyncParaFormat = TRUE;
  1075. }
  1076.  
  1077. CRichEditCntrItem* CRichEditView::GetSelectedItem() const
  1078. {
  1079.     ASSERT(m_lpRichEditOle != NULL);
  1080.     CRichEditDoc* pDoc = GetDocument();
  1081.     CRichEditCntrItem* pItem = NULL;
  1082.  
  1083.     CReObject reo;
  1084.     HRESULT hr = m_lpRichEditOle->GetObject(REO_IOB_SELECTION, &reo,
  1085.         REO_GETOBJ_ALL_INTERFACES);
  1086.     //reo's interfaces are all in UNICODE
  1087.     if (GetScode(hr) == S_OK)
  1088.     {
  1089.         pItem = pDoc->LookupItem(reo.poleobj);
  1090.         if (pItem == NULL)
  1091.             pItem = pDoc->CreateClientItem(&reo);
  1092.         ASSERT(pItem != NULL);
  1093.     }
  1094.     return pItem;
  1095. }
  1096.  
  1097. CRichEditCntrItem* CRichEditView::GetInPlaceActiveItem() const
  1098. {
  1099.     ASSERT(m_lpRichEditOle != NULL);
  1100.     CRichEditDoc* pDoc = GetDocument();
  1101.     CRichEditCntrItem* pItem = NULL;
  1102.  
  1103.     CReObject reo;
  1104.     HRESULT hr = m_lpRichEditOle->GetObject(REO_IOB_SELECTION, &reo,
  1105.         REO_GETOBJ_ALL_INTERFACES);
  1106.     //reo's interfaces are all in UNICODE
  1107.     if (GetScode(hr) == S_OK && (reo.dwFlags & REO_INPLACEACTIVE))
  1108.     {
  1109.         pItem = pDoc->LookupItem(reo.poleobj);
  1110.         if (pItem == NULL)
  1111.             pItem = pDoc->CreateClientItem(&reo);
  1112.         ASSERT(pItem != NULL);
  1113.     }
  1114.     return pItem;
  1115. }
  1116.  
  1117. /////////////////////////////////////////////////////////////////////////////
  1118. // CRichEditView operations
  1119. HRESULT CRichEditView::InsertItem(CRichEditCntrItem* pItem)
  1120. {
  1121.     ASSERT(m_lpRichEditOle != NULL);
  1122.     CReObject reo(pItem);
  1123.     reo.cp = REO_CP_SELECTION;
  1124.  
  1125.     HRESULT hr = m_lpRichEditOle->InsertObject(&reo);
  1126.  
  1127.     CHARRANGE cr;
  1128.     GetRichEditCtrl().GetSel(cr);
  1129.     cr.cpMin = cr.cpMax -1;
  1130.     GetRichEditCtrl().SetSel(cr);
  1131.     return hr;
  1132. }
  1133.  
  1134. void CRichEditView::InsertFileAsObject(LPCTSTR lpszFileName)
  1135. {
  1136.     CString str = lpszFileName;
  1137.     CWaitCursor wait;
  1138.     CRichEditCntrItem* pItem = NULL;
  1139.     TRY
  1140.     {
  1141.         // create item from dialog results
  1142.         pItem = GetDocument()->CreateClientItem();
  1143.         pItem->m_bLock = TRUE;
  1144.         if (!pItem->CreateFromFile(str))
  1145.             AfxThrowMemoryException();  // any exception will do
  1146.         pItem->UpdateLink();
  1147.         InsertItem(pItem);
  1148.         pItem->m_bLock = FALSE;
  1149.     }
  1150.     CATCH(CException, e)
  1151.     {
  1152.         if (pItem != NULL)
  1153.         {
  1154.             pItem->m_bLock = FALSE;
  1155.             ASSERT_VALID(pItem);
  1156.             pItem->Delete();
  1157.         }
  1158.     }
  1159.     END_CATCH
  1160. }
  1161.  
  1162. void CRichEditView::DoPaste(COleDataObject& dataobj, CLIPFORMAT cf, HMETAFILEPICT hMetaPict)
  1163. {
  1164.     CWaitCursor wait;
  1165.  
  1166.     CRichEditCntrItem* pItem = NULL;
  1167.     TRY
  1168.     {
  1169.         // create item from dialog results
  1170.         pItem = GetDocument()->CreateClientItem();
  1171.         pItem->m_bLock = TRUE;
  1172.  
  1173.         if (m_nPasteType == COlePasteSpecialDialog::pasteLink)      // paste link
  1174.         {
  1175.             if (!pItem->CreateLinkFromData(&dataobj))
  1176.                 AfxThrowMemoryException();  // any exception will do
  1177.         }
  1178.         else if (m_nPasteType == COlePasteSpecialDialog::pasteNormal)
  1179.         {
  1180.             if (!pItem->CreateFromData(&dataobj))
  1181.                 AfxThrowMemoryException();      // any exception will do
  1182.         }
  1183.         else if (m_nPasteType == COlePasteSpecialDialog::pasteStatic)
  1184.         {
  1185.             if (!pItem->CreateStaticFromData(&dataobj))
  1186.                 AfxThrowMemoryException();      // any exception will do
  1187.         }
  1188.         else
  1189.         {
  1190.             // paste embedded
  1191.             if (!pItem->CreateFromData(&dataobj) &&
  1192.                 !pItem->CreateStaticFromData(&dataobj))
  1193.             {
  1194.                 AfxThrowMemoryException();      // any exception will do
  1195.             }
  1196.         }
  1197.  
  1198.         if (cf == 0)
  1199.         {
  1200.             // copy the current iconic representation
  1201.             FORMATETC fmtetc;
  1202.             fmtetc.cfFormat = CF_METAFILEPICT;
  1203.             fmtetc.dwAspect = DVASPECT_ICON;
  1204.             fmtetc.ptd = NULL;
  1205.             fmtetc.tymed = TYMED_MFPICT;
  1206.             fmtetc.lindex = 1;
  1207.             HGLOBAL hObj = dataobj.GetGlobalData(CF_METAFILEPICT, &fmtetc);
  1208.             if (hObj != NULL)
  1209.             {
  1210.                 pItem->SetIconicMetafile(hObj);
  1211.                 // the following code is an easy way to free a metafile pict
  1212.                 STGMEDIUM stgMed;
  1213.                 memset(&stgMed, 0, sizeof(stgMed));
  1214.                 stgMed.tymed = TYMED_MFPICT;
  1215.                 stgMed.hGlobal = hObj;
  1216.                 ReleaseStgMedium(&stgMed);
  1217.             }
  1218.  
  1219.             // set the current drawing aspect
  1220.             hObj = dataobj.GetGlobalData((CLIPFORMAT)_oleData.cfObjectDescriptor);
  1221.             if (hObj != NULL)
  1222.             {
  1223.                 ASSERT(hObj != NULL);
  1224.                 // got CF_OBJECTDESCRIPTOR ok.  Lock it down and extract size.
  1225.                 LPOBJECTDESCRIPTOR pObjDesc = (LPOBJECTDESCRIPTOR)GlobalLock(hObj);
  1226.                 ASSERT(pObjDesc != NULL);
  1227.                 ((COleClientItem*)pItem)->SetDrawAspect((DVASPECT)pObjDesc->dwDrawAspect);
  1228.                 GlobalUnlock(hObj);
  1229.                 GlobalFree(hObj);
  1230.             }
  1231.         }
  1232.         else
  1233.         {
  1234.             if (hMetaPict != NULL)
  1235.             {
  1236.                 pItem->SetIconicMetafile(hMetaPict);
  1237.                 ((COleClientItem*)pItem)->SetDrawAspect(DVASPECT_ICON);
  1238.             }
  1239.             else
  1240.                 ((COleClientItem*)pItem)->SetDrawAspect(DVASPECT_CONTENT);
  1241.         }
  1242.  
  1243. /////////
  1244.         HRESULT hr = InsertItem(pItem);
  1245.         pItem->UpdateItemType();
  1246.  
  1247.         pItem->m_bLock = FALSE;
  1248.  
  1249.         if (hr != NOERROR)
  1250.             AfxThrowOleException(hr);
  1251.  
  1252.     }
  1253.     CATCH(CException, e)
  1254.     {
  1255.         if (pItem != NULL)
  1256.         {
  1257.             pItem->m_bLock = FALSE;
  1258.             ASSERT_VALID(pItem);
  1259.             pItem->Delete();
  1260.         }
  1261.     }
  1262.     END_CATCH
  1263. }
  1264.  
  1265. /////////////////////////////////////////////////////////////////////////////
  1266. // CRichEditView virtuals
  1267.  
  1268. void CRichEditView::OnPrinterChanged(const CDC& dcPrinter)
  1269. {
  1270.     // this is typically called by the view when it gets a WM_DEVMODECHANGE
  1271.     // also called during page setup
  1272.     CSize size;
  1273.     if (dcPrinter.m_hDC != NULL)
  1274.     {
  1275.         // this will fill in the page size
  1276.         size.cx = MulDiv(dcPrinter.GetDeviceCaps(PHYSICALWIDTH), 1440,
  1277.             dcPrinter.GetDeviceCaps(LOGPIXELSX));
  1278.         size.cy = MulDiv(dcPrinter.GetDeviceCaps(PHYSICALHEIGHT), 1440,
  1279.             dcPrinter.GetDeviceCaps(LOGPIXELSY));
  1280.     }
  1281.     else
  1282.         size = CSize(8*1440+720, 11*1440); // 8.5" by 11"
  1283.     if (GetPaperSize() != size)
  1284.     {
  1285.         SetPaperSize(size);
  1286.         if (m_nWordWrap == WrapToTargetDevice) //wrap to ruler
  1287.             WrapChanged();
  1288.     }
  1289. }
  1290.  
  1291. BOOL CRichEditView::OnPasteNativeObject(LPSTORAGE)
  1292. {
  1293.     // use this function to pull out native data from an embedded object
  1294.     // one would typically do this by create a COleStreamFile and attaching it
  1295.     // to an archive
  1296.     return FALSE;
  1297. }
  1298.  
  1299. HMENU CRichEditView::GetContextMenu(WORD, LPOLEOBJECT, CHARRANGE* )
  1300. {
  1301.     return NULL;
  1302. }
  1303.  
  1304. HRESULT CRichEditView::GetClipboardData(CHARRANGE* /*lpchrg*/, DWORD /*reco*/,
  1305.     LPDATAOBJECT /*lpRichDataObj*/, LPDATAOBJECT* /*lplpdataobj*/)
  1306. {
  1307.     return E_NOTIMPL;
  1308. }
  1309.  
  1310. HRESULT CRichEditView::QueryAcceptData(LPDATAOBJECT lpdataobj,
  1311.     CLIPFORMAT* lpcfFormat, DWORD /*dwReco*/, BOOL bReally, HGLOBAL hMetaPict)
  1312. {
  1313.     ASSERT(lpcfFormat != NULL);
  1314.     if (!bReally) // not actually pasting
  1315.         return S_OK;
  1316.     // if direct pasting a particular native format allow it
  1317.     if (IsRichEditFormat(*lpcfFormat))
  1318.         return S_OK;
  1319.  
  1320.     COleDataObject dataobj;
  1321.     dataobj.Attach(lpdataobj, FALSE);
  1322.     // if format is 0, then force particular formats if available
  1323.     if (*lpcfFormat == 0 && (m_nPasteType == 0))
  1324.     {
  1325.         if (dataobj.IsDataAvailable((CLIPFORMAT)_oleData.cfRichTextAndObjects)) // native avail, let richedit do as it wants
  1326.             return S_OK;
  1327.         else if (dataobj.IsDataAvailable((CLIPFORMAT)_oleData.cfRichTextFormat))
  1328.         {
  1329.             *lpcfFormat = (CLIPFORMAT)_oleData.cfRichTextFormat;
  1330.             return S_OK;
  1331.         }
  1332.         else if (dataobj.IsDataAvailable(CF_TEXT))
  1333.         {
  1334.             *lpcfFormat = CF_TEXT;
  1335.             return S_OK;
  1336.         }
  1337.     }
  1338.     // paste OLE formats
  1339.  
  1340.     DoPaste(dataobj, *lpcfFormat, hMetaPict);
  1341.     return S_FALSE;
  1342. }
  1343.  
  1344. HRESULT CRichEditView::GetWindowContext(LPOLEINPLACEFRAME* lplpFrame,
  1345.     LPOLEINPLACEUIWINDOW* lplpDoc, LPOLEINPLACEFRAMEINFO lpFrameInfo)
  1346. {
  1347.     CRichEditCntrItem* pItem = GetSelectedItem();
  1348.     if (pItem == NULL)
  1349.         return E_FAIL;
  1350.     pItem->m_pView = this;
  1351.     HRESULT hr = pItem->GetWindowContext(lplpFrame, lplpDoc, lpFrameInfo);
  1352.     pItem->m_pView = NULL;
  1353.     return hr;
  1354. }
  1355.  
  1356. HRESULT CRichEditView::ShowContainerUI(BOOL b)
  1357. {
  1358.     CRichEditCntrItem* pItem = GetSelectedItem();
  1359.     if (pItem == NULL)
  1360.         return E_FAIL;
  1361.     if (b)
  1362.         pItem->m_pView = this;
  1363.     HRESULT hr = pItem->ShowContainerUI(b);
  1364.     if (FAILED(hr) || !b)
  1365.         pItem->m_pView = NULL;
  1366.     return hr;
  1367. }
  1368.  
  1369.  
  1370. /////////////////////////////////////////////////////////////////////////////
  1371. // CRichEditView Find & Replace
  1372.  
  1373. void CRichEditView::AdjustDialogPosition(CDialog* pDlg)
  1374. {
  1375.     ASSERT(pDlg != NULL);
  1376.     long lStart, lEnd;
  1377.     GetRichEditCtrl().GetSel(lStart, lEnd);
  1378.     CPoint point = GetRichEditCtrl().GetCharPos(lStart);
  1379.     ClientToScreen(&point);
  1380.     CRect rectDlg;
  1381.     pDlg->GetWindowRect(&rectDlg);
  1382.     if (rectDlg.PtInRect(point))
  1383.     {
  1384.         if (point.y > rectDlg.Height())
  1385.             rectDlg.OffsetRect(0, point.y - rectDlg.bottom - 20);
  1386.         else
  1387.         {
  1388.             int nVertExt = GetSystemMetrics(SM_CYSCREEN);
  1389.             if (point.y + rectDlg.Height() < nVertExt)
  1390.                 rectDlg.OffsetRect(0, 40 + point.y - rectDlg.top);
  1391.         }
  1392.         pDlg->MoveWindow(&rectDlg);
  1393.     }
  1394. }
  1395.  
  1396. void CRichEditView::OnEditFindReplace(BOOL bFindOnly)
  1397. {
  1398.     ASSERT_VALID(this);
  1399.     m_bFirstSearch = TRUE;
  1400.     _AFX_RICHEDIT_STATE* pEditState = _afxRichEditState;
  1401.     if (pEditState->pFindReplaceDlg != NULL)
  1402.     {
  1403.         if (pEditState->bFindOnly == bFindOnly)
  1404.         {
  1405.             pEditState->pFindReplaceDlg->SetActiveWindow();
  1406.             pEditState->pFindReplaceDlg->ShowWindow(SW_SHOW);
  1407.             return;
  1408.         }
  1409.         else
  1410.         {
  1411.             ASSERT(pEditState->bFindOnly != bFindOnly);
  1412.             pEditState->pFindReplaceDlg->SendMessage(WM_CLOSE);
  1413.             ASSERT(pEditState->pFindReplaceDlg == NULL);
  1414.             ASSERT_VALID(this);
  1415.         }
  1416.     }
  1417.     CString strFind = GetRichEditCtrl().GetSelText();
  1418.     // if selection is empty or spans multiple lines use old find text
  1419.     if (strFind.IsEmpty() || (strFind.FindOneOf(_T("\n\r")) != -1))
  1420.         strFind = pEditState->strFind;
  1421.     CString strReplace = pEditState->strReplace;
  1422.     pEditState->pFindReplaceDlg = new CFindReplaceDialog;
  1423.     ASSERT(pEditState->pFindReplaceDlg != NULL);
  1424.     DWORD dwFlags = NULL;
  1425.     if (pEditState->bNext)
  1426.         dwFlags |= FR_DOWN;
  1427.     if (pEditState->bCase)
  1428.         dwFlags |= FR_MATCHCASE;
  1429.     if (pEditState->bWord)
  1430.         dwFlags |= FR_WHOLEWORD;
  1431.     // hide stuff that RichEdit doesn't support
  1432.     dwFlags |= FR_HIDEUPDOWN;
  1433.     if (!pEditState->pFindReplaceDlg->Create(bFindOnly, strFind,
  1434.         strReplace, dwFlags, this))
  1435.     {
  1436.         pEditState->pFindReplaceDlg = NULL;
  1437.         ASSERT_VALID(this);
  1438.         return;
  1439.     }
  1440.     ASSERT(pEditState->pFindReplaceDlg != NULL);
  1441.     pEditState->bFindOnly = bFindOnly;
  1442.     pEditState->pFindReplaceDlg->SetActiveWindow();
  1443.     pEditState->pFindReplaceDlg->ShowWindow(SW_SHOW);
  1444.     ASSERT_VALID(this);
  1445. }
  1446.  
  1447. void CRichEditView::OnFindNext(LPCTSTR lpszFind, BOOL bNext, BOOL bCase, BOOL bWord)
  1448. {
  1449.     ASSERT_VALID(this);
  1450.  
  1451.     _AFX_RICHEDIT_STATE* pEditState = _afxRichEditState;
  1452.     pEditState->strFind = lpszFind;
  1453.     pEditState->bCase = bCase;
  1454.     pEditState->bWord = bWord;
  1455.     pEditState->bNext = bNext;
  1456.  
  1457.     if (!FindText(pEditState))
  1458.         TextNotFound(pEditState->strFind);
  1459.     else
  1460.         AdjustDialogPosition(pEditState->pFindReplaceDlg);
  1461.     ASSERT_VALID(this);
  1462. }
  1463.  
  1464. void CRichEditView::OnReplaceSel(LPCTSTR lpszFind, BOOL bNext, BOOL bCase,
  1465.     BOOL bWord, LPCTSTR lpszReplace)
  1466. {
  1467.     ASSERT_VALID(this);
  1468.     _AFX_RICHEDIT_STATE* pEditState = _afxRichEditState;
  1469.     pEditState->strFind = lpszFind;
  1470.     pEditState->strReplace = lpszReplace;
  1471.     pEditState->bCase = bCase;
  1472.     pEditState->bWord = bWord;
  1473.     pEditState->bNext = bNext;
  1474.  
  1475.     if (!SameAsSelected(pEditState->strFind, pEditState->bCase, pEditState->bWord))
  1476.     {
  1477.         if (!FindText(pEditState))
  1478.             TextNotFound(pEditState->strFind);
  1479.         else
  1480.             AdjustDialogPosition(pEditState->pFindReplaceDlg);
  1481.         return;
  1482.     }
  1483.  
  1484.     GetRichEditCtrl().ReplaceSel(pEditState->strReplace);
  1485.     if (!FindText(pEditState))
  1486.         TextNotFound(pEditState->strFind);
  1487.     else
  1488.         AdjustDialogPosition(pEditState->pFindReplaceDlg);
  1489.     ASSERT_VALID(this);
  1490. }
  1491.  
  1492. void CRichEditView::OnReplaceAll(LPCTSTR lpszFind, LPCTSTR lpszReplace, BOOL bCase, BOOL bWord)
  1493. {
  1494.     ASSERT_VALID(this);
  1495.     _AFX_RICHEDIT_STATE* pEditState = _afxRichEditState;
  1496.     pEditState->strFind = lpszFind;
  1497.     pEditState->strReplace = lpszReplace;
  1498.     pEditState->bCase = bCase;
  1499.     pEditState->bWord = bWord;
  1500.     pEditState->bNext = TRUE;
  1501.  
  1502.     CWaitCursor wait;
  1503.     // no selection or different than what looking for
  1504.     if (!SameAsSelected(pEditState->strFind, pEditState->bCase, pEditState->bWord))
  1505.     {
  1506.         if (!FindText(pEditState))
  1507.         {
  1508.             TextNotFound(pEditState->strFind);
  1509.             return;
  1510.         }
  1511.     }
  1512.  
  1513.     GetRichEditCtrl().HideSelection(TRUE, FALSE);
  1514.     do
  1515.     {
  1516.         GetRichEditCtrl().ReplaceSel(pEditState->strReplace);
  1517.     } while (FindTextSimple(pEditState));
  1518.     TextNotFound(pEditState->strFind);
  1519.     GetRichEditCtrl().HideSelection(FALSE, FALSE);
  1520.  
  1521.     ASSERT_VALID(this);
  1522. }
  1523.  
  1524. LRESULT CRichEditView::OnFindReplaceCmd(WPARAM, LPARAM lParam)
  1525. {
  1526.     ASSERT_VALID(this);
  1527.     CFindReplaceDialog* pDialog = CFindReplaceDialog::GetNotifier(lParam);
  1528.     ASSERT(pDialog != NULL);
  1529.     _AFX_RICHEDIT_STATE* pEditState = _afxRichEditState;
  1530.     ASSERT(pDialog == pEditState->pFindReplaceDlg);
  1531.     if (pDialog->IsTerminating())
  1532.         pEditState->pFindReplaceDlg = NULL;
  1533.     else if (pDialog->FindNext())
  1534.     {
  1535.         OnFindNext(pDialog->GetFindString(), pDialog->SearchDown(),
  1536.             pDialog->MatchCase(), pDialog->MatchWholeWord());
  1537.     }
  1538.     else if (pDialog->ReplaceCurrent())
  1539.     {
  1540.         ASSERT(!pEditState->bFindOnly);
  1541.         OnReplaceSel(pDialog->GetFindString(),
  1542.             pDialog->SearchDown(), pDialog->MatchCase(), pDialog->MatchWholeWord(),
  1543.             pDialog->GetReplaceString());
  1544.     }
  1545.     else if (pDialog->ReplaceAll())
  1546.     {
  1547.         ASSERT(!pEditState->bFindOnly);
  1548.         OnReplaceAll(pDialog->GetFindString(), pDialog->GetReplaceString(),
  1549.             pDialog->MatchCase(), pDialog->MatchWholeWord());
  1550.     }
  1551.     ASSERT_VALID(this);
  1552.     return 0;
  1553. }
  1554.  
  1555. BOOL CRichEditView::SameAsSelected(LPCTSTR lpszCompare, BOOL bCase, BOOL /*bWord*/)
  1556. {
  1557.     // check length first
  1558.     size_t nLen = lstrlen(lpszCompare);
  1559.     long lStartChar, lEndChar;
  1560.     GetRichEditCtrl().GetSel(lStartChar, lEndChar);
  1561.     if (nLen != (size_t)(lEndChar - lStartChar))
  1562.         return FALSE;
  1563.  
  1564.     // length is the same, check contents
  1565.     CString strSelect = GetRichEditCtrl().GetSelText();
  1566.     return (bCase && lstrcmp(lpszCompare, strSelect) == 0) ||
  1567.         (!bCase && lstrcmpi(lpszCompare, strSelect) == 0);
  1568. }
  1569.  
  1570. BOOL CRichEditView::FindText(_AFX_RICHEDIT_STATE* pEditState)
  1571. {
  1572.     ASSERT(pEditState != NULL);
  1573.     return FindText(pEditState->strFind, pEditState->bCase, pEditState->bWord);
  1574. }
  1575.  
  1576. BOOL CRichEditView::FindText(LPCTSTR lpszFind, BOOL bCase, BOOL bWord)
  1577. {
  1578.     ASSERT_VALID(this);
  1579.     CWaitCursor wait;
  1580.     return FindTextSimple(lpszFind, bCase, bWord);
  1581. }
  1582.  
  1583. BOOL CRichEditView::FindTextSimple(_AFX_RICHEDIT_STATE* pEditState)
  1584. {
  1585.     ASSERT(pEditState != NULL);
  1586.     return FindTextSimple(pEditState->strFind, pEditState->bCase, pEditState->bWord);
  1587. }
  1588.  
  1589. BOOL CRichEditView::FindTextSimple(LPCTSTR lpszFind, BOOL bCase, BOOL bWord)
  1590. {
  1591.     USES_CONVERSION;
  1592.     ASSERT(lpszFind != NULL);
  1593.     FINDTEXTEX ft;
  1594.  
  1595.     GetRichEditCtrl().GetSel(ft.chrg);
  1596.     if (m_bFirstSearch)
  1597.     {
  1598.         m_lInitialSearchPos = ft.chrg.cpMin;
  1599.         m_bFirstSearch = FALSE;
  1600.     }
  1601.  
  1602.     ft.lpstrText = T2A((LPTSTR)lpszFind);
  1603.     if (ft.chrg.cpMin != ft.chrg.cpMax) // i.e. there is a selection
  1604.     {
  1605.  
  1606. #ifndef _UNICODE
  1607.         // If byte at beginning of selection is a DBCS lead byte,
  1608.         // increment by one extra byte.
  1609.         TEXTRANGE textRange;
  1610.         TCHAR ch[2];
  1611.         textRange.chrg.cpMin = ft.chrg.cpMin;
  1612.         textRange.chrg.cpMax = ft.chrg.cpMin + 1;
  1613.         textRange.lpstrText = ch;
  1614.         GetRichEditCtrl().SendMessage(EM_GETTEXTRANGE, 0, (LPARAM)&textRange);
  1615.         if (_istlead(ch[0]))
  1616.         {
  1617.             ASSERT(ft.chrg.cpMax - ft.chrg.cpMin >= 2);
  1618.             ft.chrg.cpMin++;
  1619.         }
  1620. #endif
  1621.  
  1622.         ft.chrg.cpMin++;
  1623.     }
  1624.  
  1625.     if (m_lInitialSearchPos >= 0)
  1626.         ft.chrg.cpMax = GetTextLength();
  1627.     else
  1628.         ft.chrg.cpMax = GetTextLength()+m_lInitialSearchPos;
  1629.  
  1630.     DWORD dwFlags = bCase ? FR_MATCHCASE : 0;
  1631.     dwFlags |= bWord ? FR_WHOLEWORD : 0;
  1632.  
  1633.     // if we find the text return TRUE
  1634.     if (FindAndSelect(dwFlags, ft) != -1)
  1635.         return TRUE;
  1636.     // if the original starting point was not the beginning of the buffer
  1637.     // and we haven't already been here
  1638.     else if (m_lInitialSearchPos > 0)
  1639.     {
  1640.         ft.chrg.cpMin = 0;
  1641.         ft.chrg.cpMax = m_lInitialSearchPos;
  1642.         m_lInitialSearchPos = m_lInitialSearchPos - GetTextLength();
  1643.         return (FindAndSelect(dwFlags, ft) == -1) ? FALSE : TRUE;
  1644.     }
  1645.     // not found
  1646.     else
  1647.         return FALSE;
  1648. }
  1649.  
  1650. long CRichEditView::FindAndSelect(DWORD dwFlags, FINDTEXTEX& ft)
  1651. {
  1652.     long index = GetRichEditCtrl().FindText(dwFlags, &ft);
  1653.     if (index != -1) // i.e. we found something
  1654.         GetRichEditCtrl().SetSel(ft.chrgText);
  1655.     return index;
  1656. }
  1657.  
  1658. void CRichEditView::TextNotFound(LPCTSTR lpszFind)
  1659. {
  1660.     ASSERT_VALID(this);
  1661.     m_bFirstSearch = TRUE;
  1662.     OnTextNotFound(lpszFind);
  1663. }
  1664.  
  1665. void CRichEditView::OnTextNotFound(LPCTSTR)
  1666. {
  1667.     MessageBeep(MB_ICONHAND);
  1668. }
  1669.  
  1670. /////////////////////////////////////////////////////////////////////////////
  1671. // CRichEditView diagnostics
  1672.  
  1673. #ifdef _DEBUG
  1674. void CRichEditView::AssertValid() const
  1675. {
  1676.     CCtrlView::AssertValid();
  1677.     ASSERT_VALID(&m_aPageStart);
  1678.     _AFX_RICHEDIT_STATE* pEditState = _afxRichEditState;
  1679.     if (pEditState->pFindReplaceDlg != NULL)
  1680.         ASSERT_VALID(pEditState->pFindReplaceDlg);
  1681. }
  1682.  
  1683. void CRichEditView::Dump(CDumpContext& dc) const
  1684. {
  1685.     CCtrlView::Dump(dc);
  1686.     AFX_DUMP1(dc, "\nm_aPageStart ", &m_aPageStart);
  1687.     AFX_DUMP0(dc, "\n Static Member Data:");
  1688.     _AFX_RICHEDIT_STATE* pEditState = _afxRichEditState;
  1689.     if (pEditState->pFindReplaceDlg != NULL)
  1690.     {
  1691.         AFX_DUMP1(dc, "\npFindReplaceDlg = ",
  1692.             (void*)pEditState->pFindReplaceDlg);
  1693.         AFX_DUMP1(dc, "\nbFindOnly = ", pEditState->bFindOnly);
  1694.     }
  1695.     AFX_DUMP1(dc, "\nstrFind = ", pEditState->strFind);
  1696.     AFX_DUMP1(dc, "\nstrReplace = ", pEditState->strReplace);
  1697.     AFX_DUMP1(dc, "\nbCase = ", pEditState->bCase);
  1698.     AFX_DUMP1(dc, "\nbWord = ", pEditState->bWord);
  1699.     AFX_DUMP1(dc, "\nbNext = ", pEditState->bNext);
  1700. }
  1701. #endif //_DEBUG
  1702.  
  1703. /////////////////////////////////////////////////////////////////////////////
  1704. // OLE Client support and commands
  1705.  
  1706. BOOL CRichEditView::IsSelected(const CObject* pDocItem) const
  1707. {
  1708.     return (pDocItem == GetSelectedItem());
  1709. }
  1710.  
  1711. /////////////////////////////////////////////////////////////////////////////
  1712. // CRichEditDoc
  1713.  
  1714. CRichEditDoc::CRichEditDoc()
  1715. {
  1716.     m_bRTF = TRUE;
  1717.     m_bUpdateObjectCache = FALSE;
  1718.     ASSERT_VALID(this);
  1719. }
  1720.  
  1721. CRichEditView* CRichEditDoc::GetView() const
  1722. {
  1723.     // find the first view - if there are no views
  1724.     // we must return NULL
  1725.  
  1726.     POSITION pos = GetFirstViewPosition();
  1727.     if (pos == NULL)
  1728.         return NULL;
  1729.  
  1730.     // find the first view that is a CRichEditView
  1731.  
  1732.     CView* pView;
  1733.     while (pos != NULL)
  1734.     {
  1735.         pView = GetNextView(pos);
  1736.         if (pView->IsKindOf(RUNTIME_CLASS(CRichEditView)))
  1737.             return (CRichEditView*) pView;
  1738.     }
  1739.  
  1740.     // can't find one--return NULL
  1741.  
  1742.     return NULL;
  1743. }
  1744.  
  1745. BOOL CRichEditDoc::IsModified()
  1746. {
  1747.     return GetView()->GetRichEditCtrl().GetModify();
  1748. }
  1749.  
  1750. void CRichEditDoc::SetModifiedFlag(BOOL bModified)
  1751. {
  1752.     GetView()->GetRichEditCtrl().SetModify(bModified);
  1753.     ASSERT(!!GetView()->GetRichEditCtrl().GetModify() == !!bModified);
  1754. }
  1755.  
  1756. COleClientItem* CRichEditDoc::GetInPlaceActiveItem(CWnd* pWnd)
  1757. {
  1758.     ASSERT_KINDOF(CRichEditView, pWnd);
  1759.     CRichEditView* pView = (CRichEditView*)pWnd;
  1760.     return pView->GetInPlaceActiveItem();
  1761. }
  1762.  
  1763. void CRichEditDoc::SetPathName(LPCTSTR lpszPathName, BOOL bAddToMRU)
  1764. {
  1765.     // we call CDocument and not COleServerDoc because we don't want to do the
  1766.     // SetHostNames stuff here.  The richedit will do it. And we tell the richedit
  1767.     // in SetTitle
  1768.     CDocument::SetPathName(lpszPathName, bAddToMRU);
  1769. }
  1770.  
  1771. void CRichEditDoc::SetTitle(LPCTSTR lpszTitle)
  1772. {
  1773.     USES_CONVERSION;
  1774.     COleServerDoc::SetTitle(lpszTitle);
  1775.     CRichEditView *pView = GetView();
  1776.     ASSERT(pView != NULL);
  1777.     ASSERT(pView->m_lpRichEditOle != NULL);
  1778.     pView->m_lpRichEditOle->SetHostNames(T2CA(AfxGetAppName()),
  1779.         T2CA(lpszTitle));
  1780. }
  1781.  
  1782. CRichEditCntrItem* CRichEditDoc::LookupItem(LPOLEOBJECT lpobj) const
  1783. {
  1784.     POSITION pos = COleServerDoc::GetStartPosition();
  1785.     CRichEditCntrItem* pItem;
  1786.     while (pos != NULL)
  1787.     {
  1788.         pItem = (CRichEditCntrItem*) COleServerDoc::GetNextItem(pos);
  1789.         // delete item is right type and not under construction
  1790.         if (pItem->IsKindOf(RUNTIME_CLASS(CRichEditCntrItem)) &&
  1791.             pItem->m_lpObject == lpobj)
  1792.         {
  1793.             return pItem;
  1794.         }
  1795.     }
  1796.     return NULL;
  1797. }
  1798.  
  1799. CRichEditCntrItem* CRichEditDoc::CreateClientItem(REOBJECT* preo) const
  1800. {
  1801.     // cast away constness of this
  1802.     return new CRichEditCntrItem(preo, (CRichEditDoc*)this);
  1803.     // a derived class typically needs  to return its own item of a class
  1804.     // derived from CRichEditCntrItem
  1805. }
  1806.  
  1807. void CRichEditDoc::MarkItemsClear() const
  1808. {
  1809.     POSITION pos = COleServerDoc::GetStartPosition();
  1810.     CRichEditCntrItem* pItem;
  1811.     while (pos != NULL)
  1812.     {
  1813.         pItem = (CRichEditCntrItem*) COleServerDoc::GetNextItem(pos);
  1814.         // Mark item as not in use unless under construction (i.e. m_lpObject == NULL)
  1815.         if (pItem->IsKindOf(RUNTIME_CLASS(CRichEditCntrItem)))
  1816.             pItem->Mark( (pItem->m_lpObject == NULL) ? TRUE : FALSE);
  1817.     }
  1818. }
  1819.  
  1820. void CRichEditDoc::DeleteUnmarkedItems() const
  1821. {
  1822.     POSITION pos = COleServerDoc::GetStartPosition();
  1823.     CRichEditCntrItem* pItem;
  1824.     while (pos != NULL)
  1825.     {
  1826.         pItem = (CRichEditCntrItem*) COleServerDoc::GetNextItem(pos);
  1827.         // Mark item as not in use unless under construction (i.e. m_lpObject == NULL)
  1828.         if (pItem->IsKindOf(RUNTIME_CLASS(CRichEditCntrItem)) && !pItem->IsMarked())
  1829.             delete pItem;
  1830.     }
  1831. }
  1832.  
  1833. POSITION CRichEditDoc::GetStartPosition() const
  1834. {
  1835.     if (m_bUpdateObjectCache)
  1836.         ((CRichEditDoc*)this)->UpdateObjectCache(); //cast away const
  1837.     return COleServerDoc::GetStartPosition();
  1838. }
  1839.  
  1840. void CRichEditDoc::UpdateObjectCache()
  1841. {
  1842.     CRichEditView* pView = GetView();
  1843.     CRichEditCntrItem* pItem;
  1844.     if (pView != NULL)
  1845.     {
  1846.         ASSERT(pView->m_lpRichEditOle != NULL);
  1847.         MarkItemsClear();
  1848.         long i,nCount = pView->m_lpRichEditOle->GetObjectCount();
  1849.         for (i=0;i<nCount;i++)
  1850.         {
  1851.             CReObject reo; // needs to be in here so destructor called to release interfaces
  1852.             HRESULT hr = pView->m_lpRichEditOle->GetObject(i, &reo, REO_GETOBJ_ALL_INTERFACES);
  1853.             //reo interfaces are UNICODE
  1854.             ASSERT(SUCCEEDED(hr));
  1855.             if (GetScode(hr) == S_OK)
  1856.             {
  1857.                 pItem = LookupItem(reo.poleobj);
  1858.                 if (pItem == NULL)
  1859.                 {
  1860.                     pItem = ((CRichEditDoc*)this)->CreateClientItem(&reo);
  1861.                     pItem->UpdateItemType();
  1862.                 }
  1863.                 ASSERT(pItem != NULL);
  1864.                 pItem->Mark(TRUE);
  1865.             }
  1866.         }
  1867.         DeleteUnmarkedItems();
  1868.     }
  1869.     m_bUpdateObjectCache = FALSE;
  1870. }
  1871. /////////////////////////////////////////////////////////////////////////////
  1872. // CRichEditDoc Attributes
  1873.  
  1874. COleClientItem* CRichEditDoc::GetPrimarySelectedItem(CView* pView)
  1875. {
  1876.     ASSERT(pView->IsKindOf(RUNTIME_CLASS(CRichEditView)));
  1877.     return ((CRichEditView*)pView)->GetSelectedItem();
  1878. }
  1879.  
  1880. /////////////////////////////////////////////////////////////////////////////
  1881. // CRichEditDoc Operations
  1882.  
  1883. void CRichEditDoc::DeleteContents()
  1884. {
  1885.     COleServerDoc::DeleteContents();
  1886.     CWaitCursor wait;
  1887.     CRichEditView *pView = GetView();
  1888.     if (pView != NULL)
  1889.     {
  1890.         pView->DeleteContents();
  1891.         pView->GetRichEditCtrl().SetModify(FALSE);
  1892.         ASSERT(pView->GetRichEditCtrl().GetModify() == FALSE);
  1893.     }
  1894. }
  1895.  
  1896. /////////////////////////////////////////////////////////////////////////////
  1897. // CRichEditDoc serialization
  1898.  
  1899. void CRichEditDoc::Serialize(CArchive& ar)
  1900. {
  1901.     CRichEditView *pView = GetView();
  1902.     if (pView != NULL)
  1903.         pView->Serialize(ar);
  1904.     // we don't call the base class COleServerDoc::Serialize
  1905.     // because we don't want the client items serialized
  1906.     // the client items are handled directly by the RichEdit control
  1907. }
  1908.  
  1909. /////////////////////////////////////////////////////////////////////////////
  1910. // CRichEditDoc diagnostics
  1911.  
  1912. #ifdef _DEBUG
  1913. void CRichEditDoc::AssertValid() const
  1914. {
  1915.     COleServerDoc::AssertValid();
  1916. }
  1917.  
  1918. void CRichEditDoc::Dump(CDumpContext& dc) const
  1919. {
  1920.     COleServerDoc::Dump(dc);
  1921. }
  1922. #endif //_DEBUG
  1923.  
  1924. /////////////////////////////////////////////////////////////////////////////
  1925. // CRichEditDoc commands
  1926.  
  1927. void CRichEditDoc::PreCloseFrame(CFrameWnd* pFrameArg)
  1928. {
  1929.     ASSERT_VALID(this);
  1930.     ASSERT_VALID(pFrameArg);
  1931.  
  1932.     // turn off redraw so the user doesn't see the deactivation happening
  1933.     BOOL bSetRedraw = FALSE;
  1934.     if (pFrameArg->GetStyle() & WS_VISIBLE)
  1935.     {
  1936.         pFrameArg->SendMessage(WM_SETREDRAW, (WPARAM)FALSE);
  1937.         bSetRedraw = TRUE;
  1938.     }
  1939.  
  1940.     // deactivate any inplace active items on this frame
  1941.     GetView()->m_lpRichEditOle->InPlaceDeactivate();
  1942.  
  1943.     POSITION pos = GetStartPosition();
  1944.     CRichEditCntrItem* pItem;
  1945.     while (pos != NULL)
  1946.     {
  1947.         pItem = (CRichEditCntrItem*) GetNextClientItem(pos);
  1948.         if (pItem == NULL)
  1949.             break;
  1950.         ASSERT(pItem->IsKindOf(RUNTIME_CLASS(CRichEditCntrItem)));
  1951.         pItem->Close();
  1952.     }
  1953.  
  1954.     // turn redraw back on
  1955.     if (bSetRedraw)
  1956.         pFrameArg->SendMessage(WM_SETREDRAW, (WPARAM)TRUE);
  1957. }
  1958.  
  1959. void CRichEditDoc::UpdateModifiedFlag()
  1960. {
  1961.     // don't do anything here
  1962.     // let the richedit handle all of this
  1963. }
  1964.  
  1965. COleServerItem* CRichEditDoc::OnGetEmbeddedItem()
  1966. {
  1967.     ASSERT(FALSE);
  1968.     return NULL;
  1969. }
  1970.  
  1971. /////////////////////////////////////////////////////////////////////////////
  1972. // CRichEditCntrItem implementation
  1973.  
  1974. CRichEditCntrItem::CRichEditCntrItem(REOBJECT *preo, CRichEditDoc* pContainer)
  1975.     : COleClientItem(pContainer)
  1976. {
  1977.     m_bMark = FALSE;
  1978.     m_bLock = FALSE;
  1979.     if (preo != NULL)
  1980.     {
  1981.         ASSERT(preo->poleobj != NULL);
  1982.         ASSERT(preo->pstg != NULL);
  1983.         ASSERT(preo->polesite != NULL);
  1984.         m_lpObject = preo->poleobj;
  1985.         m_lpStorage = preo->pstg;
  1986.         m_lpClientSite = preo->polesite;
  1987.         m_lpObject->AddRef();
  1988.         m_lpStorage->AddRef();
  1989.         m_lpClientSite->AddRef();
  1990.     }
  1991.     else
  1992.     {
  1993.         m_lpObject = NULL;
  1994.         m_lpStorage = NULL;
  1995.         m_lpClientSite = NULL;
  1996.     }
  1997. }
  1998.  
  1999. CRichEditCntrItem::~CRichEditCntrItem()
  2000. {
  2001.     if (m_lpClientSite != NULL)
  2002.         m_lpClientSite->Release();
  2003. }
  2004.  
  2005. void CRichEditCntrItem::OnDeactivateUI(BOOL bUndoable)
  2006. {
  2007.     CView* pView = GetActiveView();
  2008.     if (pView != NULL)
  2009.     {
  2010.         ASSERT(pView->GetParentFrame() != NULL);
  2011.         pView->GetParentFrame()->SendMessage(WM_SETMESSAGESTRING,
  2012.             (WPARAM)AFX_IDS_IDLEMESSAGE);
  2013.     }
  2014.     COleClientItem::OnDeactivateUI(bUndoable);
  2015. }
  2016.  
  2017. HRESULT CRichEditCntrItem::ShowContainerUI(BOOL b)
  2018. {
  2019.     if (!CanActivate())
  2020.         return E_NOTIMPL;
  2021.     if (b)
  2022.     {
  2023.         OnDeactivateUI(FALSE);
  2024.         OnDeactivate();
  2025.     }
  2026.     else
  2027.     {
  2028.         OnActivate();
  2029.         OnActivateUI();
  2030.     }
  2031.     return S_OK;
  2032. }
  2033.  
  2034. BOOL CRichEditCntrItem::OnChangeItemPosition(const CRect& /*rectPos*/)
  2035. {
  2036.     ASSERT_VALID(this);
  2037.  
  2038.     // richedit handles this
  2039.     return FALSE;
  2040. }
  2041.  
  2042. BOOL CRichEditCntrItem::CanActivate()
  2043. {
  2044.     // Editing in-place while the server itself is being edited in-place
  2045.     //  does not work and is not supported.  So, disable in-place
  2046.     //  activation in this case.
  2047.     COleServerDoc* pDoc = DYNAMIC_DOWNCAST(COleServerDoc, GetDocument());
  2048.     if (pDoc != NULL && pDoc->IsInPlaceActive())
  2049.         return FALSE;
  2050.  
  2051.     // otherwise, rely on default behavior
  2052.     return COleClientItem::CanActivate();
  2053. }
  2054.  
  2055. HRESULT CRichEditCntrItem::GetWindowContext(LPOLEINPLACEFRAME* lplpFrame,
  2056.     LPOLEINPLACEUIWINDOW* lplpDoc, LPOLEINPLACEFRAMEINFO lpFrameInfo)
  2057. {
  2058.     CRect rc1,rc2;
  2059.     if (!CanActivate())
  2060.         return E_NOTIMPL;
  2061.     return m_xOleIPSite.GetWindowContext(lplpFrame, lplpDoc, &rc1, &rc2, lpFrameInfo);
  2062. }
  2063.  
  2064. BOOL CRichEditCntrItem::ConvertTo(REFCLSID clsidNew)
  2065. {
  2066.     USES_CONVERSION;
  2067.     LPRICHEDITOLE preole = GetDocument()->GetView()->m_lpRichEditOle;
  2068.     LPOLESTR lpOleStr;
  2069.     OleRegGetUserType(clsidNew, USERCLASSTYPE_FULL, &lpOleStr);
  2070.     LPCTSTR lpsz = OLE2CT(lpOleStr);
  2071.     HRESULT hRes = preole->ConvertObject(REO_IOB_SELECTION, clsidNew, T2CA(lpsz));
  2072.     CoTaskMemFree(lpOleStr);
  2073.     return (SUCCEEDED(hRes));
  2074. }
  2075.  
  2076. BOOL CRichEditCntrItem::ActivateAs(LPCTSTR, REFCLSID clsidOld,
  2077.     REFCLSID clsidNew)
  2078. {
  2079.     LPRICHEDITOLE preole = GetDocument()->GetView()->m_lpRichEditOle;
  2080.     HRESULT hRes = preole->ActivateAs(clsidOld, clsidNew);
  2081.     return (SUCCEEDED(hRes));
  2082. }
  2083.  
  2084. void CRichEditCntrItem::SetDrawAspect(DVASPECT nDrawAspect)
  2085. {
  2086.     LPRICHEDITOLE preole = GetDocument()->GetView()->m_lpRichEditOle;
  2087.     preole->SetDvaspect(REO_IOB_SELECTION, nDrawAspect);
  2088.     COleClientItem::SetDrawAspect(nDrawAspect);
  2089. }
  2090.  
  2091. void CRichEditCntrItem::SyncToRichEditObject(REOBJECT& reo)
  2092. {
  2093.     COleClientItem::SetDrawAspect((DVASPECT)reo.dvaspect);
  2094. }
  2095.  
  2096. /////////////////////////////////////////////////////////////////////////////
  2097. // CRichEditCntrItem diagnostics
  2098.  
  2099. #ifdef _DEBUG
  2100. void CRichEditCntrItem::AssertValid() const
  2101. {
  2102.     COleClientItem::AssertValid();
  2103. }
  2104.  
  2105. void CRichEditCntrItem::Dump(CDumpContext& dc) const
  2106. {
  2107.     COleClientItem::Dump(dc);
  2108. }
  2109. #endif
  2110.  
  2111. /////////////////////////////////////////////////////////////////////////////
  2112.  
  2113. LPOLECLIENTSITE CRichEditCntrItem::GetClientSite()
  2114. {
  2115.     if (m_lpClientSite == NULL)
  2116.     {
  2117.         CRichEditDoc* pDoc = DYNAMIC_DOWNCAST(CRichEditDoc, GetDocument());
  2118.         CRichEditView* pView = DYNAMIC_DOWNCAST(CRichEditView, pDoc->GetView());
  2119.         ASSERT(pView->m_lpRichEditOle != NULL);
  2120.         HRESULT hr = pView->m_lpRichEditOle->GetClientSite(&m_lpClientSite);
  2121.         if (hr != S_OK)
  2122.             AfxThrowOleException(hr);
  2123.     }
  2124.     ASSERT(m_lpClientSite != NULL);
  2125.     return m_lpClientSite;
  2126. }
  2127.  
  2128. /////////////////////////////////////////////////////////////////////////////
  2129.  
  2130. #ifndef _AFX_ENABLE_INLINES
  2131.  
  2132. static const char _szAfxWinInl[] = "afxrich.inl";
  2133. #undef THIS_FILE
  2134. #define THIS_FILE _szAfxWinInl
  2135. #define _AFXRICH_INLINE
  2136. #include "afxrich.inl"
  2137.  
  2138. #endif //_AFX_ENABLE_INLINES
  2139.  
  2140. /////////////////////////////////////////////////////////////////////////////
  2141.  
  2142. #ifdef AFX_INIT_SEG
  2143. #pragma code_seg(AFX_INIT_SEG)
  2144. #endif
  2145.  
  2146. IMPLEMENT_SERIAL(CRichEditCntrItem, COleClientItem, 0)
  2147. IMPLEMENT_DYNAMIC(CRichEditDoc, COleServerDoc)
  2148. IMPLEMENT_DYNCREATE(CRichEditView, CCtrlView)
  2149.  
  2150. /////////////////////////////////////////////////////////////////////////////
  2151.