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

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

@ -20,11 +20,11 @@
#include "Common.h" // for generic_string #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 softerBackground = 0;
COLORREF hotBackground = 0; COLORREF hotBackground = 0;
COLORREF pureBackground = 0; COLORREF pureBackground = 0;
@ -38,30 +38,30 @@ namespace NppDarkMode
COLORREF disabledEdge = 0; COLORREF disabledEdge = 0;
}; };
struct Options struct Options //Options选项结构体
{ {
bool enable = false; bool enable = false;
bool enableMenubar = false; bool enableMenubar = false;
bool enablePlugin = false; bool enablePlugin = false;
}; };
struct NppDarkModeParams struct NppDarkModeParams //params参数结构体
{ {
const wchar_t* _themeClassName = nullptr; const wchar_t* _themeClassName = nullptr;
bool _subclass = false; bool _subclass = false;
bool _theme = false; bool _theme = false;
}; };
enum class ToolTipsType enum class ToolTipsType //域内枚举类型为ToolTipsType
{ {
tooltip, tooltip, //括号里是常量
toolbar, toolbar,
listview, listview,
treeview, treeview,
tabbar tabbar
}; };
enum ColorTone { enum ColorTone { //色温
blackTone = 0, blackTone = 0,
redTone = 1, redTone = 1,
greenTone = 2, greenTone = 2,
@ -72,14 +72,14 @@ namespace NppDarkMode
customizedTone = 32 customizedTone = 32
}; };
enum class TreeViewStyle enum class TreeViewStyle //风格
{ {
classic = 0, classic = 0,
light = 1, light = 1,
dark = 2 dark = 2
}; };
struct AdvOptDefaults struct AdvOptDefaults //默认选项
{ {
generic_string _xmlFileName; generic_string _xmlFileName;
int _toolBarIconSet = -1; int _toolBarIconSet = -1;
@ -87,7 +87,7 @@ namespace NppDarkMode
bool _tabUseTheme = false; bool _tabUseTheme = false;
}; };
struct AdvancedOptions struct AdvancedOptions //高级选项
{ {
bool _enableWindowsMode = false; bool _enableWindowsMode = false;
@ -108,7 +108,7 @@ namespace NppDarkMode
bool isWindowsModeEnabled(); bool isWindowsModeEnabled();
void setWindowsMode(bool enable); void setWindowsMode(bool enable);
generic_string getThemeName(); generic_string getThemeName(); //generic_string 类
void setThemeName(const generic_string& newThemeName); void setThemeName(const generic_string& newThemeName);
int getToolBarIconSet(bool useDark); int getToolBarIconSet(bool useDark);
void setToolBarIconSet(int state2Set, bool useDark); void setToolBarIconSet(int state2Set, bool useDark);
@ -119,7 +119,7 @@ namespace NppDarkMode
bool isWindows10(); bool isWindows10();
bool isWindows11(); bool isWindows11();
DWORD getWindowsBuildNumber(); DWORD getWindowsBuildNumber(); //DWORD 就是 Double Word 每个word为2个字节的长度DWORD 双字即为4个字节每个字节是8位共32位。
COLORREF invertLightness(COLORREF c); COLORREF invertLightness(COLORREF c);
COLORREF invertLightnessSofter(COLORREF c); COLORREF invertLightnessSofter(COLORREF c);
@ -142,7 +142,7 @@ namespace NppDarkMode
COLORREF getHotEdgeColor(); COLORREF getHotEdgeColor();
COLORREF getDisabledEdgeColor(); COLORREF getDisabledEdgeColor();
HBRUSH getBackgroundBrush(); HBRUSH getBackgroundBrush(); //HBRUSH 取画刷
HBRUSH getDarkerBackgroundBrush(); HBRUSH getDarkerBackgroundBrush();
HBRUSH getSofterBackgroundBrush(); HBRUSH getSofterBackgroundBrush();
HBRUSH getHotBackgroundBrush(); HBRUSH getHotBackgroundBrush();
@ -152,7 +152,7 @@ namespace NppDarkMode
HBRUSH getHotEdgeBrush(); HBRUSH getHotEdgeBrush();
HBRUSH getDisabledEdgeBrush(); HBRUSH getDisabledEdgeBrush();
HPEN getDarkerTextPen(); HPEN getDarkerTextPen(); //画笔
HPEN getEdgePen(); HPEN getEdgePen();
HPEN getHotEdgePen(); HPEN getHotEdgePen();
HPEN getDisabledEdgePen(); HPEN getDisabledEdgePen();
@ -175,12 +175,12 @@ namespace NppDarkMode
Colors getDarkModeDefaultColors(); Colors getDarkModeDefaultColors();
void changeCustomTheme(const Colors& colors); void changeCustomTheme(const Colors& colors);
// handle events // handle events 处理事件
void handleSettingChange(HWND hwnd, LPARAM lParam, bool isFromBtn = false); void handleSettingChange(HWND hwnd, LPARAM lParam, bool isFromBtn = false);
bool isDarkModeReg(); bool isDarkModeReg();
// processes messages related to UAH / custom menubar drawing. // processes messages related to UAH / custom menubar drawing. 处理相关信息
// return true if handled, false to continue with normal processing in your wndproc // 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); bool runUAHWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam, LRESULT* lr);
void drawUAHMenuNCBottomLine(HWND hWnd); void drawUAHMenuNCBottomLine(HWND hWnd);
@ -191,7 +191,7 @@ namespace NppDarkMode
bool allowDarkModeForWindow(HWND hWnd, bool allow); bool allowDarkModeForWindow(HWND hWnd, bool allow);
void setTitleBarThemeColor(HWND hWnd); void setTitleBarThemeColor(HWND hWnd);
// enhancements to DarkMode.h // enhancements to DarkMode.h 对于DarkMode.h的改进
void enableDarkScrollBarForWindowAndChildren(HWND hwnd); void enableDarkScrollBarForWindowAndChildren(HWND hwnd);
inline void paintRoundFrameRect(HDC hdc, const RECT rect, const HPEN hpen, int width = 0, int height = 0); 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(); bool isThemeDark();
void setBorder(HWND hwnd, bool border = true); 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(); void setDarkAutoCompletion();
LRESULT onCtlColor(HDC hdc); LRESULT onCtlColor(HDC hdc); //LRESULT是一个数据类型指的是从窗口程序或者回调函数返回的32位值
LRESULT onCtlColorSofter(HDC hdc); LRESULT onCtlColorSofter(HDC hdc);
LRESULT onCtlColorDarker(HDC hdc); LRESULT onCtlColorDarker(HDC hdc);
LRESULT onCtlColorError(HDC hdc); LRESULT onCtlColorError(HDC hdc);
LRESULT onCtlColorDarkerBGStaticText(HDC hdc, bool isTextEnabled); 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; bool DocTabView::_hideTabBarStatus = false;
//向标签视图添加新的缓冲区,首先检查缓冲区是否有效(不是无效的缓冲区),然后检查是否已经存在相同的缓冲区。如果缓冲区有效且尚未存在,则将其添加到标签页视图中,并更新父窗口的大小。
void DocTabView::addBuffer(BufferID buffer) void DocTabView::addBuffer(BufferID buffer)
{ {
if (buffer == BUFFER_INVALID) //valid only if (buffer == BUFFER_INVALID) //valid only
return; return;
if (getIndexByBuffer(buffer) != -1) //no duplicates if (getIndexByBuffer(buffer) != -1) //no duplicates
return; return;
Buffer * buf = MainFileManager.getBufferByID(buffer); Buffer* buf = MainFileManager.getBufferByID(buffer);
TCITEM tie{}; TCITEM tie{};
tie.mask = TCIF_TEXT | TCIF_IMAGE | TCIF_PARAM; tie.mask = TCIF_TEXT | TCIF_IMAGE | TCIF_PARAM;
@ -40,7 +40,7 @@ void DocTabView::addBuffer(BufferID buffer)
if (_hasImgLst) if (_hasImgLst)
index = 0; index = 0;
tie.iImage = index; tie.iImage = index;
tie.pszText = const_cast<TCHAR *>(buf->getFileName()); tie.pszText = const_cast<TCHAR*>(buf->getFileName());
tie.lParam = reinterpret_cast<LPARAM>(buffer); tie.lParam = reinterpret_cast<LPARAM>(buffer);
::SendMessage(_hSelf, TCM_INSERTITEM, _nbItem++, reinterpret_cast<LPARAM>(&tie)); ::SendMessage(_hSelf, TCM_INSERTITEM, _nbItem++, reinterpret_cast<LPARAM>(&tie));
bufferUpdated(buf, BufferChangeMask); bufferUpdated(buf, BufferChangeMask);
@ -48,25 +48,25 @@ void DocTabView::addBuffer(BufferID buffer)
::SendMessage(_hParent, WM_SIZE, 0, 0); ::SendMessage(_hParent, WM_SIZE, 0, 0);
} }
//关闭指定的缓冲区,到要关闭的缓冲区的索引,然后从标签页视图中删除它,并通知父窗口进行调整。
void DocTabView::closeBuffer(BufferID buffer) void DocTabView::closeBuffer(BufferID buffer)
{ {
int indexToClose = getIndexByBuffer(buffer); int indexToClose = getIndexByBuffer(buffer);
deletItemAt((size_t)indexToClose); deletItemAt((size_t)indexToClose);
::SendMessage(_hParent, WM_SIZE, 0, 0); ::SendMessage(_hParent, WM_SIZE, 0, 0);
} }
//为特定的标签设置颜色。根据提供的缓冲区ID设置该缓冲区在标签页中的颜色。
void DocTabView::setIndividualTabColour(BufferID bufferId, int colorId) void DocTabView::setIndividualTabColour(BufferID bufferId, int colorId)
{ {
bufferId->setDocColorId(colorId); bufferId->setDocColorId(colorId);
} }
//获取特定标签的颜色,根据提供的标签索引,返回该标签的颜色。
int DocTabView::getIndividualTabColour(int tabIndex) int DocTabView::getIndividualTabColour(int tabIndex)
{ {
BufferID bufferId = getBufferByIndex(tabIndex); BufferID bufferId = getBufferByIndex(tabIndex);
return bufferId->getDocColorId(); return bufferId->getDocColorId();
} }
//激活特定的缓冲区通过缓冲区的ID找到其索引位置并尝试激活该缓冲区如果成功则返回true否则返回false。
bool DocTabView::activateBuffer(BufferID buffer) bool DocTabView::activateBuffer(BufferID buffer)
{ {
int indexToActivate = getIndexByBuffer(buffer); int indexToActivate = getIndexByBuffer(buffer);
@ -77,15 +77,15 @@ bool DocTabView::activateBuffer(BufferID buffer)
return true; return true;
} }
//获取当前激活的缓冲区。
BufferID DocTabView::activeBuffer() BufferID DocTabView::activeBuffer()
{ {
int index = getCurrentTabIndex(); int index = getCurrentTabIndex();
return getBufferByIndex(index); return getBufferByIndex(index);
} }
//遍历所有标签页根据文件名查找匹配的缓冲区找到则返回其ID否则返回BUFFER_INVALID。
BufferID DocTabView::findBufferByName(const TCHAR * fullfilename) //-1 if not found, something else otherwise BufferID DocTabView::findBufferByName(const TCHAR* fullfilename) //-1 if not found, something else otherwise
{ {
TCITEM tie{}; TCITEM tie{};
tie.lParam = -1; 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)); ::SendMessage(_hSelf, TCM_GETITEM, i, reinterpret_cast<LPARAM>(&tie));
BufferID id = reinterpret_cast<BufferID>(tie.lParam); BufferID id = reinterpret_cast<BufferID>(tie.lParam);
Buffer * buf = MainFileManager.getBufferByID(id); Buffer* buf = MainFileManager.getBufferByID(id);
if (OrdinalIgnoreCaseCompareStrings(fullfilename, buf->getFullPathName()) == 0) if (OrdinalIgnoreCaseCompareStrings(fullfilename, buf->getFullPathName()) == 0)
{ {
return id; return id;
@ -103,7 +103,7 @@ BufferID DocTabView::findBufferByName(const TCHAR * fullfilename) //-1 if not fo
return BUFFER_INVALID; return BUFFER_INVALID;
} }
//通过缓冲区ID找到其在标签中的索引位置如果不存在则返回 - 1。
int DocTabView::getIndexByBuffer(BufferID id) int DocTabView::getIndexByBuffer(BufferID id)
{ {
TCITEM tie{}; TCITEM tie{};
@ -118,7 +118,7 @@ int DocTabView::getIndexByBuffer(BufferID id)
return -1; return -1;
} }
//通过缓冲区ID找到其在标签中的索引位置如果不存在则返回-1。
BufferID DocTabView::getBufferByIndex(size_t index) BufferID DocTabView::getBufferByIndex(size_t index)
{ {
TCITEM tie{}; TCITEM tie{};
@ -129,8 +129,8 @@ BufferID DocTabView::getBufferByIndex(size_t index)
return reinterpret_cast<BufferID>(tie.lParam); return reinterpret_cast<BufferID>(tie.lParam);
} }
//根据mask中的标志位更新与缓冲区相关的信息例如文件名变化、只读状态变化等。
void DocTabView::bufferUpdated(Buffer * buffer, int mask) void DocTabView::bufferUpdated(Buffer* buffer, int mask)
{ {
int index = getIndexByBuffer(buffer->getID()); int index = getIndexByBuffer(buffer->getID());
if (index == -1) if (index == -1)
@ -143,7 +143,7 @@ void DocTabView::bufferUpdated(Buffer * buffer, int mask)
if (mask & BufferChangeReadonly || mask & BufferChangeDirty) if (mask & BufferChangeReadonly || mask & BufferChangeDirty)
{ {
tie.mask |= TCIF_IMAGE; 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()) if (buffer->isMonitoringOn())
{ {
tie.iImage = MONITORING_IMG_INDEX; 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. //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) while (*in != 0)
if (*in == '&') if (*in == '&')
{ {
*out++ = '&';
*out++ = '&';
while (*(++in) == '&')
*out++ = '&'; *out++ = '&';
} *out++ = '&';
else while (*(++in) == '&')
*out++ = *in++; *out++ = '&';
}
else
*out++ = *in++;
*out = '\0'; *out = '\0';
} }
} }
@ -192,7 +192,7 @@ void DocTabView::bufferUpdated(Buffer * buffer, int mask)
::SendMessage(_hParent, WM_SIZE, 0, 0); ::SendMessage(_hParent, WM_SIZE, 0, 0);
} }
//根据给定的索引设置相应的缓冲区ID并更新标签显示的相关信息。
void DocTabView::setBuffer(size_t index, BufferID id) void DocTabView::setBuffer(size_t index, BufferID id)
{ {
if (index >= _nbItem) if (index >= _nbItem)
@ -208,8 +208,8 @@ void DocTabView::setBuffer(size_t index, BufferID id)
::SendMessage(_hParent, WM_SIZE, 0, 0); ::SendMessage(_hParent, WM_SIZE, 0, 0);
} }
//根据隐藏/显示标签栏状态,调整标签页视图和文本编辑器视图的大小,并根据需要发送消息以更新可点击链接。
void DocTabView::reSizeTo(RECT & rc) void DocTabView::reSizeTo(RECT& rc)
{ {
int borderWidth = ((NppParameters::getInstance()).getSVP())._borderWidth; int borderWidth = ((NppParameters::getInstance()).getSVP())._borderWidth;
if (_hideTabBarStatus) if (_hideTabBarStatus)
@ -221,9 +221,9 @@ void DocTabView::reSizeTo(RECT & rc)
else else
{ {
TabBar::reSizeTo(rc); TabBar::reSizeTo(rc);
rc.left += borderWidth; rc.left += borderWidth;
rc.right -= borderWidth * 2; rc.right -= borderWidth * 2;
rc.top += borderWidth; rc.top += borderWidth;
rc.bottom -= (borderWidth * 2); rc.bottom -= (borderWidth * 2);
_pView->reSizeTo(rc); _pView->reSizeTo(rc);
} }

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

@ -23,6 +23,9 @@
#include "Common.h" #include "Common.h"
#include "Utf8.h" #include "Utf8.h"
```cpp
using namespace std; using namespace std;
FindOption * FindReplaceDlg::_env; FindOption * FindReplaceDlg::_env;
@ -35,12 +38,15 @@ void addText2Combo(const TCHAR * txt2add, HWND hCombo)
if (!hCombo) return; if (!hCombo) return;
if (!lstrcmp(txt2add, TEXT(""))) return; if (!lstrcmp(txt2add, TEXT(""))) return;
// 在组合框中查找是否已存在相同的文本
auto i = ::SendMessage(hCombo, CB_FINDSTRINGEXACT, static_cast<WPARAM>(-1), reinterpret_cast<LPARAM>(txt2add)); 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); ::SendMessage(hCombo, CB_DELETESTRING, i, 0);
} }
// 向组合框中插入新的文本,并设置为当前选中项
i = ::SendMessage(hCombo, CB_INSERTSTRING, 0, reinterpret_cast<LPARAM>(txt2add)); i = ::SendMessage(hCombo, CB_INSERTSTRING, 0, reinterpret_cast<LPARAM>(txt2add));
::SendMessage(hCombo, CB_SETCURSEL, i, 0); ::SendMessage(hCombo, CB_SETCURSEL, i, 0);
} }
@ -59,6 +65,8 @@ void delLeftWordInEdit(HWND hEdit)
WORD cursor = 0; WORD cursor = 0;
::SendMessage(hEdit, EM_GETSEL, (WPARAM)&cursor, 0); ::SendMessage(hEdit, EM_GETSEL, (WPARAM)&cursor, 0);
WORD wordstart = cursor; WORD wordstart = cursor;
// 删除光标左边的单词
while (wordstart > 0) { while (wordstart > 0) {
TCHAR c = str[wordstart - 1]; TCHAR c = str[wordstart - 1];
if (c != ' ' && c != '\t') if (c != ' ' && c != '\t')
@ -83,6 +91,7 @@ LRESULT run_swapButtonProc(WNDPROC oldEditProc, HWND hwnd, UINT message, WPARAM
{ {
case WM_RBUTTONUP: case WM_RBUTTONUP:
{ {
// 模拟右键点击事件,发送给父窗口处理
::SendMessage(GetParent(hwnd), message, wParam, lParam); ::SendMessage(GetParent(hwnd), message, wParam, lParam);
break; 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) 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 i = 0, j = 0;
int charLeft = length; int charLeft = length;
TCHAR current; TCHAR current;
while (i < length) 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]; current = query[i];
--charLeft; --charLeft;
if (current == '\\' && charLeft) if (current == '\\' && charLeft)
{ //possible escape sequence {
++i; ++i;
--charLeft; --charLeft;
current = query[i]; current = query[i];
switch(current) switch(current)
{ {
case 'r': case 'r':
@ -131,24 +143,26 @@ int Searching::convertExtendedToString(const TCHAR * query, TCHAR * result, int
case 'u': case 'u':
{ {
int size = 0, base = 0; int size = 0, base = 0;
// 根据转义序列的类型设置不同的大小和进制
if (current == 'b') if (current == 'b')
{ //11111111 {
size = 8, base = 2; size = 8, base = 2;
} }
else if (current == 'o') else if (current == 'o')
{ //377 {
size = 3, base = 8; size = 3, base = 8;
} }
else if (current == 'd') else if (current == 'd')
{ //255 {
size = 3, base = 10; size = 3, base = 10;
} }
else if (current == 'x') else if (current == 'x')
{ //0xFF {
size = 2, base = 16; size = 2, base = 16;
} }
else if (current == 'u') else if (current == 'u')
{ //0xCDCD {
size = 4, base = 16; size = 4, base = 16;
} }
@ -162,12 +176,14 @@ int Searching::convertExtendedToString(const TCHAR * query, TCHAR * result, int
break; break;
} }
} }
//not enough chars to make parameter, use default method as fallback
// 字符不足以构成参数,则使用默认方法作为备选方案
[[fallthrough]]; [[fallthrough]];
} }
default: default:
{ //unknown sequence, treat as regular text {
// 未知序列,当做普通文本处理
result[j] = '\\'; result[j] = '\\';
++j; ++j;
result[j] = current; result[j] = current;
@ -182,6 +198,7 @@ int Searching::convertExtendedToString(const TCHAR * query, TCHAR * result, int
++i; ++i;
++j; ++j;
} }
result[j] = 0; result[j] = 0;
return j; return j;
} }
@ -195,6 +212,7 @@ bool Searching::readBase(const TCHAR * str, int * value, int base, int size)
while (i < size) while (i < size)
{ {
current = str[i]; current = str[i];
if (current >= 'A') if (current >= 'A')
{ {
current &= 0xdf; 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) 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, posStart));
pEditView->execute(SCI_ENSUREVISIBLE, pEditView->execute(SCI_LINEFROMPOSITION, posEnd)); 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_SETVISIBLEPOLICY, CARET_JUMPS | CARET_EVEN);
pEditView->execute(SCI_ENSUREVISIBLEENFORCEPOLICY, pEditView->execute(SCI_LINEFROMPOSITION, isDownwards ? posEnd : posStart)); 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_GOTOPOS, isDownwards ? posEnd : posStart);
pEditView->execute(SCI_SETVISIBLEPOLICY, CARET_EVEN); pEditView->execute(SCI_SETVISIBLEPOLICY, CARET_EVEN);
pEditView->execute(SCI_ENSUREVISIBLEENFORCEPOLICY, pEditView->execute(SCI_LINEFROMPOSITION, isDownwards ? posEnd : posStart)); 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); pEditView->execute(SCI_SCROLLRANGE, posStart, posEnd);
// Move cursor to end of result and select result // 将光标移到结果的末尾并选中结果
pEditView->execute(SCI_GOTOPOS, posEnd); pEditView->execute(SCI_GOTOPOS, posEnd);
pEditView->execute(SCI_SETANCHOR, posStart); pEditView->execute(SCI_SETANCHOR, posStart);
// Update Scintilla's knowledge about what column the caret is in, so that if user // 更新 Scintilla 中光标所在列的位置信息,以防用户在选择搜索结果后使用上下箭头导航时光标跳到意外的列
// does up/down arrow as first navigation after the search result is selected,
// the caret doesn't jump to an unexpected column
pEditView->execute(SCI_CHOOSECARETX); pEditView->execute(SCI_CHOOSECARETX);
} }
WNDPROC FindReplaceDlg::originalFinderProc = nullptr; WNDPROC FindReplaceDlg::originalFinderProc = nullptr;
WNDPROC FindReplaceDlg::originalComboEditProc = nullptr; WNDPROC FindReplaceDlg::originalComboEditProc = nullptr;
```
// important : to activate all styles // important : to activate all styles
const int STYLING_MASK = 255; const int STYLING_MASK = 255;
```cpp
// 定义 FindReplaceDlg 类的析构函数
FindReplaceDlg::~FindReplaceDlg() FindReplaceDlg::~FindReplaceDlg()
{ {
_tab.destroy(); _tab.destroy(); // 销毁标签页控件
delete _pFinder; delete _pFinder; // 删除查找对象指针
// 删除与查找对象相关的所有查找器对象
for (int n = static_cast<int32_t>(_findersOfFinder.size()) - 1; n >= 0; n--) for (int n = static_cast<int32_t>(_findersOfFinder.size()) - 1; n >= 0; n--)
{ {
delete _findersOfFinder[n]; delete _findersOfFinder[n];
_findersOfFinder.erase(_findersOfFinder.begin() + n); _findersOfFinder.erase(_findersOfFinder.begin() + n);
} }
// 销毁窗口句柄
if (_shiftTrickUpTip) if (_shiftTrickUpTip)
::DestroyWindow(_shiftTrickUpTip); ::DestroyWindow(_shiftTrickUpTip);
if (_2ButtonsTip) if (_2ButtonsTip)
::DestroyWindow(_2ButtonsTip); ::DestroyWindow(_2ButtonsTip);
if (_filterTip) if (_filterTip)
::DestroyWindow(_filterTip); ::DestroyWindow(_filterTip);
// 释放字体对象
if (_hMonospaceFont) if (_hMonospaceFont)
::DeleteObject(_hMonospaceFont); ::DeleteObject(_hMonospaceFont);
if (_hLargerBolderFont) if (_hLargerBolderFont)
::DeleteObject(_hLargerBolderFont); ::DeleteObject(_hLargerBolderFont);
if (_hCourrierNewFont) if (_hCourrierNewFont)
::DeleteObject(_hCourrierNewFont); ::DeleteObject(_hCourrierNewFont);
delete[] _uniFileName; delete[] _uniFileName; // 释放存储文件名的数组内存
} }
// 创建 FindReplaceDlg 对话框
void FindReplaceDlg::create(int dialogID, bool isRTL, bool msgDestParent, bool toShow) void FindReplaceDlg::create(int dialogID, bool isRTL, bool msgDestParent, bool toShow)
{ {
// 创建静态对话框
StaticDialog::create(dialogID, isRTL, msgDestParent); StaticDialog::create(dialogID, isRTL, msgDestParent);
fillFindHistory(); fillFindHistory(); // 填充查找历史记录
_currentStatus = REPLACE_DLG; _currentStatus = REPLACE_DLG; // 设置当前状态为替换对话框
initOptionsFromDlg(); initOptionsFromDlg(); // 从对话框初始化选项
_statusBar.init(GetModuleHandle(NULL), _hSelf, 0); _statusBar.init(GetModuleHandle(NULL), _hSelf, 0); // 初始化状态栏
_statusBar.display(); _statusBar.display(); // 显示状态栏
// 获取 DPI 管理器
DPIManager& dpiManager = NppParameters::getInstance()._dpiManager; DPIManager& dpiManager = NppParameters::getInstance()._dpiManager;
RECT rect{}; RECT rect{};
getClientRect(rect); getClientRect(rect); // 获取客户区矩形
_tab.init(_hInst, _hSelf, false, true); _tab.init(_hInst, _hSelf, false, true); // 初始化标签页控件
NppDarkMode::subclassTabControl(_tab.getHSelf()); NppDarkMode::subclassTabControl(_tab.getHSelf()); // 子类化标签页控件以适配暗黑模式
int tabDpiDynamicalHeight = dpiManager.scaleY(13); int tabDpiDynamicalHeight = dpiManager.scaleY(13); // 根据 DPI 缩放标签页高度
_tab.setFont(TEXT("Tahoma"), tabDpiDynamicalHeight); _tab.setFont(TEXT("Tahoma"), tabDpiDynamicalHeight); // 设置标签页字体
// 插入标签页内容
const TCHAR *find = TEXT("Find"); const TCHAR *find = TEXT("Find");
const TCHAR *replace = TEXT("Replace"); const TCHAR *replace = TEXT("Replace");
const TCHAR *findInFiles = TEXT("Find in Files"); const TCHAR *findInFiles = TEXT("Find in Files");
const TCHAR *findInProjects = TEXT("Find in Projects"); const TCHAR *findInProjects = TEXT("Find in Projects");
const TCHAR *mark = TEXT("Mark"); const TCHAR *mark = TEXT("Mark");
_tab.insertAtEnd(find); _tab.insertAtEnd(find);
_tab.insertAtEnd(replace); _tab.insertAtEnd(replace);
_tab.insertAtEnd(findInFiles); _tab.insertAtEnd(findInFiles);
_tab.insertAtEnd(findInProjects); _tab.insertAtEnd(findInProjects);
_tab.insertAtEnd(mark); _tab.insertAtEnd(mark);
_tab.reSizeTo(rect); // 调整标签页大小以适应客户区
_tab.display(); // 显示标签页
_tab.reSizeTo(rect); _initialClientWidth = rect.right - rect.left; // 记录初始客户区宽度
_tab.display();
_initialClientWidth = rect.right - rect.left;
//fill min dialog size info // 填充最小对话框大小信息
getWindowRect(_initialWindowRect); getWindowRect(_initialWindowRect);
_initialWindowRect.right = _initialWindowRect.right - _initialWindowRect.left + dpiManager.scaleX(10); _initialWindowRect.right = _initialWindowRect.right - _initialWindowRect.left + dpiManager.scaleX(10);
_initialWindowRect.left = 0; _initialWindowRect.left = 0;
@ -335,88 +358,65 @@ void FindReplaceDlg::create(int dialogID, bool isRTL, bool msgDestParent, bool t
NppGUI& nppGUI = nppParam.getNppGUI(); NppGUI& nppGUI = nppParam.getNppGUI();
const UINT swpFlags = toShow ? SWP_SHOWWINDOW : SWP_HIDEWINDOW; 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); RECT rc = getViewablePositionRect(nppGUI._findWindowPos);
::SetWindowPos(_hSelf, HWND_TOP, rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top, swpFlags); ::SetWindowPos(_hSelf, HWND_TOP, rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top, swpFlags);
} }
else else
{ {
goToCenter(swpFlags); goToCenter(swpFlags); // 居中显示
} }
// 获取状态栏客户区矩形
RECT rcStatusBar{}; RECT rcStatusBar{};
::GetClientRect(_statusBar.getHSelf(), &rcStatusBar); ::GetClientRect(_statusBar.getHSelf(), &rcStatusBar);
_lesssModeHeight = (countRc.bottom - dlgRc.top) + (rcStatusBar.bottom - rcStatusBar.top) + dpiManager.scaleY(10); _lesssModeHeight = (countRc.bottom - dlgRc.top) + (rcStatusBar.bottom - rcStatusBar.top) + dpiManager.scaleY(10);
if (nppGUI._findWindowLessMode) 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; nppGUI._findWindowLessMode = false;
::SendMessage(_hSelf, WM_COMMAND, IDD_RESIZE_TOGGLE_BUTTON, 0); ::SendMessage(_hSelf, WM_COMMAND, IDD_RESIZE_TOGGLE_BUTTON, 0);
} }
} }
// 填充查找历史记录
void FindReplaceDlg::fillFindHistory() void FindReplaceDlg::fillFindHistory()
{ {
NppParameters& nppParams = NppParameters::getInstance(); NppParameters& nppParams = NppParameters::getInstance();
FindHistory & findHistory = nppParams.getFindHistory(); FindHistory & findHistory = nppParams.getFindHistory();
// 填充各个 Combo Box 的历史记录
fillComboHistory(IDFINDWHAT, findHistory._findHistoryFinds); fillComboHistory(IDFINDWHAT, findHistory._findHistoryFinds);
fillComboHistory(IDREPLACEWITH, findHistory._findHistoryReplaces); fillComboHistory(IDREPLACEWITH, findHistory._findHistoryReplaces);
fillComboHistory(IDD_FINDINFILES_FILTERS_COMBO, findHistory._findHistoryFilters); fillComboHistory(IDD_FINDINFILES_FILTERS_COMBO, findHistory._findHistoryFilters);
fillComboHistory(IDD_FINDINFILES_DIR_COMBO, findHistory._findHistoryPaths); fillComboHistory(IDD_FINDINFILES_DIR_COMBO, findHistory._findHistoryPaths);
// 设置各个复选框的选中状态
::SendDlgItemMessage(_hSelf, IDWRAP, BM_SETCHECK, findHistory._isWrap, 0); ::SendDlgItemMessage(_hSelf, IDWRAP, BM_SETCHECK, findHistory._isWrap, 0);
::SendDlgItemMessage(_hSelf, IDWHOLEWORD, BM_SETCHECK, findHistory._isMatchWord, 0); ::SendDlgItemMessage(_hSelf, IDWHOLEWORD, BM_SETCHECK, findHistory._isMatchWord, 0);
::SendDlgItemMessage(_hSelf, IDMATCHCASE, BM_SETCHECK, findHistory._isMatchCase, 0); ::SendDlgItemMessage(_hSelf, IDMATCHCASE, BM_SETCHECK, findHistory._isMatchCase, 0);
::SendDlgItemMessage(_hSelf, IDC_BACKWARDDIRECTION, BM_SETCHECK, !findHistory._isDirectionDown, 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()) if (nppParams.isTransparentAvailable())
{ {
// 显示透明度相关控件
showFindDlgItem(IDC_TRANSPARENT_CHECK); showFindDlgItem(IDC_TRANSPARENT_CHECK);
showFindDlgItem(IDC_TRANSPARENT_GRPBOX); showFindDlgItem(IDC_TRANSPARENT_GRPBOX);
showFindDlgItem(IDC_TRANSPARENT_LOSSFOCUS_RADIO); showFindDlgItem(IDC_TRANSPARENT_LOSSFOCUS_RADIO);
showFindDlgItem(IDC_TRANSPARENT_ALWAYS_RADIO); showFindDlgItem(IDC_TRANSPARENT_ALWAYS_RADIO);
showFindDlgItem(IDC_PERCENTAGE_SLIDER); showFindDlgItem(IDC_PERCENTAGE_SLIDER);
// 设置滑动条范围和位置
::SendDlgItemMessage(_hSelf, IDC_PERCENTAGE_SLIDER, TBM_SETRANGE, FALSE, MAKELONG(20, 200)); ::SendDlgItemMessage(_hSelf, IDC_PERCENTAGE_SLIDER, TBM_SETRANGE, FALSE, MAKELONG(20, 200));
::SendDlgItemMessage(_hSelf, IDC_PERCENTAGE_SLIDER, TBM_SETPOS, TRUE, findHistory._transparency); ::SendDlgItemMessage(_hSelf, IDC_PERCENTAGE_SLIDER, TBM_SETPOS, TRUE, findHistory._transparency);
// 根据透明度模式设置相应的复选框选中状态
if (findHistory._transparencyMode == FindHistory::none) if (findHistory._transparencyMode == FindHistory::none)
{ {
enableFindDlgItem(IDC_TRANSPARENT_LOSSFOCUS_RADIO, false); enableFindDlgItem(IDC_TRANSPARENT_LOSSFOCUS_RADIO, false);
@ -436,44 +436,47 @@ void FindReplaceDlg::fillFindHistory()
{ {
id = IDC_TRANSPARENT_ALWAYS_RADIO; id = IDC_TRANSPARENT_ALWAYS_RADIO;
(NppParameters::getInstance()).SetTransparent(_hSelf, findHistory._transparency); (NppParameters::getInstance()).SetTransparent(_hSelf, findHistory._transparency);
} }
::SendDlgItemMessage(_hSelf, id, BM_SETCHECK, TRUE, 0); ::SendDlgItemMessage(_hSelf, id, BM_SETCHECK, TRUE, 0);
} }
} }
} }
// 填充 Combo Box 的历史记录
void FindReplaceDlg::fillComboHistory(int id, const vector<generic_string> & strings) void FindReplaceDlg::fillComboHistory(int id, const vector<generic_string> & strings)
{ {
HWND hCombo = ::GetDlgItem(_hSelf, id); HWND hCombo = ::GetDlgItem(_hSelf, id);
// 将历史记录添加到 Combo Box
for (vector<generic_string>::const_reverse_iterator i = strings.rbegin() ; i != strings.rend(); ++i) for (vector<generic_string>::const_reverse_iterator i = strings.rbegin() ; i != strings.rend(); ++i)
{ {
addText2Combo(i->c_str(), hCombo); 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()) if (!strings.empty() && strings.begin()->empty())
{ {
SetWindowText(hCombo, _T("")); SetWindowText(hCombo, _T(""));
return; return;
} }
::SendMessage(hCombo, CB_SETCURSEL, 0, 0); // select first item ::SendMessage(hCombo, CB_SETCURSEL, 0, 0); // 选择第一项
} }
// 保存查找历史记录
void FindReplaceDlg::saveFindHistory() void FindReplaceDlg::saveFindHistory()
{ {
if (! isCreated()) return; if (! isCreated()) return;
FindHistory& findHistory = (NppParameters::getInstance()).getFindHistory(); FindHistory& findHistory = (NppParameters::getInstance()).getFindHistory();
// 保存各个 Combo Box 的历史记录
saveComboHistory(IDD_FINDINFILES_DIR_COMBO, findHistory._nbMaxFindHistoryPath, findHistory._findHistoryPaths, false); saveComboHistory(IDD_FINDINFILES_DIR_COMBO, findHistory._nbMaxFindHistoryPath, findHistory._findHistoryPaths, false);
saveComboHistory(IDD_FINDINFILES_FILTERS_COMBO, findHistory._nbMaxFindHistoryFilter, findHistory._findHistoryFilters, true); saveComboHistory(IDD_FINDINFILES_FILTERS_COMBO, findHistory._nbMaxFindHistoryFilter, findHistory._findHistoryFilters, true);
saveComboHistory(IDFINDWHAT, findHistory._nbMaxFindHistoryFind, findHistory._findHistoryFinds, false); saveComboHistory(IDFINDWHAT, findHistory._nbMaxFindHistoryFind, findHistory._findHistoryFinds, false);
saveComboHistory(IDREPLACEWITH, findHistory._nbMaxFindHistoryReplace, findHistory._findHistoryReplaces, true); saveComboHistory(IDREPLACEWITH, findHistory._nbMaxFindHistoryReplace, findHistory._findHistoryReplaces, true);
} }
// 保存 Combo Box 的历史记录
int FindReplaceDlg::saveComboHistory(int id, int maxcount, vector<generic_string> & strings, bool saveEmpty) int FindReplaceDlg::saveComboHistory(int id, int maxcount, vector<generic_string> & strings, bool saveEmpty)
{ {
TCHAR text[FINDREPLACE_MAXLENGTH] = { '\0' }; TCHAR text[FINDREPLACE_MAXLENGTH] = { '\0' };
@ -485,6 +488,7 @@ int FindReplaceDlg::saveComboHistory(int id, int maxcount, vector<generic_string
strings.clear(); strings.clear();
// 如果允许保存空字符串,则检查 Combo Box 文本是否为空,并加入历史记录
if (saveEmpty) if (saveEmpty)
{ {
if (::GetWindowTextLength(hCombo) == 0) 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) for (int i = 0 ; i < count ; ++i)
{ {
auto cbTextLen = ::SendMessage(hCombo, CB_GETLBTEXTLEN, i, 0); auto cbTextLen = ::SendMessage(hCombo, CB_GETLBTEXTLEN, i, 0);
@ -504,13 +509,14 @@ int FindReplaceDlg::saveComboHistory(int id, int maxcount, vector<generic_string
} }
return count; return count;
} }
```
//更新数据Combo
void FindReplaceDlg::updateCombos() void FindReplaceDlg::updateCombos()
{ {
updateCombo(IDREPLACEWITH); updateCombo(IDREPLACEWITH);
updateCombo(IDFINDWHAT); updateCombo(IDFINDWHAT);
} }
//
void FindReplaceDlg::updateCombo(int comboID) void FindReplaceDlg::updateCombo(int comboID)
{ {
HWND hCombo = ::GetDlgItem(_hSelf, 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 3
// [ ] [ ] Y [ ] [ ] : pos_between 2 // [ ] [ ] Y [ ] [ ] : pos_between 2
// [ ] [ ] [ ] [ ] Y : pos_behind 4 // [ ] [ ] [ ] [ ] Y : pos_behind 4
```cpp
Finder::CurrentPosInLineInfo Finder::getCurrentPosInLineInfo(intptr_t currentPosInLine, const SearchResultMarkingLine& markingLine) const Finder::CurrentPosInLineInfo Finder::getCurrentPosInLineInfo(intptr_t currentPosInLine, const SearchResultMarkingLine& markingLine) const
{ {
CurrentPosInLineInfo cpili; // 定义用于返回的结构体
size_t count = 0; CurrentPosInLineInfo cpili;
intptr_t lastEnd = 0; // 初始化计数器count为0
auto selStart = _scintView.execute(SCI_GETSELECTIONSTART); size_t count = 0;
auto selEnd = _scintView.execute(SCI_GETSELECTIONEND); // 初始化上一个区间的结束位置为0
bool hasSel = (selEnd - selStart) != 0; intptr_t lastEnd = 0;
// 获取当前文本框选择的起始位置和结束位置
for (std::pair<intptr_t, intptr_t> range : markingLine._segmentPostions) auto selStart = _scintView.execute(SCI_GETSELECTIONSTART);
{ auto selEnd = _scintView.execute(SCI_GETSELECTIONEND);
++count; // 判断是否有选择文本
bool hasSel = (selEnd - selStart) != 0;
if (lastEnd <= currentPosInLine && currentPosInLine < range.first)
{ // 遍历每个区间
if (count == 1) for (std::pair<intptr_t, intptr_t> range : markingLine._segmentPostions)
{ {
cpili._status = pos_infront; ++count;
break;
} // 判断当前位置在区间的前面
else if (lastEnd <= currentPosInLine && currentPosInLine < range.first)
{ {
cpili._status = pos_between; if (count == 1)
cpili.auxiliaryInfo = count - 1; {
break; cpili._status = pos_infront; // 在第一个区间的前面
} break;
} }
else
if (range.first <= currentPosInLine && currentPosInLine <= range.second) {
{ cpili._status = pos_between; // 在两个区间之间
if (currentPosInLine == range.first && !hasSel) cpili.auxiliaryInfo = count - 1;
{ break;
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) if (range.first <= currentPosInLine && currentPosInLine <= range.second)
{ {
cpili._status = pos_between; if (currentPosInLine == range.first && !hasSel)
cpili.auxiliaryInfo = count; // c1 c2 {
// [ ]I [ ] : I is recongnized with c1, so auxiliaryInfo should be c1 cpili._status = pos_between; // 在区间的起始位置,在没有选择文本的情况下
} cpili.auxiliaryInfo = count - 1;
else }
{ else if (currentPosInLine == range.second && !hasSel)
cpili._status = pos_inside; {
cpili.auxiliaryInfo = count; cpili._status = pos_between; // 在区间的结束位置,在没有选择文本的情况下
} cpili.auxiliaryInfo = count;
break; }
} else
{
if (range.second < currentPosInLine) cpili._status = pos_inside; // 在区间内部
{ cpili.auxiliaryInfo = count;
if (markingLine._segmentPostions.size() == count) }
{ break;
cpili._status = pos_behind; }
cpili.auxiliaryInfo = count;
break; // 判断当前位置在区间的后面
} if (range.second < currentPosInLine)
} {
if (markingLine._segmentPostions.size() == count)
lastEnd = range.second; {
} 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) void Finder::anchorWithNoHeaderLines(intptr_t& currentL, intptr_t initL, intptr_t minL, intptr_t maxL, int direction)
{ {
if (currentL > maxL && direction == 0) // 如果当前行大于最大行并且方向为0则将当前行设置为最小行
currentL = minL; if (currentL > maxL && direction == 0)
currentL = minL;
while (_scintView.execute(SCI_GETFOLDLEVEL, currentL) & SC_FOLDLEVELHEADERFLAG)
{ // 循环直到当前行不是折叠标题行
currentL += direction == -1 ? -1 : 1; while (_scintView.execute(SCI_GETFOLDLEVEL, currentL) & SC_FOLDLEVELHEADERFLAG)
{
if (currentL > maxL) // 根据方向更新当前行
currentL = minL; currentL += direction == -1 ? -1 : 1;
else if (currentL < minL)
currentL = maxL; // 如果当前行超过最大行,则将当前行设置为最小行
if (currentL > maxL)
if (currentL == initL) currentL = minL;
break; // 如果当前行低于最小行,则将当前行设置为最大行
} 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) 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 currentPos = _scintView.execute(SCI_GETCURRENTPOS); auto total_lines = _scintView.execute(SCI_GETLINECOUNT);
intptr_t lno = _scintView.execute(SCI_LINEFROMPOSITION, currentPos); // 如果总行数小于等于1则直接返回
auto total_lines = _scintView.execute(SCI_GETLINECOUNT); if (total_lines <= 1) return;
if (total_lines <= 1) return;
// 获取当前行的起始位置和光标在行内的位置
auto lineStartAbsPos = _scintView.execute(SCI_POSITIONFROMLINE, lno); auto lineStartAbsPos = _scintView.execute(SCI_POSITIONFROMLINE, lno);
intptr_t currentPosInLine = currentPos - lineStartAbsPos; intptr_t currentPosInLine = currentPos - lineStartAbsPos;
auto init_lno = lno; auto init_lno = lno;
auto max_lno = _scintView.execute(SCI_GETLASTCHILD, lno, searchHeaderLevel); 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) assert(min_lno <= max_lno);
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);
}
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; if (lno > max_lno)
else if (lno < min_lno) lno = max_lno; lno = min_lno;
else if (lno < min_lno)
lno = max_lno;
// if (lno == init_lno)
// Set anchor and make sure that achor is not on the last (empty) line or head lines break;
// }
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) // 如果当前行与初始行不同
{ if (lno != init_lno)
auto extremityAbsoltePos = _scintView.execute(direction == -1 ? SCI_GETLINEENDPOSITION : SCI_POSITIONFROMLINE, lno); {
_scintView.execute(SCI_SETSEL, extremityAbsoltePos, extremityAbsoltePos); // 获取当前行的绝对位置
currentPos = extremityAbsoltePos; auto extremityAbsoltePos = _scintView.execute(direction == -1 ? SCI_GETLINEENDPOSITION : SCI_POSITIONFROMLINE, lno);
auto start = _scintView.execute(SCI_POSITIONFROMLINE, lno); // 设置选择范围为当前行的绝对位置
currentPosInLine = currentPos - start; _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 // 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" // 引入LastRecentFileList类的头文件
#include "menuCmdID.h" #include "lastRecentFileList.h"
#include "localization.h" // 引入菜单命令ID的头文件
#include "menuCmdID.h"
void LastRecentFileList::initMenu(HMENU hMenu, int idBase, int posBase, Accelerator *pAccelerator, bool doSubMenu) // 引入本地化的头文件,可能用于支持多语言
#include "localization.h"
// LastRecentFileList类的initMenu函数
void LastRecentFileList::initMenu(HMENU hMenu, int idBase, int posBase, Accelerator* pAccelerator, bool doSubMenu)
{ {
if (doSubMenu) // 如果doSubMenu为真表示需要创建一个弹出菜单
{ if (doSubMenu)
_hParentMenu = hMenu; {
_hMenu = ::CreatePopupMenu(); // 设置父菜单句柄
} _hParentMenu = hMenu;
else // 创建一个新的弹出菜单
{ _hMenu = ::CreatePopupMenu();
_hParentMenu = NULL; }
_hMenu = hMenu; // 如果doSubMenu为假表示直接使用传入的菜单句柄
} else
{
_idBase = idBase; // 设置父菜单句柄为NULL表示主菜单
_posBase = posBase; _hParentMenu = NULL;
_pAccelerator = pAccelerator; // 使用传入的菜单句柄作为当前菜单
_nativeLangEncoding = NPP_CP_WIN_1252; _hMenu = hMenu;
}
for (size_t i = 0 ; i < sizeof(_idFreeArray) ; ++i)
_idFreeArray[i] = true; // 设置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() void LastRecentFileList::switchMode()
{ {
//Remove all menu items // 从菜单中移除所有相关菜单项
::RemoveMenu(_hMenu, IDM_FILE_RESTORELASTCLOSEDFILE, MF_BYCOMMAND); ::RemoveMenu(_hMenu, IDM_FILE_RESTORELASTCLOSEDFILE, MF_BYCOMMAND);
::RemoveMenu(_hMenu, IDM_OPEN_ALL_RECENT_FILE, MF_BYCOMMAND); ::RemoveMenu(_hMenu, IDM_OPEN_ALL_RECENT_FILE, MF_BYCOMMAND);
::RemoveMenu(_hMenu, IDM_CLEAN_RECENT_FILE_LIST, MF_BYCOMMAND); ::RemoveMenu(_hMenu, IDM_CLEAN_RECENT_FILE_LIST, MF_BYCOMMAND);
for (int i = 0; i < _size; ++i) // 遍历最近打开文件列表,移除所有菜单项
{ for (int i = 0; i < _size; ++i)
::RemoveMenu(_hMenu, _lrfl.at(i)._id, MF_BYCOMMAND); {
} ::RemoveMenu(_hMenu, _lrfl.at(i)._id, MF_BYCOMMAND);
}
if (_hParentMenu == NULL) // mode main menu
{ if (_size > 0) // 根据_hParentMenu的值判断当前模式主菜单模式或子菜单模式
{ if (_hParentMenu == NULL) // mode main menu主菜单模式
::RemoveMenu(_hMenu, _posBase, MF_BYPOSITION); {
::RemoveMenu(_hMenu, _posBase, MF_BYPOSITION); if (_size > 0) // 如果最近打开文件列表不为空
} {
// switch to sub-menu mode // 从主菜单中移除一些特定的菜单项(具体移除哪些项未给出)
_hParentMenu = _hMenu; ::RemoveMenu(_hMenu, _posBase, MF_BYPOSITION);
_hMenu = ::CreatePopupMenu(); ::RemoveMenu(_hMenu, _posBase, MF_BYPOSITION);
::RemoveMenu(_hMenu, _posBase+1, MF_BYPOSITION); }
} // 切换到子菜单模式创建一个新的弹出菜单作为当前菜单并设置_hParentMenu为当前菜单即新创建的弹出菜单
else // mode sub-menu // 同时移除一些特定的菜单项(具体移除哪些项未给出)
{ _hParentMenu = _hMenu;
if (_size > 0) _hMenu = ::CreatePopupMenu();
{ ::RemoveMenu(_hMenu, _posBase + 1, MF_BYPOSITION);
::RemoveMenu(_hParentMenu, _posBase, MF_BYPOSITION); }
::RemoveMenu(_hParentMenu, _posBase, MF_BYPOSITION); else // mode sub-menu子菜单模式
} {
// switch to main menu mode if (_size > 0) // 如果最近打开文件列表不为空
::DestroyMenu(_hMenu); {
_hMenu = _hParentMenu; // 从子菜单中移除一些特定的菜单项(具体移除哪些项未给出)
_hParentMenu = NULL; ::RemoveMenu(_hParentMenu, _posBase, MF_BYPOSITION);
} ::RemoveMenu(_hParentMenu, _posBase, MF_BYPOSITION);
_hasSeparators = false; }
// switch to main menu mode
::DestroyMenu(_hMenu);
_hMenu = _hParentMenu;
_hParentMenu = NULL;
}
_hasSeparators = false;
} }
void LastRecentFileList::updateMenu() void LastRecentFileList::updateMenu()
{ {
NppParameters& nppParam = NppParameters::getInstance(); // 获取 NppParameters 的单例实例
NppParameters& nppParam = NppParameters::getInstance();
if (!_hasSeparators && _size > 0)
{ // 检查是否没有分隔符且大小大于0满足条件则进入下面的 if 语句块
//add separators if (!_hasSeparators && _size > 0)
NativeLangSpeaker *pNativeLangSpeaker = nppParam.getNativeLangSpeaker(); {
// 获取本地化语言的发言人对象
generic_string recentFileList = pNativeLangSpeaker->getSubMenuEntryName("file-recentFiles"); NativeLangSpeaker* pNativeLangSpeaker = nppParam.getNativeLangSpeaker();
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); generic_string recentFileList = pNativeLangSpeaker->getSubMenuEntryName("file-recentFiles");
generic_string openRecentClosedFile = pNativeLangSpeaker->getNativeLangMenuString(IDM_FILE_RESTORELASTCLOSEDFILE);
if (recentFileList == TEXT("")) generic_string openAllFiles = pNativeLangSpeaker->getNativeLangMenuString(IDM_OPEN_ALL_RECENT_FILE);
recentFileList = TEXT("&Recent Files"); generic_string cleanFileList = pNativeLangSpeaker->getNativeLangMenuString(IDM_CLEAN_RECENT_FILE_LIST);
if (openRecentClosedFile == TEXT(""))
openRecentClosedFile = TEXT("Restore Recent Closed File"); // 如果获取的字符串为空,则使用默认的字符串进行初始化
if (openAllFiles == TEXT("")) if (recentFileList == TEXT(""))
openAllFiles = TEXT("Open All Recent Files"); recentFileList = TEXT("&Recent Files");
if (cleanFileList == TEXT("")) if (openRecentClosedFile == TEXT(""))
cleanFileList = TEXT("Empty Recent Files List"); openRecentClosedFile = TEXT("Restore Recent Closed File");
if (openAllFiles == TEXT(""))
if (!isSubMenuMode()) openAllFiles = TEXT("Open All Recent Files");
::InsertMenu(_hMenu, _posBase + 0, MF_BYPOSITION, static_cast<UINT_PTR>(-1), 0); if (cleanFileList == TEXT(""))
cleanFileList = TEXT("Empty Recent Files List");
::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()); if (!isSubMenuMode())
::InsertMenu(_hMenu, _posBase + 4, MF_BYPOSITION, static_cast<UINT_PTR>(-1), 0); ::InsertMenu(_hMenu, _posBase + 0, MF_BYPOSITION, static_cast<UINT_PTR>(-1), 0);
_hasSeparators = true;
// 在菜单中插入四个子菜单项,分别是恢复最近关闭的文件、打开所有最近文件、清空最近文件列表和另一个分隔符
if (isSubMenuMode()) ::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(_hParentMenu, _posBase + 0, MF_BYPOSITION | MF_POPUP, reinterpret_cast<UINT_PTR>(_hMenu), (LPCTSTR)recentFileList.c_str()); ::InsertMenu(_hMenu, _posBase + 3, MF_BYPOSITION, IDM_CLEAN_RECENT_FILE_LIST, cleanFileList.c_str());
::InsertMenu(_hParentMenu, _posBase + 1, MF_BYPOSITION, static_cast<UINT_PTR>(-1), 0); ::InsertMenu(_hMenu, _posBase + 4, MF_BYPOSITION, static_cast<UINT_PTR>(-1), 0); // 插入分隔符
} // 设置标志表示已有分隔符
} _hasSeparators = true;
else if (_hasSeparators && _size == 0) //remove separators
{ // 如果当前是子菜单模式,则在父菜单中插入子菜单和分隔符
::RemoveMenu(_hMenu, _posBase + 4, MF_BYPOSITION); if (isSubMenuMode())
::RemoveMenu(_hMenu, IDM_CLEAN_RECENT_FILE_LIST, MF_BYCOMMAND); {
::RemoveMenu(_hMenu, IDM_OPEN_ALL_RECENT_FILE, MF_BYCOMMAND); ::InsertMenu(_hParentMenu, _posBase + 0, MF_BYPOSITION | MF_POPUP, reinterpret_cast<UINT_PTR>(_hMenu), (LPCTSTR)recentFileList.c_str());
::RemoveMenu(_hMenu, IDM_FILE_RESTORELASTCLOSEDFILE, MF_BYCOMMAND); ::InsertMenu(_hParentMenu, _posBase + 1, MF_BYPOSITION, static_cast<UINT_PTR>(-1), 0); // 插入分隔符
::RemoveMenu(_hMenu, _posBase + 0, MF_BYPOSITION); }
_hasSeparators = false; }
else if (_hasSeparators && _size == 0) // 当已有分隔符且大小为0时进入下面的 if 语句块,用于移除分隔符和菜单项
if (isSubMenuMode()) {
{ // 从菜单中移除一个分隔符和清空最近文件列表的菜单项
// Remove "Recent Files" Entry and the separator from the main menu ::RemoveMenu(_hMenu, _posBase + 4, MF_BYPOSITION);
::RemoveMenu(_hParentMenu, _posBase + 1, MF_BYPOSITION); ::RemoveMenu(_hMenu, IDM_CLEAN_RECENT_FILE_LIST, MF_BYCOMMAND);
::RemoveMenu(_hParentMenu, _posBase + 0, MF_BYPOSITION); ::RemoveMenu(_hMenu, IDM_OPEN_ALL_RECENT_FILE, MF_BYCOMMAND);
::RemoveMenu(_hMenu, IDM_FILE_RESTORELASTCLOSEDFILE, MF_BYCOMMAND);
// Remove the last left separator from the submenu ::RemoveMenu(_hMenu, _posBase + 0, MF_BYPOSITION);
::RemoveMenu(_hMenu, 0, MF_BYPOSITION); _hasSeparators = false;
}
} if (isSubMenuMode())
{
_pAccelerator->updateFullMenu(); // Remove "Recent Files" Entry and the separator from the main menu
::RemoveMenu(_hParentMenu, _posBase + 1, MF_BYPOSITION);
//Remove all menu items ::RemoveMenu(_hParentMenu, _posBase + 0, MF_BYPOSITION);
for (int i = 0; i < _size; ++i)
{ // Remove the last left separator from the submenu
::RemoveMenu(_hMenu, _lrfl.at(i)._id, MF_BYCOMMAND); ::RemoveMenu(_hMenu, 0, MF_BYPOSITION);
} }
//Then readd them, so everything stays in sync }
for (int j = 0; j < _size; ++j)
{ _pAccelerator->updateFullMenu();
generic_string strBuffer(BuildMenuFileName(nppParam.getRecentFileCustomLength(), j, _lrfl.at(j)._name));
::InsertMenu(_hMenu, _posBase + j, MF_BYPOSITION, _lrfl.at(j)._id, strBuffer.c_str()); //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) if (_userMax == 0 || _locked) // 如果用户定义的最大数量为0或列表被锁定直接返回不进行添加
return; return;
RecentItem itemToAdd(fn); RecentItem itemToAdd(fn); // 创建一个新的RecentItem对象使用传入的文件名初始化
int index = find(fn); int index = find(fn); // 查找该文件名在列表中的索引
if (index != -1) if (index != -1) // 如果找到
{ {
//already in list, bump upwards // 如果文件名已存在,先将其移除,然后重新添加
remove(index); remove(index);
} }
if (_size == _userMax) if (_size == _userMax) // 如果列表已满
{ {
itemToAdd._id = _lrfl.back()._id; itemToAdd._id = _lrfl.back()._id; // 使用最后一个元素的ID初始化新元素的ID
_lrfl.pop_back(); //remove oldest _lrfl.pop_back(); // 移除列表中的最后一个元素(即最旧的一个)
} }
else else // 如果列表未满
{ {
itemToAdd._id = popFirstAvailableID(); itemToAdd._id = popFirstAvailableID(); // 获取第一个可用的ID并初始化新元素的ID
++_size; ++_size; // 增加列表的大小
} }
_lrfl.push_front(itemToAdd); _lrfl.push_front(itemToAdd); // 在列表的前面添加新元素
updateMenu(); updateMenu(); // 更新菜单
} }
void LastRecentFileList::remove(const TCHAR *fn) // 根据文件名从最近的文件列表中移除一个文件。如果找到,则移除;否则什么也不做。
{ void LastRecentFileList::remove(const TCHAR* fn)
int index = find(fn); {
if (index != -1) int index = find(fn); // 查找文件名在列表中的索引
remove(index); if (index != -1) // 如果找到
remove(index); // 移除该元素
} }
void LastRecentFileList::remove(size_t index) // 根据索引从最近的文件列表中移除一个文件。如果索引有效,则移除;否则什么也不做。
void LastRecentFileList::remove(size_t index)
{ {
if (_size == 0 || _locked) if (_size == 0 || _locked) // 如果列表为空或被锁定,直接返回,不进行移除操作
return; return;
if (index < _lrfl.size()) if (index < _lrfl.size()) // 如果索引有效
{ {
::RemoveMenu(_hMenu, _lrfl.at(index)._id, MF_BYCOMMAND); ::RemoveMenu(_hMenu, _lrfl.at(index)._id, MF_BYCOMMAND); // 从菜单中移除该ID对应的菜单项
setAvailable(_lrfl.at(index)._id); setAvailable(_lrfl.at(index)._id); // 将该ID标记为可用可能是为了下次添加时重复使用
_lrfl.erase(_lrfl.begin() + index); _lrfl.erase(_lrfl.begin() + index); // 从列表中移除该元素
--_size; --_size; // 减少列表的大小
updateMenu(); updateMenu(); // 更新菜单
} }
} }
// 清空最近的文件列表。所有文件名和ID都会被移除菜单也会相应地更新。
void LastRecentFileList::clear() void LastRecentFileList::clear()
{ {
if (_size == 0) if (_size == 0) // 如果列表为空,直接返回,不进行任何操作
return; return;
for (int i = (_size - 1); i >= 0; i--) // 从后向前遍历列表,因为移除元素会影响后续元素的索引
for (int i = (_size-1); i >= 0; i--) {
{ ::RemoveMenu(_hMenu, _lrfl.at(i)._id, MF_BYCOMMAND); // 从菜单中移除该ID对应的菜单项
::RemoveMenu(_hMenu, _lrfl.at(i)._id, MF_BYCOMMAND); setAvailable(_lrfl.at(i)._id); // 将该ID标记为可用可能是为了下次添加时重复使用
setAvailable(_lrfl.at(i)._id); _lrfl.erase(_lrfl.begin() + i); // 从列表中移除该元素
_lrfl.erase(_lrfl.begin() + i); }
} _size = 0; // 将列表大小设置为0
_size = 0; updateMenu(); // 更新菜单
updateMenu();
} }
LastRecentFileList
generic_string & LastRecentFileList::getItem(int id) cpp
// 根据ID从最近的文件列表中获取一个文件名。如果找到则返回对应的文件名否则返回列表中的第一个文件名。
generic_string& LastRecentFileList::getItem(int id)
{ {
int i = 0; int i = 0; // 从索引0开始查找因为如果ID不存在可能会返回第一个文件名作为默认值。
for (; i < _size; ++i) for (; i < _size; ++i) // 遍历整个列表查找匹配的ID。如果找不到i会等于_size此时i会被重新设置为0。这是一个后备计划以防ID不存在于列表
{ {
if (_lrfl.at(i)._id == id) if (_lrfl.at(i)._id == id) // 如果找到匹配的ID
break; break;
} }
if (i == _size) if (i == _size) // 如果遍历完整个列表都没有找到匹配的ID
i = 0; i = 0; // 将索引重置为0这样可以从列表的第一个元素开始返回文件名作为默认值
return _lrfl.at(i)._name; //if not found, return first 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) void LastRecentFileList::setUserMaxNbLRF(int size)
{ {
_userMax = size; _userMax = size; // 设置用户定义的最大列表大小
if (_size > _userMax) if (_size > _userMax) // 如果当前列表大小大于新设置的大小
{ //start popping items {
int toPop = _size-_userMax; int toPop = _size - _userMax; // 计算需要移除的文件数量
while (toPop > 0) while (toPop > 0) // 当还有文件需要移除时
{ {
::RemoveMenu(_hMenu, _lrfl.back()._id, MF_BYCOMMAND); ::RemoveMenu(_hMenu, _lrfl.back()._id, MF_BYCOMMAND); // 从菜单中移除该ID对应的菜单项
setAvailable(_lrfl.back()._id); setAvailable(_lrfl.back()._id); // 将该ID标记为可用可能是为了下次添加时重复使用
_lrfl.pop_back(); _lrfl.pop_back(); // 从列表中移除该元素
toPop--; toPop--; // 减少剩余需要移除的文件数量
_size--; _size--; // 减少当前列表大小
} }
updateMenu(); updateMenu(); // 更新菜单
_size = _userMax; _size = _userMax; // 将当前列表大小设置为新设置的大小
} }
} }
// 将最近的文件列表保存到配置文件中。保存的文件名顺序与加载时相同。
void LastRecentFileList::saveLRFL() void LastRecentFileList::saveLRFL()
{ {
NppParameters& nppParams = NppParameters::getInstance(); NppParameters& nppParams = NppParameters::getInstance(); // 获取NppParameters的实例引用
if (nppParams.writeRecentFileHistorySettings(_userMax)) if (nppParams.writeRecentFileHistorySettings(_userMax)) // 如果成功写入最近的文件历史设置
{ {
for (int i = _size - 1; i >= 0; i--) //reverse order: so loading goes in correct order for (int i = _size - 1; i >= 0; i--) // 按照从后往前的顺序保存文件名,确保加载时的顺序正确
{ {
nppParams.writeHistory(_lrfl.at(i)._name.c_str()); 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) for (int i = 0; i < _size; ++i) // 遍历整个列表
{ {
if (OrdinalIgnoreCaseCompareStrings(_lrfl.at(i)._name.c_str(), fn) == 0) if (OrdinalIgnoreCaseCompareStrings(_lrfl.at(i)._name.c_str(), fn) == 0) // 如果找到匹配的文件名(忽略大小写)
{ {
return i; return i; // 返回该文件在列表中的索引
} }
} }
return -1; return -1; // 如果未找到,返回-1
} }
int LastRecentFileList::popFirstAvailableID() // 弹出第一个可用的ID。
int LastRecentFileList::popFirstAvailableID()
{ {
for (int i = 0 ; i < NB_MAX_LRF_FILE ; ++i) for (int i = 0; i < NB_MAX_LRF_FILE; ++i) // 遍历所有可能的ID
{ {
if (_idFreeArray[i]) if (_idFreeArray[i]) // 如果该ID可用未被使用
{ {
_idFreeArray[i] = false; _idFreeArray[i] = false; // 标记该ID为已使用
return i + _idBase; return i + _idBase; // 返回该ID的值从_idBase开始计算
} }
} }
return 0; return 0; // 如果所有ID都已使用返回0或默认值
} }
// 设置指定的ID为可用。
void LastRecentFileList::setAvailable(int id) void LastRecentFileList::setAvailable(int id)
{ {
int index = id - _idBase; int index = id - _idBase; // 根据ID计算其在_idFreeArray中的索引
_idFreeArray[index] = true; _idFreeArray[index] = true; // 将该索引对应的值设置为true表示该ID可用
} }

Loading…
Cancel
Save