-
Notifications
You must be signed in to change notification settings - Fork 101
Expand file tree
/
Copy pathqt_template_page.cpp
More file actions
726 lines (629 loc) · 25.8 KB
/
Copy pathqt_template_page.cpp
File metadata and controls
726 lines (629 loc) · 25.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
/******************************************************************************
* MODULE : qt_template_page.cpp
* DESCRIPTION: Template page implementation for startup tab
* COPYRIGHT : (C) 2026 Yuki Lu
******************************************************************************/
#include "qt_template_page.hpp"
#include <QDialog>
#include <QDialogButtonBox>
#include <QEvent>
#include <QFrame>
#include <QGridLayout>
#include <QGuiApplication>
#include <QHBoxLayout>
#include <QLabel>
#include <QMessageBox>
#include <QMouseEvent>
#include <QProgressDialog>
#include <QPushButton>
#include <QResizeEvent>
#include <QScreen>
#include <QScrollArea>
#include <QShowEvent>
#include <QStyle>
#include <QTimer>
#include <QVBoxLayout>
#include "qt_dpi_utils.hpp"
#include "qt_pdf_preview_widget.hpp"
#include "qt_utilities.hpp"
#include "template_manager.hpp"
#include "thumbnail_loader.hpp"
namespace {
// 预览图片尺寸(增大预览区域)
constexpr int PREVIEW_IMAGE_WIDTH= 600;
// 缩略图尺寸(使用2x尺寸以便在高分屏上显示清晰)
constexpr int THUMBNAIL_WIDTH = 160;
constexpr int THUMBNAIL_HEIGHT= 227;
constexpr int kPageMargin = 16; // 页面边距(减小边白)
constexpr int kPageSpacing = 24; // 页面主布局间距
constexpr int kCategorySpacing = 8; // 分类按钮间距
constexpr int kGridSpacing = 16; // 模板网格间距
constexpr int kCardWidth = 176; // 模板卡片宽度
constexpr int kCardHeight = 243; // 模板卡片高度(仅缩略图区域)
constexpr int kCardMargin = 8; // 卡片内边距
constexpr int kCardSpacing = 5; // 卡片内部间距
constexpr int kNameLabelMaxWidth = 176; // 模板名称最大宽度
constexpr int kNameLabelMaxHeight = 40; // 模板名称最大高度
constexpr int kPreviewDialogMinW = 700; // 预览弹窗最小宽度
constexpr int kPreviewDialogMinH = 800; // 预览弹窗最小高度
constexpr int kPreviewLayoutSpacing= 16; // 预览弹窗布局间距
constexpr int kPreviewLayoutMargin = 24; // 预览弹窗布局边距
constexpr int kPageTitleFontPx = 24; // 页面标题字号
constexpr int kLoadingFontPx = 14; // Loading 文案字号
constexpr int kTemplateNameFontPx = 11; // 模板名称字号
constexpr int kPreviewTitleFontPx = 18; // 预览标题字号
constexpr int kPreviewDescFontPx = 14; // 预览描述字号
constexpr int kUseButtonFontPx = 13; // Use Template 按钮字号
constexpr int kInfoFontPx = 10; // 模板信息字号
constexpr int kUseButtonRadiusPx = 4; // Use Template 按钮圆角
constexpr int kUseButtonPadYPx = 8; // Use Template 按钮纵向内边距
constexpr int kUseButtonPadXPx = 24; // Use Template 按钮横向内边距
constexpr int kGridMarginYPx = 5; // 网格布局上下边距
constexpr int kGridMarginXPx = 10; // 网格布局左右边距
constexpr int kCategoryBtnRadiusPx = 12; // 分类按钮圆角
constexpr int kCategoryBtnPadYPx = 6; // 分类按钮纵向内边距
constexpr int kCategoryBtnPadXPx = 14; // 分类按钮横向内边距
constexpr int kCardRadiusPx = 8; // 模板卡片圆角
} // namespace
QTTemplatePage::QTTemplatePage (QWidget* parent)
: QWidget (parent), titleLabel_ (nullptr), categoryBar_ (nullptr),
scrollArea_ (nullptr), gridWidget_ (nullptr), gridLayout_ (nullptr),
progressDialog_ (nullptr), templateManager_ (nullptr),
currentCategory_ (""), activeCategoryBtn_ (nullptr),
resizeDebounceTimer_ (nullptr) {
resizeDebounceTimer_= new QTimer (this);
resizeDebounceTimer_->setSingleShot (true);
resizeDebounceTimer_->setInterval (200);
connect (resizeDebounceTimer_, &QTimer::timeout, this, [this] () {
if (templateManager_ && templateManager_->isInitialized ()) {
int newColumnCount= calculateColumnCount ();
if (newColumnCount != currentColumnCount_) {
refreshTemplateGrid (currentCategory_);
}
}
});
setupUI ();
}
QTTemplatePage::~QTTemplatePage () {}
void
QTTemplatePage::initialize () {
templateManager_= TemplateManager::instance ();
// Connect signals (safe to call multiple times due to Qt's auto-connection)
connect (templateManager_, &TemplateManager::templatesLoaded, this,
&QTTemplatePage::onTemplatesLoaded, Qt::UniqueConnection);
connect (templateManager_, &TemplateManager::categoriesLoaded, this,
&QTTemplatePage::onCategoriesLoaded, Qt::UniqueConnection);
connect (templateManager_, &TemplateManager::downloadProgress, this,
&QTTemplatePage::onDownloadProgress, Qt::UniqueConnection);
connect (templateManager_, &TemplateManager::downloadCompleted, this,
&QTTemplatePage::onDownloadCompleted, Qt::UniqueConnection);
connect (templateManager_, &TemplateManager::downloadFailed, this,
&QTTemplatePage::onDownloadFailed, Qt::UniqueConnection);
// Check if already initialized with data
if (templateManager_->isInitialized () &&
!templateManager_->templates ().isEmpty ()) {
// Already have data, refresh immediately
onTemplatesLoaded ();
}
else if (!templateManager_->isInitialized ()) {
// Initialize asynchronously
QTimer::singleShot (0, this,
[this] () { templateManager_->initialize (); });
}
}
void
QTTemplatePage::setupUI () {
QVBoxLayout* layout= new QVBoxLayout (this);
layout->setContentsMargins (
DpiUtils::scaled (kPageMargin), DpiUtils::scaled (kPageMargin),
DpiUtils::scaled (kPageMargin), DpiUtils::scaled (kPageMargin));
layout->setSpacing (DpiUtils::scaled (kPageSpacing));
// Title
titleLabel_= new QLabel (qt_translate ("Template Center"), this);
titleLabel_->setObjectName ("startup-tab-page-title");
DpiUtils::applyScaledFont (titleLabel_, kPageTitleFontPx);
layout->addWidget (titleLabel_);
// Category bar
categoryBar_= new QWidget (this);
categoryBar_->setObjectName ("startup-tab-category-bar");
QHBoxLayout* categoryLayout= new QHBoxLayout (categoryBar_);
categoryLayout->setContentsMargins (0, 0, 0, 0);
categoryLayout->setSpacing (DpiUtils::scaled (kCategorySpacing));
layout->addWidget (categoryBar_);
// Scroll area for templates
scrollArea_= new QScrollArea (this);
scrollArea_->setWidgetResizable (true);
scrollArea_->setFrameShape (QFrame::NoFrame);
scrollArea_->setHorizontalScrollBarPolicy (Qt::ScrollBarAlwaysOff);
gridWidget_= new QWidget (scrollArea_);
gridWidget_->setObjectName ("startup-tab-grid");
gridLayout_= new QGridLayout (gridWidget_);
gridLayout_->setSpacing (DpiUtils::scaled (kGridSpacing));
gridLayout_->setContentsMargins (
DpiUtils::scaled (kGridMarginXPx), DpiUtils::scaled (kGridMarginYPx),
DpiUtils::scaled (kGridMarginXPx), DpiUtils::scaled (kGridMarginYPx));
scrollArea_->setWidget (gridWidget_);
layout->addWidget (scrollArea_, 1);
// Loading label
QLabel* loadingLabel=
new QLabel (qt_translate ("Loading templates..."), gridWidget_);
loadingLabel->setObjectName ("startup-tab-loading");
loadingLabel->setAlignment (Qt::AlignCenter);
DpiUtils::applyScaledFont (loadingLabel, kLoadingFontPx);
gridLayout_->addWidget (loadingLabel, 0, 0, 1, 1);
}
void
QTTemplatePage::setupCategoryBar () {
if (!categoryBar_) return;
activeCategoryBtn_= nullptr;
// Clear existing buttons
QLayout* layout= categoryBar_->layout ();
if (layout) {
QLayoutItem* item;
while ((item= layout->takeAt (0)) != nullptr) {
if (item->widget ()) {
delete item->widget ();
}
delete item;
}
}
if (!templateManager_) return;
QHBoxLayout* categoryLayout= qobject_cast<QHBoxLayout*> (layout);
if (!categoryLayout) return;
// Helper: apply category button style
auto styleCategoryBtn= [] (QPushButton* btn) {
btn->setStyleSheet (QString ("QPushButton#startup-tab-category-btn {"
" border-radius: %1px;"
" padding: %2px %3px;"
"}")
.arg (DpiUtils::scaled (kCategoryBtnRadiusPx))
.arg (DpiUtils::scaled (kCategoryBtnPadYPx))
.arg (DpiUtils::scaled (kCategoryBtnPadXPx)));
btn->setCursor (Qt::PointingHandCursor);
};
// Add "All" button
QPushButton* allBtn= new QPushButton (qt_translate ("All"), categoryBar_);
allBtn->setObjectName ("startup-tab-category-btn");
allBtn->setCheckable (true);
allBtn->setChecked (currentCategory_.isEmpty ());
allBtn->setProperty ("categoryId", QString ());
styleCategoryBtn (allBtn);
connect (allBtn, &QPushButton::clicked, this,
&QTTemplatePage::onCategoryClicked);
categoryLayout->addWidget (allBtn);
if (currentCategory_.isEmpty ()) {
activeCategoryBtn_= allBtn;
}
// Add category buttons
QList<TemplateCategory> categories= templateManager_->categories ();
bool hasMatchedCurrentCategory = currentCategory_.isEmpty ();
for (const auto& cat : categories) {
QPushButton* btn=
new QPushButton (qt_translate (from_qstring (cat.name)), categoryBar_);
btn->setObjectName ("startup-tab-category-btn");
btn->setCheckable (true);
btn->setChecked (cat.id == currentCategory_);
btn->setProperty ("categoryId", cat.id);
styleCategoryBtn (btn);
connect (btn, &QPushButton::clicked, this,
&QTTemplatePage::onCategoryClicked);
categoryLayout->addWidget (btn);
if (cat.id == currentCategory_) {
activeCategoryBtn_ = btn;
hasMatchedCurrentCategory= true;
}
}
if (!hasMatchedCurrentCategory) {
currentCategory_.clear ();
allBtn->setChecked (true);
activeCategoryBtn_= allBtn;
}
categoryLayout->addStretch ();
}
void
QTTemplatePage::onCategoriesLoaded () {
setupCategoryBar ();
}
int
QTTemplatePage::calculateColumnCount () const {
if (!scrollArea_) return 4;
int availableWidth= scrollArea_->viewport ()->width ();
int cardWidth = DpiUtils::scaled (kCardWidth);
int spacing = DpiUtils::scaled (kGridSpacing);
int cardSpace = cardWidth + spacing;
// Viewport not yet properly laid out (default QWidget size is small),
// return a sensible default instead of 1 column
if (availableWidth < cardSpace && availableWidth < cardWidth * 2) return 4;
int columns= (availableWidth + spacing) / cardSpace;
return qBound (1, columns, 9);
}
void
QTTemplatePage::onCategoryClicked () {
QPushButton* btn= qobject_cast<QPushButton*> (sender ());
if (!btn) return;
// Uncheck previous button
if (activeCategoryBtn_ && activeCategoryBtn_ != btn) {
activeCategoryBtn_->setChecked (false);
}
// Check current button
btn->setChecked (true);
activeCategoryBtn_= btn;
// Update current category and refresh
currentCategory_= btn->property ("categoryId").toString ();
refreshTemplateGrid (currentCategory_);
}
void
QTTemplatePage::refreshTemplateGrid (const QString& category) {
// Clear existing content
QLayoutItem* item;
while ((item= gridLayout_->takeAt (0)) != nullptr) {
if (item->widget ()) {
delete item->widget ();
}
delete item;
}
// Calculate columns first so placeholder labels span the right width
currentColumnCount_= calculateColumnCount ();
if (!templateManager_ || !templateManager_->isInitialized ()) {
QLabel* label= new QLabel (qt_translate ("Initializing..."), gridWidget_);
label->setAlignment (Qt::AlignCenter);
gridLayout_->addWidget (label, 0, 0, 1, currentColumnCount_);
gridNeedsRefresh_= false;
return;
}
// Get templates by category or all templates
QList<TemplateMetadataPtr> templates;
if (category.isEmpty ()) {
templates= templateManager_->templates ();
}
else {
templates= templateManager_->templatesByCategory (category);
}
if (templates.isEmpty ()) {
QLabel* label=
new QLabel (qt_translate ("No templates available."), gridWidget_);
label->setAlignment (Qt::AlignCenter);
gridLayout_->addWidget (label, 0, 0, 1, currentColumnCount_);
gridNeedsRefresh_= false;
return;
}
// Add template cards
int row= 0, col= 0;
for (const auto& tmpl : templates) {
QWidget* card= createTemplateCard (tmpl);
gridLayout_->addWidget (card, row, col);
col++;
if (col >= currentColumnCount_) {
col= 0;
row++;
}
}
gridLayout_->setRowStretch (row + 1, 1);
gridNeedsRefresh_= false;
}
QWidget*
QTTemplatePage::createTemplateCard (const TemplateMetadataPtr& tmpl) {
// 外层容器
QWidget* item = new QWidget (gridWidget_);
QVBoxLayout* itemLayout= new QVBoxLayout (item);
itemLayout->setContentsMargins (0, 0, 0, 0);
itemLayout->setSpacing (DpiUtils::scaled (kCardSpacing));
item->setObjectName ("startup-tab-template-item");
item->setToolTip (tmpl->description);
// 缩略图卡片
QFrame* card = new QFrame (item);
QVBoxLayout* layout= new QVBoxLayout (card);
layout->setContentsMargins (
DpiUtils::scaled (kCardMargin), DpiUtils::scaled (kCardMargin),
DpiUtils::scaled (kCardMargin), DpiUtils::scaled (kCardMargin));
layout->setSpacing (0);
card->setObjectName ("startup-tab-template-card");
card->setFixedSize (DpiUtils::scaled (kCardWidth),
DpiUtils::scaled (kCardHeight));
card->setProperty ("templateId", tmpl->id);
card->setCursor (Qt::PointingHandCursor);
card->setFrameShape (QFrame::StyledPanel);
card->setStyleSheet (QString ("QFrame#startup-tab-template-card {"
" border-radius: %1px;"
"}")
.arg (DpiUtils::scaled (kCardRadiusPx)));
// Thumbnail image
QLabel* thumbnailLabel= new QLabel (card);
thumbnailLabel->setObjectName ("startup-tab-template-thumbnail");
thumbnailLabel->setFixedSize (DpiUtils::scaled (THUMBNAIL_WIDTH),
DpiUtils::scaled (THUMBNAIL_HEIGHT));
thumbnailLabel->setAlignment (Qt::AlignCenter);
thumbnailLabel->setText (qt_translate ("Loading..."));
layout->addWidget (thumbnailLabel, 0, Qt::AlignHCenter);
// Load thumbnail from URL
if (!tmpl->thumbnailUrl.isEmpty ()) {
QSize targetSize (DpiUtils::scaled (THUMBNAIL_WIDTH),
DpiUtils::scaled (THUMBNAIL_HEIGHT));
ThumbnailLoader::instance ()->load (thumbnailLabel, tmpl->thumbnailUrl,
targetSize);
}
else {
thumbnailLabel->setText (qt_translate ("No Preview"));
}
itemLayout->addWidget (card, 0, Qt::AlignHCenter);
// Template name
QLabel* nameLabel= new QLabel (tmpl->name, item);
nameLabel->setObjectName ("startup-tab-template-name");
nameLabel->setAlignment (Qt::AlignCenter);
nameLabel->setWordWrap (true);
nameLabel->setFixedWidth (DpiUtils::scaled (kNameLabelMaxWidth));
DpiUtils::applyScaledFont (nameLabel, kTemplateNameFontPx);
// 手动计算换行后的实际高度,避免 QLabel sizeHint 不准确导致截断
{
QFontMetrics fm (nameLabel->font ());
QRect textRect= fm.boundingRect (
QRect (0, 0, DpiUtils::scaled (kNameLabelMaxWidth), INT_MAX),
Qt::AlignCenter | Qt::TextWordWrap, tmpl->name);
int neededHeight= textRect.height () + 4;
nameLabel->setFixedHeight (
qMin (neededHeight, DpiUtils::scaled (kNameLabelMaxHeight)));
}
nameLabel->setSizePolicy (QSizePolicy::Fixed, QSizePolicy::Fixed);
itemLayout->addWidget (nameLabel, 0, Qt::AlignHCenter);
// Author and version
QLabel* infoLabel=
new QLabel (QString ("%1 · v%2").arg (tmpl->author, tmpl->version), item);
infoLabel->setObjectName ("startup-tab-template-info");
infoLabel->setAlignment (Qt::AlignCenter);
DpiUtils::applyScaledFont (infoLabel, kInfoFontPx);
itemLayout->addWidget (infoLabel);
itemLayout->addStretch ();
// Install event filter on card only
card->installEventFilter (this);
return item;
}
bool
QTTemplatePage::eventFilter (QObject* watched, QEvent* event) {
if (event->type () == QEvent::MouseButtonRelease) {
QWidget* card= qobject_cast<QWidget*> (watched);
if (card && card->objectName () == "startup-tab-template-card") {
QString templateId= card->property ("templateId").toString ();
if (!templateId.isEmpty ()) {
showTemplatePreview (templateId);
return true;
}
}
}
return QWidget::eventFilter (watched, event);
}
void
QTTemplatePage::showTemplatePreview (const QString& templateId) {
if (!templateManager_) return;
TemplateMetadataPtr tmpl= templateManager_->templateById (templateId);
if (!tmpl) return;
// Create preview dialog
QDialog* dialog= new QDialog (this);
dialog->setWindowTitle (
qt_translate ("Template Preview - %1").arg (tmpl->name));
// 根据屏幕可用区域限制对话框尺寸,防止高分屏下溢出
QScreen* screen= this->screen ();
if (!screen) screen= QGuiApplication::primaryScreen ();
QRect availGeo= screen ? screen->availableGeometry () : QRect ();
int maxDlgH = availGeo.height () > 0 ? qRound (availGeo.height () * 0.9)
: DpiUtils::scaled (kPreviewDialogMinH);
// 预览区尺寸由对话框高度上限决定(1:1 正方形)
int basePreviewSize= DpiUtils::scaled (PREVIEW_IMAGE_WIDTH);
int maxPreviewSize = qRound (maxDlgH * 0.7);
int previewSize = qMin (basePreviewSize, maxPreviewSize);
// 对话框最大宽度收紧:仅比预览框宽一点(边距 + 少量余量)
int marginW = DpiUtils::scaled (kPreviewLayoutMargin) * 2;
int spacingW= DpiUtils::scaled (kPreviewLayoutSpacing);
int maxDlgW = previewSize + marginW + spacingW;
if (availGeo.width () > 0) {
maxDlgW= qMin (maxDlgW, qRound (availGeo.width () * 0.9));
}
int minW= qMin (DpiUtils::scaled (kPreviewDialogMinW), maxDlgW);
int minH= qMin (DpiUtils::scaled (kPreviewDialogMinH), maxDlgH);
dialog->setMinimumSize (minW, minH);
dialog->setMaximumSize (maxDlgW, maxDlgH);
dialog->resize (minW, minH);
QVBoxLayout* layout= new QVBoxLayout (dialog);
layout->setSpacing (DpiUtils::scaled (kPreviewLayoutSpacing));
layout->setContentsMargins (DpiUtils::scaled (kPreviewLayoutMargin),
DpiUtils::scaled (kPreviewLayoutMargin),
DpiUtils::scaled (kPreviewLayoutMargin),
DpiUtils::scaled (kPreviewLayoutMargin));
// Title
QLabel* titleLabel= new QLabel (tmpl->name, dialog);
titleLabel->setObjectName ("template-preview-title");
QFont titleFont=
DpiUtils::scaledFont (titleLabel->font (), kPreviewTitleFontPx);
titleFont.setBold (true);
titleLabel->setFont (titleFont);
layout->addWidget (titleLabel);
// Description
QLabel* descLabel= new QLabel (tmpl->description, dialog);
descLabel->setObjectName ("template-preview-desc");
descLabel->setWordWrap (true);
DpiUtils::applyScaledFont (descLabel, kPreviewDescFontPx);
layout->addWidget (descLabel);
// Info row
QHBoxLayout* infoLayout= new QHBoxLayout ();
infoLayout->addWidget (
new QLabel (qt_translate ("Author: %1").arg (tmpl->author)));
infoLayout->addWidget (
new QLabel (qt_translate ("Version: %1").arg (tmpl->version)));
infoLayout->addStretch ();
layout->addLayout (infoLayout);
// Preview area using reusable PDF preview widget
QTPdfPreviewWidget* previewWidget= new QTPdfPreviewWidget (dialog);
previewWidget->setFixedSize (previewSize, previewSize);
// Load PDF preview
if (!tmpl->previewUrl.isEmpty ()) {
previewWidget->loadFromUrl (tmpl->previewUrl);
}
else {
previewWidget->clearPreview (qt_translate ("No Preview"));
}
layout->addWidget (previewWidget, 0, Qt::AlignCenter);
// Buttons
QHBoxLayout* btnLayout= new QHBoxLayout ();
btnLayout->addStretch ();
QPushButton* cancelBtn= new QPushButton (qt_translate ("Cancel"), dialog);
cancelBtn->setObjectName ("template-cancel-btn");
DpiUtils::applyScaledFont (cancelBtn, kUseButtonFontPx);
cancelBtn->setCursor (Qt::PointingHandCursor);
cancelBtn->setStyleSheet (QString ("QPushButton#template-cancel-btn {"
" padding: %1px %2px;"
" border-radius: %3px;"
"}")
.arg (DpiUtils::scaled (kUseButtonPadYPx))
.arg (DpiUtils::scaled (kUseButtonPadXPx))
.arg (DpiUtils::scaled (kUseButtonRadiusPx)));
connect (cancelBtn, &QPushButton::clicked, dialog, &QDialog::reject);
btnLayout->addWidget (cancelBtn);
QPushButton* useBtn= new QPushButton (qt_translate ("Use Template"), dialog);
useBtn->setObjectName ("template-use-btn");
DpiUtils::applyScaledFont (useBtn, kUseButtonFontPx);
useBtn->setCursor (Qt::PointingHandCursor);
useBtn->setStyleSheet (QString ("QPushButton#template-use-btn {"
" padding: %1px %2px;"
" border-radius: %3px;"
"}")
.arg (DpiUtils::scaled (kUseButtonPadYPx))
.arg (DpiUtils::scaled (kUseButtonPadXPx))
.arg (DpiUtils::scaled (kUseButtonRadiusPx)));
useBtn->setDefault (true);
connect (useBtn, &QPushButton::clicked, [this, dialog, templateId] () {
dialog->accept ();
downloadAndUseTemplate (templateId);
});
btnLayout->addWidget (useBtn);
layout->addLayout (btnLayout);
dialog->exec ();
}
void
QTTemplatePage::downloadAndUseTemplate (const QString& templateId) {
if (!templateManager_) return;
auto cleanupProgressDialog= [this] () {
QPointer<QProgressDialog> dialog= progressDialog_;
progressDialog_ = nullptr;
if (!dialog) return;
dialog->disconnect (this);
dialog->hide ();
dialog->deleteLater ();
};
if (templateManager_->isTemplateAvailableLocally (templateId)) {
QString localPath= templateManager_->localTemplatePath (templateId);
if (localPath.isEmpty ()) {
QMessageBox::warning (this, qt_translate ("Template Error"),
qt_translate ("Local template file is missing"));
return;
}
emit templateOpened (localPath);
}
else {
// Track this download to distinguish user cancellation from real errors
downloadCancelledByUser_= false;
// Close existing progress dialog if any
if (progressDialog_) {
cleanupProgressDialog ();
}
progressDialog_=
new QProgressDialog (qt_translate ("Downloading template..."),
qt_translate ("Cancel"), 0, 100, this);
progressDialog_->setWindowModality (Qt::WindowModal);
progressDialog_->setAutoClose (true);
// Connect cancel button to actually cancel the download
connect (progressDialog_, &QProgressDialog::canceled,
[this, templateId] () {
// Mark as user-cancelled so onDownloadFailed won't show error
// dialog
downloadCancelledByUser_ = true;
QPointer<QProgressDialog> dialog= progressDialog_;
progressDialog_ = nullptr;
templateManager_->cancelDownload (templateId);
if (dialog) {
dialog->disconnect (this);
dialog->hide ();
dialog->deleteLater ();
}
});
progressDialog_->show ();
templateManager_->downloadTemplate (templateId);
}
}
void
QTTemplatePage::onTemplatesLoaded () {
// Initialize category bar if not already done
if (categoryBar_ && categoryBar_->layout () &&
categoryBar_->layout ()->count () == 0) {
setupCategoryBar ();
}
gridNeedsRefresh_= true;
refreshTemplateGrid (currentCategory_);
}
void
QTTemplatePage::onDownloadProgress (const QString& templateId,
qint64 bytesReceived, qint64 bytesTotal) {
if (progressDialog_) {
// Handle case where Content-Length is not available (bytesTotal == -1)
if (bytesTotal < 0) {
// Switch to indeterminate mode when total size is unknown
progressDialog_->setRange (0, 0);
}
else {
progressDialog_->setMaximum (static_cast<int> (bytesTotal));
progressDialog_->setValue (static_cast<int> (bytesReceived));
}
}
}
void
QTTemplatePage::onDownloadCompleted (const QString& templateId,
const QString& localPath) {
if (progressDialog_) {
QPointer<QProgressDialog> dialog= progressDialog_;
progressDialog_ = nullptr;
dialog->disconnect (this);
dialog->hide ();
dialog->deleteLater ();
}
emit templateOpened (localPath);
}
void
QTTemplatePage::onDownloadFailed (const QString& templateId,
const QString& error) {
if (progressDialog_) {
QPointer<QProgressDialog> dialog= progressDialog_;
progressDialog_ = nullptr;
dialog->disconnect (this);
dialog->hide ();
dialog->deleteLater ();
}
// Check if this download was cancelled by the user
// If so, don't show the error dialog
if (!downloadCancelledByUser_) {
QMessageBox::warning (
this, qt_translate ("Download Failed"),
qt_translate ("Failed to download template: %1").arg (error));
}
// Reset the flag for next download
downloadCancelledByUser_= false;
}
void
QTTemplatePage::showEvent (QShowEvent* event) {
QWidget::showEvent (event);
// Refresh grid when page becomes visible. If onTemplatesLoaded already
// refreshed while the widget had no proper size, recalculate now that
// the viewport has its final width to avoid showing the wrong column count.
if (templateManager_ && templateManager_->isInitialized () &&
!templateManager_->templates ().isEmpty ()) {
int newColumnCount= calculateColumnCount ();
if (gridNeedsRefresh_ || newColumnCount != currentColumnCount_) {
refreshTemplateGrid (currentCategory_);
}
}
}
void
QTTemplatePage::resizeEvent (QResizeEvent* event) {
QWidget::resizeEvent (event);
// Debounce resize to avoid frequent grid rebuilds during window dragging
if (resizeDebounceTimer_) {
resizeDebounceTimer_->start ();
}
}