Fix assertion
[TortoiseGit.git] / src / TortoiseMerge / BaseView.cpp
bloba87add82d12266f1927437557714675e1d924d62
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, 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, IDC_IBEAM)); // Set To Edit Cursor
2334 return TRUE;
2337 ::SetCursor(::LoadCursor(NULL, 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 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 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_PTR)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_PTR)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 if (this == m_pwndRight)
4564 apr_off_t nTmp = diff->modified_length;
4565 diff->modified_length = diff->original_length;
4566 diff->original_length = nTmp;
4568 nTmp = diff->modified_start;
4569 diff->modified_start = diff->original_start;
4570 diff->original_start = nTmp;
4572 apr_off_t len = diff->original_length;
4573 size_t oldpos = position;
4575 for (apr_off_t i = 0; i < len; ++i)
4577 position += (this == m_pwndRight) ? m_svnlinediff.m_line2tokens[lineoffset].size() : m_svnlinediff.m_line1tokens[lineoffset].size();
4578 lineoffset++;
4581 if (diff->type == svn_diff__type_diff_modified)
4583 inlineDiffPos p;
4584 p.start = oldpos;
4585 p.end = position;
4586 positions.push_back(p);
4589 diff = diff->next;
4592 return !positions.empty();
4595 void CBaseView::OnNavigateNextinlinediff()
4597 int nX;
4598 if (GetNextInlineDiff(nX))
4600 POINT ptCaretViewPos = GetCaretViewPosition();
4601 ptCaretViewPos.x = nX;
4602 SetCaretAndGoalViewPosition(ptCaretViewPos);
4603 m_ptSelectionViewPosOrigin = ptCaretViewPos;
4604 EnsureCaretVisible();
4608 void CBaseView::OnNavigatePrevinlinediff()
4610 int nX;
4611 if (GetPrevInlineDiff(nX))
4613 POINT ptCaretViewPos = GetCaretViewPosition();
4614 ptCaretViewPos.x = nX;
4615 SetCaretAndGoalViewPosition(ptCaretViewPos);
4616 m_ptSelectionViewPosOrigin = ptCaretViewPos;
4617 EnsureCaretVisible();
4621 bool CBaseView::HasNextInlineDiff()
4623 int nPos;
4624 return GetNextInlineDiff(nPos);
4627 bool CBaseView::GetNextInlineDiff(int & nPos)
4629 POINT ptCaretViewPos = GetCaretViewPosition();
4630 std::vector<inlineDiffPos> positions;
4631 if (GetInlineDiffPositions(ptCaretViewPos.y, positions))
4633 for (auto it = positions.cbegin(); it != positions.cend(); ++it)
4635 if (it->start > ptCaretViewPos.x)
4637 nPos = (LONG)it->start;
4638 return true;
4640 if (it->end > ptCaretViewPos.x)
4642 nPos = (LONG)it->end;
4643 return true;
4647 return false;
4650 bool CBaseView::HasPrevInlineDiff()
4652 int nPos;
4653 return GetPrevInlineDiff(nPos);
4656 bool CBaseView::GetPrevInlineDiff(int & nPos)
4658 POINT ptCaretViewPos = GetCaretViewPosition();
4659 std::vector<inlineDiffPos> positions;
4660 if (GetInlineDiffPositions(ptCaretViewPos.y, positions))
4662 for (auto it = positions.crbegin(); it != positions.crend(); ++it)
4664 if ( it->end < ptCaretViewPos.x)
4666 nPos = (LONG)it->end;
4667 return true;
4669 if ( it->start < ptCaretViewPos.x)
4671 nPos = (LONG)it->start;
4672 return true;
4676 return false;
4679 CBaseView * CBaseView::GetFirstGoodView()
4681 if (IsViewGood(m_pwndLeft))
4682 return m_pwndLeft;
4683 if (IsViewGood(m_pwndRight))
4684 return m_pwndRight;
4685 if (IsViewGood(m_pwndBottom))
4686 return m_pwndBottom;
4687 return NULL;
4690 void CBaseView::BuildAllScreen2ViewVector()
4692 CBaseView * p_pwndView = GetFirstGoodView();
4693 if (p_pwndView)
4695 m_Screen2View.ScheduleFullRebuild(p_pwndView->m_pViewData);
4699 void CBaseView::BuildAllScreen2ViewVector(int nViewLine)
4701 BuildAllScreen2ViewVector(nViewLine, nViewLine);
4704 void CBaseView::BuildAllScreen2ViewVector(int nFirstViewLine, int nLastViewLine)
4706 CBaseView * p_pwndView = GetFirstGoodView();
4707 if (p_pwndView)
4709 m_Screen2View.ScheduleRangeRebuild(p_pwndView->m_pViewData, nFirstViewLine, nLastViewLine);
4713 void CBaseView::UpdateViewLineNumbers()
4715 int nLineNumber = 0;
4716 int nViewLineCount = GetViewCount();
4717 for (int nViewLine = 0; nViewLine < nViewLineCount; nViewLine++)
4719 int oldLine = (int)GetViewLineNumber(nViewLine);
4720 if (oldLine >= 0)
4721 SetViewLineNumber(nViewLine, nLineNumber++);
4723 m_nDigits = 0;
4726 int CBaseView::CleanEmptyLines()
4728 int nRemovedCount = 0;
4729 int nViewLineCount = GetViewCount();
4730 bool bCheckLeft = IsViewGood(m_pwndLeft);
4731 bool bCheckRight = IsViewGood(m_pwndRight);
4732 bool bCheckBottom = IsViewGood(m_pwndBottom);
4733 for (int nViewLine = 0; nViewLine < nViewLineCount; )
4735 bool bAllEmpty = true;
4736 bAllEmpty &= !bCheckLeft || IsStateEmpty(m_pwndLeft->GetViewState(nViewLine));
4737 bAllEmpty &= !bCheckRight || IsStateEmpty(m_pwndRight->GetViewState(nViewLine));
4738 bAllEmpty &= !bCheckBottom || IsStateEmpty(m_pwndBottom->GetViewState(nViewLine));
4739 if (bAllEmpty)
4741 if (bCheckLeft)
4743 m_pwndLeft->RemoveViewData(nViewLine);
4745 if (bCheckRight)
4747 m_pwndRight->RemoveViewData(nViewLine);
4749 if (bCheckBottom)
4751 m_pwndBottom->RemoveViewData(nViewLine);
4753 if (CUndo::GetInstance().IsGrouping()) // if use group undo -> ensure back adding goes in right (reversed) order
4755 SaveUndoStep();
4757 nViewLineCount--;
4758 nRemovedCount++;
4759 continue;
4761 nViewLine++;
4763 return nRemovedCount;
4766 int CBaseView::FindScreenLineForViewLine( int viewLine )
4768 return m_Screen2View.FindScreenLineForViewLine(viewLine);
4771 int CBaseView::CountMultiLines( int nViewLine )
4773 if (m_ScreenedViewLine.empty())
4774 return 0; // in case the view is completely empty
4776 ASSERT(nViewLine < (int)m_ScreenedViewLine.size());
4778 if (m_ScreenedViewLine[nViewLine].bSublinesSet)
4780 return (int)m_ScreenedViewLine[nViewLine].SubLines.size();
4783 CString multiline = CStringUtils::WordWrap(m_pViewData->GetLine(nViewLine), GetScreenChars()-1, false, true, GetTabSize()); // GetMultiLine(nLine);
4785 TScreenedViewLine oScreenedLine;
4786 // tokenize string
4787 int prevpos = 0;
4788 int pos = 0;
4789 while ((pos = multiline.Find('\n', pos)) >= 0)
4791 oScreenedLine.SubLines.push_back(multiline.Mid(prevpos, pos-prevpos)); // WordWrap could return vector/list of lines instead of string
4792 pos++;
4793 prevpos = pos;
4795 oScreenedLine.SubLines.push_back(multiline.Mid(prevpos));
4796 oScreenedLine.bSublinesSet = true;
4797 m_ScreenedViewLine[nViewLine] = oScreenedLine;
4799 return CountMultiLines(nViewLine);
4802 /// prepare inline diff cache
4803 LineColors & CBaseView::GetLineColors(int nViewLine)
4805 ASSERT(nViewLine < (int)m_ScreenedViewLine.size());
4807 if (m_bWhitespaceInlineDiffs)
4809 if (m_ScreenedViewLine[nViewLine].bLineColorsSetWhiteSpace)
4810 return m_ScreenedViewLine[nViewLine].lineColorsWhiteSpace;
4812 else
4814 if (m_ScreenedViewLine[nViewLine].bLineColorsSet)
4815 return m_ScreenedViewLine[nViewLine].lineColors;
4818 LineColors oLineColors;
4819 // set main line color
4820 COLORREF crBkgnd, crText;
4821 DiffStates diffState = m_pViewData->GetState(nViewLine);
4822 CDiffColors::GetInstance().GetColors(diffState, crBkgnd, crText);
4823 oLineColors.SetColor(0, crText, crBkgnd);
4825 do {
4826 if (!m_bShowInlineDiff)
4827 break;
4829 if ((diffState == DIFFSTATE_NORMAL)&&(!m_bWhitespaceInlineDiffs))
4830 break;
4832 CString sLine = GetViewLineChars(nViewLine);
4833 if (sLine.IsEmpty())
4834 break;
4835 if (!m_pOtherView)
4836 break;
4838 CString sDiffLine = m_pOtherView->GetViewLineChars(nViewLine);
4839 if (sDiffLine.IsEmpty())
4840 break;
4842 svn_diff_t * diff = NULL;
4843 if (sLine.GetLength() > (int)m_nInlineDiffMaxLineLength)
4844 break;
4845 auto pLine1 = (this == m_pwndLeft) ? &sLine : &sDiffLine;
4846 auto pLine2 = (this == m_pwndLeft) ? &sDiffLine : &sLine;
4847 m_svnlinediff.Diff(&diff, *pLine1, pLine1->GetLength(), *pLine2, pLine2->GetLength(), m_bInlineWordDiff);
4848 if (!diff || !SVNLineDiff::ShowInlineDiff(diff) || !diff->next)
4849 break;
4851 int lineoffset = 0;
4852 int nTextStartOffset = 0;
4853 std::map<int, COLORREF> removedPositions;
4854 while (diff)
4856 if (this == m_pwndRight)
4858 apr_off_t nTmp = diff->modified_length;
4859 diff->modified_length = diff->original_length;
4860 diff->original_length = nTmp;
4862 nTmp = diff->modified_start;
4863 diff->modified_start = diff->original_start;
4864 diff->original_start = nTmp;
4866 apr_off_t len = diff->original_length;
4868 size_t nTextLength = 0;
4869 for (int i = 0; i < len; ++i)
4871 nTextLength += (this == m_pwndRight) ? m_svnlinediff.m_line2tokens[lineoffset].size() : m_svnlinediff.m_line1tokens[lineoffset].size();
4872 lineoffset++;
4874 bool bInlineDiff = (diff->type == svn_diff__type_diff_modified);
4876 CDiffColors::GetInstance().GetColors(diffState, crBkgnd, crText);
4877 if ((m_bShowInlineDiff)&&(bInlineDiff))
4879 crBkgnd = InlineViewLineDiffColor(nViewLine);
4881 else
4883 crBkgnd = m_ModifiedBk;
4886 if (len < diff->modified_length)
4888 removedPositions[nTextStartOffset] = m_InlineRemovedBk;
4890 oLineColors.SetColor(nTextStartOffset, crText, crBkgnd);
4892 nTextStartOffset += (int)nTextLength;
4893 diff = diff->next;
4895 for (std::map<int, COLORREF>::const_iterator it = removedPositions.begin(); it != removedPositions.end(); ++it)
4897 oLineColors.AddShotColor(it->first, it->second);
4899 } while (false); // error catch
4901 if (!m_bWhitespaceInlineDiffs)
4903 m_ScreenedViewLine[nViewLine].lineColors = oLineColors;
4904 m_ScreenedViewLine[nViewLine].bLineColorsSet = true;
4906 else
4908 m_ScreenedViewLine[nViewLine].lineColorsWhiteSpace = oLineColors;
4909 m_ScreenedViewLine[nViewLine].bLineColorsSetWhiteSpace = true;
4912 return GetLineColors(nViewLine);
4915 void CBaseView::OnEditSelectall()
4917 if (m_pViewData == nullptr)
4918 return;
4919 int nLastViewLine = m_pViewData->GetCount()-1;
4920 if (nLastViewLine < 0)
4921 return;
4922 SetupAllViewSelection(0, nLastViewLine);
4924 CString sLine = GetViewLineChars(nLastViewLine);
4925 m_ptSelectionViewPosStart = SetupPoint(0, 0);
4926 m_ptSelectionViewPosEnd = SetupPoint(sLine.GetLength(), nLastViewLine);
4927 m_ptSelectionViewPosOrigin = SetupPoint(-1, -1);
4929 UpdateWindow();
4932 void CBaseView::FilterWhitespaces(CString& first, CString& second)
4934 FilterWhitespaces(first);
4935 FilterWhitespaces(second);
4938 void CBaseView::FilterWhitespaces(CString& line)
4940 line.Remove(' ');
4941 line.Remove('\t');
4942 line.Remove('\r');
4943 line.Remove('\n');
4946 int CBaseView::GetButtonEventLineIndex(const POINT& point)
4948 const int nLineFromTop = (point.y - HEADERHEIGHT) / GetLineHeight();
4949 int nEventLine = nLineFromTop + m_nTopLine;
4950 nEventLine--; //we need the index
4951 return nEventLine;
4955 BOOL CBaseView::PreTranslateMessage(MSG* pMsg)
4957 if (RelayTrippleClick(pMsg))
4958 return TRUE;
4959 return CView::PreTranslateMessage(pMsg);
4963 void CBaseView::ResetUndoStep()
4965 m_AllState.Clear();
4968 void CBaseView::SaveUndoStep()
4970 if (!m_AllState.IsEmpty())
4972 CUndo::GetInstance().AddState(m_AllState, GetCaretViewPosition());
4974 ResetUndoStep();
4977 void CBaseView::InsertViewData( int index, const CString& sLine, DiffStates state, int linenumber, EOL ending, HIDESTATE hide, int movedline )
4979 m_pState->addedlines.push_back(index);
4980 m_pViewData->InsertData(index, sLine, state, linenumber, ending, hide, movedline);
4983 void CBaseView::InsertViewData( int index, const viewdata& data )
4985 m_pState->addedlines.push_back(index);
4986 m_pViewData->InsertData(index, data);
4989 void CBaseView::RemoveViewData( int index )
4991 m_pState->removedlines[index] = m_pViewData->GetData(index);
4992 m_pViewData->RemoveData(index);
4995 void CBaseView::SetViewData( int index, const viewdata& data )
4997 m_pState->replacedlines[index] = m_pViewData->GetData(index);
4998 m_pViewData->SetData(index, data);
5001 void CBaseView::SetViewState( int index, DiffStates state )
5003 m_pState->linestates[index] = m_pViewData->GetState(index);
5004 m_pViewData->SetState(index, state);
5007 void CBaseView::SetViewLine( int index, const CString& sLine )
5009 m_pState->difflines[index] = m_pViewData->GetLine(index);
5010 m_pViewData->SetLine(index, sLine);
5013 void CBaseView::SetViewLineNumber( int index, int linenumber )
5015 int oldLineNumber = m_pViewData->GetLineNumber(index);
5016 if (oldLineNumber != linenumber) {
5017 m_pState->linelines[index] = oldLineNumber;
5018 m_pViewData->SetLineNumber(index, linenumber);
5022 void CBaseView::SetViewLineEnding( int index, EOL ending )
5024 m_pState->linesEOL[index] = m_pViewData->GetLineEnding(index);
5025 m_pViewData->SetLineEnding(index, ending);
5028 void CBaseView::SetViewMarked( int index, bool marked )
5030 m_pState->markedlines[index] = m_pViewData->GetMarked(index);
5031 m_pViewData->SetMarked(index, marked);
5035 BOOL CBaseView::GetViewSelection( int& start, int& end ) const
5037 if (HasSelection())
5039 start = m_nSelViewBlockStart;
5040 end = m_nSelViewBlockEnd;
5041 return true;
5043 return false;
5046 int CBaseView::Screen2View::GetViewLineForScreen( int screenLine )
5048 RebuildIfNecessary();
5049 if ((size() <= screenLine) || (screenLine < 0))
5050 return 0;
5051 return m_Screen2View[screenLine].nViewLine;
5054 int CBaseView::Screen2View::size()
5056 RebuildIfNecessary();
5057 return (int)m_Screen2View.size();
5060 int CBaseView::Screen2View::GetSubLineOffset( int screenLine )
5062 RebuildIfNecessary();
5063 if (size() <= screenLine)
5064 return 0;
5065 return m_Screen2View[screenLine].nViewSubLine;
5068 CBaseView::TScreenLineInfo CBaseView::Screen2View::GetScreenLineInfo( int screenLine )
5070 RebuildIfNecessary();
5071 return m_Screen2View[screenLine];
5075 doing partial rebuild, whole screen2view vector is built, but uses ScreenedViewLine cache to do it faster
5077 void CBaseView::Screen2View::RebuildIfNecessary()
5079 if (!m_pViewData)
5080 return; // rebuild not necessary
5082 FixScreenedCacheSize(m_pwndLeft);
5083 FixScreenedCacheSize(m_pwndRight);
5084 FixScreenedCacheSize(m_pwndBottom);
5085 if (!m_bFull)
5087 for (auto it = m_RebuildRanges.cbegin(); it != m_RebuildRanges.cend(); ++it)
5089 ResetScreenedViewLineCache(m_pwndLeft, *it);
5090 ResetScreenedViewLineCache(m_pwndRight, *it);
5091 ResetScreenedViewLineCache(m_pwndBottom, *it);
5094 else
5096 ResetScreenedViewLineCache(m_pwndLeft);
5097 ResetScreenedViewLineCache(m_pwndRight);
5098 ResetScreenedViewLineCache(m_pwndBottom);
5100 m_RebuildRanges.clear();
5101 m_bFull = false;
5103 size_t OldSize = m_Screen2View.size();
5104 m_Screen2View.clear();
5105 m_Screen2View.reserve(OldSize); // guess same size
5106 for (int i = 0; i < m_pViewData->GetCount(); ++i)
5108 if (m_pMainFrame->m_bCollapsed)
5110 while ((i < m_pViewData->GetCount())&&(m_pViewData->GetHideState(i) == HIDESTATE_HIDDEN))
5111 ++i;
5112 if (!(i < m_pViewData->GetCount()))
5113 break;
5115 TScreenLineInfo oLineInfo;
5116 oLineInfo.nViewLine = i;
5117 oLineInfo.nViewSubLine = -1; // no wrap
5118 if (m_pMainFrame->m_bWrapLines && !IsViewLineHidden(m_pViewData, i))
5120 int nMaxLines = 0;
5121 if (IsLeftViewGood())
5122 nMaxLines = std::max<int>(nMaxLines, m_pwndLeft->CountMultiLines(i));
5123 if (IsRightViewGood())
5124 nMaxLines = std::max<int>(nMaxLines, m_pwndRight->CountMultiLines(i));
5125 if (IsBottomViewGood())
5126 nMaxLines = std::max<int>(nMaxLines, m_pwndBottom->CountMultiLines(i));
5127 for (int l = 0; l < (nMaxLines-1); ++l)
5129 oLineInfo.nViewSubLine++;
5130 m_Screen2View.push_back(oLineInfo);
5132 oLineInfo.nViewSubLine++;
5134 m_Screen2View.push_back(oLineInfo);
5136 m_pViewData = NULL;
5138 if (IsLeftViewGood())
5139 m_pwndLeft->BuildMarkedWordArray();
5140 if (IsRightViewGood())
5141 m_pwndRight->BuildMarkedWordArray();
5142 if (IsBottomViewGood())
5143 m_pwndBottom->BuildMarkedWordArray();
5144 UpdateLocator();
5145 RecalcAllVertScrollBars();
5146 RecalcAllHorzScrollBars();
5149 int CBaseView::Screen2View::FindScreenLineForViewLine( int viewLine )
5151 RebuildIfNecessary();
5153 int nScreenLineCount = (int)m_Screen2View.size();
5155 int nPos = 0;
5156 if (nScreenLineCount>16)
5158 // for enough long data search for last screen
5159 // with viewline less than one we are looking for
5160 // use approximate method (based on) binary search using asymmetric start point
5161 // in form 2**n (determined as MSB of length) to go around division and rounding;
5162 // this effectively looks for bit values from MSB to LSB
5164 int nTestBit;
5165 //GetMostSignificantBitValue
5166 // note _BitScanReverse(&nTestBit, nScreenLineCount); can be used instead
5167 nTestBit = nScreenLineCount;
5168 nTestBit |= nTestBit>>1;
5169 nTestBit |= nTestBit>>2;
5170 nTestBit |= nTestBit>>4;
5171 nTestBit |= nTestBit>>8;
5172 nTestBit |= nTestBit>>16;
5173 nTestBit ^= (nTestBit>>1);
5175 while (nTestBit)
5177 int nTestPos = nPos | nTestBit;
5178 if (nTestPos < nScreenLineCount && m_Screen2View[nTestPos].nViewLine < viewLine)
5180 nPos = nTestPos;
5182 nTestBit >>= 1;
5185 while (nPos < nScreenLineCount && m_Screen2View[nPos].nViewLine < viewLine)
5187 nPos++;
5190 return nPos;
5193 void CBaseView::Screen2View::ScheduleFullRebuild(CViewData * pViewData) {
5194 m_bFull = true;
5196 m_pViewData = pViewData;
5199 void CBaseView::Screen2View::ScheduleRangeRebuild(CViewData * pViewData, int nFirstViewLine, int nLastViewLine)
5201 if (m_bFull)
5202 return;
5204 m_pViewData = pViewData;
5206 TRebuildRange Range;
5207 Range.FirstViewLine=nFirstViewLine;
5208 Range.LastViewLine=nLastViewLine;
5209 m_RebuildRanges.push_back(Range);
5212 bool CBaseView::Screen2View::FixScreenedCacheSize(CBaseView* pwndView)
5214 if (!IsViewGood(pwndView))
5216 return false;
5218 const int nOldSize = (int)pwndView->m_ScreenedViewLine.size();
5219 const int nViewCount = std::max<int>(pwndView->GetViewCount(), 0);
5220 if (nOldSize == nViewCount)
5222 return false;
5224 pwndView->m_ScreenedViewLine.resize(nViewCount);
5225 return true;
5228 bool CBaseView::Screen2View::ResetScreenedViewLineCache(CBaseView* pwndView) const
5230 if (!IsViewGood(pwndView))
5232 return false;
5234 TRebuildRange Range={0, pwndView->GetViewCount()-1};
5235 ResetScreenedViewLineCache(pwndView, Range);
5236 return true;
5239 bool CBaseView::Screen2View::ResetScreenedViewLineCache(CBaseView* pwndView, const TRebuildRange& Range) const
5241 if (!IsViewGood(pwndView))
5243 return false;
5245 if (Range.LastViewLine == -1)
5247 return false;
5249 ASSERT(Range.FirstViewLine >= 0);
5250 ASSERT(Range.LastViewLine < pwndView->GetViewCount());
5251 for (int i = Range.FirstViewLine; i <= Range.LastViewLine; i++)
5253 pwndView->m_ScreenedViewLine[i].Clear();
5255 return false;
5258 void CBaseView::WrapChanged()
5260 m_nMaxLineLength = -1;
5261 m_nOffsetChar = 0;
5264 void CBaseView::OnEditFind()
5266 if (m_pFindDialog)
5267 return;
5269 m_pFindDialog = new CFindDlg(this);
5270 m_pFindDialog->Create(this);
5272 m_pFindDialog->SetFindString(HasTextSelection() ? GetSelectedText() : L"");
5273 m_pFindDialog->SetReadonly(m_bReadonly);
5276 LRESULT CBaseView::OnFindDialogMessage(WPARAM wParam, LPARAM /*lParam*/)
5278 ASSERT(m_pFindDialog != NULL);
5280 if (m_pFindDialog->IsTerminating())
5282 // invalidate the handle identifying the dialog box.
5283 m_pFindDialog = NULL;
5284 return 0;
5287 if(m_pFindDialog->FindNext())
5289 //read data from dialog
5290 m_sFindText = m_pFindDialog->GetFindString();
5291 m_bMatchCase = (m_pFindDialog->MatchCase() == TRUE);
5292 m_bLimitToDiff = m_pFindDialog->LimitToDiffs();
5293 m_bWholeWord = m_pFindDialog->WholeWord();
5295 if (!m_bMatchCase)
5296 m_sFindText = m_sFindText.MakeLower();
5298 BuildFindStringArray();
5299 if ((CFindDlg::FindType)wParam == CFindDlg::FindType::Find)
5301 if (m_pFindDialog->SearchUp())
5302 OnEditFindprev();
5303 else
5304 OnEditFindnext();
5306 else if ((CFindDlg::FindType)wParam == CFindDlg::FindType::Count)
5308 size_t count = 0;
5309 for (size_t i = 0; i < m_arFindStringLines.size(); ++i)
5310 count += m_arFindStringLines[i];
5311 CString format;
5312 format.LoadString(IDS_FIND_COUNT);
5313 CString matches;
5314 matches.Format(format, count);
5315 m_pFindDialog->SetStatusText(matches);
5317 else if ((CFindDlg::FindType)wParam == CFindDlg::FindType::Replace)
5319 if (!IsWritable())
5320 return 0;
5321 bool bFound = false;
5322 if (m_pFindDialog->SearchUp())
5323 bFound = Search(SearchPrevious, true, true, false);
5324 else
5325 bFound = Search(SearchNext, true, true, false);
5326 if (bFound)
5328 CString sReplaceText = m_pFindDialog->GetReplaceString();
5329 CUndo::GetInstance().BeginGrouping();
5330 RemoveSelectedText();
5331 InsertText(sReplaceText);
5332 CUndo::GetInstance().EndGrouping();
5336 else if ((CFindDlg::FindType)wParam == CFindDlg::FindType::ReplaceAll)
5338 if (!IsWritable())
5339 return 0;
5340 bool bFound = false;
5341 int replaceCount = 0;
5342 POINT lastPoint = m_ptSelectionViewPosStart;
5343 m_ptSelectionViewPosStart.x = m_ptSelectionViewPosStart.y = 0;
5344 CUndo::GetInstance().BeginGrouping();
5347 bFound = Search(SearchNext, true, false, true);
5348 if (bFound)
5350 CString sReplaceText = m_pFindDialog->GetReplaceString();
5351 RemoveSelectedText();
5352 InsertText(sReplaceText);
5353 ++replaceCount;
5355 } while (bFound);
5356 CUndo::GetInstance().EndGrouping();
5357 if (replaceCount == 0)
5358 m_ptSelectionViewPosStart = lastPoint;
5359 CString message;
5360 message.Format(IDS_FIND_REPLACED, replaceCount);
5361 if (m_pFindDialog)
5362 m_pFindDialog->SetStatusText(message, RGB(0, 0, 0));
5367 return 0;
5370 void CBaseView::OnEditFindnextStart()
5372 if (m_pViewData == nullptr)
5373 return;
5374 if (HasTextSelection())
5376 m_sFindText = GetSelectedText();
5377 m_bMatchCase = false;
5378 m_bLimitToDiff = false;
5379 m_bWholeWord = false;
5380 m_sFindText = m_sFindText.MakeLower();
5382 BuildFindStringArray();
5383 OnEditFindnext();
5385 else
5387 m_sFindText.Empty();
5388 BuildFindStringArray();
5392 void CBaseView::OnEditFindprevStart()
5394 if (m_pViewData == nullptr)
5395 return;
5396 if (HasTextSelection())
5398 m_sFindText = GetSelectedText();
5399 m_bMatchCase = false;
5400 m_bLimitToDiff = false;
5401 m_bWholeWord = false;
5402 m_sFindText = m_sFindText.MakeLower();
5404 BuildFindStringArray();
5405 OnEditFindprev();
5407 else
5409 m_sFindText.Empty();
5410 BuildFindStringArray();
5414 bool CBaseView::StringFound(const CString& str, SearchDirection srchDir, int& start, int& end) const
5416 if (srchDir == SearchPrevious)
5418 int laststart = -1;
5419 int laststart2 = -1;
5422 laststart2 = laststart;
5423 laststart = str.Find(m_sFindText, laststart + 1);
5424 } while (laststart >= 0 && laststart < start);
5425 start = laststart2;
5427 else
5428 start = str.Find(m_sFindText, start);
5429 end = start + m_sFindText.GetLength();
5430 bool bStringFound = (start >= 0);
5431 if (bStringFound && m_bWholeWord)
5433 if (start)
5434 bStringFound = IsWordSeparator(str.Mid(start-1,1).GetAt(0));
5436 if (bStringFound)
5438 if (str.GetLength() > end)
5439 bStringFound = IsWordSeparator(str.Mid(end, 1).GetAt(0));
5442 return bStringFound;
5445 void CBaseView::OnEditFindprev()
5447 Search(SearchPrevious, false, true, false);
5450 void CBaseView::OnEditFindnext()
5452 Search(SearchNext, false, true, false);
5455 bool CBaseView::Search(SearchDirection srchDir, bool useStart, bool flashIfNotFound, bool stopEof)
5457 if (m_sFindText.IsEmpty())
5458 return false;
5459 if(!m_pViewData)
5460 return false;
5462 POINT start = useStart ? m_ptSelectionViewPosStart : m_ptSelectionViewPosEnd;
5463 POINT end;
5464 end.y = m_pViewData->GetCount()-1;
5465 if (end.y < 0)
5466 return false;
5468 if (srchDir==SearchNext)
5469 end.x = GetViewLineLength(end.y);
5470 else
5472 end.x = m_ptSelectionViewPosStart.x;
5473 start.x = 0;
5476 if (!HasTextSelection())
5478 start.y = m_ptCaretViewPos.y;
5479 if (srchDir==SearchNext)
5480 start.x = m_ptCaretViewPos.x;
5481 else
5483 start.x = 0;
5484 end.x = m_ptCaretViewPos.x;
5487 CString sSelectedText;
5488 int startline = -1;
5489 for (int nViewLine=start.y; ;srchDir==SearchNext ? nViewLine++ : nViewLine--)
5491 if (nViewLine < 0)
5493 if (stopEof)
5494 return false;
5495 nViewLine = m_pViewData->GetCount()-1;
5496 startline = start.y;
5497 if (flashIfNotFound)
5499 if (m_pFindDialog)
5500 m_pFindDialog->SetStatusText(CString(MAKEINTRESOURCE(IDS_FIND_TOPREACHED)), RGB(63, 127, 47));
5501 m_pMainFrame->FlashWindowEx(FLASHW_ALL, 2, 100);
5504 if (nViewLine > end.y)
5506 if (stopEof)
5507 return false;
5508 nViewLine = 0;
5509 startline = start.y;
5510 if (flashIfNotFound)
5512 if (m_pFindDialog)
5513 m_pFindDialog->SetStatusText(CString(MAKEINTRESOURCE(IDS_FIND_BOTTOMREACHED)), RGB(63, 127, 47));
5514 m_pMainFrame->FlashWindowEx(FLASHW_ALL, 2, 100);
5517 switch (m_pViewData->GetState(nViewLine))
5519 case DIFFSTATE_EMPTY:
5520 break;
5521 case DIFFSTATE_UNKNOWN:
5522 case DIFFSTATE_NORMAL:
5523 if (m_bLimitToDiff)
5524 break;
5525 case DIFFSTATE_REMOVED:
5526 case DIFFSTATE_REMOVEDWHITESPACE:
5527 case DIFFSTATE_ADDED:
5528 case DIFFSTATE_ADDEDWHITESPACE:
5529 case DIFFSTATE_WHITESPACE:
5530 case DIFFSTATE_WHITESPACE_DIFF:
5531 case DIFFSTATE_CONFLICTED:
5532 case DIFFSTATE_CONFLICTED_IGNORED:
5533 case DIFFSTATE_CONFLICTADDED:
5534 case DIFFSTATE_CONFLICTEMPTY:
5535 case DIFFSTATE_CONFLICTRESOLVED:
5536 case DIFFSTATE_IDENTICALREMOVED:
5537 case DIFFSTATE_IDENTICALADDED:
5538 case DIFFSTATE_THEIRSREMOVED:
5539 case DIFFSTATE_THEIRSADDED:
5540 case DIFFSTATE_YOURSREMOVED:
5541 case DIFFSTATE_YOURSADDED:
5542 case DIFFSTATE_EDITED:
5544 sSelectedText = GetViewLineChars(nViewLine);
5545 if (nViewLine == start.y && startline < 0)
5546 sSelectedText = srchDir == SearchNext ? sSelectedText.Mid(start.x) : sSelectedText.Left(end.x);
5547 if (!m_bMatchCase)
5548 sSelectedText = sSelectedText.MakeLower();
5549 int startfound = srchDir == SearchNext ? 0 : sSelectedText.GetLength();
5550 int endfound = 0;
5551 if (StringFound(sSelectedText, srchDir, startfound, endfound))
5553 HighlightViewLines(nViewLine, nViewLine);
5554 m_ptSelectionViewPosStart.x = startfound;
5555 m_ptSelectionViewPosEnd.x = endfound;
5556 if (nViewLine == start.y && startline < 0)
5558 m_ptSelectionViewPosStart.x += start.x;
5559 m_ptSelectionViewPosEnd.x += start.x;
5561 m_ptSelectionViewPosEnd.x = m_ptSelectionViewPosStart.x + m_sFindText.GetLength();
5562 m_ptSelectionViewPosStart.y = nViewLine;
5563 m_ptSelectionViewPosEnd.y = nViewLine;
5564 m_ptCaretViewPos = m_ptSelectionViewPosStart;
5565 UpdateViewsCaretPosition();
5566 EnsureCaretVisible();
5567 Invalidate();
5568 return true;
5571 break;
5574 if (startline >= 0)
5576 if (nViewLine == startline)
5578 if (flashIfNotFound)
5580 CString message;
5581 message.Format(IDS_FIND_NOTFOUND, m_sFindText);
5582 if (m_pFindDialog)
5583 m_pFindDialog->SetStatusText(message, RGB(255, 0, 0));
5584 ::MessageBeep(0xFFFFFFFF);
5585 m_pMainFrame->FlashWindowEx(FLASHW_ALL, 3, 100);
5587 break;
5591 m_pMainFrame->m_nMoveMovesToIgnore = MOVESTOIGNORE;
5592 return false;
5595 CString CBaseView::GetSelectedText() const
5597 CString sSelectedText;
5598 POINT start = m_ptSelectionViewPosStart;
5599 POINT end = m_ptSelectionViewPosEnd;
5600 if (!HasTextSelection())
5602 if (!HasSelection())
5603 return sSelectedText;
5604 start.y = m_nSelViewBlockStart;
5605 start.x = 0;
5606 end.y = m_nSelViewBlockEnd;
5607 end.x = GetViewLineLength(m_nSelViewBlockEnd);
5609 if (m_pViewData == nullptr)
5610 return sSelectedText;
5611 // first store the selected lines in one CString
5612 for (int nViewLine=start.y; nViewLine<=end.y; nViewLine++)
5614 switch (m_pViewData->GetState(nViewLine))
5616 case DIFFSTATE_EMPTY:
5617 break;
5618 case DIFFSTATE_UNKNOWN:
5619 case DIFFSTATE_NORMAL:
5620 case DIFFSTATE_REMOVED:
5621 case DIFFSTATE_REMOVEDWHITESPACE:
5622 case DIFFSTATE_ADDED:
5623 case DIFFSTATE_ADDEDWHITESPACE:
5624 case DIFFSTATE_WHITESPACE:
5625 case DIFFSTATE_WHITESPACE_DIFF:
5626 case DIFFSTATE_CONFLICTED:
5627 case DIFFSTATE_CONFLICTED_IGNORED:
5628 case DIFFSTATE_CONFLICTADDED:
5629 case DIFFSTATE_CONFLICTEMPTY:
5630 case DIFFSTATE_CONFLICTRESOLVED:
5631 case DIFFSTATE_IDENTICALREMOVED:
5632 case DIFFSTATE_IDENTICALADDED:
5633 case DIFFSTATE_THEIRSREMOVED:
5634 case DIFFSTATE_THEIRSADDED:
5635 case DIFFSTATE_YOURSREMOVED:
5636 case DIFFSTATE_YOURSADDED:
5637 case DIFFSTATE_EDITED:
5638 sSelectedText += GetViewLineChars(nViewLine);
5639 sSelectedText += _T("\r\n");
5640 break;
5643 // remove the non-selected chars from the first line, last line and last \r\n
5644 int nLeftCut = start.x;
5645 int nRightCut = GetViewLineChars(end.y).GetLength() - end.x + 2;
5646 sSelectedText = sSelectedText.Mid(nLeftCut, sSelectedText.GetLength()-nLeftCut-nRightCut);
5647 return sSelectedText;
5650 void CBaseView::CheckModifications(bool& hasMods, bool& hasConflicts, bool& hasWhitespaceMods)
5652 hasMods = false;
5653 hasConflicts = false;
5654 hasWhitespaceMods = false;
5656 if (m_pViewData)
5658 for (int i=0; i<m_pViewData->GetCount(); i++)
5660 DiffStates state = m_pViewData->GetState(i);
5661 switch (state)
5663 case DIFFSTATE_ADDED:
5664 case DIFFSTATE_IDENTICALADDED:
5665 case DIFFSTATE_THEIRSADDED:
5666 case DIFFSTATE_YOURSADDED:
5667 case DIFFSTATE_CONFLICTADDED:
5668 case DIFFSTATE_IDENTICALREMOVED:
5669 case DIFFSTATE_REMOVED:
5670 case DIFFSTATE_THEIRSREMOVED:
5671 case DIFFSTATE_YOURSREMOVED:
5672 case DIFFSTATE_EMPTY:
5673 hasMods = true;
5674 break;
5675 case DIFFSTATE_CONFLICTED:
5676 case DIFFSTATE_CONFLICTED_IGNORED:
5677 hasConflicts = true;
5678 break;
5679 case DIFFSTATE_REMOVEDWHITESPACE:
5680 case DIFFSTATE_ADDEDWHITESPACE:
5681 case DIFFSTATE_WHITESPACE:
5682 case DIFFSTATE_WHITESPACE_DIFF:
5683 hasWhitespaceMods = true;
5684 break;
5690 void CBaseView::OnEditGotoline()
5692 if (m_pViewData == NULL)
5693 return;
5694 // find the last and first line number
5695 int nViewLineCount = m_pViewData->GetCount();
5697 int nLastLineNumber = DIFF_EMPTYLINENUMBER;
5698 for (int nViewLine=nViewLineCount-1; nViewLine>=0; --nViewLine)
5700 nLastLineNumber = m_pViewData->GetLineNumber(nViewLine);
5701 if (nLastLineNumber!=DIFF_EMPTYLINENUMBER)
5703 break;
5706 if (nLastLineNumber==DIFF_EMPTYLINENUMBER || nLastLineNumber==0) // not numbered line foud or last one is first
5708 return;
5710 nLastLineNumber++;
5711 int nFirstLineNumber=1; // first is always 1
5713 CString sText;
5714 sText.Format(IDS_GOTOLINE, nFirstLineNumber, nLastLineNumber);
5716 CGotoLineDlg dlg(this);
5717 dlg.SetLabel(sText);
5718 dlg.SetLimits(nFirstLineNumber, nLastLineNumber);
5719 if (dlg.DoModal() == IDOK)
5721 for (int nViewLine = 0; nViewLine < nViewLineCount; ++nViewLine)
5723 if ((m_pViewData->GetLineNumber(nViewLine)+1) == dlg.GetLineNumber())
5725 HighlightViewLines(nViewLine, nViewLine);
5726 return;
5732 void CBaseView::OnToggleReadonly()
5734 if (IsReadonlyChangable()) {
5735 SetWritable(IsReadonly());
5739 int CBaseView::SaveFile(int nFlags)
5741 Invalidate();
5742 if (m_pViewData!=NULL && m_pWorkingFile!=NULL)
5744 CFileTextLines file;
5745 m_SaveParams.m_LineEndings = m_lineendings;
5746 m_SaveParams.m_UnicodeType = m_texttype;
5747 file.SetSaveParams(m_SaveParams);
5749 for (int i=0; i<m_pViewData->GetCount(); i++)
5751 //only copy non-removed lines
5752 DiffStates state = m_pViewData->GetState(i);
5753 switch (state)
5755 case DIFFSTATE_CONFLICTED:
5756 case DIFFSTATE_CONFLICTED_IGNORED:
5758 int first = i;
5759 int last = i;
5762 last++;
5763 } while((last<m_pViewData->GetCount()) && ((m_pViewData->GetState(last)==DIFFSTATE_CONFLICTED)||(m_pViewData->GetState(last)==DIFFSTATE_CONFLICTED_IGNORED)));
5764 file.Add(_T("<<<<<<< .mine"), EOL_NOENDING);
5765 for (int j=first; j<last; j++)
5767 file.Add(m_pwndRight->m_pViewData->GetLine(j), m_pwndRight->m_pViewData->GetLineEnding(j));
5769 file.Add(_T("======="), EOL_NOENDING);
5770 for (int j=first; j<last; j++)
5772 file.Add(m_pwndLeft->m_pViewData->GetLine(j), m_pwndLeft->m_pViewData->GetLineEnding(j));
5774 file.Add(_T(">>>>>>> .theirs"), EOL_NOENDING);
5775 i = last-1;
5777 break;
5778 case DIFFSTATE_EMPTY:
5779 break;
5780 case DIFFSTATE_CONFLICTEMPTY:
5781 case DIFFSTATE_IDENTICALREMOVED:
5782 case DIFFSTATE_REMOVED:
5783 case DIFFSTATE_THEIRSREMOVED:
5784 case DIFFSTATE_YOURSREMOVED:
5785 case DIFFSTATE_CONFLICTRESOLVEDEMPTY:
5786 if ((nFlags&SAVE_REMOVEDLINES) == 0)
5788 // do not save removed lines
5789 break;
5791 default:
5792 file.Add(m_pViewData->GetLine(i), m_pViewData->GetLineEnding(i));
5793 break;
5796 CString filename = m_pWorkingFile->GetFilename();
5797 if (m_pWorkingFile->IsReadonly())
5798 if (!CCommonAppUtils::FileOpenSave(filename, NULL, IDS_SAVEASTITLE, IDS_COMMONFILEFILTER, false, m_hWnd))
5799 return -1;
5800 if (!file.Save(filename))
5802 ::MessageBox(m_hWnd, file.GetErrorString(), _T("TortoiseGitMerge"), MB_ICONERROR);
5803 return -1;
5805 m_pWorkingFile->SetFileName(filename);
5806 m_pWorkingFile->StoreFileAttributes();
5807 // m_dlgFilePatches.SetFileStatusAsPatched(sFilePath);
5808 SetModified(FALSE);
5809 CUndo::GetInstance().MarkAsOriginalState(
5810 this == m_pwndLeft,
5811 this == m_pwndRight,
5812 this == m_pwndBottom);
5813 if (file.GetCount() == 1 && file.GetAt(0).IsEmpty() && file.GetLineEnding(0) == EOL_NOENDING)
5814 return 0;
5815 return file.GetCount();
5817 return 1;
5821 int CBaseView::SaveFileTo(CString sFileName, int nFlags)
5823 if (m_pWorkingFile)
5825 m_pWorkingFile->SetFileName(sFileName);
5826 return SaveFile(nFlags);
5828 return -1;
5832 EOL CBaseView::GetLineEndings()
5834 return GetLineEndings(GetWhitecharsProperties().HasMixedEols);
5837 EOL CBaseView::GetLineEndings(bool bHasMixedEols)
5839 if (bHasMixedEols)
5841 return EOL_AUTOLINE; // mixed eols - hack value
5843 if (m_lineendings == EOL_AUTOLINE)
5845 return EOL_CRLF;
5847 return m_lineendings;
5850 void CBaseView::ReplaceLineEndings(EOL eEol)
5852 if (eEol == EOL_AUTOLINE)
5854 return;
5856 // set AUTOLINE
5857 m_lineendings = eEol;
5858 // replace all set EOLs
5859 // TODO store line endings and lineendings in undo
5860 //CUndo::BeginGrouping();
5861 for (int i = 0; i < GetViewCount(); ++i)
5863 if (IsLineEmpty(i))
5865 continue;
5867 EOL eLineEol = GetViewLineEnding(i);
5868 if (eLineEol == EOL_AUTOLINE || eLineEol == EOL_NOENDING || eLineEol == m_lineendings)
5870 continue;
5872 SetViewLineEnding(i, eEol);
5874 //CUndo::EndGrouping();
5875 //CUndo::saveundostep;
5876 DocumentUpdated();
5877 SetModified();
5880 void CBaseView::SetLineEndingStyle(EOL eEol)
5882 m_lineendings = eEol;
5885 void CBaseView::SetTextType(CFileTextLines::UnicodeType eTextType)
5887 if (m_texttype == eTextType)
5889 return;
5891 m_texttype = eTextType;
5892 DocumentUpdated();
5893 SetModified();
5896 void CBaseView::AskUserForNewLineEndingsAndTextType(int nTextId)
5898 if (IsReadonly())
5899 return; // nothing to be changed in read-only view
5900 CEncodingDlg dlg;
5901 dlg.view = CString(MAKEINTRESOURCE(nTextId));
5902 dlg.texttype = m_texttype;
5903 dlg.lineendings = GetLineEndings();
5904 if (dlg.DoModal() != IDOK)
5905 return;
5906 SetTextType(dlg.texttype);
5907 ReplaceLineEndings(dlg.lineendings);
5911 Replaces lines from source view to this
5913 void CBaseView::UseViewBlock(CBaseView * pwndView, int nFirstViewLine, int nLastViewLine, std::function<bool(int)> fnSkip)
5915 if (!IsViewGood(pwndView))
5916 return;
5917 if (!IsWritable())
5918 return;
5919 CUndo::GetInstance().BeginGrouping();
5921 for (int viewLine = nFirstViewLine; viewLine <= nLastViewLine; viewLine++)
5923 bool skip = fnSkip(viewLine);
5924 if (skip)
5926 if (GetViewMarked(viewLine))
5927 SetViewMarked(viewLine, false);
5928 continue;
5930 viewdata line = pwndView->GetViewData(viewLine);
5931 if (line.ending != EOL_NOENDING)
5932 line.ending = m_lineendings;
5933 switch (line.state)
5935 case DIFFSTATE_CONFLICTEMPTY:
5936 case DIFFSTATE_UNKNOWN:
5937 line.state = DIFFSTATE_EMPTY;
5938 case DIFFSTATE_EMPTY:
5939 break;
5940 case DIFFSTATE_ADDED:
5941 case DIFFSTATE_CONFLICTADDED:
5942 case DIFFSTATE_CONFLICTED:
5943 case DIFFSTATE_CONFLICTED_IGNORED:
5944 case DIFFSTATE_IDENTICALADDED:
5945 case DIFFSTATE_THEIRSADDED:
5946 case DIFFSTATE_YOURSADDED:
5947 case DIFFSTATE_IDENTICALREMOVED:
5948 case DIFFSTATE_REMOVED:
5949 case DIFFSTATE_THEIRSREMOVED:
5950 case DIFFSTATE_YOURSREMOVED:
5951 pwndView->SetViewState(viewLine, DIFFSTATE_NORMAL);
5952 line.state = DIFFSTATE_NORMAL;
5953 case DIFFSTATE_NORMAL:
5954 break;
5955 default:
5956 break;
5958 bool marked = GetViewMarked(viewLine);
5959 SetViewData(viewLine, line);
5960 if (marked)
5961 SetViewMarked(viewLine, false);
5962 if ((m_texttype == UnicodeType::ASCII) && (pwndView->GetTextType() != UnicodeType::ASCII))
5964 // if this view is in ASCII and the other is not, we have to make sure that
5965 // the text we copy from the other view can actually be saved in ASCII encoding.
5966 // if not, we have to change this views encoding to the same encoding as the other view
5967 BOOL useDefault = FALSE;
5968 WideCharToMultiByte(CP_ACP, WC_NO_BEST_FIT_CHARS, line.sLine, -1, NULL, 0, 0, &useDefault);
5969 if (useDefault) // a default char is required, so the char can not be saved as ASCII
5970 SetTextType(pwndView->GetTextType());
5973 // normal lines is mostly same but may differ in EOL so any copied line change view state to modified
5974 // TODO: check if copied line is same as original one set modified only when differ
5975 SetModified();
5976 SaveUndoStep();
5978 int nRemovedLines = CleanEmptyLines();
5979 SaveUndoStep();
5980 //VerifyEols();
5981 // make sure all non empty line have EOL set but last
5982 // wrong can be last copied line(have eol, but no line under),
5983 // or old last line (line before copied block missing eol, but have line under)
5984 // we'll check all lines to be sure
5985 int nLine = GetViewCount();
5986 // check last line have no EOL set
5987 while (--nLine>=0)
5989 if (!IsViewLineEmpty(nLine))
5991 if (GetViewLineEnding(nLine) != EOL_NOENDING)
5993 // we added non last line into empty block on the end (or should we remove eol from this one ?)
5994 // so next line is empty
5995 ASSERT(IsViewLineEmpty(nLine+1));
5996 // and we can turn it to normal empty line
5997 SetViewData(nLine+1, viewdata(CString(), DIFFSTATE_ADDED, 1, EOL_NOENDING, HIDESTATE_SHOWN));
5999 break;
6002 // check all (nonlast) line have EOL set
6003 while (--nLine>=0)
6005 if (!IsViewLineEmpty(nLine))
6007 if (GetViewLineEnding(nLine) == EOL_NOENDING)
6009 SetViewLineEnding(nLine, m_lineendings);
6010 // in theory there should be only one line needing fix, but most of time we get over all anyway
6011 // break;
6015 SaveUndoStep();
6016 UpdateViewLineNumbers();
6017 SaveUndoStep();
6019 CUndo::GetInstance().EndGrouping();
6021 if (nRemovedLines!=0)
6023 // some lines are gone update selection
6024 ClearSelection();
6025 SetupAllViewSelection(nFirstViewLine, nLastViewLine - nRemovedLines);
6027 BuildAllScreen2ViewVector();
6028 pwndView->Invalidate();
6029 RefreshViews();
6032 void CBaseView::MarkBlock(bool marked, int nFirstViewLine, int nLastViewLine)
6034 if (!IsWritable())
6035 return;
6036 CUndo::GetInstance().BeginGrouping();
6038 for (int viewLine = nFirstViewLine; viewLine <= nLastViewLine; viewLine++)
6039 SetViewMarked(viewLine, marked);
6041 SetModified();
6042 SaveUndoStep();
6043 CUndo::GetInstance().EndGrouping();
6045 BuildAllScreen2ViewVector();
6046 Invalidate();
6047 RefreshViews();
6050 void CBaseView::LeaveOnlyMarkedBlocks(CBaseView *pwndView)
6052 auto fn = [this](int viewLine) -> bool { return GetViewMarked(viewLine) || GetViewState(viewLine) == DIFFSTATE_EDITED; };
6053 UseViewBlock(pwndView, 0, GetViewCount() - 1, fn);
6056 void CBaseView::UseViewFileOfMarked(CBaseView *pwndView)
6058 auto fn = [this](int viewLine) -> bool { return !GetViewMarked(viewLine) || GetViewState(viewLine) == DIFFSTATE_EDITED; };
6059 UseViewBlock(pwndView, 0, GetViewCount() - 1, fn);
6062 void CBaseView::UseViewFileExceptEdited(CBaseView *pwndView)
6064 auto fn = [this](int viewLine) -> bool { return GetViewState(viewLine) == DIFFSTATE_EDITED; };
6065 UseViewBlock(pwndView, 0, GetViewCount() - 1, fn);
6068 int CBaseView::GetIndentCharsForLine(int x, int y)
6070 const int maxGuessLine = 100;
6071 int nTabMode = -1;
6072 CString line = GetViewLine(y);
6073 if (m_nTabMode & TABMODE_SMARTINDENT)
6075 // detect left char and right char
6076 TCHAR lc = x > 0 ? line[x - 1] : '\0';
6077 TCHAR rc = x < line.GetLength() ? line[x] : '\0';
6078 if (lc == ' ' && rc != '\t' || rc == ' ' && lc != '\t')
6079 nTabMode = 1;
6080 if (lc == '\t' && rc != ' ' || rc == '\t' && lc != ' ')
6081 nTabMode = 0;
6082 if (lc == ' ' && rc == '\t' || rc == ' ' && lc == '\t')
6083 nTabMode = m_nTabMode & TABMODE_USESPACES;
6085 // detect lines nearby
6086 for (int i = y - 1, j = y + 1; nTabMode == -1; --i, ++j)
6088 bool above = i > 0 && i >= y - maxGuessLine;
6089 bool below = j < GetViewCount() && j <= y + maxGuessLine;
6090 if (!(above || below))
6091 break;
6092 TCHAR ac = above ? GetViewLine(i)[0] : '\0';
6093 TCHAR bc = below ? GetViewLine(j)[0] : '\0';
6094 if (ac == ' ' && bc != '\t' || bc == ' ' && ac != '\t')
6095 nTabMode = 1;
6096 else if (ac == '\t' && bc != ' ' || bc == '\t' && ac != ' ')
6097 nTabMode = 0;
6098 else if (ac == ' ' && bc == '\t' || bc == ' ' && ac == '\t')
6099 nTabMode = m_nTabMode & TABMODE_USESPACES;
6102 else
6103 nTabMode = m_nTabMode & TABMODE_USESPACES;
6105 if (nTabMode > 0)
6107 // use spaces
6108 x = CountExpandedChars(line, x);
6109 return (m_nTabSize - (x % m_nTabSize));
6112 // use tab
6113 return 0;
6116 void CBaseView::AddIndentationForSelectedBlock()
6118 bool bModified = false;
6119 for (int nViewLine = m_ptSelectionViewPosStart.y; nViewLine <= m_ptSelectionViewPosEnd.y; nViewLine++)
6121 // skip the line if no character is selected in the last selected line
6122 if (nViewLine == m_ptSelectionViewPosEnd.y && m_ptSelectionViewPosEnd.x == 0)
6124 continue;
6126 // skip empty lines
6127 if (IsLineEmpty(nViewLine))
6129 continue;
6131 const CString &sLine = GetViewLine(nViewLine);
6132 CString sTemp = sLine;
6133 if (sTemp.Trim().IsEmpty())
6135 // skip empty and whitechar only lines
6136 continue;
6138 // add tab to line start (alternatively m_nTabSize spaces can be used)
6139 CString tabStr;
6140 int indentChars = GetIndentCharsForLine(0, nViewLine);
6141 tabStr = indentChars > 0 ? CString(_T(' '), indentChars) : _T("\t");
6142 SetViewLine(nViewLine, tabStr + sLine);
6143 bModified = true;
6145 if (bModified)
6147 SetModified();
6148 SaveUndoStep();
6149 BuildAllScreen2ViewVector();
6153 void CBaseView::RemoveIndentationForSelectedBlock()
6155 bool bModified = false;
6156 for (int nViewLine = m_ptSelectionViewPosStart.y; nViewLine <= m_ptSelectionViewPosEnd.y; nViewLine++)
6158 // skip the line if no character is selected in the last selected line
6159 if (nViewLine == m_ptSelectionViewPosEnd.y && m_ptSelectionViewPosEnd.x == 0)
6161 continue;
6163 // skip empty lines
6164 if (IsLineEmpty(nViewLine))
6166 continue;
6168 CString sLine = GetViewLine(nViewLine);
6169 // remove up to n spaces from line start
6170 // and one tab (if less then n spaces was removed)
6171 int nPos = 0;
6172 while (nPos<m_nTabSize)
6174 switch (sLine[nPos])
6176 case ' ':
6177 nPos++;
6178 continue;
6179 case '\t':
6180 nPos++;
6182 break;
6184 if (nPos>0)
6186 sLine.Delete(0, nPos);
6187 SetViewLine(nViewLine, sLine);
6188 bModified = true;
6191 if (bModified)
6193 SetModified();
6194 SaveUndoStep();
6195 BuildAllScreen2ViewVector();
6200 there are two possible versions
6201 - convert tabs to spaces only in front of text (implemented)
6202 - convert all tabs to spaces
6204 void CBaseView::ConvertTabToSpaces()
6206 bool bModified = false;
6207 for (int nViewLine = 0; nViewLine < GetViewCount(); nViewLine++)
6209 if (IsLineEmpty(nViewLine))
6211 continue;
6213 const CString &sLine = GetViewLine(nViewLine);
6214 bool bTabToConvertFound = false;
6215 int nPosIn = 0;
6216 int nPosOut = 0;
6217 while (nPosIn<sLine.GetLength())
6219 switch (sLine[nPosIn])
6221 case ' ':
6222 nPosIn++;
6223 nPosOut++;
6224 continue;
6225 case '\t':
6226 nPosIn++;
6227 bTabToConvertFound = true;
6228 nPosOut = (nPosOut+m_nTabSize) - nPosOut%m_nTabSize;
6229 continue;
6231 break;
6233 if (bTabToConvertFound)
6235 CString sLineNew = sLine;
6236 sLineNew.Delete(0, nPosIn);
6237 sLineNew = CString(' ', nPosOut) + sLineNew;
6238 SetViewLine(nViewLine, sLineNew);
6239 bModified = true;
6242 if (bModified)
6244 SetModified();
6245 SaveUndoStep();
6246 BuildAllScreen2ViewVector();
6251 there are two possible version
6252 - convert spaces to tabs only in front of text (implemented)
6253 - convert all spaces to tabs
6255 void CBaseView::Tabularize()
6257 bool bModified = false;
6258 for (int nViewLine = 0; nViewLine < GetViewCount(); nViewLine++)
6260 if (IsLineEmpty(nViewLine))
6262 continue;
6264 const CString &sLine = GetViewLine(nViewLine);
6265 int nDel = 0;
6266 int nTabCount = 0; // total tabs to be used
6267 int nSpaceCount = 0; // number of spaces in tab size run
6268 int nPos = 0;
6269 while (nPos<sLine.GetLength())
6271 switch (sLine[nPos++])
6273 case ' ':
6274 //bSpace = true;
6275 if (++nSpaceCount < m_nTabSize)
6277 continue;
6279 case '\t':
6280 nTabCount++;
6281 nSpaceCount = 0;
6282 nDel = nPos;
6283 continue;
6285 break;
6287 if (nDel > 0)
6289 CString sLineNew = sLine;
6290 sLineNew.Delete(0, nDel);
6291 sLineNew = CString('\t', nTabCount) + sLineNew;
6292 if (sLine!=sLineNew)
6294 SetViewLine(nViewLine, sLineNew);
6295 bModified = true;
6299 if (bModified)
6301 SetModified();
6302 SaveUndoStep();
6303 BuildAllScreen2ViewVector();
6307 void CBaseView::RemoveTrailWhiteChars()
6309 bool bModified = false;
6310 for (int nViewLine = 0; nViewLine < GetViewCount(); nViewLine++)
6312 if (IsLineEmpty(nViewLine))
6314 continue;
6316 const CString &sLine = GetViewLine(nViewLine);
6317 CString sLineNew = sLine;
6318 sLineNew.TrimRight();
6319 if (sLine.GetLength()!=sLineNew.GetLength())
6321 SetViewLine(nViewLine, sLineNew);
6322 bModified = true;
6325 if (bModified)
6327 SetModified();
6328 SaveUndoStep();
6329 BuildAllScreen2ViewVector();
6333 CBaseView::TWhitecharsProperties CBaseView::GetWhitecharsProperties()
6335 if (GetViewCount()>10000)
6337 // 10k lines is enough to check
6338 TWhitecharsProperties oRet = {true, true, true, true};
6339 return oRet;
6341 TWhitecharsProperties oRet = {};
6342 for (int nViewLine = 0; nViewLine < GetViewCount(); nViewLine++)
6344 if (IsLineEmpty(nViewLine))
6346 continue;
6348 const CString &sLine = GetViewLine(nViewLine);
6349 if (sLine.IsEmpty())
6351 continue;
6353 // check leading whites for convertible tabs and spaces
6354 int nPos = 0;
6355 int nSpaceCount = 0; // number of spaces in tab size run
6356 while (nPos<sLine.GetLength() && (!oRet.HasSpacesToConvert || !oRet.HasTabsToConvert))
6358 switch (sLine[nPos++])
6360 case ' ':
6361 if (++nSpaceCount >= m_nTabSize)
6363 oRet.HasSpacesToConvert = true;
6365 continue;
6366 case '\t':
6367 oRet.HasTabsToConvert = true;
6368 if (nSpaceCount!=0)
6370 oRet.HasSpacesToConvert = true;
6372 continue;
6374 break;
6377 // check trailing whites for removable chars
6378 switch (sLine[sLine.GetLength()-1])
6380 case ' ':
6381 case '\t':
6382 oRet.HasTrailWhiteChars = true;
6385 // check EOLs
6386 EOL eLineEol = GetViewLineEnding(nViewLine);
6387 if (!oRet.HasMixedEols && (eLineEol != m_lineendings) && (eLineEol != EOL_AUTOLINE) && (eLineEol != EOL_NOENDING))
6389 oRet.HasMixedEols = true;
6392 return oRet;
6395 void CBaseView::InsertText(const CString& sText)
6397 ResetUndoStep();
6399 POINT ptCaretViewPos = GetCaretViewPosition();
6400 int nLeft = ptCaretViewPos.x;
6401 int nViewLine = ptCaretViewPos.y;
6403 if ((nViewLine == 0) && (GetViewCount() == 0))
6404 OnChar(VK_RETURN, 0, 0);
6406 std::vector<CString> lines;
6407 int nStart = 0;
6408 int nEolPos = 0;
6409 while ((nEolPos = sText.Find('\r', nEolPos)) >= 0)
6411 CString sLine = sText.Mid(nStart, nEolPos - nStart);
6412 lines.push_back(sLine);
6413 nEolPos++;
6414 nStart = nEolPos;
6416 CString sLine = sText.Mid(nStart);
6417 lines.push_back(sLine);
6419 int nLinesToPaste = (int)lines.size();
6420 if (nLinesToPaste > 1)
6422 // multiline text
6424 // We want to undo the multiline insertion in a single step.
6425 CUndo::GetInstance().BeginGrouping();
6427 sLine = GetViewLineChars(nViewLine);
6428 CString sLineLeft = sLine.Left(nLeft);
6429 CString sLineRight = sLine.Right(sLine.GetLength() - nLeft);
6430 EOL eOriginalEnding = GetViewLineEnding(nViewLine);
6431 viewdata newLine(L"", DIFFSTATE_EDITED, 1, m_lineendings, HIDESTATE_SHOWN);
6432 if (!lines[0].IsEmpty() || !sLineRight.IsEmpty() || (eOriginalEnding != m_lineendings))
6434 newLine.sLine = sLineLeft + lines[0];
6435 SetViewData(nViewLine, newLine);
6438 int nInsertLine = nViewLine;
6439 for (int i = 1; i < nLinesToPaste - 1; i++)
6441 newLine.sLine = lines[i];
6442 InsertViewData(++nInsertLine, newLine);
6444 newLine.sLine = lines[nLinesToPaste - 1] + sLineRight;
6445 newLine.ending = eOriginalEnding;
6446 InsertViewData(++nInsertLine, newLine);
6448 SetModified();
6449 SaveUndoStep();
6451 // adds new lines everywhere except me
6452 if (IsViewGood(m_pwndLeft) && m_pwndLeft != this)
6454 m_pwndLeft->InsertViewEmptyLines(nViewLine + 1, nLinesToPaste - 1);
6456 if (IsViewGood(m_pwndRight) && m_pwndRight != this)
6458 m_pwndRight->InsertViewEmptyLines(nViewLine + 1, nLinesToPaste - 1);
6460 if (IsViewGood(m_pwndBottom) && m_pwndBottom != this)
6462 m_pwndBottom->InsertViewEmptyLines(nViewLine + 1, nLinesToPaste - 1);
6464 SaveUndoStep();
6466 UpdateViewLineNumbers();
6467 CUndo::GetInstance().EndGrouping();
6469 ptCaretViewPos = SetupPoint(lines[nLinesToPaste - 1].GetLength(), nInsertLine);
6471 else
6473 // single line text - just insert it
6474 sLine = GetViewLineChars(nViewLine);
6475 sLine.Insert(nLeft, sText);
6476 ptCaretViewPos = SetupPoint(nLeft + sText.GetLength(), nViewLine);
6477 SetViewLine(nViewLine, sLine);
6478 SetViewState(nViewLine, DIFFSTATE_EDITED);
6479 SetModified();
6480 SaveUndoStep();
6483 RefreshViews();
6484 BuildAllScreen2ViewVector();
6485 UpdateCaretViewPosition(ptCaretViewPos);