The number of characters to be copied must be one less than the buffer size to accoun...
[TortoiseGit.git] / src / TortoiseMerge / BaseView.cpp
blobaae6a700f8ed84e875e24a31728402575b22372a
1 // TortoiseGitMerge - a Diff/Patch program
3 // Copyright (C) 2003-2015 - TortoiseSVN
4 // Copyright (C) 2011-2012 Sven Strickroth <email@cs-ware.de>
6 // This program is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU General Public License
8 // as published by the Free Software Foundation; either version 2
9 // of the License, or (at your option) any later version.
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
16 // You should have received a copy of the GNU General Public License
17 // along with this program; if not, write to the Free Software Foundation,
18 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 #include "stdafx.h"
22 #include "registry.h"
23 #include "TortoiseMerge.h"
24 #include "MainFrm.h"
25 #include "BaseView.h"
26 #include "DiffColors.h"
27 #include "StringUtils.h"
28 #include "AppUtils.h"
29 #include "GotoLineDlg.h"
30 #include "EncodingDlg.h"
31 #include "EditorConfigWrapper.h"
33 // Note about lines:
34 // We use three different kind of lines here:
35 // 1. The real lines of the original files.
36 // These are shown in the view margin and are not used elsewhere, they're only for user information.
37 // 2. Screen lines.
38 // The lines actually shown on screen. All methods use screen lines as parameters/outputs if not explicitly specified otherwise.
39 // 3. View lines.
40 // These are the lines of the diff data. If unmodified sections are collapsed, not all of those lines are shown.
42 // Basically view lines are the line data, while screen lines are shown lines.
45 #ifdef _DEBUG
46 #define new DEBUG_NEW
47 #endif
49 #define MARGINWIDTH 20
50 #define HEADERHEIGHT 10
52 #define IDT_SCROLLTIMER 101
54 CBaseView * CBaseView::m_pwndLeft = NULL;
55 CBaseView * CBaseView::m_pwndRight = NULL;
56 CBaseView * CBaseView::m_pwndBottom = NULL;
57 CLocatorBar * CBaseView::m_pwndLocator = NULL;
58 CLineDiffBar * CBaseView::m_pwndLineDiffBar = NULL;
59 CMFCStatusBar * CBaseView::m_pwndStatusBar = NULL;
60 CMFCRibbonStatusBar * CBaseView::m_pwndRibbonStatusBar = NULL;
61 CMainFrame * CBaseView::m_pMainFrame = NULL;
62 CBaseView::Screen2View CBaseView::m_Screen2View;
63 const UINT CBaseView::m_FindDialogMessage = RegisterWindowMessage(FINDMSGSTRING);
65 allviewstate CBaseView::m_AllState;
67 IMPLEMENT_DYNCREATE(CBaseView, CView)
69 CBaseView::CBaseView()
70 : m_pCacheBitmap(NULL)
71 , m_pViewData(NULL)
72 , m_pOtherViewData(NULL)
73 , m_pOtherView(NULL)
74 , m_nLineHeight(-1)
75 , m_nCharWidth(-1)
76 , m_nScreenChars(-1)
77 , m_nLastScreenChars(-1)
78 , m_nMaxLineLength(-1)
79 , m_nScreenLines(-1)
80 , m_nTopLine(0)
81 , m_nOffsetChar(0)
82 , m_nDigits(0)
83 , m_nMouseLine(-1)
84 , m_mouseInMargin(false)
85 , m_bIsHidden(FALSE)
86 , m_lineendings(EOL_AUTOLINE)
87 , m_bReadonly(true)
88 , m_bReadonlyIsChangable(false)
89 , m_bTarget(false)
90 , m_nCaretGoalPos(0)
91 , m_nSelViewBlockStart(-1)
92 , m_nSelViewBlockEnd(-1)
93 , m_bFocused(FALSE)
94 , m_bShowSelection(true)
95 , m_texttype(CFileTextLines::AUTOTYPE)
96 , m_bModified(FALSE)
97 , m_bOtherDiffChecked(false)
98 , m_bInlineWordDiff(true)
99 , m_bWhitespaceInlineDiffs(false)
100 , m_pState(NULL)
101 , m_pFindDialog(NULL)
102 , m_nStatusBarID(0)
103 , m_bMatchCase(false)
104 , m_bLimitToDiff(true)
105 , m_bWholeWord(false)
106 , m_pDC(NULL)
107 , m_pWorkingFile(NULL)
108 , m_bInsertMode(true)
109 , m_bEditorConfigEnabled(false)
110 , m_bEditorConfigLoaded(2) // 2 = not evaluated
112 m_ptCaretViewPos.x = 0;
113 m_ptCaretViewPos.y = 0;
114 m_ptSelectionViewPosStart = m_ptCaretViewPos;
115 m_ptSelectionViewPosEnd = m_ptSelectionViewPosStart;
116 m_ptSelectionViewPosOrigin = m_ptSelectionViewPosEnd;
117 m_bViewWhitespace = CRegDWORD(_T("Software\\TortoiseGitMerge\\ViewWhitespaces"), 1);
118 m_bViewLinenumbers = CRegDWORD(_T("Software\\TortoiseGitMerge\\ViewLinenumbers"), 1);
119 m_bShowInlineDiff = CRegDWORD(_T("Software\\TortoiseGitMerge\\DisplayBinDiff"), TRUE);
120 m_nInlineDiffMaxLineLength = CRegDWORD(_T("Software\\TortoiseGitMerge\\InlineDiffMaxLineLength"), 3000);
121 m_InlineAddedBk = CRegDWORD(_T("Software\\TortoiseGitMerge\\InlineAdded"), INLINEADDED_COLOR);
122 m_InlineRemovedBk = CRegDWORD(_T("Software\\TortoiseGitMerge\\InlineRemoved"), INLINEREMOVED_COLOR);
123 m_ModifiedBk = CRegDWORD(_T("Software\\TortoiseGitMerge\\Colors\\ColorModifiedB"), MODIFIED_COLOR);
124 m_WhiteSpaceFg = CRegDWORD(_T("Software\\TortoiseGitMerge\\Colors\\Whitespace"), GetSysColor(COLOR_GRAYTEXT));
125 m_sWordSeparators = CRegString(_T("Software\\TortoiseGitMerge\\WordSeparators"), _T("[]();:.,{}!@#$%^&*-+=|/\\<>'`~\"?"));
126 m_bIconLFs = CRegDWORD(_T("Software\\TortoiseGitMerge\\IconLFs"), 0);
127 m_nTabSize = (int)(DWORD)CRegDWORD(_T("Software\\TortoiseGitMerge\\TabSize"), 4);
128 m_nTabMode = (int)(DWORD)CRegDWORD(_T("Software\\TortoiseGitMerge\\TabMode"), TABMODE_NONE);
129 m_bEditorConfigEnabled = !!(DWORD)CRegDWORD(_T("Software\\TortoiseGitMerge\\EnableEditorConfig"), FALSE);
130 std::fill_n(m_apFonts, fontsCount, (CFont*)NULL);
131 m_hConflictedIcon = LoadIcon(IDI_CONFLICTEDLINE);
132 m_hConflictedIgnoredIcon = LoadIcon(IDI_CONFLICTEDIGNOREDLINE);
133 m_hRemovedIcon = LoadIcon(IDI_REMOVEDLINE);
134 m_hAddedIcon = LoadIcon(IDI_ADDEDLINE);
135 m_hWhitespaceBlockIcon = LoadIcon(IDI_WHITESPACELINE);
136 m_hEqualIcon = LoadIcon(IDI_EQUALLINE);
137 m_hLineEndingCR = LoadIcon(IDI_LINEENDINGCR);
138 m_hLineEndingCRLF = LoadIcon(IDI_LINEENDINGCRLF);
139 m_hLineEndingLF = LoadIcon(IDI_LINEENDINGLF);
140 m_hEditedIcon = LoadIcon(IDI_LINEEDITED);
141 m_hMovedIcon = LoadIcon(IDI_MOVEDLINE);
142 m_hMarkedIcon = LoadIcon(IDI_LINEMARKED);
143 m_margincursor = (HCURSOR)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(IDC_MARGINCURSOR), IMAGE_CURSOR, 0, 0, LR_DEFAULTSIZE);
145 for (int i=0; i<1024; ++i)
146 m_sConflictedText += _T("??");
147 m_sNoLineNr.LoadString(IDS_EMPTYLINETT);
149 m_szTip[0] = 0;
150 m_wszTip[0] = 0;
151 SecureZeroMemory(&m_lfBaseFont, sizeof(m_lfBaseFont));
152 EnableToolTips();
154 m_Eols[EOL_LF] = L"\n"; // x0a
155 m_Eols[EOL_CR] = L"\r"; // x0d
156 m_Eols[EOL_CRLF] = L"\r\n"; // x0d x0a
157 m_Eols[EOL_LFCR] = L"\n\r";
158 m_Eols[EOL_VT] = L"\v"; // x0b
159 m_Eols[EOL_FF] = L"\f"; // x0c
160 m_Eols[EOL_NEL] = L"\x85";
161 m_Eols[EOL_LS] = L"\x2028";
162 m_Eols[EOL_PS] = L"\x2029";
163 m_Eols[EOL_AUTOLINE] = m_Eols[m_lineendings==EOL_AUTOLINE
164 ? EOL_CRLF
165 : m_lineendings];
166 m_SaveParams.m_LineEndings = EOL::EOL_AUTOLINE;
167 m_SaveParams.m_UnicodeType = CFileTextLines::AUTOTYPE;
170 CBaseView::~CBaseView()
172 ReleaseBitmap();
173 DeleteFonts();
174 DestroyIcon(m_hAddedIcon);
175 DestroyIcon(m_hRemovedIcon);
176 DestroyIcon(m_hConflictedIcon);
177 DestroyIcon(m_hConflictedIgnoredIcon);
178 DestroyIcon(m_hWhitespaceBlockIcon);
179 DestroyIcon(m_hEqualIcon);
180 DestroyIcon(m_hLineEndingCR);
181 DestroyIcon(m_hLineEndingCRLF);
182 DestroyIcon(m_hLineEndingLF);
183 DestroyIcon(m_hEditedIcon);
184 DestroyIcon(m_hMovedIcon);
185 DestroyIcon(m_hMarkedIcon);
186 DestroyCursor(m_margincursor);
189 BEGIN_MESSAGE_MAP(CBaseView, CView)
190 ON_WM_VSCROLL()
191 ON_WM_HSCROLL()
192 ON_WM_ERASEBKGND()
193 ON_WM_CREATE()
194 ON_WM_DESTROY()
195 ON_WM_SIZE()
196 ON_WM_MOUSEWHEEL()
197 ON_WM_MOUSEHWHEEL()
198 ON_WM_SETCURSOR()
199 ON_WM_KILLFOCUS()
200 ON_WM_SETFOCUS()
201 ON_WM_CONTEXTMENU()
202 ON_COMMAND(ID_NAVIGATE_NEXTDIFFERENCE, OnMergeNextdifference)
203 ON_COMMAND(ID_NAVIGATE_PREVIOUSDIFFERENCE, OnMergePreviousdifference)
204 ON_NOTIFY_EX_RANGE(TTN_NEEDTEXTW, 0, 0xFFFF, OnToolTipNotify)
205 ON_NOTIFY_EX_RANGE(TTN_NEEDTEXTA, 0, 0xFFFF, OnToolTipNotify)
206 ON_WM_KEYDOWN()
207 ON_WM_LBUTTONDOWN()
208 ON_COMMAND(ID_EDIT_COPY, OnEditCopy)
209 ON_WM_MOUSEMOVE()
210 ON_COMMAND(ID_NAVIGATE_PREVIOUSCONFLICT, OnMergePreviousconflict)
211 ON_COMMAND(ID_NAVIGATE_NEXTCONFLICT, OnMergeNextconflict)
212 ON_WM_CHAR()
213 ON_COMMAND(ID_CARET_DOWN, &CBaseView::OnCaretDown)
214 ON_COMMAND(ID_CARET_LEFT, &CBaseView::OnCaretLeft)
215 ON_COMMAND(ID_CARET_RIGHT, &CBaseView::OnCaretRight)
216 ON_COMMAND(ID_CARET_UP, &CBaseView::OnCaretUp)
217 ON_COMMAND(ID_CARET_WORDLEFT, &CBaseView::OnCaretWordleft)
218 ON_COMMAND(ID_CARET_WORDRIGHT, &CBaseView::OnCaretWordright)
219 ON_COMMAND(ID_EDIT_CUT, &CBaseView::OnEditCut)
220 ON_COMMAND(ID_EDIT_PASTE, &CBaseView::OnEditPaste)
221 ON_WM_TIMER()
222 ON_WM_LBUTTONDBLCLK()
223 ON_COMMAND(ID_NAVIGATE_NEXTINLINEDIFF, &CBaseView::OnNavigateNextinlinediff)
224 ON_COMMAND(ID_NAVIGATE_PREVINLINEDIFF, &CBaseView::OnNavigatePrevinlinediff)
225 ON_COMMAND(ID_EDIT_SELECTALL, &CBaseView::OnEditSelectall)
226 ON_COMMAND(ID_EDIT_FIND, OnEditFind)
227 ON_REGISTERED_MESSAGE(m_FindDialogMessage, OnFindDialogMessage)
228 ON_COMMAND(ID_EDIT_FINDNEXT, OnEditFindnext)
229 ON_COMMAND(ID_EDIT_FINDPREV, OnEditFindprev)
230 ON_COMMAND(ID_EDIT_FINDNEXTSTART, OnEditFindnextStart)
231 ON_COMMAND(ID_EDIT_FINDPREVSTART, OnEditFindprevStart)
232 ON_COMMAND(ID_EDIT_GOTOLINE, &CBaseView::OnEditGotoline)
233 ON_WM_LBUTTONUP()
234 END_MESSAGE_MAP()
237 void CBaseView::DocumentUpdated()
239 ReleaseBitmap();
240 m_nLineHeight = -1;
241 m_nCharWidth = -1;
242 m_nScreenChars = -1;
243 m_nLastScreenChars = -1;
244 m_nMaxLineLength = -1;
245 m_nScreenLines = -1;
246 m_nTopLine = 0;
247 m_bModified = FALSE;
248 m_bOtherDiffChecked = false;
249 m_nDigits = 0;
250 m_nMouseLine = -1;
251 m_nTabSize = (int)(DWORD)CRegDWORD(_T("Software\\TortoiseGitMerge\\TabSize"), 4);
252 m_nTabMode = (int)(DWORD)CRegDWORD(_T("Software\\TortoiseGitMerge\\TabMode"), TABMODE_NONE);
253 m_bViewLinenumbers = CRegDWORD(_T("Software\\TortoiseGitMerge\\ViewLinenumbers"), 1);
254 m_InlineAddedBk = CRegDWORD(_T("Software\\TortoiseGitMerge\\InlineAdded"), INLINEADDED_COLOR);
255 m_InlineRemovedBk = CRegDWORD(_T("Software\\TortoiseGitMerge\\InlineRemoved"), INLINEREMOVED_COLOR);
256 m_ModifiedBk = CRegDWORD(_T("Software\\TortoiseGitMerge\\Colors\\ColorModifiedB"), MODIFIED_COLOR);
257 m_WhiteSpaceFg = CRegDWORD(_T("Software\\TortoiseGitMerge\\Colors\\Whitespace"), GetSysColor(COLOR_GRAYTEXT));
258 m_bIconLFs = CRegDWORD(_T("Software\\TortoiseGitMerge\\IconLFs"), 0);
259 m_nInlineDiffMaxLineLength = CRegDWORD(_T("Software\\TortoiseGitMerge\\InlineDiffMaxLineLength"), 3000);
260 m_Eols[EOL_AUTOLINE] = m_Eols[m_lineendings==EOL_AUTOLINE
261 ? EOL_CRLF
262 : m_lineendings];
263 SetEditorConfigEnabled(m_bEditorConfigEnabled);
264 DeleteFonts();
265 ClearCurrentSelection();
266 UpdateStatusBar();
267 Invalidate();
270 void CBaseView::SetEditorConfigEnabled(bool bEditorConfigEnabled)
272 m_bEditorConfigEnabled = bEditorConfigEnabled;
273 m_nTabSize = (int)(DWORD)CRegDWORD(_T("Software\\TortoiseGitMerge\\TabSize"), 4);
274 m_nTabMode = (int)(DWORD)CRegDWORD(_T("Software\\TortoiseGitMerge\\TabMode"), TABMODE_NONE);
275 if (m_bEditorConfigEnabled)
277 m_bEditorConfigLoaded = FALSE; // no editorconfig entries loaded
278 CEditorConfigWrapper ec;
279 if (ec.Load(m_sReflectedName.IsEmpty() ? m_sFullFilePath : m_sReflectedName))
281 m_bEditorConfigLoaded = TRUE;
282 if (ec.m_nTabWidth != nullptr)
283 m_nTabSize = ec.m_nTabWidth;
284 if (ec.m_bIndentStyle != nullptr)
285 m_nTabMode = (m_nTabMode & ~TABMODE_USESPACES) | (ec.m_bIndentStyle ? TABMODE_USESPACES : TABMODE_NONE);
290 static CString GetTabModeString(int nTabMode, int nTabSize, bool bEditorConfig)
292 CString text;
293 if (nTabMode & TABMODE_USESPACES)
294 text = L"Space";
295 else
296 text = L"Tab";
297 text.AppendFormat(L" %d", nTabSize);
298 if (nTabMode & TABMODE_SMARTINDENT)
299 text += L" Smart";
300 if (bEditorConfig)
301 text += L" EC";
302 return text;
305 void CBaseView::UpdateStatusBar()
307 int nRemovedLines = 0;
308 int nAddedLines = 0;
309 int nConflictedLines = 0;
311 if (m_pViewData)
313 for (int i=0; i<m_pViewData->GetCount(); i++)
315 DiffStates state = m_pViewData->GetState(i);
316 switch (state)
318 case DIFFSTATE_ADDED:
319 case DIFFSTATE_IDENTICALADDED:
320 case DIFFSTATE_THEIRSADDED:
321 case DIFFSTATE_YOURSADDED:
322 case DIFFSTATE_CONFLICTADDED:
323 nAddedLines++;
324 break;
325 case DIFFSTATE_IDENTICALREMOVED:
326 case DIFFSTATE_REMOVED:
327 case DIFFSTATE_THEIRSREMOVED:
328 case DIFFSTATE_YOURSREMOVED:
329 nRemovedLines++;
330 break;
331 case DIFFSTATE_CONFLICTED:
332 case DIFFSTATE_CONFLICTED_IGNORED:
333 nConflictedLines++;
334 break;
339 CString sBarText;
340 CString sTemp;
342 if (m_pwndStatusBar)
344 sBarText += CFileTextLines::GetEncodingName(m_texttype);
345 sBarText += sBarText.IsEmpty() ? L"" : L" ";
346 sBarText += GetEolName(m_lineendings);
347 sBarText += sBarText.IsEmpty() ? L"" : L" ";
349 if (sBarText.IsEmpty())
350 sBarText += _T(" / ");
353 if (nRemovedLines)
355 sTemp.Format(IDS_STATUSBAR_REMOVEDLINES, nRemovedLines);
356 if (!sBarText.IsEmpty())
357 sBarText += _T(" / ");
358 sBarText += sTemp;
360 if (nAddedLines)
362 sTemp.Format(IDS_STATUSBAR_ADDEDLINES, nAddedLines);
363 if (!sBarText.IsEmpty())
364 sBarText += _T(" / ");
365 sBarText += sTemp;
367 if (nConflictedLines)
369 sTemp.Format(IDS_STATUSBAR_CONFLICTEDLINES, nConflictedLines);
370 if (!sBarText.IsEmpty())
371 sBarText += _T(" / ");
372 sBarText += sTemp;
374 if (m_pwndStatusBar || m_pwndRibbonStatusBar)
376 if (m_pwndStatusBar)
378 UINT nID;
379 UINT nStyle;
380 int cxWidth;
381 if (m_nStatusBarID == ID_INDICATOR_BOTTOMVIEW)
383 sBarText.Format(IDS_STATUSBAR_CONFLICTS, nConflictedLines);
385 if (m_nStatusBarID == ID_INDICATOR_LEFTVIEW)
387 sTemp.LoadString(IDS_STATUSBAR_LEFTVIEW);
388 sBarText = sTemp+sBarText;
390 if (m_nStatusBarID == ID_INDICATOR_RIGHTVIEW)
392 sTemp.LoadString(IDS_STATUSBAR_RIGHTVIEW);
393 sBarText = sTemp+sBarText;
395 int nIndex = m_pwndStatusBar->CommandToIndex(m_nStatusBarID);
396 m_pwndStatusBar->GetPaneInfo(nIndex, nID, nStyle, cxWidth);
397 //calculate the width of the text
398 CDC * pDC = m_pwndStatusBar->GetDC();
399 if (pDC)
401 CSize size = pDC->GetTextExtent(sBarText);
402 m_pwndStatusBar->SetPaneInfo(nIndex, nID, nStyle, size.cx+2);
403 ReleaseDC(pDC);
405 m_pwndStatusBar->SetPaneText(nIndex, sBarText);
407 else if (m_pwndRibbonStatusBar)
409 if (!IsViewGood(m_pwndBottom))
410 m_pwndRibbonStatusBar->RemoveElement(ID_INDICATOR_BOTTOMVIEW);
411 if ((m_nStatusBarID == ID_INDICATOR_BOTTOMVIEW) && (IsViewGood(this)))
413 m_pwndRibbonStatusBar->RemoveElement(ID_INDICATOR_BOTTOMVIEW);
414 std::unique_ptr<CMFCRibbonButtonsGroup> apBtnGroupBottom(new CMFCRibbonButtonsGroup);
415 apBtnGroupBottom->SetID(ID_INDICATOR_BOTTOMVIEW);
416 apBtnGroupBottom->AddButton(new CMFCRibbonStatusBarPane(ID_SEPARATOR, CString(MAKEINTRESOURCE(IDS_STATUSBAR_BOTTOMVIEW)), TRUE));
417 CMFCRibbonButton * pButton = new CMFCRibbonButton(ID_INDICATOR_BOTTOMVIEWCOMBOENCODING, L"");
418 m_pMainFrame->FillEncodingButton(pButton, ID_INDICATOR_BOTTOMENCODINGSTART);
419 apBtnGroupBottom->AddButton(pButton);
420 pButton = new CMFCRibbonButton(ID_INDICATOR_BOTTOMVIEWCOMBOEOL, L"");
421 m_pMainFrame->FillEOLButton(pButton, ID_INDICATOR_BOTTOMEOLSTART);
422 apBtnGroupBottom->AddButton(pButton);
423 pButton = new CMFCRibbonButton(ID_INDICATOR_BOTTOMVIEWCOMBOTABMODE, L"");
424 m_pMainFrame->FillEOLButton(pButton, ID_INDICATOR_BOTTOMTABMODESTART);
425 apBtnGroupBottom->AddButton(pButton);
426 apBtnGroupBottom->AddButton(new CMFCRibbonStatusBarPane(ID_INDICATOR_BOTTOMVIEW, L"", TRUE));
427 m_pwndRibbonStatusBar->AddExtendedElement(apBtnGroupBottom.release(), L"");
430 CMFCRibbonButtonsGroup * pGroup = DYNAMIC_DOWNCAST(CMFCRibbonButtonsGroup, m_pwndRibbonStatusBar->FindByID(m_nStatusBarID));
431 if (pGroup)
433 CMFCRibbonStatusBarPane* pPane = DYNAMIC_DOWNCAST(CMFCRibbonStatusBarPane, pGroup->GetButton(4));
434 if (pPane)
436 pPane->SetText(sBarText);
438 CMFCRibbonButton * pButton = DYNAMIC_DOWNCAST(CMFCRibbonButton, pGroup->GetButton(1));
439 if (pButton)
441 pButton->SetText(CFileTextLines::GetEncodingName(m_texttype));
442 pButton->SetDescription(CFileTextLines::GetEncodingName(m_texttype));
444 pButton = DYNAMIC_DOWNCAST(CMFCRibbonButton, pGroup->GetButton(2));
445 if (pButton)
447 pButton->SetText(GetEolName(m_lineendings));
448 pButton->SetDescription(GetEolName(m_lineendings));
450 pButton = DYNAMIC_DOWNCAST(CMFCRibbonButton, pGroup->GetButton(3));
451 if (pButton)
453 pButton->SetText(GetTabModeString(m_nTabMode, m_nTabSize, m_bEditorConfigEnabled && m_bEditorConfigLoaded));
454 pButton->SetDescription(GetTabModeString(m_nTabMode, m_nTabSize, m_bEditorConfigEnabled && m_bEditorConfigLoaded));
457 m_pwndRibbonStatusBar->RecalcLayout();
458 m_pwndRibbonStatusBar->Invalidate();
463 BOOL CBaseView::PreCreateWindow(CREATESTRUCT& cs)
465 if (!CView::PreCreateWindow(cs))
466 return FALSE;
468 cs.dwExStyle |= WS_EX_CLIENTEDGE;
469 cs.style &= ~WS_BORDER;
470 cs.lpszClass = AfxRegisterWndClass(CS_HREDRAW|CS_VREDRAW|CS_DBLCLKS,
471 ::LoadCursor(NULL, IDC_ARROW), reinterpret_cast<HBRUSH>(COLOR_WINDOW+1), NULL);
473 CWnd *pParentWnd = CWnd::FromHandlePermanent(cs.hwndParent);
474 if (pParentWnd == NULL || ! pParentWnd->IsKindOf(RUNTIME_CLASS(CSplitterWnd)))
476 // View must always create its own scrollbars,
477 // if only it's not used within splitter
478 cs.style |= (WS_HSCROLL | WS_VSCROLL);
480 cs.lpszClass = AfxRegisterWndClass(CS_DBLCLKS);
481 return TRUE;
484 CFont* CBaseView::GetFont(BOOL bItalic /*= FALSE*/, BOOL bBold /*= FALSE*/)
486 int nIndex = 0;
487 if (bBold)
488 nIndex |= 1;
489 if (bItalic)
490 nIndex |= 2;
491 if (m_apFonts[nIndex] == NULL)
493 m_apFonts[nIndex] = new CFont;
494 m_lfBaseFont.lfCharSet = DEFAULT_CHARSET;
495 m_lfBaseFont.lfWeight = bBold ? FW_BOLD : FW_NORMAL;
496 m_lfBaseFont.lfItalic = (BYTE) bItalic;
497 CDC * pDC = GetDC();
498 if (pDC)
500 m_lfBaseFont.lfHeight = -MulDiv((DWORD)CRegDWORD(_T("Software\\TortoiseGitMerge\\LogFontSize"), 10), GetDeviceCaps(pDC->m_hDC, LOGPIXELSY), 72);
501 ReleaseDC(pDC);
503 _tcsncpy_s(m_lfBaseFont.lfFaceName, (LPCTSTR)(CString)CRegString(_T("Software\\TortoiseGitMerge\\LogFontName"), _T("Courier New")), _countof(m_lfBaseFont.lfFaceName) - 1);
504 if (!m_apFonts[nIndex]->CreateFontIndirect(&m_lfBaseFont))
506 delete m_apFonts[nIndex];
507 m_apFonts[nIndex] = NULL;
508 return CView::GetFont();
511 return m_apFonts[nIndex];
514 void CBaseView::CalcLineCharDim()
516 CDC *pDC = GetDC();
517 if (pDC == nullptr)
518 return;
519 CFont *pOldFont = pDC->SelectObject(GetFont());
520 const CSize szCharExt = pDC->GetTextExtent(_T("X"));
521 pDC->SelectObject(pOldFont);
522 ReleaseDC(pDC);
524 m_nLineHeight = szCharExt.cy;
525 if (m_nLineHeight <= 0)
526 m_nLineHeight = -1;
527 m_nCharWidth = szCharExt.cx;
528 if (m_nCharWidth <= 0)
529 m_nCharWidth = -1;
532 int CBaseView::GetScreenChars()
534 if (m_nScreenChars == -1)
536 CRect rect;
537 GetClientRect(&rect);
538 m_nScreenChars = (rect.Width() - GetMarginWidth() - GetSystemMetrics(SM_CXVSCROLL)) / GetCharWidth();
539 if (m_nScreenChars < 0)
540 m_nScreenChars = 0;
542 return m_nScreenChars;
545 int CBaseView::GetAllMinScreenChars() const
547 int nChars = INT_MAX;
548 if (IsLeftViewGood())
549 nChars = std::min<int>(nChars, m_pwndLeft->GetScreenChars());
550 if (IsRightViewGood())
551 nChars = std::min<int>(nChars, m_pwndRight->GetScreenChars());
552 if (IsBottomViewGood())
553 nChars = std::min<int>(nChars, m_pwndBottom->GetScreenChars());
554 return (nChars==INT_MAX) ? 0 : nChars;
557 int CBaseView::GetAllMaxLineLength() const
559 int nLength = 0;
560 if (IsLeftViewGood())
561 nLength = std::max<int>(nLength, m_pwndLeft->GetMaxLineLength());
562 if (IsRightViewGood())
563 nLength = std::max<int>(nLength, m_pwndRight->GetMaxLineLength());
564 if (IsBottomViewGood())
565 nLength = std::max<int>(nLength, m_pwndBottom->GetMaxLineLength());
566 return nLength;
569 int CBaseView::GetLineHeight()
571 if (m_nLineHeight == -1)
572 CalcLineCharDim();
573 if (m_nLineHeight <= 0)
574 return 1;
575 return m_nLineHeight;
578 int CBaseView::GetCharWidth()
580 if (m_nCharWidth == -1)
581 CalcLineCharDim();
582 if (m_nCharWidth <= 0)
583 return 1;
584 return m_nCharWidth;
587 int CBaseView::GetMaxLineLength()
589 if (m_nMaxLineLength == -1)
591 m_nMaxLineLength = 0;
592 int nLineCount = GetLineCount();
593 for (int i=0; i<nLineCount; i++)
595 int nActualLength = GetLineLength(i);
596 if (m_nMaxLineLength < nActualLength)
597 m_nMaxLineLength = nActualLength;
600 return m_nMaxLineLength;
603 int CBaseView::GetLineLength(int index)
605 if (m_pViewData == NULL)
606 return 0;
607 if (m_pViewData->GetCount() == 0)
608 return 0;
609 if ((int)m_Screen2View.size() <= index)
610 return 0;
611 int viewLine = GetViewLineForScreen(index);
612 if (m_pMainFrame->m_bWrapLines)
614 int nLineLength = GetLineChars(index).GetLength();
615 ASSERT(nLineLength >= 0);
616 return nLineLength;
618 int nLineLength = m_pViewData->GetLine(viewLine).GetLength();
619 ASSERT(nLineLength >= 0);
620 return nLineLength;
623 int CBaseView::GetViewLineLength(int nViewLine) const
625 if (m_pViewData == NULL)
626 return 0;
627 if (m_pViewData->GetCount() <= nViewLine)
628 return 0;
629 int nLineLength = m_pViewData->GetLine(nViewLine).GetLength();
630 ASSERT(nLineLength >= 0);
631 return nLineLength;
634 int CBaseView::GetLineCount() const
636 if (m_pViewData == NULL)
637 return 1;
638 int nLineCount = (int)m_Screen2View.size();
639 ASSERT(nLineCount >= 0);
640 return nLineCount;
643 int CBaseView::GetSubLineOffset(int index)
645 return m_Screen2View.GetSubLineOffset(index);
648 CString CBaseView::GetViewLineChars(int nViewLine) const
650 if (m_pViewData == NULL)
651 return 0;
652 if (m_pViewData->GetCount() <= nViewLine)
653 return 0;
654 return m_pViewData->GetLine(nViewLine);
657 CString CBaseView::GetLineChars(int index)
659 if (m_pViewData == NULL)
660 return 0;
661 if (m_pViewData->GetCount() == 0)
662 return 0;
663 if ((int)m_Screen2View.size() <= index)
664 return 0;
665 int viewLine = GetViewLineForScreen(index);
666 if (m_pMainFrame->m_bWrapLines)
668 int subLine = GetSubLineOffset(index);
669 if (subLine >= 0)
671 if (subLine < CountMultiLines(viewLine))
673 return m_ScreenedViewLine[viewLine].SubLines[subLine];
675 return L"";
678 return m_pViewData->GetLine(viewLine);
681 void CBaseView::CheckOtherView()
683 if (m_bOtherDiffChecked)
684 return;
685 // find out what the 'other' file is
686 m_pOtherViewData = NULL;
687 m_pOtherView = NULL;
688 if (this == m_pwndLeft && IsRightViewGood())
690 m_pOtherViewData = m_pwndRight->m_pViewData;
691 m_pOtherView = m_pwndRight;
694 if (this == m_pwndRight && IsLeftViewGood())
696 m_pOtherViewData = m_pwndLeft->m_pViewData;
697 m_pOtherView = m_pwndLeft;
700 m_bOtherDiffChecked = true;
704 void CBaseView::GetWhitespaceBlock(CViewData *viewData, int nLineIndex, int & nStartBlock, int & nEndBlock)
706 enum { MAX_WHITESPACEBLOCK_SIZE = 8 };
707 ASSERT(viewData);
709 DiffStates origstate = viewData->GetState(nLineIndex);
711 // Go back and forward at most MAX_WHITESPACEBLOCK_SIZE lines to see where this block ends
712 nStartBlock = nLineIndex;
713 nEndBlock = nLineIndex;
714 while ((nStartBlock > 0) && (nStartBlock > (nLineIndex - MAX_WHITESPACEBLOCK_SIZE)))
716 DiffStates state = viewData->GetState(nStartBlock - 1);
717 if ((origstate == DIFFSTATE_EMPTY) && (state != DIFFSTATE_NORMAL))
718 origstate = state;
719 if ((origstate == state) || (state == DIFFSTATE_EMPTY))
720 nStartBlock--;
721 else
722 break;
724 while ((nEndBlock < (viewData->GetCount() - 1)) && (nEndBlock < (nLineIndex + MAX_WHITESPACEBLOCK_SIZE)))
726 DiffStates state = viewData->GetState(nEndBlock + 1);
727 if ((origstate == DIFFSTATE_EMPTY) && (state != DIFFSTATE_NORMAL))
728 origstate = state;
729 if ((origstate == state) || (state == DIFFSTATE_EMPTY))
730 nEndBlock++;
731 else
732 break;
736 CString CBaseView::GetWhitespaceString(CViewData *viewData, int nStartBlock, int nEndBlock)
738 enum { MAX_WHITESPACEBLOCK_SIZE = 8 };
740 int len = 0;
741 for (int i = nStartBlock; i <= nEndBlock; ++i)
742 len += viewData->GetLine(i).GetLength()+2;
744 CString block;
745 // do not check for whitespace blocks if the line is too long, because
746 // reserving a lot of memory here takes too much time (performance hog)
747 if (len > MAX_WHITESPACEBLOCK_SIZE*256)
748 return block;
749 block.Preallocate(len+1);
750 for (int i = nStartBlock; i <= nEndBlock; ++i)
752 block += viewData->GetLine(i);
753 block += m_Eols[viewData->GetLineEnding(i)];
755 return block;
758 bool CBaseView::IsBlockWhitespaceOnly(int nLineIndex, bool& bIdentical, int& blockstart, int& blockend)
760 if (m_pViewData == NULL)
761 return false;
762 bIdentical = false;
763 CheckOtherView();
764 if (!m_pOtherViewData)
765 return false;
766 int viewLine = GetViewLineForScreen(nLineIndex);
767 if (
768 (m_pViewData->GetState(viewLine) == DIFFSTATE_NORMAL) &&
769 (m_pOtherViewData->GetLine(viewLine) == m_pViewData->GetLine(viewLine))
772 bIdentical = true;
773 return false;
775 // first check whether the line itself only has whitespace changes
776 CString mine = m_pViewData->GetLine(viewLine);
777 CString other = m_pOtherViewData->GetLine(min(viewLine, m_pOtherViewData->GetCount() - 1));
778 if (mine.IsEmpty() && other.IsEmpty())
780 bIdentical = true;
781 return false;
784 if (mine == other)
786 bIdentical = true;
787 return true;
789 FilterWhitespaces(mine, other);
790 if (mine == other)
791 return true;
793 int nStartBlock2, nEndBlock2;
794 GetWhitespaceBlock(m_pViewData, viewLine, blockstart, blockend);
795 GetWhitespaceBlock(m_pOtherViewData, min(viewLine, m_pOtherViewData->GetCount() - 1), nStartBlock2, nEndBlock2);
796 mine = GetWhitespaceString(m_pViewData, blockstart, blockend);
797 if (mine.IsEmpty())
798 bIdentical = false;
799 else
801 other = GetWhitespaceString(m_pOtherViewData, nStartBlock2, nEndBlock2);
802 bIdentical = mine == other;
803 FilterWhitespaces(mine, other);
806 return (!mine.IsEmpty()) && (mine == other);
809 bool CBaseView::IsViewLineHidden(int nViewLine)
811 return IsViewLineHidden(m_pViewData, nViewLine);
814 bool CBaseView::IsViewLineHidden(CViewData * pViewData, int nViewLine)
816 return m_pMainFrame->m_bCollapsed && (pViewData->GetHideState(nViewLine)!=HIDESTATE_SHOWN);
819 int CBaseView::GetLineNumber(int index) const
821 if (m_pViewData == NULL)
822 return -1;
823 int viewLine = GetViewLineForScreen(index);
824 if (m_pViewData->GetLineNumber(viewLine)==DIFF_EMPTYLINENUMBER)
825 return -1;
826 return m_pViewData->GetLineNumber(viewLine);
829 int CBaseView::GetScreenLines()
831 if (m_nScreenLines == -1)
833 int scrollBarHeight = 0;
834 SCROLLBARINFO sbi = { sizeof(sbi) };
835 if (GetScrollBarInfo(OBJID_HSCROLL, &sbi))
837 // only use the scroll bar size if the info is correct and the scrollbar is visible
838 // if anything isn't proper, assume the scrollbar has a size of zero
839 // and calculate the screen lines without it.
840 if (!(sbi.rgstate[0] & STATE_SYSTEM_INVISIBLE) && !(sbi.rgstate[0] & STATE_SYSTEM_UNAVAILABLE))
841 scrollBarHeight = sbi.rcScrollBar.bottom - sbi.rcScrollBar.top;
843 CRect rect;
844 GetClientRect(&rect);
845 m_nScreenLines = (rect.Height() - HEADERHEIGHT - scrollBarHeight) / GetLineHeight();
846 if (m_nScreenLines < 0)
847 m_nScreenLines = 0;
849 return m_nScreenLines;
852 int CBaseView::GetAllMinScreenLines() const
854 int nLines = INT_MAX;
855 if (IsLeftViewGood())
856 nLines = m_pwndLeft->GetScreenLines();
857 if (IsRightViewGood())
858 nLines = std::min<int>(nLines, m_pwndRight->GetScreenLines());
859 if (IsBottomViewGood())
860 nLines = std::min<int>(nLines, m_pwndBottom->GetScreenLines());
861 return (nLines == INT_MAX) || (nLines < 0) ? 0 : nLines;
864 int CBaseView::GetAllLineCount() const
866 int nLines = 0;
867 if (IsLeftViewGood())
868 nLines = m_pwndLeft->GetLineCount();
869 if (IsRightViewGood())
870 nLines = std::max<int>(nLines, m_pwndRight->GetLineCount());
871 if (IsBottomViewGood())
872 nLines = std::max<int>(nLines, m_pwndBottom->GetLineCount());
873 return nLines;
876 void CBaseView::RecalcAllVertScrollBars(BOOL bPositionOnly /*= FALSE*/)
878 if (IsLeftViewGood())
879 m_pwndLeft->RecalcVertScrollBar(bPositionOnly);
880 if (IsRightViewGood())
881 m_pwndRight->RecalcVertScrollBar(bPositionOnly);
882 if (IsBottomViewGood())
883 m_pwndBottom->RecalcVertScrollBar(bPositionOnly);
886 void CBaseView::RecalcVertScrollBar(BOOL bPositionOnly /*= FALSE*/)
888 SCROLLINFO si;
889 si.cbSize = sizeof(si);
890 if (bPositionOnly)
892 si.fMask = SIF_POS;
893 si.nPos = m_nTopLine;
895 else
897 EnableScrollBarCtrl(SB_VERT, TRUE);
898 if (GetAllMinScreenLines() >= GetAllLineCount() && m_nTopLine > 0)
900 m_nTopLine = 0;
901 Invalidate();
903 si.fMask = SIF_DISABLENOSCROLL | SIF_PAGE | SIF_POS | SIF_RANGE;
904 si.nMin = 0;
905 si.nMax = GetAllLineCount();
906 si.nPage = GetAllMinScreenLines();
907 si.nPos = m_nTopLine;
909 VERIFY(SetScrollInfo(SB_VERT, &si));
912 void CBaseView::OnVScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar)
914 CView::OnVScroll(nSBCode, nPos, pScrollBar);
915 if (m_pwndLeft)
916 m_pwndLeft->OnDoVScroll(nSBCode, nPos, pScrollBar, this);
917 if (m_pwndRight)
918 m_pwndRight->OnDoVScroll(nSBCode, nPos, pScrollBar, this);
919 if (m_pwndBottom)
920 m_pwndBottom->OnDoVScroll(nSBCode, nPos, pScrollBar, this);
921 if (m_pwndLocator)
922 m_pwndLocator->Invalidate();
925 void CBaseView::OnDoVScroll(UINT nSBCode, UINT /*nPos*/, CScrollBar* /*pScrollBar*/, CBaseView * master)
927 // Note we cannot use nPos because of its 16-bit nature
928 SCROLLINFO si;
929 si.cbSize = sizeof(si);
930 si.fMask = SIF_ALL;
931 VERIFY(master->GetScrollInfo(SB_VERT, &si));
933 int nPageLines = GetScreenLines();
934 int nLineCount = GetLineCount();
936 int nNewTopLine;
938 static LONG textwidth = 0;
939 static CString sFormat(MAKEINTRESOURCE(IDS_VIEWSCROLLTIPTEXT));
940 switch (nSBCode)
942 case SB_TOP:
943 nNewTopLine = 0;
944 break;
945 case SB_BOTTOM:
946 nNewTopLine = nLineCount - nPageLines + 1;
947 break;
948 case SB_LINEUP:
949 nNewTopLine = m_nTopLine - 1;
950 break;
951 case SB_LINEDOWN:
952 nNewTopLine = m_nTopLine + 1;
953 break;
954 case SB_PAGEUP:
955 nNewTopLine = m_nTopLine - si.nPage + 1;
956 break;
957 case SB_PAGEDOWN:
958 nNewTopLine = m_nTopLine + si.nPage - 1;
959 break;
960 case SB_THUMBPOSITION:
961 m_ScrollTool.Clear();
962 nNewTopLine = si.nTrackPos;
963 textwidth = 0;
964 break;
965 case SB_THUMBTRACK:
966 nNewTopLine = si.nTrackPos;
967 if (GetFocus() == this)
969 RECT thumbrect;
970 GetClientRect(&thumbrect);
971 ClientToScreen(&thumbrect);
973 POINT thumbpoint;
974 thumbpoint.x = thumbrect.right;
975 thumbpoint.y = thumbrect.top + ((thumbrect.bottom-thumbrect.top)*si.nTrackPos)/(si.nMax-si.nMin);
976 m_ScrollTool.Init(&thumbpoint);
977 if (textwidth == 0)
979 CString sTemp = sFormat;
980 sTemp.Format(sFormat, m_nDigits, 10*m_nDigits-1);
981 textwidth = m_ScrollTool.GetTextWidth(sTemp);
983 thumbpoint.x -= textwidth;
984 int line = GetLineNumber(nNewTopLine);
985 if (line >= 0)
986 m_ScrollTool.SetText(&thumbpoint, sFormat, m_nDigits, GetLineNumber(nNewTopLine)+1);
987 else
988 m_ScrollTool.SetText(&thumbpoint, m_sNoLineNr);
990 break;
991 default:
992 return;
995 if (nNewTopLine < 0)
996 nNewTopLine = 0;
997 if (nNewTopLine >= nLineCount)
998 nNewTopLine = nLineCount - 1;
999 ScrollToLine(nNewTopLine);
1002 void CBaseView::RecalcAllHorzScrollBars(BOOL bPositionOnly /*= FALSE*/)
1004 if (IsLeftViewGood())
1005 m_pwndLeft->RecalcHorzScrollBar(bPositionOnly);
1006 if (IsRightViewGood())
1007 m_pwndRight->RecalcHorzScrollBar(bPositionOnly);
1008 if (IsBottomViewGood())
1009 m_pwndBottom->RecalcHorzScrollBar(bPositionOnly);
1012 void CBaseView::RecalcHorzScrollBar(BOOL bPositionOnly /*= FALSE*/)
1014 SCROLLINFO si;
1015 si.cbSize = sizeof(si);
1016 if (bPositionOnly)
1018 si.fMask = SIF_POS;
1019 si.nPos = m_nOffsetChar;
1021 else
1023 EnableScrollBarCtrl(SB_HORZ, !m_pMainFrame->m_bWrapLines);
1024 if (!m_pMainFrame->m_bWrapLines)
1026 int minScreenChars = GetAllMinScreenChars();
1027 int maxLineLength = GetAllMaxLineLength();
1028 if (minScreenChars >= maxLineLength && m_nOffsetChar > 0)
1030 m_nOffsetChar = 0;
1031 Invalidate();
1033 si.fMask = SIF_DISABLENOSCROLL | SIF_PAGE | SIF_POS | SIF_RANGE;
1034 si.nMin = 0;
1035 si.nMax = m_pMainFrame->m_bWrapLines ? minScreenChars : maxLineLength;
1036 si.nMax += GetMarginWidth()/GetCharWidth();
1037 si.nPage = GetScreenChars();
1038 si.nPos = m_nOffsetChar;
1041 VERIFY(SetScrollInfo(SB_HORZ, &si));
1044 void CBaseView::OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar)
1046 CView::OnHScroll(nSBCode, nPos, pScrollBar);
1047 if (m_pwndLeft)
1048 m_pwndLeft->OnDoHScroll(nSBCode, nPos, pScrollBar, this);
1049 if (m_pwndRight)
1050 m_pwndRight->OnDoHScroll(nSBCode, nPos, pScrollBar, this);
1051 if (m_pwndBottom)
1052 m_pwndBottom->OnDoHScroll(nSBCode, nPos, pScrollBar, this);
1053 if (m_pwndLocator)
1054 m_pwndLocator->Invalidate();
1057 void CBaseView::OnDoHScroll(UINT nSBCode, UINT /*nPos*/, CScrollBar* /*pScrollBar*/, CBaseView * master)
1059 SCROLLINFO si;
1060 si.cbSize = sizeof(si);
1061 si.fMask = SIF_ALL;
1062 VERIFY(master->GetScrollInfo(SB_HORZ, &si));
1064 int nPageChars = GetScreenChars();
1065 int nMaxLineLength = GetMaxLineLength();
1067 int nNewOffset;
1068 switch (nSBCode)
1070 case SB_LEFT:
1071 nNewOffset = 0;
1072 break;
1073 case SB_BOTTOM:
1074 nNewOffset = nMaxLineLength - nPageChars + 1;
1075 break;
1076 case SB_LINEUP:
1077 nNewOffset = m_nOffsetChar - 1;
1078 break;
1079 case SB_LINEDOWN:
1080 nNewOffset = m_nOffsetChar + 1;
1081 break;
1082 case SB_PAGEUP:
1083 nNewOffset = m_nOffsetChar - si.nPage + 1;
1084 break;
1085 case SB_PAGEDOWN:
1086 nNewOffset = m_nOffsetChar + si.nPage - 1;
1087 break;
1088 case SB_THUMBPOSITION:
1089 case SB_THUMBTRACK:
1090 nNewOffset = si.nTrackPos;
1091 break;
1092 default:
1093 return;
1096 if (nNewOffset >= nMaxLineLength)
1097 nNewOffset = nMaxLineLength - 1;
1098 if (nNewOffset < 0)
1099 nNewOffset = 0;
1100 ScrollToChar(nNewOffset, TRUE);
1103 void CBaseView::ScrollToChar(int nNewOffsetChar, BOOL bTrackScrollBar /*= TRUE*/)
1105 if (m_nOffsetChar != nNewOffsetChar)
1107 int nScrollChars = m_nOffsetChar - nNewOffsetChar;
1108 m_nOffsetChar = nNewOffsetChar;
1109 CRect rcScroll;
1110 GetClientRect(&rcScroll);
1111 rcScroll.left += GetMarginWidth();
1112 rcScroll.top += GetLineHeight()+HEADERHEIGHT;
1113 ScrollWindow(nScrollChars * GetCharWidth(), 0, &rcScroll, &rcScroll);
1114 // update the view header
1115 rcScroll.left = 0;
1116 rcScroll.top = 0;
1117 rcScroll.bottom = GetLineHeight()+HEADERHEIGHT;
1118 InvalidateRect(&rcScroll, FALSE);
1119 UpdateWindow();
1120 if (bTrackScrollBar)
1121 RecalcHorzScrollBar(TRUE);
1122 UpdateCaret();
1123 if (m_pwndLineDiffBar)
1124 m_pwndLineDiffBar->Invalidate();
1128 void CBaseView::ScrollAllToChar(int nNewOffsetChar, BOOL bTrackScrollBar /* = TRUE */)
1130 if (m_pwndLeft)
1131 m_pwndLeft->ScrollToChar(nNewOffsetChar, bTrackScrollBar);
1132 if (m_pwndRight)
1133 m_pwndRight->ScrollToChar(nNewOffsetChar, bTrackScrollBar);
1134 if (m_pwndBottom)
1135 m_pwndBottom->ScrollToChar(nNewOffsetChar, bTrackScrollBar);
1138 void CBaseView::ScrollAllSide(int delta)
1140 int nNewOffset = m_nOffsetChar;
1141 nNewOffset += delta;
1142 int nMaxLineLength = GetMaxLineLength();
1143 if (nNewOffset >= nMaxLineLength)
1144 nNewOffset = nMaxLineLength - 1;
1145 if (nNewOffset < 0)
1146 nNewOffset = 0;
1147 ScrollAllToChar(nNewOffset, TRUE);
1148 if (m_pwndLineDiffBar)
1149 m_pwndLineDiffBar->Invalidate();
1150 UpdateCaret();
1153 void CBaseView::ScrollSide(int delta)
1155 int nNewOffset = m_nOffsetChar;
1156 nNewOffset += delta;
1157 int nMaxLineLength = GetMaxLineLength();
1158 if (nNewOffset >= nMaxLineLength)
1159 nNewOffset = nMaxLineLength - 1;
1160 if (nNewOffset < 0)
1161 nNewOffset = 0;
1162 ScrollToChar(nNewOffset, TRUE);
1163 if (m_pwndLineDiffBar)
1164 m_pwndLineDiffBar->Invalidate();
1165 UpdateCaret();
1168 void CBaseView::ScrollVertical(short zDelta)
1170 const int nLineCount = GetLineCount();
1171 int nTopLine = m_nTopLine;
1172 nTopLine -= (zDelta/30);
1173 if (nTopLine < 0)
1174 nTopLine = 0;
1175 if (nTopLine >= nLineCount)
1176 nTopLine = nLineCount - 1;
1177 ScrollToLine(nTopLine, TRUE);
1180 void CBaseView::ScrollToLine(int nNewTopLine, BOOL bTrackScrollBar /*= TRUE*/)
1182 if (m_nTopLine != nNewTopLine)
1184 if (nNewTopLine < 0)
1185 nNewTopLine = 0;
1187 int nScrollLines = m_nTopLine - nNewTopLine;
1189 m_nTopLine = nNewTopLine;
1190 CRect rcScroll;
1191 GetClientRect(&rcScroll);
1192 rcScroll.top += GetLineHeight()+HEADERHEIGHT;
1193 ScrollWindow(0, nScrollLines * GetLineHeight(), &rcScroll, &rcScroll);
1194 UpdateWindow();
1195 if (bTrackScrollBar)
1196 RecalcVertScrollBar(TRUE);
1197 UpdateCaret();
1202 void CBaseView::DrawMargin(CDC *pdc, const CRect &rect, int nLineIndex)
1204 pdc->FillSolidRect(rect, ::GetSysColor(COLOR_SCROLLBAR));
1206 if ((nLineIndex >= 0)&&(m_pViewData)&&(m_pViewData->GetCount()))
1208 int nViewLine = GetViewLineForScreen(nLineIndex);
1209 HICON icon = NULL;
1210 ASSERT(nViewLine<(int)m_ScreenedViewLine.size());
1211 TScreenedViewLine::EIcon eIcon = m_ScreenedViewLine[nViewLine].eIcon;
1212 if (eIcon==TScreenedViewLine::ICN_UNKNOWN)
1214 DiffStates state = m_pViewData->GetState(nViewLine);
1215 switch (state)
1217 case DIFFSTATE_ADDED:
1218 case DIFFSTATE_THEIRSADDED:
1219 case DIFFSTATE_YOURSADDED:
1220 case DIFFSTATE_IDENTICALADDED:
1221 case DIFFSTATE_CONFLICTADDED:
1222 eIcon = TScreenedViewLine::ICN_ADD;
1223 break;
1224 case DIFFSTATE_REMOVED:
1225 case DIFFSTATE_THEIRSREMOVED:
1226 case DIFFSTATE_YOURSREMOVED:
1227 case DIFFSTATE_IDENTICALREMOVED:
1228 eIcon = TScreenedViewLine::ICN_REMOVED;
1229 break;
1230 case DIFFSTATE_CONFLICTED:
1231 eIcon = TScreenedViewLine::ICN_CONFLICT;
1232 break;
1233 case DIFFSTATE_CONFLICTED_IGNORED:
1234 eIcon = TScreenedViewLine::ICN_CONFLICTIGNORED;
1235 break;
1236 case DIFFSTATE_EDITED:
1237 eIcon = TScreenedViewLine::ICN_EDIT;
1238 break;
1239 default:
1240 break;
1242 bool bIdentical = false;
1243 int blockstart = -1;
1244 int blockend = -1;
1245 if ((state != DIFFSTATE_EDITED)&&(IsBlockWhitespaceOnly(nLineIndex, bIdentical, blockstart, blockend)))
1247 if (bIdentical)
1248 eIcon = TScreenedViewLine::ICN_SAME;
1249 else
1250 eIcon = TScreenedViewLine::ICN_WHITESPACEDIFF;
1251 if (((blockstart >= 0) && (blockend >= 0)) && (blockstart < blockend))
1253 if (nViewLine > blockstart)
1254 Invalidate(); // redraw the upper icons since they're now changing
1255 while (blockstart <= blockend)
1256 m_ScreenedViewLine[blockstart++].eIcon = eIcon;
1259 if (m_pViewData->GetMovedIndex(nViewLine) >= 0)
1260 eIcon = TScreenedViewLine::ICN_MOVED;
1261 if (m_pViewData->GetMarked(nViewLine))
1262 eIcon = TScreenedViewLine::ICN_MARKED;
1263 m_ScreenedViewLine[nViewLine].eIcon = eIcon;
1265 switch (eIcon)
1267 case TScreenedViewLine::ICN_UNKNOWN:
1268 case TScreenedViewLine::ICN_NONE:
1269 break;
1270 case TScreenedViewLine::ICN_SAME:
1271 icon = m_hEqualIcon;
1272 break;
1273 case TScreenedViewLine::ICN_EDIT:
1274 icon = m_hEditedIcon;
1275 break;
1276 case TScreenedViewLine::ICN_WHITESPACEDIFF:
1277 icon = m_hWhitespaceBlockIcon;
1278 break;
1279 case TScreenedViewLine::ICN_ADD:
1280 icon = m_hAddedIcon;
1281 break;
1282 case TScreenedViewLine::ICN_CONFLICT:
1283 icon = m_hConflictedIcon;
1284 break;
1285 case TScreenedViewLine::ICN_CONFLICTIGNORED:
1286 icon = m_hConflictedIgnoredIcon;
1287 break;
1288 case TScreenedViewLine::ICN_REMOVED:
1289 icon = m_hRemovedIcon;
1290 break;
1291 case TScreenedViewLine::ICN_MOVED:
1292 icon = m_hMovedIcon;
1293 break;
1294 case TScreenedViewLine::ICN_MARKED:
1295 icon = m_hMarkedIcon;
1296 break;
1300 if (icon)
1302 ::DrawIconEx(pdc->m_hDC, rect.left + 2, rect.top + (rect.Height()-16)/2, icon, 16, 16, NULL, NULL, DI_NORMAL);
1304 if ((m_bViewLinenumbers)&&(m_nDigits))
1306 int nSubLine = GetSubLineOffset(nLineIndex);
1307 bool bIsFirstSubline = (nSubLine == 0) || (nSubLine == -1);
1308 CString sLinenumber;
1309 if (bIsFirstSubline)
1311 CString sLinenumberFormat;
1312 int nLineNumber = GetLineNumber(nLineIndex);
1313 if (IsViewLineHidden(GetViewLineForScreen(nLineIndex)))
1315 // TODO: do not show if there is no number hidden
1316 // TODO: show number if there is only one
1317 sLinenumberFormat.Format(_T("%%%ds"), m_nDigits);
1318 sLinenumber.Format(sLinenumberFormat, (m_nDigits>1) ? _T("↕⁞") : _T("⁞")); // alternative …
1320 else if (nLineNumber >= 0)
1322 sLinenumberFormat.Format(_T("%%%dd"), m_nDigits);
1323 sLinenumber.Format(sLinenumberFormat, nLineNumber+1);
1325 else if (m_pMainFrame->m_bWrapLines)
1327 sLinenumberFormat.Format(_T("%%%ds"), m_nDigits);
1328 sLinenumber.Format(sLinenumberFormat, _T("·"));
1330 if (!sLinenumber.IsEmpty())
1332 pdc->SetBkColor(::GetSysColor(COLOR_SCROLLBAR));
1333 pdc->SetTextColor(::GetSysColor(COLOR_WINDOWTEXT));
1335 pdc->SelectObject(GetFont());
1336 pdc->ExtTextOut(rect.left + 18, rect.top, ETO_CLIPPED, &rect, sLinenumber, NULL);
1343 int CBaseView::GetMarginWidth()
1345 if ((m_bViewLinenumbers)&&(m_pViewData)&&(m_pViewData->GetCount()))
1347 if (m_nDigits <= 0)
1349 int nLength = (int)m_pViewData->GetCount();
1350 // find out how many digits are needed to show the highest line number
1351 CString sMax;
1352 sMax.Format(_T("%d"), nLength);
1353 m_nDigits = sMax.GetLength();
1355 int nWidth = GetCharWidth();
1356 return (MARGINWIDTH + (m_nDigits * nWidth) + 2);
1358 return MARGINWIDTH;
1361 void CBaseView::DrawHeader(CDC *pdc, const CRect &rect)
1363 CRect textrect(rect.left, rect.top, rect.Width(), GetLineHeight()+HEADERHEIGHT);
1364 COLORREF crBk, crFg;
1365 if (IsBottomViewGood())
1367 CDiffColors::GetInstance().GetColors(DIFFSTATE_NORMAL, crBk, crFg);
1368 crBk = ::GetSysColor(COLOR_SCROLLBAR);
1370 else
1372 DiffStates state = DIFFSTATE_REMOVED;
1373 if (this == m_pwndRight)
1375 state = DIFFSTATE_ADDED;
1377 CDiffColors::GetInstance().GetColors(state, crBk, crFg);
1379 pdc->SetBkColor(crBk);
1380 pdc->FillSolidRect(textrect, crBk);
1382 pdc->SetTextColor(crFg);
1384 pdc->SelectObject(GetFont(FALSE, TRUE));
1386 CString sViewTitle;
1387 if (IsModified())
1389 sViewTitle = _T("* ") + m_sWindowName;
1391 else
1393 sViewTitle = m_sWindowName;
1395 int nStringLength = (GetCharWidth()*m_sWindowName.GetLength());
1396 if (nStringLength > rect.Width())
1398 int offset = std::min<int>(m_nOffsetChar, (nStringLength-rect.Width())/GetCharWidth()+1);
1399 sViewTitle = m_sWindowName.Mid(offset);
1401 pdc->ExtTextOut(std::max<int>(rect.left + (rect.Width()-nStringLength)/2, 1),
1402 rect.top+(HEADERHEIGHT/2), ETO_CLIPPED, textrect, sViewTitle, NULL);
1403 if (this->GetFocus() == this)
1404 pdc->DrawEdge(textrect, EDGE_BUMP, BF_RECT);
1405 else
1406 pdc->DrawEdge(textrect, EDGE_ETCHED, BF_RECT);
1409 void CBaseView::OnDraw(CDC * pDC)
1411 CRect rcClient;
1412 GetClientRect(rcClient);
1414 int nLineCount = GetLineCount();
1415 int nLineHeight = GetLineHeight();
1417 CDC cacheDC;
1418 VERIFY(cacheDC.CreateCompatibleDC(pDC));
1419 if (m_pCacheBitmap == NULL)
1421 m_pCacheBitmap = new CBitmap;
1422 VERIFY(m_pCacheBitmap->CreateCompatibleBitmap(pDC, rcClient.Width(), nLineHeight));
1424 CBitmap *pOldBitmap = cacheDC.SelectObject(m_pCacheBitmap);
1426 DrawHeader(pDC, rcClient);
1428 CRect rcLine;
1429 rcLine = rcClient;
1430 rcLine.top += nLineHeight+HEADERHEIGHT;
1431 rcLine.bottom = rcLine.top + nLineHeight;
1432 CRect rcCacheMargin(0, 0, GetMarginWidth(), nLineHeight);
1433 CRect rcCacheLine(GetMarginWidth(), 0, rcLine.Width(), nLineHeight);
1435 int nCurrentLine = m_nTopLine;
1436 bool bBeyondFileLineCached = false;
1437 while (rcLine.top < rcClient.bottom)
1439 if (nCurrentLine < nLineCount)
1441 DrawMargin(&cacheDC, rcCacheMargin, nCurrentLine);
1442 DrawSingleLine(&cacheDC, rcCacheLine, nCurrentLine);
1443 bBeyondFileLineCached = false;
1445 else if (!bBeyondFileLineCached)
1447 DrawMargin(&cacheDC, rcCacheMargin, -1);
1448 DrawSingleLine(&cacheDC, rcCacheLine, -1);
1449 bBeyondFileLineCached = true;
1452 VERIFY(pDC->BitBlt(rcLine.left, rcLine.top, rcLine.Width(), rcLine.Height(), &cacheDC, 0, 0, SRCCOPY));
1454 nCurrentLine ++;
1455 rcLine.OffsetRect(0, nLineHeight);
1458 cacheDC.SelectObject(pOldBitmap);
1459 cacheDC.DeleteDC();
1462 bool CBaseView::IsStateConflicted(DiffStates state)
1464 switch (state)
1466 case DIFFSTATE_CONFLICTED:
1467 case DIFFSTATE_CONFLICTED_IGNORED:
1468 case DIFFSTATE_CONFLICTEMPTY:
1469 case DIFFSTATE_CONFLICTADDED:
1470 return true;
1472 return false;
1475 bool CBaseView::IsStateEmpty(DiffStates state)
1477 switch (state)
1479 case DIFFSTATE_CONFLICTEMPTY:
1480 case DIFFSTATE_UNKNOWN:
1481 case DIFFSTATE_EMPTY:
1482 return true;
1484 return false;
1487 bool CBaseView::IsStateRemoved(DiffStates state)
1489 switch (state)
1491 case DIFFSTATE_REMOVED:
1492 case DIFFSTATE_THEIRSREMOVED:
1493 case DIFFSTATE_YOURSREMOVED:
1494 case DIFFSTATE_IDENTICALREMOVED:
1495 return true;
1497 return false;
1500 DiffStates CBaseView::ResolveState(DiffStates state)
1502 if (IsStateConflicted(state))
1504 if (state == DIFFSTATE_CONFLICTEMPTY)
1505 return DIFFSTATE_CONFLICTRESOLVEDEMPTY;
1506 else
1507 return DIFFSTATE_CONFLICTRESOLVED;
1509 return state;
1513 bool CBaseView::IsLineEmpty(int nLineIndex)
1515 if (m_pViewData == 0)
1516 return FALSE;
1517 int nViewLine = GetViewLineForScreen(nLineIndex);
1518 return IsViewLineEmpty(nViewLine);
1521 bool CBaseView::IsViewLineEmpty(int nViewLine)
1523 if (m_pViewData == 0)
1524 return FALSE;
1525 const DiffStates state = m_pViewData->GetState(nViewLine);
1526 return IsStateEmpty(state);
1529 bool CBaseView::IsLineRemoved(int nLineIndex)
1531 if (m_pViewData == 0)
1532 return FALSE;
1533 int nViewLine = GetViewLineForScreen(nLineIndex);
1534 return IsViewLineRemoved(nViewLine);
1537 bool CBaseView::IsViewLineRemoved(int nViewLine)
1539 if (m_pViewData == 0)
1540 return FALSE;
1541 const DiffStates state = m_pViewData->GetState(nViewLine);
1542 return IsStateRemoved(state);
1545 bool CBaseView::IsViewLineConflicted(int nLineIndex)
1547 if (m_pViewData == 0)
1548 return false;
1549 const DiffStates state = m_pViewData->GetState(nLineIndex);
1550 return IsStateConflicted(state);
1553 COLORREF CBaseView::InlineDiffColor(int nLineIndex)
1555 return IsLineRemoved(nLineIndex) ? m_InlineRemovedBk : m_InlineAddedBk;
1558 COLORREF CBaseView::InlineViewLineDiffColor(int nViewLine)
1560 return IsViewLineRemoved(nViewLine) ? m_InlineRemovedBk : m_InlineAddedBk;
1563 void CBaseView::DrawLineEnding(CDC *pDC, const CRect &rc, int nLineIndex, const CPoint& origin)
1565 if (origin.x < (rc.left - GetCharWidth() +1))
1566 return;
1567 if (!(m_bViewWhitespace && m_pViewData && (nLineIndex >= 0) && (nLineIndex < GetLineCount())))
1568 return;
1569 int viewLine = GetViewLineForScreen(nLineIndex);
1570 EOL ending = m_pViewData->GetLineEnding(viewLine);
1571 if (m_bIconLFs)
1573 HICON hEndingIcon = NULL;
1574 switch (ending)
1576 case EOL_CR: hEndingIcon = m_hLineEndingCR; break;
1577 case EOL_CRLF: hEndingIcon = m_hLineEndingCRLF; break;
1578 case EOL_LF: hEndingIcon = m_hLineEndingLF; break;
1579 default: return;
1581 // If EOL style has changed, color end-of-line markers as inline differences.
1583 m_bShowInlineDiff && m_pOtherViewData &&
1584 (viewLine < m_pOtherViewData->GetCount()) &&
1585 (ending != EOL_NOENDING) &&
1586 (ending != m_pOtherViewData->GetLineEnding(viewLine) &&
1587 (m_pOtherViewData->GetLineEnding(viewLine) != EOL_NOENDING))
1590 pDC->FillSolidRect(origin.x, origin.y, rc.Height(), rc.Height(), InlineDiffColor(nLineIndex));
1593 DrawIconEx(pDC->GetSafeHdc(), origin.x, origin.y, hEndingIcon, rc.Height(), rc.Height(), NULL, NULL, DI_NORMAL);
1595 else
1597 CPen pen(PS_SOLID, 0, m_WhiteSpaceFg);
1598 CPen * oldpen = pDC->SelectObject(&pen);
1599 int yMiddle = origin.y + rc.Height()/2;
1600 int xMiddle = origin.x+GetCharWidth()/2;
1601 bool bMultiline = false;
1602 if (((int)m_Screen2View.size() > nLineIndex+1) && (GetViewLineForScreen(nLineIndex+1) == viewLine))
1604 if (GetLineLength(nLineIndex+1))
1606 // multiline
1607 bMultiline = true;
1608 pDC->MoveTo(origin.x, yMiddle-2);
1609 pDC->LineTo(origin.x+GetCharWidth()-1, yMiddle-2);
1610 pDC->LineTo(origin.x+GetCharWidth()-1, yMiddle+2);
1611 pDC->LineTo(origin.x, yMiddle+2);
1613 else if (GetLineLength(nLineIndex) == 0)
1614 bMultiline = true;
1616 else if ((nLineIndex > 0) && (GetViewLineForScreen(nLineIndex-1) == viewLine) && (GetLineLength(nLineIndex) == 0))
1617 bMultiline = true;
1619 if (!bMultiline)
1621 switch (ending)
1623 case EOL_AUTOLINE:
1624 case EOL_CRLF:
1625 // arrow from top to middle+2, then left
1626 pDC->MoveTo(origin.x+GetCharWidth()-1, rc.top+1);
1627 pDC->LineTo(origin.x+GetCharWidth()-1, yMiddle);
1628 case EOL_CR:
1629 // arrow from right to left
1630 pDC->MoveTo(origin.x+GetCharWidth()-1, yMiddle);
1631 pDC->LineTo(origin.x, yMiddle);
1632 pDC->LineTo(origin.x+4, yMiddle+4);
1633 pDC->MoveTo(origin.x, yMiddle);
1634 pDC->LineTo(origin.x+4, yMiddle-4);
1635 break;
1636 case EOL_LFCR:
1637 // from right-upper to left then down
1638 pDC->MoveTo(origin.x+GetCharWidth()-1, yMiddle-2);
1639 pDC->LineTo(xMiddle, yMiddle-2);
1640 pDC->LineTo(xMiddle, rc.bottom-1);
1641 pDC->LineTo(xMiddle+4, rc.bottom-5);
1642 pDC->MoveTo(xMiddle, rc.bottom-1);
1643 pDC->LineTo(xMiddle-4, rc.bottom-5);
1644 break;
1645 case EOL_LF:
1646 // arrow from top to bottom
1647 pDC->MoveTo(xMiddle, rc.top);
1648 pDC->LineTo(xMiddle, rc.bottom-1);
1649 pDC->LineTo(xMiddle+4, rc.bottom-5);
1650 pDC->MoveTo(xMiddle, rc.bottom-1);
1651 pDC->LineTo(xMiddle-4, rc.bottom-5);
1652 break;
1653 case EOL_FF: // Form Feed, U+000C
1654 case EOL_NEL: // Next Line, U+0085
1655 case EOL_LS: // Line Separator, U+2028
1656 case EOL_PS: // Paragraph Separator, U+2029
1657 // draw a horizontal line at the bottom of this line
1658 pDC->FillSolidRect(rc.left, rc.bottom-1, rc.right, rc.bottom, GetSysColor(COLOR_WINDOWTEXT));
1659 pDC->MoveTo(origin.x+GetCharWidth()-1, rc.bottom-GetCharWidth()-2);
1660 pDC->LineTo(origin.x, rc.bottom-2);
1661 pDC->LineTo(origin.x+5, rc.bottom-2);
1662 pDC->MoveTo(origin.x, rc.bottom-2);
1663 pDC->LineTo(origin.x+1, rc.bottom-6);
1664 break;
1665 default: // other EOLs
1666 // arrow from top right to bottom left
1667 pDC->MoveTo(origin.x+GetCharWidth()-1, rc.bottom-GetCharWidth());
1668 pDC->LineTo(origin.x, rc.bottom-1);
1669 pDC->LineTo(origin.x+5, rc.bottom-2);
1670 pDC->MoveTo(origin.x, rc.bottom-1);
1671 pDC->LineTo(origin.x+1, rc.bottom-6);
1672 break;
1673 case EOL_NOENDING:
1674 break;
1677 pDC->SelectObject(oldpen);
1681 void CBaseView::DrawBlockLine(CDC *pDC, const CRect &rc, int nLineIndex)
1683 if (!m_bShowSelection)
1684 return;
1686 int nSelBlockStart;
1687 int nSelBlockEnd;
1688 if (!GetViewSelection(nSelBlockStart, nSelBlockEnd))
1689 return;
1691 const int THICKNESS = 2;
1692 COLORREF rectcol = GetSysColor(m_bFocused ? COLOR_WINDOWTEXT : COLOR_GRAYTEXT);
1694 int nViewLineIndex = GetViewLineForScreen(nLineIndex);
1695 int nSubLine = GetSubLineOffset(nLineIndex);
1696 bool bFirstLineOfViewLine = (nSubLine==0 || nSubLine==-1);
1697 if ((nViewLineIndex == nSelBlockStart) && bFirstLineOfViewLine)
1699 pDC->FillSolidRect(rc.left, rc.top, rc.Width(), THICKNESS, rectcol);
1702 bool bLastLineOfViewLine = (nLineIndex+1 == m_Screen2View.size()) || (GetViewLineForScreen(nLineIndex) != GetViewLineForScreen(nLineIndex+1));
1703 if ((nViewLineIndex == nSelBlockEnd) && bLastLineOfViewLine)
1705 pDC->FillSolidRect(rc.left, rc.bottom - THICKNESS, rc.Width(), THICKNESS, rectcol);
1709 void CBaseView::DrawTextLine(
1710 CDC * pDC, const CRect &rc, int nLineIndex, POINT& coords)
1712 ASSERT(nLineIndex < GetLineCount());
1713 int nViewLine = GetViewLineForScreen(nLineIndex);
1714 ASSERT(m_pViewData && (nViewLine < m_pViewData->GetCount()));
1716 LineColors lineCols = GetLineColors(nViewLine);
1718 CString sViewLine = GetViewLineChars(nViewLine);
1719 // mark selection
1720 if (m_bShowSelection && HasTextSelection())
1722 // has this line selection ?
1723 if ((m_ptSelectionViewPosStart.y <= nViewLine) && (nViewLine <= m_ptSelectionViewPosEnd.y))
1725 int nViewLineLength = sViewLine.GetLength();
1727 // first suppose the whole line is selected
1728 int selectedStart = 0;
1729 int selectedEnd = nViewLineLength;
1731 // the view line is partially selected
1732 if (m_ptSelectionViewPosStart.y == nViewLine)
1734 selectedStart = m_ptSelectionViewPosStart.x;
1737 if (m_ptSelectionViewPosEnd.y == nViewLine)
1739 selectedEnd = m_ptSelectionViewPosEnd.x;
1741 // apply selection coloring
1742 // First enforce start and end point
1743 lineCols.SplitBlock(selectedStart);
1744 lineCols.SplitBlock(selectedEnd);
1745 // change color of affected parts
1746 long intenseColorScale = m_bFocused ? 70 : 30;
1747 std::map<int, linecolors_t>::iterator it = lineCols.lower_bound(selectedStart);
1748 for ( ; it != lineCols.end() && it->first < selectedEnd; ++it)
1750 COLORREF crBk = CAppUtils::IntenseColor(intenseColorScale, it->second.background);
1751 if (it->second.shot == it->second.background)
1753 it->second.shot = crBk;
1755 it->second.background = crBk;
1756 it->second.text = CAppUtils::IntenseColor(intenseColorScale, it->second.text);
1761 // TODO: remove duplicate from selection and mark
1762 if (!m_sMarkedWord.IsEmpty())
1764 int nMarkLength = m_sMarkedWord.GetLength();
1765 //int nViewLineLength = sViewLine.GetLength();
1766 const TCHAR * text = sViewLine;
1767 const TCHAR * findText = text;
1768 while ((findText = _tcsstr(findText, (LPCTSTR)m_sMarkedWord))!=0)
1770 int nMarkStart = static_cast<int>(findText - text);
1771 int nMarkEnd = nMarkStart + nMarkLength;
1772 findText += nMarkLength;
1773 ECharGroup eLeft = GetCharGroup(sViewLine, nMarkStart - 1);
1774 ECharGroup eStart = GetCharGroup(sViewLine, nMarkStart);
1775 if (eLeft == eStart)
1776 continue;
1777 ECharGroup eRight = GetCharGroup(sViewLine, nMarkEnd);
1778 ECharGroup eEnd = GetCharGroup(sViewLine, nMarkEnd - 1);
1779 if (eRight == eEnd)
1780 continue;
1782 // First enforce start and end point
1783 lineCols.SplitBlock(nMarkStart);
1784 lineCols.SplitBlock(nMarkEnd);
1785 // change color of affected parts
1786 const long int nIntenseColorScale = 200;
1787 std::map<int, linecolors_t>::iterator it = lineCols.lower_bound(nMarkStart);
1788 for ( ; it != lineCols.end() && it->first < nMarkEnd; ++it)
1790 COLORREF crBk = CAppUtils::IntenseColor(nIntenseColorScale, it->second.background);
1791 if (it->second.shot == it->second.background)
1793 it->second.shot = crBk;
1795 it->second.background = crBk;
1796 it->second.text = CAppUtils::IntenseColor(nIntenseColorScale, it->second.text);
1800 if (!m_sFindText.IsEmpty())
1802 int nMarkStart = 0;
1803 int nMarkEnd = 0;
1804 int nStringPos = nMarkStart;
1805 CString searchLine = sViewLine;
1806 if (!m_bMatchCase)
1807 searchLine.MakeLower();
1808 while (StringFound(searchLine, SearchNext, nMarkStart, nMarkEnd)!=0)
1810 // First enforce start and end point
1811 lineCols.SplitBlock(nMarkStart+nStringPos);
1812 lineCols.SplitBlock(nMarkEnd+nStringPos);
1813 // change color of affected parts
1814 const long int nIntenseColorScale = 30;
1815 std::map<int, linecolors_t>::iterator it = lineCols.lower_bound(nMarkStart+nStringPos);
1816 for ( ; it != lineCols.end() && it->first < nMarkEnd; ++it)
1818 COLORREF crBk = CAppUtils::IntenseColor(nIntenseColorScale, it->second.background);
1819 if (it->second.shot == it->second.background)
1821 it->second.shot = crBk;
1823 it->second.background = crBk;
1824 it->second.text = CAppUtils::IntenseColor(nIntenseColorScale, it->second.text);
1826 searchLine = searchLine.Mid(nMarkEnd);
1827 nStringPos = nMarkEnd;
1828 nMarkStart = 0;
1829 nMarkEnd = 0;
1833 // @ this point we may cache data for next line which may be same in wrapped mode
1835 int nTextOffset = 0;
1836 int nSubline = GetSubLineOffset(nLineIndex);
1837 for (int n=0; n<nSubline; n++)
1839 CString sLine = m_ScreenedViewLine[nViewLine].SubLines[n];
1840 nTextOffset += sLine.GetLength();
1843 CString sLine = GetLineChars(nLineIndex);
1844 int nLineLength = sLine.GetLength();
1845 CString sLineExp = ExpandChars(sLine);
1846 LPCTSTR textExp = sLineExp;
1847 //int nLineLengthExp = sLineExp.GetLength();
1848 int nStartExp = 0;
1849 int nLeft = coords.x;
1850 for (std::map<int, linecolors_t>::const_iterator itStart = lineCols.begin(); itStart != lineCols.end(); ++itStart)
1852 std::map<int, linecolors_t>::const_iterator itEnd = itStart;
1853 ++itEnd;
1854 int nStart = std::max<int>(0, itStart->first - nTextOffset);
1855 int nEnd = nLineLength;
1856 if (itEnd != lineCols.end())
1858 nEnd = std::min<int>(nEnd, itEnd->first - nTextOffset);
1860 int nBlockLength = nEnd - nStart;
1861 if (nBlockLength > 0 && nEnd>=0)
1863 pDC->SetBkColor(itStart->second.background);
1864 pDC->SetTextColor(itStart->second.text);
1865 int nEndExp = CountExpandedChars(sLine, nEnd);
1866 int nTextLength = nEndExp - nStartExp;
1867 LPCTSTR p_zBlockText = textExp + nStartExp;
1868 SIZE Size;
1869 GetTextExtentPoint32(pDC->GetSafeHdc(), p_zBlockText, nTextLength, &Size); // falls time-2-tme
1870 int nRight = nLeft + Size.cx;
1871 if ((nRight > rc.left) && (nLeft < rc.right))
1873 // note: ExtTextOut has a limit for the length of the string. That limit is supposed
1874 // to be 8192, but that's not really true: I found that the limit (at least on my machine and a few others)
1875 // is 4094 (4095 doesn't work anymore).
1876 // So we limit the length here to that 4094 chars.
1877 // In case we're scrolled to the right, there's no need to draw the string
1878 // from way outside our window, so we also offset the drawing to the start of the window.
1879 // This reduces the string length as well.
1880 int offset = 0;
1881 int leftcoord = nLeft;
1882 if (nLeft < 0)
1884 int fit = nTextLength;
1885 std::unique_ptr<int> posBuffer(new int[fit]);
1886 GetTextExtentExPoint(pDC->GetSafeHdc(), p_zBlockText, nTextLength, INT_MAX, &fit, posBuffer.get(), &Size);
1887 int lower = 0, upper = fit - 1;
1890 int middle = (upper + lower + 1) / 2;
1891 int width = posBuffer.get()[middle];
1892 if (rc.left - nLeft < width)
1893 upper = middle - 1;
1894 else
1895 lower = middle;
1896 } while (lower < upper);
1898 offset = lower;
1899 nTextLength -= offset;
1900 leftcoord += lower > 0 ? posBuffer.get()[lower - 1] : 0;
1903 pDC->ExtTextOut(leftcoord, coords.y, ETO_CLIPPED, &rc, p_zBlockText+offset, min(nTextLength, 4094), NULL);
1904 if ((itStart->second.shot != itStart->second.background) && (itStart->first == nStart + nTextOffset))
1906 pDC->FillSolidRect(nLeft-1, rc.top, 1, rc.Height(), itStart->second.shot);
1909 nLeft = nRight;
1910 coords.x = nRight;
1911 nStartExp = nEndExp;
1916 void CBaseView::DrawSingleLine(CDC *pDC, const CRect &rc, int nLineIndex)
1918 if (nLineIndex >= GetLineCount())
1919 nLineIndex = -1;
1920 ASSERT(nLineIndex >= -1);
1922 if ((nLineIndex == -1) || !m_pViewData)
1924 // Draw line beyond the text
1925 COLORREF crBkgnd, crText;
1926 CDiffColors::GetInstance().GetColors(DIFFSTATE_UNKNOWN, crBkgnd, crText);
1927 pDC->FillSolidRect(rc, crBkgnd);
1928 return;
1931 int viewLine = GetViewLineForScreen(nLineIndex);
1932 if (m_pMainFrame->m_bCollapsed)
1934 if (m_pViewData->GetHideState(viewLine) == HIDESTATE_MARKER)
1936 COLORREF crBkgnd, crText;
1937 CDiffColors::GetInstance().GetColors(DIFFSTATE_UNKNOWN, crBkgnd, crText);
1938 pDC->FillSolidRect(rc, crBkgnd);
1940 const int THICKNESS = 2;
1941 COLORREF rectcol = GetSysColor(COLOR_WINDOWTEXT);
1942 pDC->FillSolidRect(rc.left, rc.top + (rc.Height()/2), rc.Width(), THICKNESS, rectcol);
1943 pDC->SetTextColor(GetSysColor(COLOR_GRAYTEXT));
1944 pDC->SetBkColor(crBkgnd);
1945 CRect rect = rc;
1946 pDC->DrawText(_T("{...}"), &rect, DT_NOPREFIX|DT_SINGLELINE|DT_CENTER);
1947 return;
1951 DiffStates diffState = m_pViewData->GetState(viewLine);
1952 COLORREF crBkgnd, crText;
1953 CDiffColors::GetInstance().GetColors(diffState, crBkgnd, crText);
1955 if (diffState == DIFFSTATE_CONFLICTED)
1957 // conflicted lines are shown without 'text' on them
1958 CRect rect = rc;
1959 pDC->FillSolidRect(rc, crBkgnd);
1960 // now draw some faint text patterns
1961 pDC->SetTextColor(CAppUtils::IntenseColor(130, crBkgnd));
1962 pDC->DrawText(m_sConflictedText, rect, DT_LEFT|DT_NOPREFIX|DT_SINGLELINE);
1963 DrawBlockLine(pDC, rc, nLineIndex);
1964 return;
1967 CPoint origin(rc.left - m_nOffsetChar * GetCharWidth(), rc.top);
1968 CString sLine = GetLineChars(nLineIndex);
1969 if (sLine.IsEmpty())
1971 pDC->FillSolidRect(rc, crBkgnd);
1972 DrawBlockLine(pDC, rc, nLineIndex);
1973 DrawLineEnding(pDC, rc, nLineIndex, origin);
1974 return;
1977 CheckOtherView();
1979 // Draw the line
1981 pDC->SelectObject(GetFont(FALSE, FALSE));
1983 DrawTextLine(pDC, rc, nLineIndex, origin);
1985 // draw white space after the end of line
1986 CRect frect = rc;
1987 if (origin.x > frect.left)
1988 frect.left = origin.x;
1989 if (frect.right > frect.left)
1990 pDC->FillSolidRect(frect, crBkgnd);
1992 // draw the whitespace chars
1993 LPCTSTR pszChars = (LPCWSTR)sLine;
1994 if (m_bViewWhitespace)
1996 int xpos = 0;
1997 int nChars = 0;
1998 LPCTSTR pLastSpace = pszChars;
1999 int y = rc.top + (rc.bottom-rc.top)/2;
2000 xpos -= m_nOffsetChar * GetCharWidth();
2002 CPen pen(PS_SOLID, 0, m_WhiteSpaceFg);
2003 CPen pen2(PS_SOLID, 2, m_WhiteSpaceFg);
2004 while (*pszChars)
2006 switch (*pszChars)
2008 case '\t':
2010 xpos += pDC->GetTextExtent(pLastSpace, (int)(pszChars - pLastSpace)).cx;
2011 pLastSpace = pszChars + 1;
2012 // draw an arrow
2013 int nSpaces = GetTabSize() - nChars % GetTabSize();
2014 if (xpos + nSpaces * GetCharWidth() > 0)
2016 int xposreal = max(xpos, 0);
2017 if ((xposreal > 0) || (nSpaces > 0))
2019 CPen * oldPen = pDC->SelectObject(&pen);
2020 pDC->MoveTo(xposreal + rc.left, y);
2021 pDC->LineTo((xpos + nSpaces * GetCharWidth()) + rc.left - 2, y);
2022 pDC->LineTo((xpos + nSpaces * GetCharWidth()) + rc.left - 6, y - 4);
2023 pDC->MoveTo((xpos + nSpaces * GetCharWidth()) + rc.left - 2, y);
2024 pDC->LineTo((xpos + nSpaces * GetCharWidth()) + rc.left - 6, y + 4);
2025 pDC->SelectObject(oldPen);
2028 xpos += nSpaces * GetCharWidth();
2029 nChars += nSpaces;
2031 break;
2032 case ' ':
2034 xpos += pDC->GetTextExtent(pLastSpace, (int)(pszChars - pLastSpace)).cx;
2035 pLastSpace = pszChars + 1;
2036 // draw a small dot
2037 if (xpos >= 0)
2039 CPen * oldPen = pDC->SelectObject(&pen2);
2040 pDC->MoveTo(xpos + rc.left + GetCharWidth()/2-1, y);
2041 pDC->LineTo(xpos + rc.left + GetCharWidth()/2+1, y);
2042 pDC->SelectObject(oldPen);
2044 xpos += GetCharWidth();
2045 nChars++;
2047 break;
2048 default:
2049 nChars++;
2050 break;
2052 pszChars++;
2055 DrawBlockLine(pDC, rc, nLineIndex);
2056 if (origin.x >= rc.left)
2057 DrawLineEnding(pDC, rc, nLineIndex, origin);
2060 void CBaseView::ExpandChars(const CString &sLine, int nOffset, int nCount, CString &line)
2062 if (nCount <= 0)
2064 line = _T("");
2065 return;
2068 int nTabSize = GetTabSize();
2070 int nActualOffset = CountExpandedChars(sLine, nOffset);
2072 LPCTSTR pszChars = (LPCWSTR)sLine;
2073 pszChars += nOffset;
2074 int nLength = nCount;
2076 int nTabCount = 0;
2077 for (int i=0; i<nLength; i++)
2079 if (pszChars[i] == _T('\t'))
2080 nTabCount ++;
2083 LPTSTR pszBuf = line.GetBuffer(nLength + nTabCount * (nTabSize - 1) + 1);
2084 int nCurPos = 0;
2085 if (nTabCount > 0 || m_bViewWhitespace)
2087 for (int i=0; i<nLength; i++)
2089 if (pszChars[i] == _T('\t'))
2091 int nSpaces = nTabSize - (nActualOffset + nCurPos) % nTabSize;
2092 while (nSpaces > 0)
2094 pszBuf[nCurPos ++] = _T(' ');
2095 nSpaces --;
2098 else
2100 pszBuf[nCurPos] = pszChars[i];
2101 nCurPos ++;
2105 else
2107 memcpy(pszBuf, pszChars, sizeof(TCHAR) * nLength);
2108 nCurPos = nLength;
2110 pszBuf[nCurPos] = 0;
2111 line.ReleaseBuffer();
2114 CString CBaseView::ExpandChars(const CString &sLine, int nOffset)
2116 CString sRet;
2117 int nLength = sLine.GetLength();
2118 ExpandChars(sLine, nOffset, nLength, sRet);
2119 return sRet;
2122 int CBaseView::CountExpandedChars(const CString &sLine, int nLength)
2124 int nTabSize = GetTabSize();
2126 int nActualOffset = 0;
2127 for (int i=0; i<nLength; i++)
2129 if (sLine[i] == _T('\t'))
2130 nActualOffset += (nTabSize - nActualOffset % nTabSize);
2131 else
2132 nActualOffset ++;
2134 return nActualOffset;
2137 void CBaseView::ScrollAllToLine(int nNewTopLine, BOOL bTrackScrollBar)
2139 if (m_pwndLeft)
2140 m_pwndLeft->ScrollToLine(nNewTopLine, bTrackScrollBar);
2141 if (m_pwndRight)
2142 m_pwndRight->ScrollToLine(nNewTopLine, bTrackScrollBar);
2143 if (m_pwndBottom)
2144 m_pwndBottom->ScrollToLine(nNewTopLine, bTrackScrollBar);
2145 if (m_pwndLocator)
2146 m_pwndLocator->Invalidate();
2149 void CBaseView::GoToLine(int nNewLine, BOOL bAll)
2151 //almost the same as ScrollAllToLine, but try to put the line in the
2152 //middle of the view, not on top
2153 int nNewTopLine = nNewLine - GetScreenLines()/2;
2154 if (nNewTopLine < 0)
2155 nNewTopLine = 0;
2156 if (nNewTopLine >= (int)m_Screen2View.size())
2157 nNewTopLine = (int)m_Screen2View.size()-1;
2158 if (bAll)
2159 ScrollAllToLine(nNewTopLine);
2160 else
2161 ScrollToLine(nNewTopLine);
2164 BOOL CBaseView::OnEraseBkgnd(CDC* /*pDC*/)
2166 return TRUE;
2169 int CBaseView::OnCreate(LPCREATESTRUCT lpCreateStruct)
2171 if (CView::OnCreate(lpCreateStruct) == -1)
2172 return -1;
2174 SecureZeroMemory(&m_lfBaseFont, sizeof(m_lfBaseFont));
2175 //lstrcpy(m_lfBaseFont.lfFaceName, _T("Courier New"));
2176 //lstrcpy(m_lfBaseFont.lfFaceName, _T("FixedSys"));
2177 m_lfBaseFont.lfHeight = 0;
2178 m_lfBaseFont.lfWeight = FW_NORMAL;
2179 m_lfBaseFont.lfItalic = FALSE;
2180 m_lfBaseFont.lfCharSet = DEFAULT_CHARSET;
2181 m_lfBaseFont.lfOutPrecision = OUT_DEFAULT_PRECIS;
2182 m_lfBaseFont.lfClipPrecision = CLIP_DEFAULT_PRECIS;
2183 m_lfBaseFont.lfQuality = DEFAULT_QUALITY;
2184 m_lfBaseFont.lfPitchAndFamily = DEFAULT_PITCH;
2186 return 0;
2189 void CBaseView::OnDestroy()
2191 if ((m_pFindDialog)&&(!m_pFindDialog->IsTerminating()))
2193 m_pFindDialog->SendMessage(WM_CLOSE);
2194 return;
2196 CView::OnDestroy();
2197 DeleteFonts();
2198 ReleaseBitmap();
2201 void CBaseView::OnSize(UINT nType, int cx, int cy)
2203 CView::OnSize(nType, cx, cy);
2204 ReleaseBitmap();
2206 m_nScreenLines = -1;
2207 m_nScreenChars = -1;
2208 if (m_nLastScreenChars != GetScreenChars())
2210 BuildAllScreen2ViewVector();
2211 m_nLastScreenChars = m_nScreenChars;
2212 if (m_pMainFrame && m_pMainFrame->m_bWrapLines)
2214 // if we're in wrap mode, the line wrapping most likely changed
2215 // and that means we have to redraw the whole window, not just the
2216 // scrolled part.
2217 Invalidate(FALSE);
2219 else
2221 // make sure the view header is redrawn
2222 CRect rcScroll;
2223 GetClientRect(&rcScroll);
2224 rcScroll.bottom = GetLineHeight()+HEADERHEIGHT;
2225 InvalidateRect(&rcScroll, FALSE);
2228 else
2230 // make sure the view header is redrawn
2231 CRect rcScroll;
2232 GetClientRect(&rcScroll);
2233 rcScroll.bottom = GetLineHeight()+HEADERHEIGHT;
2234 InvalidateRect(&rcScroll, FALSE);
2236 UpdateLocator();
2237 RecalcVertScrollBar();
2238 RecalcHorzScrollBar();
2240 UpdateCaret();
2243 BOOL CBaseView::OnMouseWheel(UINT nFlags, short zDelta, CPoint pt)
2245 if (m_pwndLeft)
2246 m_pwndLeft->OnDoMouseWheel(nFlags, zDelta, pt);
2247 if (m_pwndRight)
2248 m_pwndRight->OnDoMouseWheel(nFlags, zDelta, pt);
2249 if (m_pwndBottom)
2250 m_pwndBottom->OnDoMouseWheel(nFlags, zDelta, pt);
2251 if (m_pwndLocator)
2252 m_pwndLocator->Invalidate();
2253 return CView::OnMouseWheel(nFlags, zDelta, pt);
2256 void CBaseView::OnMouseHWheel(UINT nFlags, short zDelta, CPoint pt)
2258 if (m_pwndLeft)
2259 m_pwndLeft->OnDoMouseHWheel(nFlags, zDelta, pt);
2260 if (m_pwndRight)
2261 m_pwndRight->OnDoMouseHWheel(nFlags, zDelta, pt);
2262 if (m_pwndBottom)
2263 m_pwndBottom->OnDoMouseHWheel(nFlags, zDelta, pt);
2264 if (m_pwndLocator)
2265 m_pwndLocator->Invalidate();
2268 void CBaseView::OnDoMouseWheel(UINT /*nFlags*/, short zDelta, CPoint /*pt*/)
2270 bool bControl = !!(GetKeyState(VK_CONTROL)&0x8000);
2271 bool bShift = !!(GetKeyState(VK_SHIFT)&0x8000);
2273 if (bControl || bShift)
2275 if (m_pMainFrame->m_bWrapLines)
2276 return;
2277 // Ctrl-Wheel scrolls sideways
2278 ScrollSide(-zDelta/30);
2280 else
2282 ScrollVertical(zDelta);
2286 void CBaseView::OnDoMouseHWheel(UINT /*nFlags*/, short zDelta, CPoint /*pt*/)
2288 bool bControl = !!(GetKeyState(VK_CONTROL)&0x8000);
2289 bool bShift = !!(GetKeyState(VK_SHIFT)&0x8000);
2291 if (bControl || bShift)
2293 ScrollVertical(zDelta);
2295 else
2297 if (m_pMainFrame->m_bWrapLines)
2298 return;
2299 // Ctrl-Wheel scrolls sideways
2300 ScrollSide(-zDelta/30);
2304 BOOL CBaseView::OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message)
2306 if (nHitTest == HTCLIENT)
2308 if ((m_pViewData)&&(m_pMainFrame->m_bCollapsed))
2310 if (m_nMouseLine < (int)m_Screen2View.size())
2312 if (m_nMouseLine >= 0)
2314 int viewLine = GetViewLineForScreen(m_nMouseLine);
2315 if (viewLine < m_pViewData->GetCount())
2317 if (m_pViewData->GetHideState(viewLine) == HIDESTATE_MARKER)
2319 ::SetCursor(::LoadCursor(NULL, MAKEINTRESOURCE(IDC_HAND)));
2320 return TRUE;
2326 if (m_mouseInMargin)
2328 ::SetCursor(m_margincursor);
2329 return TRUE;
2331 if (m_nMouseLine >= 0)
2333 ::SetCursor(::LoadCursor(NULL, MAKEINTRESOURCE(IDC_IBEAM))); // Set To Edit Cursor
2334 return TRUE;
2337 ::SetCursor(::LoadCursor(NULL, MAKEINTRESOURCE(IDC_ARROW))); // Set To Arrow Cursor
2338 return TRUE;
2340 return CView::OnSetCursor(pWnd, nHitTest, message);
2343 void CBaseView::OnKillFocus(CWnd* pNewWnd)
2345 CView::OnKillFocus(pNewWnd);
2346 m_bFocused = FALSE;
2347 UpdateCaret();
2348 Invalidate();
2351 void CBaseView::OnSetFocus(CWnd* pOldWnd)
2353 CView::OnSetFocus(pOldWnd);
2354 m_bFocused = TRUE;
2355 UpdateCaret();
2356 Invalidate();
2359 int CBaseView::GetLineFromPoint(CPoint point)
2361 ScreenToClient(&point);
2362 return (((point.y - HEADERHEIGHT) / GetLineHeight()) + m_nTopLine);
2365 void CBaseView::OnContextMenu(CPoint point, DiffStates state)
2367 if (!this->IsWindowVisible())
2368 return;
2370 CIconMenu popup;
2371 if (!popup.CreatePopupMenu())
2372 return;
2374 AddContextItems(popup, state);
2376 CMenu popupEols;
2377 CMenu popupUnicode;
2378 int nEncodingCommandBase = POPUPCOMMAND__LAST;
2379 int nEolCommandBase = nEncodingCommandBase+_countof(uctArray);
2380 if (IsWritable())
2382 CString temp;
2383 TWhitecharsProperties oWhites = GetWhitecharsProperties();
2384 temp.LoadString(IDS_EDIT_TAB2SPACE);
2385 popup.AppendMenu((MF_STRING | oWhites.HasTabsToConvert) ? MF_ENABLED : (MF_DISABLED|MF_GRAYED), POPUPCOMMAND_TABTOSPACES, temp);
2386 temp.LoadString(IDS_EDIT_SPACE2TAB);
2387 popup.AppendMenu((MF_STRING | oWhites.HasSpacesToConvert) ? MF_ENABLED : (MF_DISABLED|MF_GRAYED), POPUPCOMMAND_SPACESTOTABS, temp);
2388 temp.LoadString(IDS_EDIT_TRIM);
2389 popup.AppendMenu((MF_STRING | oWhites.HasTrailWhiteChars) ? MF_ENABLED : (MF_DISABLED|MF_GRAYED), POPUPCOMMAND_REMOVETRAILWHITES, temp);
2391 // add eol submenu
2392 if (!popupEols.CreatePopupMenu())
2393 return;
2395 EOL eEolType = GetLineEndings(oWhites.HasMixedEols);
2396 for (int i = 1; i < _countof(eolArray); i++)
2398 CString temp = GetEolName(eolArray[i]);
2399 bool bChecked = (eEolType == eolArray[i]);
2400 popupEols.AppendMenu(MF_STRING | MF_ENABLED | (bChecked ? MF_CHECKED : 0), nEolCommandBase+i, temp);
2403 temp.LoadString(IDS_VIEWCONTEXTMENU_EOL);
2404 popup.AppendMenuW(MF_POPUP | MF_ENABLED, (UINT_PTR)popupEols.GetSafeHmenu(), temp);
2406 // add encoding submenu
2407 if (!popupUnicode.CreatePopupMenu())
2408 return;
2409 for (int i = 0; i < _countof(uctArray); i++)
2411 CString temp = CFileTextLines::GetEncodingName(uctArray[i]);
2412 bool bChecked = (m_texttype == uctArray[i]);
2413 popupUnicode.AppendMenu(MF_STRING | MF_ENABLED | (bChecked ? MF_CHECKED : 0), nEncodingCommandBase+i, temp);
2415 temp.LoadString(IDS_VIEWCONTEXTMENU_ENCODING);
2416 popup.AppendMenuW(MF_POPUP | MF_ENABLED, (UINT_PTR)popupUnicode.GetSafeHmenu(), temp);
2420 CompensateForKeyboard(point);
2422 int cmd = popup.TrackPopupMenu(TPM_RETURNCMD | TPM_LEFTALIGN | TPM_NONOTIFY | TPM_RIGHTBUTTON, point.x, point.y, this, 0);
2423 ResetUndoStep();
2424 if ((cmd>=nEncodingCommandBase) && (cmd<nEncodingCommandBase+(int)_countof(uctArray)))
2426 SetTextType(uctArray[cmd-nEncodingCommandBase]);
2428 if ((cmd>=nEolCommandBase) && (cmd<nEolCommandBase+(int)_countof(eolArray)))
2430 ReplaceLineEndings(eolArray[cmd-nEolCommandBase]);
2431 SaveUndoStep();
2433 switch (cmd)
2435 // 2-pane view commands; target is right view
2436 case POPUPCOMMAND_USELEFTBLOCK:
2437 m_pwndRight->UseLeftBlock();
2438 break;
2439 case POPUPCOMMAND_USELEFTFILE:
2440 m_pwndRight->UseLeftFile();
2441 break;
2442 case POPUPCOMMAND_USEBOTHLEFTFIRST:
2443 m_pwndRight->UseBothLeftFirst();
2444 break;
2445 case POPUPCOMMAND_USEBOTHRIGHTFIRST:
2446 m_pwndRight->UseBothRightFirst();
2447 break;
2448 case POPUPCOMMAND_MARKBLOCK:
2449 m_pwndRight->MarkBlock(true);
2450 break;
2451 case POPUPCOMMAND_UNMARKBLOCK:
2452 m_pwndRight->MarkBlock(false);
2453 break;
2454 case POPUPCOMMAND_LEAVEONLYMARKEDBLOCKS:
2455 m_pwndRight->LeaveOnlyMarkedBlocks();
2456 break;
2457 // 2-pane view multiedit commands; target is left view
2458 case POPUPCOMMAND_PREPENDFROMRIGHT:
2459 if (!m_pwndLeft->IsReadonly())
2460 m_pwndLeft->UseBothRightFirst();
2461 break;
2462 case POPUPCOMMAND_REPLACEBYRIGHT:
2463 if (!m_pwndLeft->IsReadonly())
2464 m_pwndLeft->UseRightBlock();
2465 break;
2466 case POPUPCOMMAND_APPENDFROMRIGHT:
2467 if (!m_pwndLeft->IsReadonly())
2468 m_pwndLeft->UseBothLeftFirst();
2469 break;
2470 case POPUPCOMMAND_USERIGHTFILE:
2471 m_pwndLeft->UseRightFile();
2472 break;
2473 // 3-pane view commands; target is bottom view
2474 case POPUPCOMMAND_USEYOURANDTHEIRBLOCK:
2475 m_pwndBottom->UseBothRightFirst();
2476 break;
2477 case POPUPCOMMAND_USETHEIRANDYOURBLOCK:
2478 m_pwndBottom->UseBothLeftFirst();
2479 break;
2480 case POPUPCOMMAND_USEYOURBLOCK:
2481 m_pwndBottom->UseRightBlock();
2482 break;
2483 case POPUPCOMMAND_USEYOURFILE:
2484 m_pwndBottom->UseRightFile();
2485 break;
2486 case POPUPCOMMAND_USETHEIRBLOCK:
2487 m_pwndBottom->UseLeftBlock();
2488 break;
2489 case POPUPCOMMAND_USETHEIRFILE:
2490 m_pwndBottom->UseLeftFile();
2491 break;
2492 // copy, cut and paste commands
2493 case ID_EDIT_COPY:
2494 OnEditCopy();
2495 break;
2496 case ID_EDIT_CUT:
2497 OnEditCut();
2498 break;
2499 case ID_EDIT_PASTE:
2500 OnEditPaste();
2501 break;
2502 // white chars manipulations
2503 case POPUPCOMMAND_TABTOSPACES:
2504 ConvertTabToSpaces();
2505 break;
2506 case POPUPCOMMAND_SPACESTOTABS:
2507 Tabularize();
2508 break;
2509 case POPUPCOMMAND_REMOVETRAILWHITES:
2510 RemoveTrailWhiteChars();
2511 break;
2512 default:
2513 return;
2514 } // switch (cmd)
2515 SaveUndoStep(); // all except copy, cut paste save undo step, but this should not be harmful as step is empty already and thus not saved
2516 return;
2519 void CBaseView::OnContextMenu(CWnd* /*pWnd*/, CPoint point)
2521 if (!m_pViewData)
2522 return;
2524 int nViewBlockStart = -1;
2525 int nViewBlockEnd = -1;
2526 GetViewSelection(nViewBlockStart, nViewBlockEnd);
2527 if ((point.x >= 0) && (point.y >= 0))
2529 int nLine = GetLineFromPoint(point)-1;
2530 if ((nLine >= 0) && (nLine < m_Screen2View.size()))
2532 int nViewLine = GetViewLineForScreen(nLine);
2533 if (((nViewLine < nViewBlockStart) || (nViewBlockEnd < nViewLine)))
2535 ClearSelection(); // Clear text-copy selection
2537 nViewBlockStart = nViewLine;
2538 nViewBlockEnd = nViewLine;
2539 DiffStates state = m_pViewData->GetState(nViewLine);
2540 while (nViewBlockStart > 0)
2542 const DiffStates lineState = m_pViewData->GetState(nViewBlockStart-1);
2543 if (!LinesInOneChange(-1, state, lineState))
2544 break;
2545 nViewBlockStart--;
2548 while (nViewBlockEnd < (m_pViewData->GetCount()-1))
2550 const DiffStates lineState = m_pViewData->GetState(nViewBlockEnd+1);
2551 if (!LinesInOneChange(1, state, lineState))
2552 break;
2553 nViewBlockEnd++;
2556 SetupAllViewSelection(nViewBlockStart, nViewBlockEnd);
2557 UpdateCaretPosition(point);
2562 // FixSelection(); fix selection range
2563 /*if (m_nSelBlockEnd >= m_pViewData->GetCount())
2564 m_nSelBlockEnd = m_pViewData->GetCount()-1;//*/
2566 DiffStates state = DIFFSTATE_UNKNOWN;
2567 if (GetViewSelection(nViewBlockStart, nViewBlockEnd))
2569 // find a more 'relevant' state in the selection
2570 for (int i=nViewBlockStart; i<=nViewBlockEnd; ++i)
2572 state = m_pViewData->GetState(i);
2573 if ((state != DIFFSTATE_NORMAL) && (state != DIFFSTATE_UNKNOWN))
2574 break;
2577 OnContextMenu(point, state);
2580 void CBaseView::RefreshViews()
2582 if (m_pwndLeft)
2584 m_pwndLeft->UpdateStatusBar();
2585 m_pwndLeft->Invalidate();
2587 if (m_pwndRight)
2589 m_pwndRight->UpdateStatusBar();
2590 m_pwndRight->Invalidate();
2592 if (m_pwndBottom)
2594 m_pwndBottom->UpdateStatusBar();
2595 m_pwndBottom->Invalidate();
2597 if (m_pwndLocator)
2598 m_pwndLocator->Invalidate();
2601 void CBaseView::GoToFirstDifference()
2603 SetCaretToFirstViewLine();
2604 SelectNextBlock(1, false, false);
2607 void CBaseView::GoToFirstConflict()
2609 SetCaretToFirstViewLine();
2610 SelectNextBlock(1, true, false);
2613 void CBaseView::HighlightLines(int nStart, int nEnd /* = -1 */)
2615 ClearSelection();
2616 SetupAllSelection(nStart, max(nStart, nEnd));
2618 UpdateCaretPosition(SetupPoint(0, nStart));
2619 Invalidate();
2622 void CBaseView::HighlightViewLines(int nStart, int nEnd /* = -1 */)
2624 ClearSelection();
2625 SetupAllViewSelection(nStart, max(nStart, nEnd));
2627 UpdateCaretViewPosition(SetupPoint(0, nStart));
2628 Invalidate();
2631 void CBaseView::SetupAllViewSelection(int start, int end)
2633 SetupViewSelection(m_pwndBottom, start, end);
2634 SetupViewSelection(m_pwndLeft, start, end);
2635 SetupViewSelection(m_pwndRight, start, end);
2638 void CBaseView::SetupAllSelection(int start, int end)
2640 SetupAllViewSelection(GetViewLineForScreen(start), GetViewLineForScreen(end));
2643 //void CBaseView::SetupSelection(CBaseView* view, int start, int end) { }
2645 void CBaseView::SetupSelection(int start, int end)
2647 SetupViewSelection(GetViewLineForScreen(start), GetViewLineForScreen(end));
2650 void CBaseView::SetupViewSelection(CBaseView* view, int start, int end)
2652 if (!IsViewGood(view))
2653 return;
2654 view->SetupViewSelection(start, end);
2657 void CBaseView::SetupViewSelection(int start, int end)
2659 // clear text selection before setting line selection ?
2660 m_nSelViewBlockStart = start;
2661 m_nSelViewBlockEnd = end;
2662 Invalidate();
2666 void CBaseView::OnMergePreviousconflict()
2668 SelectNextBlock(-1, true);
2671 void CBaseView::OnMergeNextconflict()
2673 SelectNextBlock(1, true);
2676 void CBaseView::OnMergeNextdifference()
2678 SelectNextBlock(1, false);
2681 void CBaseView::OnMergePreviousdifference()
2683 SelectNextBlock(-1, false);
2686 bool CBaseView::HasNextConflict()
2688 return SelectNextBlock(1, true, true, true);
2691 bool CBaseView::HasPrevConflict()
2693 return SelectNextBlock(-1, true, true, true);
2696 bool CBaseView::HasNextDiff()
2698 return SelectNextBlock(1, false, true, true);
2701 bool CBaseView::HasPrevDiff()
2703 return SelectNextBlock(-1, false, true, true);
2706 bool CBaseView::LinesInOneChange(int direction,
2707 DiffStates initialLineState, DiffStates currentLineState)
2709 // Checks whether all the adjacent lines starting from the initial line
2710 // and up to the current line form the single change
2712 // First of all, if the two lines have identical states, they surely
2713 // belong to one change.
2714 if (initialLineState == currentLineState)
2715 return true;
2717 // Either we move down and initial line state is "added" or "removed" and
2718 // current line state is "empty"...
2719 if (direction > 0)
2721 if (currentLineState == DIFFSTATE_EMPTY)
2723 if (initialLineState == DIFFSTATE_ADDED || initialLineState == DIFFSTATE_REMOVED)
2724 return true;
2726 if (initialLineState == DIFFSTATE_CONFLICTADDED && currentLineState == DIFFSTATE_CONFLICTEMPTY)
2727 return true;
2729 // ...or we move up and initial line state is "empty" and current line
2730 // state is "added" or "removed".
2731 if (direction < 0)
2733 if (initialLineState == DIFFSTATE_EMPTY)
2735 if (currentLineState == DIFFSTATE_ADDED || currentLineState == DIFFSTATE_REMOVED)
2736 return true;
2738 if (initialLineState == DIFFSTATE_CONFLICTEMPTY && currentLineState == DIFFSTATE_CONFLICTADDED)
2739 return true;
2741 return false;
2744 bool CBaseView::SelectNextBlock(int nDirection, bool bConflict, bool bSkipEndOfCurrentBlock /* = true */, bool dryrun /* = false */)
2746 if (! m_pViewData)
2747 return false;
2749 const int linesCount = (int)m_Screen2View.size();
2750 if(linesCount == 0)
2751 return false;
2753 int nCenterPos = GetCaretPosition().y;
2754 int nLimit = -1;
2755 if (nDirection > 0)
2756 nLimit = linesCount;
2758 if (nCenterPos >= linesCount)
2759 nCenterPos = linesCount-1;
2761 if (bSkipEndOfCurrentBlock)
2763 // Find end of current block
2764 const DiffStates state = m_pViewData->GetState(GetViewLineForScreen(nCenterPos));
2765 while (nCenterPos != nLimit)
2767 const DiffStates lineState = m_pViewData->GetState(GetViewLineForScreen(nCenterPos));
2768 if (!LinesInOneChange(nDirection, state, lineState))
2769 break;
2770 nCenterPos += nDirection;
2774 // Find next diff/conflict block
2775 while (nCenterPos != nLimit)
2777 DiffStates linestate = m_pViewData->GetState(GetViewLineForScreen(nCenterPos));
2778 if (!bConflict &&
2779 (linestate != DIFFSTATE_NORMAL) &&
2780 (linestate != DIFFSTATE_UNKNOWN))
2782 break;
2784 if (bConflict &&
2785 ((linestate == DIFFSTATE_CONFLICTADDED) ||
2786 (linestate == DIFFSTATE_CONFLICTED_IGNORED) ||
2787 (linestate == DIFFSTATE_CONFLICTED) ||
2788 (linestate == DIFFSTATE_CONFLICTEMPTY)))
2790 break;
2793 nCenterPos += nDirection;
2795 if (nCenterPos == nLimit)
2796 return false;
2797 if (dryrun)
2798 return (nCenterPos != nLimit);
2800 // Find end of new block
2801 DiffStates state = m_pViewData->GetState(GetViewLineForScreen(nCenterPos));
2802 int nBlockEnd = nCenterPos;
2803 const int maxAllowedLine = nLimit-nDirection;
2804 while (nBlockEnd != maxAllowedLine)
2806 const int lineIndex = nBlockEnd + nDirection;
2807 if (lineIndex >= linesCount)
2808 break;
2809 DiffStates lineState = m_pViewData->GetState(GetViewLineForScreen(lineIndex));
2810 if (!LinesInOneChange(nDirection, state, lineState))
2811 break;
2812 nBlockEnd += nDirection;
2815 int nTopPos = nCenterPos - (GetScreenLines()/2);
2816 if (nTopPos < 0)
2817 nTopPos = 0;
2819 POINT ptCaretPos = {0, nCenterPos};
2820 SetCaretPosition(ptCaretPos);
2821 ClearSelection();
2822 if (nDirection > 0)
2823 SetupAllSelection(nCenterPos, nBlockEnd);
2824 else
2825 SetupAllSelection(nBlockEnd, nCenterPos);
2827 ScrollAllToLine(nTopPos, FALSE);
2828 RecalcAllVertScrollBars(TRUE);
2829 SetCaretToLineStart();
2830 EnsureCaretVisible();
2831 OnNavigateNextinlinediff();
2833 UpdateViewsCaretPosition();
2834 UpdateCaret();
2835 ShowDiffLines(nCenterPos);
2836 return true;
2839 BOOL CBaseView::OnToolTipNotify(UINT /*id*/, NMHDR *pNMHDR, LRESULT *pResult)
2841 if (pNMHDR->idFrom != (UINT)m_hWnd)
2842 return FALSE;
2844 CString strTipText;
2845 strTipText = m_sWindowName + _T("\r\n") + m_sFullFilePath;
2847 DWORD pos = GetMessagePos();
2848 CPoint point(GET_X_LPARAM(pos), GET_Y_LPARAM(pos));
2849 ScreenToClient(&point);
2850 const int nLine = GetButtonEventLineIndex(point);
2852 if (nLine >= 0)
2854 int nViewLine = GetViewLineForScreen(nLine);
2855 if((m_pViewData)&&(nViewLine < m_pViewData->GetCount()))
2857 auto movedIndex = m_pViewData->GetMovedIndex(nViewLine);
2858 if (movedIndex >= 0)
2860 if (m_pViewData->IsMovedFrom(nViewLine))
2862 strTipText.Format(IDS_MOVED_TO_TT, movedIndex+1);
2864 else
2866 strTipText.Format(IDS_MOVED_FROM_TT, movedIndex+1);
2873 *pResult = 0;
2874 if (strTipText.IsEmpty())
2875 return TRUE;
2877 // need to handle both ANSI and UNICODE versions of the message
2878 if (pNMHDR->code == TTN_NEEDTEXTA)
2880 TOOLTIPTEXTA* pTTTA = (TOOLTIPTEXTA*)pNMHDR;
2881 pTTTA->lpszText = m_szTip;
2882 WideCharToMultiByte(CP_ACP, 0, strTipText, -1, m_szTip, strTipText.GetLength()+1, 0, 0);
2884 else
2886 TOOLTIPTEXTW* pTTTW = (TOOLTIPTEXTW*)pNMHDR;
2887 lstrcpyn(m_wszTip, strTipText, min(strTipText.GetLength() + 1, _countof(m_wszTip) - 1));
2888 pTTTW->lpszText = m_wszTip;
2891 return TRUE; // message was handled
2894 INT_PTR CBaseView::OnToolHitTest(CPoint point, TOOLINFO* pTI) const
2896 CRect rcClient;
2897 GetClientRect(rcClient);
2898 CRect textrect(rcClient.left, rcClient.top, rcClient.Width(), m_nLineHeight+HEADERHEIGHT);
2899 int marginwidth = MARGINWIDTH;
2900 if ((m_bViewLinenumbers)&&(m_pViewData)&&(m_pViewData->GetCount())&&(m_nDigits > 0))
2902 marginwidth = (MARGINWIDTH + (m_nDigits * m_nCharWidth) + 2);
2904 CRect borderrect(rcClient.left, rcClient.top+m_nLineHeight+HEADERHEIGHT, marginwidth, rcClient.bottom);
2906 if (textrect.PtInRect(point) || borderrect.PtInRect(point))
2908 // inside the header part of the view (showing the filename)
2909 pTI->hwnd = this->m_hWnd;
2910 this->GetClientRect(&pTI->rect);
2911 pTI->uFlags |= TTF_ALWAYSTIP | TTF_IDISHWND;
2912 pTI->uId = (UINT)m_hWnd;
2913 pTI->lpszText = LPSTR_TEXTCALLBACK;
2915 // we want multi line tooltips
2916 CToolTipCtrl* pToolTip = AfxGetModuleThreadState()->m_pToolTip;
2917 if (pToolTip->GetSafeHwnd() != NULL)
2919 pToolTip->SetMaxTipWidth(INT_MAX);
2922 return (textrect.PtInRect(point) ? 1 : 2);
2925 return -1;
2928 void CBaseView::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags)
2930 bool bControl = !!(GetKeyState(VK_CONTROL)&0x8000);
2931 bool bShift = !!(GetKeyState(VK_SHIFT)&0x8000);
2933 switch (nChar)
2935 case VK_TAB:
2936 if (bControl)
2938 if (this==m_pwndLeft)
2940 if (IsViewGood(m_pwndRight))
2942 m_pwndRight->SetFocus();
2944 else if (IsViewGood(m_pwndBottom))
2946 m_pwndBottom->SetFocus();
2949 else if (this==m_pwndRight)
2951 if (IsViewGood(m_pwndBottom))
2953 m_pwndBottom->SetFocus();
2955 else if (IsViewGood(m_pwndLeft))
2957 m_pwndLeft->SetFocus();
2960 else if (this==m_pwndBottom)
2962 if (IsViewGood(m_pwndLeft))
2964 m_pwndLeft->SetFocus();
2966 else if (IsViewGood(m_pwndRight))
2968 m_pwndRight->SetFocus();
2972 break;
2973 case VK_PRIOR:
2975 POINT ptCaretPos = GetCaretPosition();
2976 ptCaretPos.y -= GetScreenLines();
2977 ptCaretPos.y = max(ptCaretPos.y, 0);
2978 ptCaretPos.x = CalculateCharIndex(ptCaretPos.y, m_nCaretGoalPos);
2979 SetCaretPosition(ptCaretPos);
2980 OnCaretMove(MOVELEFT, bShift);
2981 ShowDiffLines(ptCaretPos.y);
2983 break;
2984 case VK_NEXT:
2986 POINT ptCaretPos = GetCaretPosition();
2987 ptCaretPos.y += GetScreenLines();
2988 if (ptCaretPos.y >= GetLineCount())
2989 ptCaretPos.y = GetLineCount()-1;
2990 ptCaretPos.x = CalculateCharIndex(ptCaretPos.y, m_nCaretGoalPos);
2991 SetCaretPosition(ptCaretPos);
2992 OnCaretMove(MOVERIGHT, bShift);
2993 ShowDiffLines(ptCaretPos.y);
2995 break;
2996 case VK_HOME:
2998 if (bControl)
3000 ScrollAllToLine(0);
3001 SetCaretToViewStart();
3002 m_nCaretGoalPos = 0;
3003 if (bShift)
3004 AdjustSelection(MOVELEFT);
3005 else
3006 ClearSelection();
3007 UpdateCaret();
3009 else
3011 POINT ptCaretPos = GetCaretPosition();
3012 CString sLine = GetLineChars(ptCaretPos.y);
3013 int pos = 0;
3014 while (pos < sLine.GetLength())
3016 if (sLine[pos] != ' ' && sLine[pos] != '\t')
3017 break;
3018 ++pos;
3020 if (ptCaretPos.x == pos)
3022 SetCaretToLineStart();
3023 m_nCaretGoalPos = 0;
3024 OnCaretMove(MOVERIGHT, bShift);
3025 ScrollAllToChar(0);
3027 else
3029 ptCaretPos.x = pos;
3030 SetCaretAndGoalPosition(ptCaretPos);
3031 OnCaretMove(MOVELEFT, bShift);
3035 break;
3036 case VK_END:
3038 if (bControl)
3040 ScrollAllToLine(GetLineCount()-GetAllMinScreenLines());
3041 POINT ptCaretPos;
3042 ptCaretPos.y = GetLineCount()-1;
3043 ptCaretPos.x = GetLineLength(ptCaretPos.y);
3044 SetCaretAndGoalPosition(ptCaretPos);
3045 if (bShift)
3046 AdjustSelection(MOVERIGHT);
3047 else
3048 ClearSelection();
3050 else
3052 POINT ptCaretPos = GetCaretPosition();
3053 ptCaretPos.x = GetLineLength(ptCaretPos.y);
3054 if ((GetSubLineOffset(ptCaretPos.y) != -1) && (GetSubLineOffset(ptCaretPos.y) != CountMultiLines(GetViewLineForScreen(ptCaretPos.y))-1)) // not last screen line of view line
3056 ptCaretPos.x--;
3058 SetCaretAndGoalPosition(ptCaretPos);
3059 OnCaretMove(MOVERIGHT, bShift);
3062 break;
3063 case VK_BACK:
3064 if (IsWritable())
3066 if (! HasTextSelection())
3068 POINT ptCaretPos = GetCaretPosition();
3069 if (ptCaretPos.y == 0 && ptCaretPos.x == 0)
3070 break;
3071 m_ptSelectionViewPosEnd = GetCaretViewPosition();
3072 if (bControl)
3073 MoveCaretWordLeft();
3074 else
3076 while (MoveCaretLeft() && IsViewLineEmpty(GetCaretViewPosition().y))
3080 m_ptSelectionViewPosStart = GetCaretViewPosition();
3082 RemoveSelectedText();
3084 break;
3085 case VK_DELETE:
3086 if (IsWritable())
3088 if (! HasTextSelection())
3090 if (bControl)
3092 m_ptSelectionViewPosStart = GetCaretViewPosition();
3093 MoveCaretWordRight();
3094 m_ptSelectionViewPosEnd = GetCaretViewPosition();
3096 else
3098 if (! MoveCaretRight())
3099 break;
3100 m_ptSelectionViewPosEnd = GetCaretViewPosition();
3101 MoveCaretLeft();
3102 m_ptSelectionViewPosStart = GetCaretViewPosition();
3105 RemoveSelectedText();
3107 break;
3108 case VK_INSERT:
3109 m_bInsertMode = !m_bInsertMode;
3110 UpdateCaret();
3111 break;
3113 CView::OnKeyDown(nChar, nRepCnt, nFlags);
3116 void CBaseView::OnLButtonDown(UINT nFlags, CPoint point)
3118 const int nClickedLine = GetButtonEventLineIndex(point);
3119 if ((nClickedLine >= m_nTopLine)&&(nClickedLine < GetLineCount()))
3121 POINT ptCaretPos;
3122 ptCaretPos.y = nClickedLine;
3123 int xpos2 = CalcColFromPoint(point.x, nClickedLine);
3124 ptCaretPos.x = CalculateCharIndex(ptCaretPos.y, xpos2);
3125 SetCaretAndGoalPosition(ptCaretPos);
3127 if (nFlags & MK_SHIFT)
3128 AdjustSelection(MOVERIGHT);
3129 else
3131 ClearSelection();
3132 SetupAllSelection(ptCaretPos.y, ptCaretPos.y);
3133 if (point.x < GetMarginWidth())
3135 // select the whole line
3136 m_ptSelectionViewPosStart = m_ptSelectionViewPosEnd = GetCaretViewPosition();
3137 m_ptSelectionViewPosEnd.x = GetViewLineLength(m_ptSelectionViewPosEnd.y);
3141 UpdateViewsCaretPosition();
3142 Invalidate();
3145 CView::OnLButtonDown(nFlags, point);
3148 CBaseView::ECharGroup CBaseView::GetCharGroup(wchar_t zChar) const
3150 if (zChar == ' ' || zChar == '\t' )
3152 return CHG_WHITESPACE;
3154 if (zChar < 0x20)
3156 return CHG_CONTROL;
3158 if (m_sWordSeparators.Find(zChar) >= 0)
3160 return CHG_WORDSEPARATOR;
3162 return CHG_WORDLETTER;
3165 void CBaseView::OnLButtonDblClk(UINT nFlags, CPoint point)
3167 if (m_pViewData == 0) {
3168 CView::OnLButtonDblClk(nFlags, point);
3169 return;
3172 const int nClickedLine = GetButtonEventLineIndex(point);
3173 if ( nClickedLine < 0)
3174 return;
3175 int nViewLine = GetViewLineForScreen(nClickedLine);
3176 if (point.x < GetMarginWidth()) // only if double clicked on the margin
3178 if((nViewLine < m_pViewData->GetCount())) // a double click on moved line scrolls to corresponding line
3180 if (m_pViewData->GetMovedIndex(nViewLine)>=0)
3182 int movedindex = m_pViewData->GetMovedIndex(nViewLine);
3183 int screenLine = FindViewLineNumber(movedindex);
3184 int nTop = screenLine - GetScreenLines()/2;
3185 if (nTop < 0)
3186 nTop = 0;
3187 ScrollAllToLine(nTop);
3188 // find and select the whole moved block
3189 int startSel = movedindex;
3190 int endSel = movedindex;
3191 while ((startSel > 0) && (m_pOtherViewData->GetMovedIndex(startSel) >= 0))
3192 startSel--;
3193 startSel++;
3194 while ((endSel < GetLineCount()) && (m_pOtherViewData->GetMovedIndex(endSel) >= 0))
3195 endSel++;
3196 endSel--;
3197 m_pOtherView->SetupSelection(startSel, endSel);
3198 return CView::OnLButtonDblClk(nFlags, point);
3202 if ((m_pMainFrame->m_bCollapsed)&&(m_pViewData->GetHideState(nViewLine) == HIDESTATE_MARKER))
3204 // a double click on a marker expands the hidden text
3205 int i = nViewLine;
3206 while ((i < m_pViewData->GetCount())&&(m_pViewData->GetHideState(i) != HIDESTATE_SHOWN))
3208 if ((m_pwndLeft)&&(m_pwndLeft->m_pViewData))
3209 m_pwndLeft->m_pViewData->SetLineHideState(i, HIDESTATE_SHOWN);
3210 if ((m_pwndRight)&&(m_pwndRight->m_pViewData))
3211 m_pwndRight->m_pViewData->SetLineHideState(i, HIDESTATE_SHOWN);
3212 if ((m_pwndBottom)&&(m_pwndBottom->m_pViewData))
3213 m_pwndBottom->m_pViewData->SetLineHideState(i, HIDESTATE_SHOWN);
3214 i++;
3216 BuildAllScreen2ViewVector();
3217 if (m_pwndLeft)
3218 m_pwndLeft->Invalidate();
3219 if (m_pwndRight)
3220 m_pwndRight->Invalidate();
3221 if (m_pwndBottom)
3222 m_pwndBottom->Invalidate();
3224 else
3226 POINT ptCaretPos;
3227 ptCaretPos.y = nClickedLine;
3228 ptCaretPos.x = CalculateCharIndex(ptCaretPos.y, m_nOffsetChar + (point.x - GetMarginWidth()) / GetCharWidth());
3229 SetCaretPosition(ptCaretPos);
3230 ClearSelection();
3232 POINT ptViewCarret = GetCaretViewPosition();
3233 nViewLine = ptViewCarret.y;
3234 if (nViewLine >= GetViewCount())
3235 return;
3236 const CString &sLine = GetViewLine(nViewLine);
3237 int nLineLength = sLine.GetLength();
3238 int nBasePos = ptViewCarret.x;
3239 // get target char group
3240 ECharGroup eLeft = CHG_UNKNOWN;
3241 if (nBasePos > 0)
3243 eLeft = GetCharGroup(sLine[nBasePos-1]);
3245 ECharGroup eRight = CHG_UNKNOWN;
3246 if (nBasePos < nLineLength)
3248 eRight = GetCharGroup(sLine[nBasePos]);
3250 ECharGroup eTarget = max(eRight, eLeft);
3251 // find left margin
3252 int nLeft = nBasePos;
3253 while (nLeft > 0 && GetCharGroup(sLine[nLeft-1]) == eTarget)
3255 nLeft--;
3257 // get right margin
3258 int nRight = nBasePos;
3259 while (nRight < nLineLength && GetCharGroup(sLine[nRight]) == eTarget)
3261 nRight++;
3263 // set selection
3264 m_ptSelectionViewPosStart.x = nLeft;
3265 m_ptSelectionViewPosStart.y = nViewLine;
3266 m_ptSelectionViewPosEnd.x = nRight;
3267 m_ptSelectionViewPosEnd.y = nViewLine;
3268 m_ptSelectionViewPosOrigin = m_ptSelectionViewPosStart;
3269 SetupAllViewSelection(nViewLine, nViewLine);
3270 // set caret
3271 ptCaretPos = ConvertViewPosToScreen(m_ptSelectionViewPosEnd);
3272 UpdateViewsCaretPosition();
3273 UpdateGoalPos();
3275 // set mark word
3276 m_sPreviousMarkedWord = m_sMarkedWord; // store marked word to recall in case of triple click
3277 int nMarkWidth = max(nRight - nLeft, 0);
3278 m_sMarkedWord = sLine.Mid(m_ptSelectionViewPosStart.x, nMarkWidth).Trim();
3279 if (m_sMarkedWord.Compare(m_sPreviousMarkedWord) == 0)
3281 m_sMarkedWord.Empty();
3284 if (m_pwndLeft)
3285 m_pwndLeft->SetMarkedWord(m_sMarkedWord);
3286 if (m_pwndRight)
3287 m_pwndRight->SetMarkedWord(m_sMarkedWord);
3288 if (m_pwndBottom)
3289 m_pwndBottom->SetMarkedWord(m_sMarkedWord);
3291 Invalidate();
3292 if (m_pwndLocator)
3293 m_pwndLocator->Invalidate();
3296 CView::OnLButtonDblClk(nFlags, point);
3299 void CBaseView::OnLButtonTrippleClick( UINT /*nFlags*/, CPoint point )
3301 const int nClickedLine = GetButtonEventLineIndex(point);
3302 if (((point.y - HEADERHEIGHT) / GetLineHeight()) <= 0)
3304 if (!m_sConvertedFilePath.IsEmpty() && (GetKeyState(VK_CONTROL)&0x8000))
3306 PCIDLIST_ABSOLUTE __unaligned pidl = ILCreateFromPath((LPCTSTR)m_sConvertedFilePath);
3307 if (pidl)
3309 SHOpenFolderAndSelectItems(pidl,0,0,0);
3310 CoTaskMemFree((LPVOID)pidl);
3313 return;
3315 POINT ptCaretPos;
3316 ptCaretPos.y = nClickedLine;
3317 ptCaretPos.x = CalculateCharIndex(ptCaretPos.y, m_nOffsetChar + (point.x - GetMarginWidth()) / GetCharWidth());
3318 SetCaretAndGoalPosition(ptCaretPos);
3319 m_sMarkedWord = m_sPreviousMarkedWord; // recall previous Marked word
3320 if (m_pwndLeft)
3321 m_pwndLeft->SetMarkedWord(m_sMarkedWord);
3322 if (m_pwndRight)
3323 m_pwndRight->SetMarkedWord(m_sMarkedWord);
3324 if (m_pwndBottom)
3325 m_pwndBottom->SetMarkedWord(m_sMarkedWord);
3326 ClearSelection();
3327 m_ptSelectionViewPosStart.x = 0;
3328 m_ptSelectionViewPosStart.y = nClickedLine;
3329 m_ptSelectionViewPosEnd.x = GetLineLength(nClickedLine);
3330 m_ptSelectionViewPosEnd.y = nClickedLine;
3331 SetupSelection(m_ptSelectionViewPosStart.y, m_ptSelectionViewPosEnd.y);
3332 UpdateViewsCaretPosition();
3333 Invalidate();
3334 if (m_pwndLocator)
3335 m_pwndLocator->Invalidate();
3338 void CBaseView::OnEditCopy()
3340 CString sCopyData = GetSelectedText();
3342 if (!sCopyData.IsEmpty())
3344 CStringUtils::WriteAsciiStringToClipboard(sCopyData, m_hWnd);
3348 void CBaseView::OnMouseMove(UINT nFlags, CPoint point)
3350 if (m_pMainFrame->m_nMoveMovesToIgnore > 0)
3352 --m_pMainFrame->m_nMoveMovesToIgnore;
3353 CView::OnMouseMove(nFlags, point);
3354 return;
3356 int nMouseLine = GetButtonEventLineIndex(point);
3357 if (nMouseLine < -1)
3358 nMouseLine = -1;
3359 m_mouseInMargin = point.x < GetMarginWidth();
3361 ShowDiffLines(nMouseLine);
3363 KillTimer(IDT_SCROLLTIMER);
3364 if (nFlags & MK_LBUTTON)
3366 int saveMouseLine = nMouseLine >= 0 ? nMouseLine : 0;
3367 saveMouseLine = saveMouseLine < GetLineCount() ? saveMouseLine : GetLineCount() - 1;
3368 if (saveMouseLine < 0)
3369 return;
3370 int col = CalcColFromPoint(point.x, saveMouseLine);
3371 int charIndex = CalculateCharIndex(saveMouseLine, col);
3372 if (HasSelection() &&
3373 ((nMouseLine >= m_nTopLine)&&(nMouseLine < GetLineCount())))
3375 POINT ptCaretPos = {charIndex, nMouseLine};
3376 SetCaretAndGoalPosition(ptCaretPos);
3377 AdjustSelection(MOVERIGHT);
3378 Invalidate();
3379 UpdateWindow();
3381 if (nMouseLine < m_nTopLine)
3383 ScrollAllToLine(m_nTopLine-1, TRUE);
3384 SetTimer(IDT_SCROLLTIMER, 20, NULL);
3386 if (nMouseLine >= m_nTopLine + GetScreenLines() - 2)
3388 ScrollAllToLine(m_nTopLine+1, TRUE);
3389 SetTimer(IDT_SCROLLTIMER, 20, NULL);
3391 if (!m_pMainFrame->m_bWrapLines && ((m_nOffsetChar + (point.x - GetMarginWidth()) / GetCharWidth()) <= m_nOffsetChar))
3393 ScrollAllSide(-1);
3394 SetTimer(IDT_SCROLLTIMER, 20, NULL);
3396 if (!m_pMainFrame->m_bWrapLines && (charIndex >= (GetScreenChars()+m_nOffsetChar-4)))
3398 ScrollAllSide(1);
3399 SetTimer(IDT_SCROLLTIMER, 20, NULL);
3401 SetCapture();
3405 CView::OnMouseMove(nFlags, point);
3408 void CBaseView::OnLButtonUp(UINT nFlags, CPoint point)
3410 ShowDiffLines(-1);
3411 ReleaseCapture();
3412 KillTimer(IDT_SCROLLTIMER);
3414 __super::OnLButtonUp(nFlags, point);
3417 void CBaseView::OnTimer(UINT_PTR nIDEvent)
3419 if (nIDEvent == IDT_SCROLLTIMER)
3421 POINT point;
3422 GetCursorPos(&point);
3423 ScreenToClient(&point);
3424 int nMouseLine = GetButtonEventLineIndex(point);
3425 if (nMouseLine < -1)
3427 nMouseLine = -1;
3429 if (GetKeyState(VK_LBUTTON)&0x8000)
3431 int saveMouseLine = nMouseLine >= 0 ? nMouseLine : 0;
3432 saveMouseLine = saveMouseLine < GetLineCount() ? saveMouseLine : GetLineCount() - 1;
3433 int charIndex = CalculateCharIndex(saveMouseLine, m_nOffsetChar + (point.x - GetMarginWidth()) / GetCharWidth());
3434 if (nMouseLine < m_nTopLine)
3436 ScrollAllToLine(m_nTopLine-1, TRUE);
3437 SetTimer(IDT_SCROLLTIMER, 20, NULL);
3439 if (nMouseLine >= m_nTopLine + GetScreenLines() - 2)
3441 ScrollAllToLine(m_nTopLine+1, TRUE);
3442 SetTimer(IDT_SCROLLTIMER, 20, NULL);
3444 if (!m_pMainFrame->m_bWrapLines && ((m_nOffsetChar + (point.x - GetMarginWidth()) / GetCharWidth()) <= m_nOffsetChar))
3446 ScrollAllSide(-1);
3447 SetTimer(IDT_SCROLLTIMER, 20, NULL);
3449 if (!m_pMainFrame->m_bWrapLines && (charIndex >= (GetScreenChars()+m_nOffsetChar-4)))
3451 ScrollAllSide(1);
3452 SetTimer(IDT_SCROLLTIMER, 20, NULL);
3458 CView::OnTimer(nIDEvent);
3461 void CBaseView::ShowDiffLines(int nLine)
3463 if ((nLine < m_nTopLine)||(nLine >= GetLineCount()))
3465 m_pwndLineDiffBar->ShowLines(nLine);
3466 nLine = -1;
3467 m_nMouseLine = nLine;
3468 return;
3471 if ((!m_pwndRight)||(!m_pwndLeft))
3472 return;
3473 if(m_pMainFrame->m_bOneWay)
3474 return;
3476 nLine = (nLine > (int)m_pwndRight->m_Screen2View.size() ? -1 : nLine);
3477 nLine = (nLine > (int)m_pwndLeft->m_Screen2View.size() ? -1 : nLine);
3479 if (nLine < 0)
3480 return;
3482 if (nLine != m_nMouseLine)
3484 if (nLine >= GetLineCount())
3485 nLine = -1;
3486 m_nMouseLine = nLine;
3487 m_pwndLineDiffBar->ShowLines(nLine);
3489 m_pMainFrame->m_nMoveMovesToIgnore = MOVESTOIGNORE;
3492 const viewdata& CBaseView::GetEmptyLineData()
3494 static const viewdata emptyLine(_T(""), DIFFSTATE_EMPTY, -1, EOL_NOENDING, HIDESTATE_SHOWN);
3495 return emptyLine;
3498 void CBaseView::InsertViewEmptyLines(int nFirstView, int nCount)
3500 for (int i = 0; i < nCount; i++)
3502 InsertViewData(nFirstView, GetEmptyLineData());
3507 void CBaseView::UpdateCaret()
3509 POINT ptCaretPos = GetCaretPosition();
3510 ptCaretPos.y = std::max<int>(std::min<int>(ptCaretPos.y, GetLineCount()-1), 0);
3511 ptCaretPos.x = std::max<int>(std::min<int>(ptCaretPos.x, GetLineLength(ptCaretPos.y)), 0);
3512 SetCaretPosition(ptCaretPos);
3514 int nCaretOffset = CalculateActualOffset(ptCaretPos);
3516 if (m_bFocused &&
3517 ptCaretPos.y >= m_nTopLine &&
3518 ptCaretPos.y < (m_nTopLine+GetScreenLines()) &&
3519 nCaretOffset >= m_nOffsetChar &&
3520 nCaretOffset < (m_nOffsetChar+GetScreenChars()))
3522 POINT pt1 = TextToClient(ptCaretPos);
3523 if (m_bInsertMode)
3524 CreateSolidCaret(2, GetLineHeight());
3525 else
3527 POINT pt = { ptCaretPos.x + 1, ptCaretPos.y };
3528 POINT pt2 = TextToClient(pt);
3529 int width = max(GetCharWidth(), pt2.x - pt1.x);
3530 CreateSolidCaret(width, GetLineHeight());
3532 SetCaretPos(pt1);
3533 ShowCaret();
3535 else
3537 HideCaret();
3541 POINT CBaseView::ConvertScreenPosToView(const POINT& pt)
3543 POINT ptViewPos;
3544 ptViewPos.x = pt.x;
3546 int nSubLine = GetSubLineOffset(pt.y);
3547 if (nSubLine > 0)
3549 for (int nScreenLine = pt.y-1; nScreenLine >= pt.y-nSubLine; nScreenLine--)
3551 ptViewPos.x += GetLineChars(nScreenLine).GetLength();
3555 ptViewPos.y = GetViewLineForScreen(pt.y);
3556 return ptViewPos;
3559 POINT CBaseView::ConvertViewPosToScreen(const POINT& pt)
3561 POINT ptPos;
3562 int nViewLineLenLeft = GetViewLineLength(pt.y);
3563 ptPos.x = min(nViewLineLenLeft, pt.x);
3564 ptPos.y = FindScreenLineForViewLine(pt.y);
3565 if (GetViewLineForScreen(ptPos.y) != pt.y )
3567 ptPos.x = 0;
3569 else if (GetSubLineOffset(ptPos.y) >= 0) // sublined
3571 int nSubLineLength = GetLineChars(ptPos.y).GetLength();
3572 while (nSubLineLength < ptPos.x)
3574 ptPos.x -= nSubLineLength;
3575 nViewLineLenLeft -= nSubLineLength;
3576 ptPos.y++;
3577 nSubLineLength = GetLineChars(ptPos.y).GetLength();
3579 // last pos of non last sub-line go to start of next screen line
3580 // Note: while this works correctly, it's not what a user might expect:
3581 // cursor-right when the caret is before the last char of a wrapped line
3582 // now moves the caret to the next line. But users expect the caret to
3583 // move to the right of the last char instead, and with another cursor-right
3584 // keystroke to move the caret to the next line.
3585 // Basically, this would require to handle two caret positions for the same
3586 // logical position in the line string (one on the last position of the first line,
3587 // one on the first position of the new line. For non-wrapped lines this works
3588 // because there's an 'invisible' newline char at the end of the first line.
3589 if (nSubLineLength == ptPos.x && nViewLineLenLeft > nSubLineLength)
3591 ptPos.x = 0;
3592 ptPos.y++;
3596 return ptPos;
3600 void CBaseView::EnsureCaretVisible()
3602 POINT ptCaretPos = GetCaretPosition();
3603 int nCaretOffset = CalculateActualOffset(ptCaretPos);
3605 if (ptCaretPos.y < m_nTopLine)
3606 ScrollAllToLine(ptCaretPos.y);
3607 int screnLines = GetScreenLines();
3608 if (screnLines)
3610 if (ptCaretPos.y >= (m_nTopLine+screnLines)-1)
3611 ScrollAllToLine(ptCaretPos.y-screnLines+2);
3612 if (nCaretOffset < m_nOffsetChar)
3613 ScrollAllToChar(nCaretOffset);
3614 if (nCaretOffset > (m_nOffsetChar+GetScreenChars()-1))
3615 ScrollAllToChar(nCaretOffset-GetScreenChars()+1);
3619 int CBaseView::CalculateActualOffset(const POINT& point)
3621 int nLineIndex = point.y;
3622 int nCharIndex = point.x;
3623 ASSERT(nCharIndex >= 0);
3624 CString sLine = GetLineChars(nLineIndex);
3625 int nLineLength = sLine.GetLength();
3626 return CountExpandedChars(sLine, min(nCharIndex, nLineLength));
3629 int CBaseView::CalculateCharIndex(int nLineIndex, int nActualOffset)
3631 int nLength = GetLineLength(nLineIndex);
3632 int nSubLine = GetSubLineOffset(nLineIndex);
3633 if (nSubLine>=0)
3635 int nViewLine = GetViewLineForScreen(nLineIndex);
3636 if ((nViewLine>=0)&&(nViewLine < (int)m_ScreenedViewLine.size()))
3638 int nMultilineCount = CountMultiLines(nViewLine);
3639 if ((nMultilineCount>0) && (nSubLine<nMultilineCount-1))
3641 nLength--;
3645 CString Line = GetLineChars(nLineIndex);
3646 int nIndex = 0;
3647 int nOffset = 0;
3648 int nTabSize = GetTabSize();
3649 while (nOffset < nActualOffset && nIndex < nLength)
3651 if (Line.GetAt(nIndex) == _T('\t'))
3652 nOffset += (nTabSize - nOffset % nTabSize);
3653 else
3654 ++nOffset;
3655 ++nIndex;
3657 return nIndex;
3661 * @param xpos X coordinate in CBaseView
3662 * @param lineIndex logical line index (e.g. wrap/collapse)
3664 int CBaseView::CalcColFromPoint(int xpos, int lineIndex)
3666 int xpos2;
3667 CDC *pDC = GetDC();
3668 if (pDC != nullptr)
3670 CString text = ExpandChars(GetLineChars(lineIndex), 0);
3671 int fit = text.GetLength();
3672 std::unique_ptr<int> posBuffer(new int[fit]);
3673 pDC->SelectObject(GetFont()); // is this right font ?
3674 SIZE size;
3675 GetTextExtentExPoint(pDC->GetSafeHdc(), text, fit, INT_MAX, &fit, posBuffer.get(), &size);
3676 ReleaseDC(pDC);
3677 int lower = -1, upper = fit - 1;
3678 int xcheck = xpos - GetMarginWidth() + m_nOffsetChar * GetCharWidth();
3681 int middle = (upper + lower + 1) / 2;
3682 int width = posBuffer.get()[middle];
3683 if (xcheck < width)
3684 upper = middle - 1;
3685 else
3686 lower = middle;
3687 } while (lower < upper);
3688 lower++;
3689 xpos2 = lower;
3690 if (lower < fit - 1)
3692 int charWidth = posBuffer.get()[lower] - (lower > 0 ? posBuffer.get()[lower - 1] : 0);
3693 if (posBuffer.get()[lower] - xcheck <= charWidth / 2)
3694 xpos2++;
3697 else
3699 xpos2 = (xpos - GetMarginWidth()) / GetCharWidth() + m_nOffsetChar;
3700 if ((xpos % GetCharWidth()) >= (GetCharWidth()/2))
3701 xpos2++;
3703 return xpos2;
3706 POINT CBaseView::TextToClient(const POINT& point)
3708 POINT pt;
3709 int nOffsetScreenLine = max(0, (point.y - m_nTopLine));
3710 pt.y = nOffsetScreenLine * GetLineHeight();
3711 pt.x = CalculateActualOffset(point);
3713 int nLeft = GetMarginWidth() - m_nOffsetChar * GetCharWidth();
3714 CDC * pDC = GetDC();
3715 if (pDC)
3717 pDC->SelectObject(GetFont()); // is this right font ?
3718 int nScreenLine = nOffsetScreenLine + m_nTopLine;
3719 CString sLine = GetLineChars(nScreenLine);
3720 ExpandChars(sLine, 0, std::min<int>(pt.x, sLine.GetLength()), sLine);
3721 nLeft += pDC->GetTextExtent(sLine, pt.x).cx;
3722 ReleaseDC(pDC);
3723 } else {
3724 nLeft += pt.x * GetCharWidth();
3727 pt.x = nLeft;
3728 pt.y = (pt.y + GetLineHeight() + HEADERHEIGHT);
3729 return pt;
3732 void CBaseView::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags)
3734 CView::OnChar(nChar, nRepCnt, nFlags);
3736 bool bShift = !!(GetKeyState(VK_SHIFT)&0x8000);
3737 bool bSkipSelectionClear = false;
3739 if (IsReadonly())
3740 return;
3742 if ((::GetKeyState(VK_LBUTTON) & 0x8000) != 0 ||
3743 (::GetKeyState(VK_RBUTTON) & 0x8000) != 0)
3745 return;
3748 if (!m_pViewData) // no data - nothing to do
3749 return;
3751 if (nChar == VK_F16)
3753 // generated by a ctrl+backspace - ignore.
3755 else if (nChar==VK_TAB && HasTextLineSelection())
3757 // change indentation for selected lines
3758 if (bShift)
3760 RemoveIndentationForSelectedBlock();
3762 else
3764 AddIndentationForSelectedBlock();
3766 bSkipSelectionClear = true;
3768 else if ((nChar > 31)||(nChar == VK_TAB))
3770 ResetUndoStep();
3771 RemoveSelectedText();
3772 POINT ptCaretViewPos = GetCaretViewPosition();
3773 int nViewLine = ptCaretViewPos.y;
3774 if ((nViewLine==0)&&(GetViewCount()==0))
3775 OnChar(VK_RETURN, 0, 0);
3776 int charCount = 1;
3777 viewdata lineData = GetViewData(nViewLine);
3778 if (nChar == VK_TAB)
3780 int indentChars = GetIndentCharsForLine(ptCaretViewPos.x, nViewLine);
3781 if (indentChars > 0)
3783 lineData.sLine.Insert(ptCaretViewPos.x, CString(_T(' '), indentChars));
3784 charCount = indentChars;
3786 else
3787 lineData.sLine.Insert(ptCaretViewPos.x, _T('\t'));
3789 else
3791 if (m_bInsertMode)
3792 lineData.sLine.Insert(ptCaretViewPos.x, (wchar_t)nChar);
3793 else
3795 if (lineData.sLine.GetLength() > ptCaretViewPos.x)
3796 lineData.sLine.SetAt(ptCaretViewPos.x, (wchar_t)nChar);
3797 else
3798 lineData.sLine.Insert(ptCaretViewPos.x, (wchar_t)nChar);
3801 if (IsStateEmpty(lineData.state))
3803 // if not last line set EOL
3804 for (int nCheckViewLine = nViewLine+1; nCheckViewLine < GetViewCount(); nCheckViewLine++)
3806 if (!IsViewLineEmpty(nCheckViewLine))
3808 lineData.ending = m_lineendings;
3809 break;
3812 // make sure previous (non empty) line have EOL set
3813 for (int nCheckViewLine = nViewLine-1; nCheckViewLine > 0; nCheckViewLine--)
3815 if (!IsViewLineEmpty(nCheckViewLine))
3817 if (GetViewLineEnding(nCheckViewLine) == EOL_NOENDING)
3819 SetViewLineEnding(nCheckViewLine, m_lineendings);
3821 break;
3825 lineData.state = DIFFSTATE_EDITED;
3826 bool bNeedRenumber = false;
3827 if (lineData.linenumber == -1)
3829 lineData.linenumber = 0;
3830 bNeedRenumber = true;
3832 SetViewData(nViewLine, lineData);
3833 SetModified();
3834 SaveUndoStep();
3835 BuildAllScreen2ViewVector(nViewLine);
3836 if (bNeedRenumber)
3838 UpdateViewLineNumbers();
3840 for (int i = 0; i < charCount; ++i)
3841 MoveCaretRight();
3842 UpdateGoalPos();
3844 else if (nChar == 10)
3846 int nViewLine = GetViewLineForScreen(GetCaretPosition().y);
3847 EOL eol = m_pViewData->GetLineEnding(nViewLine);
3848 EOL newEOL = EOL_CRLF;
3849 switch (eol)
3851 case EOL_CRLF:
3852 newEOL = EOL_CR;
3853 break;
3854 case EOL_CR:
3855 newEOL = EOL_LF;
3856 break;
3857 case EOL_LF:
3858 newEOL = EOL_CRLF;
3859 break;
3861 if (eol==EOL_NOENDING || eol==newEOL)
3862 // don't allow to change enter on empty line, or last text line (lines with EOL_NOENDING)
3863 // to add EOL on newly edited empty line hit enter
3864 // don't store into UNDO if no change happened
3865 // and don't mark file as modified
3866 return;
3867 AddUndoViewLine(nViewLine);
3868 m_pViewData->SetLineEnding(nViewLine, newEOL);
3869 m_pViewData->SetState(nViewLine, DIFFSTATE_EDITED);
3870 UpdateGoalPos();
3872 else if (nChar == VK_RETURN)
3874 // insert a new, fresh and empty line below the cursor
3875 RemoveSelectedText();
3877 CUndo::GetInstance().BeginGrouping();
3879 POINT ptCaretViewPos = GetCaretViewPosition();
3880 int nViewLine = ptCaretViewPos.y;
3881 int nLeft = ptCaretViewPos.x;
3882 CString sLine = GetViewLineChars(nViewLine);
3883 CString sLineLeft = sLine.Left(nLeft);
3884 CString sLineRight = sLine.Right(sLine.GetLength() - nLeft);
3885 EOL eOriginalEnding = EOL_AUTOLINE;
3886 if (m_pViewData->GetCount() > nViewLine)
3887 eOriginalEnding = GetViewLineEnding(nViewLine);
3889 if (!sLineRight.IsEmpty() || (eOriginalEnding!=m_lineendings))
3891 viewdata newFirstLine(sLineLeft, DIFFSTATE_EDITED, 1, m_lineendings, HIDESTATE_SHOWN);
3892 SetViewData(nViewLine, newFirstLine);
3895 int nInsertLine = (m_pViewData->GetCount()==0) ? 0 : nViewLine + 1;
3896 viewdata newLastLine(sLineRight, DIFFSTATE_EDITED, 1, eOriginalEnding, HIDESTATE_SHOWN);
3897 InsertViewData(nInsertLine, newLastLine);
3898 SetModified();
3899 SaveUndoStep();
3901 // adds new line everywhere except me
3902 if (IsViewGood(m_pwndLeft) && m_pwndLeft!=this)
3904 m_pwndLeft->InsertViewEmptyLines(nInsertLine, 1);
3906 if (IsViewGood(m_pwndRight) && m_pwndRight!=this)
3908 m_pwndRight->InsertViewEmptyLines(nInsertLine, 1);
3910 if (IsViewGood(m_pwndBottom) && m_pwndBottom!=this)
3912 m_pwndBottom->InsertViewEmptyLines(nInsertLine, 1);
3914 SaveUndoStep();
3916 UpdateViewLineNumbers();
3917 SaveUndoStep();
3918 CUndo::GetInstance().EndGrouping();
3920 BuildAllScreen2ViewVector();
3921 // move the cursor to the new line
3922 ptCaretViewPos = SetupPoint(0, nViewLine+1);
3923 SetCaretAndGoalViewPosition(ptCaretViewPos);
3925 else
3926 return; // Unknown control character -- ignore it.
3927 if (!bSkipSelectionClear)
3928 ClearSelection();
3929 EnsureCaretVisible();
3930 UpdateCaret();
3931 Invalidate(FALSE);
3934 void CBaseView::AddUndoViewLine(int nViewLine, bool bAddEmptyLine)
3936 ResetUndoStep();
3937 m_AllState.left.AddViewLineFromView(m_pwndLeft, nViewLine, bAddEmptyLine);
3938 m_AllState.right.AddViewLineFromView(m_pwndRight, nViewLine, bAddEmptyLine);
3939 m_AllState.bottom.AddViewLineFromView(m_pwndBottom, nViewLine, bAddEmptyLine);
3940 SetModified();
3941 SaveUndoStep();
3942 RecalcAllVertScrollBars();
3943 Invalidate(FALSE);
3946 void CBaseView::AddEmptyViewLine(int nViewLineIndex)
3948 if (m_pViewData == NULL)
3949 return;
3950 int viewLine = nViewLineIndex;
3951 EOL ending = m_pViewData->GetLineEnding(viewLine);
3952 if (ending == EOL_NOENDING)
3954 ending = m_lineendings;
3956 viewdata newLine(_T(""), DIFFSTATE_EDITED, -1, ending, HIDESTATE_SHOWN);
3957 if (IsTarget()) // TODO: once more wievs will writable this is not correct anymore
3959 CString sPartLine = GetViewLineChars(nViewLineIndex);
3960 int nPosx = GetCaretPosition().x; // should be view pos ?
3961 m_pViewData->SetLine(viewLine, sPartLine.Left(nPosx));
3962 sPartLine = sPartLine.Mid(nPosx);
3963 newLine.sLine = sPartLine;
3965 m_pViewData->InsertData(viewLine+1, newLine);
3966 BuildAllScreen2ViewVector();
3969 void CBaseView::RemoveSelectedText()
3971 if (m_pViewData == NULL)
3972 return;
3973 if (!HasTextSelection())
3974 return;
3976 // fix selection if starts or ends on empty line
3977 SetCaretViewPosition(m_ptSelectionViewPosEnd);
3978 while (IsViewLineEmpty(GetCaretViewPosition().y) && MoveCaretRight())
3981 m_ptSelectionViewPosEnd = GetCaretViewPosition();
3982 SetCaretViewPosition(m_ptSelectionViewPosStart);
3983 while (IsViewLineEmpty(GetCaretViewPosition().y) && MoveCaretRight())
3986 m_ptSelectionViewPosStart = GetCaretViewPosition();
3987 if (!HasTextSelection())
3989 ClearSelection();
3990 return;
3993 // We want to undo the insertion in a single step.
3994 ResetUndoStep();
3995 CUndo::GetInstance().BeginGrouping();
3997 // combine first and last line
3998 viewdata oFirstLine = GetViewData(m_ptSelectionViewPosStart.y);
3999 viewdata oLastLine = GetViewData(m_ptSelectionViewPosEnd.y);
4000 oFirstLine.sLine = oFirstLine.sLine.Left(m_ptSelectionViewPosStart.x) + oLastLine.sLine.Mid(m_ptSelectionViewPosEnd.x);
4001 oFirstLine.ending = oLastLine.ending;
4002 oFirstLine.state = DIFFSTATE_EDITED;
4003 SetViewData(m_ptSelectionViewPosStart.y, oFirstLine);
4005 // clean up middle lines if any
4006 if (m_ptSelectionViewPosStart.y != m_ptSelectionViewPosEnd.y)
4008 viewdata oEmptyLine = GetEmptyLineData();
4009 for (int nViewLine = m_ptSelectionViewPosStart.y+1; nViewLine <= m_ptSelectionViewPosEnd.y; nViewLine++)
4011 SetViewData(nViewLine, oEmptyLine);
4013 SaveUndoStep();
4015 if (CleanEmptyLines())
4017 BuildAllScreen2ViewVector(); // schedule full rebuild
4019 SaveUndoStep();
4020 UpdateViewLineNumbers();
4023 SetModified(); //TODO set modified only if real data was changed
4024 SaveUndoStep();
4025 CUndo::GetInstance().EndGrouping();
4027 BuildAllScreen2ViewVector(m_ptSelectionViewPosStart.y, m_ptSelectionViewPosEnd.y);
4028 SetCaretViewPosition(m_ptSelectionViewPosStart);
4029 UpdateGoalPos();
4030 ClearSelection();
4031 UpdateCaret();
4032 EnsureCaretVisible();
4033 Invalidate(FALSE);
4036 void CBaseView::PasteText()
4038 if (!OpenClipboard())
4039 return;
4041 CString sClipboardText;
4042 HGLOBAL hglb = GetClipboardData(CF_TEXT);
4043 if (hglb)
4045 LPCSTR lpstr = (LPCSTR)GlobalLock(hglb);
4046 sClipboardText = CString(lpstr);
4047 GlobalUnlock(hglb);
4049 hglb = GetClipboardData(CF_UNICODETEXT);
4050 if (hglb)
4052 LPCTSTR lpstr = (LPCTSTR)GlobalLock(hglb);
4053 sClipboardText = lpstr;
4054 GlobalUnlock(hglb);
4056 CloseClipboard();
4058 if (sClipboardText.IsEmpty())
4059 return;
4061 sClipboardText.Replace(_T("\r\n"), _T("\r"));
4062 sClipboardText.Replace('\n', '\r');
4064 InsertText(sClipboardText);
4067 void CBaseView::OnCaretDown()
4069 POINT ptCaretPos = GetCaretPosition();
4070 int nLine = ptCaretPos.y;
4071 int nNextLine = nLine + 1;
4072 if (nNextLine >= GetLineCount()) // already at last line
4074 return;
4077 POINT ptCaretViewPos = GetCaretViewPosition();
4078 int nViewLine = ptCaretViewPos.y;
4079 int nNextViewLine = GetViewLineForScreen(nNextLine);
4080 if (!((nNextViewLine == nViewLine) && (GetSubLineOffset(nNextLine)<CountMultiLines(nNextViewLine)))) // not on same view line
4082 // find next suitable screen line
4083 while ((nNextViewLine == nViewLine) || IsViewLineHidden(nNextViewLine))
4085 nNextLine++;
4086 if (nNextLine >= GetLineCount())
4088 return;
4090 nNextViewLine = GetViewLineForScreen(nNextLine);
4093 ptCaretPos.y = nNextLine;
4094 ptCaretPos.x = CalculateCharIndex(ptCaretPos.y, m_nCaretGoalPos);
4095 SetCaretPosition(ptCaretPos);
4096 OnCaretMove(MOVELEFT);
4097 ShowDiffLines(ptCaretPos.y);
4100 bool CBaseView::MoveCaretLeft()
4102 POINT ptCaretViewPos = GetCaretViewPosition();
4104 //int nViewLine = ptCaretViewPos.y;
4105 if (ptCaretViewPos.x == 0)
4107 int nPrevLine = GetCaretPosition().y;
4108 int nPrevViewLine;
4109 do {
4110 nPrevLine--;
4111 if (nPrevLine < 0)
4113 return false;
4115 nPrevViewLine = GetViewLineForScreen(nPrevLine);
4116 } while ((GetSubLineOffset(nPrevLine) >= CountMultiLines(nPrevViewLine)) || IsViewLineHidden(nPrevViewLine));
4117 ptCaretViewPos = ConvertScreenPosToView(SetupPoint(GetLineLength(nPrevLine), nPrevLine));
4118 ShowDiffLines(nPrevLine);
4120 else
4121 --ptCaretViewPos.x;
4123 SetCaretAndGoalViewPosition(ptCaretViewPos);
4124 return true;
4127 bool CBaseView::MoveCaretRight()
4129 POINT ptCaretViewPos = GetCaretViewPosition();
4131 int nViewLine = ptCaretViewPos.y;
4132 int nViewLineLen = GetViewLineLength(nViewLine);
4133 if (ptCaretViewPos.x >= nViewLineLen)
4135 int nNextLine = GetCaretPosition().y;
4136 int nNextViewLine;
4137 do {
4138 nNextLine++;
4139 if (nNextLine >= GetLineCount())
4141 return false;
4143 nNextViewLine = GetViewLineForScreen(nNextLine);
4144 } while (nNextViewLine == nViewLine || IsViewLineHidden(nNextViewLine));
4145 ptCaretViewPos.y = nNextViewLine;
4146 ptCaretViewPos.x = 0;
4147 ShowDiffLines(nNextLine);
4149 else
4150 ++ptCaretViewPos.x;
4152 SetCaretAndGoalViewPosition(ptCaretViewPos);
4153 return true;
4156 void CBaseView::UpdateGoalPos()
4158 m_nCaretGoalPos = CalculateActualOffset(GetCaretPosition());
4161 void CBaseView::OnCaretLeft()
4163 MoveCaretLeft();
4164 OnCaretMove(MOVELEFT);
4167 void CBaseView::OnCaretRight()
4169 MoveCaretRight();
4170 OnCaretMove(MOVERIGHT);
4173 void CBaseView::OnCaretUp()
4175 POINT ptCaretPos = GetCaretPosition();
4176 int nLine = ptCaretPos.y;
4177 if (nLine <= 0) // already at first line
4179 return;
4181 int nPrevLine = nLine - 1;
4183 POINT ptCaretViewPos = GetCaretViewPosition();
4184 int nViewLine = ptCaretViewPos.y;
4185 int nPrevViewLine = GetViewLineForScreen(nPrevLine);
4186 if (nPrevViewLine != nViewLine) // not on same view line
4188 // find previous suitable screen line
4189 while ((GetSubLineOffset(nPrevLine) >= CountMultiLines(nPrevViewLine)) || IsViewLineHidden(nPrevViewLine))
4191 if (nPrevLine <= 0)
4193 return;
4195 nPrevLine--;
4196 nPrevViewLine = GetViewLineForScreen(nPrevLine);
4199 ptCaretPos.y = nPrevLine;
4200 ptCaretPos.x = CalculateCharIndex(ptCaretPos.y, m_nCaretGoalPos);
4201 SetCaretPosition(ptCaretPos);
4202 OnCaretMove(MOVELEFT);
4203 ShowDiffLines(ptCaretPos.y);
4206 bool CBaseView::IsWordSeparator(const wchar_t ch) const
4208 switch (GetCharGroup(ch))
4210 case CHG_CONTROL:
4211 case CHG_WHITESPACE:
4212 case CHG_WORDSEPARATOR:
4213 return true;
4215 return false;
4218 bool CBaseView::IsCaretAtWordBoundary()
4220 POINT ptViewCaret = GetCaretViewPosition();
4221 CString line = GetViewLineChars(ptViewCaret.y);
4222 if (line.IsEmpty())
4223 return false; // no boundary at the empty lines
4224 if (ptViewCaret.x == 0)
4225 return !IsWordSeparator(line.GetAt(ptViewCaret.x));
4226 if (ptViewCaret.x >= GetViewLineLength(ptViewCaret.y))
4227 return !IsWordSeparator(line.GetAt(ptViewCaret.x - 1));
4228 return
4229 IsWordSeparator(line.GetAt(ptViewCaret.x)) !=
4230 IsWordSeparator(line.GetAt(ptViewCaret.x - 1));
4233 void CBaseView::UpdateViewsCaretPosition()
4235 POINT ptCaretPos = GetCaretPosition();
4236 if (m_pwndBottom && m_pwndBottom!=this)
4237 m_pwndBottom->UpdateCaretPosition(ptCaretPos);
4238 if (m_pwndLeft && m_pwndLeft!=this)
4239 m_pwndLeft->UpdateCaretPosition(ptCaretPos);
4240 if (m_pwndRight && m_pwndRight!=this)
4241 m_pwndRight->UpdateCaretPosition(ptCaretPos);
4244 void CBaseView::OnCaretWordleft()
4246 MoveCaretWordLeft();
4247 OnCaretMove(MOVELEFT);
4250 void CBaseView::OnCaretWordright()
4252 MoveCaretWordRight();
4253 OnCaretMove(MOVERIGHT);
4256 void CBaseView::MoveCaretWordLeft()
4258 while (MoveCaretLeft() && !IsCaretAtWordBoundary())
4263 void CBaseView::MoveCaretWordRight()
4265 while (MoveCaretRight() && !IsCaretAtWordBoundary())
4270 void CBaseView::ClearCurrentSelection()
4272 m_ptSelectionViewPosStart = GetCaretViewPosition();
4273 m_ptSelectionViewPosEnd = m_ptSelectionViewPosStart;
4274 m_ptSelectionViewPosOrigin = m_ptSelectionViewPosStart;
4275 m_nSelViewBlockStart = -1;
4276 m_nSelViewBlockEnd = -1;
4277 Invalidate(FALSE);
4280 void CBaseView::ClearSelection()
4282 if (m_pwndLeft)
4283 m_pwndLeft->ClearCurrentSelection();
4284 if (m_pwndRight)
4285 m_pwndRight->ClearCurrentSelection();
4286 if (m_pwndBottom)
4287 m_pwndBottom->ClearCurrentSelection();
4290 void CBaseView::AdjustSelection(bool bMoveLeft)
4292 POINT ptCaretViewPos = GetCaretViewPosition();
4293 if (ArePointsSame(m_ptSelectionViewPosOrigin, SetupPoint(-1, -1)))
4295 // select all have been used recently update origin
4296 m_ptSelectionViewPosOrigin = bMoveLeft ? m_ptSelectionViewPosEnd : m_ptSelectionViewPosStart;
4298 if ((ptCaretViewPos.y < m_ptSelectionViewPosOrigin.y) ||
4299 (ptCaretViewPos.y == m_ptSelectionViewPosOrigin.y && ptCaretViewPos.x <= m_ptSelectionViewPosOrigin.x))
4301 m_ptSelectionViewPosStart = ptCaretViewPos;
4302 m_ptSelectionViewPosEnd = m_ptSelectionViewPosOrigin;
4304 else
4306 m_ptSelectionViewPosStart = m_ptSelectionViewPosOrigin;
4307 m_ptSelectionViewPosEnd = ptCaretViewPos;
4310 SetupAllViewSelection(m_ptSelectionViewPosStart.y, m_ptSelectionViewPosEnd.y);
4312 Invalidate(FALSE);
4315 void CBaseView::OnEditCut()
4317 if (IsWritable())
4319 OnEditCopy();
4320 RemoveSelectedText();
4324 void CBaseView::OnEditPaste()
4326 if (IsWritable())
4328 CUndo::GetInstance().BeginGrouping();
4329 RemoveSelectedText();
4330 PasteText();
4331 CUndo::GetInstance().EndGrouping();
4335 void CBaseView::DeleteFonts()
4337 for (int i=0; i<fontsCount; i++)
4339 if (m_apFonts[i] != NULL)
4341 m_apFonts[i]->DeleteObject();
4342 delete m_apFonts[i];
4343 m_apFonts[i] = NULL;
4348 void CBaseView::OnCaretMove(bool bMoveLeft)
4350 bool bShift = !!(GetKeyState(VK_SHIFT)&0x8000);
4351 OnCaretMove(bMoveLeft, bShift);
4354 void CBaseView::OnCaretMove(bool bMoveLeft, bool isShiftPressed)
4356 if(isShiftPressed)
4357 AdjustSelection(bMoveLeft);
4358 else
4359 ClearSelection();
4360 EnsureCaretVisible();
4361 UpdateCaret();
4364 void CBaseView::AddContextItems(CIconMenu& popup, DiffStates /*state*/)
4366 AddCutCopyAndPaste(popup);
4369 void CBaseView::AddCutCopyAndPaste(CIconMenu& popup)
4371 popup.AppendMenu(MF_SEPARATOR, NULL);
4372 CString temp;
4373 temp.LoadString(IDS_EDIT_COPY);
4374 popup.AppendMenu(MF_STRING | (HasTextSelection() ? MF_ENABLED : MF_DISABLED|MF_GRAYED), ID_EDIT_COPY, temp);
4375 if (IsWritable())
4377 temp.LoadString(IDS_EDIT_CUT);
4378 popup.AppendMenu(MF_STRING | (HasTextSelection() ? MF_ENABLED : MF_DISABLED|MF_GRAYED), ID_EDIT_CUT, temp);
4379 temp.LoadString(IDS_EDIT_PASTE);
4380 popup.AppendMenu(MF_STRING | (CAppUtils::HasClipboardFormat(CF_UNICODETEXT)||CAppUtils::HasClipboardFormat(CF_TEXT) ? MF_ENABLED : MF_DISABLED|MF_GRAYED), ID_EDIT_PASTE, temp);
4381 popup.AppendMenu(MF_SEPARATOR, NULL);
4385 void CBaseView::CompensateForKeyboard(CPoint& point)
4387 // if the context menu is invoked through the keyboard, we have to use
4388 // a calculated position on where to anchor the menu on
4389 if (ArePointsSame(point, SetupPoint(-1, -1)))
4391 CRect rect;
4392 GetWindowRect(&rect);
4393 point = rect.CenterPoint();
4397 HICON CBaseView::LoadIcon(WORD iconId)
4399 HANDLE icon = ::LoadImage( AfxGetResourceHandle(), MAKEINTRESOURCE(iconId),
4400 IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR);
4401 return (HICON)icon;
4404 void CBaseView::ReleaseBitmap()
4406 if (m_pCacheBitmap != NULL)
4408 m_pCacheBitmap->DeleteObject();
4409 delete m_pCacheBitmap;
4410 m_pCacheBitmap = NULL;
4414 void CBaseView::BuildMarkedWordArray()
4416 int lineCount = GetLineCount();
4417 m_arMarkedWordLines.clear();
4418 m_arMarkedWordLines.reserve(lineCount);
4419 bool bDoit = !m_sMarkedWord.IsEmpty();
4420 for (int i = 0; i < lineCount; ++i)
4422 if (bDoit)
4424 CString line = GetLineChars(i);
4426 if (!line.IsEmpty())
4428 int found = 0;
4429 int nMarkStart = -1;
4430 while ((nMarkStart = line.Find(m_sMarkedWord, ++nMarkStart)) >= 0)
4432 int nMarkEnd = nMarkStart + m_sMarkedWord.GetLength();
4433 ECharGroup eLeft = GetCharGroup(line, nMarkStart - 1);
4434 ECharGroup eStart = GetCharGroup(line, nMarkStart);
4435 if (eLeft != eStart)
4437 ECharGroup eRight = GetCharGroup(line, nMarkEnd);
4438 ECharGroup eEnd = GetCharGroup(line, nMarkEnd - 1);
4439 if (eRight != eEnd)
4441 found = 1;
4442 break;
4446 m_arMarkedWordLines.push_back(found);
4448 else
4449 m_arMarkedWordLines.push_back(0);
4451 else
4452 m_arMarkedWordLines.push_back(0);
4456 void CBaseView::BuildFindStringArray()
4458 int lineCount = GetLineCount();
4459 m_arFindStringLines.clear();
4460 m_arFindStringLines.reserve(lineCount);
4461 bool bDoit = !m_sFindText.IsEmpty();
4462 int s = 0;
4463 int e = 0;
4464 for (int i = 0; i < lineCount; ++i)
4466 if (bDoit)
4468 CString line = GetLineChars(i);
4470 if (!line.IsEmpty())
4472 switch (m_pViewData->GetState(GetViewLineForScreen(i)))
4474 case DIFFSTATE_EMPTY:
4475 m_arFindStringLines.push_back(0);
4476 break;
4477 case DIFFSTATE_UNKNOWN:
4478 case DIFFSTATE_NORMAL:
4479 if (m_bLimitToDiff)
4481 m_arFindStringLines.push_back(0);
4482 break;
4484 case DIFFSTATE_REMOVED:
4485 case DIFFSTATE_REMOVEDWHITESPACE:
4486 case DIFFSTATE_ADDED:
4487 case DIFFSTATE_ADDEDWHITESPACE:
4488 case DIFFSTATE_WHITESPACE:
4489 case DIFFSTATE_WHITESPACE_DIFF:
4490 case DIFFSTATE_CONFLICTED:
4491 case DIFFSTATE_CONFLICTED_IGNORED:
4492 case DIFFSTATE_CONFLICTADDED:
4493 case DIFFSTATE_CONFLICTEMPTY:
4494 case DIFFSTATE_CONFLICTRESOLVED:
4495 case DIFFSTATE_IDENTICALREMOVED:
4496 case DIFFSTATE_IDENTICALADDED:
4497 case DIFFSTATE_THEIRSREMOVED:
4498 case DIFFSTATE_THEIRSADDED:
4499 case DIFFSTATE_YOURSREMOVED:
4500 case DIFFSTATE_YOURSADDED:
4501 case DIFFSTATE_EDITED:
4503 if (!m_bMatchCase)
4504 line = line.MakeLower();
4505 s = 0;
4506 e = 0;
4507 int match = 0;
4508 while (StringFound(line, SearchNext, s, e))
4510 match++;
4511 s = e;
4512 e = 0;
4514 m_arFindStringLines.push_back(match);
4515 break;
4517 default:
4518 m_arFindStringLines.push_back(0);
4521 else
4522 m_arFindStringLines.push_back(0);
4524 else
4525 m_arFindStringLines.push_back(0);
4527 UpdateLocator();
4530 bool CBaseView::GetInlineDiffPositions(int nViewLine, std::vector<inlineDiffPos>& positions)
4532 if (!m_bShowInlineDiff)
4533 return false;
4534 if ((m_pwndBottom != NULL) && !(m_pwndBottom->IsHidden()))
4535 return false;
4537 if (m_pViewData == nullptr || m_pViewData->GetCount() <= nViewLine)
4538 return false;
4539 const CString &sLine = m_pViewData->GetLine(nViewLine);
4540 if (sLine.IsEmpty())
4541 return false;
4543 CheckOtherView();
4544 if (!m_pOtherViewData)
4545 return false;
4547 const CString &sDiffLine = m_pOtherViewData->GetLine(nViewLine);
4548 if (sDiffLine.IsEmpty())
4549 return false;
4551 svn_diff_t * diff = NULL;
4552 auto pLine1 = (this == m_pwndLeft) ? &sLine : &sDiffLine;
4553 auto pLine2 = (this == m_pwndLeft) ? &sDiffLine : &sLine;
4554 m_svnlinediff.Diff(&diff, *pLine1, pLine1->GetLength(), *pLine2, pLine2->GetLength(), m_bInlineWordDiff);
4555 if (!diff || !SVNLineDiff::ShowInlineDiff(diff))
4556 return false;
4558 size_t lineoffset = 0;
4559 size_t position = 0;
4560 while (diff)
4562 apr_off_t len = diff->original_length;
4563 size_t oldpos = position;
4565 for (apr_off_t i = 0; i < len; ++i)
4567 position += (this == m_pwndRight) ? m_svnlinediff.m_line2tokens[lineoffset].size() : m_svnlinediff.m_line1tokens[lineoffset].size();
4568 lineoffset++;
4571 if (diff->type == svn_diff__type_diff_modified)
4573 inlineDiffPos p;
4574 p.start = oldpos;
4575 p.end = position;
4576 positions.push_back(p);
4579 diff = diff->next;
4582 return !positions.empty();
4585 void CBaseView::OnNavigateNextinlinediff()
4587 int nX;
4588 if (GetNextInlineDiff(nX))
4590 POINT ptCaretViewPos = GetCaretViewPosition();
4591 ptCaretViewPos.x = nX;
4592 SetCaretAndGoalViewPosition(ptCaretViewPos);
4593 m_ptSelectionViewPosOrigin = ptCaretViewPos;
4594 EnsureCaretVisible();
4598 void CBaseView::OnNavigatePrevinlinediff()
4600 int nX;
4601 if (GetPrevInlineDiff(nX))
4603 POINT ptCaretViewPos = GetCaretViewPosition();
4604 ptCaretViewPos.x = nX;
4605 SetCaretAndGoalViewPosition(ptCaretViewPos);
4606 m_ptSelectionViewPosOrigin = ptCaretViewPos;
4607 EnsureCaretVisible();
4611 bool CBaseView::HasNextInlineDiff()
4613 int nPos;
4614 return GetNextInlineDiff(nPos);
4617 bool CBaseView::GetNextInlineDiff(int & nPos)
4619 POINT ptCaretViewPos = GetCaretViewPosition();
4620 std::vector<inlineDiffPos> positions;
4621 if (GetInlineDiffPositions(ptCaretViewPos.y, positions))
4623 for (auto it = positions.cbegin(); it != positions.cend(); ++it)
4625 if (it->start > ptCaretViewPos.x)
4627 nPos = (LONG)it->start;
4628 return true;
4630 if (it->end > ptCaretViewPos.x)
4632 nPos = (LONG)it->end;
4633 return true;
4637 return false;
4640 bool CBaseView::HasPrevInlineDiff()
4642 int nPos;
4643 return GetPrevInlineDiff(nPos);
4646 bool CBaseView::GetPrevInlineDiff(int & nPos)
4648 POINT ptCaretViewPos = GetCaretViewPosition();
4649 std::vector<inlineDiffPos> positions;
4650 if (GetInlineDiffPositions(ptCaretViewPos.y, positions))
4652 for (auto it = positions.crbegin(); it != positions.crend(); ++it)
4654 if ( it->end < ptCaretViewPos.x)
4656 nPos = (LONG)it->end;
4657 return true;
4659 if ( it->start < ptCaretViewPos.x)
4661 nPos = (LONG)it->start;
4662 return true;
4666 return false;
4669 CBaseView * CBaseView::GetFirstGoodView()
4671 if (IsViewGood(m_pwndLeft))
4672 return m_pwndLeft;
4673 if (IsViewGood(m_pwndRight))
4674 return m_pwndRight;
4675 if (IsViewGood(m_pwndBottom))
4676 return m_pwndBottom;
4677 return NULL;
4680 void CBaseView::BuildAllScreen2ViewVector()
4682 CBaseView * p_pwndView = GetFirstGoodView();
4683 if (p_pwndView)
4685 m_Screen2View.ScheduleFullRebuild(p_pwndView->m_pViewData);
4689 void CBaseView::BuildAllScreen2ViewVector(int nViewLine)
4691 BuildAllScreen2ViewVector(nViewLine, nViewLine);
4694 void CBaseView::BuildAllScreen2ViewVector(int nFirstViewLine, int nLastViewLine)
4696 CBaseView * p_pwndView = GetFirstGoodView();
4697 if (p_pwndView)
4699 m_Screen2View.ScheduleRangeRebuild(p_pwndView->m_pViewData, nFirstViewLine, nLastViewLine);
4703 void CBaseView::UpdateViewLineNumbers()
4705 int nLineNumber = 0;
4706 int nViewLineCount = GetViewCount();
4707 for (int nViewLine = 0; nViewLine < nViewLineCount; nViewLine++)
4709 int oldLine = (int)GetViewLineNumber(nViewLine);
4710 if (oldLine >= 0)
4711 SetViewLineNumber(nViewLine, nLineNumber++);
4713 m_nDigits = 0;
4716 int CBaseView::CleanEmptyLines()
4718 int nRemovedCount = 0;
4719 int nViewLineCount = GetViewCount();
4720 bool bCheckLeft = IsViewGood(m_pwndLeft);
4721 bool bCheckRight = IsViewGood(m_pwndRight);
4722 bool bCheckBottom = IsViewGood(m_pwndBottom);
4723 for (int nViewLine = 0; nViewLine < nViewLineCount; )
4725 bool bAllEmpty = true;
4726 bAllEmpty &= !bCheckLeft || IsStateEmpty(m_pwndLeft->GetViewState(nViewLine));
4727 bAllEmpty &= !bCheckRight || IsStateEmpty(m_pwndRight->GetViewState(nViewLine));
4728 bAllEmpty &= !bCheckBottom || IsStateEmpty(m_pwndBottom->GetViewState(nViewLine));
4729 if (bAllEmpty)
4731 if (bCheckLeft)
4733 m_pwndLeft->RemoveViewData(nViewLine);
4735 if (bCheckRight)
4737 m_pwndRight->RemoveViewData(nViewLine);
4739 if (bCheckBottom)
4741 m_pwndBottom->RemoveViewData(nViewLine);
4743 if (CUndo::GetInstance().IsGrouping()) // if use group undo -> ensure back adding goes in right (reversed) order
4745 SaveUndoStep();
4747 nViewLineCount--;
4748 nRemovedCount++;
4749 continue;
4751 nViewLine++;
4753 return nRemovedCount;
4756 int CBaseView::FindScreenLineForViewLine( int viewLine )
4758 return m_Screen2View.FindScreenLineForViewLine(viewLine);
4761 int CBaseView::CountMultiLines( int nViewLine )
4763 if (m_ScreenedViewLine.empty())
4764 return 0; // in case the view is completely empty
4766 ASSERT(nViewLine < (int)m_ScreenedViewLine.size());
4768 if (m_ScreenedViewLine[nViewLine].bSublinesSet)
4770 return (int)m_ScreenedViewLine[nViewLine].SubLines.size();
4773 CString multiline = CStringUtils::WordWrap(m_pViewData->GetLine(nViewLine), GetScreenChars()-1, false, true, GetTabSize()); // GetMultiLine(nLine);
4775 TScreenedViewLine oScreenedLine;
4776 // tokenize string
4777 int prevpos = 0;
4778 int pos = 0;
4779 while ((pos = multiline.Find('\n', pos)) >= 0)
4781 oScreenedLine.SubLines.push_back(multiline.Mid(prevpos, pos-prevpos)); // WordWrap could return vector/list of lines instead of string
4782 pos++;
4783 prevpos = pos;
4785 oScreenedLine.SubLines.push_back(multiline.Mid(prevpos));
4786 oScreenedLine.bSublinesSet = true;
4787 m_ScreenedViewLine[nViewLine] = oScreenedLine;
4789 return CountMultiLines(nViewLine);
4792 /// prepare inline diff cache
4793 LineColors & CBaseView::GetLineColors(int nViewLine)
4795 ASSERT(nViewLine < (int)m_ScreenedViewLine.size());
4797 if (m_bWhitespaceInlineDiffs)
4799 if (m_ScreenedViewLine[nViewLine].bLineColorsSetWhiteSpace)
4800 return m_ScreenedViewLine[nViewLine].lineColorsWhiteSpace;
4802 else
4804 if (m_ScreenedViewLine[nViewLine].bLineColorsSet)
4805 return m_ScreenedViewLine[nViewLine].lineColors;
4808 LineColors oLineColors;
4809 // set main line color
4810 COLORREF crBkgnd, crText;
4811 DiffStates diffState = m_pViewData->GetState(nViewLine);
4812 CDiffColors::GetInstance().GetColors(diffState, crBkgnd, crText);
4813 oLineColors.SetColor(0, crText, crBkgnd);
4815 do {
4816 if (!m_bShowInlineDiff)
4817 break;
4819 if ((diffState == DIFFSTATE_NORMAL)&&(!m_bWhitespaceInlineDiffs))
4820 break;
4822 CString sLine = GetViewLineChars(nViewLine);
4823 if (sLine.IsEmpty())
4824 break;
4825 if (!m_pOtherView)
4826 break;
4828 CString sDiffLine = m_pOtherView->GetViewLineChars(nViewLine);
4829 if (sDiffLine.IsEmpty())
4830 break;
4832 svn_diff_t * diff = NULL;
4833 if (sLine.GetLength() > (int)m_nInlineDiffMaxLineLength)
4834 break;
4835 auto pLine1 = (this == m_pwndLeft) ? &sLine : &sDiffLine;
4836 auto pLine2 = (this == m_pwndLeft) ? &sDiffLine : &sLine;
4837 m_svnlinediff.Diff(&diff, *pLine1, pLine1->GetLength(), *pLine2, pLine2->GetLength(), m_bInlineWordDiff);
4838 if (!diff || !SVNLineDiff::ShowInlineDiff(diff) || !diff->next)
4839 break;
4841 int lineoffset = 0;
4842 int nTextStartOffset = 0;
4843 std::map<int, COLORREF> removedPositions;
4844 while (diff)
4846 if (this == m_pwndRight)
4848 apr_off_t nTmp = diff->modified_length;
4849 diff->modified_length = diff->original_length;
4850 diff->original_length = nTmp;
4852 nTmp = diff->modified_start;
4853 diff->modified_start = diff->original_start;
4854 diff->original_start = nTmp;
4856 apr_off_t len = diff->original_length;
4858 size_t nTextLength = 0;
4859 for (int i = 0; i < len; ++i)
4861 nTextLength += (this == m_pwndRight) ? m_svnlinediff.m_line2tokens[lineoffset].size() : m_svnlinediff.m_line1tokens[lineoffset].size();
4862 lineoffset++;
4864 bool bInlineDiff = (diff->type == svn_diff__type_diff_modified);
4866 CDiffColors::GetInstance().GetColors(diffState, crBkgnd, crText);
4867 if ((m_bShowInlineDiff)&&(bInlineDiff))
4869 crBkgnd = InlineViewLineDiffColor(nViewLine);
4871 else
4873 crBkgnd = m_ModifiedBk;
4876 if (len < diff->modified_length)
4878 removedPositions[nTextStartOffset] = m_InlineRemovedBk;
4880 oLineColors.SetColor(nTextStartOffset, crText, crBkgnd);
4882 nTextStartOffset += (int)nTextLength;
4883 diff = diff->next;
4885 for (std::map<int, COLORREF>::const_iterator it = removedPositions.begin(); it != removedPositions.end(); ++it)
4887 oLineColors.AddShotColor(it->first, it->second);
4889 } while (false); // error catch
4891 if (!m_bWhitespaceInlineDiffs)
4893 m_ScreenedViewLine[nViewLine].lineColors = oLineColors;
4894 m_ScreenedViewLine[nViewLine].bLineColorsSet = true;
4896 else
4898 m_ScreenedViewLine[nViewLine].lineColorsWhiteSpace = oLineColors;
4899 m_ScreenedViewLine[nViewLine].bLineColorsSetWhiteSpace = true;
4902 return GetLineColors(nViewLine);
4905 void CBaseView::OnEditSelectall()
4907 if (m_pViewData == nullptr)
4908 return;
4909 int nLastViewLine = m_pViewData->GetCount()-1;
4910 if (nLastViewLine < 0)
4911 return;
4912 SetupAllViewSelection(0, nLastViewLine);
4914 CString sLine = GetViewLineChars(nLastViewLine);
4915 m_ptSelectionViewPosStart = SetupPoint(0, 0);
4916 m_ptSelectionViewPosEnd = SetupPoint(sLine.GetLength(), nLastViewLine);
4917 m_ptSelectionViewPosOrigin = SetupPoint(-1, -1);
4919 UpdateWindow();
4922 void CBaseView::FilterWhitespaces(CString& first, CString& second)
4924 FilterWhitespaces(first);
4925 FilterWhitespaces(second);
4928 void CBaseView::FilterWhitespaces(CString& line)
4930 line.Remove(' ');
4931 line.Remove('\t');
4932 line.Remove('\r');
4933 line.Remove('\n');
4936 int CBaseView::GetButtonEventLineIndex(const POINT& point)
4938 const int nLineFromTop = (point.y - HEADERHEIGHT) / GetLineHeight();
4939 int nEventLine = nLineFromTop + m_nTopLine;
4940 nEventLine--; //we need the index
4941 return nEventLine;
4945 BOOL CBaseView::PreTranslateMessage(MSG* pMsg)
4947 if (RelayTrippleClick(pMsg))
4948 return TRUE;
4949 return CView::PreTranslateMessage(pMsg);
4953 void CBaseView::ResetUndoStep()
4955 m_AllState.Clear();
4958 void CBaseView::SaveUndoStep()
4960 if (!m_AllState.IsEmpty())
4962 CUndo::GetInstance().AddState(m_AllState, GetCaretViewPosition());
4964 ResetUndoStep();
4967 void CBaseView::InsertViewData( int index, const CString& sLine, DiffStates state, int linenumber, EOL ending, HIDESTATE hide, int movedline )
4969 m_pState->addedlines.push_back(index);
4970 m_pViewData->InsertData(index, sLine, state, linenumber, ending, hide, movedline);
4973 void CBaseView::InsertViewData( int index, const viewdata& data )
4975 m_pState->addedlines.push_back(index);
4976 m_pViewData->InsertData(index, data);
4979 void CBaseView::RemoveViewData( int index )
4981 m_pState->removedlines[index] = m_pViewData->GetData(index);
4982 m_pViewData->RemoveData(index);
4985 void CBaseView::SetViewData( int index, const viewdata& data )
4987 m_pState->replacedlines[index] = m_pViewData->GetData(index);
4988 m_pViewData->SetData(index, data);
4991 void CBaseView::SetViewState( int index, DiffStates state )
4993 m_pState->linestates[index] = m_pViewData->GetState(index);
4994 m_pViewData->SetState(index, state);
4997 void CBaseView::SetViewLine( int index, const CString& sLine )
4999 m_pState->difflines[index] = m_pViewData->GetLine(index);
5000 m_pViewData->SetLine(index, sLine);
5003 void CBaseView::SetViewLineNumber( int index, int linenumber )
5005 int oldLineNumber = m_pViewData->GetLineNumber(index);
5006 if (oldLineNumber != linenumber) {
5007 m_pState->linelines[index] = oldLineNumber;
5008 m_pViewData->SetLineNumber(index, linenumber);
5012 void CBaseView::SetViewLineEnding( int index, EOL ending )
5014 m_pState->linesEOL[index] = m_pViewData->GetLineEnding(index);
5015 m_pViewData->SetLineEnding(index, ending);
5018 void CBaseView::SetViewMarked( int index, bool marked )
5020 m_pState->markedlines[index] = m_pViewData->GetMarked(index);
5021 m_pViewData->SetMarked(index, marked);
5025 BOOL CBaseView::GetViewSelection( int& start, int& end ) const
5027 if (HasSelection())
5029 start = m_nSelViewBlockStart;
5030 end = m_nSelViewBlockEnd;
5031 return true;
5033 return false;
5036 int CBaseView::Screen2View::GetViewLineForScreen( int screenLine )
5038 RebuildIfNecessary();
5039 if ((size() <= screenLine) || (screenLine < 0))
5040 return 0;
5041 return m_Screen2View[screenLine].nViewLine;
5044 int CBaseView::Screen2View::size()
5046 RebuildIfNecessary();
5047 return (int)m_Screen2View.size();
5050 int CBaseView::Screen2View::GetSubLineOffset( int screenLine )
5052 RebuildIfNecessary();
5053 if (size() <= screenLine)
5054 return 0;
5055 return m_Screen2View[screenLine].nViewSubLine;
5058 CBaseView::TScreenLineInfo CBaseView::Screen2View::GetScreenLineInfo( int screenLine )
5060 RebuildIfNecessary();
5061 return m_Screen2View[screenLine];
5065 doing partial rebuild, whole screen2view vector is built, but uses ScreenedViewLine cache to do it faster
5067 void CBaseView::Screen2View::RebuildIfNecessary()
5069 if (!m_pViewData)
5070 return; // rebuild not necessary
5072 FixScreenedCacheSize(m_pwndLeft);
5073 FixScreenedCacheSize(m_pwndRight);
5074 FixScreenedCacheSize(m_pwndBottom);
5075 if (!m_bFull)
5077 for (auto it = m_RebuildRanges.cbegin(); it != m_RebuildRanges.cend(); ++it)
5079 ResetScreenedViewLineCache(m_pwndLeft, *it);
5080 ResetScreenedViewLineCache(m_pwndRight, *it);
5081 ResetScreenedViewLineCache(m_pwndBottom, *it);
5084 else
5086 ResetScreenedViewLineCache(m_pwndLeft);
5087 ResetScreenedViewLineCache(m_pwndRight);
5088 ResetScreenedViewLineCache(m_pwndBottom);
5090 m_RebuildRanges.clear();
5091 m_bFull = false;
5093 size_t OldSize = m_Screen2View.size();
5094 m_Screen2View.clear();
5095 m_Screen2View.reserve(OldSize); // guess same size
5096 for (int i = 0; i < m_pViewData->GetCount(); ++i)
5098 if (m_pMainFrame->m_bCollapsed)
5100 while ((i < m_pViewData->GetCount())&&(m_pViewData->GetHideState(i) == HIDESTATE_HIDDEN))
5101 ++i;
5102 if (!(i < m_pViewData->GetCount()))
5103 break;
5105 TScreenLineInfo oLineInfo;
5106 oLineInfo.nViewLine = i;
5107 oLineInfo.nViewSubLine = -1; // no wrap
5108 if (m_pMainFrame->m_bWrapLines && !IsViewLineHidden(m_pViewData, i))
5110 int nMaxLines = 0;
5111 if (IsLeftViewGood())
5112 nMaxLines = std::max<int>(nMaxLines, m_pwndLeft->CountMultiLines(i));
5113 if (IsRightViewGood())
5114 nMaxLines = std::max<int>(nMaxLines, m_pwndRight->CountMultiLines(i));
5115 if (IsBottomViewGood())
5116 nMaxLines = std::max<int>(nMaxLines, m_pwndBottom->CountMultiLines(i));
5117 for (int l = 0; l < (nMaxLines-1); ++l)
5119 oLineInfo.nViewSubLine++;
5120 m_Screen2View.push_back(oLineInfo);
5122 oLineInfo.nViewSubLine++;
5124 m_Screen2View.push_back(oLineInfo);
5126 m_pViewData = NULL;
5128 if (IsLeftViewGood())
5129 m_pwndLeft->BuildMarkedWordArray();
5130 if (IsRightViewGood())
5131 m_pwndRight->BuildMarkedWordArray();
5132 if (IsBottomViewGood())
5133 m_pwndBottom->BuildMarkedWordArray();
5134 UpdateLocator();
5135 RecalcAllVertScrollBars();
5136 RecalcAllHorzScrollBars();
5139 int CBaseView::Screen2View::FindScreenLineForViewLine( int viewLine )
5141 RebuildIfNecessary();
5143 int nScreenLineCount = (int)m_Screen2View.size();
5145 int nPos = 0;
5146 if (nScreenLineCount>16)
5148 // for enough long data search for last screen
5149 // with viewline less than one we are looking for
5150 // use approximate method (based on) binary search using asymmetric start point
5151 // in form 2**n (determined as MSB of length) to go around division and rounding;
5152 // this effectively looks for bit values from MSB to LSB
5154 int nTestBit;
5155 //GetMostSignificantBitValue
5156 // note _BitScanReverse(&nTestBit, nScreenLineCount); can be used instead
5157 nTestBit = nScreenLineCount;
5158 nTestBit |= nTestBit>>1;
5159 nTestBit |= nTestBit>>2;
5160 nTestBit |= nTestBit>>4;
5161 nTestBit |= nTestBit>>8;
5162 nTestBit |= nTestBit>>16;
5163 nTestBit ^= (nTestBit>>1);
5165 while (nTestBit)
5167 int nTestPos = nPos | nTestBit;
5168 if (nTestPos < nScreenLineCount && m_Screen2View[nTestPos].nViewLine < viewLine)
5170 nPos = nTestPos;
5172 nTestBit >>= 1;
5175 while (nPos < nScreenLineCount && m_Screen2View[nPos].nViewLine < viewLine)
5177 nPos++;
5180 return nPos;
5183 void CBaseView::Screen2View::ScheduleFullRebuild(CViewData * pViewData) {
5184 m_bFull = true;
5186 m_pViewData = pViewData;
5189 void CBaseView::Screen2View::ScheduleRangeRebuild(CViewData * pViewData, int nFirstViewLine, int nLastViewLine)
5191 if (m_bFull)
5192 return;
5194 m_pViewData = pViewData;
5196 TRebuildRange Range;
5197 Range.FirstViewLine=nFirstViewLine;
5198 Range.LastViewLine=nLastViewLine;
5199 m_RebuildRanges.push_back(Range);
5202 bool CBaseView::Screen2View::FixScreenedCacheSize(CBaseView* pwndView)
5204 if (!IsViewGood(pwndView))
5206 return false;
5208 const int nOldSize = (int)pwndView->m_ScreenedViewLine.size();
5209 const int nViewCount = std::max<int>(pwndView->GetViewCount(), 0);
5210 if (nOldSize == nViewCount)
5212 return false;
5214 pwndView->m_ScreenedViewLine.resize(nViewCount);
5215 return true;
5218 bool CBaseView::Screen2View::ResetScreenedViewLineCache(CBaseView* pwndView) const
5220 if (!IsViewGood(pwndView))
5222 return false;
5224 TRebuildRange Range={0, pwndView->GetViewCount()-1};
5225 ResetScreenedViewLineCache(pwndView, Range);
5226 return true;
5229 bool CBaseView::Screen2View::ResetScreenedViewLineCache(CBaseView* pwndView, const TRebuildRange& Range) const
5231 if (!IsViewGood(pwndView))
5233 return false;
5235 if (Range.LastViewLine == -1)
5237 return false;
5239 ASSERT(Range.FirstViewLine >= 0);
5240 ASSERT(Range.LastViewLine < pwndView->GetViewCount());
5241 for (int i = Range.FirstViewLine; i <= Range.LastViewLine; i++)
5243 pwndView->m_ScreenedViewLine[i].Clear();
5245 return false;
5248 void CBaseView::WrapChanged()
5250 m_nMaxLineLength = -1;
5251 m_nOffsetChar = 0;
5254 void CBaseView::OnEditFind()
5256 if (m_pFindDialog)
5257 return;
5259 m_pFindDialog = new CFindDlg(this);
5260 m_pFindDialog->Create(this);
5262 m_pFindDialog->SetFindString(HasTextSelection() ? GetSelectedText() : L"");
5263 m_pFindDialog->SetReadonly(m_bReadonly);
5266 LRESULT CBaseView::OnFindDialogMessage(WPARAM wParam, LPARAM /*lParam*/)
5268 ASSERT(m_pFindDialog != NULL);
5270 if (m_pFindDialog->IsTerminating())
5272 // invalidate the handle identifying the dialog box.
5273 m_pFindDialog = NULL;
5274 return 0;
5277 if(m_pFindDialog->FindNext())
5279 //read data from dialog
5280 m_sFindText = m_pFindDialog->GetFindString();
5281 m_bMatchCase = (m_pFindDialog->MatchCase() == TRUE);
5282 m_bLimitToDiff = m_pFindDialog->LimitToDiffs();
5283 m_bWholeWord = m_pFindDialog->WholeWord();
5285 if (!m_bMatchCase)
5286 m_sFindText = m_sFindText.MakeLower();
5288 BuildFindStringArray();
5289 if ((CFindDlg::FindType)wParam == CFindDlg::FindType::Find)
5291 if (m_pFindDialog->SearchUp())
5292 OnEditFindprev();
5293 else
5294 OnEditFindnext();
5296 else if ((CFindDlg::FindType)wParam == CFindDlg::FindType::Count)
5298 size_t count = 0;
5299 for (size_t i = 0; i < m_arFindStringLines.size(); ++i)
5300 count += m_arFindStringLines[i];
5301 CString format;
5302 format.LoadString(IDS_FIND_COUNT);
5303 CString matches;
5304 matches.Format(format, count);
5305 m_pFindDialog->SetStatusText(matches);
5307 else if ((CFindDlg::FindType)wParam == CFindDlg::FindType::Replace)
5309 if (!IsWritable())
5310 return 0;
5311 bool bFound = false;
5312 if (m_pFindDialog->SearchUp())
5313 bFound = Search(SearchPrevious, true, true, false);
5314 else
5315 bFound = Search(SearchNext, true, true, false);
5316 if (bFound)
5318 CString sReplaceText = m_pFindDialog->GetReplaceString();
5319 CUndo::GetInstance().BeginGrouping();
5320 RemoveSelectedText();
5321 InsertText(sReplaceText);
5322 CUndo::GetInstance().EndGrouping();
5326 else if ((CFindDlg::FindType)wParam == CFindDlg::FindType::ReplaceAll)
5328 if (!IsWritable())
5329 return 0;
5330 bool bFound = false;
5331 int replaceCount = 0;
5332 POINT lastPoint = m_ptSelectionViewPosStart;
5333 m_ptSelectionViewPosStart.x = m_ptSelectionViewPosStart.y = 0;
5334 CUndo::GetInstance().BeginGrouping();
5337 bFound = Search(SearchNext, true, false, true);
5338 if (bFound)
5340 CString sReplaceText = m_pFindDialog->GetReplaceString();
5341 RemoveSelectedText();
5342 InsertText(sReplaceText);
5343 ++replaceCount;
5345 } while (bFound);
5346 CUndo::GetInstance().EndGrouping();
5347 if (replaceCount == 0)
5348 m_ptSelectionViewPosStart = lastPoint;
5349 CString message;
5350 message.Format(IDS_FIND_REPLACED, replaceCount);
5351 if (m_pFindDialog)
5352 m_pFindDialog->SetStatusText(message, RGB(0, 0, 0));
5357 return 0;
5360 void CBaseView::OnEditFindnextStart()
5362 if (m_pViewData == nullptr)
5363 return;
5364 if (HasTextSelection())
5366 m_sFindText = GetSelectedText();
5367 m_bMatchCase = false;
5368 m_bLimitToDiff = false;
5369 m_bWholeWord = false;
5370 m_sFindText = m_sFindText.MakeLower();
5372 BuildFindStringArray();
5373 OnEditFindnext();
5375 else
5377 m_sFindText.Empty();
5378 BuildFindStringArray();
5382 void CBaseView::OnEditFindprevStart()
5384 if (m_pViewData == nullptr)
5385 return;
5386 if (HasTextSelection())
5388 m_sFindText = GetSelectedText();
5389 m_bMatchCase = false;
5390 m_bLimitToDiff = false;
5391 m_bWholeWord = false;
5392 m_sFindText = m_sFindText.MakeLower();
5394 BuildFindStringArray();
5395 OnEditFindprev();
5397 else
5399 m_sFindText.Empty();
5400 BuildFindStringArray();
5404 bool CBaseView::StringFound(const CString& str, SearchDirection srchDir, int& start, int& end) const
5406 if (srchDir == SearchPrevious)
5408 int laststart = -1;
5409 int laststart2 = -1;
5412 laststart2 = laststart;
5413 laststart = str.Find(m_sFindText, laststart + 1);
5414 } while (laststart >= 0 && laststart < start);
5415 start = laststart2;
5417 else
5418 start = str.Find(m_sFindText, start);
5419 end = start + m_sFindText.GetLength();
5420 bool bStringFound = (start >= 0);
5421 if (bStringFound && m_bWholeWord)
5423 if (start)
5424 bStringFound = IsWordSeparator(str.Mid(start-1,1).GetAt(0));
5426 if (bStringFound)
5428 if (str.GetLength() > end)
5429 bStringFound = IsWordSeparator(str.Mid(end, 1).GetAt(0));
5432 return bStringFound;
5435 void CBaseView::OnEditFindprev()
5437 Search(SearchPrevious, false, true, false);
5440 void CBaseView::OnEditFindnext()
5442 Search(SearchNext, false, true, false);
5445 bool CBaseView::Search(SearchDirection srchDir, bool useStart, bool flashIfNotFound, bool stopEof)
5447 if (m_sFindText.IsEmpty())
5448 return false;
5449 if(!m_pViewData)
5450 return false;
5452 POINT start = useStart ? m_ptSelectionViewPosStart : m_ptSelectionViewPosEnd;
5453 POINT end;
5454 end.y = m_pViewData->GetCount()-1;
5455 if (end.y < 0)
5456 return false;
5458 if (srchDir==SearchNext)
5459 end.x = GetViewLineLength(end.y);
5460 else
5462 end.x = m_ptSelectionViewPosStart.x;
5463 start.x = 0;
5466 if (!HasTextSelection())
5468 start.y = m_ptCaretViewPos.y;
5469 if (srchDir==SearchNext)
5470 start.x = m_ptCaretViewPos.x;
5471 else
5473 start.x = 0;
5474 end.x = m_ptCaretViewPos.x;
5477 CString sSelectedText;
5478 int startline = -1;
5479 for (int nViewLine=start.y; ;srchDir==SearchNext ? nViewLine++ : nViewLine--)
5481 if (nViewLine < 0)
5483 if (stopEof)
5484 return false;
5485 nViewLine = m_pViewData->GetCount()-1;
5486 startline = start.y;
5487 if (flashIfNotFound)
5489 if (m_pFindDialog)
5490 m_pFindDialog->SetStatusText(CString(MAKEINTRESOURCE(IDS_FIND_TOPREACHED)), RGB(63, 127, 47));
5491 m_pMainFrame->FlashWindowEx(FLASHW_ALL, 2, 100);
5494 if (nViewLine > end.y)
5496 if (stopEof)
5497 return false;
5498 nViewLine = 0;
5499 startline = start.y;
5500 if (flashIfNotFound)
5502 if (m_pFindDialog)
5503 m_pFindDialog->SetStatusText(CString(MAKEINTRESOURCE(IDS_FIND_BOTTOMREACHED)), RGB(63, 127, 47));
5504 m_pMainFrame->FlashWindowEx(FLASHW_ALL, 2, 100);
5507 switch (m_pViewData->GetState(nViewLine))
5509 case DIFFSTATE_EMPTY:
5510 break;
5511 case DIFFSTATE_UNKNOWN:
5512 case DIFFSTATE_NORMAL:
5513 if (m_bLimitToDiff)
5514 break;
5515 case DIFFSTATE_REMOVED:
5516 case DIFFSTATE_REMOVEDWHITESPACE:
5517 case DIFFSTATE_ADDED:
5518 case DIFFSTATE_ADDEDWHITESPACE:
5519 case DIFFSTATE_WHITESPACE:
5520 case DIFFSTATE_WHITESPACE_DIFF:
5521 case DIFFSTATE_CONFLICTED:
5522 case DIFFSTATE_CONFLICTED_IGNORED:
5523 case DIFFSTATE_CONFLICTADDED:
5524 case DIFFSTATE_CONFLICTEMPTY:
5525 case DIFFSTATE_CONFLICTRESOLVED:
5526 case DIFFSTATE_IDENTICALREMOVED:
5527 case DIFFSTATE_IDENTICALADDED:
5528 case DIFFSTATE_THEIRSREMOVED:
5529 case DIFFSTATE_THEIRSADDED:
5530 case DIFFSTATE_YOURSREMOVED:
5531 case DIFFSTATE_YOURSADDED:
5532 case DIFFSTATE_EDITED:
5534 sSelectedText = GetViewLineChars(nViewLine);
5535 if (nViewLine == start.y && startline < 0)
5536 sSelectedText = srchDir == SearchNext ? sSelectedText.Mid(start.x) : sSelectedText.Left(end.x);
5537 if (!m_bMatchCase)
5538 sSelectedText = sSelectedText.MakeLower();
5539 int startfound = srchDir == SearchNext ? 0 : sSelectedText.GetLength();
5540 int endfound = 0;
5541 if (StringFound(sSelectedText, srchDir, startfound, endfound))
5543 HighlightViewLines(nViewLine, nViewLine);
5544 m_ptSelectionViewPosStart.x = startfound;
5545 m_ptSelectionViewPosEnd.x = endfound;
5546 if (nViewLine == start.y && startline < 0)
5548 m_ptSelectionViewPosStart.x += start.x;
5549 m_ptSelectionViewPosEnd.x += start.x;
5551 m_ptSelectionViewPosEnd.x = m_ptSelectionViewPosStart.x + m_sFindText.GetLength();
5552 m_ptSelectionViewPosStart.y = nViewLine;
5553 m_ptSelectionViewPosEnd.y = nViewLine;
5554 m_ptCaretViewPos = m_ptSelectionViewPosStart;
5555 UpdateViewsCaretPosition();
5556 EnsureCaretVisible();
5557 Invalidate();
5558 return true;
5561 break;
5564 if (startline >= 0)
5566 if (nViewLine == startline)
5568 if (flashIfNotFound)
5570 CString message;
5571 message.Format(IDS_FIND_NOTFOUND, m_sFindText);
5572 if (m_pFindDialog)
5573 m_pFindDialog->SetStatusText(message, RGB(255, 0, 0));
5574 ::MessageBeep(0xFFFFFFFF);
5575 m_pMainFrame->FlashWindowEx(FLASHW_ALL, 3, 100);
5577 break;
5581 m_pMainFrame->m_nMoveMovesToIgnore = MOVESTOIGNORE;
5582 return false;
5585 CString CBaseView::GetSelectedText() const
5587 CString sSelectedText;
5588 POINT start = m_ptSelectionViewPosStart;
5589 POINT end = m_ptSelectionViewPosEnd;
5590 if (!HasTextSelection())
5592 if (!HasSelection())
5593 return sSelectedText;
5594 start.y = m_nSelViewBlockStart;
5595 start.x = 0;
5596 end.y = m_nSelViewBlockEnd;
5597 end.x = GetViewLineLength(m_nSelViewBlockEnd);
5599 if (m_pViewData == nullptr)
5600 return sSelectedText;
5601 // first store the selected lines in one CString
5602 for (int nViewLine=start.y; nViewLine<=end.y; nViewLine++)
5604 switch (m_pViewData->GetState(nViewLine))
5606 case DIFFSTATE_EMPTY:
5607 break;
5608 case DIFFSTATE_UNKNOWN:
5609 case DIFFSTATE_NORMAL:
5610 case DIFFSTATE_REMOVED:
5611 case DIFFSTATE_REMOVEDWHITESPACE:
5612 case DIFFSTATE_ADDED:
5613 case DIFFSTATE_ADDEDWHITESPACE:
5614 case DIFFSTATE_WHITESPACE:
5615 case DIFFSTATE_WHITESPACE_DIFF:
5616 case DIFFSTATE_CONFLICTED:
5617 case DIFFSTATE_CONFLICTED_IGNORED:
5618 case DIFFSTATE_CONFLICTADDED:
5619 case DIFFSTATE_CONFLICTEMPTY:
5620 case DIFFSTATE_CONFLICTRESOLVED:
5621 case DIFFSTATE_IDENTICALREMOVED:
5622 case DIFFSTATE_IDENTICALADDED:
5623 case DIFFSTATE_THEIRSREMOVED:
5624 case DIFFSTATE_THEIRSADDED:
5625 case DIFFSTATE_YOURSREMOVED:
5626 case DIFFSTATE_YOURSADDED:
5627 case DIFFSTATE_EDITED:
5628 sSelectedText += GetViewLineChars(nViewLine);
5629 sSelectedText += _T("\r\n");
5630 break;
5633 // remove the non-selected chars from the first line, last line and last \r\n
5634 int nLeftCut = start.x;
5635 int nRightCut = GetViewLineChars(end.y).GetLength() - end.x + 2;
5636 sSelectedText = sSelectedText.Mid(nLeftCut, sSelectedText.GetLength()-nLeftCut-nRightCut);
5637 return sSelectedText;
5640 void CBaseView::CheckModifications(bool& hasMods, bool& hasConflicts, bool& hasWhitespaceMods)
5642 hasMods = false;
5643 hasConflicts = false;
5644 hasWhitespaceMods = false;
5646 if (m_pViewData)
5648 for (int i=0; i<m_pViewData->GetCount(); i++)
5650 DiffStates state = m_pViewData->GetState(i);
5651 switch (state)
5653 case DIFFSTATE_ADDED:
5654 case DIFFSTATE_IDENTICALADDED:
5655 case DIFFSTATE_THEIRSADDED:
5656 case DIFFSTATE_YOURSADDED:
5657 case DIFFSTATE_CONFLICTADDED:
5658 case DIFFSTATE_IDENTICALREMOVED:
5659 case DIFFSTATE_REMOVED:
5660 case DIFFSTATE_THEIRSREMOVED:
5661 case DIFFSTATE_YOURSREMOVED:
5662 case DIFFSTATE_EMPTY:
5663 hasMods = true;
5664 break;
5665 case DIFFSTATE_CONFLICTED:
5666 case DIFFSTATE_CONFLICTED_IGNORED:
5667 hasConflicts = true;
5668 break;
5669 case DIFFSTATE_REMOVEDWHITESPACE:
5670 case DIFFSTATE_ADDEDWHITESPACE:
5671 case DIFFSTATE_WHITESPACE:
5672 case DIFFSTATE_WHITESPACE_DIFF:
5673 hasWhitespaceMods = true;
5674 break;
5680 void CBaseView::OnEditGotoline()
5682 if (m_pViewData == NULL)
5683 return;
5684 // find the last and first line number
5685 int nViewLineCount = m_pViewData->GetCount();
5687 int nLastLineNumber = DIFF_EMPTYLINENUMBER;
5688 for (int nViewLine=nViewLineCount-1; nViewLine>=0; --nViewLine)
5690 nLastLineNumber = m_pViewData->GetLineNumber(nViewLine);
5691 if (nLastLineNumber!=DIFF_EMPTYLINENUMBER)
5693 break;
5696 if (nLastLineNumber==DIFF_EMPTYLINENUMBER || nLastLineNumber==0) // not numbered line foud or last one is first
5698 return;
5700 nLastLineNumber++;
5701 int nFirstLineNumber=1; // first is always 1
5703 CString sText;
5704 sText.Format(IDS_GOTOLINE, nFirstLineNumber, nLastLineNumber);
5706 CGotoLineDlg dlg(this);
5707 dlg.SetLabel(sText);
5708 dlg.SetLimits(nFirstLineNumber, nLastLineNumber);
5709 if (dlg.DoModal() == IDOK)
5711 for (int nViewLine = 0; nViewLine < nViewLineCount; ++nViewLine)
5713 if ((m_pViewData->GetLineNumber(nViewLine)+1) == dlg.GetLineNumber())
5715 HighlightViewLines(nViewLine, nViewLine);
5716 return;
5722 void CBaseView::OnToggleReadonly()
5724 if (IsReadonlyChangable()) {
5725 SetWritable(IsReadonly());
5729 int CBaseView::SaveFile(int nFlags)
5731 Invalidate();
5732 if (m_pViewData!=NULL && m_pWorkingFile!=NULL)
5734 CFileTextLines file;
5735 m_SaveParams.m_LineEndings = m_lineendings;
5736 m_SaveParams.m_UnicodeType = m_texttype;
5737 file.SetSaveParams(m_SaveParams);
5739 for (int i=0; i<m_pViewData->GetCount(); i++)
5741 //only copy non-removed lines
5742 DiffStates state = m_pViewData->GetState(i);
5743 switch (state)
5745 case DIFFSTATE_CONFLICTED:
5746 case DIFFSTATE_CONFLICTED_IGNORED:
5748 int first = i;
5749 int last = i;
5752 last++;
5753 } while((last<m_pViewData->GetCount()) && ((m_pViewData->GetState(last)==DIFFSTATE_CONFLICTED)||(m_pViewData->GetState(last)==DIFFSTATE_CONFLICTED_IGNORED)));
5754 file.Add(_T("<<<<<<< .mine"), EOL_NOENDING);
5755 for (int j=first; j<last; j++)
5757 file.Add(m_pwndRight->m_pViewData->GetLine(j), m_pwndRight->m_pViewData->GetLineEnding(j));
5759 file.Add(_T("======="), EOL_NOENDING);
5760 for (int j=first; j<last; j++)
5762 file.Add(m_pwndLeft->m_pViewData->GetLine(j), m_pwndLeft->m_pViewData->GetLineEnding(j));
5764 file.Add(_T(">>>>>>> .theirs"), EOL_NOENDING);
5765 i = last-1;
5767 break;
5768 case DIFFSTATE_EMPTY:
5769 break;
5770 case DIFFSTATE_CONFLICTEMPTY:
5771 case DIFFSTATE_IDENTICALREMOVED:
5772 case DIFFSTATE_REMOVED:
5773 case DIFFSTATE_THEIRSREMOVED:
5774 case DIFFSTATE_YOURSREMOVED:
5775 case DIFFSTATE_CONFLICTRESOLVEDEMPTY:
5776 if ((nFlags&SAVE_REMOVEDLINES) == 0)
5778 // do not save removed lines
5779 break;
5781 default:
5782 file.Add(m_pViewData->GetLine(i), m_pViewData->GetLineEnding(i));
5783 break;
5786 CString filename = m_pWorkingFile->GetFilename();
5787 if (m_pWorkingFile->IsReadonly())
5788 if (!CCommonAppUtils::FileOpenSave(filename, NULL, IDS_SAVEASTITLE, IDS_COMMONFILEFILTER, false, m_hWnd))
5789 return -1;
5790 if (!file.Save(filename))
5792 ::MessageBox(m_hWnd, file.GetErrorString(), _T("TortoiseGitMerge"), MB_ICONERROR);
5793 return -1;
5795 m_pWorkingFile->SetFileName(filename);
5796 m_pWorkingFile->StoreFileAttributes();
5797 // m_dlgFilePatches.SetFileStatusAsPatched(sFilePath);
5798 SetModified(FALSE);
5799 CUndo::GetInstance().MarkAsOriginalState(
5800 this == m_pwndLeft,
5801 this == m_pwndRight,
5802 this == m_pwndBottom);
5803 if (file.GetCount() == 1 && file.GetAt(0).IsEmpty() && file.GetLineEnding(0) == EOL_NOENDING)
5804 return 0;
5805 return file.GetCount();
5807 return 1;
5811 int CBaseView::SaveFileTo(CString sFileName, int nFlags)
5813 if (m_pWorkingFile)
5815 m_pWorkingFile->SetFileName(sFileName);
5816 return SaveFile(nFlags);
5818 return -1;
5822 EOL CBaseView::GetLineEndings()
5824 return GetLineEndings(GetWhitecharsProperties().HasMixedEols);
5827 EOL CBaseView::GetLineEndings(bool bHasMixedEols)
5829 if (bHasMixedEols)
5831 return EOL_AUTOLINE; // mixed eols - hack value
5833 if (m_lineendings == EOL_AUTOLINE)
5835 return EOL_CRLF;
5837 return m_lineendings;
5840 void CBaseView::ReplaceLineEndings(EOL eEol)
5842 if (eEol == EOL_AUTOLINE)
5844 return;
5846 // set AUTOLINE
5847 m_lineendings = eEol;
5848 // replace all set EOLs
5849 // TODO store line endings and lineendings in undo
5850 //CUndo::BeginGrouping();
5851 for (int i = 0; i < GetViewCount(); ++i)
5853 if (IsLineEmpty(i))
5855 continue;
5857 EOL eLineEol = GetViewLineEnding(i);
5858 if (eLineEol == EOL_AUTOLINE || eLineEol == EOL_NOENDING || eLineEol == m_lineendings)
5860 continue;
5862 SetViewLineEnding(i, eEol);
5864 //CUndo::EndGrouping();
5865 //CUndo::saveundostep;
5866 DocumentUpdated();
5867 SetModified();
5870 void CBaseView::SetLineEndingStyle(EOL eEol)
5872 m_lineendings = eEol;
5875 void CBaseView::SetTextType(CFileTextLines::UnicodeType eTextType)
5877 if (m_texttype == eTextType)
5879 return;
5881 m_texttype = eTextType;
5882 DocumentUpdated();
5883 SetModified();
5886 void CBaseView::AskUserForNewLineEndingsAndTextType(int nTextId)
5888 if (IsReadonly())
5889 return; // nothing to be changed in read-only view
5890 CEncodingDlg dlg;
5891 dlg.view = CString(MAKEINTRESOURCE(nTextId));
5892 dlg.texttype = m_texttype;
5893 dlg.lineendings = GetLineEndings();
5894 if (dlg.DoModal() != IDOK)
5895 return;
5896 SetTextType(dlg.texttype);
5897 ReplaceLineEndings(dlg.lineendings);
5901 Replaces lines from source view to this
5903 void CBaseView::UseViewBlock(CBaseView * pwndView, int nFirstViewLine, int nLastViewLine, std::function<bool(int)> fnSkip)
5905 if (!IsViewGood(pwndView))
5906 return;
5907 if (!IsWritable())
5908 return;
5909 CUndo::GetInstance().BeginGrouping();
5911 for (int viewLine = nFirstViewLine; viewLine <= nLastViewLine; viewLine++)
5913 bool skip = fnSkip(viewLine);
5914 if (skip)
5916 if (GetViewMarked(viewLine))
5917 SetViewMarked(viewLine, false);
5918 continue;
5920 viewdata line = pwndView->GetViewData(viewLine);
5921 if (line.ending != EOL_NOENDING)
5922 line.ending = m_lineendings;
5923 switch (line.state)
5925 case DIFFSTATE_CONFLICTEMPTY:
5926 case DIFFSTATE_UNKNOWN:
5927 line.state = DIFFSTATE_EMPTY;
5928 case DIFFSTATE_EMPTY:
5929 break;
5930 case DIFFSTATE_ADDED:
5931 case DIFFSTATE_CONFLICTADDED:
5932 case DIFFSTATE_CONFLICTED:
5933 case DIFFSTATE_CONFLICTED_IGNORED:
5934 case DIFFSTATE_IDENTICALADDED:
5935 case DIFFSTATE_THEIRSADDED:
5936 case DIFFSTATE_YOURSADDED:
5937 case DIFFSTATE_IDENTICALREMOVED:
5938 case DIFFSTATE_REMOVED:
5939 case DIFFSTATE_THEIRSREMOVED:
5940 case DIFFSTATE_YOURSREMOVED:
5941 pwndView->SetViewState(viewLine, DIFFSTATE_NORMAL);
5942 line.state = DIFFSTATE_NORMAL;
5943 case DIFFSTATE_NORMAL:
5944 break;
5945 default:
5946 break;
5948 bool marked = GetViewMarked(viewLine);
5949 SetViewData(viewLine, line);
5950 if (marked)
5951 SetViewMarked(viewLine, false);
5952 if ((m_texttype == UnicodeType::ASCII) && (pwndView->GetTextType() != UnicodeType::ASCII))
5954 // if this view is in ASCII and the other is not, we have to make sure that
5955 // the text we copy from the other view can actually be saved in ASCII encoding.
5956 // if not, we have to change this views encoding to the same encoding as the other view
5957 BOOL useDefault = FALSE;
5958 WideCharToMultiByte(CP_ACP, WC_NO_BEST_FIT_CHARS, line.sLine, -1, NULL, 0, 0, &useDefault);
5959 if (useDefault) // a default char is required, so the char can not be saved as ASCII
5960 SetTextType(pwndView->GetTextType());
5963 // normal lines is mostly same but may differ in EOL so any copied line change view state to modified
5964 // TODO: check if copied line is same as original one set modified only when differ
5965 SetModified();
5966 SaveUndoStep();
5968 int nRemovedLines = CleanEmptyLines();
5969 SaveUndoStep();
5970 //VerifyEols();
5971 // make sure all non empty line have EOL set but last
5972 // wrong can be last copied line(have eol, but no line under),
5973 // or old last line (line before copied block missing eol, but have line under)
5974 // we'll check all lines to be sure
5975 int nLine = GetViewCount();
5976 // check last line have no EOL set
5977 while (--nLine>=0)
5979 if (!IsViewLineEmpty(nLine))
5981 if (GetViewLineEnding(nLine) != EOL_NOENDING)
5983 // we added non last line into empty block on the end (or should we remove eol from this one ?)
5984 // so next line is empty
5985 ASSERT(IsViewLineEmpty(nLine+1));
5986 // and we can turn it to normal empty line
5987 SetViewData(nLine+1, viewdata(CString(), DIFFSTATE_ADDED, 1, EOL_NOENDING, HIDESTATE_SHOWN));
5989 break;
5992 // check all (nonlast) line have EOL set
5993 while (--nLine>=0)
5995 if (!IsViewLineEmpty(nLine))
5997 if (GetViewLineEnding(nLine) == EOL_NOENDING)
5999 SetViewLineEnding(nLine, m_lineendings);
6000 // in theory there should be only one line needing fix, but most of time we get over all anyway
6001 // break;
6005 SaveUndoStep();
6006 UpdateViewLineNumbers();
6007 SaveUndoStep();
6009 CUndo::GetInstance().EndGrouping();
6011 if (nRemovedLines!=0)
6013 // some lines are gone update selection
6014 ClearSelection();
6015 SetupAllViewSelection(nFirstViewLine, nLastViewLine - nRemovedLines);
6017 BuildAllScreen2ViewVector();
6018 pwndView->Invalidate();
6019 RefreshViews();
6022 void CBaseView::MarkBlock(bool marked, int nFirstViewLine, int nLastViewLine)
6024 if (!IsWritable())
6025 return;
6026 CUndo::GetInstance().BeginGrouping();
6028 for (int viewLine = nFirstViewLine; viewLine <= nLastViewLine; viewLine++)
6029 SetViewMarked(viewLine, marked);
6031 SetModified();
6032 SaveUndoStep();
6033 CUndo::GetInstance().EndGrouping();
6035 BuildAllScreen2ViewVector();
6036 Invalidate();
6037 RefreshViews();
6040 void CBaseView::LeaveOnlyMarkedBlocks(CBaseView *pwndView)
6042 auto fn = [this](int viewLine) -> bool { return GetViewMarked(viewLine) || GetViewState(viewLine) == DIFFSTATE_EDITED; };
6043 UseViewBlock(pwndView, 0, GetViewCount() - 1, fn);
6046 void CBaseView::UseViewFileOfMarked(CBaseView *pwndView)
6048 auto fn = [this](int viewLine) -> bool { return !GetViewMarked(viewLine) || GetViewState(viewLine) == DIFFSTATE_EDITED; };
6049 UseViewBlock(pwndView, 0, GetViewCount() - 1, fn);
6052 void CBaseView::UseViewFileExceptEdited(CBaseView *pwndView)
6054 auto fn = [this](int viewLine) -> bool { return GetViewState(viewLine) == DIFFSTATE_EDITED; };
6055 UseViewBlock(pwndView, 0, GetViewCount() - 1, fn);
6058 int CBaseView::GetIndentCharsForLine(int x, int y)
6060 const int maxGuessLine = 100;
6061 int nTabMode = -1;
6062 CString line = GetViewLine(y);
6063 if (m_nTabMode & TABMODE_SMARTINDENT)
6065 // detect left char and right char
6066 TCHAR lc = x > 0 ? line[x - 1] : '\0';
6067 TCHAR rc = x < line.GetLength() ? line[x] : '\0';
6068 if (lc == ' ' && rc != '\t' || rc == ' ' && lc != '\t')
6069 nTabMode = 1;
6070 if (lc == '\t' && rc != ' ' || rc == '\t' && lc != ' ')
6071 nTabMode = 0;
6072 if (lc == ' ' && rc == '\t' || rc == ' ' && lc == '\t')
6073 nTabMode = m_nTabMode & TABMODE_USESPACES;
6075 // detect lines nearby
6076 for (int i = y - 1, j = y + 1; nTabMode == -1; --i, ++j)
6078 bool above = i > 0 && i >= y - maxGuessLine;
6079 bool below = j < GetViewCount() && j <= y + maxGuessLine;
6080 if (!(above || below))
6081 break;
6082 TCHAR ac = above ? GetViewLine(i)[0] : '\0';
6083 TCHAR bc = below ? GetViewLine(j)[0] : '\0';
6084 if (ac == ' ' && bc != '\t' || bc == ' ' && ac != '\t')
6085 nTabMode = 1;
6086 else if (ac == '\t' && bc != ' ' || bc == '\t' && ac != ' ')
6087 nTabMode = 0;
6088 else if (ac == ' ' && bc == '\t' || bc == ' ' && ac == '\t')
6089 nTabMode = m_nTabMode & TABMODE_USESPACES;
6092 else
6093 nTabMode = m_nTabMode & TABMODE_USESPACES;
6095 if (nTabMode > 0)
6097 // use spaces
6098 x = CountExpandedChars(line, x);
6099 return (m_nTabSize - (x % m_nTabSize));
6102 // use tab
6103 return 0;
6106 void CBaseView::AddIndentationForSelectedBlock()
6108 bool bModified = false;
6109 for (int nViewLine = m_ptSelectionViewPosStart.y; nViewLine <= m_ptSelectionViewPosEnd.y; nViewLine++)
6111 // skip the line if no character is selected in the last selected line
6112 if (nViewLine == m_ptSelectionViewPosEnd.y && m_ptSelectionViewPosEnd.x == 0)
6114 continue;
6116 // skip empty lines
6117 if (IsLineEmpty(nViewLine))
6119 continue;
6121 const CString &sLine = GetViewLine(nViewLine);
6122 CString sTemp = sLine;
6123 if (sTemp.Trim().IsEmpty())
6125 // skip empty and whitechar only lines
6126 continue;
6128 // add tab to line start (alternatively m_nTabSize spaces can be used)
6129 CString tabStr;
6130 int indentChars = GetIndentCharsForLine(0, nViewLine);
6131 tabStr = indentChars > 0 ? CString(_T(' '), indentChars) : _T("\t");
6132 SetViewLine(nViewLine, tabStr + sLine);
6133 bModified = true;
6135 if (bModified)
6137 SetModified();
6138 SaveUndoStep();
6139 BuildAllScreen2ViewVector();
6143 void CBaseView::RemoveIndentationForSelectedBlock()
6145 bool bModified = false;
6146 for (int nViewLine = m_ptSelectionViewPosStart.y; nViewLine <= m_ptSelectionViewPosEnd.y; nViewLine++)
6148 // skip the line if no character is selected in the last selected line
6149 if (nViewLine == m_ptSelectionViewPosEnd.y && m_ptSelectionViewPosEnd.x == 0)
6151 continue;
6153 // skip empty lines
6154 if (IsLineEmpty(nViewLine))
6156 continue;
6158 CString sLine = GetViewLine(nViewLine);
6159 // remove up to n spaces from line start
6160 // and one tab (if less then n spaces was removed)
6161 int nPos = 0;
6162 while (nPos<m_nTabSize)
6164 switch (sLine[nPos])
6166 case ' ':
6167 nPos++;
6168 continue;
6169 case '\t':
6170 nPos++;
6172 break;
6174 if (nPos>0)
6176 sLine.Delete(0, nPos);
6177 SetViewLine(nViewLine, sLine);
6178 bModified = true;
6181 if (bModified)
6183 SetModified();
6184 SaveUndoStep();
6185 BuildAllScreen2ViewVector();
6190 there are two possible versions
6191 - convert tabs to spaces only in front of text (implemented)
6192 - convert all tabs to spaces
6194 void CBaseView::ConvertTabToSpaces()
6196 bool bModified = false;
6197 for (int nViewLine = 0; nViewLine < GetViewCount(); nViewLine++)
6199 if (IsLineEmpty(nViewLine))
6201 continue;
6203 const CString &sLine = GetViewLine(nViewLine);
6204 bool bTabToConvertFound = false;
6205 int nPosIn = 0;
6206 int nPosOut = 0;
6207 while (nPosIn<sLine.GetLength())
6209 switch (sLine[nPosIn])
6211 case ' ':
6212 nPosIn++;
6213 nPosOut++;
6214 continue;
6215 case '\t':
6216 nPosIn++;
6217 bTabToConvertFound = true;
6218 nPosOut = (nPosOut+m_nTabSize) - nPosOut%m_nTabSize;
6219 continue;
6221 break;
6223 if (bTabToConvertFound)
6225 CString sLineNew = sLine;
6226 sLineNew.Delete(0, nPosIn);
6227 sLineNew = CString(' ', nPosOut) + sLineNew;
6228 SetViewLine(nViewLine, sLineNew);
6229 bModified = true;
6232 if (bModified)
6234 SetModified();
6235 SaveUndoStep();
6236 BuildAllScreen2ViewVector();
6241 there are two possible version
6242 - convert spaces to tabs only in front of text (implemented)
6243 - convert all spaces to tabs
6245 void CBaseView::Tabularize()
6247 bool bModified = false;
6248 for (int nViewLine = 0; nViewLine < GetViewCount(); nViewLine++)
6250 if (IsLineEmpty(nViewLine))
6252 continue;
6254 const CString &sLine = GetViewLine(nViewLine);
6255 int nDel = 0;
6256 int nTabCount = 0; // total tabs to be used
6257 int nSpaceCount = 0; // number of spaces in tab size run
6258 int nPos = 0;
6259 while (nPos<sLine.GetLength())
6261 switch (sLine[nPos++])
6263 case ' ':
6264 //bSpace = true;
6265 if (++nSpaceCount < m_nTabSize)
6267 continue;
6269 case '\t':
6270 nTabCount++;
6271 nSpaceCount = 0;
6272 nDel = nPos;
6273 continue;
6275 break;
6277 if (nDel > 0)
6279 CString sLineNew = sLine;
6280 sLineNew.Delete(0, nDel);
6281 sLineNew = CString('\t', nTabCount) + sLineNew;
6282 if (sLine!=sLineNew)
6284 SetViewLine(nViewLine, sLineNew);
6285 bModified = true;
6289 if (bModified)
6291 SetModified();
6292 SaveUndoStep();
6293 BuildAllScreen2ViewVector();
6297 void CBaseView::RemoveTrailWhiteChars()
6299 bool bModified = false;
6300 for (int nViewLine = 0; nViewLine < GetViewCount(); nViewLine++)
6302 if (IsLineEmpty(nViewLine))
6304 continue;
6306 const CString &sLine = GetViewLine(nViewLine);
6307 CString sLineNew = sLine;
6308 sLineNew.TrimRight();
6309 if (sLine.GetLength()!=sLineNew.GetLength())
6311 SetViewLine(nViewLine, sLineNew);
6312 bModified = true;
6315 if (bModified)
6317 SetModified();
6318 SaveUndoStep();
6319 BuildAllScreen2ViewVector();
6323 CBaseView::TWhitecharsProperties CBaseView::GetWhitecharsProperties()
6325 if (GetViewCount()>10000)
6327 // 10k lines is enough to check
6328 TWhitecharsProperties oRet = {true, true, true, true};
6329 return oRet;
6331 TWhitecharsProperties oRet = {};
6332 for (int nViewLine = 0; nViewLine < GetViewCount(); nViewLine++)
6334 if (IsLineEmpty(nViewLine))
6336 continue;
6338 const CString &sLine = GetViewLine(nViewLine);
6339 if (sLine.IsEmpty())
6341 continue;
6343 // check leading whites for convertible tabs and spaces
6344 int nPos = 0;
6345 int nSpaceCount = 0; // number of spaces in tab size run
6346 while (nPos<sLine.GetLength() && (!oRet.HasSpacesToConvert || !oRet.HasTabsToConvert))
6348 switch (sLine[nPos++])
6350 case ' ':
6351 if (++nSpaceCount >= m_nTabSize)
6353 oRet.HasSpacesToConvert = true;
6355 continue;
6356 case '\t':
6357 oRet.HasTabsToConvert = true;
6358 if (nSpaceCount!=0)
6360 oRet.HasSpacesToConvert = true;
6362 continue;
6364 break;
6367 // check trailing whites for removable chars
6368 switch (sLine[sLine.GetLength()-1])
6370 case ' ':
6371 case '\t':
6372 oRet.HasTrailWhiteChars = true;
6375 // check EOLs
6376 EOL eLineEol = GetViewLineEnding(nViewLine);
6377 if (!oRet.HasMixedEols && (eLineEol != m_lineendings) && (eLineEol != EOL_AUTOLINE) && (eLineEol != EOL_NOENDING))
6379 oRet.HasMixedEols = true;
6382 return oRet;
6385 void CBaseView::InsertText(const CString& sText)
6387 ResetUndoStep();
6389 POINT ptCaretViewPos = GetCaretViewPosition();
6390 int nLeft = ptCaretViewPos.x;
6391 int nViewLine = ptCaretViewPos.y;
6393 if ((nViewLine == 0) && (GetViewCount() == 0))
6394 OnChar(VK_RETURN, 0, 0);
6396 std::vector<CString> lines;
6397 int nStart = 0;
6398 int nEolPos = 0;
6399 while ((nEolPos = sText.Find('\r', nEolPos)) >= 0)
6401 CString sLine = sText.Mid(nStart, nEolPos - nStart);
6402 lines.push_back(sLine);
6403 nEolPos++;
6404 nStart = nEolPos;
6406 CString sLine = sText.Mid(nStart);
6407 lines.push_back(sLine);
6409 int nLinesToPaste = (int)lines.size();
6410 if (nLinesToPaste > 1)
6412 // multiline text
6414 // We want to undo the multiline insertion in a single step.
6415 CUndo::GetInstance().BeginGrouping();
6417 sLine = GetViewLineChars(nViewLine);
6418 CString sLineLeft = sLine.Left(nLeft);
6419 CString sLineRight = sLine.Right(sLine.GetLength() - nLeft);
6420 EOL eOriginalEnding = GetViewLineEnding(nViewLine);
6421 viewdata newLine(L"", DIFFSTATE_EDITED, 1, m_lineendings, HIDESTATE_SHOWN);
6422 if (!lines[0].IsEmpty() || !sLineRight.IsEmpty() || (eOriginalEnding != m_lineendings))
6424 newLine.sLine = sLineLeft + lines[0];
6425 SetViewData(nViewLine, newLine);
6428 int nInsertLine = nViewLine;
6429 for (int i = 1; i < nLinesToPaste - 1; i++)
6431 newLine.sLine = lines[i];
6432 InsertViewData(++nInsertLine, newLine);
6434 newLine.sLine = lines[nLinesToPaste - 1] + sLineRight;
6435 newLine.ending = eOriginalEnding;
6436 InsertViewData(++nInsertLine, newLine);
6438 SetModified();
6439 SaveUndoStep();
6441 // adds new lines everywhere except me
6442 if (IsViewGood(m_pwndLeft) && m_pwndLeft != this)
6444 m_pwndLeft->InsertViewEmptyLines(nViewLine + 1, nLinesToPaste - 1);
6446 if (IsViewGood(m_pwndRight) && m_pwndRight != this)
6448 m_pwndRight->InsertViewEmptyLines(nViewLine + 1, nLinesToPaste - 1);
6450 if (IsViewGood(m_pwndBottom) && m_pwndBottom != this)
6452 m_pwndBottom->InsertViewEmptyLines(nViewLine + 1, nLinesToPaste - 1);
6454 SaveUndoStep();
6456 UpdateViewLineNumbers();
6457 CUndo::GetInstance().EndGrouping();
6459 ptCaretViewPos = SetupPoint(lines[nLinesToPaste - 1].GetLength(), nInsertLine);
6461 else
6463 // single line text - just insert it
6464 sLine = GetViewLineChars(nViewLine);
6465 sLine.Insert(nLeft, sText);
6466 ptCaretViewPos = SetupPoint(nLeft + sText.GetLength(), nViewLine);
6467 SetViewLine(nViewLine, sLine);
6468 SetViewState(nViewLine, DIFFSTATE_EDITED);
6469 SetModified();
6470 SaveUndoStep();
6473 RefreshViews();
6474 BuildAllScreen2ViewVector();
6475 UpdateCaretViewPosition(ptCaretViewPos);