Compare commits

..

No commits in common. 'master' and 'zhouyangbranch' have entirely different histories.

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,17 +1560,13 @@ 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); //将窗口 hwnd 子类化为 TabSubclass并分配一个唯一的子类 ID g_tabSubclassID。 SetWindowSubclass(hwnd, TabSubclass, g_tabSubclassID, 0);
} }
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,
@ -1584,9 +1580,6 @@ namespace NppDarkMode
static bool isHotStatic = false; static bool isHotStatic = false;
//在这个函数中,根据不同的消息类型进行不同的处理。
//其中WM_NCPAINT 消息用于非客户区绘制,即窗口的边框绘制。
//在这里,通过重绘窗口的边框,实现了自定义的边框绘制效果。
switch (uMsg) switch (uMsg)
{ {
case WM_NCPAINT: case WM_NCPAINT:
@ -1642,25 +1635,19 @@ namespace NppDarkMode
return 0; return 0;
} }
break; break;
//以上部分代码使用 GetWindowDC 函数获取窗口的设备上下文,然后根据窗口的样式和状态计算绘制边框所需的相关信息。
//通过调用 NppDarkMode::paintRoundFrameRect 函数来绘制圆角矩形边框,使用不同的画笔来绘制不同的边框样式。
//绘制完成后,通过 ReleaseDC 函数释放设备上下文。最后,返回值为 0表示消息已经被处理完毕。
case WM_NCCALCSIZE: case WM_NCCALCSIZE:
{ {
if (!NppDarkMode::isEnabled()) //检查是否启用了 NppDarkMode如果没有启用则直接跳过。 if (!NppDarkMode::isEnabled())
{ {
break; break;
} }
auto lpRect = reinterpret_cast<LPRECT>(lParam); //通过将 lParam 强制转换为 LPRECT 类型,获取指向窗口矩形结构的指针。 auto lpRect = reinterpret_cast<LPRECT>(lParam);
::InflateRect(lpRect, -(::GetSystemMetrics(SM_CXEDGE)), -(::GetSystemMetrics(SM_CYEDGE))); //利用 InflateRect 函数扩展客户区矩形的尺寸,将其减去窗口边框的宽度和高度(使用 SM_CXEDGE 和 SM_CYEDGE 系统度量值)。这样可以得到去除边框后的客户区矩形。 ::InflateRect(lpRect, -(::GetSystemMetrics(SM_CXEDGE)), -(::GetSystemMetrics(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);
@ -1672,14 +1659,10 @@ namespace NppDarkMode
lpRect->bottom -= ::GetSystemMetrics(SM_CYHSCROLL); lpRect->bottom -= ::GetSystemMetrics(SM_CYHSCROLL);
} }
return 0; //返回值为 0表示已经处理完 WM_NCCALCSIZE 消息。 return 0;
} }
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())
@ -1707,10 +1690,6 @@ namespace NppDarkMode
} }
break; break;
//在这个代码块中,首先检查是否启用了 NppDarkMode如果没有启用则直接跳过。
//然后,检查 isHotStatic 变量的值。如果它为真,则将其设置为假,并通过调用 SetWindowPos 函数更新窗口的位置和大小。
//接下来,同样创建一个 TRACKMOUSEEVENT 结构体,并设置其中的成员变量。
//然后,通过调用 TrackMouseEvent 函数,取消对鼠标离开窗口的跟踪,并清除鼠标悬停时间。
case WM_MOUSELEAVE: case WM_MOUSELEAVE:
{ {
if (!NppDarkMode::isEnabled()) if (!NppDarkMode::isEnabled())
@ -1735,21 +1714,20 @@ namespace NppDarkMode
case WM_NCDESTROY: case WM_NCDESTROY:
{ {
RemoveWindowSubclass(hWnd, CustomBorderSubclass, uIdSubclass); //调用 RemoveWindowSubclass 函数,将窗口子类移除,以确保在窗口销毁时不再收到自定义边框的消息。 RemoveWindowSubclass(hWnd, CustomBorderSubclass, uIdSubclass);
} }
break; break;
} }
return DefSubclassProc(hWnd, uMsg, wParam, lParam); //通过调用 DefSubclassProc 函数,将消息传递给默认的窗口过程进行处理。 return DefSubclassProc(hWnd, uMsg, wParam, lParam);
} }
void subclassCustomBorderForListBoxAndEditControls(HWND hwnd) //hwnd为要进行子类化的窗口句柄。 void subclassCustomBorderForListBoxAndEditControls(HWND hwnd)
{ {
SetWindowSubclass(hwnd, CustomBorderSubclass, g_customBorderSubclassID, 0); SetWindowSubclass(hwnd, CustomBorderSubclass, g_customBorderSubclassID, 0);
} }
constexpr UINT_PTR g_comboBoxSubclassID = 42; //标识子类化的ID constexpr UINT_PTR g_comboBoxSubclassID = 42;
//子类函数 ComboBoxSubclass它是一个回调函数用于处理窗口消息。
LRESULT CALLBACK ComboBoxSubclass( LRESULT CALLBACK ComboBoxSubclass(
HWND hWnd, HWND hWnd,
UINT uMsg, UINT uMsg,
@ -1758,7 +1736,6 @@ 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);
@ -1770,15 +1747,13 @@ 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());
@ -1786,16 +1761,11 @@ namespace NppDarkMode
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;
@ -1809,16 +1779,12 @@ namespace NppDarkMode
}; };
} }
bool hasFocus = false; //定义了一个 hasFocus 变量,并且获取了窗口是否启用的状态。 bool hasFocus = false;
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;
@ -1862,8 +1828,6 @@ 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;
@ -1888,10 +1852,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);
@ -1911,10 +1875,7 @@ 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 //命名空间NppDarkMode namespace NppDarkMode
{ {
struct Colors //Colors颜色结构体 struct Colors
{ {
COLORREF background = 0; //COLORREF 是一个 32-bit 整型数值,它代表了一种颜色。 COLORREF background = 0;
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 //Options选项结构体 struct Options
{ {
bool enable = false; bool enable = false;
bool enableMenubar = false; bool enableMenubar = false;
bool enablePlugin = false; bool enablePlugin = false;
}; };
struct NppDarkModeParams //params参数结构体 struct NppDarkModeParams
{ {
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 //域内枚举类型为ToolTipsType enum class 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 类 generic_string getThemeName();
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 就是 Double Word 每个word为2个字节的长度DWORD 双字即为4个字节每个字节是8位共32位。 DWORD getWindowsBuildNumber();
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 取画刷 HBRUSH getBackgroundBrush();
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 解决了返回true否则false继续处理 // return true if handled, false to continue with normal processing in your wndproc
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 对于DarkMode.h的改进 // enhancements to 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); //Windows API中的回调函数用于枚举自动完成列表中的项。HWND hwnd自动完成列表的窗口句柄。 LPARAM lParam用户定义的附加参数。 BOOL CALLBACK enumAutocompleteProc(HWND hwnd, LPARAM lParam);
void setDarkAutoCompletion(); void setDarkAutoCompletion();
LRESULT onCtlColor(HDC hdc); //LRESULT是一个数据类型指的是从窗口程序或者回调函数返回的32位值 LRESULT onCtlColor(HDC hdc);
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是特殊定义的类型是为了解决32位与64位编译器的兼容性而设置的关键字 INT_PTR onCtlColorListbox(WPARAM wParam, LPARAM lParam);
} }

@ -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 fou
{ {
::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 fou
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;
@ -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)

@ -14,15 +14,11 @@
// 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;
@ -30,15 +26,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;
@ -56,56 +52,51 @@ 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();
// 根据文件名查找缓冲区,返回索引值,如果未找到则返回-1 BufferID findBufferByName(const TCHAR * fullfilename); //-1 if not found, something else otherwise
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,9 +23,6 @@
#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;
@ -38,15 +35,12 @@ 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) // 找到了相同的文本 if (i != CB_ERR) // found
{ {
// 删除已存在的文本
::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);
} }
@ -65,8 +59,6 @@ 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')
@ -91,7 +83,6 @@ 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;
} }
@ -103,22 +94,19 @@ 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':
@ -143,26 +131,24 @@ 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;
} }
@ -176,14 +162,12 @@ 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;
@ -198,7 +182,6 @@ int Searching::convertExtendedToString(const TCHAR * query, TCHAR * result, int
++i; ++i;
++j; ++j;
} }
result[j] = 0; result[j] = 0;
return j; return j;
} }
@ -212,7 +195,6 @@ 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;
@ -238,110 +220,105 @@ 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);
// 更新 Scintilla 中光标所在列的位置信息,以防用户在选择搜索结果后使用上下箭头导航时光标跳到意外的列 // 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
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); // 根据 DPI 缩放标签页高度 int tabDpiDynamicalHeight = dpiManager.scaleY(13);
_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(); // 显示标签页
_initialClientWidth = rect.right - rect.left; // 记录初始客户区宽度 _tab.reSizeTo(rect);
_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;
@ -358,65 +335,88 @@ 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) // 检查配置数据是否有效 if (nppGUI._findWindowPos.bottom - nppGUI._findWindowPos.top != 0) // check height against 0 as a test of valid data from config
{ {
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)
{ {
// 反转 _findWindowLessMode 的值,因为在 IDD_RESIZE_TOGGLE_BUTTON 中会再次反转该值 // reverse the value of _findWindowLessMode because the value will be inversed again in 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,47 +436,44 @@ 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);
} }
// 如果历史记录不为空且第一个元素为空字符串,则手动设置 Combo Box 文本为空 //empty string is not added to CB items, so we need to set it manually
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); // 选择第一项 ::SendMessage(hCombo, CB_SETCURSEL, 0, 0); // select first item
} }
// 保存查找历史记录
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' };
@ -488,7 +485,6 @@ 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)
@ -497,7 +493,6 @@ 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);
@ -509,14 +504,13 @@ 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);
@ -731,71 +725,62 @@ 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; CurrentPosInLineInfo cpili;
// 初始化计数器count为0
size_t count = 0; size_t count = 0;
// 初始化上一个区间的结束位置为0
intptr_t lastEnd = 0; intptr_t lastEnd = 0;
// 获取当前文本框选择的起始位置和结束位置
auto selStart = _scintView.execute(SCI_GETSELECTIONSTART); auto selStart = _scintView.execute(SCI_GETSELECTIONSTART);
auto selEnd = _scintView.execute(SCI_GETSELECTIONEND); auto selEnd = _scintView.execute(SCI_GETSELECTIONEND);
// 判断是否有选择文本
bool hasSel = (selEnd - selStart) != 0; bool hasSel = (selEnd - selStart) != 0;
// 遍历每个区间
for (std::pair<intptr_t, intptr_t> range : markingLine._segmentPostions) for (std::pair<intptr_t, intptr_t> range : markingLine._segmentPostions)
{ {
++count; ++count;
// 判断当前位置在区间的前面
if (lastEnd <= currentPosInLine && currentPosInLine < range.first) if (lastEnd <= currentPosInLine && currentPosInLine < range.first)
{ {
if (count == 1) if (count == 1)
{ {
cpili._status = pos_infront; // 在第一个区间的前面 cpili._status = pos_infront;
break; break;
} }
else else
{ {
cpili._status = pos_between; // 在两个区间之间 cpili._status = pos_between;
cpili.auxiliaryInfo = count - 1; cpili.auxiliaryInfo = count - 1;
break; break;
} }
} }
// 判断当前位置在区间内部
if (range.first <= currentPosInLine && currentPosInLine <= range.second) if (range.first <= currentPosInLine && currentPosInLine <= range.second)
{ {
if (currentPosInLine == range.first && !hasSel) if (currentPosInLine == range.first && !hasSel)
{ {
cpili._status = pos_between; // 在区间的起始位置,在没有选择文本的情况下 cpili._status = pos_between;
cpili.auxiliaryInfo = count - 1; 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) else if (currentPosInLine == range.second && !hasSel)
{ {
cpili._status = pos_between; // 在区间的结束位置,在没有选择文本的情况下 cpili._status = pos_between;
cpili.auxiliaryInfo = count; cpili.auxiliaryInfo = count; // c1 c2
// [ ]I [ ] : I is recongnized with c1, so auxiliaryInfo should be c1
} }
else else
{ {
cpili._status = pos_inside; // 在区间内部 cpili._status = pos_inside;
cpili.auxiliaryInfo = count; cpili.auxiliaryInfo = count;
} }
break; break;
} }
// 判断当前位置在区间的后面
if (range.second < currentPosInLine) if (range.second < currentPosInLine)
{ {
if (markingLine._segmentPostions.size() == count) if (markingLine._segmentPostions.size() == count)
{ {
cpili._status = pos_behind; // 在最后一个区间的后面 cpili._status = pos_behind;
cpili.auxiliaryInfo = count; cpili.auxiliaryInfo = count;
break; break;
} }
@ -809,44 +794,36 @@ Finder::CurrentPosInLineInfo Finder::getCurrentPosInLineInfo(intptr_t currentPos
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)
{ {
// 如果当前行大于最大行并且方向为0则将当前行设置为最小行
if (currentL > maxL && direction == 0) if (currentL > maxL && direction == 0)
currentL = minL; currentL = minL;
// 循环直到当前行不是折叠标题行
while (_scintView.execute(SCI_GETFOLDLEVEL, currentL) & SC_FOLDLEVELHEADERFLAG) while (_scintView.execute(SCI_GETFOLDLEVEL, currentL) & SC_FOLDLEVELHEADERFLAG)
{ {
// 根据方向更新当前行
currentL += direction == -1 ? -1 : 1; currentL += direction == -1 ? -1 : 1;
// 如果当前行超过最大行,则将当前行设置为最小行
if (currentL > maxL) if (currentL > maxL)
currentL = minL; currentL = minL;
// 如果当前行低于最小行,则将当前行设置为最大行
else if (currentL < minL) else if (currentL < minL)
currentL = maxL; currentL = maxL;
// 如果当前行等于初始行,则跳出循环
if (currentL == initL) if (currentL == initL)
break; break;
} }
// 获取当前行的绝对位置
auto extremityAbsoltePos = _scintView.execute(direction == -1 ? SCI_GETLINEENDPOSITION : SCI_POSITIONFROMLINE, currentL); auto extremityAbsoltePos = _scintView.execute(direction == -1 ? SCI_GETLINEENDPOSITION : SCI_POSITIONFROMLINE, currentL);
// 设置选择范围为当前行的绝对位置
_scintView.execute(SCI_SETSEL, extremityAbsoltePos, extremityAbsoltePos); _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); auto currentPos = _scintView.execute(SCI_GETCURRENTPOS);
intptr_t lno = _scintView.execute(SCI_LINEFROMPOSITION, currentPos); intptr_t lno = _scintView.execute(SCI_LINEFROMPOSITION, currentPos);
auto total_lines = _scintView.execute(SCI_GETLINECOUNT); auto total_lines = _scintView.execute(SCI_GETLINECOUNT);
// 如果总行数小于等于1则直接返回
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;
@ -855,7 +832,7 @@ void Finder::gotoNextFoundResult(int direction)
assert(max_lno <= total_lines - 2); assert(max_lno <= total_lines - 2);
// 获取当前搜索行号searchHeaderLevel // get the line number of the current search (searchHeaderLevel)
int level = _scintView.execute(SCI_GETFOLDLEVEL, lno) & SC_FOLDLEVELNUMBERMASK; int level = _scintView.execute(SCI_GETFOLDLEVEL, lno) & SC_FOLDLEVELNUMBERMASK;
auto min_lno = lno; auto min_lno = lno;
while (level-- >= fileHeaderLevel) while (level-- >= fileHeaderLevel)
@ -864,15 +841,16 @@ void Finder::gotoNextFoundResult(int direction)
assert(min_lno >= 0); assert(min_lno >= 0);
} }
if (min_lno < 0) min_lno = lno; // 当lno是一个搜索标题行时 if (min_lno < 0) min_lno = lno; // when lno is a search header line
assert(min_lno <= max_lno); assert(min_lno <= max_lno);
// 根据方向更新当前行号
if (lno > max_lno && direction == 0) lno = min_lno; if (lno > max_lno && direction == 0) lno = min_lno;
else if (lno < min_lno) lno = max_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) while (_scintView.execute(SCI_GETFOLDLEVEL, lno) & SC_FOLDLEVELHEADERFLAG)
{ {
lno += direction == -1 ? -1 : 1; lno += direction == -1 ? -1 : 1;
@ -886,27 +864,24 @@ void Finder::gotoNextFoundResult(int direction)
break; break;
} }
// 如果当前行与初始行不同
if (lno != init_lno) if (lno != init_lno)
{ {
// 获取当前行的绝对位置
auto extremityAbsoltePos = _scintView.execute(direction == -1 ? SCI_GETLINEENDPOSITION : SCI_POSITIONFROMLINE, lno); auto extremityAbsoltePos = _scintView.execute(direction == -1 ? SCI_GETLINEENDPOSITION : SCI_POSITIONFROMLINE, lno);
// 设置选择范围为当前行的绝对位置
_scintView.execute(SCI_SETSEL, extremityAbsoltePos, extremityAbsoltePos); _scintView.execute(SCI_SETSEL, extremityAbsoltePos, extremityAbsoltePos);
currentPos = extremityAbsoltePos; currentPos = extremityAbsoltePos;
// 获取当前行的起始位置和光标在行内的位置
auto start = _scintView.execute(SCI_POSITIONFROMLINE, lno); auto start = _scintView.execute(SCI_POSITIONFROMLINE, lno);
currentPosInLine = currentPos - start; currentPosInLine = currentPos - start;
} }
size_t n = 0; size_t n = 0;
const SearchResultMarkingLine& markingLine = *(_pMainMarkings->begin() + lno); const SearchResultMarkingLine& markingLine = *(_pMainMarkings->begin() + lno);
// 获取当前位置在行内的状态 //
// Determinate currentPosInLine status among pos_infront, pose_between, pos_inside and pos_behind
//
CurrentPosInLineInfo cpili = getCurrentPosInLineInfo(currentPosInLine, markingLine); 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
// //

@ -13,7 +13,7 @@
// //
// 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/>.
//处理工具栏按钮
#include <stdexcept> #include <stdexcept>
#include "TabBar.h" #include "TabBar.h"
#include "Parameters.h" #include "Parameters.h"
@ -38,24 +38,24 @@ COLORREF TabBarPlus::_activeTopBarUnfocusedColour = RGB(250, 210, 150);
COLORREF TabBarPlus::_inactiveTextColour = grey; COLORREF TabBarPlus::_inactiveTextColour = grey;
COLORREF TabBarPlus::_inactiveBgColour = RGB(192, 192, 192); COLORREF TabBarPlus::_inactiveBgColour = RGB(192, 192, 192);
HWND TabBarPlus::_hwndArray[nbCtrlMax] = { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL }; HWND TabBarPlus::_hwndArray[nbCtrlMax] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
int TabBarPlus::_nbCtrl = 0; int TabBarPlus::_nbCtrl = 0;
//初始化标签栏,创建窗口
void TabBar::init(HINSTANCE hInst, HWND parent, bool isVertical, bool isMultiLine) void TabBar::init(HINSTANCE hInst, HWND parent, bool isVertical, bool isMultiLine)
{ {
Window::init(hInst, parent); Window::init(hInst, parent);
int vertical = isVertical ? (TCS_VERTICAL | TCS_MULTILINE | TCS_RIGHTJUSTIFY) : 0; int vertical = isVertical?(TCS_VERTICAL | TCS_MULTILINE | TCS_RIGHTJUSTIFY):0;
_isVertical = isVertical; _isVertical = isVertical;
_isMultiLine = isMultiLine; _isMultiLine = isMultiLine;
INITCOMMONCONTROLSEX icce{};//初始化通用控件库 INITCOMMONCONTROLSEX icce{};
icce.dwSize = sizeof(icce); icce.dwSize = sizeof(icce);
icce.dwICC = ICC_TAB_CLASSES; icce.dwICC = ICC_TAB_CLASSES;
InitCommonControlsEx(&icce); InitCommonControlsEx(&icce);
int multiLine = isMultiLine ? TCS_MULTILINE : 0; int multiLine = isMultiLine ? TCS_MULTILINE : 0;
int style = WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_VISIBLE | \ int style = WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_VISIBLE |\
TCS_FOCUSNEVER | TCS_TABS | WS_TABSTOP | vertical | multiLine; TCS_FOCUSNEVER | TCS_TABS | WS_TABSTOP | vertical | multiLine;
_hSelf = ::CreateWindowEx( _hSelf = ::CreateWindowEx(
@ -75,27 +75,27 @@ void TabBar::init(HINSTANCE hInst, HWND parent, bool isVertical, bool isMultiLin
} }
} }
//清理与TabBar相关的资源
void TabBar::destroy() void TabBar::destroy()
{ {
if (_hFont) if (_hFont)
{ {
::DeleteObject(_hFont); ::DeleteObject(_hFont);
_hFont = nullptr; _hFont = nullptr;
}//删除字体对象 }
if (_hLargeFont) if (_hLargeFont)
{ {
::DeleteObject(_hLargeFont); ::DeleteObject(_hLargeFont);
_hLargeFont = nullptr; _hLargeFont = nullptr;
}//删除字体大小格式 }
if (_hVerticalFont) if (_hVerticalFont)
{ {
::DeleteObject(_hVerticalFont); ::DeleteObject(_hVerticalFont);
_hVerticalFont = nullptr; _hVerticalFont = nullptr;
} }
//删除垂直字体对象
if (_hVerticalLargeFont) if (_hVerticalLargeFont)
{ {
::DeleteObject(_hVerticalLargeFont); ::DeleteObject(_hVerticalLargeFont);
@ -106,39 +106,39 @@ void TabBar::destroy()
_hSelf = nullptr; _hSelf = nullptr;
} }
//在TabBar末尾插入一个新的选项卡并设置名称。使用TCITEM结构设置选项卡的属性并发送消息将选项卡插入TabBar中
int TabBar::insertAtEnd(const TCHAR* subTabName) int TabBar::insertAtEnd(const TCHAR *subTabName)
{ {
TCITEM tie{}; TCITEM tie{};
tie.mask = TCIF_TEXT | TCIF_IMAGE; tie.mask = TCIF_TEXT | TCIF_IMAGE;
int index = -1; int index = -1;
//如果存在图像列表那么新TabItem应该被放置在列表的开始。
if (_hasImgLst) if (_hasImgLst)
index = 0; index = 0;
tie.iImage = index; tie.iImage = index;
tie.pszText = (TCHAR*)subTabName; tie.pszText = (TCHAR *)subTabName;
return int(::SendMessage(_hSelf, TCM_INSERTITEM, _nbItem++, reinterpret_cast<LPARAM>(&tie))); return int(::SendMessage(_hSelf, TCM_INSERTITEM, _nbItem++, reinterpret_cast<LPARAM>(&tie)));
} }
//获取当前选定选项卡的标题。
void TabBar::getCurrentTitle(TCHAR* title, int titleLen) void TabBar::getCurrentTitle(TCHAR *title, int titleLen)
{ {
TCITEM tci{}; TCITEM tci{};
tci.mask = TCIF_TEXT; tci.mask = TCIF_TEXT;
tci.pszText = title; tci.pszText = title;
tci.cchTextMax = titleLen - 1; tci.cchTextMax = titleLen-1;
::SendMessage(_hSelf, TCM_GETITEM, getCurrentTabIndex(), reinterpret_cast<LPARAM>(&tci)); ::SendMessage(_hSelf, TCM_GETITEM, getCurrentTabIndex(), reinterpret_cast<LPARAM>(&tci));
} }
//为TabBar中的选项卡设置字体。根据提供的参数创建新字体并发送消息为TabBar设置该字体
void TabBar::setFont(const TCHAR* fontName, int fontSize) void TabBar::setFont(const TCHAR *fontName, int fontSize)
{ {
if (_hFont) if (_hFont)
::DeleteObject(_hFont); ::DeleteObject(_hFont);
_hFont = ::CreateFont(fontSize, 0, _hFont = ::CreateFont( fontSize, 0,
(_isVertical) ? 900 : 0, (_isVertical) ? 900:0,
(_isVertical) ? 900 : 0, (_isVertical) ? 900:0,
FW_NORMAL, FW_NORMAL,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
@ -147,7 +147,7 @@ void TabBar::setFont(const TCHAR* fontName, int fontSize)
::SendMessage(_hSelf, WM_SETFONT, reinterpret_cast<WPARAM>(_hFont), 0); ::SendMessage(_hSelf, WM_SETFONT, reinterpret_cast<WPARAM>(_hFont), 0);
} }
//激活指定索引处的选项卡。发送消息以确保在TabBar中激活指定索引处的选项卡。
void TabBar::activateAt(int index) const void TabBar::activateAt(int index) const
{ {
if (getCurrentTabIndex() != index) if (getCurrentTabIndex() != index)
@ -163,14 +163,14 @@ void TabBar::activateAt(int index) const
} }
} }
//删除指定索引处的选项卡
void TabBar::deletItemAt(size_t index) void TabBar::deletItemAt(size_t index)
{ {
if (index == _nbItem - 1) if (index == _nbItem - 1)
{ {
//prevent invisible tabs. If last visible tab is removed, other tabs are put in view but not redrawn //prevent invisible tabs. If last visible tab is removed, other tabs are put in view but not redrawn
//Therefore, scroll one tab to the left if only one tab visible //Therefore, scroll one tab to the left if only one tab visible
if (_nbItem > 1)//至少两个 if (_nbItem > 1)
{ {
RECT itemRect{}; RECT itemRect{};
::SendMessage(_hSelf, TCM_GETITEMRECT, index, reinterpret_cast<LPARAM>(&itemRect)); ::SendMessage(_hSelf, TCM_GETITEMRECT, index, reinterpret_cast<LPARAM>(&itemRect));
@ -182,7 +182,7 @@ void TabBar::deletItemAt(size_t index)
//There seems to be no negative effect on any internal state of the tab control or the up/down control //There seems to be no negative effect on any internal state of the tab control or the up/down control
int wParam = MAKEWPARAM(SB_THUMBPOSITION, index - 1); int wParam = MAKEWPARAM(SB_THUMBPOSITION, index - 1);
::SendMessage(_hSelf, WM_HSCROLL, wParam, 0); ::SendMessage(_hSelf, WM_HSCROLL, wParam, 0);
//TabBar控件向左滚动一个Tab项的位置。
wParam = MAKEWPARAM(SB_ENDSCROLL, index - 1); wParam = MAKEWPARAM(SB_ENDSCROLL, index - 1);
::SendMessage(_hSelf, WM_HSCROLL, wParam, 0); ::SendMessage(_hSelf, WM_HSCROLL, wParam, 0);
} }
@ -192,15 +192,15 @@ void TabBar::deletItemAt(size_t index)
_nbItem--; _nbItem--;
} }
//设置TabBar中的图像列表。使用TCM_SETIMAGELIST消息来设置图像列表。
void TabBar::setImageList(HIMAGELIST himl) void TabBar::setImageList(HIMAGELIST himl)
{ {
_hasImgLst = true; _hasImgLst = true;
::SendMessage(_hSelf, TCM_SETIMAGELIST, 0, reinterpret_cast<LPARAM>(himl)); ::SendMessage(_hSelf, TCM_SETIMAGELIST, 0, reinterpret_cast<LPARAM>(himl));
} }
//调整TabBar的大小以适应给定的矩形区域。调整TabBar的显示方式并计算新的大小然后调整提供的矩形区域。
void TabBar::reSizeTo(RECT& rc2Ajust) void TabBar::reSizeTo(RECT & rc2Ajust)
{ {
RECT rowRect{}; RECT rowRect{};
int rowCount = 0, tabsHight = 0; int rowCount = 0, tabsHight = 0;
@ -208,7 +208,6 @@ void TabBar::reSizeTo(RECT& rc2Ajust)
// Important to do that! // Important to do that!
// Otherwise, the window(s) it contains will take all the resouce of CPU // Otherwise, the window(s) it contains will take all the resouce of CPU
// We don't need to resize the contained windows if they are even invisible anyway // We don't need to resize the contained windows if they are even invisible anyway
//调用display方法根据调整矩形的右边界是否大于10来决定是否显示TabBar中的窗口
display(rc2Ajust.right > 10); display(rc2Ajust.right > 10);
RECT rc = rc2Ajust; RECT rc = rc2Ajust;
Window::reSizeTo(rc); Window::reSizeTo(rc);
@ -227,7 +226,7 @@ void TabBar::reSizeTo(RECT& rc2Ajust)
if (rowCount == 1) if (rowCount == 1)
{ {
style &= ~TCS_BUTTONS; style &= ~TCS_BUTTONS;
}// 如果有多行Tab项至少两行则启用TabCtrl的按钮样式并计算间距的值 }
else // (rowCount >= 2) else // (rowCount >= 2)
{ {
style |= TCS_BUTTONS; style |= TCS_BUTTONS;
@ -250,23 +249,19 @@ void TabBar::reSizeTo(RECT& rc2Ajust)
} }
} }
//销毁TabBarPlus及其资源。
void TabBarPlus::destroy() void TabBarPlus::destroy()
{ {
TabBar::destroy(); TabBar::destroy();
::DestroyWindow(_tooltips); ::DestroyWindow(_tooltips);
_tooltips = NULL; _tooltips = NULL;
} }
/*
TabBarPlus
TabControl
TabBarPlus便
*/
void TabBarPlus::init(HINSTANCE hInst, HWND parent, bool isVertical, bool isMultiLine) void TabBarPlus::init(HINSTANCE hInst, HWND parent, bool isVertical, bool isMultiLine)
{ {
Window::init(hInst, parent); Window::init(hInst, parent);
int vertical = isVertical ? (TCS_VERTICAL | TCS_MULTILINE | TCS_RIGHTJUSTIFY) : 0; int vertical = isVertical?(TCS_VERTICAL | TCS_MULTILINE | TCS_RIGHTJUSTIFY):0;
_isVertical = isVertical; _isVertical = isVertical;
_isMultiLine = isMultiLine; _isMultiLine = isMultiLine;
@ -295,7 +290,7 @@ void TabBarPlus::init(HINSTANCE hInst, HWND parent, bool isVertical, bool isMult
{ {
throw std::runtime_error("TabBarPlus::init : CreateWindowEx() function return null"); throw std::runtime_error("TabBarPlus::init : CreateWindowEx() function return null");
} }
//工具提示
_tooltips = ::CreateWindowEx( _tooltips = ::CreateWindowEx(
0, 0,
TOOLTIPS_CLASS, TOOLTIPS_CLASS,
@ -311,7 +306,7 @@ void TabBarPlus::init(HINSTANCE hInst, HWND parent, bool isVertical, bool isMult
{ {
throw std::runtime_error("TabBarPlus::init : tooltip CreateWindowEx() function return null"); throw std::runtime_error("TabBarPlus::init : tooltip CreateWindowEx() function return null");
} }
//暗色主题
NppDarkMode::setDarkTooltips(_tooltips, NppDarkMode::ToolTipsType::tooltip); NppDarkMode::setDarkTooltips(_tooltips, NppDarkMode::ToolTipsType::tooltip);
::SendMessage(_hSelf, TCM_SETTOOLTIPS, reinterpret_cast<WPARAM>(_tooltips), 0); ::SendMessage(_hSelf, TCM_SETTOOLTIPS, reinterpret_cast<WPARAM>(_tooltips), 0);
@ -322,13 +317,12 @@ void TabBarPlus::init(HINSTANCE hInst, HWND parent, bool isVertical, bool isMult
_ctrlID = _nbCtrl; _ctrlID = _nbCtrl;
} }
else else
{//查找第一个为空的位置并设置_ctrlID为该位置的值 {
int i = 0; int i = 0;
bool found = false; bool found = false;
for (; i < nbCtrlMax && !found; ++i) for ( ; i < nbCtrlMax && !found ; ++i)
if (!_hwndArray[i]) if (!_hwndArray[i])
found = true; found = true;
//满了未找到,销毁
if (!found) if (!found)
{ {
_ctrlID = -1; _ctrlID = -1;
@ -360,16 +354,15 @@ void TabBarPlus::init(HINSTANCE hInst, HWND parent, bool isVertical, bool isMult
_hVerticalLargeFont = CreateFontIndirect(&lfVer); _hVerticalLargeFont = CreateFontIndirect(&lfVer);
} }
//处理选项卡控件的自定义填充。
void TabBarPlus::doOwnerDrawTab() void TabBarPlus::doOwnerDrawTab()
{ {
::SendMessage(_hwndArray[0], TCM_SETPADDING, 0, MAKELPARAM(6, 0)); ::SendMessage(_hwndArray[0], TCM_SETPADDING, 0, MAKELPARAM(6, 0));
for (int i = 0; i < _nbCtrl; ++i) for (int i = 0 ; i < _nbCtrl ; ++i)
{ {
if (_hwndArray[i]) if (_hwndArray[i])
{ {
LONG_PTR style = ::GetWindowLongPtr(_hwndArray[i], GWL_STYLE); LONG_PTR style = ::GetWindowLongPtr(_hwndArray[i], GWL_STYLE);
//检查是否需要自定义
if (isOwnerDrawTab()) if (isOwnerDrawTab())
style |= TCS_OWNERDRAWFIXED; style |= TCS_OWNERDRAWFIXED;
else else
@ -385,7 +378,7 @@ void TabBarPlus::doOwnerDrawTab()
} }
} }
//根据给定的索引为选项卡栏设置不同的颜色(如活动文本颜色、背景颜色等)。在更新颜色之后它调用doOwnerDrawTab()来刷新显示。
void TabBarPlus::setColour(COLORREF colour2Set, tabColourIndex i) void TabBarPlus::setColour(COLORREF colour2Set, tabColourIndex i)
{ {
switch (i) switch (i)
@ -402,35 +395,35 @@ void TabBarPlus::setColour(COLORREF colour2Set, tabColourIndex i)
case inactiveText: case inactiveText:
_inactiveTextColour = colour2Set; _inactiveTextColour = colour2Set;
break; break;
case inactiveBg: case inactiveBg :
_inactiveBgColour = colour2Set; _inactiveBgColour = colour2Set;
break; break;
default: default :
return; return;
} }
doOwnerDrawTab(); doOwnerDrawTab();
} }
//设置垂直选项卡
void TabBarPlus::doVertical() void TabBarPlus::doVertical()
{ {
for (int i = 0; i < _nbCtrl; ++i) for (int i = 0 ; i < _nbCtrl ; ++i)
{ {
if (_hwndArray[i]) if (_hwndArray[i])
SendMessage(_hwndArray[i], WM_TABSETSTYLE, isVertical(), TCS_VERTICAL); SendMessage(_hwndArray[i], WM_TABSETSTYLE, isVertical(), TCS_VERTICAL);
} }
} }
//显示多行选项卡
void TabBarPlus::doMultiLine() void TabBarPlus::doMultiLine()
{ {
for (int i = 0; i < _nbCtrl; ++i) for (int i = 0 ; i < _nbCtrl ; ++i)
{ {
if (_hwndArray[i]) if (_hwndArray[i])
SendMessage(_hwndArray[i], WM_TABSETSTYLE, isMultiLine(), TCS_MULTILINE); SendMessage(_hwndArray[i], WM_TABSETSTYLE, isMultiLine(), TCS_MULTILINE);
} }
} }
//向父窗口发送通知消息,其中包含有关选项卡索引和特定通知代码的信息。
void TabBarPlus::notify(int notifyCode, int tabIndex) void TabBarPlus::notify(int notifyCode, int tabIndex)
{ {
TBHDR nmhdr{}; TBHDR nmhdr{};
@ -440,7 +433,7 @@ void TabBarPlus::notify(int notifyCode, int tabIndex)
nmhdr._tabOrigin = tabIndex; nmhdr._tabOrigin = tabIndex;
::SendMessage(_hParent, WM_NOTIFY, 0, reinterpret_cast<LPARAM>(&nmhdr)); ::SendMessage(_hParent, WM_NOTIFY, 0, reinterpret_cast<LPARAM>(&nmhdr));
} }
//启动对选项卡栏控件上的鼠标事件的跟踪,例如当鼠标进入或离开控件区域时。
void TabBarPlus::trackMouseEvent(DWORD event2check) void TabBarPlus::trackMouseEvent(DWORD event2check)
{ {
TRACKMOUSEEVENT tme = {}; TRACKMOUSEEVENT tme = {};
@ -449,13 +442,12 @@ void TabBarPlus::trackMouseEvent(DWORD event2check)
tme.hwndTrack = _hSelf; tme.hwndTrack = _hSelf;
TrackMouseEvent(&tme); TrackMouseEvent(&tme);
} }
//消息处理,处理窗口消息
LRESULT TabBarPlus::runProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam) LRESULT TabBarPlus::runProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam)
{ {
switch (Message) switch (Message)
{ {
// Custom window message to change tab control style on the fly // Custom window message to change tab control style on the fly
//改变窗口样式
case WM_TABSETSTYLE: case WM_TABSETSTYLE:
{ {
LONG_PTR style = ::GetWindowLongPtr(hwnd, GWL_STYLE); LONG_PTR style = ::GetWindowLongPtr(hwnd, GWL_STYLE);
@ -473,13 +465,13 @@ LRESULT TabBarPlus::runProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lPara
return TRUE; return TRUE;
} }
//深色模式
case NPPM_INTERNAL_REFRESHDARKMODE: case NPPM_INTERNAL_REFRESHDARKMODE:
{ {
NppDarkMode::setDarkTooltips(hwnd, NppDarkMode::ToolTipsType::tabbar); NppDarkMode::setDarkTooltips(hwnd, NppDarkMode::ToolTipsType::tabbar);
return TRUE; return TRUE;
} }
//鼠标滚轮
case WM_MOUSEWHEEL: case WM_MOUSEWHEEL:
{ {
// .............................................................................. // ..............................................................................
@ -497,7 +489,7 @@ LRESULT TabBarPlus::runProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lPara
// CTRL + SHIFT + MOUSEWHEEL: // CTRL + SHIFT + MOUSEWHEEL:
// will switch to the first/last tab // will switch to the first/last tab
// .............................................................................. // ..............................................................................
//是否被拖动,如是,会交换当前鼠标所在位置和目标位置的数据
if (_isDragging) if (_isDragging)
return TRUE; return TRUE;
@ -589,8 +581,8 @@ LRESULT TabBarPlus::runProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lPara
} }
return TRUE; return TRUE;
} }
//左键按下
case WM_LBUTTONDOWN: case WM_LBUTTONDOWN :
{ {
if (::GetWindowLongPtr(_hSelf, GWL_STYLE) & TCS_BUTTONS) if (::GetWindowLongPtr(_hSelf, GWL_STYLE) & TCS_BUTTONS)
{ {
@ -600,7 +592,7 @@ LRESULT TabBarPlus::runProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lPara
setActiveTab(nTab); setActiveTab(nTab);
} }
} }
//是否关闭
if (_drawTabCloseButton) if (_drawTabCloseButton)
{ {
int xPos = LOWORD(lParam); int xPos = LOWORD(lParam);
@ -629,8 +621,8 @@ LRESULT TabBarPlus::runProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lPara
return TRUE; return TRUE;
} }
//右键按下,处理选项
case WM_RBUTTONDOWN: //rightclick selects tab aswell case WM_RBUTTONDOWN : //rightclick selects tab aswell
{ {
// TCS_BUTTONS doesn't select the tab // TCS_BUTTONS doesn't select the tab
if (::GetWindowLongPtr(_hSelf, GWL_STYLE) & TCS_BUTTONS) if (::GetWindowLongPtr(_hSelf, GWL_STYLE) & TCS_BUTTONS)
@ -645,8 +637,8 @@ LRESULT TabBarPlus::runProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lPara
::CallWindowProc(_tabBarDefaultProc, hwnd, WM_LBUTTONDOWN, wParam, lParam); ::CallWindowProc(_tabBarDefaultProc, hwnd, WM_LBUTTONDOWN, wParam, lParam);
return TRUE; return TRUE;
} }
//鼠标移动
case WM_MOUSEMOVE: case WM_MOUSEMOVE :
{ {
if (_mightBeDragging && !_isDragging) if (_mightBeDragging && !_isDragging)
{ {
@ -678,7 +670,7 @@ LRESULT TabBarPlus::runProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lPara
POINT p{}; POINT p{};
p.x = LOWORD(lParam); p.x = LOWORD(lParam);
p.y = HIWORD(lParam); p.y = HIWORD(lParam);
//是否拖动tag光标移动tab数据交换判断并进行相关操作
if (_isDragging) if (_isDragging)
{ {
exchangeItemData(p); exchangeItemData(p);
@ -766,7 +758,7 @@ LRESULT TabBarPlus::runProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lPara
break; break;
} }
//鼠标移开,重绘鼠标区域,重置相关变量
case WM_MOUSELEAVE: case WM_MOUSELEAVE:
{ {
if (_isCloseHover) if (_isCloseHover)
@ -780,8 +772,8 @@ LRESULT TabBarPlus::runProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lPara
notify(TCN_MOUSELEAVING, _currentHoverTabItem); notify(TCN_MOUSELEAVING, _currentHoverTabItem);
break; break;
} }
//释放左键,告知操作结束
case WM_LBUTTONUP: case WM_LBUTTONUP :
{ {
_mightBeDragging = false; _mightBeDragging = false;
_dragCount = 0; _dragCount = 0;
@ -800,7 +792,7 @@ LRESULT TabBarPlus::runProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lPara
_isDragging = false; _isDragging = false;
} }
notify(_isDraggingInside ? TCN_TABDROPPED : TCN_TABDROPPEDOUTSIDE, currentTabOn); notify(_isDraggingInside?TCN_TABDROPPED:TCN_TABDROPPEDOUTSIDE, currentTabOn);
return TRUE; return TRUE;
} }
@ -828,8 +820,8 @@ LRESULT TabBarPlus::runProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lPara
break; break;
} }
//抓取鼠标输入的改变
case WM_CAPTURECHANGED: case WM_CAPTURECHANGED :
{ {
if (_isDragging) if (_isDragging)
{ {
@ -838,20 +830,20 @@ LRESULT TabBarPlus::runProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lPara
} }
break; break;
} }
//重绘tab
case WM_DRAWITEM: case WM_DRAWITEM :
{ {
drawItem((DRAWITEMSTRUCT*)lParam); drawItem((DRAWITEMSTRUCT *)lParam);
return TRUE; return TRUE;
} }
//是否按下control键
case WM_KEYDOWN: case WM_KEYDOWN :
{ {
if (wParam == VK_LCONTROL) if (wParam == VK_LCONTROL)
::SetCursor(::LoadCursor(_hInst, MAKEINTRESOURCE(IDC_DRAG_PLUS_TAB))); ::SetCursor(::LoadCursor(_hInst, MAKEINTRESOURCE(IDC_DRAG_PLUS_TAB)));
return TRUE; return TRUE;
} }
//鼠标中键释放
case WM_MBUTTONUP: case WM_MBUTTONUP:
{ {
int xPos = LOWORD(lParam); int xPos = LOWORD(lParam);
@ -860,7 +852,7 @@ LRESULT TabBarPlus::runProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lPara
notify(TCN_TABDELETE, currentTabOn); notify(TCN_TABDELETE, currentTabOn);
return TRUE; return TRUE;
} }
//双击鼠标左键
case WM_LBUTTONDBLCLK: case WM_LBUTTONDBLCLK:
{ {
if (_isDbClk2Close) if (_isDbClk2Close)
@ -872,7 +864,7 @@ LRESULT TabBarPlus::runProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lPara
} }
return TRUE; return TRUE;
} }
//如果程序正在使用暗黑模式将会用指定的画刷填充整个Tab的客户区代替了系统默认的橡皮擦背景操作。
case WM_ERASEBKGND: case WM_ERASEBKGND:
{ {
if (!NppDarkMode::isEnabled()) if (!NppDarkMode::isEnabled())
@ -886,7 +878,7 @@ LRESULT TabBarPlus::runProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lPara
return 1; return 1;
} }
//在Tab控件需要重绘时调用这里会进行大量的绘制操作内容包括Tab本身和每一个Tab的文字、关闭按钮等元素。
case WM_PAINT: case WM_PAINT:
{ {
if (!NppDarkMode::isEnabled()) if (!NppDarkMode::isEnabled())
@ -1057,8 +1049,8 @@ LRESULT TabBarPlus::runProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lPara
return ::CallWindowProc(_tabBarDefaultProc, hwnd, Message, wParam, lParam); return ::CallWindowProc(_tabBarDefaultProc, hwnd, Message, wParam, lParam);
} }
//实现了Tab的绘制过程包括对Tab背景颜色、文字颜色的调整判断并处理当前Tab的激活状态处理Tab的图标和标题等。
void TabBarPlus::drawItem(DRAWITEMSTRUCT* pDrawItemStruct, bool isDarkMode) void TabBarPlus::drawItem(DRAWITEMSTRUCT *pDrawItemStruct, bool isDarkMode)
{ {
RECT rect = pDrawItemStruct->rcItem; RECT rect = pDrawItemStruct->rcItem;
@ -1071,9 +1063,9 @@ void TabBarPlus::drawItem(DRAWITEMSTRUCT* pDrawItemStruct, bool isDarkMode)
TCHAR label[MAX_PATH] = { '\0' }; TCHAR label[MAX_PATH] = { '\0' };
TCITEM tci{}; TCITEM tci{};
tci.mask = TCIF_TEXT | TCIF_IMAGE; tci.mask = TCIF_TEXT|TCIF_IMAGE;
tci.pszText = label; tci.pszText = label;
tci.cchTextMax = MAX_PATH - 1; tci.cchTextMax = MAX_PATH-1;
if (!::SendMessage(_hSelf, TCM_GETITEM, nTab, reinterpret_cast<LPARAM>(&tci))) if (!::SendMessage(_hSelf, TCM_GETITEM, nTab, reinterpret_cast<LPARAM>(&tci)))
{ {
@ -1379,7 +1371,7 @@ void TabBarPlus::drawItem(DRAWITEMSTRUCT* pDrawItemStruct, bool isDarkMode)
::RestoreDC(hDC, nSavedDC); ::RestoreDC(hDC, nSavedDC);
} }
//用于改变鼠标光标的形状,根据用户托拽标签的不同位置(是否在同一应用中、是否在一个有效的放置位置等)表现为不同的光标形状。
void TabBarPlus::draggingCursor(POINT screenPoint) void TabBarPlus::draggingCursor(POINT screenPoint)
{ {
HWND hWin = ::WindowFromPoint(screenPoint); HWND hWin = ::WindowFromPoint(screenPoint);
@ -1402,7 +1394,7 @@ void TabBarPlus::draggingCursor(POINT screenPoint)
::SetCursor(::LoadCursor(_hInst, MAKEINTRESOURCE(IDC_DRAG_OUT_TAB))); ::SetCursor(::LoadCursor(_hInst, MAKEINTRESOURCE(IDC_DRAG_OUT_TAB)));
} }
} }
//简单地把指定的标签设为活动状态。
void TabBarPlus::setActiveTab(int tabIndex) void TabBarPlus::setActiveTab(int tabIndex)
{ {
// TCM_SETCURFOCUS is busted on WINE/ReactOS for single line (non-TCS_BUTTONS) tabs... // TCM_SETCURFOCUS is busted on WINE/ReactOS for single line (non-TCS_BUTTONS) tabs...
@ -1415,7 +1407,7 @@ void TabBarPlus::setActiveTab(int tabIndex)
::SendMessage(_hSelf, TCM_SETCURSEL, tabIndex, 0); ::SendMessage(_hSelf, TCM_SETCURSEL, tabIndex, 0);
notify(TCN_SELCHANGE, tabIndex); notify(TCN_SELCHANGE, tabIndex);
} }
//交换两个Tab的数据实现两个Tab的位置交换。
void TabBarPlus::exchangeTabItemData(int oldTab, int newTab) void TabBarPlus::exchangeTabItemData(int oldTab, int newTab)
{ {
//1. shift their data, and insert the source //1. shift their data, and insert the source
@ -1457,7 +1449,7 @@ void TabBarPlus::exchangeTabItemData(int oldTab, int newTab)
//2. set to focus //2. set to focus
setActiveTab(newTab); setActiveTab(newTab);
} }
//在接收到鼠标托拽消息的时候被调用,用于各个标签的排序和交换位置。
void TabBarPlus::exchangeItemData(POINT point) void TabBarPlus::exchangeItemData(POINT point)
{ {
// Find the destination tab... // Find the destination tab...
@ -1494,7 +1486,7 @@ void TabBarPlus::exchangeItemData(POINT point)
} }
//用于处理与关闭按钮相关的操作,如获取关闭按钮的大小及位置,判断是否点击到了关闭按钮等。
CloseButtonZone::CloseButtonZone() CloseButtonZone::CloseButtonZone()
{ {
// TODO: get width/height of close button dynamically // TODO: get width/height of close button dynamically
@ -1502,7 +1494,7 @@ CloseButtonZone::CloseButtonZone()
_height = _width; _height = _width;
} }
bool CloseButtonZone::isHit(int x, int y, const RECT& tabRect, bool isVertical) const bool CloseButtonZone::isHit(int x, int y, const RECT & tabRect, bool isVertical) const
{ {
RECT buttonRect = getButtonRectFrom(tabRect, isVertical); RECT buttonRect = getButtonRectFrom(tabRect, isVertical);
@ -1512,7 +1504,7 @@ bool CloseButtonZone::isHit(int x, int y, const RECT& tabRect, bool isVertical)
return false; return false;
} }
RECT CloseButtonZone::getButtonRectFrom(const RECT& tabRect, bool isVertical) const RECT CloseButtonZone::getButtonRectFrom(const RECT & tabRect, bool isVertical) const
{ {
RECT buttonRect{}; RECT buttonRect{};

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

Loading…
Cancel
Save