diff --git a/tests/test_ccolorpickwidget_show_event.cpp b/tests/test_ccolorpickwidget_show_event.cpp new file mode 100644 index 000000000..5f0d01668 --- /dev/null +++ b/tests/test_ccolorpickwidget_show_event.cpp @@ -0,0 +1,133 @@ +// SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd. +// +// SPDX-License-Identifier: GPL-3.0-or-later + +/* + * Unit tests for CColorPickWidget::show() and event() branches + * (issue V-8981 §2). + * + * Source: src/frame/AttributesWidgets/ccolorpickwidget.cpp + * + * Covers: + * - show(int, int): hasBlurWindow() true path (setContent + DArrowRectangle::show) + * and false path (hide + popup m_colorPanel->show). + * - event(): QEvent::Hide and QEvent::Show dispatch to m_colorPanel->hide()/show(). + * + * hasBlurWindow() depends on the window manager and cannot be toggled in CI. + * Both branches are exercised by calling show() — the actual branch taken depends + * on the runtime, but the assertion is "no crash and the widget remains valid." + * event() is tested by explicitly sending Hide/Show events. + */ + +#include +#include + +#include +#include +#include + +#define protected public +#define private public +#include "ccolorpickwidget.h" +#include "private/colorpanel.h" +#undef protected +#undef private + +// =========================================================================== +// show(int, int) — exercises both hasBlurWindow branches +// =========================================================================== + +TEST(CColorPickWidgetShowTest, ShowDoesNotCrashAndWidgetRemainsValid) +{ + CColorPickWidget wgt; + // show(int,int) takes the hasBlurWindow() true or false path depending on + // the runtime; both must complete without crashing. + wgt.show(100, 100); + // Flush pending events so any queued show/hide lands. + QCoreApplication::processEvents(QEventLoop::AllEvents, 200); + // The widget pointer must still be valid (no self-destruct). + EXPECT_NE(&wgt, nullptr); + wgt.hide(); +} + +TEST(CColorPickWidgetShowTest, ColorPanelExistsAfterConstruction) +{ + CColorPickWidget wgt; + // m_colorPanel is created in the constructor; verify it is non-null. + ASSERT_NE(wgt.colorPanel(), nullptr); +} + +TEST(CColorPickWidgetShowTest, MultipleShowCallsDoNotCrash) +{ + CColorPickWidget wgt; + wgt.show(50, 50); + QCoreApplication::processEvents(QEventLoop::AllEvents, 100); + wgt.hide(); + QCoreApplication::processEvents(QEventLoop::AllEvents, 100); + wgt.show(200, 200); + QCoreApplication::processEvents(QEventLoop::AllEvents, 100); + wgt.hide(); + SUCCEED(); +} + +// =========================================================================== +// event() — Hide / Show dispatch to m_colorPanel +// =========================================================================== + +TEST(CColorPickWidgetEventTest, HideEventHidesColorPanel) +{ + CColorPickWidget wgt; + ColorPanel *panel = wgt.colorPanel(); + ASSERT_NE(panel, nullptr); + + // Make the panel visible first so we can observe the hide. + panel->show(); + QCoreApplication::processEvents(QEventLoop::AllEvents, 100); + + // Send a Hide event to the widget; event() should call m_colorPanel->hide(). + QEvent hideEvent(QEvent::Hide); + QCoreApplication::sendEvent(&wgt, &hideEvent); + QCoreApplication::processEvents(QEventLoop::AllEvents, 100); + + // The panel should be hidden now. + EXPECT_FALSE(panel->isVisible()); +} + +TEST(CColorPickWidgetEventTest, ShowEventShowsColorPanel) +{ + CColorPickWidget wgt; + ColorPanel *panel = wgt.colorPanel(); + ASSERT_NE(panel, nullptr); + + // Ensure panel starts hidden. + panel->hide(); + QCoreApplication::processEvents(QEventLoop::AllEvents, 100); + + // Send a Show event to the widget; event() should call m_colorPanel->show(). + QEvent showEvent(QEvent::Show); + QCoreApplication::sendEvent(&wgt, &showEvent); + QCoreApplication::processEvents(QEventLoop::AllEvents, 200); + + // In offscreen mode the panel may not become "visible" in the windowing + // sense; the key assertion is that event() dispatches Show without crash. + // Verify the event was handled (no crash) and the panel object is still valid. + EXPECT_NE(panel, nullptr); + panel->hide(); +} + +TEST(CColorPickWidgetEventTest, OtherEventDoesNotAffectColorPanel) +{ + CColorPickWidget wgt; + ColorPanel *panel = wgt.colorPanel(); + ASSERT_NE(panel, nullptr); + + panel->hide(); + QCoreApplication::processEvents(QEventLoop::AllEvents, 100); + + // A non-Hide/Show event should not change the panel's visibility. + QEvent moveEvent(QEvent::Move); + QCoreApplication::sendEvent(&wgt, &moveEvent); + QCoreApplication::processEvents(QEventLoop::AllEvents, 100); + + EXPECT_FALSE(panel->isVisible()); +} diff --git a/tests/test_filehander_imageio.cpp b/tests/test_filehander_imageio.cpp new file mode 100644 index 000000000..8ff946ba4 --- /dev/null +++ b/tests/test_filehander_imageio.cpp @@ -0,0 +1,258 @@ +// SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd. +// +// SPDX-License-Identifier: GPL-3.0-or-later + +/* + * Unit tests for FileHander::loadImage and saveToImage real-data paths + * (issue V-8981 §4). + * + * Source: src/service/filehander.cpp + * + * Covers: + * - loadImage: valid PNG/JPG load, unsupported suffix, damaged file, + * non-existent path. + * - saveToImage: PNG save, JPG save, PDF branch, TIFF/TIF branch, + * null-render failure, illegal path failure. + * - (Qt6) convertToSRgbColorSpace is exercised implicitly through loadImage. + * + * These tests use real images written to QTemporaryDir and real PageContext + * rendering where needed. The application harness (drawApp) must be running. + */ + +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#define protected public +#define private public +#include "filehander.h" +#include "publicApi.h" +#include "cdrawparamsigleton.h" +#undef protected +#undef private + +// Helper: create a valid small PNG at the given path. +static QString createValidPng(const QString &dirPath, const QString &name = "test.png") +{ + QString path = dirPath + "/" + name; + QImage img(32, 32, QImage::Format_ARGB32); + img.fill(Qt::red); + QPainter p(&img); + p.setPen(Qt::blue); + p.drawLine(0, 0, 31, 31); + p.end(); + img.save(path, "PNG"); + return path; +} + +// Helper: create a valid small JPG at the given path. +static QString createValidJpg(const QString &dirPath, const QString &name = "test.jpg") +{ + QString path = dirPath + "/" + name; + QImage img(32, 32, QImage::Format_RGB32); + img.fill(Qt::green); + QPainter p(&img); + p.setPen(Qt::red); + p.drawRect(2, 2, 28, 28); + p.end(); + img.save(path, "JPG"); + return path; +} + +// Helper: create a damaged file (garbage bytes with .png suffix). +static QString createDamagedFile(const QString &dirPath, const QString &name = "damaged.png") +{ + QString path = dirPath + "/" + name; + QFile f(path); + f.open(QIODevice::WriteOnly); + f.write("NOT_A_PNG_FILE_GARBAGE_DATA_1234567890"); + f.close(); + return path; +} + +// Helper: get current PageContext from the running app. +static PageContext *getCurrentContext() +{ + Page *page = drawApp->topMainWindow()->drawBoard()->currentPage(); + return page ? page->context() : nullptr; +} + +// =========================================================================== +// loadImage — valid image loading +// =========================================================================== + +TEST(FileHanderLoadImageTest, LoadValidPngReturnsNonEmptyImage) +{ + QTemporaryDir dir; + ASSERT_TRUE(dir.isValid()); + QString pngPath = createValidPng(dir.path()); + + FileHander fh; + QImage img = fh.loadImage(pngPath); + EXPECT_FALSE(img.isNull()); + EXPECT_EQ(fh.lastError(), FileHander::NoError); +} + +TEST(FileHanderLoadImageTest, LoadValidJpgReturnsNonEmptyImage) +{ + QTemporaryDir dir; + ASSERT_TRUE(dir.isValid()); + QString jpgPath = createValidJpg(dir.path()); + + FileHander fh; + QImage img = fh.loadImage(jpgPath); + EXPECT_FALSE(img.isNull()); + EXPECT_EQ(fh.lastError(), FileHander::NoError); +} + +// =========================================================================== +// loadImage — error paths +// =========================================================================== + +TEST(FileHanderLoadImageTest, LoadDamagedFileReturnsError) +{ + QTemporaryDir dir; + ASSERT_TRUE(dir.isValid()); + QString damagedPath = createDamagedFile(dir.path()); + + FileHander fh; + QImage img = fh.loadImage(damagedPath); + EXPECT_TRUE(img.isNull()); + EXPECT_EQ(fh.lastError(), FileHander::EDamagedImageFile); +} + +TEST(FileHanderLoadImageTest, LoadNonExistentFileReturnsError) +{ + FileHander fh; + QImage img = fh.loadImage("/tmp/no_such_dir_12345/nonexistent.png"); + EXPECT_TRUE(img.isNull()); + EXPECT_NE(fh.lastError(), FileHander::NoError); +} + +TEST(FileHanderLoadImageTest, LoadUnsupportedSuffixReturnsError) +{ + QTemporaryDir dir; + ASSERT_TRUE(dir.isValid()); + QString path = dir.path() + "/test.xyz"; + QFile f(path); + f.open(QIODevice::WriteOnly); + f.write("data"); + f.close(); + + FileHander fh; + QImage img = fh.loadImage(path); + EXPECT_TRUE(img.isNull()); + EXPECT_NE(fh.lastError(), FileHander::NoError); +} + +TEST(FileHanderLoadImageTest, LoadEmptyPathReturnsEmptyImage) +{ + FileHander fh; + QImage img = fh.loadImage(""); + EXPECT_TRUE(img.isNull()); +} + +// =========================================================================== +// saveToImage — valid saves +// =========================================================================== + +TEST(FileHanderSaveToImageTest, SavePngSucceeds) +{ + QTemporaryDir dir; + ASSERT_TRUE(dir.isValid()); + PageContext *ctx = getCurrentContext(); + ASSERT_NE(ctx, nullptr); + + QString path = dir.path() + "/output.png"; + FileHander fh; + bool ok = fh.saveToImage(ctx, path, QSize(100, 100), 100); + EXPECT_TRUE(ok); + EXPECT_TRUE(QFileInfo::exists(path)); +} + +TEST(FileHanderSaveToImageTest, SaveJpgSucceeds) +{ + QTemporaryDir dir; + ASSERT_TRUE(dir.isValid()); + PageContext *ctx = getCurrentContext(); + ASSERT_NE(ctx, nullptr); + + QString path = dir.path() + "/output.jpg"; + FileHander fh; + bool ok = fh.saveToImage(ctx, path, QSize(100, 100), 90); + EXPECT_TRUE(ok); + EXPECT_TRUE(QFileInfo::exists(path)); +} + +TEST(FileHanderSaveToImageTest, SavePdfSucceeds) +{ + QTemporaryDir dir; + ASSERT_TRUE(dir.isValid()); + PageContext *ctx = getCurrentContext(); + ASSERT_NE(ctx, nullptr); + + QString path = dir.path() + "/output.pdf"; + FileHander fh; + bool ok = fh.saveToImage(ctx, path, QSize(100, 100), 100); + EXPECT_TRUE(ok); + EXPECT_TRUE(QFileInfo::exists(path)); +} + +TEST(FileHanderSaveToImageTest, SaveTiffSucceeds) +{ + QTemporaryDir dir; + ASSERT_TRUE(dir.isValid()); + PageContext *ctx = getCurrentContext(); + ASSERT_NE(ctx, nullptr); + + QString path = dir.path() + "/output.tiff"; + FileHander fh; + bool ok = fh.saveToImage(ctx, path, QSize(100, 100), 100); + // TIFF support depends on Qt image format plugins; if it fails the + // error should be non-zero. + if (ok) { + EXPECT_TRUE(QFileInfo::exists(path)); + } else { + EXPECT_NE(fh.lastError(), FileHander::NoError); + } +} + +// =========================================================================== +// saveToImage — failure paths +// =========================================================================== + +TEST(FileHanderSaveToImageTest, SaveToEmptyPathReturnsFalse) +{ + FileHander fh; + bool ok = fh.saveToImage(nullptr, ""); + EXPECT_FALSE(ok); +} + +TEST(FileHanderSaveToImageTest, SaveToIllegalPathReturnsFalse) +{ + PageContext *ctx = getCurrentContext(); + ASSERT_NE(ctx, nullptr); + + FileHander fh; + // Non-existent parent directory. + bool ok = fh.saveToImage(ctx, "/tmp/no_such_dir_12345/output.png"); + EXPECT_FALSE(ok); +} + +TEST(FileHanderSaveToImageTest, SaveToDirectoryPathReturnsFalse) +{ + PageContext *ctx = getCurrentContext(); + ASSERT_NE(ctx, nullptr); + + FileHander fh; + // A directory path (no actual file component) should fail to save. + bool ok = fh.saveToImage(ctx, "/tmp/"); + EXPECT_FALSE(ok); +} diff --git a/tests/test_pagecontext_save.cpp b/tests/test_pagecontext_save.cpp new file mode 100644 index 000000000..c8abd8c46 --- /dev/null +++ b/tests/test_pagecontext_save.cpp @@ -0,0 +1,184 @@ +// SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd. +// +// SPDX-License-Identifier: GPL-3.0-or-later + +/* + * Unit tests for PageContext::save branches (issue V-8981 §5). + * + * Source: src/drawshape/cdrawparamsigleton.cpp + * + * Covers: + * - save(""): uses current file; file is empty → returns false. + * - save("") with a non-empty current file and !isDirty() → returns true (skip). + * - save with .ddf suffix → delegates to saveToDdf. + * - save with non-ddf suffix (e.g. .png) → delegates to saveToImage; + * on success updates file path and clears dirty state. + * + * These tests use the running application harness (drawApp) to obtain a + * PageContext and QTemporaryDir for temp file management. + */ + +#include +#include + +#include +#include +#include + +#define protected public +#define private public +#include "publicApi.h" +#include "cdrawparamsigleton.h" +#include "ccentralwidget.h" +#include "filehander.h" +#undef protected +#undef private + +// Helper: get a fresh PageContext with a clean page. +static PageContext *getFreshContext() +{ + ensurePageExists(); + Page *page = drawApp->topMainWindow()->drawBoard()->currentPage(); + return page ? page->context() : nullptr; +} + +// =========================================================================== +// save("") — empty file path, file() is also empty → returns false +// =========================================================================== + +TEST(PageContextSaveTest, SaveEmptyFilePathWhenFileIsEmptyReturnsFalse) +{ + PageContext *ctx = getFreshContext(); + ASSERT_NE(ctx, nullptr); + + // Ensure the context's file is empty. + ctx->setFile(""); + ctx->setDirty(false); + + bool result = ctx->save(""); + EXPECT_FALSE(result); +} + +// =========================================================================== +// save("") — uses current file; !isDirty() → returns true (skip save) +// =========================================================================== + +TEST(PageContextSaveTest, SaveEmptyFilePathWhenNotDirtyReturnsTrue) +{ + PageContext *ctx = getFreshContext(); + ASSERT_NE(ctx, nullptr); + + // Set a file path and mark as not dirty. + ctx->setFile("/tmp/test_skip_save.ddf"); + ctx->setDirty(false); + + // save("") should use the current file, see !isDirty(), and return true + // without actually writing. + bool result = ctx->save(""); + EXPECT_TRUE(result); + + // Clean up. + ctx->setFile(""); +} + +// =========================================================================== +// save with .png suffix → saveToImage path, updates file & dirty +// =========================================================================== + +TEST(PageContextSaveTest, SavePngUpdatesFileAndClearsDirty) +{ + QTemporaryDir dir; + ASSERT_TRUE(dir.isValid()); + + PageContext *ctx = getFreshContext(); + ASSERT_NE(ctx, nullptr); + + ctx->setDirty(true); + QString pngPath = dir.path() + "/save_test.png"; + + bool result = ctx->save(pngPath); + EXPECT_TRUE(result); + + // On successful image save, file() should be updated and dirty cleared. + EXPECT_EQ(ctx->file(), pngPath); + EXPECT_FALSE(ctx->isDirty()); + + // Clean up. + ctx->setFile(""); +} + +// =========================================================================== +// save with .png to illegal path → returns false +// =========================================================================== + +TEST(PageContextSaveTest, SavePngToIllegalPathReturnsFalse) +{ + PageContext *ctx = getFreshContext(); + ASSERT_NE(ctx, nullptr); + + ctx->setDirty(true); + + // Non-existent parent directory. + bool result = ctx->save("/tmp/no_such_dir_12345/save_test.png"); + EXPECT_FALSE(result); +} + +// =========================================================================== +// save with .ddf suffix → delegates to saveToDdf +// =========================================================================== + +TEST(PageContextSaveTest, SaveDdfDoesNotCrash) +{ + QTemporaryDir dir; + ASSERT_TRUE(dir.isValid()); + + PageContext *ctx = getFreshContext(); + ASSERT_NE(ctx, nullptr); + + ctx->setDirty(true); + QString ddfPath = dir.path() + "/save_test.ddf"; + + // saveToDdf may succeed or fail depending on the internal serialization, + // but it must not crash. If it succeeds, the file should exist. + bool result = ctx->save(ddfPath); + if (result) { + // saveToDdf does not update file()/dirty in the save() code path + // (only the image path does), so we just verify no crash. + SUCCEED(); + } else { + // Failure is acceptable if the DDF serialization has prerequisites + // not met in the test harness. + SUCCEED(); + } + + // Clean up. + ctx->setFile(""); +} + +// =========================================================================== +// save("") with current file set and isDirty() → triggers actual save +// =========================================================================== + +TEST(PageContextSaveTest, SaveEmptyPathWithDirtyFileTriggersSave) +{ + QTemporaryDir dir; + ASSERT_TRUE(dir.isValid()); + + PageContext *ctx = getFreshContext(); + ASSERT_NE(ctx, nullptr); + + // Set a current file path and mark dirty. + QString imgPath = dir.path() + "/current.png"; + ctx->setFile(imgPath); + ctx->setDirty(true); + + // save("") should use the current file path and perform the save. + bool result = ctx->save(""); + EXPECT_TRUE(result); + + // After successful save, dirty should be cleared. + EXPECT_FALSE(ctx->isDirty()); + + // Clean up. + ctx->setFile(""); +} diff --git a/tests/test_tabbarwgt_lambdas.cpp b/tests/test_tabbarwgt_lambdas.cpp new file mode 100644 index 000000000..e98346293 --- /dev/null +++ b/tests/test_tabbarwgt_lambdas.cpp @@ -0,0 +1,229 @@ +// SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd. +// +// SPDX-License-Identifier: GPL-3.0-or-later + +/* + * Unit tests for TabBarWgt signal lambdas and "Close other tabs" action + * (issue V-8981 §3). + * + * Source: src/frame/cmultiptabbarwidget.cpp + * + * Covers: + * - Constructor lambda: tabAddRequested → pageManager()->addPage() + * - Constructor lambda: tabCloseRequested → pageManager()->closePage(key) + * - Constructor lambda: currentChanged → pageManager()->setCurrentPage(key) + * - menu() "Close other tabs" action lambda (including closePage-false break) + * + * TabBarWgt's constructor is private; the friend DrawBoard grants access. + * We use `#define private public` to construct TabBarWgt directly against the + * running DrawBoard from the test harness. + */ + +#include +#include + +#include +#include +#include + +#include "publicApi.h" + +#define protected public +#define private public +#include "cmultiptabbarwidget.h" +#include "ccentralwidget.h" +#undef protected +#undef private + +// Helper: get the running DrawBoard. +static DrawBoard *getBoard() +{ + MainWindow *mw = drawApp->topMainWindow(); + return mw->drawBoard(); +} + +// =========================================================================== +// tabAddRequested → pageManager()->addPage() +// =========================================================================== + +TEST(TabBarWgtLambdaTest, TabAddRequestedAddsPage) +{ + DrawBoard *board = getBoard(); + ASSERT_NE(board, nullptr); + int initialCount = board->count(); + + TabBarWgt bar(board); + bar.show(); + + // Emit tabAddRequested to trigger the constructor lambda. + emit bar.tabAddRequested(); + QCoreApplication::processEvents(QEventLoop::AllEvents, 200); + + // A new page should have been added. + EXPECT_EQ(board->count(), initialCount + 1); + + // Clean up: close the added page. + while (board->count() > initialCount) { + Page *p = board->currentPage(); + if (p == nullptr || !p->close(true)) + break; + QCoreApplication::sendPostedEvents(board, QEvent::MetaCall); + } +} + +// =========================================================================== +// tabCloseRequested → pageManager()->closePage(key) +// =========================================================================== + +TEST(TabBarWgtLambdaTest, TabCloseRequestedClosesPage) +{ + DrawBoard *board = getBoard(); + ASSERT_NE(board, nullptr); + + // Add two pages so we have one to close. + Page *p1 = board->addPage(); + ASSERT_NE(p1, nullptr); + Page *p2 = board->addPage(); + ASSERT_NE(p2, nullptr); + int countBefore = board->count(); + + TabBarWgt bar(board); + bar.show(); + + // Add tabs to the bar matching the pages. + bar.addItem(p1->name(), p1->key()); + bar.addItem(p2->name(), p2->key()); + + // Emit tabCloseRequested for index 0 (p1's tab). + emit bar.tabCloseRequested(0); + QCoreApplication::processEvents(QEventLoop::AllEvents, 200); + + // At least one page should have been closed. + EXPECT_LE(board->count(), countBefore); + + // Clean up remaining test pages. + while (board->count() > 1) { + Page *p = board->currentPage(); + if (p == nullptr || !p->close(true)) + break; + QCoreApplication::sendPostedEvents(board, QEvent::MetaCall); + } +} + +// =========================================================================== +// currentChanged → pageManager()->setCurrentPage(key) +// =========================================================================== + +TEST(TabBarWgtLambdaTest, CurrentChangedSwitchesPage) +{ + DrawBoard *board = getBoard(); + ASSERT_NE(board, nullptr); + + Page *p1 = board->addPage(); + ASSERT_NE(p1, nullptr); + Page *p2 = board->addPage(); + ASSERT_NE(p2, nullptr); + + // Make p1 the current page first. + board->setCurrentPage(p1); + QCoreApplication::processEvents(QEventLoop::AllEvents, 200); + EXPECT_EQ(board->currentPage(), p1); + + TabBarWgt bar(board); + bar.show(); + bar.addItem(p1->name(), p1->key()); + bar.addItem(p2->name(), p2->key()); + + // Emit currentChanged with index 1 (p2's tab) to trigger the lambda. + emit bar.currentChanged(1); + QCoreApplication::processEvents(QEventLoop::AllEvents, 200); + + // The current page should now be p2. + EXPECT_EQ(board->currentPage()->key(), p2->key()); + + // Clean up. + while (board->count() > 1) { + Page *p = board->currentPage(); + if (p == nullptr || !p->close(true)) + break; + QCoreApplication::sendPostedEvents(board, QEvent::MetaCall); + } +} + +// =========================================================================== +// menu() "Close other tabs" action — iterates and closes non-current pages. +// The lambda uses key(currentIndex()) to determine which page to keep, so +// we must add tabs for ALL pages and set the bar's current index correctly. +// NOTE: menu() returns a static singleton with the TabBarWgt as parent; +// the menu is destroyed when its parent TabBarWgt is destroyed, so only the +// first TabBarWgt to call menu() gets a valid menu. Both sub-scenarios are +// tested in one TEST to keep the menu alive throughout. +// =========================================================================== + +TEST(TabBarWgtLambdaTest, CloseOtherTabsActionClosesNonCurrentPages) +{ + DrawBoard *board = getBoard(); + ASSERT_NE(board, nullptr); + + // Start from a clean baseline (1 page). + while (board->count() > 1) { + Page *p = board->currentPage(); + if (p == nullptr || !p->close(true)) + break; + QCoreApplication::sendPostedEvents(board, QEvent::MetaCall); + } + ASSERT_EQ(board->count(), 1); + + // Remember the initial page and add two extra pages (3 total). + Page *p0 = board->currentPage(); + ASSERT_NE(p0, nullptr); + Page *p1 = board->addPage(); + ASSERT_NE(p1, nullptr); + Page *p2 = board->addPage(); + ASSERT_NE(p2, nullptr); + EXPECT_EQ(board->count(), 3); + + TabBarWgt bar(board); + bar.show(); + + // Add tabs for ALL pages so key(currentIndex()) resolves to a real page. + bar.addItem(p0->name(), p0->key()); // index 0 + bar.addItem(p1->name(), p1->key()); // index 1 + bar.addItem(p2->name(), p2->key()); // index 2 + + // Set the bar's current index to p2's tab so p2 survives "close others". + bar.setCurrentIndex(2); + QCoreApplication::processEvents(QEventLoop::AllEvents, 200); + + QMenu *m = bar.menu(); + ASSERT_NE(m, nullptr); + + // Find the "Close other tabs" action and trigger it. + auto actions = m->actions(); + QAction *closeOtherAction = nullptr; + for (QAction *act : actions) { + if (act->text().contains("other", Qt::CaseInsensitive) || + act->text().contains("其他", Qt::CaseInsensitive)) { + closeOtherAction = act; + break; + } + } + ASSERT_NE(closeOtherAction, nullptr); + + closeOtherAction->trigger(); + QCoreApplication::processEvents(QEventLoop::AllEvents, 300); + + // After "close other tabs", only the current page (p2) should remain. + EXPECT_EQ(board->count(), 1); + if (board->currentPage() != nullptr) { + EXPECT_EQ(board->currentPage()->key(), p2->key()); + } + + // --- Sub-scenario: with only one page, "close other tabs" is a no-op --- + // The menu is still valid because bar is still alive. + closeOtherAction->trigger(); + QCoreApplication::processEvents(QEventLoop::AllEvents, 200); + + // Still one page — the loop immediately exits with no non-current pages. + EXPECT_EQ(board->count(), 1); +} diff --git a/tests/test_toolbutton_paint_branches.cpp b/tests/test_toolbutton_paint_branches.cpp new file mode 100644 index 000000000..06228ac2e --- /dev/null +++ b/tests/test_toolbutton_paint_branches.cpp @@ -0,0 +1,270 @@ +// SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd. +// +// SPDX-License-Identifier: GPL-3.0-or-later + +/* + * Unit tests for ToolButton paintEvent / sizeHint / getPen branches + * not covered by existing test_toolbutton*.cpp (issue V-8981 §1). + * + * Source: src/widgets/toolbutton.cpp + * + * Covers: + * - paintEvent: MENU_STYLE with State_On highlight background, + * State_MouseOver shadow background, and the corresponding text color + * branches (highlightedText / text). + * - sizeHint: BUTTON_STYLE with icon and menu indicator width; + * MENU_STYLE with empty text falling back to placeholder "XXXX". + * - getPen: dark-theme (themeType != 1) and light-theme (themeType == 1) + * for disabled / MouseOver / Sunken / normal states. + * + * paintEvent is exercised by rendering the widget onto an offscreen QImage, + * which issues a paint event. All assertions are crash-safety + observable + * property checks, keeping the tests headless-safe. + */ + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +DGUI_USE_NAMESPACE + +#define protected public +#define private public +#include "toolbutton.h" +#undef protected +#undef private + +// ---- helper: render a widget onto an offscreen QImage (issues paintEvent) ---- +static bool renderToImage(QWidget &w) +{ + if (w.size().isEmpty()) + w.resize(100, 36); + QImage img(w.size(), QImage::Format_ARGB32); + img.fill(Qt::transparent); + QPainter p(&img); + w.render(&p); + return !img.isNull(); +} + +// =========================================================================== +// paintEvent — MENU_STYLE State_On / State_MouseOver background & text branches +// =========================================================================== + +TEST(ToolButtonPaintBranchTest, MenuStyleOnStateRendersWithoutCrash) +{ + ToolButton btn(nullptr, MENU_STYLE); + btn.setShowText(false); + btn.setText(QStringLiteral("Cut")); + QPixmap pix(16, 16); + pix.fill(Qt::red); + btn.setIcon(QIcon(pix)); + btn.resize(100, 36); + btn.setChecked(true); + btn.setCheckable(true); + EXPECT_TRUE(renderToImage(btn)); +} + +TEST(ToolButtonPaintBranchTest, MenuStyleMouseOverRendersWithoutCrash) +{ + ToolButton btn(nullptr, MENU_STYLE); + btn.setShowText(false); + btn.setText(QStringLiteral("Copy")); + QPixmap pix(16, 16); + pix.fill(Qt::blue); + btn.setIcon(QIcon(pix)); + btn.resize(100, 36); + // Simulate mouse-over by entering the widget's geometry. + btn.setAttribute(Qt::WA_UnderMouse, true); + EXPECT_TRUE(renderToImage(btn)); + btn.setAttribute(Qt::WA_UnderMouse, false); +} + +TEST(ToolButtonPaintBranchTest, MenuStyleNoIconRendersWithoutCrash) +{ + // Exercises the icon().isNull() branch inside paintEvent. + ToolButton btn(nullptr, MENU_STYLE); + btn.setShowText(false); + btn.setText(QStringLiteral("NoIcon")); + btn.resize(100, 36); + EXPECT_TRUE(renderToImage(btn)); +} + +TEST(ToolButtonPaintBranchTest, MenuStyleAlignCenterRendersWithoutCrash) +{ + // Exercises the m_alignment != AlignLeft path. + ToolButton btn(nullptr, MENU_STYLE); + btn.setShowText(false); + btn.setText(QStringLiteral("Centered")); + btn.setAlignment(Qt::AlignCenter); + QPixmap pix(16, 16); + pix.fill(Qt::green); + btn.setIcon(QIcon(pix)); + btn.resize(120, 36); + EXPECT_TRUE(renderToImage(btn)); +} + +// =========================================================================== +// sizeHint — icon / menu / placeholder-text branches +// =========================================================================== + +TEST(ToolButtonSizeHintBranchTest, ButtonStyleWithoutShowTextWithIconReturnsNonZero) +{ + ToolButton btn(nullptr, BUTTON_STYLE); + btn.setShowText(false); + QPixmap pix(32, 32); + pix.fill(Qt::red); + btn.setIcon(QIcon(pix)); + const QSize sz = btn.sizeHint(); + // With an icon, width should reflect iconSize. + EXPECT_GT(sz.width(), 0); +} + +TEST(ToolButtonSizeHintBranchTest, ButtonStyleWithoutShowTextWithMenuReturnsLargerWidth) +{ + ToolButton btn(nullptr, BUTTON_STYLE); + btn.setShowText(false); + QPixmap pix(32, 32); + pix.fill(Qt::red); + btn.setIcon(QIcon(pix)); + + // Without menu + const QSize szNoMenu = btn.sizeHint(); + + // With a menu — adds PM_MenuButtonIndicator width. + QMenu *menu = new QMenu(&btn); + menu->addAction("A"); + btn.setMenu(menu); + const QSize szWithMenu = btn.sizeHint(); + + EXPECT_GE(szWithMenu.width(), szNoMenu.width()); +} + +TEST(ToolButtonSizeHintBranchTest, MenuStyleEmptyTextUsesPlaceholderFallback) +{ + // MENU_STYLE with empty text and !m_bShowText: the "XXXX" placeholder + // path in sizeHint is exercised. + ToolButton btn(nullptr, MENU_STYLE); + btn.setShowText(false); + btn.setText(QString()); // empty text + const QSize sz = btn.sizeHint(); + // Placeholder "XXXX" guarantees a non-zero size. + EXPECT_GT(sz.width(), 0); + EXPECT_GT(sz.height(), 0); +} + +TEST(ToolButtonSizeHintBranchTest, MenuStyleEmptyTextWithIconReturnsNonZero) +{ + // MENU_STYLE, empty text, with icon: the `!empty || !w` / `!empty || !h` + // branches where w and h are non-zero from the icon. + ToolButton btn(nullptr, MENU_STYLE); + btn.setShowText(false); + btn.setText(QString()); + QPixmap pix(32, 32); + pix.fill(Qt::red); + btn.setIcon(QIcon(pix)); + const QSize sz = btn.sizeHint(); + EXPECT_GT(sz.width(), 0); + EXPECT_GT(sz.height(), 0); +} + +// =========================================================================== +// getPen — all state × theme combinations +// =========================================================================== + +TEST(ToolButtonGetPenBranchTest, LightThemeDisabledReturnsGrayPen) +{ + DGuiApplicationHelper::instance()->setPaletteType(DGuiApplicationHelper::LightType); + ToolButton btn(nullptr, MENU_STYLE); + QStyleOptionButton opt; + opt.state = QStyle::State_None; // not enabled + QPen pen = btn.getPen(opt); + EXPECT_EQ(pen.color(), QColor("#9C9C9C")); +} + +TEST(ToolButtonGetPenBranchTest, LightThemeMouseOverReturnsWhitePen) +{ + DGuiApplicationHelper::instance()->setPaletteType(DGuiApplicationHelper::LightType); + ToolButton btn(nullptr, MENU_STYLE); + QStyleOptionButton opt; + opt.state = QStyle::State_Enabled | QStyle::State_MouseOver; + QPen pen = btn.getPen(opt); + EXPECT_EQ(pen.color(), QColor(Qt::white)); +} + +TEST(ToolButtonGetPenBranchTest, LightThemeSunkenReturnsBluePen) +{ + DGuiApplicationHelper::instance()->setPaletteType(DGuiApplicationHelper::LightType); + ToolButton btn(nullptr, MENU_STYLE); + QStyleOptionButton opt; + opt.state = QStyle::State_Enabled | QStyle::State_Sunken; + QPen pen = btn.getPen(opt); + EXPECT_EQ(pen.color(), QColor("#99cdff")); +} + +TEST(ToolButtonGetPenBranchTest, LightThemeNormalReturnsDarkPen) +{ + DGuiApplicationHelper::instance()->setPaletteType(DGuiApplicationHelper::LightType); + ToolButton btn(nullptr, MENU_STYLE); + QStyleOptionButton opt; + opt.state = QStyle::State_Enabled; + QPen pen = btn.getPen(opt); + EXPECT_EQ(pen.color(), QColor("#343434")); +} + +TEST(ToolButtonGetPenBranchTest, DarkThemeDisabledReturnsGrayPen) +{ + DGuiApplicationHelper::instance()->setPaletteType(DGuiApplicationHelper::DarkType); + ToolButton btn(nullptr, MENU_STYLE); + QStyleOptionButton opt; + opt.state = QStyle::State_None; + QPen pen = btn.getPen(opt); + EXPECT_EQ(pen.color(), QColor("#8D8D8D")); +} + +TEST(ToolButtonGetPenBranchTest, DarkThemeMouseOverReturnsWhitePen) +{ + DGuiApplicationHelper::instance()->setPaletteType(DGuiApplicationHelper::DarkType); + ToolButton btn(nullptr, MENU_STYLE); + QStyleOptionButton opt; + opt.state = QStyle::State_Enabled | QStyle::State_MouseOver; + QPen pen = btn.getPen(opt); + EXPECT_EQ(pen.color(), QColor(Qt::white)); +} + +TEST(ToolButtonGetPenBranchTest, DarkThemeSunkenReturnsBluePen) +{ + DGuiApplicationHelper::instance()->setPaletteType(DGuiApplicationHelper::DarkType); + ToolButton btn(nullptr, MENU_STYLE); + QStyleOptionButton opt; + opt.state = QStyle::State_Enabled | QStyle::State_Sunken; + QPen pen = btn.getPen(opt); + EXPECT_EQ(pen.color(), QColor("#99cdff")); +} + +TEST(ToolButtonGetPenBranchTest, DarkThemeNormalReturnsWhitePen) +{ + DGuiApplicationHelper::instance()->setPaletteType(DGuiApplicationHelper::DarkType); + ToolButton btn(nullptr, MENU_STYLE); + QStyleOptionButton opt; + opt.state = QStyle::State_Enabled; + QPen pen = btn.getPen(opt); + EXPECT_EQ(pen.color(), QColor(Qt::white)); +} + +// Reset palette type to auto after all getPen tests to avoid leaking state. +TEST(ToolButtonGetPenBranchTest, ResetPaletteTypeToAuto) +{ + DGuiApplicationHelper::instance()->setPaletteType(DGuiApplicationHelper::UnknownType); + SUCCEED(); +}