Compare commits

...

10 Commits

Binary file not shown.

Binary file not shown.

@ -16,31 +16,31 @@
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
//该cpp文件实现了处理崩溃的类MiniDumper.h
#include <shlwapi.h>
#include "MiniDumper.h"
//消息标题
LPCTSTR msgTitle = TEXT("Notepad++ crash analysis");
MiniDumper::MiniDumper()
{
}
bool MiniDumper::writeDump(EXCEPTION_POINTERS * pExceptionInfo)
//写入崩溃转储的函数
bool MiniDumper::writeDump(EXCEPTION_POINTERS* pExceptionInfo)
{
TCHAR szDumpPath[MAX_PATH];
TCHAR szScratch[MAX_PATH];
LPCTSTR szResult = NULL;
bool retval = false;
//加载动态链接库
HMODULE hDll = ::LoadLibraryEx(TEXT("DBGHELP.DLL"), nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); //that wont work on older windows version than XP, #care :)
if (hDll)
{
MINIDUMPWRITEDUMP pDump = (MINIDUMPWRITEDUMP)::GetProcAddress( hDll, "MiniDumpWriteDump" );
MINIDUMPWRITEDUMP pDump = (MINIDUMPWRITEDUMP)::GetProcAddress(hDll, "MiniDumpWriteDump");
if (pDump)
{
{//获取当前模块的文件路径
::GetModuleFileName(NULL, szDumpPath, MAX_PATH);
::PathRemoveFileSpec(szDumpPath);
wcscat_s(szDumpPath, TEXT("\\NppDump.dmp"));
@ -50,10 +50,10 @@ bool MiniDumper::writeDump(EXCEPTION_POINTERS * pExceptionInfo)
if (msgret == IDYES)
{
// create the file
HANDLE hFile = ::CreateFile( szDumpPath, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL, NULL );
HANDLE hFile = ::CreateFile(szDumpPath, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile!=INVALID_HANDLE_VALUE)
if (hFile != INVALID_HANDLE_VALUE)
{
_MINIDUMP_EXCEPTION_INFORMATION ExInfo{};
@ -62,23 +62,23 @@ bool MiniDumper::writeDump(EXCEPTION_POINTERS * pExceptionInfo)
ExInfo.ClientPointers = FALSE;
// write the dump
BOOL bOK = pDump( GetCurrentProcess(), GetCurrentProcessId(), hFile, MiniDumpNormal, &ExInfo, NULL, NULL );
BOOL bOK = pDump(GetCurrentProcess(), GetCurrentProcessId(), hFile, MiniDumpNormal, &ExInfo, NULL, NULL);
if (bOK)
{
wsprintf( szScratch, TEXT("Saved dump file to '%s'"), szDumpPath );
wsprintf(szScratch, TEXT("Saved dump file to '%s'"), szDumpPath);
szResult = szScratch;
retval = true;
}
else
{
wsprintf( szScratch, TEXT("Failed to save dump file to '%s' (error %d)"), szDumpPath, GetLastError() );
wsprintf(szScratch, TEXT("Failed to save dump file to '%s' (error %d)"), szDumpPath, GetLastError());
szResult = szScratch;
}
::CloseHandle(hFile);
}
else
{
wsprintf( szScratch, TEXT("Failed to create dump file '%s' (error %d)"), szDumpPath, GetLastError() );
wsprintf(szScratch, TEXT("Failed to create dump file '%s' (error %d)"), szDumpPath, GetLastError());
szResult = szScratch;
}
}
@ -93,7 +93,7 @@ bool MiniDumper::writeDump(EXCEPTION_POINTERS * pExceptionInfo)
{
szResult = TEXT("Unable to load the debugging DLL,\r\nfind a recent copy of dbghelp.dll and install it.");
}
//弹出消息框显示结果
if (szResult)
::MessageBox(NULL, szResult, msgTitle, MB_OK);

@ -1560,13 +1560,17 @@ namespace NppDarkMode
return DefSubclassProc(hWnd, uMsg, wParam, lParam);
}
//窗口子类化的示例,它为指定的窗口处理了自定义的边框绘制逻辑。
void subclassTabControl(HWND hwnd)
{
SetWindowSubclass(hwnd, TabSubclass, g_tabSubclassID, 0);
SetWindowSubclass(hwnd, TabSubclass, g_tabSubclassID, 0); //将窗口 hwnd 子类化为 TabSubclass并分配一个唯一的子类 ID g_tabSubclassID。
}
constexpr UINT_PTR g_customBorderSubclassID = 42;
//这个函数是一个回调函数,用于处理窗口消息。它被用作窗口子类的回调函数。
//当窗口接收到消息时,该函数会被调用来处理消息。
//注意,该函数的签名必须与 SUBCLASSPROC 类型匹配。
LRESULT CALLBACK CustomBorderSubclass(
HWND hWnd,
UINT uMsg,
@ -1580,6 +1584,9 @@ namespace NppDarkMode
static bool isHotStatic = false;
//在这个函数中,根据不同的消息类型进行不同的处理。
//其中WM_NCPAINT 消息用于非客户区绘制,即窗口的边框绘制。
//在这里,通过重绘窗口的边框,实现了自定义的边框绘制效果。
switch (uMsg)
{
case WM_NCPAINT:
@ -1635,19 +1642,25 @@ namespace NppDarkMode
return 0;
}
break;
//以上部分代码使用 GetWindowDC 函数获取窗口的设备上下文,然后根据窗口的样式和状态计算绘制边框所需的相关信息。
//通过调用 NppDarkMode::paintRoundFrameRect 函数来绘制圆角矩形边框,使用不同的画笔来绘制不同的边框样式。
//绘制完成后,通过 ReleaseDC 函数释放设备上下文。最后,返回值为 0表示消息已经被处理完毕。
case WM_NCCALCSIZE:
{
if (!NppDarkMode::isEnabled())
if (!NppDarkMode::isEnabled()) //检查是否启用了 NppDarkMode如果没有启用则直接跳过。
{
break;
}
auto lpRect = reinterpret_cast<LPRECT>(lParam);
::InflateRect(lpRect, -(::GetSystemMetrics(SM_CXEDGE)), -(::GetSystemMetrics(SM_CYEDGE)));
auto lpRect = reinterpret_cast<LPRECT>(lParam); //通过将 lParam 强制转换为 LPRECT 类型,获取指向窗口矩形结构的指针。
::InflateRect(lpRect, -(::GetSystemMetrics(SM_CXEDGE)), -(::GetSystemMetrics(SM_CYEDGE))); //利用 InflateRect 函数扩展客户区矩形的尺寸,将其减去窗口边框的宽度和高度(使用 SM_CXEDGE 和 SM_CYEDGE 系统度量值)。这样可以得到去除边框后的客户区矩形。
auto style = ::GetWindowLongPtr(hWnd, GWL_STYLE);
bool hasVerScrollbar = (style & WS_VSCROLL) == WS_VSCROLL;
//根据窗口的样式,检查是否有垂直和水平滚动条。如果有垂直滚动条,则将客户区矩形的右边减去垂直滚动条的宽度(使用 SM_CXVSCROLL 系统度量值)。
//如果有水平滚动条,则将客户区矩形的底部减去水平滚动条的高度(使用 SM_CYHSCROLL 系统度量值)。
if (hasVerScrollbar)
{
lpRect->right -= ::GetSystemMetrics(SM_CXVSCROLL);
@ -1659,10 +1672,14 @@ namespace NppDarkMode
lpRect->bottom -= ::GetSystemMetrics(SM_CYHSCROLL);
}
return 0;
return 0; //返回值为 0表示已经处理完 WM_NCCALCSIZE 消息。
}
break;
//在这个代码块中,首先检查是否启用了 NppDarkMode如果没有启用则直接跳过。
//然后,通过调用 GetFocus 函数检查窗口是否具有焦点,如果有焦点则跳过。
//接下来,创建一个 TRACKMOUSEEVENT 结构体,并设置其中的成员变量。这个结构体用于跟踪鼠标离开窗口的消息。通过调用 TrackMouseEvent 函数,将该结构体传递给系统,以便在鼠标离开窗口时收到 WM_MOUSELEAVE 消息。
//然后,检查 isHotStatic 变量的值。如果它为假,则将其设置为真,并通过调用 SetWindowPos 函数更新窗口的位置和大小。这里使用了 SWP_NOMOVE、SWP_NOSIZE 和 SWP_NOZORDER 标志,表示不改变窗口的位置、大小和层次关系,只刷新窗口的边框样式(使用 SWP_FRAMECHANGED 标志)。
case WM_MOUSEMOVE:
{
if (!NppDarkMode::isEnabled())
@ -1690,6 +1707,10 @@ namespace NppDarkMode
}
break;
//在这个代码块中,首先检查是否启用了 NppDarkMode如果没有启用则直接跳过。
//然后,检查 isHotStatic 变量的值。如果它为真,则将其设置为假,并通过调用 SetWindowPos 函数更新窗口的位置和大小。
//接下来,同样创建一个 TRACKMOUSEEVENT 结构体,并设置其中的成员变量。
//然后,通过调用 TrackMouseEvent 函数,取消对鼠标离开窗口的跟踪,并清除鼠标悬停时间。
case WM_MOUSELEAVE:
{
if (!NppDarkMode::isEnabled())
@ -1714,20 +1735,21 @@ namespace NppDarkMode
case WM_NCDESTROY:
{
RemoveWindowSubclass(hWnd, CustomBorderSubclass, uIdSubclass);
RemoveWindowSubclass(hWnd, CustomBorderSubclass, uIdSubclass); //调用 RemoveWindowSubclass 函数,将窗口子类移除,以确保在窗口销毁时不再收到自定义边框的消息。
}
break;
}
return DefSubclassProc(hWnd, uMsg, wParam, lParam);
return DefSubclassProc(hWnd, uMsg, wParam, lParam); //通过调用 DefSubclassProc 函数,将消息传递给默认的窗口过程进行处理。
}
void subclassCustomBorderForListBoxAndEditControls(HWND hwnd)
void subclassCustomBorderForListBoxAndEditControls(HWND hwnd) //hwnd为要进行子类化的窗口句柄。
{
SetWindowSubclass(hwnd, CustomBorderSubclass, g_customBorderSubclassID, 0);
}
constexpr UINT_PTR g_comboBoxSubclassID = 42;
constexpr UINT_PTR g_comboBoxSubclassID = 42; //标识子类化的ID
//子类函数 ComboBoxSubclass它是一个回调函数用于处理窗口消息。
LRESULT CALLBACK ComboBoxSubclass(
HWND hWnd,
UINT uMsg,
@ -1736,6 +1758,7 @@ namespace NppDarkMode
UINT_PTR uIdSubclass,
DWORD_PTR dwRefData
)
{
auto hwndEdit = reinterpret_cast<HWND>(dwRefData);
@ -1747,25 +1770,32 @@ namespace NppDarkMode
{
break;
}
//定义一个名为 rc 的 RECT 结构体,并使用 ::GetClientRect 函数获取窗口客户区的矩形区域信息。
RECT rc{};
::GetClientRect(hWnd, &rc);
//定义一个名为 ps 的 PAINTSTRUCT 结构体,并调用 ::BeginPaint 函数开始绘制操作,将得到的设备上下文句柄保存在 hdc 变量中。
PAINTSTRUCT ps{};
auto hdc = ::BeginPaint(hWnd, &ps);
//选择关联字体
::SelectObject(hdc, reinterpret_cast<HFONT>(::SendMessage(hWnd, WM_GETFONT, 0, 0)));
::SetBkColor(hdc, NppDarkMode::getBackgroundColor());
auto holdBrush = ::SelectObject(hdc, NppDarkMode::getDarkerBackgroundBrush());
auto& dpiManager = NppParameters::getInstance()._dpiManager;
//定义一个名为 rcArrow 的 RECT 结构体变量,用于存储组合框箭头的位置和尺寸信息。
RECT rcArrow{};
//定义一个名为 cbi 的 COMBOBOXINFO 结构体,并设置其 cbSize 成员为结构体的大小。
//然后通过调用 ::GetComboBoxInfo 函数获取与指定组合框窗口相关的信息,并将结果存储在 cbi 变量中。
COMBOBOXINFO cbi{};
cbi.cbSize = sizeof(COMBOBOXINFO);
const bool resultCbi = ::GetComboBoxInfo(hWnd, &cbi) != FALSE;
//根据获取到的组合框信息或者客户区的尺寸,动态地确定箭头区域的位置和尺寸
if (resultCbi)
{
rcArrow = cbi.rcButton;
@ -1779,12 +1809,16 @@ namespace NppDarkMode
};
}
bool hasFocus = false;
bool hasFocus = false; //定义了一个 hasFocus 变量,并且获取了窗口是否启用的状态。
const bool isWindowEnabled = ::IsWindowEnabled(hWnd) == TRUE;
// CBS_DROPDOWN text is handled by parent by WM_CTLCOLOREDIT
auto style = ::GetWindowLongPtr(hWnd, GWL_STYLE);
//如果组合框是下拉列表框CBS_DROPDOWNLIST则根据获取到的组合框信息或者客户区的尺寸确定文本背景的矩形区域 rcTextBg并使用 FillRect 函数擦除文本背景。
//然后根据当前选中的项来设置文本颜色和背景颜色,并绘制文本到指定的位置上。
//最后,如果组合框有焦点且未展开下拉列表,则使用 DrawFocusRect 函数绘制焦点矩形框。
if ((style & CBS_DROPDOWNLIST) == CBS_DROPDOWNLIST)
{
hasFocus = ::GetFocus() == hWnd;
@ -1828,6 +1862,8 @@ namespace NppDarkMode
::DrawFocusRect(hdc, &rcTextBg);
}
}
//如果组合框是可编辑的下拉框CBS_DROPDOWN则判断编辑框是否拥有焦点并根据情况设置 hasFocus 变量的值。
else if ((style & CBS_DROPDOWN) == CBS_DROPDOWN && hwndEdit != nullptr)
{
hasFocus = ::GetFocus() == hwndEdit;
@ -1852,10 +1888,10 @@ namespace NppDarkMode
auto holdPen = static_cast<HPEN>(::SelectObject(hdc, hSelectedPen));
POINT edge[] = {
{rcArrow.left - 1, rcArrow.top},
{rcArrow.left - 1, rcArrow.bottom}
{rcArrow.left - 1, rcArrow.top}, //箭头区域左侧顶部
{rcArrow.left - 1, rcArrow.bottom} //箭头区域左侧底部
};
::Polyline(hdc, edge, _countof(edge));
::Polyline(hdc, edge, _countof(edge)); //绘制连线(边框线)
int roundCornerValue = NppDarkMode::isWindows11() ? dpiManager.scaleX(4) : 0;
NppDarkMode::paintRoundFrameRect(hdc, rc, hSelectedPen, roundCornerValue, roundCornerValue);
@ -1875,7 +1911,10 @@ namespace NppDarkMode
}
return DefSubclassProc(hWnd, uMsg, wParam, lParam);
}
// 以上代码用于自定义列表框和编辑控件的边框和外观,通过调用 SetWindowSubclass 函数将子类函数与窗口句柄关联起来,实现自定义的绘制效果。
//给组合框控件设置子类化
void subclassComboBoxControl(HWND hwnd)
{
DWORD_PTR hwndEditData = 0;

@ -20,11 +20,11 @@
#include "Common.h" // for generic_string
namespace NppDarkMode
namespace NppDarkMode //命名空间NppDarkMode
{
struct Colors
struct Colors //Colors颜色结构体
{
COLORREF background = 0;
COLORREF background = 0; //COLORREF 是一个 32-bit 整型数值,它代表了一种颜色。
COLORREF softerBackground = 0;
COLORREF hotBackground = 0;
COLORREF pureBackground = 0;
@ -38,30 +38,30 @@ namespace NppDarkMode
COLORREF disabledEdge = 0;
};
struct Options
struct Options //Options选项结构体
{
bool enable = false;
bool enableMenubar = false;
bool enablePlugin = false;
};
struct NppDarkModeParams
struct NppDarkModeParams //params参数结构体
{
const wchar_t* _themeClassName = nullptr;
bool _subclass = false;
bool _theme = false;
};
enum class ToolTipsType
enum class ToolTipsType //域内枚举类型为ToolTipsType
{
tooltip,
tooltip, //括号里是常量
toolbar,
listview,
treeview,
tabbar
};
enum ColorTone {
enum ColorTone { //色温
blackTone = 0,
redTone = 1,
greenTone = 2,
@ -72,14 +72,14 @@ namespace NppDarkMode
customizedTone = 32
};
enum class TreeViewStyle
enum class TreeViewStyle //风格
{
classic = 0,
light = 1,
dark = 2
};
struct AdvOptDefaults
struct AdvOptDefaults //默认选项
{
generic_string _xmlFileName;
int _toolBarIconSet = -1;
@ -87,7 +87,7 @@ namespace NppDarkMode
bool _tabUseTheme = false;
};
struct AdvancedOptions
struct AdvancedOptions //高级选项
{
bool _enableWindowsMode = false;
@ -108,7 +108,7 @@ namespace NppDarkMode
bool isWindowsModeEnabled();
void setWindowsMode(bool enable);
generic_string getThemeName();
generic_string getThemeName(); //generic_string 类
void setThemeName(const generic_string& newThemeName);
int getToolBarIconSet(bool useDark);
void setToolBarIconSet(int state2Set, bool useDark);
@ -119,7 +119,7 @@ namespace NppDarkMode
bool isWindows10();
bool isWindows11();
DWORD getWindowsBuildNumber();
DWORD getWindowsBuildNumber(); //DWORD 就是 Double Word 每个word为2个字节的长度DWORD 双字即为4个字节每个字节是8位共32位。
COLORREF invertLightness(COLORREF c);
COLORREF invertLightnessSofter(COLORREF c);
@ -142,7 +142,7 @@ namespace NppDarkMode
COLORREF getHotEdgeColor();
COLORREF getDisabledEdgeColor();
HBRUSH getBackgroundBrush();
HBRUSH getBackgroundBrush(); //HBRUSH 取画刷
HBRUSH getDarkerBackgroundBrush();
HBRUSH getSofterBackgroundBrush();
HBRUSH getHotBackgroundBrush();
@ -152,7 +152,7 @@ namespace NppDarkMode
HBRUSH getHotEdgeBrush();
HBRUSH getDisabledEdgeBrush();
HPEN getDarkerTextPen();
HPEN getDarkerTextPen(); //画笔
HPEN getEdgePen();
HPEN getHotEdgePen();
HPEN getDisabledEdgePen();
@ -175,12 +175,12 @@ namespace NppDarkMode
Colors getDarkModeDefaultColors();
void changeCustomTheme(const Colors& colors);
// handle events
// handle events 处理事件
void handleSettingChange(HWND hwnd, LPARAM lParam, bool isFromBtn = false);
bool isDarkModeReg();
// processes messages related to UAH / custom menubar drawing.
// return true if handled, false to continue with normal processing in your wndproc
// processes messages related to UAH / custom menubar drawing. 处理相关信息
// return true if handled, false to continue with normal processing in your wndproc 解决了返回true否则false继续处理
bool runUAHWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam, LRESULT* lr);
void drawUAHMenuNCBottomLine(HWND hWnd);
@ -191,7 +191,7 @@ namespace NppDarkMode
bool allowDarkModeForWindow(HWND hWnd, bool allow);
void setTitleBarThemeColor(HWND hWnd);
// enhancements to DarkMode.h
// enhancements to DarkMode.h 对于DarkMode.h的改进
void enableDarkScrollBarForWindowAndChildren(HWND hwnd);
inline void paintRoundFrameRect(HDC hdc, const RECT rect, const HPEN hpen, int width = 0, int height = 0);
@ -235,13 +235,13 @@ namespace NppDarkMode
bool isThemeDark();
void setBorder(HWND hwnd, bool border = true);
BOOL CALLBACK enumAutocompleteProc(HWND hwnd, LPARAM lParam);
BOOL CALLBACK enumAutocompleteProc(HWND hwnd, LPARAM lParam); //Windows API中的回调函数用于枚举自动完成列表中的项。HWND hwnd自动完成列表的窗口句柄。 LPARAM lParam用户定义的附加参数。
void setDarkAutoCompletion();
LRESULT onCtlColor(HDC hdc);
LRESULT onCtlColor(HDC hdc); //LRESULT是一个数据类型指的是从窗口程序或者回调函数返回的32位值
LRESULT onCtlColorSofter(HDC hdc);
LRESULT onCtlColorDarker(HDC hdc);
LRESULT onCtlColorError(HDC hdc);
LRESULT onCtlColorDarkerBGStaticText(HDC hdc, bool isTextEnabled);
INT_PTR onCtlColorListbox(WPARAM wParam, LPARAM lParam);
INT_PTR onCtlColorListbox(WPARAM wParam, LPARAM lParam); //INT_PTR是特殊定义的类型是为了解决32位与64位编译器的兼容性而设置的关键字
}

@ -25,14 +25,14 @@
bool DocTabView::_hideTabBarStatus = false;
//向标签视图添加新的缓冲区,首先检查缓冲区是否有效(不是无效的缓冲区),然后检查是否已经存在相同的缓冲区。如果缓冲区有效且尚未存在,则将其添加到标签页视图中,并更新父窗口的大小。
void DocTabView::addBuffer(BufferID buffer)
{
if (buffer == BUFFER_INVALID) //valid only
return;
if (getIndexByBuffer(buffer) != -1) //no duplicates
return;
Buffer * buf = MainFileManager.getBufferByID(buffer);
Buffer* buf = MainFileManager.getBufferByID(buffer);
TCITEM tie{};
tie.mask = TCIF_TEXT | TCIF_IMAGE | TCIF_PARAM;
@ -40,7 +40,7 @@ void DocTabView::addBuffer(BufferID buffer)
if (_hasImgLst)
index = 0;
tie.iImage = index;
tie.pszText = const_cast<TCHAR *>(buf->getFileName());
tie.pszText = const_cast<TCHAR*>(buf->getFileName());
tie.lParam = reinterpret_cast<LPARAM>(buffer);
::SendMessage(_hSelf, TCM_INSERTITEM, _nbItem++, reinterpret_cast<LPARAM>(&tie));
bufferUpdated(buf, BufferChangeMask);
@ -48,25 +48,25 @@ void DocTabView::addBuffer(BufferID buffer)
::SendMessage(_hParent, WM_SIZE, 0, 0);
}
//关闭指定的缓冲区,到要关闭的缓冲区的索引,然后从标签页视图中删除它,并通知父窗口进行调整。
void DocTabView::closeBuffer(BufferID buffer)
{
int indexToClose = getIndexByBuffer(buffer);
deletItemAt((size_t)indexToClose);
::SendMessage(_hParent, WM_SIZE, 0, 0);
}
//为特定的标签设置颜色。根据提供的缓冲区ID设置该缓冲区在标签页中的颜色。
void DocTabView::setIndividualTabColour(BufferID bufferId, int colorId)
{
bufferId->setDocColorId(colorId);
}
//获取特定标签的颜色,根据提供的标签索引,返回该标签的颜色。
int DocTabView::getIndividualTabColour(int tabIndex)
{
BufferID bufferId = getBufferByIndex(tabIndex);
return bufferId->getDocColorId();
}
//激活特定的缓冲区通过缓冲区的ID找到其索引位置并尝试激活该缓冲区如果成功则返回true否则返回false。
bool DocTabView::activateBuffer(BufferID buffer)
{
int indexToActivate = getIndexByBuffer(buffer);
@ -77,15 +77,15 @@ bool DocTabView::activateBuffer(BufferID buffer)
return true;
}
//获取当前激活的缓冲区。
BufferID DocTabView::activeBuffer()
{
int index = getCurrentTabIndex();
return getBufferByIndex(index);
}
BufferID DocTabView::findBufferByName(const TCHAR * fullfilename) //-1 if not found, something else otherwise
//遍历所有标签页根据文件名查找匹配的缓冲区找到则返回其ID否则返回BUFFER_INVALID。
BufferID DocTabView::findBufferByName(const TCHAR* fullfilename) //-1 if not found, something else otherwise
{
TCITEM tie{};
tie.lParam = -1;
@ -94,7 +94,7 @@ BufferID DocTabView::findBufferByName(const TCHAR * fullfilename) //-1 if not fo
{
::SendMessage(_hSelf, TCM_GETITEM, i, reinterpret_cast<LPARAM>(&tie));
BufferID id = reinterpret_cast<BufferID>(tie.lParam);
Buffer * buf = MainFileManager.getBufferByID(id);
Buffer* buf = MainFileManager.getBufferByID(id);
if (OrdinalIgnoreCaseCompareStrings(fullfilename, buf->getFullPathName()) == 0)
{
return id;
@ -103,7 +103,7 @@ BufferID DocTabView::findBufferByName(const TCHAR * fullfilename) //-1 if not fo
return BUFFER_INVALID;
}
//通过缓冲区ID找到其在标签中的索引位置如果不存在则返回 - 1。
int DocTabView::getIndexByBuffer(BufferID id)
{
TCITEM tie{};
@ -118,7 +118,7 @@ int DocTabView::getIndexByBuffer(BufferID id)
return -1;
}
//通过缓冲区ID找到其在标签中的索引位置如果不存在则返回-1。
BufferID DocTabView::getBufferByIndex(size_t index)
{
TCITEM tie{};
@ -129,8 +129,8 @@ BufferID DocTabView::getBufferByIndex(size_t index)
return reinterpret_cast<BufferID>(tie.lParam);
}
void DocTabView::bufferUpdated(Buffer * buffer, int mask)
//根据mask中的标志位更新与缓冲区相关的信息例如文件名变化、只读状态变化等。
void DocTabView::bufferUpdated(Buffer* buffer, int mask)
{
int index = getIndexByBuffer(buffer->getID());
if (index == -1)
@ -143,7 +143,7 @@ void DocTabView::bufferUpdated(Buffer * buffer, int mask)
if (mask & BufferChangeReadonly || mask & BufferChangeDirty)
{
tie.mask |= TCIF_IMAGE;
tie.iImage = buffer->isDirty()?UNSAVED_IMG_INDEX:SAVED_IMG_INDEX;
tie.iImage = buffer->isDirty() ? UNSAVED_IMG_INDEX : SAVED_IMG_INDEX;
if (buffer->isMonitoringOn())
{
tie.iImage = MONITORING_IMG_INDEX;
@ -171,15 +171,15 @@ void DocTabView::bufferUpdated(Buffer * buffer, int mask)
//Tab's caption must be encoded like this because otherwise tab control would make tab too small or too big for the text.
while (*in != 0)
if (*in == '&')
{
*out++ = '&';
*out++ = '&';
while (*(++in) == '&')
if (*in == '&')
{
*out++ = '&';
}
else
*out++ = *in++;
*out++ = '&';
while (*(++in) == '&')
*out++ = '&';
}
else
*out++ = *in++;
*out = '\0';
}
}
@ -192,7 +192,7 @@ void DocTabView::bufferUpdated(Buffer * buffer, int mask)
::SendMessage(_hParent, WM_SIZE, 0, 0);
}
//根据给定的索引设置相应的缓冲区ID并更新标签显示的相关信息。
void DocTabView::setBuffer(size_t index, BufferID id)
{
if (index >= _nbItem)
@ -208,8 +208,8 @@ void DocTabView::setBuffer(size_t index, BufferID id)
::SendMessage(_hParent, WM_SIZE, 0, 0);
}
void DocTabView::reSizeTo(RECT & rc)
//根据隐藏/显示标签栏状态,调整标签页视图和文本编辑器视图的大小,并根据需要发送消息以更新可点击链接。
void DocTabView::reSizeTo(RECT& rc)
{
int borderWidth = ((NppParameters::getInstance()).getSVP())._borderWidth;
if (_hideTabBarStatus)
@ -221,9 +221,9 @@ void DocTabView::reSizeTo(RECT & rc)
else
{
TabBar::reSizeTo(rc);
rc.left += borderWidth;
rc.left += borderWidth;
rc.right -= borderWidth * 2;
rc.top += borderWidth;
rc.top += borderWidth;
rc.bottom -= (borderWidth * 2);
_pView->reSizeTo(rc);
}

@ -14,11 +14,15 @@
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
//该类继承自TabBarPlus类。该类负责管理文档选项卡视图并提供一系列方法用于添加、关闭、激活缓冲区以及设置选项卡的个性化选项等功能。
#pragma once
#include "TabBar.h"
#include "Buffer.h"
// 定义一些常量用作图片索引
const int SAVED_IMG_INDEX = 0;
const int UNSAVED_IMG_INDEX = 1;
const int REDONLY_IMG_INDEX = 2;
@ -26,15 +30,15 @@ const int MONITORING_IMG_INDEX = 3;
class DocTabView : public TabBarPlus
{
public :
DocTabView():TabBarPlus(), _pView(NULL) {};
virtual ~DocTabView(){};
public:
DocTabView() :TabBarPlus(), _pView(NULL) {};
virtual ~DocTabView() {};
void destroy() override {
TabBarPlus::destroy();
};
void init(HINSTANCE hInst, HWND parent, ScintillaEditView * pView, std::vector<IconList *> pIconListVector, unsigned char indexChoice) {
//初始化函数传入实例句柄、父窗口句柄、ScintillaEditView指针、以及图片列表和选择的图片索引
void init(HINSTANCE hInst, HWND parent, ScintillaEditView* pView, std::vector<IconList*> pIconListVector, unsigned char indexChoice) {
TabBarPlus::init(hInst, parent);
_pView = pView;
@ -52,51 +56,56 @@ public :
TabBar::setImageList(_pIconListVector[_iconListIndexChoice]->getHandle());
return;
};
// 改变选中的图片列表
void changeIcons(unsigned char choice) {
if (choice >= _pIconListVector.size())
return;
_iconListIndexChoice = choice;
TabBar::setImageList(_pIconListVector[_iconListIndexChoice]->getHandle());
};
// 添加缓冲区
void addBuffer(BufferID buffer);
// 关闭缓冲区
void closeBuffer(BufferID buffer);
void bufferUpdated(Buffer * buffer, int mask);
// 缓冲区更新
void bufferUpdated(Buffer* buffer, int mask);
// 激活缓冲区
bool activateBuffer(BufferID buffer);
// 获取当前激活的缓冲区
BufferID activeBuffer();
BufferID findBufferByName(const TCHAR * fullfilename); //-1 if not found, something else otherwise
// 根据文件名查找缓冲区,返回索引值,如果未找到则返回-1
BufferID findBufferByName(const TCHAR* fullfilename); //-1 if not found, something else otherwise
// 根据缓冲区获取索引值
int getIndexByBuffer(BufferID id);
// 根据索引值获取缓冲区
BufferID getBufferByIndex(size_t index);
// 设置指定索引位置的缓冲区
void setBuffer(size_t index, BufferID id);
// 静态函数,用于设置隐藏或显示选项卡栏的状态
static bool setHideTabBarStatus(bool hideOrNot) {
bool temp = _hideTabBarStatus;
_hideTabBarStatus = hideOrNot;
return temp;
};
// 静态函数,获取隐藏或显示选项卡栏的状态
static bool getHideTabBarStatus() {
return _hideTabBarStatus;
};
void reSizeTo(RECT & rc) override;
// 重写父类的reSizeTo方法
void reSizeTo(RECT& rc) override;
// 获取ScintillaEditView指针
const ScintillaEditView* getScintillaEditView() const {
return _pView;
};
// 设置指定缓冲区的个性化选项卡颜色
void setIndividualTabColour(BufferID bufferId, int colorId);
// 获取指定索引位置的个性化选项卡颜色
int getIndividualTabColour(int tabIndex) override;
private :
ScintillaEditView *_pView = nullptr;
private:
ScintillaEditView* _pView = nullptr;
static bool _hideTabBarStatus;
std::vector<IconList *> _pIconListVector;
std::vector<IconList*> _pIconListVector;
int _iconListIndexChoice = -1;
};

@ -23,6 +23,9 @@
#include "Common.h"
#include "Utf8.h"
```cpp
using namespace std;
FindOption * FindReplaceDlg::_env;
@ -35,12 +38,15 @@ void addText2Combo(const TCHAR * txt2add, HWND hCombo)
if (!hCombo) return;
if (!lstrcmp(txt2add, TEXT(""))) return;
// 在组合框中查找是否已存在相同的文本
auto i = ::SendMessage(hCombo, CB_FINDSTRINGEXACT, static_cast<WPARAM>(-1), reinterpret_cast<LPARAM>(txt2add));
if (i != CB_ERR) // found
if (i != CB_ERR) // 找到了相同的文本
{
// 删除已存在的文本
::SendMessage(hCombo, CB_DELETESTRING, i, 0);
}
// 向组合框中插入新的文本,并设置为当前选中项
i = ::SendMessage(hCombo, CB_INSERTSTRING, 0, reinterpret_cast<LPARAM>(txt2add));
::SendMessage(hCombo, CB_SETCURSEL, i, 0);
}
@ -59,6 +65,8 @@ void delLeftWordInEdit(HWND hEdit)
WORD cursor = 0;
::SendMessage(hEdit, EM_GETSEL, (WPARAM)&cursor, 0);
WORD wordstart = cursor;
// 删除光标左边的单词
while (wordstart > 0) {
TCHAR c = str[wordstart - 1];
if (c != ' ' && c != '\t')
@ -83,6 +91,7 @@ LRESULT run_swapButtonProc(WNDPROC oldEditProc, HWND hwnd, UINT message, WPARAM
{
case WM_RBUTTONUP:
{
// 模拟右键点击事件,发送给父窗口处理
::SendMessage(GetParent(hwnd), message, wParam, lParam);
break;
}
@ -94,19 +103,22 @@ LRESULT run_swapButtonProc(WNDPROC oldEditProc, HWND hwnd, UINT message, WPARAM
}
int Searching::convertExtendedToString(const TCHAR * query, TCHAR * result, int length)
{ //query may equal to result, since it always gets smaller
{
// 将扩展的字符串转换为普通字符串
int i = 0, j = 0;
int charLeft = length;
TCHAR current;
while (i < length)
{ //because the backslash escape quences always reduce the size of the generic_string, no overflow checks have to be made for target, assuming parameters are correct
{
current = query[i];
--charLeft;
if (current == '\\' && charLeft)
{ //possible escape sequence
{
++i;
--charLeft;
current = query[i];
switch(current)
{
case 'r':
@ -131,24 +143,26 @@ int Searching::convertExtendedToString(const TCHAR * query, TCHAR * result, int
case 'u':
{
int size = 0, base = 0;
// 根据转义序列的类型设置不同的大小和进制
if (current == 'b')
{ //11111111
{
size = 8, base = 2;
}
else if (current == 'o')
{ //377
{
size = 3, base = 8;
}
else if (current == 'd')
{ //255
{
size = 3, base = 10;
}
else if (current == 'x')
{ //0xFF
{
size = 2, base = 16;
}
else if (current == 'u')
{ //0xCDCD
{
size = 4, base = 16;
}
@ -162,12 +176,14 @@ int Searching::convertExtendedToString(const TCHAR * query, TCHAR * result, int
break;
}
}
//not enough chars to make parameter, use default method as fallback
// 字符不足以构成参数,则使用默认方法作为备选方案
[[fallthrough]];
}
default:
{ //unknown sequence, treat as regular text
{
// 未知序列,当做普通文本处理
result[j] = '\\';
++j;
result[j] = current;
@ -182,6 +198,7 @@ int Searching::convertExtendedToString(const TCHAR * query, TCHAR * result, int
++i;
++j;
}
result[j] = 0;
return j;
}
@ -195,6 +212,7 @@ bool Searching::readBase(const TCHAR * str, int * value, int base, int size)
while (i < size)
{
current = str[i];
if (current >= 'A')
{
current &= 0xdf;
@ -220,105 +238,110 @@ bool Searching::readBase(const TCHAR * str, int * value, int base, int size)
void Searching::displaySectionCentered(size_t posStart, size_t posEnd, ScintillaEditView * pEditView, bool isDownwards)
{
// Make sure target lines are unfolded
// 确保目标行未折叠
pEditView->execute(SCI_ENSUREVISIBLE, pEditView->execute(SCI_LINEFROMPOSITION, posStart));
pEditView->execute(SCI_ENSUREVISIBLE, pEditView->execute(SCI_LINEFROMPOSITION, posEnd));
// Jump-scroll to center, if current position is out of view
// 跳转滚动到居中位置,如果当前位置不可见
pEditView->execute(SCI_SETVISIBLEPOLICY, CARET_JUMPS | CARET_EVEN);
pEditView->execute(SCI_ENSUREVISIBLEENFORCEPOLICY, pEditView->execute(SCI_LINEFROMPOSITION, isDownwards ? posEnd : posStart));
// When searching up, the beginning of the (possible multiline) result is important, when scrolling down the end
// 当向上搜索时,重要的是结果的开头,当向下滚动时是结果的结尾
pEditView->execute(SCI_GOTOPOS, isDownwards ? posEnd : posStart);
pEditView->execute(SCI_SETVISIBLEPOLICY, CARET_EVEN);
pEditView->execute(SCI_ENSUREVISIBLEENFORCEPOLICY, pEditView->execute(SCI_LINEFROMPOSITION, isDownwards ? posEnd : posStart));
// Adjust so that we see the entire match; primarily horizontally
// 调整使得能够看到完整的匹配;主要是水平方向的调整
pEditView->execute(SCI_SCROLLRANGE, posStart, posEnd);
// Move cursor to end of result and select result
// 将光标移到结果的末尾并选中结果
pEditView->execute(SCI_GOTOPOS, posEnd);
pEditView->execute(SCI_SETANCHOR, posStart);
// Update Scintilla's knowledge about what column the caret is in, so that if user
// does up/down arrow as first navigation after the search result is selected,
// the caret doesn't jump to an unexpected column
// 更新 Scintilla 中光标所在列的位置信息,以防用户在选择搜索结果后使用上下箭头导航时光标跳到意外的列
pEditView->execute(SCI_CHOOSECARETX);
}
WNDPROC FindReplaceDlg::originalFinderProc = nullptr;
WNDPROC FindReplaceDlg::originalComboEditProc = nullptr;
```
// important : to activate all styles
const int STYLING_MASK = 255;
```cpp
// 定义 FindReplaceDlg 类的析构函数
FindReplaceDlg::~FindReplaceDlg()
{
_tab.destroy();
delete _pFinder;
_tab.destroy(); // 销毁标签页控件
delete _pFinder; // 删除查找对象指针
// 删除与查找对象相关的所有查找器对象
for (int n = static_cast<int32_t>(_findersOfFinder.size()) - 1; n >= 0; n--)
{
delete _findersOfFinder[n];
_findersOfFinder.erase(_findersOfFinder.begin() + n);
}
// 销毁窗口句柄
if (_shiftTrickUpTip)
::DestroyWindow(_shiftTrickUpTip);
if (_2ButtonsTip)
::DestroyWindow(_2ButtonsTip);
if (_filterTip)
::DestroyWindow(_filterTip);
// 释放字体对象
if (_hMonospaceFont)
::DeleteObject(_hMonospaceFont);
if (_hLargerBolderFont)
::DeleteObject(_hLargerBolderFont);
if (_hCourrierNewFont)
::DeleteObject(_hCourrierNewFont);
delete[] _uniFileName;
delete[] _uniFileName; // 释放存储文件名的数组内存
}
// 创建 FindReplaceDlg 对话框
void FindReplaceDlg::create(int dialogID, bool isRTL, bool msgDestParent, bool toShow)
{
// 创建静态对话框
StaticDialog::create(dialogID, isRTL, msgDestParent);
fillFindHistory();
_currentStatus = REPLACE_DLG;
initOptionsFromDlg();
fillFindHistory(); // 填充查找历史记录
_currentStatus = REPLACE_DLG; // 设置当前状态为替换对话框
initOptionsFromDlg(); // 从对话框初始化选项
_statusBar.init(GetModuleHandle(NULL), _hSelf, 0);
_statusBar.display();
_statusBar.init(GetModuleHandle(NULL), _hSelf, 0); // 初始化状态栏
_statusBar.display(); // 显示状态栏
// 获取 DPI 管理器
DPIManager& dpiManager = NppParameters::getInstance()._dpiManager;
RECT rect{};
getClientRect(rect);
_tab.init(_hInst, _hSelf, false, true);
NppDarkMode::subclassTabControl(_tab.getHSelf());
int tabDpiDynamicalHeight = dpiManager.scaleY(13);
_tab.setFont(TEXT("Tahoma"), tabDpiDynamicalHeight);
getClientRect(rect); // 获取客户区矩形
_tab.init(_hInst, _hSelf, false, true); // 初始化标签页控件
NppDarkMode::subclassTabControl(_tab.getHSelf()); // 子类化标签页控件以适配暗黑模式
int tabDpiDynamicalHeight = dpiManager.scaleY(13); // 根据 DPI 缩放标签页高度
_tab.setFont(TEXT("Tahoma"), tabDpiDynamicalHeight); // 设置标签页字体
// 插入标签页内容
const TCHAR *find = TEXT("Find");
const TCHAR *replace = TEXT("Replace");
const TCHAR *findInFiles = TEXT("Find in Files");
const TCHAR *findInProjects = TEXT("Find in Projects");
const TCHAR *mark = TEXT("Mark");
_tab.insertAtEnd(find);
_tab.insertAtEnd(replace);
_tab.insertAtEnd(findInFiles);
_tab.insertAtEnd(findInProjects);
_tab.insertAtEnd(mark);
_tab.reSizeTo(rect); // 调整标签页大小以适应客户区
_tab.display(); // 显示标签页
_tab.reSizeTo(rect);
_tab.display();
_initialClientWidth = rect.right - rect.left;
_initialClientWidth = rect.right - rect.left; // 记录初始客户区宽度
//fill min dialog size info
// 填充最小对话框大小信息
getWindowRect(_initialWindowRect);
_initialWindowRect.right = _initialWindowRect.right - _initialWindowRect.left + dpiManager.scaleX(10);
_initialWindowRect.left = 0;
@ -335,88 +358,65 @@ void FindReplaceDlg::create(int dialogID, bool isRTL, bool msgDestParent, bool t
NppGUI& nppGUI = nppParam.getNppGUI();
const UINT swpFlags = toShow ? SWP_SHOWWINDOW : SWP_HIDEWINDOW;
if (nppGUI._findWindowPos.bottom - nppGUI._findWindowPos.top != 0) // check height against 0 as a test of valid data from config
if (nppGUI._findWindowPos.bottom - nppGUI._findWindowPos.top != 0) // 检查配置数据是否有效
{
RECT rc = getViewablePositionRect(nppGUI._findWindowPos);
::SetWindowPos(_hSelf, HWND_TOP, rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top, swpFlags);
}
else
{
goToCenter(swpFlags);
goToCenter(swpFlags); // 居中显示
}
// 获取状态栏客户区矩形
RECT rcStatusBar{};
::GetClientRect(_statusBar.getHSelf(), &rcStatusBar);
_lesssModeHeight = (countRc.bottom - dlgRc.top) + (rcStatusBar.bottom - rcStatusBar.top) + dpiManager.scaleY(10);
if (nppGUI._findWindowLessMode)
{
// reverse the value of _findWindowLessMode because the value will be inversed again in IDD_RESIZE_TOGGLE_BUTTON
// 反转 _findWindowLessMode 的值,因为在 IDD_RESIZE_TOGGLE_BUTTON 中会再次反转该值
nppGUI._findWindowLessMode = false;
::SendMessage(_hSelf, WM_COMMAND, IDD_RESIZE_TOGGLE_BUTTON, 0);
}
}
// 填充查找历史记录
void FindReplaceDlg::fillFindHistory()
{
NppParameters& nppParams = NppParameters::getInstance();
FindHistory & findHistory = nppParams.getFindHistory();
// 填充各个 Combo Box 的历史记录
fillComboHistory(IDFINDWHAT, findHistory._findHistoryFinds);
fillComboHistory(IDREPLACEWITH, findHistory._findHistoryReplaces);
fillComboHistory(IDD_FINDINFILES_FILTERS_COMBO, findHistory._findHistoryFilters);
fillComboHistory(IDD_FINDINFILES_DIR_COMBO, findHistory._findHistoryPaths);
// 设置各个复选框的选中状态
::SendDlgItemMessage(_hSelf, IDWRAP, BM_SETCHECK, findHistory._isWrap, 0);
::SendDlgItemMessage(_hSelf, IDWHOLEWORD, BM_SETCHECK, findHistory._isMatchWord, 0);
::SendDlgItemMessage(_hSelf, IDMATCHCASE, BM_SETCHECK, findHistory._isMatchCase, 0);
::SendDlgItemMessage(_hSelf, IDC_BACKWARDDIRECTION, BM_SETCHECK, !findHistory._isDirectionDown, 0);
::SendDlgItemMessage(_hSelf, IDD_FINDINFILES_INHIDDENDIR_CHECK, BM_SETCHECK, findHistory._isFifInHiddenFolder, 0);
::SendDlgItemMessage(_hSelf, IDD_FINDINFILES_RECURSIVE_CHECK, BM_SETCHECK, findHistory._isFifRecuisive, 0);
::SendDlgItemMessage(_hSelf, IDD_FINDINFILES_FOLDERFOLLOWSDOC_CHECK, BM_SETCHECK, findHistory._isFolderFollowDoc, 0);
::SendDlgItemMessage(_hSelf, IDD_FINDINFILES_PROJECT1_CHECK, BM_SETCHECK, findHistory._isFifProjectPanel_1, 0);
::SendDlgItemMessage(_hSelf, IDD_FINDINFILES_PROJECT2_CHECK, BM_SETCHECK, findHistory._isFifProjectPanel_2, 0);
::SendDlgItemMessage(_hSelf, IDD_FINDINFILES_PROJECT3_CHECK, BM_SETCHECK, findHistory._isFifProjectPanel_3, 0);
::SendDlgItemMessage(_hSelf, IDNORMAL, BM_SETCHECK, findHistory._searchMode == FindHistory::normal, 0);
::SendDlgItemMessage(_hSelf, IDEXTENDED, BM_SETCHECK, findHistory._searchMode == FindHistory::extended, 0);
::SendDlgItemMessage(_hSelf, IDREGEXP, BM_SETCHECK, findHistory._searchMode == FindHistory::regExpr, 0);
::SendDlgItemMessage(_hSelf, IDREDOTMATCHNL, BM_SETCHECK, findHistory._dotMatchesNewline, 0);
::SendDlgItemMessage(_hSelf, IDC_MARKLINE_CHECK, BM_SETCHECK, findHistory._isBookmarkLine, 0);
::SendDlgItemMessage(_hSelf, IDC_PURGE_CHECK, BM_SETCHECK, findHistory._isPurge, 0);
::SendDlgItemMessage(_hSelf, IDC_2_BUTTONS_MODE, BM_SETCHECK, findHistory._isSearch2ButtonsMode, 0);
if (findHistory._searchMode == FindHistory::regExpr)
{
//regex doesn't allow wholeword
::SendDlgItemMessage(_hSelf, IDWHOLEWORD, BM_SETCHECK, BST_UNCHECKED, 0);
enableFindDlgItem(IDWHOLEWORD, false);
// regex upward search is disabled
::SendDlgItemMessage(_hSelf, IDC_BACKWARDDIRECTION, BM_SETCHECK, BST_UNCHECKED, 0);
enableFindDlgItem(IDC_BACKWARDDIRECTION, nppParams.regexBackward4PowerUser());
enableFindDlgItem(IDC_FINDPREV, nppParams.regexBackward4PowerUser());
// If the search mode from history is regExp then enable the checkbox (. matches newline)
enableFindDlgItem(IDREDOTMATCHNL);
}
// 设置其他复选框的选中状态
// ...
// 如果系统支持透明度,则设置透明度相关控件的显示状态和属性
if (nppParams.isTransparentAvailable())
{
// 显示透明度相关控件
showFindDlgItem(IDC_TRANSPARENT_CHECK);
showFindDlgItem(IDC_TRANSPARENT_GRPBOX);
showFindDlgItem(IDC_TRANSPARENT_LOSSFOCUS_RADIO);
showFindDlgItem(IDC_TRANSPARENT_ALWAYS_RADIO);
showFindDlgItem(IDC_PERCENTAGE_SLIDER);
// 设置滑动条范围和位置
::SendDlgItemMessage(_hSelf, IDC_PERCENTAGE_SLIDER, TBM_SETRANGE, FALSE, MAKELONG(20, 200));
::SendDlgItemMessage(_hSelf, IDC_PERCENTAGE_SLIDER, TBM_SETPOS, TRUE, findHistory._transparency);
// 根据透明度模式设置相应的复选框选中状态
if (findHistory._transparencyMode == FindHistory::none)
{
enableFindDlgItem(IDC_TRANSPARENT_LOSSFOCUS_RADIO, false);
@ -436,44 +436,47 @@ void FindReplaceDlg::fillFindHistory()
{
id = IDC_TRANSPARENT_ALWAYS_RADIO;
(NppParameters::getInstance()).SetTransparent(_hSelf, findHistory._transparency);
}
::SendDlgItemMessage(_hSelf, id, BM_SETCHECK, TRUE, 0);
}
}
}
// 填充 Combo Box 的历史记录
void FindReplaceDlg::fillComboHistory(int id, const vector<generic_string> & strings)
{
HWND hCombo = ::GetDlgItem(_hSelf, id);
// 将历史记录添加到 Combo Box
for (vector<generic_string>::const_reverse_iterator i = strings.rbegin() ; i != strings.rend(); ++i)
{
addText2Combo(i->c_str(), hCombo);
}
//empty string is not added to CB items, so we need to set it manually
// 如果历史记录不为空且第一个元素为空字符串,则手动设置 Combo Box 文本为空
if (!strings.empty() && strings.begin()->empty())
{
SetWindowText(hCombo, _T(""));
return;
}
::SendMessage(hCombo, CB_SETCURSEL, 0, 0); // select first item
::SendMessage(hCombo, CB_SETCURSEL, 0, 0); // 选择第一项
}
// 保存查找历史记录
void FindReplaceDlg::saveFindHistory()
{
if (! isCreated()) return;
FindHistory& findHistory = (NppParameters::getInstance()).getFindHistory();
// 保存各个 Combo Box 的历史记录
saveComboHistory(IDD_FINDINFILES_DIR_COMBO, findHistory._nbMaxFindHistoryPath, findHistory._findHistoryPaths, false);
saveComboHistory(IDD_FINDINFILES_FILTERS_COMBO, findHistory._nbMaxFindHistoryFilter, findHistory._findHistoryFilters, true);
saveComboHistory(IDFINDWHAT, findHistory._nbMaxFindHistoryFind, findHistory._findHistoryFinds, false);
saveComboHistory(IDREPLACEWITH, findHistory._nbMaxFindHistoryReplace, findHistory._findHistoryReplaces, true);
saveComboHistory(IDFINDWHAT, findHistory._nbMaxFindHistoryFind, findHistory._findHistoryFinds, false);
saveComboHistory(IDREPLACEWITH, findHistory._nbMaxFindHistoryReplace, findHistory._findHistoryReplaces, true);
}
// 保存 Combo Box 的历史记录
int FindReplaceDlg::saveComboHistory(int id, int maxcount, vector<generic_string> & strings, bool saveEmpty)
{
TCHAR text[FINDREPLACE_MAXLENGTH] = { '\0' };
@ -485,6 +488,7 @@ int FindReplaceDlg::saveComboHistory(int id, int maxcount, vector<generic_string
strings.clear();
// 如果允许保存空字符串,则检查 Combo Box 文本是否为空,并加入历史记录
if (saveEmpty)
{
if (::GetWindowTextLength(hCombo) == 0)
@ -493,6 +497,7 @@ int FindReplaceDlg::saveComboHistory(int id, int maxcount, vector<generic_string
}
}
// 保存 Combo Box 中的文本到历史记录
for (int i = 0 ; i < count ; ++i)
{
auto cbTextLen = ::SendMessage(hCombo, CB_GETLBTEXTLEN, i, 0);
@ -504,13 +509,14 @@ int FindReplaceDlg::saveComboHistory(int id, int maxcount, vector<generic_string
}
return count;
}
```
//更新数据Combo
void FindReplaceDlg::updateCombos()
{
updateCombo(IDREPLACEWITH);
updateCombo(IDFINDWHAT);
}
//
void FindReplaceDlg::updateCombo(int comboID)
{
HWND hCombo = ::GetDlgItem(_hSelf, comboID);
@ -725,162 +731,181 @@ bool Finder::canFind(const TCHAR *fileName, size_t lineNumber, size_t* indexToSt
// [ ] [ ] [ Y [ ] : pos_between 3
// [ ] [ ] Y [ ] [ ] : pos_between 2
// [ ] [ ] [ ] [ ] Y : pos_behind 4
```cpp
Finder::CurrentPosInLineInfo Finder::getCurrentPosInLineInfo(intptr_t currentPosInLine, const SearchResultMarkingLine& markingLine) const
{
CurrentPosInLineInfo cpili;
size_t count = 0;
intptr_t lastEnd = 0;
auto selStart = _scintView.execute(SCI_GETSELECTIONSTART);
auto selEnd = _scintView.execute(SCI_GETSELECTIONEND);
bool hasSel = (selEnd - selStart) != 0;
for (std::pair<intptr_t, intptr_t> range : markingLine._segmentPostions)
{
++count;
if (lastEnd <= currentPosInLine && currentPosInLine < range.first)
{
if (count == 1)
{
cpili._status = pos_infront;
break;
}
else
{
cpili._status = pos_between;
cpili.auxiliaryInfo = count - 1;
break;
}
}
if (range.first <= currentPosInLine && currentPosInLine <= range.second)
{
if (currentPosInLine == range.first && !hasSel)
{
cpili._status = pos_between;
cpili.auxiliaryInfo = count - 1; // c1 c2
// [ ] I[ ] : I is recongnized with c2, so auxiliaryInfo should be c1 (c2-1)
}
else if (currentPosInLine == range.second && !hasSel)
{
cpili._status = pos_between;
cpili.auxiliaryInfo = count; // c1 c2
// [ ]I [ ] : I is recongnized with c1, so auxiliaryInfo should be c1
}
else
{
cpili._status = pos_inside;
cpili.auxiliaryInfo = count;
}
break;
}
if (range.second < currentPosInLine)
{
if (markingLine._segmentPostions.size() == count)
{
cpili._status = pos_behind;
cpili.auxiliaryInfo = count;
break;
}
}
lastEnd = range.second;
}
// 定义用于返回的结构体
CurrentPosInLineInfo cpili;
// 初始化计数器count为0
size_t count = 0;
// 初始化上一个区间的结束位置为0
intptr_t lastEnd = 0;
// 获取当前文本框选择的起始位置和结束位置
auto selStart = _scintView.execute(SCI_GETSELECTIONSTART);
auto selEnd = _scintView.execute(SCI_GETSELECTIONEND);
// 判断是否有选择文本
bool hasSel = (selEnd - selStart) != 0;
// 遍历每个区间
for (std::pair<intptr_t, intptr_t> range : markingLine._segmentPostions)
{
++count;
// 判断当前位置在区间的前面
if (lastEnd <= currentPosInLine && currentPosInLine < range.first)
{
if (count == 1)
{
cpili._status = pos_infront; // 在第一个区间的前面
break;
}
else
{
cpili._status = pos_between; // 在两个区间之间
cpili.auxiliaryInfo = count - 1;
break;
}
}
// 判断当前位置在区间内部
if (range.first <= currentPosInLine && currentPosInLine <= range.second)
{
if (currentPosInLine == range.first && !hasSel)
{
cpili._status = pos_between; // 在区间的起始位置,在没有选择文本的情况下
cpili.auxiliaryInfo = count - 1;
}
else if (currentPosInLine == range.second && !hasSel)
{
cpili._status = pos_between; // 在区间的结束位置,在没有选择文本的情况下
cpili.auxiliaryInfo = count;
}
else
{
cpili._status = pos_inside; // 在区间内部
cpili.auxiliaryInfo = count;
}
break;
}
// 判断当前位置在区间的后面
if (range.second < currentPosInLine)
{
if (markingLine._segmentPostions.size() == count)
{
cpili._status = pos_behind; // 在最后一个区间的后面
cpili.auxiliaryInfo = count;
break;
}
}
lastEnd = range.second;
}
return cpili;
return cpili;
}
void Finder::anchorWithNoHeaderLines(intptr_t& currentL, intptr_t initL, intptr_t minL, intptr_t maxL, int direction)
{
if (currentL > maxL && direction == 0)
currentL = minL;
while (_scintView.execute(SCI_GETFOLDLEVEL, currentL) & SC_FOLDLEVELHEADERFLAG)
{
currentL += direction == -1 ? -1 : 1;
if (currentL > maxL)
currentL = minL;
else if (currentL < minL)
currentL = maxL;
if (currentL == initL)
break;
}
// 如果当前行大于最大行并且方向为0则将当前行设置为最小行
if (currentL > maxL && direction == 0)
currentL = minL;
// 循环直到当前行不是折叠标题行
while (_scintView.execute(SCI_GETFOLDLEVEL, currentL) & SC_FOLDLEVELHEADERFLAG)
{
// 根据方向更新当前行
currentL += direction == -1 ? -1 : 1;
// 如果当前行超过最大行,则将当前行设置为最小行
if (currentL > maxL)
currentL = minL;
// 如果当前行低于最小行,则将当前行设置为最大行
else if (currentL < minL)
currentL = maxL;
// 如果当前行等于初始行,则跳出循环
if (currentL == initL)
break;
}
auto extremityAbsoltePos = _scintView.execute(direction == -1 ? SCI_GETLINEENDPOSITION : SCI_POSITIONFROMLINE, currentL);
_scintView.execute(SCI_SETSEL, extremityAbsoltePos, extremityAbsoltePos);
// 获取当前行的绝对位置
auto extremityAbsoltePos = _scintView.execute(direction == -1 ? SCI_GETLINEENDPOSITION : SCI_POSITIONFROMLINE, currentL);
// 设置选择范围为当前行的绝对位置
_scintView.execute(SCI_SETSEL, extremityAbsoltePos, extremityAbsoltePos);
}
void Finder::gotoNextFoundResult(int direction)
{
//
// Get currentLine & currentPosInLine from CurrentPos
//
auto currentPos = _scintView.execute(SCI_GETCURRENTPOS);
intptr_t lno = _scintView.execute(SCI_LINEFROMPOSITION, currentPos);
auto total_lines = _scintView.execute(SCI_GETLINECOUNT);
if (total_lines <= 1) return;
auto lineStartAbsPos = _scintView.execute(SCI_POSITIONFROMLINE, lno);
intptr_t currentPosInLine = currentPos - lineStartAbsPos;
auto init_lno = lno;
auto max_lno = _scintView.execute(SCI_GETLASTCHILD, lno, searchHeaderLevel);
// 获取当前光标位置及所在行号
auto currentPos = _scintView.execute(SCI_GETCURRENTPOS);
intptr_t lno = _scintView.execute(SCI_LINEFROMPOSITION, currentPos);
auto total_lines = _scintView.execute(SCI_GETLINECOUNT);
// 如果总行数小于等于1则直接返回
if (total_lines <= 1) return;
// 获取当前行的起始位置和光标在行内的位置
auto lineStartAbsPos = _scintView.execute(SCI_POSITIONFROMLINE, lno);
intptr_t currentPosInLine = currentPos - lineStartAbsPos;
auto init_lno = lno;
auto max_lno = _scintView.execute(SCI_GETLASTCHILD, lno, searchHeaderLevel);
assert(max_lno <= total_lines - 2);
// 获取当前搜索行号searchHeaderLevel
int level = _scintView.execute(SCI_GETFOLDLEVEL, lno) & SC_FOLDLEVELNUMBERMASK;
auto min_lno = lno;
while (level-- >= fileHeaderLevel)
{
min_lno = _scintView.execute(SCI_GETFOLDPARENT, min_lno);
assert(min_lno >= 0);
}
assert(max_lno <= total_lines - 2);
if (min_lno < 0) min_lno = lno; // 当lno是一个搜索标题行时
// get the line number of the current search (searchHeaderLevel)
int level = _scintView.execute(SCI_GETFOLDLEVEL, lno) & SC_FOLDLEVELNUMBERMASK;
auto min_lno = lno;
while (level-- >= fileHeaderLevel)
{
min_lno = _scintView.execute(SCI_GETFOLDPARENT, min_lno);
assert(min_lno >= 0);
}
assert(min_lno <= max_lno);
if (min_lno < 0) min_lno = lno; // when lno is a search header line
// 根据方向更新当前行号
if (lno > max_lno && direction == 0) lno = min_lno;
else if (lno < min_lno) lno = max_lno;
assert(min_lno <= max_lno);
// 设置锚点,确保锚点不在最后一行或折叠标题行上
while (_scintView.execute(SCI_GETFOLDLEVEL, lno) & SC_FOLDLEVELHEADERFLAG)
{
lno += direction == -1 ? -1 : 1;
if (lno > max_lno && direction == 0) lno = min_lno;
else if (lno < min_lno) lno = max_lno;
if (lno > max_lno)
lno = min_lno;
else if (lno < min_lno)
lno = max_lno;
//
// Set anchor and make sure that achor is not on the last (empty) line or head lines
//
while (_scintView.execute(SCI_GETFOLDLEVEL, lno) & SC_FOLDLEVELHEADERFLAG)
{
lno += direction == -1 ? -1 : 1;
if (lno > max_lno)
lno = min_lno;
else if (lno < min_lno)
lno = max_lno;
if (lno == init_lno)
break;
}
if (lno == init_lno)
break;
}
if (lno != init_lno)
{
auto extremityAbsoltePos = _scintView.execute(direction == -1 ? SCI_GETLINEENDPOSITION : SCI_POSITIONFROMLINE, lno);
_scintView.execute(SCI_SETSEL, extremityAbsoltePos, extremityAbsoltePos);
currentPos = extremityAbsoltePos;
auto start = _scintView.execute(SCI_POSITIONFROMLINE, lno);
currentPosInLine = currentPos - start;
}
// 如果当前行与初始行不同
if (lno != init_lno)
{
// 获取当前行的绝对位置
auto extremityAbsoltePos = _scintView.execute(direction == -1 ? SCI_GETLINEENDPOSITION : SCI_POSITIONFROMLINE, lno);
// 设置选择范围为当前行的绝对位置
_scintView.execute(SCI_SETSEL, extremityAbsoltePos, extremityAbsoltePos);
currentPos = extremityAbsoltePos;
// 获取当前行的起始位置和光标在行内的位置
auto start = _scintView.execute(SCI_POSITIONFROMLINE, lno);
currentPosInLine = currentPos - start;
}
size_t n = 0;
const SearchResultMarkingLine& markingLine = *(_pMainMarkings->begin() + lno);
size_t n = 0;
const SearchResultMarkingLine& markingLine = *(_pMainMarkings->begin() + lno);
// 获取当前位置在行内的状态
CurrentPosInLineInfo cpili = getCurrentPosInLineInfo(currentPosInLine, markingLine);
//
// Determinate currentPosInLine status among pos_infront, pose_between, pos_inside and pos_behind
//
CurrentPosInLineInfo cpili = getCurrentPosInLineInfo(currentPosInLine, markingLine);
// 根据方向和当前
//
// According CurrentPosInLineInfo and direction, set position and get number of occurrence

File diff suppressed because it is too large Load Diff

@ -16,291 +16,331 @@
#include "lastRecentFileList.h"
#include "menuCmdID.h"
#include "localization.h"
void LastRecentFileList::initMenu(HMENU hMenu, int idBase, int posBase, Accelerator *pAccelerator, bool doSubMenu)
// 引入LastRecentFileList类的头文件
#include "lastRecentFileList.h"
// 引入菜单命令ID的头文件
#include "menuCmdID.h"
// 引入本地化的头文件,可能用于支持多语言
#include "localization.h"
// LastRecentFileList类的initMenu函数
void LastRecentFileList::initMenu(HMENU hMenu, int idBase, int posBase, Accelerator* pAccelerator, bool doSubMenu)
{
if (doSubMenu)
{
_hParentMenu = hMenu;
_hMenu = ::CreatePopupMenu();
}
else
{
_hParentMenu = NULL;
_hMenu = hMenu;
}
_idBase = idBase;
_posBase = posBase;
_pAccelerator = pAccelerator;
_nativeLangEncoding = NPP_CP_WIN_1252;
for (size_t i = 0 ; i < sizeof(_idFreeArray) ; ++i)
_idFreeArray[i] = true;
// 如果doSubMenu为真表示需要创建一个弹出菜单
if (doSubMenu)
{
// 设置父菜单句柄
_hParentMenu = hMenu;
// 创建一个新的弹出菜单
_hMenu = ::CreatePopupMenu();
}
// 如果doSubMenu为假表示直接使用传入的菜单句柄
else
{
// 设置父菜单句柄为NULL表示主菜单
_hParentMenu = NULL;
// 使用传入的菜单句柄作为当前菜单
_hMenu = hMenu;
}
// 设置ID的基础值
_idBase = idBase;
// 设置位置的基础值
_posBase = posBase;
// 设置指向Accelerator对象的指针用于处理键盘快捷键等加速功能
_pAccelerator = pAccelerator;
// 设置本地化语言编码为Windows的1252编码这是一种西欧语言编码
_nativeLangEncoding = NPP_CP_WIN_1252;
// 初始化idFreeArray数组所有元素都设置为true表示ID可用
for (size_t i = 0; i < sizeof(_idFreeArray); ++i)
_idFreeArray[i] = true;
}
// LastRecentFileList类的switchMode函数用于切换模式
void LastRecentFileList::switchMode()
{
//Remove all menu items
::RemoveMenu(_hMenu, IDM_FILE_RESTORELASTCLOSEDFILE, MF_BYCOMMAND);
::RemoveMenu(_hMenu, IDM_OPEN_ALL_RECENT_FILE, MF_BYCOMMAND);
::RemoveMenu(_hMenu, IDM_CLEAN_RECENT_FILE_LIST, MF_BYCOMMAND);
for (int i = 0; i < _size; ++i)
{
::RemoveMenu(_hMenu, _lrfl.at(i)._id, MF_BYCOMMAND);
}
if (_hParentMenu == NULL) // mode main menu
{ if (_size > 0)
{
::RemoveMenu(_hMenu, _posBase, MF_BYPOSITION);
::RemoveMenu(_hMenu, _posBase, MF_BYPOSITION);
}
// switch to sub-menu mode
_hParentMenu = _hMenu;
_hMenu = ::CreatePopupMenu();
::RemoveMenu(_hMenu, _posBase+1, MF_BYPOSITION);
}
else // mode sub-menu
{
if (_size > 0)
{
::RemoveMenu(_hParentMenu, _posBase, MF_BYPOSITION);
::RemoveMenu(_hParentMenu, _posBase, MF_BYPOSITION);
}
// switch to main menu mode
::DestroyMenu(_hMenu);
_hMenu = _hParentMenu;
_hParentMenu = NULL;
}
_hasSeparators = false;
// 从菜单中移除所有相关菜单项
::RemoveMenu(_hMenu, IDM_FILE_RESTORELASTCLOSEDFILE, MF_BYCOMMAND);
::RemoveMenu(_hMenu, IDM_OPEN_ALL_RECENT_FILE, MF_BYCOMMAND);
::RemoveMenu(_hMenu, IDM_CLEAN_RECENT_FILE_LIST, MF_BYCOMMAND);
// 遍历最近打开文件列表,移除所有菜单项
for (int i = 0; i < _size; ++i)
{
::RemoveMenu(_hMenu, _lrfl.at(i)._id, MF_BYCOMMAND);
}
// 根据_hParentMenu的值判断当前模式主菜单模式或子菜单模式
if (_hParentMenu == NULL) // mode main menu主菜单模式
{
if (_size > 0) // 如果最近打开文件列表不为空
{
// 从主菜单中移除一些特定的菜单项(具体移除哪些项未给出)
::RemoveMenu(_hMenu, _posBase, MF_BYPOSITION);
::RemoveMenu(_hMenu, _posBase, MF_BYPOSITION);
}
// 切换到子菜单模式创建一个新的弹出菜单作为当前菜单并设置_hParentMenu为当前菜单即新创建的弹出菜单
// 同时移除一些特定的菜单项(具体移除哪些项未给出)
_hParentMenu = _hMenu;
_hMenu = ::CreatePopupMenu();
::RemoveMenu(_hMenu, _posBase + 1, MF_BYPOSITION);
}
else // mode sub-menu子菜单模式
{
if (_size > 0) // 如果最近打开文件列表不为空
{
// 从子菜单中移除一些特定的菜单项(具体移除哪些项未给出)
::RemoveMenu(_hParentMenu, _posBase, MF_BYPOSITION);
::RemoveMenu(_hParentMenu, _posBase, MF_BYPOSITION);
}
// switch to main menu mode
::DestroyMenu(_hMenu);
_hMenu = _hParentMenu;
_hParentMenu = NULL;
}
_hasSeparators = false;
}
void LastRecentFileList::updateMenu()
{
NppParameters& nppParam = NppParameters::getInstance();
if (!_hasSeparators && _size > 0)
{
//add separators
NativeLangSpeaker *pNativeLangSpeaker = nppParam.getNativeLangSpeaker();
generic_string recentFileList = pNativeLangSpeaker->getSubMenuEntryName("file-recentFiles");
generic_string openRecentClosedFile = pNativeLangSpeaker->getNativeLangMenuString(IDM_FILE_RESTORELASTCLOSEDFILE);
generic_string openAllFiles = pNativeLangSpeaker->getNativeLangMenuString(IDM_OPEN_ALL_RECENT_FILE);
generic_string cleanFileList = pNativeLangSpeaker->getNativeLangMenuString(IDM_CLEAN_RECENT_FILE_LIST);
if (recentFileList == TEXT(""))
recentFileList = TEXT("&Recent Files");
if (openRecentClosedFile == TEXT(""))
openRecentClosedFile = TEXT("Restore Recent Closed File");
if (openAllFiles == TEXT(""))
openAllFiles = TEXT("Open All Recent Files");
if (cleanFileList == TEXT(""))
cleanFileList = TEXT("Empty Recent Files List");
if (!isSubMenuMode())
::InsertMenu(_hMenu, _posBase + 0, MF_BYPOSITION, static_cast<UINT_PTR>(-1), 0);
::InsertMenu(_hMenu, _posBase + 1, MF_BYPOSITION, IDM_FILE_RESTORELASTCLOSEDFILE, openRecentClosedFile.c_str());
::InsertMenu(_hMenu, _posBase + 2, MF_BYPOSITION, IDM_OPEN_ALL_RECENT_FILE, openAllFiles.c_str());
::InsertMenu(_hMenu, _posBase + 3, MF_BYPOSITION, IDM_CLEAN_RECENT_FILE_LIST, cleanFileList.c_str());
::InsertMenu(_hMenu, _posBase + 4, MF_BYPOSITION, static_cast<UINT_PTR>(-1), 0);
_hasSeparators = true;
if (isSubMenuMode())
{
::InsertMenu(_hParentMenu, _posBase + 0, MF_BYPOSITION | MF_POPUP, reinterpret_cast<UINT_PTR>(_hMenu), (LPCTSTR)recentFileList.c_str());
::InsertMenu(_hParentMenu, _posBase + 1, MF_BYPOSITION, static_cast<UINT_PTR>(-1), 0);
}
}
else if (_hasSeparators && _size == 0) //remove separators
{
::RemoveMenu(_hMenu, _posBase + 4, MF_BYPOSITION);
::RemoveMenu(_hMenu, IDM_CLEAN_RECENT_FILE_LIST, MF_BYCOMMAND);
::RemoveMenu(_hMenu, IDM_OPEN_ALL_RECENT_FILE, MF_BYCOMMAND);
::RemoveMenu(_hMenu, IDM_FILE_RESTORELASTCLOSEDFILE, MF_BYCOMMAND);
::RemoveMenu(_hMenu, _posBase + 0, MF_BYPOSITION);
_hasSeparators = false;
if (isSubMenuMode())
{
// Remove "Recent Files" Entry and the separator from the main menu
::RemoveMenu(_hParentMenu, _posBase + 1, MF_BYPOSITION);
::RemoveMenu(_hParentMenu, _posBase + 0, MF_BYPOSITION);
// Remove the last left separator from the submenu
::RemoveMenu(_hMenu, 0, MF_BYPOSITION);
}
}
_pAccelerator->updateFullMenu();
//Remove all menu items
for (int i = 0; i < _size; ++i)
{
::RemoveMenu(_hMenu, _lrfl.at(i)._id, MF_BYCOMMAND);
}
//Then readd them, so everything stays in sync
for (int j = 0; j < _size; ++j)
{
generic_string strBuffer(BuildMenuFileName(nppParam.getRecentFileCustomLength(), j, _lrfl.at(j)._name));
::InsertMenu(_hMenu, _posBase + j, MF_BYPOSITION, _lrfl.at(j)._id, strBuffer.c_str());
}
}
// 获取 NppParameters 的单例实例
NppParameters& nppParam = NppParameters::getInstance();
// 检查是否没有分隔符且大小大于0满足条件则进入下面的 if 语句块
if (!_hasSeparators && _size > 0)
{
// 获取本地化语言的发言人对象
NativeLangSpeaker* pNativeLangSpeaker = nppParam.getNativeLangSpeaker();
// 从发言人对象中获取一些本地化菜单字符串
generic_string recentFileList = pNativeLangSpeaker->getSubMenuEntryName("file-recentFiles");
generic_string openRecentClosedFile = pNativeLangSpeaker->getNativeLangMenuString(IDM_FILE_RESTORELASTCLOSEDFILE);
generic_string openAllFiles = pNativeLangSpeaker->getNativeLangMenuString(IDM_OPEN_ALL_RECENT_FILE);
generic_string cleanFileList = pNativeLangSpeaker->getNativeLangMenuString(IDM_CLEAN_RECENT_FILE_LIST);
// 如果获取的字符串为空,则使用默认的字符串进行初始化
if (recentFileList == TEXT(""))
recentFileList = TEXT("&Recent Files");
if (openRecentClosedFile == TEXT(""))
openRecentClosedFile = TEXT("Restore Recent Closed File");
if (openAllFiles == TEXT(""))
openAllFiles = TEXT("Open All Recent Files");
if (cleanFileList == TEXT(""))
cleanFileList = TEXT("Empty Recent Files List");
// 如果当前不是子菜单模式,则在菜单中插入一个分隔符
if (!isSubMenuMode())
::InsertMenu(_hMenu, _posBase + 0, MF_BYPOSITION, static_cast<UINT_PTR>(-1), 0);
// 在菜单中插入四个子菜单项,分别是恢复最近关闭的文件、打开所有最近文件、清空最近文件列表和另一个分隔符
::InsertMenu(_hMenu, _posBase + 1, MF_BYPOSITION, IDM_FILE_RESTORELASTCLOSEDFILE, openRecentClosedFile.c_str());
::InsertMenu(_hMenu, _posBase + 2, MF_BYPOSITION, IDM_OPEN_ALL_RECENT_FILE, openAllFiles.c_str());
::InsertMenu(_hMenu, _posBase + 3, MF_BYPOSITION, IDM_CLEAN_RECENT_FILE_LIST, cleanFileList.c_str());
::InsertMenu(_hMenu, _posBase + 4, MF_BYPOSITION, static_cast<UINT_PTR>(-1), 0); // 插入分隔符
// 设置标志表示已有分隔符
_hasSeparators = true;
// 如果当前是子菜单模式,则在父菜单中插入子菜单和分隔符
if (isSubMenuMode())
{
::InsertMenu(_hParentMenu, _posBase + 0, MF_BYPOSITION | MF_POPUP, reinterpret_cast<UINT_PTR>(_hMenu), (LPCTSTR)recentFileList.c_str());
::InsertMenu(_hParentMenu, _posBase + 1, MF_BYPOSITION, static_cast<UINT_PTR>(-1), 0); // 插入分隔符
}
}
else if (_hasSeparators && _size == 0) // 当已有分隔符且大小为0时进入下面的 if 语句块,用于移除分隔符和菜单项
{
// 从菜单中移除一个分隔符和清空最近文件列表的菜单项
::RemoveMenu(_hMenu, _posBase + 4, MF_BYPOSITION);
::RemoveMenu(_hMenu, IDM_CLEAN_RECENT_FILE_LIST, MF_BYCOMMAND);
::RemoveMenu(_hMenu, IDM_OPEN_ALL_RECENT_FILE, MF_BYCOMMAND);
::RemoveMenu(_hMenu, IDM_FILE_RESTORELASTCLOSEDFILE, MF_BYCOMMAND);
::RemoveMenu(_hMenu, _posBase + 0, MF_BYPOSITION);
_hasSeparators = false;
if (isSubMenuMode())
{
// Remove "Recent Files" Entry and the separator from the main menu
::RemoveMenu(_hParentMenu, _posBase + 1, MF_BYPOSITION);
::RemoveMenu(_hParentMenu, _posBase + 0, MF_BYPOSITION);
// Remove the last left separator from the submenu
::RemoveMenu(_hMenu, 0, MF_BYPOSITION);
}
}
_pAccelerator->updateFullMenu();
//Remove all menu items
for (int i = 0; i < _size; ++i)
{
::RemoveMenu(_hMenu, _lrfl.at(i)._id, MF_BYCOMMAND);
}
//Then readd them, so everything stays in sync
for (int j = 0; j < _size; ++j)
{
generic_string strBuffer(BuildMenuFileName(nppParam.getRecentFileCustomLength(), j, _lrfl.at(j)._name));
::InsertMenu(_hMenu, _posBase + j, MF_BYPOSITION, _lrfl.at(j)._id, strBuffer.c_str());
}
void LastRecentFileList::add(const TCHAR *fn)
}
// 向最近的文件列表中添加一个文件名。如果达到用户定义的最大限制或列表被锁定,则不会添加。
// 如果文件名已存在,则会先将其移除再添加。
void LastRecentFileList::add(const TCHAR* fn)
{
if (_userMax == 0 || _locked)
return;
RecentItem itemToAdd(fn);
int index = find(fn);
if (index != -1)
{
//already in list, bump upwards
remove(index);
}
if (_size == _userMax)
{
itemToAdd._id = _lrfl.back()._id;
_lrfl.pop_back(); //remove oldest
}
else
{
itemToAdd._id = popFirstAvailableID();
++_size;
}
_lrfl.push_front(itemToAdd);
updateMenu();
if (_userMax == 0 || _locked) // 如果用户定义的最大数量为0或列表被锁定直接返回不进行添加
return;
RecentItem itemToAdd(fn); // 创建一个新的RecentItem对象使用传入的文件名初始化
int index = find(fn); // 查找该文件名在列表中的索引
if (index != -1) // 如果找到
{
// 如果文件名已存在,先将其移除,然后重新添加
remove(index);
}
if (_size == _userMax) // 如果列表已满
{
itemToAdd._id = _lrfl.back()._id; // 使用最后一个元素的ID初始化新元素的ID
_lrfl.pop_back(); // 移除列表中的最后一个元素(即最旧的一个)
}
else // 如果列表未满
{
itemToAdd._id = popFirstAvailableID(); // 获取第一个可用的ID并初始化新元素的ID
++_size; // 增加列表的大小
}
_lrfl.push_front(itemToAdd); // 在列表的前面添加新元素
updateMenu(); // 更新菜单
}
void LastRecentFileList::remove(const TCHAR *fn)
{
int index = find(fn);
if (index != -1)
remove(index);
// 根据文件名从最近的文件列表中移除一个文件。如果找到,则移除;否则什么也不做。
void LastRecentFileList::remove(const TCHAR* fn)
{
int index = find(fn); // 查找文件名在列表中的索引
if (index != -1) // 如果找到
remove(index); // 移除该元素
}
void LastRecentFileList::remove(size_t index)
// 根据索引从最近的文件列表中移除一个文件。如果索引有效,则移除;否则什么也不做。
void LastRecentFileList::remove(size_t index)
{
if (_size == 0 || _locked)
return;
if (index < _lrfl.size())
{
::RemoveMenu(_hMenu, _lrfl.at(index)._id, MF_BYCOMMAND);
setAvailable(_lrfl.at(index)._id);
_lrfl.erase(_lrfl.begin() + index);
--_size;
updateMenu();
}
if (_size == 0 || _locked) // 如果列表为空或被锁定,直接返回,不进行移除操作
return;
if (index < _lrfl.size()) // 如果索引有效
{
::RemoveMenu(_hMenu, _lrfl.at(index)._id, MF_BYCOMMAND); // 从菜单中移除该ID对应的菜单项
setAvailable(_lrfl.at(index)._id); // 将该ID标记为可用可能是为了下次添加时重复使用
_lrfl.erase(_lrfl.begin() + index); // 从列表中移除该元素
--_size; // 减少列表的大小
updateMenu(); // 更新菜单
}
}
void LastRecentFileList::clear()
// 清空最近的文件列表。所有文件名和ID都会被移除菜单也会相应地更新。
void LastRecentFileList::clear()
{
if (_size == 0)
return;
for (int i = (_size-1); i >= 0; i--)
{
::RemoveMenu(_hMenu, _lrfl.at(i)._id, MF_BYCOMMAND);
setAvailable(_lrfl.at(i)._id);
_lrfl.erase(_lrfl.begin() + i);
}
_size = 0;
updateMenu();
if (_size == 0) // 如果列表为空,直接返回,不进行任何操作
return;
for (int i = (_size - 1); i >= 0; i--) // 从后向前遍历列表,因为移除元素会影响后续元素的索引
{
::RemoveMenu(_hMenu, _lrfl.at(i)._id, MF_BYCOMMAND); // 从菜单中移除该ID对应的菜单项
setAvailable(_lrfl.at(i)._id); // 将该ID标记为可用可能是为了下次添加时重复使用
_lrfl.erase(_lrfl.begin() + i); // 从列表中移除该元素
}
_size = 0; // 将列表大小设置为0
updateMenu(); // 更新菜单
}
LastRecentFileList
generic_string & LastRecentFileList::getItem(int id)
cpp
// 根据ID从最近的文件列表中获取一个文件名。如果找到则返回对应的文件名否则返回列表中的第一个文件名。
generic_string& LastRecentFileList::getItem(int id)
{
int i = 0;
for (; i < _size; ++i)
{
if (_lrfl.at(i)._id == id)
break;
}
if (i == _size)
i = 0;
return _lrfl.at(i)._name; //if not found, return first
int i = 0; // 从索引0开始查找因为如果ID不存在可能会返回第一个文件名作为默认值。
for (; i < _size; ++i) // 遍历整个列表查找匹配的ID。如果找不到i会等于_size此时i会被重新设置为0。这是一个后备计划以防ID不存在于列表
{
if (_lrfl.at(i)._id == id) // 如果找到匹配的ID
break;
}
if (i == _size) // 如果遍历完整个列表都没有找到匹配的ID
i = 0; // 将索引重置为0这样可以从列表的第一个元素开始返回文件名作为默认值
return _lrfl.at(i)._name; // 返回找到的文件名或默认文件名
}
generic_string & LastRecentFileList::getIndex(int index)
// 根据索引从最近的文件列表中获取一个文件名。如果索引有效,则返回对应的文件名;否则返回列表中的第一个文件名。
generic_string& LastRecentFileList::getIndex(int index)
{
return _lrfl.at(index)._name; //if not found, return first
return _lrfl.at(index)._name; // 返回找到的文件名或默认文件名
}
// 设置用户定义的最大最近文件列表大小。如果当前列表大小大于新设置的大小,则移除最旧的文件直到列表大小等于新设置的大小。
void LastRecentFileList::setUserMaxNbLRF(int size)
{
_userMax = size;
if (_size > _userMax)
{ //start popping items
int toPop = _size-_userMax;
while (toPop > 0)
{
::RemoveMenu(_hMenu, _lrfl.back()._id, MF_BYCOMMAND);
setAvailable(_lrfl.back()._id);
_lrfl.pop_back();
toPop--;
_size--;
}
updateMenu();
_size = _userMax;
}
_userMax = size; // 设置用户定义的最大列表大小
if (_size > _userMax) // 如果当前列表大小大于新设置的大小
{
int toPop = _size - _userMax; // 计算需要移除的文件数量
while (toPop > 0) // 当还有文件需要移除时
{
::RemoveMenu(_hMenu, _lrfl.back()._id, MF_BYCOMMAND); // 从菜单中移除该ID对应的菜单项
setAvailable(_lrfl.back()._id); // 将该ID标记为可用可能是为了下次添加时重复使用
_lrfl.pop_back(); // 从列表中移除该元素
toPop--; // 减少剩余需要移除的文件数量
_size--; // 减少当前列表大小
}
updateMenu(); // 更新菜单
_size = _userMax; // 将当前列表大小设置为新设置的大小
}
}
// 将最近的文件列表保存到配置文件中。保存的文件名顺序与加载时相同。
void LastRecentFileList::saveLRFL()
{
NppParameters& nppParams = NppParameters::getInstance();
if (nppParams.writeRecentFileHistorySettings(_userMax))
{
for (int i = _size - 1; i >= 0; i--) //reverse order: so loading goes in correct order
{
nppParams.writeHistory(_lrfl.at(i)._name.c_str());
}
}
NppParameters& nppParams = NppParameters::getInstance(); // 获取NppParameters的实例引用
if (nppParams.writeRecentFileHistorySettings(_userMax)) // 如果成功写入最近的文件历史设置
{
for (int i = _size - 1; i >= 0; i--) // 按照从后往前的顺序保存文件名,确保加载时的顺序正确
{
nppParams.writeHistory(_lrfl.at(i)._name.c_str()); // 将文件名写入配置文件的历史记录部分
}
}
}
int LastRecentFileList::find(const TCHAR *fn)
// 在最近的文件列表中查找指定的文件名。
int LastRecentFileList::find(const TCHAR* fn)
{
for (int i = 0; i < _size; ++i)
{
if (OrdinalIgnoreCaseCompareStrings(_lrfl.at(i)._name.c_str(), fn) == 0)
{
return i;
}
}
return -1;
for (int i = 0; i < _size; ++i) // 遍历整个列表
{
if (OrdinalIgnoreCaseCompareStrings(_lrfl.at(i)._name.c_str(), fn) == 0) // 如果找到匹配的文件名(忽略大小写)
{
return i; // 返回该文件在列表中的索引
}
}
return -1; // 如果未找到,返回-1
}
int LastRecentFileList::popFirstAvailableID()
// 弹出第一个可用的ID。
int LastRecentFileList::popFirstAvailableID()
{
for (int i = 0 ; i < NB_MAX_LRF_FILE ; ++i)
{
if (_idFreeArray[i])
{
_idFreeArray[i] = false;
return i + _idBase;
}
}
return 0;
for (int i = 0; i < NB_MAX_LRF_FILE; ++i) // 遍历所有可能的ID
{
if (_idFreeArray[i]) // 如果该ID可用未被使用
{
_idFreeArray[i] = false; // 标记该ID为已使用
return i + _idBase; // 返回该ID的值从_idBase开始计算
}
}
return 0; // 如果所有ID都已使用返回0或默认值
}
// 设置指定的ID为可用。
void LastRecentFileList::setAvailable(int id)
{
int index = id - _idBase;
_idFreeArray[index] = true;
int index = id - _idBase; // 根据ID计算其在_idFreeArray中的索引
_idFreeArray[index] = true; // 将该索引对应的值设置为true表示该ID可用
}

Loading…
Cancel
Save